FFMpegManager.cs 8.9 KB

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