FFMpegManager.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using System.Collections.Generic;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.MediaInfo;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Persistence;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using System;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Controller.MediaInfo
  15. {
  16. /// <summary>
  17. /// Class FFMpegManager
  18. /// </summary>
  19. public class FFMpegManager
  20. {
  21. /// <summary>
  22. /// Gets or sets the video image cache.
  23. /// </summary>
  24. /// <value>The video image cache.</value>
  25. internal FileSystemRepository VideoImageCache { get; set; }
  26. /// <summary>
  27. /// Gets or sets the subtitle cache.
  28. /// </summary>
  29. /// <value>The subtitle cache.</value>
  30. internal FileSystemRepository SubtitleCache { get; set; }
  31. private readonly ILibraryManager _libraryManager;
  32. private readonly IServerApplicationPaths _appPaths;
  33. private readonly IMediaEncoder _encoder;
  34. private readonly ILogger _logger;
  35. private readonly IItemRepository _itemRepo;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="FFMpegManager" /> class.
  38. /// </summary>
  39. /// <param name="appPaths">The app paths.</param>
  40. /// <param name="encoder">The encoder.</param>
  41. /// <param name="libraryManager">The library manager.</param>
  42. /// <param name="logger">The logger.</param>
  43. /// <param name="itemRepo">The item repo.</param>
  44. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  45. public FFMpegManager(IServerApplicationPaths appPaths, IMediaEncoder encoder, ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo)
  46. {
  47. _appPaths = appPaths;
  48. _encoder = encoder;
  49. _libraryManager = libraryManager;
  50. _logger = logger;
  51. _itemRepo = itemRepo;
  52. VideoImageCache = new FileSystemRepository(VideoImagesDataPath);
  53. SubtitleCache = new FileSystemRepository(SubtitleCachePath);
  54. }
  55. /// <summary>
  56. /// Gets the video images data path.
  57. /// </summary>
  58. /// <value>The video images data path.</value>
  59. public string VideoImagesDataPath
  60. {
  61. get
  62. {
  63. return Path.Combine(_appPaths.DataPath, "extracted-video-images");
  64. }
  65. }
  66. /// <summary>
  67. /// Gets the audio images data path.
  68. /// </summary>
  69. /// <value>The audio images data path.</value>
  70. public string AudioImagesDataPath
  71. {
  72. get
  73. {
  74. return Path.Combine(_appPaths.DataPath, "extracted-audio-images");
  75. }
  76. }
  77. /// <summary>
  78. /// Gets the subtitle cache path.
  79. /// </summary>
  80. /// <value>The subtitle cache path.</value>
  81. public string SubtitleCachePath
  82. {
  83. get
  84. {
  85. return Path.Combine(_appPaths.CachePath, "subtitles");
  86. }
  87. }
  88. /// <summary>
  89. /// The first chapter ticks
  90. /// </summary>
  91. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  92. /// <summary>
  93. /// Extracts the chapter images.
  94. /// </summary>
  95. /// <param name="video">The video.</param>
  96. /// <param name="chapters">The chapters.</param>
  97. /// <param name="extractImages">if set to <c>true</c> [extract images].</param>
  98. /// <param name="saveChapters">if set to <c>true</c> [save chapters].</param>
  99. /// <param name="cancellationToken">The cancellation token.</param>
  100. /// <returns>Task.</returns>
  101. /// <exception cref="System.ArgumentNullException"></exception>
  102. public async Task<bool> PopulateChapterImages(Video video, List<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
  103. {
  104. // Can't extract images if there are no video streams
  105. if (video.MediaStreams == null || video.MediaStreams.All(m => m.Type != MediaStreamType.Video))
  106. {
  107. return true;
  108. }
  109. var success = true;
  110. var changesMade = false;
  111. var runtimeTicks = video.RunTimeTicks ?? 0;
  112. foreach (var chapter in chapters)
  113. {
  114. if (chapter.StartPositionTicks >= runtimeTicks)
  115. {
  116. _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  117. break;
  118. }
  119. var filename = video.Id + "_" + video.DateModified.Ticks + "_" + chapter.StartPositionTicks;
  120. var path = VideoImageCache.GetResourcePath(filename, ".jpg");
  121. if (!File.Exists(path))
  122. {
  123. if (extractImages)
  124. {
  125. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  126. {
  127. continue;
  128. }
  129. if (video.VideoType == VideoType.BluRay)
  130. {
  131. // Can only extract reliably on single file blurays
  132. if (video.PlayableStreamFileNames == null || video.PlayableStreamFileNames.Count != 1)
  133. {
  134. continue;
  135. }
  136. }
  137. // Add some time for the first chapter to make sure we don't end up with a black image
  138. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  139. InputType type;
  140. var inputPath = MediaEncoderHelpers.GetInputArgument(video, null, out type);
  141. try
  142. {
  143. var parentPath = Path.GetDirectoryName(path);
  144. if (!Directory.Exists(parentPath))
  145. {
  146. Directory.CreateDirectory(parentPath);
  147. }
  148. await _encoder.ExtractImage(inputPath, type, video.Video3DFormat, time, path, cancellationToken).ConfigureAwait(false);
  149. chapter.ImagePath = path;
  150. changesMade = true;
  151. }
  152. catch
  153. {
  154. success = false;
  155. break;
  156. }
  157. }
  158. }
  159. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  160. {
  161. chapter.ImagePath = path;
  162. changesMade = true;
  163. }
  164. }
  165. if (saveChapters && changesMade)
  166. {
  167. await _itemRepo.SaveChapters(video.Id, chapters, cancellationToken).ConfigureAwait(false);
  168. }
  169. return success;
  170. }
  171. /// <summary>
  172. /// Gets the subtitle cache path.
  173. /// </summary>
  174. /// <param name="input">The input.</param>
  175. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  176. /// <param name="offset">The offset.</param>
  177. /// <param name="outputExtension">The output extension.</param>
  178. /// <returns>System.String.</returns>
  179. public string GetSubtitleCachePath(Video input, int subtitleStreamIndex, TimeSpan? offset, string outputExtension)
  180. {
  181. var ticksParam = offset.HasValue ? "_" + offset.Value.Ticks : "";
  182. var stream = input.MediaStreams[subtitleStreamIndex];
  183. if (stream.IsExternal)
  184. {
  185. ticksParam += File.GetLastWriteTimeUtc(stream.Path).Ticks;
  186. }
  187. return SubtitleCache.GetResourcePath(input.Id + "_" + subtitleStreamIndex + "_" + input.DateModified.Ticks + ticksParam, outputExtension);
  188. }
  189. }
  190. }