FFMpegManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 System;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using MediaBrowser.Model.Logging;
  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. /// Holds the list of new items to generate chapter image for when the NewItemTimer expires
  37. /// </summary>
  38. private readonly List<Video> _newlyAddedItems = new List<Video>();
  39. /// <summary>
  40. /// The amount of time to wait before generating chapter images
  41. /// </summary>
  42. private const int NewItemDelay = 300000;
  43. /// <summary>
  44. /// The current new item timer
  45. /// </summary>
  46. /// <value>The new item timer.</value>
  47. private Timer NewItemTimer { get; set; }
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="FFMpegManager" /> class.
  50. /// </summary>
  51. /// <param name="appPaths">The app paths.</param>
  52. /// <param name="encoder">The encoder.</param>
  53. /// <param name="libraryManager">The library manager.</param>
  54. /// <param name="logger">The logger.</param>
  55. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  56. public FFMpegManager(IServerApplicationPaths appPaths, IMediaEncoder encoder, ILibraryManager libraryManager, ILogger logger)
  57. {
  58. _appPaths = appPaths;
  59. _encoder = encoder;
  60. _libraryManager = libraryManager;
  61. _logger = logger;
  62. VideoImageCache = new FileSystemRepository(VideoImagesDataPath);
  63. SubtitleCache = new FileSystemRepository(SubtitleCachePath);
  64. libraryManager.LibraryChanged += libraryManager_LibraryChanged;
  65. }
  66. /// <summary>
  67. /// Handles the LibraryChanged event of the libraryManager control.
  68. /// </summary>
  69. /// <param name="sender">The source of the event.</param>
  70. /// <param name="e">The <see cref="ChildrenChangedEventArgs"/> instance containing the event data.</param>
  71. void libraryManager_LibraryChanged(object sender, ChildrenChangedEventArgs e)
  72. {
  73. var videos = e.ItemsAdded.OfType<Video>().ToList();
  74. videos.AddRange(e.ItemsUpdated.OfType<Video>());
  75. // Use a timer to prevent lots of these notifications from showing in a short period of time
  76. if (videos.Count > 0)
  77. {
  78. lock (_newlyAddedItems)
  79. {
  80. _newlyAddedItems.AddRange(videos);
  81. if (NewItemTimer == null)
  82. {
  83. NewItemTimer = new Timer(NewItemTimerCallback, null, NewItemDelay, Timeout.Infinite);
  84. }
  85. else
  86. {
  87. NewItemTimer.Change(NewItemDelay, Timeout.Infinite);
  88. }
  89. }
  90. }
  91. }
  92. /// <summary>
  93. /// The _video images data path
  94. /// </summary>
  95. private string _videoImagesDataPath;
  96. /// <summary>
  97. /// Gets the video images data path.
  98. /// </summary>
  99. /// <value>The video images data path.</value>
  100. public string VideoImagesDataPath
  101. {
  102. get
  103. {
  104. if (_videoImagesDataPath == null)
  105. {
  106. _videoImagesDataPath = Path.Combine(_appPaths.DataPath, "extracted-video-images");
  107. if (!Directory.Exists(_videoImagesDataPath))
  108. {
  109. Directory.CreateDirectory(_videoImagesDataPath);
  110. }
  111. }
  112. return _videoImagesDataPath;
  113. }
  114. }
  115. /// <summary>
  116. /// The _audio images data path
  117. /// </summary>
  118. private string _audioImagesDataPath;
  119. /// <summary>
  120. /// Gets the audio images data path.
  121. /// </summary>
  122. /// <value>The audio images data path.</value>
  123. public string AudioImagesDataPath
  124. {
  125. get
  126. {
  127. if (_audioImagesDataPath == null)
  128. {
  129. _audioImagesDataPath = Path.Combine(_appPaths.DataPath, "extracted-audio-images");
  130. if (!Directory.Exists(_audioImagesDataPath))
  131. {
  132. Directory.CreateDirectory(_audioImagesDataPath);
  133. }
  134. }
  135. return _audioImagesDataPath;
  136. }
  137. }
  138. /// <summary>
  139. /// The _subtitle cache path
  140. /// </summary>
  141. private string _subtitleCachePath;
  142. /// <summary>
  143. /// Gets the subtitle cache path.
  144. /// </summary>
  145. /// <value>The subtitle cache path.</value>
  146. public string SubtitleCachePath
  147. {
  148. get
  149. {
  150. if (_subtitleCachePath == null)
  151. {
  152. _subtitleCachePath = Path.Combine(_appPaths.CachePath, "subtitles");
  153. if (!Directory.Exists(_subtitleCachePath))
  154. {
  155. Directory.CreateDirectory(_subtitleCachePath);
  156. }
  157. }
  158. return _subtitleCachePath;
  159. }
  160. }
  161. /// <summary>
  162. /// Called when the new item timer expires
  163. /// </summary>
  164. /// <param name="state">The state.</param>
  165. private async void NewItemTimerCallback(object state)
  166. {
  167. List<Video> newItems;
  168. // Lock the list and release all resources
  169. lock (_newlyAddedItems)
  170. {
  171. newItems = _newlyAddedItems.ToList();
  172. _newlyAddedItems.Clear();
  173. NewItemTimer.Dispose();
  174. NewItemTimer = null;
  175. }
  176. // Limit the number of videos we generate images for
  177. // The idea is to catch new items that are added here and there
  178. // Mass image generation can be left to the scheduled task
  179. foreach (var video in newItems.Where(c => c.Chapters != null).Take(5))
  180. {
  181. try
  182. {
  183. await PopulateChapterImages(video, CancellationToken.None, true, true).ConfigureAwait(false);
  184. }
  185. catch (Exception ex)
  186. {
  187. _logger.ErrorException("Error creating chapter images for {0}", ex, video.Name);
  188. }
  189. }
  190. }
  191. /// <summary>
  192. /// The first chapter ticks
  193. /// </summary>
  194. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  195. /// <summary>
  196. /// Extracts the chapter images.
  197. /// </summary>
  198. /// <param name="video">The video.</param>
  199. /// <param name="cancellationToken">The cancellation token.</param>
  200. /// <param name="extractImages">if set to <c>true</c> [extract images].</param>
  201. /// <param name="saveItem">if set to <c>true</c> [save item].</param>
  202. /// <returns>Task.</returns>
  203. /// <exception cref="System.ArgumentNullException"></exception>
  204. public async Task PopulateChapterImages(Video video, CancellationToken cancellationToken, bool extractImages, bool saveItem)
  205. {
  206. if (video.Chapters == null)
  207. {
  208. throw new ArgumentNullException();
  209. }
  210. // Can't extract images if there are no video streams
  211. if (video.MediaStreams == null || video.MediaStreams.All(m => m.Type != MediaStreamType.Video))
  212. {
  213. return;
  214. }
  215. var changesMade = false;
  216. foreach (var chapter in video.Chapters)
  217. {
  218. var filename = video.Id + "_" + video.DateModified.Ticks + "_" + chapter.StartPositionTicks;
  219. var path = VideoImageCache.GetResourcePath(filename, ".jpg");
  220. if (!VideoImageCache.ContainsFilePath(path))
  221. {
  222. if (extractImages)
  223. {
  224. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  225. {
  226. continue;
  227. }
  228. if (video.VideoType == VideoType.BluRay)
  229. {
  230. // Can only extract reliably on single file blurays
  231. if (video.PlayableStreamFileNames == null || video.PlayableStreamFileNames.Count != 1)
  232. {
  233. continue;
  234. }
  235. }
  236. // Add some time for the first chapter to make sure we don't end up with a black image
  237. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  238. InputType type;
  239. var inputPath = MediaEncoderHelpers.GetInputArgument(video, null, out type);
  240. try
  241. {
  242. await _encoder.ExtractImage(inputPath, type, time, path, cancellationToken).ConfigureAwait(false);
  243. chapter.ImagePath = path;
  244. changesMade = true;
  245. }
  246. catch
  247. {
  248. break;
  249. }
  250. }
  251. }
  252. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  253. {
  254. chapter.ImagePath = path;
  255. changesMade = true;
  256. }
  257. }
  258. if (saveItem && changesMade)
  259. {
  260. await _libraryManager.SaveItem(video, CancellationToken.None).ConfigureAwait(false);
  261. }
  262. }
  263. /// <summary>
  264. /// Gets the subtitle cache path.
  265. /// </summary>
  266. /// <param name="input">The input.</param>
  267. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  268. /// <param name="offset">The offset.</param>
  269. /// <param name="outputExtension">The output extension.</param>
  270. /// <returns>System.String.</returns>
  271. public string GetSubtitleCachePath(Video input, int subtitleStreamIndex, TimeSpan? offset, string outputExtension)
  272. {
  273. var ticksParam = offset.HasValue ? "_" + offset.Value.Ticks : "";
  274. return SubtitleCache.GetResourcePath(input.Id + "_" + subtitleStreamIndex + "_" + input.DateModified.Ticks + ticksParam, outputExtension);
  275. }
  276. }
  277. }