FFMpegManager.cs 9.5 KB

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