FFMpegManager.cs 11 KB

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