FFMpegManager.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. /// The _video images data path
  53. /// </summary>
  54. private string _videoImagesDataPath;
  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. if (_videoImagesDataPath == null)
  64. {
  65. _videoImagesDataPath = Path.Combine(_appPaths.DataPath, "extracted-video-images");
  66. if (!Directory.Exists(_videoImagesDataPath))
  67. {
  68. Directory.CreateDirectory(_videoImagesDataPath);
  69. }
  70. }
  71. return _videoImagesDataPath;
  72. }
  73. }
  74. /// <summary>
  75. /// The _audio images data path
  76. /// </summary>
  77. private string _audioImagesDataPath;
  78. /// <summary>
  79. /// Gets the audio images data path.
  80. /// </summary>
  81. /// <value>The audio images data path.</value>
  82. public string AudioImagesDataPath
  83. {
  84. get
  85. {
  86. if (_audioImagesDataPath == null)
  87. {
  88. _audioImagesDataPath = Path.Combine(_appPaths.DataPath, "extracted-audio-images");
  89. if (!Directory.Exists(_audioImagesDataPath))
  90. {
  91. Directory.CreateDirectory(_audioImagesDataPath);
  92. }
  93. }
  94. return _audioImagesDataPath;
  95. }
  96. }
  97. /// <summary>
  98. /// The _subtitle cache path
  99. /// </summary>
  100. private string _subtitleCachePath;
  101. /// <summary>
  102. /// Gets the subtitle cache path.
  103. /// </summary>
  104. /// <value>The subtitle cache path.</value>
  105. public string SubtitleCachePath
  106. {
  107. get
  108. {
  109. if (_subtitleCachePath == null)
  110. {
  111. _subtitleCachePath = Path.Combine(_appPaths.CachePath, "subtitles");
  112. if (!Directory.Exists(_subtitleCachePath))
  113. {
  114. Directory.CreateDirectory(_subtitleCachePath);
  115. }
  116. }
  117. return _subtitleCachePath;
  118. }
  119. }
  120. /// <summary>
  121. /// The first chapter ticks
  122. /// </summary>
  123. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  124. /// <summary>
  125. /// Extracts the chapter images.
  126. /// </summary>
  127. /// <param name="video">The video.</param>
  128. /// <param name="cancellationToken">The cancellation token.</param>
  129. /// <param name="extractImages">if set to <c>true</c> [extract images].</param>
  130. /// <param name="saveItem">if set to <c>true</c> [save item].</param>
  131. /// <returns>Task.</returns>
  132. /// <exception cref="System.ArgumentNullException"></exception>
  133. public async Task PopulateChapterImages(Video video, CancellationToken cancellationToken, bool extractImages, bool saveItem)
  134. {
  135. if (video.Chapters == null)
  136. {
  137. throw new ArgumentNullException();
  138. }
  139. // Can't extract images if there are no video streams
  140. if (video.MediaStreams == null || video.MediaStreams.All(m => m.Type != MediaStreamType.Video))
  141. {
  142. return;
  143. }
  144. var changesMade = false;
  145. foreach (var chapter in video.Chapters)
  146. {
  147. var filename = video.Id + "_" + video.DateModified.Ticks + "_" + chapter.StartPositionTicks;
  148. var path = VideoImageCache.GetResourcePath(filename, ".jpg");
  149. if (!VideoImageCache.ContainsFilePath(path))
  150. {
  151. if (extractImages)
  152. {
  153. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  154. {
  155. continue;
  156. }
  157. if (video.VideoType == VideoType.BluRay)
  158. {
  159. // Can only extract reliably on single file blurays
  160. if (video.PlayableStreamFileNames == null || video.PlayableStreamFileNames.Count != 1)
  161. {
  162. continue;
  163. }
  164. }
  165. // Add some time for the first chapter to make sure we don't end up with a black image
  166. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  167. InputType type;
  168. var inputPath = MediaEncoderHelpers.GetInputArgument(video, null, out type);
  169. try
  170. {
  171. await _encoder.ExtractImage(inputPath, type, time, path, cancellationToken).ConfigureAwait(false);
  172. chapter.ImagePath = path;
  173. changesMade = true;
  174. }
  175. catch
  176. {
  177. break;
  178. }
  179. }
  180. }
  181. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  182. {
  183. chapter.ImagePath = path;
  184. changesMade = true;
  185. }
  186. }
  187. if (saveItem && changesMade)
  188. {
  189. await _libraryManager.UpdateItem(video, CancellationToken.None).ConfigureAwait(false);
  190. }
  191. }
  192. /// <summary>
  193. /// Gets the subtitle cache path.
  194. /// </summary>
  195. /// <param name="input">The input.</param>
  196. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  197. /// <param name="offset">The offset.</param>
  198. /// <param name="outputExtension">The output extension.</param>
  199. /// <returns>System.String.</returns>
  200. public string GetSubtitleCachePath(Video input, int subtitleStreamIndex, TimeSpan? offset, string outputExtension)
  201. {
  202. var ticksParam = offset.HasValue ? "_" + offset.Value.Ticks : "";
  203. var stream = input.MediaStreams[subtitleStreamIndex];
  204. if (stream.IsExternal)
  205. {
  206. ticksParam += File.GetLastWriteTimeUtc(stream.Path).Ticks;
  207. }
  208. return SubtitleCache.GetResourcePath(input.Id + "_" + subtitleStreamIndex + "_" + input.DateModified.Ticks + ticksParam, outputExtension);
  209. }
  210. }
  211. }