EncodingManager.cs 8.6 KB

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