EncodingManager.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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.MediaEncoding;
  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.Server.Implementations.MediaEncoder
  19. {
  20. public class EncodingManager : IEncodingManager
  21. {
  22. private readonly IServerConfigurationManager _config;
  23. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  24. private readonly IFileSystem _fileSystem;
  25. private readonly ILogger _logger;
  26. private readonly IItemRepository _itemRepo;
  27. private readonly IMediaEncoder _encoder;
  28. public EncodingManager(IServerConfigurationManager config, IFileSystem fileSystem, ILogger logger, IItemRepository itemRepo, IMediaEncoder encoder)
  29. {
  30. _config = config;
  31. _fileSystem = fileSystem;
  32. _logger = logger;
  33. _itemRepo = itemRepo;
  34. _encoder = encoder;
  35. }
  36. private string SubtitleCachePath
  37. {
  38. get
  39. {
  40. return Path.Combine(_config.ApplicationPaths.CachePath, "subtitles");
  41. }
  42. }
  43. public string GetSubtitleCachePath(string originalSubtitlePath, string outputSubtitleExtension)
  44. {
  45. var ticksParam = _fileSystem.GetLastWriteTimeUtc(originalSubtitlePath).Ticks;
  46. var filename = (originalSubtitlePath + ticksParam).GetMD5() + outputSubtitleExtension;
  47. var prefix = filename.Substring(0, 1);
  48. return Path.Combine(SubtitleCachePath, prefix, filename);
  49. }
  50. public string GetSubtitleCachePath(string mediaPath, int subtitleStreamIndex, string outputSubtitleExtension)
  51. {
  52. var ticksParam = string.Empty;
  53. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  54. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(_usCulture) + "_" + date.Ticks.ToString(_usCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  55. var prefix = filename.Substring(0, 1);
  56. return Path.Combine(SubtitleCachePath, prefix, filename);
  57. }
  58. /// <summary>
  59. /// Gets the chapter images data path.
  60. /// </summary>
  61. /// <value>The chapter images data path.</value>
  62. private string GetChapterImagesPath(Guid itemId)
  63. {
  64. return Path.Combine(_config.ApplicationPaths.GetInternalMetadataPath(itemId), "chapters");
  65. }
  66. /// <summary>
  67. /// Determines whether [is eligible for chapter image extraction] [the specified video].
  68. /// </summary>
  69. /// <param name="video">The video.</param>
  70. /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
  71. private bool IsEligibleForChapterImageExtraction(Video video)
  72. {
  73. if (video is Movie)
  74. {
  75. if (!_config.Configuration.EnableMovieChapterImageExtraction)
  76. {
  77. return false;
  78. }
  79. }
  80. else if (video is Episode)
  81. {
  82. if (!_config.Configuration.EnableEpisodeChapterImageExtraction)
  83. {
  84. return false;
  85. }
  86. }
  87. else
  88. {
  89. if (!_config.Configuration.EnableOtherVideoChapterImageExtraction)
  90. {
  91. return false;
  92. }
  93. }
  94. // Can't extract images if there are no video streams
  95. return video.DefaultVideoStreamIndex.HasValue;
  96. }
  97. /// <summary>
  98. /// The first chapter ticks
  99. /// </summary>
  100. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  101. public async Task<bool> RefreshChapterImages(ChapterImageRefreshOptions options, CancellationToken cancellationToken)
  102. {
  103. var extractImages = options.ExtractImages;
  104. var video = options.Video;
  105. var chapters = options.Chapters;
  106. var saveChapters = options.SaveChapters;
  107. if (!IsEligibleForChapterImageExtraction(video))
  108. {
  109. extractImages = false;
  110. }
  111. var success = true;
  112. var changesMade = false;
  113. var runtimeTicks = video.RunTimeTicks ?? 0;
  114. var currentImages = GetSavedChapterImages(video);
  115. foreach (var chapter in chapters)
  116. {
  117. if (chapter.StartPositionTicks >= runtimeTicks)
  118. {
  119. _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  120. break;
  121. }
  122. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  123. if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase))
  124. {
  125. if (extractImages)
  126. {
  127. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  128. {
  129. continue;
  130. }
  131. if (video.VideoType == VideoType.BluRay)
  132. {
  133. // Can only extract reliably on single file blurays
  134. if (video.PlayableStreamFileNames == null || video.PlayableStreamFileNames.Count != 1)
  135. {
  136. continue;
  137. }
  138. }
  139. // Add some time for the first chapter to make sure we don't end up with a black image
  140. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  141. InputType type;
  142. var inputPath = MediaEncoderHelpers.GetInputArgument(video.Path, false, video.VideoType, video.IsoType, null, video.PlayableStreamFileNames, out type);
  143. try
  144. {
  145. Directory.CreateDirectory(Path.GetDirectoryName(path));
  146. using (var stream = await _encoder.ExtractImage(inputPath, type, false, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false))
  147. {
  148. using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  149. {
  150. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  151. }
  152. }
  153. chapter.ImagePath = path;
  154. changesMade = true;
  155. }
  156. catch
  157. {
  158. success = false;
  159. break;
  160. }
  161. }
  162. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  163. {
  164. chapter.ImagePath = null;
  165. changesMade = true;
  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 string GetChapterImagePath(Video video, long chapterPositionTicks)
  182. {
  183. var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg";
  184. return Path.Combine(GetChapterImagesPath(video.Id), filename);
  185. }
  186. private List<string> GetSavedChapterImages(Video video)
  187. {
  188. var path = GetChapterImagesPath(video.Id);
  189. try
  190. {
  191. return Directory.EnumerateFiles(path)
  192. .ToList();
  193. }
  194. catch (DirectoryNotFoundException)
  195. {
  196. return new List<string>();
  197. }
  198. }
  199. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  200. {
  201. var deadImages = images
  202. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  203. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase))
  204. .ToList();
  205. foreach (var image in deadImages)
  206. {
  207. _logger.Debug("Deleting dead chapter image {0}", image);
  208. try
  209. {
  210. File.Delete(image);
  211. }
  212. catch (IOException ex)
  213. {
  214. _logger.ErrorException("Error deleting {0}.", ex, image);
  215. }
  216. }
  217. }
  218. }
  219. }