EncodingManager.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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)
  60. {
  61. if (!libraryOptions.EnableChapterImageExtraction)
  62. {
  63. return false;
  64. }
  65. }
  66. else
  67. {
  68. return false;
  69. }
  70. // Can't extract images if there are no video streams
  71. return video.DefaultVideoStreamIndex.HasValue;
  72. }
  73. /// <summary>
  74. /// The first chapter ticks
  75. /// </summary>
  76. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  77. public async Task<bool> RefreshChapterImages(ChapterImageRefreshOptions options, CancellationToken cancellationToken)
  78. {
  79. var extractImages = options.ExtractImages;
  80. var video = options.Video;
  81. var chapters = options.Chapters;
  82. var saveChapters = options.SaveChapters;
  83. if (!IsEligibleForChapterImageExtraction(video))
  84. {
  85. extractImages = false;
  86. }
  87. var success = true;
  88. var changesMade = false;
  89. var runtimeTicks = video.RunTimeTicks ?? 0;
  90. var currentImages = GetSavedChapterImages(video);
  91. foreach (var chapter in chapters)
  92. {
  93. if (chapter.StartPositionTicks >= runtimeTicks)
  94. {
  95. _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  96. break;
  97. }
  98. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  99. if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase))
  100. {
  101. if (extractImages)
  102. {
  103. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  104. {
  105. continue;
  106. }
  107. if (video.VideoType == VideoType.BluRay || video.VideoType == VideoType.Dvd)
  108. {
  109. if (video.PlayableStreamFileNames.Count != 1)
  110. {
  111. continue;
  112. }
  113. }
  114. try
  115. {
  116. // Add some time for the first chapter to make sure we don't end up with a black image
  117. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  118. var protocol = MediaProtocol.File;
  119. var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, video.PlayableStreamFileNames);
  120. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  121. var container = video.Container;
  122. var tempFile = await _encoder.ExtractVideoImage(inputPath, container, protocol, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  123. File.Copy(tempFile, path, true);
  124. try
  125. {
  126. File.Delete(tempFile);
  127. }
  128. catch
  129. {
  130. }
  131. chapter.ImagePath = path;
  132. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  133. changesMade = true;
  134. }
  135. catch (Exception ex)
  136. {
  137. _logger.ErrorException("Error extracting chapter images for {0}", ex, string.Join(",", video.Path));
  138. success = false;
  139. break;
  140. }
  141. }
  142. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  143. {
  144. chapter.ImagePath = null;
  145. changesMade = true;
  146. }
  147. }
  148. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  149. {
  150. chapter.ImagePath = path;
  151. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  152. changesMade = true;
  153. }
  154. }
  155. if (saveChapters && changesMade)
  156. {
  157. await _chapterManager.SaveChapters(video.Id.ToString(), chapters, cancellationToken).ConfigureAwait(false);
  158. }
  159. DeleteDeadImages(currentImages, chapters);
  160. return success;
  161. }
  162. private string GetChapterImagePath(Video video, long chapterPositionTicks)
  163. {
  164. var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg";
  165. return Path.Combine(GetChapterImagesPath(video), filename);
  166. }
  167. private List<string> GetSavedChapterImages(Video video)
  168. {
  169. var path = GetChapterImagesPath(video);
  170. try
  171. {
  172. return _fileSystem.GetFilePaths(path)
  173. .ToList();
  174. }
  175. catch (DirectoryNotFoundException)
  176. {
  177. return new List<string>();
  178. }
  179. }
  180. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  181. {
  182. var deadImages = images
  183. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  184. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase))
  185. .ToList();
  186. foreach (var image in deadImages)
  187. {
  188. _logger.Debug("Deleting dead chapter image {0}", image);
  189. try
  190. {
  191. _fileSystem.DeleteFile(image);
  192. }
  193. catch (IOException ex)
  194. {
  195. _logger.ErrorException("Error deleting {0}.", ex, image);
  196. }
  197. }
  198. }
  199. }
  200. }