EncodingManager.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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.IsPlaceHolder)
  74. {
  75. return false;
  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. public async Task<bool> RefreshChapterImages(ChapterImageRefreshOptions options, CancellationToken cancellationToken)
  106. {
  107. var extractImages = options.ExtractImages;
  108. var video = options.Video;
  109. var chapters = options.Chapters;
  110. var saveChapters = options.SaveChapters;
  111. if (!IsEligibleForChapterImageExtraction(video))
  112. {
  113. extractImages = false;
  114. }
  115. var success = true;
  116. var changesMade = false;
  117. var runtimeTicks = video.RunTimeTicks ?? 0;
  118. var currentImages = GetSavedChapterImages(video);
  119. foreach (var chapter in chapters)
  120. {
  121. if (chapter.StartPositionTicks >= runtimeTicks)
  122. {
  123. _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  124. break;
  125. }
  126. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  127. if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase))
  128. {
  129. if (extractImages)
  130. {
  131. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  132. {
  133. continue;
  134. }
  135. if (video.VideoType == VideoType.BluRay)
  136. {
  137. // Can only extract reliably on single file blurays
  138. if (video.PlayableStreamFileNames == null || video.PlayableStreamFileNames.Count != 1)
  139. {
  140. continue;
  141. }
  142. }
  143. // Add some time for the first chapter to make sure we don't end up with a black image
  144. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  145. InputType type;
  146. var inputPath = MediaEncoderHelpers.GetInputArgument(video.Path, false, video.VideoType, video.IsoType, null, video.PlayableStreamFileNames, out type);
  147. try
  148. {
  149. Directory.CreateDirectory(Path.GetDirectoryName(path));
  150. using (var stream = await _encoder.ExtractImage(inputPath, type, false, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false))
  151. {
  152. using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  153. {
  154. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  155. }
  156. }
  157. chapter.ImagePath = path;
  158. changesMade = true;
  159. }
  160. catch
  161. {
  162. success = false;
  163. break;
  164. }
  165. }
  166. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  167. {
  168. chapter.ImagePath = null;
  169. changesMade = true;
  170. }
  171. }
  172. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  173. {
  174. chapter.ImagePath = path;
  175. changesMade = true;
  176. }
  177. }
  178. if (saveChapters && changesMade)
  179. {
  180. await _itemRepo.SaveChapters(video.Id, chapters, cancellationToken).ConfigureAwait(false);
  181. }
  182. DeleteDeadImages(currentImages, chapters);
  183. return success;
  184. }
  185. private string GetChapterImagePath(Video video, long chapterPositionTicks)
  186. {
  187. var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg";
  188. return Path.Combine(GetChapterImagesPath(video.Id), filename);
  189. }
  190. private List<string> GetSavedChapterImages(Video video)
  191. {
  192. var path = GetChapterImagesPath(video.Id);
  193. try
  194. {
  195. return Directory.EnumerateFiles(path)
  196. .ToList();
  197. }
  198. catch (DirectoryNotFoundException)
  199. {
  200. return new List<string>();
  201. }
  202. }
  203. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  204. {
  205. var deadImages = images
  206. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  207. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase))
  208. .ToList();
  209. foreach (var image in deadImages)
  210. {
  211. _logger.Debug("Deleting dead chapter image {0}", image);
  212. try
  213. {
  214. File.Delete(image);
  215. }
  216. catch (IOException ex)
  217. {
  218. _logger.ErrorException("Error deleting {0}.", ex, image);
  219. }
  220. }
  221. }
  222. }
  223. }