VideoImageProvider.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.MediaEncoding;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Model.Drawing;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.MediaInfo;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using CommonIO;
  18. namespace MediaBrowser.Providers.MediaInfo
  19. {
  20. public class VideoImageProvider : IDynamicImageProvider, IHasItemChangeMonitor, IHasOrder
  21. {
  22. private readonly IIsoManager _isoManager;
  23. private readonly IMediaEncoder _mediaEncoder;
  24. private readonly IServerConfigurationManager _config;
  25. private readonly ILibraryManager _libraryManager;
  26. private readonly ILogger _logger;
  27. private readonly IFileSystem _fileSystem;
  28. public VideoImageProvider(IIsoManager isoManager, IMediaEncoder mediaEncoder, IServerConfigurationManager config, ILibraryManager libraryManager, ILogger logger, IFileSystem fileSystem)
  29. {
  30. _isoManager = isoManager;
  31. _mediaEncoder = mediaEncoder;
  32. _config = config;
  33. _libraryManager = libraryManager;
  34. _logger = logger;
  35. _fileSystem = fileSystem;
  36. }
  37. /// <summary>
  38. /// The null mount task result
  39. /// </summary>
  40. protected readonly Task<IIsoMount> NullMountTaskResult = Task.FromResult<IIsoMount>(null);
  41. /// <summary>
  42. /// Mounts the iso if needed.
  43. /// </summary>
  44. /// <param name="item">The item.</param>
  45. /// <param name="cancellationToken">The cancellation token.</param>
  46. /// <returns>Task{IIsoMount}.</returns>
  47. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  48. {
  49. if (item.VideoType == VideoType.Iso)
  50. {
  51. return _isoManager.Mount(item.Path, cancellationToken);
  52. }
  53. return NullMountTaskResult;
  54. }
  55. public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
  56. {
  57. return new List<ImageType> { ImageType.Primary };
  58. }
  59. public Task<DynamicImageResponse> GetImage(IHasImages item, ImageType type, CancellationToken cancellationToken)
  60. {
  61. var video = (Video)item;
  62. // No support for this
  63. if (video.VideoType == VideoType.HdDvd || video.IsPlaceHolder)
  64. {
  65. return Task.FromResult(new DynamicImageResponse { HasImage = false });
  66. }
  67. // Can't extract from iso's if we weren't unable to determine iso type
  68. if (video.VideoType == VideoType.Iso && !video.IsoType.HasValue)
  69. {
  70. return Task.FromResult(new DynamicImageResponse { HasImage = false });
  71. }
  72. // Can't extract if we didn't find a video stream in the file
  73. if (!video.DefaultVideoStreamIndex.HasValue)
  74. {
  75. _logger.Info("Skipping image extraction due to missing DefaultVideoStreamIndex for {0}.", video.Path ?? string.Empty);
  76. return Task.FromResult(new DynamicImageResponse { HasImage = false });
  77. }
  78. return GetVideoImage(video, cancellationToken);
  79. }
  80. public async Task<DynamicImageResponse> GetVideoImage(Video item, CancellationToken cancellationToken)
  81. {
  82. var isoMount = await MountIsoIfNeeded(item, cancellationToken).ConfigureAwait(false);
  83. try
  84. {
  85. var protocol = item.LocationType == LocationType.Remote
  86. ? MediaProtocol.Http
  87. : MediaProtocol.File;
  88. var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, item.Path, protocol, isoMount, item.PlayableStreamFileNames);
  89. var mediaStreams =
  90. item.GetMediaSources(false)
  91. .Take(1)
  92. .SelectMany(i => i.MediaStreams)
  93. .ToList();
  94. var imageStreams =
  95. mediaStreams
  96. .Where(i => i.Type == MediaStreamType.EmbeddedImage)
  97. .ToList();
  98. var imageStream = imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("front", StringComparison.OrdinalIgnoreCase) != -1) ??
  99. imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("cover", StringComparison.OrdinalIgnoreCase) != -1) ??
  100. imageStreams.FirstOrDefault();
  101. string extractedImagePath;
  102. if (imageStream != null)
  103. {
  104. // Instead of using the raw stream index, we need to use nth video/embedded image stream
  105. var videoIndex = -1;
  106. foreach (var mediaStream in mediaStreams)
  107. {
  108. if (mediaStream.Type == MediaStreamType.Video ||
  109. mediaStream.Type == MediaStreamType.EmbeddedImage)
  110. {
  111. videoIndex++;
  112. }
  113. if (mediaStream == imageStream)
  114. {
  115. break;
  116. }
  117. }
  118. extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, protocol, videoIndex, cancellationToken).ConfigureAwait(false);
  119. }
  120. else
  121. {
  122. // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in.
  123. // Always use 10 seconds for dvd because our duration could be out of whack
  124. var imageOffset = item.VideoType != VideoType.Dvd && item.RunTimeTicks.HasValue &&
  125. item.RunTimeTicks.Value > 0
  126. ? TimeSpan.FromTicks(Convert.ToInt64(item.RunTimeTicks.Value * .1))
  127. : TimeSpan.FromSeconds(10);
  128. extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, protocol, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false);
  129. }
  130. return new DynamicImageResponse
  131. {
  132. Format = ImageFormat.Jpg,
  133. HasImage = true,
  134. Path = extractedImagePath,
  135. Protocol = MediaProtocol.File
  136. };
  137. }
  138. finally
  139. {
  140. if (isoMount != null)
  141. {
  142. isoMount.Dispose();
  143. }
  144. }
  145. }
  146. public string Name
  147. {
  148. get { return "Screen Grabber"; }
  149. }
  150. public bool Supports(IHasImages item)
  151. {
  152. var video = item as Video;
  153. if (item.LocationType == LocationType.FileSystem && video != null && !video.IsPlaceHolder &&
  154. !video.IsShortcut && !video.IsArchive)
  155. {
  156. return true;
  157. }
  158. return false;
  159. }
  160. public int Order
  161. {
  162. get
  163. {
  164. // Make sure this comes after internet image providers
  165. return 100;
  166. }
  167. }
  168. public bool HasChanged(IHasMetadata item, IDirectoryService directoryService)
  169. {
  170. var file = directoryService.GetFile(item.Path);
  171. if (file != null && file.LastWriteTimeUtc != item.DateModified)
  172. {
  173. return true;
  174. }
  175. return false;
  176. }
  177. }
  178. }