EncodingManager.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 IChapterManager _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. IChapterManager 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. public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
  83. {
  84. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  85. if (!IsEligibleForChapterImageExtraction(video, libraryOptions))
  86. {
  87. extractImages = false;
  88. }
  89. var success = true;
  90. var changesMade = false;
  91. var runtimeTicks = video.RunTimeTicks ?? 0;
  92. var currentImages = GetSavedChapterImages(video, directoryService);
  93. foreach (var chapter in chapters)
  94. {
  95. if (chapter.StartPositionTicks >= runtimeTicks)
  96. {
  97. _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  98. break;
  99. }
  100. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  101. if (!currentImages.Contains(path, StringComparison.OrdinalIgnoreCase))
  102. {
  103. if (extractImages)
  104. {
  105. cancellationToken.ThrowIfCancellationRequested();
  106. try
  107. {
  108. // Add some time for the first chapter to make sure we don't end up with a black image
  109. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  110. var inputPath = video.Path;
  111. Directory.CreateDirectory(Path.GetDirectoryName(path));
  112. var container = video.Container;
  113. var mediaSource = new MediaSourceInfo
  114. {
  115. VideoType = video.VideoType,
  116. IsoType = video.IsoType,
  117. Protocol = video.PathProtocol.Value,
  118. };
  119. var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  120. File.Copy(tempFile, path, true);
  121. try
  122. {
  123. _fileSystem.DeleteFile(tempFile);
  124. }
  125. catch (IOException ex)
  126. {
  127. _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile);
  128. }
  129. chapter.ImagePath = path;
  130. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  131. changesMade = true;
  132. }
  133. catch (Exception ex)
  134. {
  135. _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path));
  136. success = false;
  137. break;
  138. }
  139. }
  140. else if (!string.IsNullOrEmpty(chapter.ImagePath))
  141. {
  142. chapter.ImagePath = null;
  143. changesMade = true;
  144. }
  145. }
  146. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  147. {
  148. chapter.ImagePath = path;
  149. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  150. changesMade = true;
  151. }
  152. else if (libraryOptions?.EnableChapterImageExtraction != true)
  153. {
  154. // We have an image for the current chapter but the user has disabled chapter image extraction -> delete this chapter's image
  155. chapter.ImagePath = null;
  156. changesMade = true;
  157. }
  158. }
  159. if (saveChapters && changesMade)
  160. {
  161. _chapterManager.SaveChapters(video.Id, chapters);
  162. }
  163. DeleteDeadImages(currentImages, chapters);
  164. return success;
  165. }
  166. private string GetChapterImagePath(Video video, long chapterPositionTicks)
  167. {
  168. var filename = video.DateModified.Ticks.ToString(CultureInfo.InvariantCulture) + "_" + chapterPositionTicks.ToString(CultureInfo.InvariantCulture) + ".jpg";
  169. return Path.Combine(GetChapterImagesPath(video), filename);
  170. }
  171. private static IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
  172. {
  173. var path = GetChapterImagesPath(video);
  174. if (!Directory.Exists(path))
  175. {
  176. return Array.Empty<string>();
  177. }
  178. try
  179. {
  180. return directoryService.GetFilePaths(path);
  181. }
  182. catch (IOException)
  183. {
  184. return Array.Empty<string>();
  185. }
  186. }
  187. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  188. {
  189. var deadImages = images
  190. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  191. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i.AsSpan()), StringComparison.OrdinalIgnoreCase))
  192. .ToList();
  193. foreach (var image in deadImages)
  194. {
  195. _logger.LogDebug("Deleting dead chapter image {Path}", image);
  196. try
  197. {
  198. _fileSystem.DeleteFile(image);
  199. }
  200. catch (IOException ex)
  201. {
  202. _logger.LogError(ex, "Error deleting {Path}.", image);
  203. }
  204. }
  205. }
  206. }
  207. }