AttachmentExtractor.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. using System;
  2. using System.Diagnostics;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using AsyncKeyedLock;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.IO;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.MediaEncoding;
  14. using MediaBrowser.MediaEncoding.Encoder;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.IO;
  18. using Microsoft.Extensions.Logging;
  19. namespace MediaBrowser.MediaEncoding.Attachments
  20. {
  21. /// <inheritdoc cref="IAttachmentExtractor"/>
  22. public sealed class AttachmentExtractor : IAttachmentExtractor, IDisposable
  23. {
  24. private readonly ILogger<AttachmentExtractor> _logger;
  25. private readonly IFileSystem _fileSystem;
  26. private readonly IMediaEncoder _mediaEncoder;
  27. private readonly IMediaSourceManager _mediaSourceManager;
  28. private readonly IPathManager _pathManager;
  29. private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o =>
  30. {
  31. o.PoolSize = 20;
  32. o.PoolInitialFill = 1;
  33. });
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="AttachmentExtractor"/> class.
  36. /// </summary>
  37. /// <param name="logger">The <see cref="ILogger{AttachmentExtractor}"/>.</param>
  38. /// <param name="fileSystem">The <see cref="IFileSystem"/>.</param>
  39. /// <param name="mediaEncoder">The <see cref="IMediaEncoder"/>.</param>
  40. /// <param name="mediaSourceManager">The <see cref="IMediaSourceManager"/>.</param>
  41. /// <param name="pathManager">The <see cref="IPathManager"/>.</param>
  42. public AttachmentExtractor(
  43. ILogger<AttachmentExtractor> logger,
  44. IFileSystem fileSystem,
  45. IMediaEncoder mediaEncoder,
  46. IMediaSourceManager mediaSourceManager,
  47. IPathManager pathManager)
  48. {
  49. _logger = logger;
  50. _fileSystem = fileSystem;
  51. _mediaEncoder = mediaEncoder;
  52. _mediaSourceManager = mediaSourceManager;
  53. _pathManager = pathManager;
  54. }
  55. /// <inheritdoc />
  56. public async Task<(MediaAttachment Attachment, Stream Stream)> GetAttachment(BaseItem item, string mediaSourceId, int attachmentStreamIndex, CancellationToken cancellationToken)
  57. {
  58. ArgumentNullException.ThrowIfNull(item);
  59. if (string.IsNullOrWhiteSpace(mediaSourceId))
  60. {
  61. throw new ArgumentNullException(nameof(mediaSourceId));
  62. }
  63. var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
  64. var mediaSource = mediaSources
  65. .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  66. if (mediaSource is null)
  67. {
  68. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} not found");
  69. }
  70. var mediaAttachment = mediaSource.MediaAttachments
  71. .FirstOrDefault(i => i.Index == attachmentStreamIndex);
  72. if (mediaAttachment is null)
  73. {
  74. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {attachmentStreamIndex}");
  75. }
  76. if (string.Equals(mediaAttachment.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  77. {
  78. throw new ResourceNotFoundException($"Attachment with stream index {attachmentStreamIndex} can't be extracted for MediaSource {mediaSourceId}");
  79. }
  80. var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
  81. .ConfigureAwait(false);
  82. return (mediaAttachment, attachmentStream);
  83. }
  84. /// <inheritdoc />
  85. public async Task ExtractAllAttachments(
  86. string inputFile,
  87. MediaSourceInfo mediaSource,
  88. CancellationToken cancellationToken)
  89. {
  90. var shouldExtractOneByOne = mediaSource.MediaAttachments.Any(a => !string.IsNullOrEmpty(a.FileName)
  91. && (a.FileName.Contains('/', StringComparison.OrdinalIgnoreCase) || a.FileName.Contains('\\', StringComparison.OrdinalIgnoreCase)));
  92. if (shouldExtractOneByOne && !inputFile.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  93. {
  94. foreach (var attachment in mediaSource.MediaAttachments)
  95. {
  96. if (!string.Equals(attachment.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  97. {
  98. await ExtractAttachment(inputFile, mediaSource, attachment, cancellationToken).ConfigureAwait(false);
  99. }
  100. }
  101. }
  102. else
  103. {
  104. await ExtractAllAttachmentsInternal(
  105. inputFile,
  106. mediaSource,
  107. false,
  108. cancellationToken).ConfigureAwait(false);
  109. }
  110. }
  111. private async Task ExtractAllAttachmentsInternal(
  112. string inputFile,
  113. MediaSourceInfo mediaSource,
  114. bool isExternal,
  115. CancellationToken cancellationToken)
  116. {
  117. var inputPath = _mediaEncoder.GetInputArgument(inputFile, mediaSource);
  118. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  119. var outputFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
  120. using (await _semaphoreLocks.LockAsync(outputFolder, cancellationToken).ConfigureAwait(false))
  121. {
  122. if (!Directory.Exists(outputFolder))
  123. {
  124. Directory.CreateDirectory(outputFolder);
  125. }
  126. else
  127. {
  128. var fileNames = Directory.GetFiles(outputFolder, "*", SearchOption.TopDirectoryOnly).Select(f => Path.GetFileName(f));
  129. var missingFiles = mediaSource.MediaAttachments.Where(a => !fileNames.Contains(a.FileName) && !string.Equals(a.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase));
  130. if (!missingFiles.Any())
  131. {
  132. // Skip extraction if all files already exist
  133. return;
  134. }
  135. }
  136. var processArgs = string.Format(
  137. CultureInfo.InvariantCulture,
  138. "-dump_attachment:t \"\" -y {0} -i {1} -t 0 -f null null",
  139. inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty,
  140. inputPath);
  141. int exitCode;
  142. using (var process = new Process
  143. {
  144. StartInfo = new ProcessStartInfo
  145. {
  146. Arguments = processArgs,
  147. FileName = _mediaEncoder.EncoderPath,
  148. UseShellExecute = false,
  149. CreateNoWindow = true,
  150. WindowStyle = ProcessWindowStyle.Hidden,
  151. WorkingDirectory = outputFolder,
  152. ErrorDialog = false
  153. },
  154. EnableRaisingEvents = true
  155. })
  156. {
  157. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  158. process.Start();
  159. try
  160. {
  161. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  162. exitCode = process.ExitCode;
  163. }
  164. catch (OperationCanceledException)
  165. {
  166. process.Kill(true);
  167. exitCode = -1;
  168. }
  169. }
  170. var failed = false;
  171. if (exitCode != 0)
  172. {
  173. if (isExternal && exitCode == 1)
  174. {
  175. // ffmpeg returns exitCode 1 because there is no video or audio stream
  176. // this can be ignored
  177. }
  178. else
  179. {
  180. failed = true;
  181. _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputFolder, exitCode);
  182. try
  183. {
  184. Directory.Delete(outputFolder);
  185. }
  186. catch (IOException ex)
  187. {
  188. _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputFolder);
  189. }
  190. }
  191. }
  192. else if (!Directory.Exists(outputFolder))
  193. {
  194. failed = true;
  195. }
  196. if (failed)
  197. {
  198. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputFolder);
  199. throw new InvalidOperationException(
  200. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputFolder));
  201. }
  202. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputFolder);
  203. }
  204. }
  205. private async Task<Stream> GetAttachmentStream(
  206. MediaSourceInfo mediaSource,
  207. MediaAttachment mediaAttachment,
  208. CancellationToken cancellationToken)
  209. {
  210. var attachmentPath = await ExtractAttachment(mediaSource.Path, mediaSource, mediaAttachment, cancellationToken)
  211. .ConfigureAwait(false);
  212. return AsyncFile.OpenRead(attachmentPath);
  213. }
  214. private async Task<string> ExtractAttachment(
  215. string inputFile,
  216. MediaSourceInfo mediaSource,
  217. MediaAttachment mediaAttachment,
  218. CancellationToken cancellationToken)
  219. {
  220. var attachmentFolderPath = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
  221. using (await _semaphoreLocks.LockAsync(attachmentFolderPath, cancellationToken).ConfigureAwait(false))
  222. {
  223. var attachmentPath = _pathManager.GetAttachmentPath(mediaSource.Id, mediaAttachment.FileName ?? mediaAttachment.Index.ToString(CultureInfo.InvariantCulture));
  224. if (!File.Exists(attachmentPath))
  225. {
  226. await ExtractAttachmentInternal(
  227. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  228. mediaAttachment.Index,
  229. attachmentPath,
  230. cancellationToken).ConfigureAwait(false);
  231. }
  232. return attachmentPath;
  233. }
  234. }
  235. private async Task ExtractAttachmentInternal(
  236. string inputPath,
  237. int attachmentStreamIndex,
  238. string outputPath,
  239. CancellationToken cancellationToken)
  240. {
  241. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  242. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  243. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputPath)));
  244. var processArgs = string.Format(
  245. CultureInfo.InvariantCulture,
  246. "-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
  247. inputPath,
  248. attachmentStreamIndex,
  249. EncodingUtils.NormalizePath(outputPath));
  250. int exitCode;
  251. using (var process = new Process
  252. {
  253. StartInfo = new ProcessStartInfo
  254. {
  255. Arguments = processArgs,
  256. FileName = _mediaEncoder.EncoderPath,
  257. UseShellExecute = false,
  258. CreateNoWindow = true,
  259. WindowStyle = ProcessWindowStyle.Hidden,
  260. ErrorDialog = false
  261. },
  262. EnableRaisingEvents = true
  263. })
  264. {
  265. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  266. process.Start();
  267. try
  268. {
  269. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  270. exitCode = process.ExitCode;
  271. }
  272. catch (OperationCanceledException)
  273. {
  274. process.Kill(true);
  275. exitCode = -1;
  276. }
  277. }
  278. var failed = false;
  279. if (exitCode != 0)
  280. {
  281. failed = true;
  282. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  283. try
  284. {
  285. if (File.Exists(outputPath))
  286. {
  287. _fileSystem.DeleteFile(outputPath);
  288. }
  289. }
  290. catch (IOException ex)
  291. {
  292. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  293. }
  294. }
  295. else if (!File.Exists(outputPath))
  296. {
  297. failed = true;
  298. }
  299. if (failed)
  300. {
  301. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  302. throw new InvalidOperationException(
  303. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  304. }
  305. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  306. }
  307. /// <inheritdoc />
  308. public void Dispose()
  309. {
  310. _semaphoreLocks.Dispose();
  311. }
  312. }
  313. }