FFMpegManager.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.IO;
  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.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Controller.MediaInfo
  15. {
  16. /// <summary>
  17. /// Class FFMpegManager
  18. /// </summary>
  19. public class FFMpegManager
  20. {
  21. /// <summary>
  22. /// Gets or sets the video image cache.
  23. /// </summary>
  24. /// <value>The video image cache.</value>
  25. internal FileSystemRepository VideoImageCache { get; set; }
  26. /// <summary>
  27. /// Gets or sets the subtitle cache.
  28. /// </summary>
  29. /// <value>The subtitle cache.</value>
  30. internal FileSystemRepository SubtitleCache { get; set; }
  31. private readonly IServerApplicationPaths _appPaths;
  32. private readonly IMediaEncoder _encoder;
  33. private readonly ILogger _logger;
  34. private readonly IItemRepository _itemRepo;
  35. private readonly IFileSystem _fileSystem;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="FFMpegManager" /> class.
  38. /// </summary>
  39. /// <param name="appPaths">The app paths.</param>
  40. /// <param name="encoder">The encoder.</param>
  41. /// <param name="logger">The logger.</param>
  42. /// <param name="itemRepo">The item repo.</param>
  43. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  44. public FFMpegManager(IServerApplicationPaths appPaths, IMediaEncoder encoder, ILogger logger, IItemRepository itemRepo, IFileSystem fileSystem)
  45. {
  46. _appPaths = appPaths;
  47. _encoder = encoder;
  48. _logger = logger;
  49. _itemRepo = itemRepo;
  50. _fileSystem = fileSystem;
  51. VideoImageCache = new FileSystemRepository(VideoImagesDataPath);
  52. SubtitleCache = new FileSystemRepository(SubtitleCachePath);
  53. }
  54. /// <summary>
  55. /// Gets the video images data path.
  56. /// </summary>
  57. /// <value>The video images data path.</value>
  58. public string VideoImagesDataPath
  59. {
  60. get
  61. {
  62. return Path.Combine(_appPaths.DataPath, "extracted-video-images");
  63. }
  64. }
  65. /// <summary>
  66. /// Gets the audio images data path.
  67. /// </summary>
  68. /// <value>The audio images data path.</value>
  69. public string AudioImagesDataPath
  70. {
  71. get
  72. {
  73. return Path.Combine(_appPaths.DataPath, "extracted-audio-images");
  74. }
  75. }
  76. /// <summary>
  77. /// Gets the subtitle cache path.
  78. /// </summary>
  79. /// <value>The subtitle cache path.</value>
  80. public string SubtitleCachePath
  81. {
  82. get
  83. {
  84. return Path.Combine(_appPaths.CachePath, "subtitles");
  85. }
  86. }
  87. /// <summary>
  88. /// The first chapter ticks
  89. /// </summary>
  90. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  91. /// <summary>
  92. /// Extracts the chapter images.
  93. /// </summary>
  94. /// <param name="video">The video.</param>
  95. /// <param name="chapters">The chapters.</param>
  96. /// <param name="extractImages">if set to <c>true</c> [extract images].</param>
  97. /// <param name="saveChapters">if set to <c>true</c> [save chapters].</param>
  98. /// <param name="cancellationToken">The cancellation token.</param>
  99. /// <returns>Task.</returns>
  100. /// <exception cref="System.ArgumentNullException"></exception>
  101. public async Task<bool> PopulateChapterImages(Video video, List<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
  102. {
  103. // Can't extract images if there are no video streams
  104. if (!video.DefaultVideoStreamIndex.HasValue)
  105. {
  106. return true;
  107. }
  108. var success = true;
  109. var changesMade = false;
  110. var runtimeTicks = video.RunTimeTicks ?? 0;
  111. foreach (var chapter in chapters)
  112. {
  113. if (chapter.StartPositionTicks >= runtimeTicks)
  114. {
  115. _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  116. break;
  117. }
  118. var filename = video.Path + "_" + video.DateModified.Ticks + "_" + chapter.StartPositionTicks;
  119. var path = VideoImageCache.GetResourcePath(filename, ".jpg");
  120. if (!File.Exists(path))
  121. {
  122. if (extractImages)
  123. {
  124. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  125. {
  126. continue;
  127. }
  128. if (video.VideoType == VideoType.BluRay)
  129. {
  130. // Can only extract reliably on single file blurays
  131. if (video.PlayableStreamFileNames == null || video.PlayableStreamFileNames.Count != 1)
  132. {
  133. continue;
  134. }
  135. }
  136. // Add some time for the first chapter to make sure we don't end up with a black image
  137. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  138. InputType type;
  139. var inputPath = MediaEncoderHelpers.GetInputArgument(video, null, out type);
  140. try
  141. {
  142. var parentPath = Path.GetDirectoryName(path);
  143. Directory.CreateDirectory(parentPath);
  144. await _encoder.ExtractImage(inputPath, type, video.Video3DFormat, time, path, cancellationToken).ConfigureAwait(false);
  145. chapter.ImagePath = path;
  146. changesMade = true;
  147. }
  148. catch
  149. {
  150. success = false;
  151. break;
  152. }
  153. }
  154. }
  155. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  156. {
  157. chapter.ImagePath = path;
  158. changesMade = true;
  159. }
  160. }
  161. if (saveChapters && changesMade)
  162. {
  163. await _itemRepo.SaveChapters(video.Id, chapters, cancellationToken).ConfigureAwait(false);
  164. }
  165. return success;
  166. }
  167. /// <summary>
  168. /// Gets the subtitle cache path.
  169. /// </summary>
  170. /// <param name="input">The input.</param>
  171. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  172. /// <param name="offset">The offset.</param>
  173. /// <param name="outputExtension">The output extension.</param>
  174. /// <returns>System.String.</returns>
  175. public string GetSubtitleCachePath(Video input, int subtitleStreamIndex, TimeSpan? offset, string outputExtension)
  176. {
  177. var ticksParam = offset.HasValue ? "_" + offset.Value.Ticks : "";
  178. var stream = _itemRepo.GetMediaStreams(new MediaStreamQuery
  179. {
  180. ItemId = input.Id,
  181. Index = subtitleStreamIndex
  182. }).FirstOrDefault();
  183. if (stream == null)
  184. {
  185. return null;
  186. }
  187. if (stream.IsExternal)
  188. {
  189. ticksParam += _fileSystem.GetLastWriteTimeUtc(stream.Path).Ticks;
  190. }
  191. return SubtitleCache.GetResourcePath(input.Id + "_" + subtitleStreamIndex + "_" + input.DateModified.Ticks + ticksParam, outputExtension);
  192. }
  193. }
  194. }