EncodingManager.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Controller.Chapters;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.MediaEncoding;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.IO;
  18. using Microsoft.Extensions.Logging;
  19. namespace Emby.Server.Implementations.MediaEncoder
  20. {
  21. public class EncodingManager : IEncodingManager
  22. {
  23. private readonly IFileSystem _fileSystem;
  24. private readonly ILogger<EncodingManager> _logger;
  25. private readonly IMediaEncoder _encoder;
  26. private readonly IChapterManager _chapterManager;
  27. private readonly ILibraryManager _libraryManager;
  28. /// <summary>
  29. /// The first chapter ticks.
  30. /// </summary>
  31. private static readonly long _firstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  32. public EncodingManager(
  33. ILogger<EncodingManager> logger,
  34. IFileSystem fileSystem,
  35. IMediaEncoder encoder,
  36. IChapterManager chapterManager,
  37. ILibraryManager libraryManager)
  38. {
  39. _logger = logger;
  40. _fileSystem = fileSystem;
  41. _encoder = encoder;
  42. _chapterManager = chapterManager;
  43. _libraryManager = libraryManager;
  44. }
  45. /// <summary>
  46. /// Gets the chapter images data path.
  47. /// </summary>
  48. /// <value>The chapter images data path.</value>
  49. private static string GetChapterImagesPath(BaseItem item)
  50. {
  51. return Path.Combine(item.GetInternalMetadataPath(), "chapters");
  52. }
  53. /// <summary>
  54. /// Determines whether [is eligible for chapter image extraction] [the specified video].
  55. /// </summary>
  56. /// <param name="video">The video.</param>
  57. /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
  58. private bool IsEligibleForChapterImageExtraction(Video video)
  59. {
  60. if (video.IsPlaceHolder)
  61. {
  62. return false;
  63. }
  64. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  65. if (libraryOptions != null)
  66. {
  67. if (!libraryOptions.EnableChapterImageExtraction)
  68. {
  69. return false;
  70. }
  71. }
  72. else
  73. {
  74. return false;
  75. }
  76. if (video.IsShortcut)
  77. {
  78. return false;
  79. }
  80. if (!video.IsCompleteMedia)
  81. {
  82. return false;
  83. }
  84. // Can't extract images if there are no video streams
  85. return video.DefaultVideoStreamIndex.HasValue;
  86. }
  87. public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
  88. {
  89. if (!IsEligibleForChapterImageExtraction(video))
  90. {
  91. extractImages = false;
  92. }
  93. var success = true;
  94. var changesMade = false;
  95. var runtimeTicks = video.RunTimeTicks ?? 0;
  96. var currentImages = GetSavedChapterImages(video, directoryService);
  97. foreach (var chapter in chapters)
  98. {
  99. if (chapter.StartPositionTicks >= runtimeTicks)
  100. {
  101. _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  102. break;
  103. }
  104. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  105. if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase))
  106. {
  107. if (extractImages)
  108. {
  109. cancellationToken.ThrowIfCancellationRequested();
  110. try
  111. {
  112. // Add some time for the first chapter to make sure we don't end up with a black image
  113. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  114. var inputPath = video.Path;
  115. Directory.CreateDirectory(Path.GetDirectoryName(path));
  116. var container = video.Container;
  117. var mediaSource = new MediaSourceInfo
  118. {
  119. VideoType = video.VideoType,
  120. IsoType = video.IsoType,
  121. Protocol = video.PathProtocol.Value,
  122. };
  123. var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  124. File.Copy(tempFile, path, true);
  125. try
  126. {
  127. _fileSystem.DeleteFile(tempFile);
  128. }
  129. catch (IOException ex)
  130. {
  131. _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile);
  132. }
  133. chapter.ImagePath = path;
  134. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  135. changesMade = true;
  136. }
  137. catch (Exception ex)
  138. {
  139. _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path));
  140. success = false;
  141. break;
  142. }
  143. }
  144. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  145. {
  146. chapter.ImagePath = null;
  147. changesMade = true;
  148. }
  149. }
  150. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  151. {
  152. chapter.ImagePath = path;
  153. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  154. changesMade = true;
  155. }
  156. }
  157. if (saveChapters && changesMade)
  158. {
  159. _chapterManager.SaveChapters(video.Id, chapters);
  160. }
  161. DeleteDeadImages(currentImages, chapters);
  162. return success;
  163. }
  164. private string GetChapterImagePath(Video video, long chapterPositionTicks)
  165. {
  166. var filename = video.DateModified.Ticks.ToString(CultureInfo.InvariantCulture) + "_" + chapterPositionTicks.ToString(CultureInfo.InvariantCulture) + ".jpg";
  167. return Path.Combine(GetChapterImagesPath(video), filename);
  168. }
  169. private static IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
  170. {
  171. var path = GetChapterImagesPath(video);
  172. if (!Directory.Exists(path))
  173. {
  174. return Array.Empty<string>();
  175. }
  176. try
  177. {
  178. return directoryService.GetFilePaths(path);
  179. }
  180. catch (IOException)
  181. {
  182. return Array.Empty<string>();
  183. }
  184. }
  185. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  186. {
  187. var deadImages = images
  188. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  189. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase))
  190. .ToList();
  191. foreach (var image in deadImages)
  192. {
  193. _logger.LogDebug("Deleting dead chapter image {Path}", image);
  194. try
  195. {
  196. _fileSystem.DeleteFile(image);
  197. }
  198. catch (IOException ex)
  199. {
  200. _logger.LogError(ex, "Error deleting {Path}.", image);
  201. }
  202. }
  203. }
  204. }
  205. }