EncodingManager.cs 8.6 KB

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