EncodingManager.cs 8.8 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 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. List<string> playableStreamFileNames = null;
  109. if (video.VideoType == VideoType.BluRay || video.VideoType == VideoType.Dvd)
  110. {
  111. continue;
  112. }
  113. if (playableStreamFileNames == null)
  114. {
  115. playableStreamFileNames = new List<string>();
  116. }
  117. try
  118. {
  119. // Add some time for the first chapter to make sure we don't end up with a black image
  120. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  121. var protocol = MediaProtocol.File;
  122. var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, playableStreamFileNames);
  123. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  124. var container = video.Container;
  125. var tempFile = await _encoder.ExtractVideoImage(inputPath, container, protocol, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  126. _fileSystem.CopyFile(tempFile, path, true);
  127. try
  128. {
  129. _fileSystem.DeleteFile(tempFile);
  130. }
  131. catch
  132. {
  133. }
  134. chapter.ImagePath = path;
  135. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  136. changesMade = true;
  137. }
  138. catch (Exception ex)
  139. {
  140. _logger.ErrorException("Error extracting chapter images for {0}", ex, string.Join(",", video.Path));
  141. success = false;
  142. break;
  143. }
  144. }
  145. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  146. {
  147. chapter.ImagePath = null;
  148. changesMade = true;
  149. }
  150. }
  151. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  152. {
  153. chapter.ImagePath = path;
  154. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  155. changesMade = true;
  156. }
  157. }
  158. if (saveChapters && changesMade)
  159. {
  160. await _chapterManager.SaveChapters(video.Id.ToString(), chapters, cancellationToken).ConfigureAwait(false);
  161. }
  162. DeleteDeadImages(currentImages, chapters);
  163. return success;
  164. }
  165. private string GetChapterImagePath(Video video, long chapterPositionTicks)
  166. {
  167. var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg";
  168. return Path.Combine(GetChapterImagesPath(video), filename);
  169. }
  170. private List<string> GetSavedChapterImages(Video video)
  171. {
  172. var path = GetChapterImagesPath(video);
  173. try
  174. {
  175. return _fileSystem.GetFilePaths(path)
  176. .ToList();
  177. }
  178. catch (IOException)
  179. {
  180. return new List<string>();
  181. }
  182. }
  183. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  184. {
  185. var deadImages = images
  186. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  187. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase))
  188. .ToList();
  189. foreach (var image in deadImages)
  190. {
  191. _logger.Debug("Deleting dead chapter image {0}", image);
  192. try
  193. {
  194. _fileSystem.DeleteFile(image);
  195. }
  196. catch (IOException ex)
  197. {
  198. _logger.ErrorException("Error deleting {0}.", ex, image);
  199. }
  200. }
  201. }
  202. }
  203. }