EncodingManager.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using Microsoft.Extensions.Logging;
  20. namespace Emby.Server.Implementations.MediaEncoder
  21. {
  22. public class EncodingManager : IEncodingManager
  23. {
  24. private readonly IFileSystem _fileSystem;
  25. private readonly ILogger<EncodingManager> _logger;
  26. private readonly IMediaEncoder _encoder;
  27. private readonly IChapterManager _chapterManager;
  28. private readonly ILibraryManager _libraryManager;
  29. /// <summary>
  30. /// The first chapter ticks.
  31. /// </summary>
  32. private static readonly long _firstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  33. public EncodingManager(
  34. ILogger<EncodingManager> logger,
  35. IFileSystem fileSystem,
  36. IMediaEncoder encoder,
  37. IChapterManager chapterManager,
  38. ILibraryManager libraryManager)
  39. {
  40. _logger = logger;
  41. _fileSystem = fileSystem;
  42. _encoder = encoder;
  43. _chapterManager = chapterManager;
  44. _libraryManager = libraryManager;
  45. }
  46. /// <summary>
  47. /// Gets the chapter images data path.
  48. /// </summary>
  49. /// <value>The chapter images data path.</value>
  50. private static string GetChapterImagesPath(BaseItem item)
  51. {
  52. return Path.Combine(item.GetInternalMetadataPath(), "chapters");
  53. }
  54. /// <summary>
  55. /// Determines whether [is eligible for chapter image extraction] [the specified video].
  56. /// </summary>
  57. /// <param name="video">The video.</param>
  58. /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
  59. private bool IsEligibleForChapterImageExtraction(Video video)
  60. {
  61. if (video.IsPlaceHolder)
  62. {
  63. return false;
  64. }
  65. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  66. if (libraryOptions is not null)
  67. {
  68. if (!libraryOptions.EnableChapterImageExtraction)
  69. {
  70. return false;
  71. }
  72. }
  73. else
  74. {
  75. return false;
  76. }
  77. if (video.IsShortcut)
  78. {
  79. return false;
  80. }
  81. if (!video.IsCompleteMedia)
  82. {
  83. return false;
  84. }
  85. // Can't extract images if there are no video streams
  86. return video.DefaultVideoStreamIndex.HasValue;
  87. }
  88. public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
  89. {
  90. if (!IsEligibleForChapterImageExtraction(video))
  91. {
  92. extractImages = false;
  93. }
  94. var success = true;
  95. var changesMade = false;
  96. var runtimeTicks = video.RunTimeTicks ?? 0;
  97. var currentImages = GetSavedChapterImages(video, directoryService);
  98. foreach (var chapter in chapters)
  99. {
  100. if (chapter.StartPositionTicks >= runtimeTicks)
  101. {
  102. _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
  103. break;
  104. }
  105. var path = GetChapterImagePath(video, chapter.StartPositionTicks);
  106. if (!currentImages.Contains(path, StringComparison.OrdinalIgnoreCase))
  107. {
  108. if (extractImages)
  109. {
  110. cancellationToken.ThrowIfCancellationRequested();
  111. try
  112. {
  113. // Add some time for the first chapter to make sure we don't end up with a black image
  114. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  115. var inputPath = video.Path;
  116. Directory.CreateDirectory(Path.GetDirectoryName(path));
  117. var container = video.Container;
  118. var mediaSource = new MediaSourceInfo
  119. {
  120. VideoType = video.VideoType,
  121. IsoType = video.IsoType,
  122. Protocol = video.PathProtocol.Value,
  123. };
  124. var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
  125. File.Copy(tempFile, path, true);
  126. try
  127. {
  128. _fileSystem.DeleteFile(tempFile);
  129. }
  130. catch (IOException ex)
  131. {
  132. _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile);
  133. }
  134. chapter.ImagePath = path;
  135. chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
  136. changesMade = true;
  137. }
  138. catch (Exception ex)
  139. {
  140. _logger.LogError(ex, "Error extracting chapter images for {0}", 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. _chapterManager.SaveChapters(video.Id, chapters);
  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(CultureInfo.InvariantCulture) + "_" + chapterPositionTicks.ToString(CultureInfo.InvariantCulture) + ".jpg";
  168. return Path.Combine(GetChapterImagesPath(video), filename);
  169. }
  170. private static IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
  171. {
  172. var path = GetChapterImagesPath(video);
  173. if (!Directory.Exists(path))
  174. {
  175. return Array.Empty<string>();
  176. }
  177. try
  178. {
  179. return directoryService.GetFilePaths(path);
  180. }
  181. catch (IOException)
  182. {
  183. return Array.Empty<string>();
  184. }
  185. }
  186. private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
  187. {
  188. var deadImages = images
  189. .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
  190. .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparison.OrdinalIgnoreCase))
  191. .ToList();
  192. foreach (var image in deadImages)
  193. {
  194. _logger.LogDebug("Deleting dead chapter image {Path}", image);
  195. try
  196. {
  197. _fileSystem.DeleteFile(image);
  198. }
  199. catch (IOException ex)
  200. {
  201. _logger.LogError(ex, "Error deleting {Path}.", image);
  202. }
  203. }
  204. }
  205. }
  206. }