FFMpegManager.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Movies;
  6. using MediaBrowser.Controller.Entities.TV;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Controller.MediaInfo
  18. {
  19. /// <summary>
  20. /// Class FFMpegManager
  21. /// </summary>
  22. public class FFMpegManager
  23. {
  24. private readonly IServerConfigurationManager _config;
  25. private readonly IMediaEncoder _encoder;
  26. private readonly ILogger _logger;
  27. private readonly IItemRepository _itemRepo;
  28. private readonly IFileSystem _fileSystem;
  29. public static FFMpegManager Instance { get; private set; }
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="FFMpegManager" /> class.
  32. /// </summary>
  33. /// <param name="encoder">The encoder.</param>
  34. /// <param name="logger">The logger.</param>
  35. /// <param name="itemRepo">The item repo.</param>
  36. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  37. public FFMpegManager(IMediaEncoder encoder, ILogger logger, IItemRepository itemRepo, IFileSystem fileSystem, IServerConfigurationManager config)
  38. {
  39. _encoder = encoder;
  40. _logger = logger;
  41. _itemRepo = itemRepo;
  42. _fileSystem = fileSystem;
  43. _config = config;
  44. // TODO: Remove this static instance
  45. Instance = this;
  46. }
  47. /// <summary>
  48. /// Gets the chapter images data path.
  49. /// </summary>
  50. /// <value>The chapter images data path.</value>
  51. public string ChapterImagesPath
  52. {
  53. get
  54. {
  55. return Path.Combine(_config.ApplicationPaths.DataPath, "chapter-images");
  56. }
  57. }
  58. /// <summary>
  59. /// Gets the subtitle cache path.
  60. /// </summary>
  61. /// <value>The subtitle cache path.</value>
  62. private string SubtitleCachePath
  63. {
  64. get
  65. {
  66. return Path.Combine(_config.ApplicationPaths.CachePath, "subtitles");
  67. }
  68. }
  69. /// <summary>
  70. /// Determines whether [is eligible for chapter image extraction] [the specified video].
  71. /// </summary>
  72. /// <param name="video">The video.</param>
  73. /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
  74. private bool IsEligibleForChapterImageExtraction(Video video)
  75. {
  76. if (video is Movie)
  77. {
  78. if (!_config.Configuration.EnableMovieChapterImageExtraction)
  79. {
  80. return false;
  81. }
  82. }
  83. else if (video is Episode)
  84. {
  85. if (!_config.Configuration.EnableEpisodeChapterImageExtraction)
  86. {
  87. return false;
  88. }
  89. }
  90. else
  91. {
  92. if (!_config.Configuration.EnableOtherVideoChapterImageExtraction)
  93. {
  94. return false;
  95. }
  96. }
  97. // Can't extract images if there are no video streams
  98. return video.DefaultVideoStreamIndex.HasValue;
  99. }
  100. /// <summary>
  101. /// The first chapter ticks
  102. /// </summary>
  103. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  104. /// <summary>
  105. /// Extracts the chapter images.
  106. /// </summary>
  107. /// <param name="video">The video.</param>
  108. /// <param name="chapters">The chapters.</param>
  109. /// <param name="extractImages">if set to <c>true</c> [extract images].</param>
  110. /// <param name="saveChapters">if set to <c>true</c> [save chapters].</param>
  111. /// <param name="cancellationToken">The cancellation token.</param>
  112. /// <returns>Task.</returns>
  113. /// <exception cref="System.ArgumentNullException"></exception>
  114. public async Task<bool> PopulateChapterImages(Video video, List<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
  115. {
  116. if (!IsEligibleForChapterImageExtraction(video))
  117. {
  118. return true;
  119. }
  120. var success = true;
  121. var changesMade = false;
  122. var runtimeTicks = video.RunTimeTicks ?? 0;
  123. var currentImages = GetSavedChapterImages(video);
  124. foreach (var chapter in chapters)
  125. {
  126. if (chapter.StartPositionTicks >= runtimeTicks)
  127. {
  128. _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  129. break;
  130. }
  131. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  132. if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase))
  133. {
  134. if (extractImages)
  135. {
  136. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  137. {
  138. continue;
  139. }
  140. if (video.VideoType == VideoType.BluRay)
  141. {
  142. // Can only extract reliably on single file blurays
  143. if (video.PlayableStreamFileNames == null || video.PlayableStreamFileNames.Count != 1)
  144. {
  145. continue;
  146. }
  147. }
  148. // Add some time for the first chapter to make sure we don't end up with a black image
  149. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  150. InputType type;
  151. var inputPath = MediaEncoderHelpers.GetInputArgument(video.Path, false, video.VideoType, video.IsoType, null, video.PlayableStreamFileNames, out type);
  152. try
  153. {
  154. var parentPath = Path.GetDirectoryName(path);
  155. Directory.CreateDirectory(parentPath);
  156. await _encoder.ExtractImage(inputPath, type, false, video.Video3DFormat, time, path, cancellationToken).ConfigureAwait(false);
  157. chapter.ImagePath = path;
  158. changesMade = true;
  159. }
  160. catch
  161. {
  162. success = false;
  163. break;
  164. }
  165. }
  166. }
  167. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  168. {
  169. chapter.ImagePath = path;
  170. changesMade = true;
  171. }
  172. }
  173. if (saveChapters && changesMade)
  174. {
  175. await _itemRepo.SaveChapters(video.Id, chapters, cancellationToken).ConfigureAwait(false);
  176. }
  177. DeleteDeadImages(currentImages, chapters);
  178. return success;
  179. }
  180. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  181. {
  182. var deadImages = images
  183. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  184. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase))
  185. .ToList();
  186. foreach (var image in deadImages)
  187. {
  188. _logger.Debug("Deleting dead chapter image {0}", image);
  189. try
  190. {
  191. File.Delete(image);
  192. }
  193. catch (IOException ex)
  194. {
  195. _logger.ErrorException("Error deleting {0}.", ex, image);
  196. }
  197. }
  198. }
  199. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  200. /// <summary>
  201. /// Gets the subtitle cache path.
  202. /// </summary>
  203. /// <param name="mediaPath">The media path.</param>
  204. /// <param name="subtitleStream">The subtitle stream.</param>
  205. /// <param name="outputExtension">The output extension.</param>
  206. /// <returns>System.String.</returns>
  207. public string GetSubtitleCachePath(string mediaPath, MediaStream subtitleStream, string outputExtension)
  208. {
  209. var ticksParam = string.Empty;
  210. if (subtitleStream.IsExternal)
  211. {
  212. ticksParam += _fileSystem.GetLastWriteTimeUtc(subtitleStream.Path).Ticks;
  213. }
  214. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  215. var filename = (mediaPath + "_" + subtitleStream.Index.ToString(_usCulture) + "_" + date.Ticks.ToString(_usCulture) + ticksParam).GetMD5() + outputExtension;
  216. var prefix = filename.Substring(0, 1);
  217. return Path.Combine(SubtitleCachePath, prefix, filename);
  218. }
  219. public string GetChapterImagePath(Video video, long chapterPositionTicks)
  220. {
  221. var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg";
  222. var videoId = video.Id.ToString();
  223. var prefix = videoId.Substring(0, 1);
  224. return Path.Combine(ChapterImagesPath, prefix, videoId, filename);
  225. }
  226. public List<string> GetSavedChapterImages(Video video)
  227. {
  228. var videoId = video.Id.ToString();
  229. var prefix = videoId.Substring(0, 1);
  230. var path = Path.Combine(ChapterImagesPath, prefix, videoId);
  231. try
  232. {
  233. return Directory.EnumerateFiles(path)
  234. .ToList();
  235. }
  236. catch (DirectoryNotFoundException)
  237. {
  238. return new List<string>();
  239. }
  240. }
  241. }
  242. }