EncodingManager.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. using MediaBrowser.Controller.Chapters;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Movies;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Controller.MediaEncoding;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.MediaInfo;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using CommonIO;
  17. using MediaBrowser.Controller.Library;
  18. namespace MediaBrowser.Server.Implementations.MediaEncoder
  19. {
  20. public class EncodingManager : IEncodingManager
  21. {
  22. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  23. private readonly IFileSystem _fileSystem;
  24. private readonly ILogger _logger;
  25. private readonly IMediaEncoder _encoder;
  26. private readonly IChapterManager _chapterManager;
  27. private readonly ILibraryManager _libraryManager;
  28. public EncodingManager(IFileSystem fileSystem,
  29. ILogger logger,
  30. IMediaEncoder encoder,
  31. IChapterManager chapterManager)
  32. {
  33. _fileSystem = fileSystem;
  34. _logger = logger;
  35. _encoder = encoder;
  36. _chapterManager = chapterManager;
  37. }
  38. /// <summary>
  39. /// Gets the chapter images data path.
  40. /// </summary>
  41. /// <value>The chapter images data path.</value>
  42. private string GetChapterImagesPath(IHasImages item)
  43. {
  44. return Path.Combine(item.GetInternalMetadataPath(), "chapters");
  45. }
  46. /// <summary>
  47. /// Determines whether [is eligible for chapter image extraction] [the specified video].
  48. /// </summary>
  49. /// <param name="video">The video.</param>
  50. /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
  51. private bool IsEligibleForChapterImageExtraction(Video video)
  52. {
  53. if (video.IsPlaceHolder)
  54. {
  55. return false;
  56. }
  57. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  58. if (libraryOptions != null && libraryOptions.SchemaVersion >= 2)
  59. {
  60. if (!libraryOptions.EnableChapterImageExtraction)
  61. {
  62. return false;
  63. }
  64. }
  65. else
  66. {
  67. var options = _chapterManager.GetConfiguration();
  68. if (video is Movie)
  69. {
  70. if (!options.EnableMovieChapterImageExtraction)
  71. {
  72. return false;
  73. }
  74. }
  75. else if (video is Episode)
  76. {
  77. if (!options.EnableEpisodeChapterImageExtraction)
  78. {
  79. return false;
  80. }
  81. }
  82. else
  83. {
  84. if (!options.EnableOtherVideoChapterImageExtraction)
  85. {
  86. return false;
  87. }
  88. }
  89. }
  90. // Can't extract images if there are no video streams
  91. return video.DefaultVideoStreamIndex.HasValue;
  92. }
  93. /// <summary>
  94. /// The first chapter ticks
  95. /// </summary>
  96. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  97. public async Task<bool> RefreshChapterImages(ChapterImageRefreshOptions options, CancellationToken cancellationToken)
  98. {
  99. var extractImages = options.ExtractImages;
  100. var video = options.Video;
  101. var chapters = options.Chapters;
  102. var saveChapters = options.SaveChapters;
  103. if (!IsEligibleForChapterImageExtraction(video))
  104. {
  105. extractImages = false;
  106. }
  107. var success = true;
  108. var changesMade = false;
  109. var runtimeTicks = video.RunTimeTicks ?? 0;
  110. var currentImages = GetSavedChapterImages(video);
  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 path = GetChapterImagePath(video, chapter.StartPositionTicks);
  119. if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase))
  120. {
  121. if (extractImages)
  122. {
  123. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  124. {
  125. continue;
  126. }
  127. if (video.VideoType == VideoType.BluRay || video.VideoType == VideoType.Dvd)
  128. {
  129. if (video.PlayableStreamFileNames.Count != 1)
  130. {
  131. continue;
  132. }
  133. }
  134. // Add some time for the first chapter to make sure we don't end up with a black image
  135. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  136. var protocol = MediaProtocol.File;
  137. var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, video.PlayableStreamFileNames);
  138. try
  139. {
  140. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  141. var tempFile = await _encoder.ExtractVideoImage(inputPath, protocol, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  142. File.Copy(tempFile, path, true);
  143. try
  144. {
  145. File.Delete(tempFile);
  146. }
  147. catch
  148. {
  149. }
  150. chapter.ImagePath = path;
  151. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  152. changesMade = true;
  153. }
  154. catch (Exception ex)
  155. {
  156. _logger.ErrorException("Error extracting chapter images for {0}", ex, string.Join(",", inputPath));
  157. success = false;
  158. break;
  159. }
  160. }
  161. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  162. {
  163. chapter.ImagePath = null;
  164. changesMade = true;
  165. }
  166. }
  167. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  168. {
  169. chapter.ImagePath = path;
  170. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  171. changesMade = true;
  172. }
  173. }
  174. if (saveChapters && changesMade)
  175. {
  176. await _chapterManager.SaveChapters(video.Id.ToString(), 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), filename);
  185. }
  186. private List<string> GetSavedChapterImages(Video video)
  187. {
  188. var path = GetChapterImagesPath(video);
  189. try
  190. {
  191. return _fileSystem.GetFilePaths(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. _fileSystem.DeleteFile(image);
  211. }
  212. catch (IOException ex)
  213. {
  214. _logger.ErrorException("Error deleting {0}.", ex, image);
  215. }
  216. }
  217. }
  218. }
  219. }