EncodingManager.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. using MediaBrowser.Controller.Chapters;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Movies;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Controller.MediaEncoding;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.MediaInfo;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using MediaBrowser.Common.IO;
  17. using MediaBrowser.Controller.IO;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Controller.Library;
  20. namespace Emby.Server.Implementations.MediaEncoder
  21. {
  22. public class EncodingManager : IEncodingManager
  23. {
  24. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  25. private readonly IFileSystem _fileSystem;
  26. private readonly ILogger _logger;
  27. private readonly IMediaEncoder _encoder;
  28. private readonly IChapterManager _chapterManager;
  29. private readonly ILibraryManager _libraryManager;
  30. public EncodingManager(IFileSystem fileSystem,
  31. ILogger logger,
  32. IMediaEncoder encoder,
  33. IChapterManager chapterManager, ILibraryManager libraryManager)
  34. {
  35. _fileSystem = fileSystem;
  36. _logger = logger;
  37. _encoder = encoder;
  38. _chapterManager = chapterManager;
  39. _libraryManager = libraryManager;
  40. }
  41. /// <summary>
  42. /// Gets the chapter images data path.
  43. /// </summary>
  44. /// <value>The chapter images data path.</value>
  45. private string GetChapterImagesPath(IHasImages item)
  46. {
  47. return Path.Combine(item.GetInternalMetadataPath(), "chapters");
  48. }
  49. /// <summary>
  50. /// Determines whether [is eligible for chapter image extraction] [the specified video].
  51. /// </summary>
  52. /// <param name="video">The video.</param>
  53. /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
  54. private bool IsEligibleForChapterImageExtraction(Video video)
  55. {
  56. if (video.IsPlaceHolder)
  57. {
  58. return false;
  59. }
  60. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  61. if (libraryOptions != null)
  62. {
  63. if (!libraryOptions.EnableChapterImageExtraction)
  64. {
  65. return false;
  66. }
  67. }
  68. else
  69. {
  70. return false;
  71. }
  72. // Can't extract images if there are no video streams
  73. return video.DefaultVideoStreamIndex.HasValue;
  74. }
  75. /// <summary>
  76. /// The first chapter ticks
  77. /// </summary>
  78. private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  79. public async Task<bool> RefreshChapterImages(ChapterImageRefreshOptions options, CancellationToken cancellationToken)
  80. {
  81. var extractImages = options.ExtractImages;
  82. var video = options.Video;
  83. var chapters = options.Chapters;
  84. var saveChapters = options.SaveChapters;
  85. if (!IsEligibleForChapterImageExtraction(video))
  86. {
  87. extractImages = false;
  88. }
  89. var success = true;
  90. var changesMade = false;
  91. var runtimeTicks = video.RunTimeTicks ?? 0;
  92. var currentImages = GetSavedChapterImages(video);
  93. foreach (var chapter in chapters)
  94. {
  95. if (chapter.StartPositionTicks >= runtimeTicks)
  96. {
  97. _logger.Info("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, StringComparer.OrdinalIgnoreCase))
  102. {
  103. if (extractImages)
  104. {
  105. if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso)
  106. {
  107. continue;
  108. }
  109. if (video.VideoType == VideoType.BluRay || video.VideoType == VideoType.Dvd)
  110. {
  111. if (video.PlayableStreamFileNames.Count != 1)
  112. {
  113. continue;
  114. }
  115. }
  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, video.PlayableStreamFileNames);
  122. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  123. var container = video.Container;
  124. var tempFile = await _encoder.ExtractVideoImage(inputPath, container, protocol, 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.ErrorException("Error extracting chapter images for {0}", ex, 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. await _chapterManager.SaveChapters(video.Id.ToString(), chapters, cancellationToken).ConfigureAwait(false);
  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 List<string> GetSavedChapterImages(Video video)
  170. {
  171. var path = GetChapterImagesPath(video);
  172. try
  173. {
  174. return _fileSystem.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.Debug("Deleting dead chapter image {0}", image);
  191. try
  192. {
  193. _fileSystem.DeleteFile(image);
  194. }
  195. catch (IOException ex)
  196. {
  197. _logger.ErrorException("Error deleting {0}.", ex, image);
  198. }
  199. }
  200. }
  201. }
  202. }