EncodingManager.cs 8.7 KB

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