EncodingManager.cs 8.9 KB

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