FFMpegManager.cs 11 KB

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