EncodingManager.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Extensions;
  11. using MediaBrowser.Controller.Chapters;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.MediaEncoding;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.IO;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.MediaEncoder
  22. {
  23. public class EncodingManager : IEncodingManager
  24. {
  25. private readonly IFileSystem _fileSystem;
  26. private readonly ILogger<EncodingManager> _logger;
  27. private readonly IMediaEncoder _encoder;
  28. private readonly IChapterRepository _chapterManager;
  29. private readonly ILibraryManager _libraryManager;
  30. /// <summary>
  31. /// The first chapter ticks.
  32. /// </summary>
  33. private static readonly long _firstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  34. public EncodingManager(
  35. ILogger<EncodingManager> logger,
  36. IFileSystem fileSystem,
  37. IMediaEncoder encoder,
  38. IChapterRepository chapterManager,
  39. ILibraryManager libraryManager)
  40. {
  41. _logger = logger;
  42. _fileSystem = fileSystem;
  43. _encoder = encoder;
  44. _chapterManager = chapterManager;
  45. _libraryManager = libraryManager;
  46. }
  47. /// <summary>
  48. /// Gets the chapter images data path.
  49. /// </summary>
  50. /// <value>The chapter images data path.</value>
  51. private static string GetChapterImagesPath(BaseItem item)
  52. {
  53. return Path.Combine(item.GetInternalMetadataPath(), "chapters");
  54. }
  55. /// <summary>
  56. /// Determines whether [is eligible for chapter image extraction] [the specified video].
  57. /// </summary>
  58. /// <param name="video">The video.</param>
  59. /// <param name="libraryOptions">The library options for the video.</param>
  60. /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
  61. private bool IsEligibleForChapterImageExtraction(Video video, LibraryOptions libraryOptions)
  62. {
  63. if (video.IsPlaceHolder)
  64. {
  65. return false;
  66. }
  67. if (libraryOptions is null || !libraryOptions.EnableChapterImageExtraction)
  68. {
  69. return false;
  70. }
  71. if (video.IsShortcut)
  72. {
  73. return false;
  74. }
  75. if (!video.IsCompleteMedia)
  76. {
  77. return false;
  78. }
  79. // Can't extract images if there are no video streams
  80. return video.DefaultVideoStreamIndex.HasValue;
  81. }
  82. private long GetAverageDurationBetweenChapters(IReadOnlyList<ChapterInfo> chapters)
  83. {
  84. if (chapters.Count < 2)
  85. {
  86. return 0;
  87. }
  88. long sum = 0;
  89. for (int i = 1; i < chapters.Count; i++)
  90. {
  91. sum += chapters[i].StartPositionTicks - chapters[i - 1].StartPositionTicks;
  92. }
  93. return sum / chapters.Count;
  94. }
  95. public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
  96. {
  97. if (chapters.Count == 0)
  98. {
  99. return true;
  100. }
  101. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  102. if (!IsEligibleForChapterImageExtraction(video, libraryOptions))
  103. {
  104. extractImages = false;
  105. }
  106. var averageChapterDuration = GetAverageDurationBetweenChapters(chapters);
  107. var threshold = TimeSpan.FromSeconds(1).Ticks;
  108. if (averageChapterDuration < threshold)
  109. {
  110. _logger.LogInformation("Skipping chapter image extraction for {Video} as the average chapter duration {AverageDuration} was lower than the minimum threshold {Threshold}", video.Name, averageChapterDuration, threshold);
  111. extractImages = false;
  112. }
  113. var success = true;
  114. var changesMade = false;
  115. var runtimeTicks = video.RunTimeTicks ?? 0;
  116. var currentImages = GetSavedChapterImages(video, directoryService);
  117. foreach (var chapter in chapters)
  118. {
  119. if (chapter.StartPositionTicks >= runtimeTicks)
  120. {
  121. _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  122. break;
  123. }
  124. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  125. if (!currentImages.Contains(path, StringComparison.OrdinalIgnoreCase))
  126. {
  127. if (extractImages)
  128. {
  129. cancellationToken.ThrowIfCancellationRequested();
  130. try
  131. {
  132. // Add some time for the first chapter to make sure we don't end up with a black image
  133. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  134. var inputPath = video.Path;
  135. Directory.CreateDirectory(Path.GetDirectoryName(path));
  136. var container = video.Container;
  137. var mediaSource = new MediaSourceInfo
  138. {
  139. VideoType = video.VideoType,
  140. IsoType = video.IsoType,
  141. Protocol = video.PathProtocol.Value,
  142. };
  143. var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  144. File.Copy(tempFile, path, true);
  145. try
  146. {
  147. _fileSystem.DeleteFile(tempFile);
  148. }
  149. catch (IOException ex)
  150. {
  151. _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile);
  152. }
  153. chapter.ImagePath = path;
  154. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  155. changesMade = true;
  156. }
  157. catch (Exception ex)
  158. {
  159. _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path));
  160. success = false;
  161. break;
  162. }
  163. }
  164. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  165. {
  166. chapter.ImagePath = null;
  167. changesMade = true;
  168. }
  169. }
  170. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  171. {
  172. chapter.ImagePath = path;
  173. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  174. changesMade = true;
  175. }
  176. else if (libraryOptions?.EnableChapterImageExtraction != true)
  177. {
  178. // We have an image for the current chapter but the user has disabled chapter image extraction -> delete this chapter's image
  179. chapter.ImagePath = null;
  180. changesMade = true;
  181. }
  182. }
  183. if (saveChapters && changesMade)
  184. {
  185. _chapterManager.SaveChapters(video.Id, chapters);
  186. }
  187. DeleteDeadImages(currentImages, chapters);
  188. return success;
  189. }
  190. private string GetChapterImagePath(Video video, long chapterPositionTicks)
  191. {
  192. var filename = video.DateModified.Ticks.ToString(CultureInfo.InvariantCulture) + "_" + chapterPositionTicks.ToString(CultureInfo.InvariantCulture) + ".jpg";
  193. return Path.Combine(GetChapterImagesPath(video), filename);
  194. }
  195. private static IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
  196. {
  197. var path = GetChapterImagesPath(video);
  198. if (!Directory.Exists(path))
  199. {
  200. return Array.Empty<string>();
  201. }
  202. try
  203. {
  204. return directoryService.GetFilePaths(path);
  205. }
  206. catch (IOException)
  207. {
  208. return Array.Empty<string>();
  209. }
  210. }
  211. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  212. {
  213. var deadImages = images
  214. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  215. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i.AsSpan()), StringComparison.OrdinalIgnoreCase))
  216. .ToList();
  217. foreach (var image in deadImages)
  218. {
  219. _logger.LogDebug("Deleting dead chapter image {Path}", image);
  220. try
  221. {
  222. _fileSystem.DeleteFile(image);
  223. }
  224. catch (IOException ex)
  225. {
  226. _logger.LogError(ex, "Error deleting {Path}.", image);
  227. }
  228. }
  229. }
  230. }
  231. }