EncodingManager.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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.ChapterOptions.EnableMovieChapterImageExtraction)
  80. {
  81. return false;
  82. }
  83. }
  84. else if (video is Episode)
  85. {
  86. if (!_config.Configuration.ChapterOptions.EnableEpisodeChapterImageExtraction)
  87. {
  88. return false;
  89. }
  90. }
  91. else
  92. {
  93. if (!_config.Configuration.ChapterOptions.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. video.VideoType == VideoType.BluRay)
  133. {
  134. continue;
  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.Path, false, video.VideoType, video.IsoType, null, video.PlayableStreamFileNames, out type);
  140. try
  141. {
  142. Directory.CreateDirectory(Path.GetDirectoryName(path));
  143. using (var stream = await _encoder.ExtractVideoImage(inputPath, type, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false))
  144. {
  145. using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  146. {
  147. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  148. }
  149. }
  150. chapter.ImagePath = path;
  151. changesMade = true;
  152. }
  153. catch
  154. {
  155. success = false;
  156. break;
  157. }
  158. }
  159. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  160. {
  161. chapter.ImagePath = null;
  162. changesMade = true;
  163. }
  164. }
  165. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  166. {
  167. chapter.ImagePath = path;
  168. changesMade = true;
  169. }
  170. }
  171. if (saveChapters && changesMade)
  172. {
  173. await _itemRepo.SaveChapters(video.Id, chapters, cancellationToken).ConfigureAwait(false);
  174. }
  175. DeleteDeadImages(currentImages, chapters);
  176. return success;
  177. }
  178. private string GetChapterImagePath(Video video, long chapterPositionTicks)
  179. {
  180. var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg";
  181. return Path.Combine(GetChapterImagesPath(video.Id), filename);
  182. }
  183. private List<string> GetSavedChapterImages(Video video)
  184. {
  185. var path = GetChapterImagesPath(video.Id);
  186. try
  187. {
  188. return Directory.EnumerateFiles(path)
  189. .ToList();
  190. }
  191. catch (DirectoryNotFoundException)
  192. {
  193. return new List<string>();
  194. }
  195. }
  196. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  197. {
  198. var deadImages = images
  199. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  200. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase))
  201. .ToList();
  202. foreach (var image in deadImages)
  203. {
  204. _logger.Debug("Deleting dead chapter image {0}", image);
  205. try
  206. {
  207. File.Delete(image);
  208. }
  209. catch (IOException ex)
  210. {
  211. _logger.ErrorException("Error deleting {0}.", ex, image);
  212. }
  213. }
  214. }
  215. }
  216. }