FFMpegManager.cs 8.0 KB

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