FFMpegManager.cs 9.3 KB

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