EncodingManager.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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, ILibraryManager libraryManager)
  32. {
  33. _fileSystem = fileSystem;
  34. _logger = logger;
  35. _encoder = encoder;
  36. _chapterManager = chapterManager;
  37. _libraryManager = libraryManager;
  38. }
  39. /// <summary>
  40. /// Gets the chapter images data path.
  41. /// </summary>
  42. /// <value>The chapter images data path.</value>
  43. private string GetChapterImagesPath(IHasImages item)
  44. {
  45. return Path.Combine(item.GetInternalMetadataPath(), "chapters");
  46. }
  47. /// <summary>
  48. /// Determines whether [is eligible for chapter image extraction] [the specified video].
  49. /// </summary>
  50. /// <param name="video">The video.</param>
  51. /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
  52. private bool IsEligibleForChapterImageExtraction(Video video)
  53. {
  54. if (video.IsPlaceHolder)
  55. {
  56. return false;
  57. }
  58. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  59. if (libraryOptions != null && libraryOptions.SchemaVersion >= 2)
  60. {
  61. if (!libraryOptions.EnableChapterImageExtraction)
  62. {
  63. return false;
  64. }
  65. }
  66. else
  67. {
  68. var options = _chapterManager.GetConfiguration();
  69. if (video is Movie)
  70. {
  71. if (!options.EnableMovieChapterImageExtraction)
  72. {
  73. return false;
  74. }
  75. }
  76. else if (video is Episode)
  77. {
  78. if (!options.EnableEpisodeChapterImageExtraction)
  79. {
  80. return false;
  81. }
  82. }
  83. else
  84. {
  85. if (!options.EnableOtherVideoChapterImageExtraction)
  86. {
  87. return false;
  88. }
  89. }
  90. }
  91. // Can't extract images if there are no video streams
  92. return video.DefaultVideoStreamIndex.HasValue;
  93. }
  94. /// <summary>
  95. /// The first chapter ticks
  96. /// </summary>
  97. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  98. public async Task<bool> RefreshChapterImages(ChapterImageRefreshOptions options, CancellationToken cancellationToken)
  99. {
  100. var extractImages = options.ExtractImages;
  101. var video = options.Video;
  102. var chapters = options.Chapters;
  103. var saveChapters = options.SaveChapters;
  104. if (!IsEligibleForChapterImageExtraction(video))
  105. {
  106. extractImages = false;
  107. }
  108. var success = true;
  109. var changesMade = false;
  110. var runtimeTicks = video.RunTimeTicks ?? 0;
  111. var currentImages = GetSavedChapterImages(video);
  112. foreach (var chapter in chapters)
  113. {
  114. if (chapter.StartPositionTicks >= runtimeTicks)
  115. {
  116. _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  117. break;
  118. }
  119. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  120. if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase))
  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 || video.VideoType == VideoType.Dvd)
  129. {
  130. if (video.PlayableStreamFileNames.Count != 1)
  131. {
  132. continue;
  133. }
  134. }
  135. try
  136. {
  137. // Add some time for the first chapter to make sure we don't end up with a black image
  138. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  139. var protocol = MediaProtocol.File;
  140. var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, video.PlayableStreamFileNames);
  141. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  142. var tempFile = await _encoder.ExtractVideoImage(inputPath, protocol, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  143. File.Copy(tempFile, path, true);
  144. try
  145. {
  146. File.Delete(tempFile);
  147. }
  148. catch
  149. {
  150. }
  151. chapter.ImagePath = path;
  152. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  153. changesMade = true;
  154. }
  155. catch (Exception ex)
  156. {
  157. _logger.ErrorException("Error extracting chapter images for {0}", ex, string.Join(",", video.Path));
  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. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  172. changesMade = true;
  173. }
  174. }
  175. if (saveChapters && changesMade)
  176. {
  177. await _chapterManager.SaveChapters(video.Id.ToString(), chapters, cancellationToken).ConfigureAwait(false);
  178. }
  179. DeleteDeadImages(currentImages, chapters);
  180. return success;
  181. }
  182. private string GetChapterImagePath(Video video, long chapterPositionTicks)
  183. {
  184. var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg";
  185. return Path.Combine(GetChapterImagesPath(video), filename);
  186. }
  187. private List<string> GetSavedChapterImages(Video video)
  188. {
  189. var path = GetChapterImagesPath(video);
  190. try
  191. {
  192. return _fileSystem.GetFilePaths(path)
  193. .ToList();
  194. }
  195. catch (DirectoryNotFoundException)
  196. {
  197. return new List<string>();
  198. }
  199. }
  200. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  201. {
  202. var deadImages = images
  203. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  204. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase))
  205. .ToList();
  206. foreach (var image in deadImages)
  207. {
  208. _logger.Debug("Deleting dead chapter image {0}", image);
  209. try
  210. {
  211. _fileSystem.DeleteFile(image);
  212. }
  213. catch (IOException ex)
  214. {
  215. _logger.ErrorException("Error deleting {0}.", ex, image);
  216. }
  217. }
  218. }
  219. }
  220. }