FFMpegManager.cs 7.9 KB

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