EncodingManager.cs 8.5 KB

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