FFMpegManager.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Providers.MediaInfo;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  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 ILibraryManager _libraryManager;
  31. private readonly IServerApplicationPaths _appPaths;
  32. private readonly IMediaEncoder _encoder;
  33. private readonly ILogger _logger;
  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="libraryManager">The library manager.</param>
  40. /// <param name="logger">The logger.</param>
  41. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  42. public FFMpegManager(IServerApplicationPaths appPaths, IMediaEncoder encoder, ILibraryManager libraryManager, ILogger logger)
  43. {
  44. _appPaths = appPaths;
  45. _encoder = encoder;
  46. _libraryManager = libraryManager;
  47. _logger = logger;
  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="cancellationToken">The cancellation token.</param>
  93. /// <param name="extractImages">if set to <c>true</c> [extract images].</param>
  94. /// <param name="saveItem">if set to <c>true</c> [save item].</param>
  95. /// <returns>Task.</returns>
  96. /// <exception cref="System.ArgumentNullException"></exception>
  97. public async Task<bool> PopulateChapterImages(Video video, CancellationToken cancellationToken, bool extractImages, bool saveItem)
  98. {
  99. if (video.Chapters == null)
  100. {
  101. throw new ArgumentNullException();
  102. }
  103. // Can't extract images if there are no video streams
  104. if (video.MediaStreams == null || video.MediaStreams.All(m => m.Type != MediaStreamType.Video))
  105. {
  106. return true;
  107. }
  108. var success = true;
  109. var changesMade = false;
  110. var runtimeTicks = video.RunTimeTicks ?? 0;
  111. foreach (var chapter in video.Chapters)
  112. {
  113. if (chapter.StartPositionTicks >= runtimeTicks)
  114. {
  115. _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  116. break;
  117. }
  118. var filename = video.Id + "_" + video.DateModified.Ticks + "_" + chapter.StartPositionTicks;
  119. var path = VideoImageCache.GetResourcePath(filename, ".jpg");
  120. if (!File.Exists(path))
  121. {
  122. if (extractImages)
  123. {
  124. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  125. {
  126. continue;
  127. }
  128. if (video.VideoType == VideoType.BluRay)
  129. {
  130. // Can only extract reliably on single file blurays
  131. if (video.PlayableStreamFileNames == null || video.PlayableStreamFileNames.Count != 1)
  132. {
  133. continue;
  134. }
  135. }
  136. // Add some time for the first chapter to make sure we don't end up with a black image
  137. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  138. InputType type;
  139. var inputPath = MediaEncoderHelpers.GetInputArgument(video, null, out type);
  140. try
  141. {
  142. var parentPath = Path.GetDirectoryName(path);
  143. if (!Directory.Exists(parentPath))
  144. {
  145. Directory.CreateDirectory(parentPath);
  146. }
  147. await _encoder.ExtractImage(inputPath, type, time, path, cancellationToken).ConfigureAwait(false);
  148. chapter.ImagePath = path;
  149. changesMade = true;
  150. }
  151. catch
  152. {
  153. success = false;
  154. break;
  155. }
  156. }
  157. }
  158. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  159. {
  160. chapter.ImagePath = path;
  161. changesMade = true;
  162. }
  163. }
  164. if (saveItem && changesMade)
  165. {
  166. await _libraryManager.UpdateItem(video, CancellationToken.None).ConfigureAwait(false);
  167. }
  168. return success;
  169. }
  170. /// <summary>
  171. /// Gets the subtitle cache path.
  172. /// </summary>
  173. /// <param name="input">The input.</param>
  174. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  175. /// <param name="offset">The offset.</param>
  176. /// <param name="outputExtension">The output extension.</param>
  177. /// <returns>System.String.</returns>
  178. public string GetSubtitleCachePath(Video input, int subtitleStreamIndex, TimeSpan? offset, string outputExtension)
  179. {
  180. var ticksParam = offset.HasValue ? "_" + offset.Value.Ticks : "";
  181. var stream = input.MediaStreams[subtitleStreamIndex];
  182. if (stream.IsExternal)
  183. {
  184. ticksParam += File.GetLastWriteTimeUtc(stream.Path).Ticks;
  185. }
  186. return SubtitleCache.GetResourcePath(input.Id + "_" + subtitleStreamIndex + "_" + input.DateModified.Ticks + ticksParam, outputExtension);
  187. }
  188. }
  189. }