EncodingManager.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Controller.Chapters;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.MediaInfo;
  16. using Microsoft.Extensions.Logging;
  17. namespace Emby.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. private readonly ILibraryManager _libraryManager;
  27. public EncodingManager(
  28. IFileSystem fileSystem,
  29. ILoggerFactory loggerFactory,
  30. IMediaEncoder encoder,
  31. IChapterManager chapterManager, ILibraryManager libraryManager)
  32. {
  33. _fileSystem = fileSystem;
  34. _logger = loggerFactory.CreateLogger(nameof(EncodingManager));
  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 static string GetChapterImagesPath(BaseItem 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. if (video.VideoType == VideoType.Iso)
  71. {
  72. return false;
  73. }
  74. if (video.VideoType == VideoType.BluRay || video.VideoType == VideoType.Dvd)
  75. {
  76. return false;
  77. }
  78. if (video.IsShortcut)
  79. {
  80. return false;
  81. }
  82. if (!video.IsCompleteMedia)
  83. {
  84. return false;
  85. }
  86. // Can't extract images if there are no video streams
  87. return video.DefaultVideoStreamIndex.HasValue;
  88. }
  89. /// <summary>
  90. /// The first chapter ticks
  91. /// </summary>
  92. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  93. public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, List<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
  94. {
  95. if (!IsEligibleForChapterImageExtraction(video))
  96. {
  97. extractImages = false;
  98. }
  99. var success = true;
  100. var changesMade = false;
  101. var runtimeTicks = video.RunTimeTicks ?? 0;
  102. var currentImages = GetSavedChapterImages(video, directoryService);
  103. foreach (var chapter in chapters)
  104. {
  105. if (chapter.StartPositionTicks >= runtimeTicks)
  106. {
  107. _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  108. break;
  109. }
  110. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  111. if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase))
  112. {
  113. if (extractImages)
  114. {
  115. cancellationToken.ThrowIfCancellationRequested();
  116. try
  117. {
  118. // Add some time for the first chapter to make sure we don't end up with a black image
  119. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  120. var protocol = MediaProtocol.File;
  121. var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, Array.Empty<string>());
  122. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  123. var container = video.Container;
  124. var tempFile = await _encoder.ExtractVideoImage(inputPath, container, protocol, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  125. _fileSystem.CopyFile(tempFile, path, true);
  126. try
  127. {
  128. _fileSystem.DeleteFile(tempFile);
  129. }
  130. catch
  131. {
  132. }
  133. chapter.ImagePath = path;
  134. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  135. changesMade = true;
  136. }
  137. catch (Exception ex)
  138. {
  139. _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(",", video.Path));
  140. success = false;
  141. break;
  142. }
  143. }
  144. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  145. {
  146. chapter.ImagePath = null;
  147. changesMade = true;
  148. }
  149. }
  150. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  151. {
  152. chapter.ImagePath = path;
  153. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  154. changesMade = true;
  155. }
  156. }
  157. if (saveChapters && changesMade)
  158. {
  159. _chapterManager.SaveChapters(video.Id.ToString(), chapters);
  160. }
  161. DeleteDeadImages(currentImages, chapters);
  162. return success;
  163. }
  164. private string GetChapterImagePath(Video video, long chapterPositionTicks)
  165. {
  166. var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg";
  167. return Path.Combine(GetChapterImagesPath(video), filename);
  168. }
  169. private static List<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
  170. {
  171. var path = GetChapterImagesPath(video);
  172. try
  173. {
  174. return directoryService.GetFilePaths(path)
  175. .ToList();
  176. }
  177. catch (IOException)
  178. {
  179. return new List<string>();
  180. }
  181. }
  182. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  183. {
  184. var deadImages = images
  185. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  186. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase))
  187. .ToList();
  188. foreach (var image in deadImages)
  189. {
  190. _logger.LogDebug("Deleting dead chapter image {path}", image);
  191. try
  192. {
  193. _fileSystem.DeleteFile(image);
  194. }
  195. catch (IOException ex)
  196. {
  197. _logger.LogError(ex, "Error deleting {path}.", image);
  198. }
  199. }
  200. }
  201. }
  202. }