2
0

AttachmentExtractor.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. var directory = Directory.CreateDirectory(outputFolder);
  123. var fileNames = directory.GetFiles("*", SearchOption.TopDirectoryOnly).Select(f => f.Name).ToHashSet();
  124. var missingFiles = mediaSource.MediaAttachments.Where(a => a.FileName is not null && !fileNames.Contains(a.FileName) && !string.Equals(a.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase));
  125. if (!missingFiles.Any())
  126. {
  127. // Skip extraction if all files already exist
  128. return;
  129. }
  130. var processArgs = string.Format(
  131. CultureInfo.InvariantCulture,
  132. "-dump_attachment:t \"\" -y {0} -i {1} -t 0 -f null null",
  133. inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty,
  134. inputPath);
  135. int exitCode;
  136. using (var process = new Process
  137. {
  138. StartInfo = new ProcessStartInfo
  139. {
  140. Arguments = processArgs,
  141. FileName = _mediaEncoder.EncoderPath,
  142. UseShellExecute = false,
  143. CreateNoWindow = true,
  144. WindowStyle = ProcessWindowStyle.Hidden,
  145. WorkingDirectory = outputFolder,
  146. ErrorDialog = false
  147. },
  148. EnableRaisingEvents = true
  149. })
  150. {
  151. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  152. process.Start();
  153. try
  154. {
  155. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  156. exitCode = process.ExitCode;
  157. }
  158. catch (OperationCanceledException)
  159. {
  160. process.Kill(true);
  161. exitCode = -1;
  162. }
  163. }
  164. var failed = false;
  165. if (exitCode != 0)
  166. {
  167. if (isExternal && exitCode == 1)
  168. {
  169. // ffmpeg returns exitCode 1 because there is no video or audio stream
  170. // this can be ignored
  171. }
  172. else
  173. {
  174. failed = true;
  175. _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputFolder, exitCode);
  176. try
  177. {
  178. Directory.Delete(outputFolder);
  179. }
  180. catch (IOException ex)
  181. {
  182. _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputFolder);
  183. }
  184. }
  185. }
  186. else if (!Directory.Exists(outputFolder))
  187. {
  188. failed = true;
  189. }
  190. if (failed)
  191. {
  192. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputFolder);
  193. throw new InvalidOperationException(
  194. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputFolder));
  195. }
  196. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputFolder);
  197. }
  198. }
  199. private async Task<Stream> GetAttachmentStream(
  200. MediaSourceInfo mediaSource,
  201. MediaAttachment mediaAttachment,
  202. CancellationToken cancellationToken)
  203. {
  204. var attachmentPath = await ExtractAttachment(mediaSource.Path, mediaSource, mediaAttachment, cancellationToken)
  205. .ConfigureAwait(false);
  206. return AsyncFile.OpenRead(attachmentPath);
  207. }
  208. private async Task<string> ExtractAttachment(
  209. string inputFile,
  210. MediaSourceInfo mediaSource,
  211. MediaAttachment mediaAttachment,
  212. CancellationToken cancellationToken)
  213. {
  214. var attachmentFolderPath = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
  215. using (await _semaphoreLocks.LockAsync(attachmentFolderPath, cancellationToken).ConfigureAwait(false))
  216. {
  217. var attachmentPath = _pathManager.GetAttachmentPath(mediaSource.Id, mediaAttachment.FileName ?? mediaAttachment.Index.ToString(CultureInfo.InvariantCulture));
  218. if (!File.Exists(attachmentPath))
  219. {
  220. await ExtractAttachmentInternal(
  221. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  222. mediaAttachment.Index,
  223. attachmentPath,
  224. cancellationToken).ConfigureAwait(false);
  225. }
  226. return attachmentPath;
  227. }
  228. }
  229. private async Task ExtractAttachmentInternal(
  230. string inputPath,
  231. int attachmentStreamIndex,
  232. string outputPath,
  233. CancellationToken cancellationToken)
  234. {
  235. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  236. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  237. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputPath)));
  238. var processArgs = string.Format(
  239. CultureInfo.InvariantCulture,
  240. "-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
  241. inputPath,
  242. attachmentStreamIndex,
  243. EncodingUtils.NormalizePath(outputPath));
  244. int exitCode;
  245. using (var process = new Process
  246. {
  247. StartInfo = new ProcessStartInfo
  248. {
  249. Arguments = processArgs,
  250. FileName = _mediaEncoder.EncoderPath,
  251. UseShellExecute = false,
  252. CreateNoWindow = true,
  253. WindowStyle = ProcessWindowStyle.Hidden,
  254. ErrorDialog = false
  255. },
  256. EnableRaisingEvents = true
  257. })
  258. {
  259. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  260. process.Start();
  261. try
  262. {
  263. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  264. exitCode = process.ExitCode;
  265. }
  266. catch (OperationCanceledException)
  267. {
  268. process.Kill(true);
  269. exitCode = -1;
  270. }
  271. }
  272. var failed = false;
  273. if (exitCode != 0)
  274. {
  275. failed = true;
  276. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  277. try
  278. {
  279. if (File.Exists(outputPath))
  280. {
  281. _fileSystem.DeleteFile(outputPath);
  282. }
  283. }
  284. catch (IOException ex)
  285. {
  286. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  287. }
  288. }
  289. else if (!File.Exists(outputPath))
  290. {
  291. failed = true;
  292. }
  293. if (failed)
  294. {
  295. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  296. throw new InvalidOperationException(
  297. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  298. }
  299. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  300. }
  301. /// <inheritdoc />
  302. public void Dispose()
  303. {
  304. _semaphoreLocks.Dispose();
  305. }
  306. }
  307. }