AttachmentExtractor.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using AsyncKeyedLock;
  11. using MediaBrowser.Common;
  12. using MediaBrowser.Common.Configuration;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Controller.Entities;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Controller.MediaEncoding;
  17. using MediaBrowser.MediaEncoding.Encoder;
  18. using MediaBrowser.Model.Dto;
  19. using MediaBrowser.Model.Entities;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.MediaInfo;
  22. using Microsoft.Extensions.Logging;
  23. namespace MediaBrowser.MediaEncoding.Attachments
  24. {
  25. public sealed class AttachmentExtractor : IAttachmentExtractor, IDisposable
  26. {
  27. private readonly ILogger<AttachmentExtractor> _logger;
  28. private readonly IApplicationPaths _appPaths;
  29. private readonly IFileSystem _fileSystem;
  30. private readonly IMediaEncoder _mediaEncoder;
  31. private readonly IMediaSourceManager _mediaSourceManager;
  32. private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o =>
  33. {
  34. o.PoolSize = 20;
  35. o.PoolInitialFill = 1;
  36. });
  37. public AttachmentExtractor(
  38. ILogger<AttachmentExtractor> logger,
  39. IApplicationPaths appPaths,
  40. IFileSystem fileSystem,
  41. IMediaEncoder mediaEncoder,
  42. IMediaSourceManager mediaSourceManager)
  43. {
  44. _logger = logger;
  45. _appPaths = appPaths;
  46. _fileSystem = fileSystem;
  47. _mediaEncoder = mediaEncoder;
  48. _mediaSourceManager = mediaSourceManager;
  49. }
  50. /// <inheritdoc />
  51. public async Task<(MediaAttachment Attachment, Stream Stream)> GetAttachment(BaseItem item, string mediaSourceId, int attachmentStreamIndex, CancellationToken cancellationToken)
  52. {
  53. ArgumentNullException.ThrowIfNull(item);
  54. if (string.IsNullOrWhiteSpace(mediaSourceId))
  55. {
  56. throw new ArgumentNullException(nameof(mediaSourceId));
  57. }
  58. var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
  59. var mediaSource = mediaSources
  60. .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  61. if (mediaSource is null)
  62. {
  63. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} not found");
  64. }
  65. var mediaAttachment = mediaSource.MediaAttachments
  66. .FirstOrDefault(i => i.Index == attachmentStreamIndex);
  67. if (mediaAttachment is null)
  68. {
  69. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {attachmentStreamIndex}");
  70. }
  71. var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
  72. .ConfigureAwait(false);
  73. return (mediaAttachment, attachmentStream);
  74. }
  75. public async Task ExtractAllAttachments(
  76. string inputFile,
  77. MediaSourceInfo mediaSource,
  78. string outputPath,
  79. CancellationToken cancellationToken)
  80. {
  81. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  82. {
  83. if (!Directory.Exists(outputPath))
  84. {
  85. await ExtractAllAttachmentsInternal(
  86. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  87. outputPath,
  88. false,
  89. cancellationToken).ConfigureAwait(false);
  90. }
  91. }
  92. }
  93. public async Task ExtractAllAttachmentsExternal(
  94. string inputArgument,
  95. string id,
  96. string outputPath,
  97. CancellationToken cancellationToken)
  98. {
  99. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  100. {
  101. if (!File.Exists(Path.Join(outputPath, id)))
  102. {
  103. await ExtractAllAttachmentsInternal(
  104. inputArgument,
  105. outputPath,
  106. true,
  107. cancellationToken).ConfigureAwait(false);
  108. if (Directory.Exists(outputPath))
  109. {
  110. File.Create(Path.Join(outputPath, id));
  111. }
  112. }
  113. }
  114. }
  115. private async Task ExtractAllAttachmentsInternal(
  116. string inputPath,
  117. string outputPath,
  118. bool isExternal,
  119. CancellationToken cancellationToken)
  120. {
  121. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  122. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  123. Directory.CreateDirectory(outputPath);
  124. var processArgs = string.Format(
  125. CultureInfo.InvariantCulture,
  126. "-dump_attachment:t \"\" -y {0} -i {1} -t 0 -f null null",
  127. inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty,
  128. inputPath);
  129. int exitCode;
  130. using (var process = new Process
  131. {
  132. StartInfo = new ProcessStartInfo
  133. {
  134. Arguments = processArgs,
  135. FileName = _mediaEncoder.EncoderPath,
  136. UseShellExecute = false,
  137. CreateNoWindow = true,
  138. WindowStyle = ProcessWindowStyle.Hidden,
  139. WorkingDirectory = outputPath,
  140. ErrorDialog = false
  141. },
  142. EnableRaisingEvents = true
  143. })
  144. {
  145. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  146. process.Start();
  147. try
  148. {
  149. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  150. exitCode = process.ExitCode;
  151. }
  152. catch (OperationCanceledException)
  153. {
  154. process.Kill(true);
  155. exitCode = -1;
  156. }
  157. }
  158. var failed = false;
  159. if (exitCode != 0)
  160. {
  161. if (isExternal && exitCode == 1)
  162. {
  163. // ffmpeg returns exitCode 1 because there is no video or audio stream
  164. // this can be ignored
  165. }
  166. else
  167. {
  168. failed = true;
  169. _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputPath, exitCode);
  170. try
  171. {
  172. Directory.Delete(outputPath);
  173. }
  174. catch (IOException ex)
  175. {
  176. _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputPath);
  177. }
  178. }
  179. }
  180. else if (!Directory.Exists(outputPath))
  181. {
  182. failed = true;
  183. }
  184. if (failed)
  185. {
  186. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  187. throw new InvalidOperationException(
  188. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  189. }
  190. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  191. }
  192. private async Task<Stream> GetAttachmentStream(
  193. MediaSourceInfo mediaSource,
  194. MediaAttachment mediaAttachment,
  195. CancellationToken cancellationToken)
  196. {
  197. var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
  198. return AsyncFile.OpenRead(attachmentPath);
  199. }
  200. private async Task<string> GetReadableFile(
  201. string mediaPath,
  202. string inputFile,
  203. MediaSourceInfo mediaSource,
  204. MediaAttachment mediaAttachment,
  205. CancellationToken cancellationToken)
  206. {
  207. await CacheAllAttachments(mediaPath, inputFile, mediaSource, cancellationToken).ConfigureAwait(false);
  208. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
  209. await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
  210. .ConfigureAwait(false);
  211. return outputPath;
  212. }
  213. private async Task CacheAllAttachments(
  214. string mediaPath,
  215. string inputFile,
  216. MediaSourceInfo mediaSource,
  217. CancellationToken cancellationToken)
  218. {
  219. var outputFileLocks = new List<IDisposable>();
  220. var extractableAttachmentIds = new List<int>();
  221. try
  222. {
  223. foreach (var attachment in mediaSource.MediaAttachments)
  224. {
  225. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachment.Index);
  226. var releaser = await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false);
  227. if (File.Exists(outputPath))
  228. {
  229. releaser.Dispose();
  230. continue;
  231. }
  232. outputFileLocks.Add(releaser);
  233. extractableAttachmentIds.Add(attachment.Index);
  234. }
  235. if (extractableAttachmentIds.Count > 0)
  236. {
  237. await CacheAllAttachmentsInternal(mediaPath, inputFile, mediaSource, extractableAttachmentIds, cancellationToken).ConfigureAwait(false);
  238. }
  239. }
  240. catch (Exception ex)
  241. {
  242. _logger.LogWarning(ex, "Unable to cache media attachments for File:{File}", mediaPath);
  243. }
  244. finally
  245. {
  246. outputFileLocks.ForEach(x => x.Dispose());
  247. }
  248. }
  249. private async Task CacheAllAttachmentsInternal(
  250. string mediaPath,
  251. string inputFile,
  252. MediaSourceInfo mediaSource,
  253. List<int> extractableAttachmentIds,
  254. CancellationToken cancellationToken)
  255. {
  256. var outputPaths = new List<string>();
  257. var processArgs = string.Empty;
  258. foreach (var attachmentId in extractableAttachmentIds)
  259. {
  260. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachmentId);
  261. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
  262. outputPaths.Add(outputPath);
  263. processArgs += string.Format(
  264. CultureInfo.InvariantCulture,
  265. " -dump_attachment:{0} \"{1}\"",
  266. attachmentId,
  267. EncodingUtils.NormalizePath(outputPath));
  268. }
  269. processArgs += string.Format(
  270. CultureInfo.InvariantCulture,
  271. " -i \"{0}\" -t 0 -f null null",
  272. inputFile);
  273. int exitCode;
  274. using (var process = new Process
  275. {
  276. StartInfo = new ProcessStartInfo
  277. {
  278. Arguments = processArgs,
  279. FileName = _mediaEncoder.EncoderPath,
  280. UseShellExecute = false,
  281. CreateNoWindow = true,
  282. WindowStyle = ProcessWindowStyle.Hidden,
  283. ErrorDialog = false
  284. },
  285. EnableRaisingEvents = true
  286. })
  287. {
  288. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  289. process.Start();
  290. try
  291. {
  292. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  293. exitCode = process.ExitCode;
  294. }
  295. catch (OperationCanceledException)
  296. {
  297. process.Kill(true);
  298. exitCode = -1;
  299. }
  300. }
  301. var failed = false;
  302. if (exitCode == -1)
  303. {
  304. failed = true;
  305. foreach (var outputPath in outputPaths)
  306. {
  307. try
  308. {
  309. _logger.LogWarning("Deleting extracted media attachment due to failure: {Path}", outputPath);
  310. _fileSystem.DeleteFile(outputPath);
  311. }
  312. catch (FileNotFoundException)
  313. {
  314. // ffmpeg failed, so it is normal that one or more expected output files do not exist.
  315. // There is no need to log anything for the user here.
  316. }
  317. catch (IOException ex)
  318. {
  319. _logger.LogError(ex, "Error deleting extracted media attachment {Path}", outputPath);
  320. }
  321. }
  322. }
  323. else
  324. {
  325. foreach (var outputPath in outputPaths)
  326. {
  327. if (!File.Exists(outputPath))
  328. {
  329. _logger.LogError("ffmpeg media attachment extraction failed for {InputPath} to {OutputPath}", inputFile, outputPath);
  330. failed = true;
  331. continue;
  332. }
  333. _logger.LogInformation("ffmpeg media attachment extraction completed for {InputPath} to {OutputPath}", inputFile, outputPath);
  334. }
  335. }
  336. if (failed)
  337. {
  338. throw new FfmpegException(
  339. string.Format(CultureInfo.InvariantCulture, "ffmpeg media attachment extraction failed for {0}", inputFile));
  340. }
  341. }
  342. private async Task ExtractAttachment(
  343. string inputFile,
  344. MediaSourceInfo mediaSource,
  345. int attachmentStreamIndex,
  346. string outputPath,
  347. CancellationToken cancellationToken)
  348. {
  349. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  350. {
  351. if (!File.Exists(outputPath))
  352. {
  353. await ExtractAttachmentInternal(
  354. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  355. attachmentStreamIndex,
  356. outputPath,
  357. cancellationToken).ConfigureAwait(false);
  358. }
  359. }
  360. }
  361. private async Task ExtractAttachmentInternal(
  362. string inputPath,
  363. int attachmentStreamIndex,
  364. string outputPath,
  365. CancellationToken cancellationToken)
  366. {
  367. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  368. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  369. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputPath)));
  370. var processArgs = string.Format(
  371. CultureInfo.InvariantCulture,
  372. "-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
  373. inputPath,
  374. attachmentStreamIndex,
  375. EncodingUtils.NormalizePath(outputPath));
  376. int exitCode;
  377. using (var process = new Process
  378. {
  379. StartInfo = new ProcessStartInfo
  380. {
  381. Arguments = processArgs,
  382. FileName = _mediaEncoder.EncoderPath,
  383. UseShellExecute = false,
  384. CreateNoWindow = true,
  385. WindowStyle = ProcessWindowStyle.Hidden,
  386. ErrorDialog = false
  387. },
  388. EnableRaisingEvents = true
  389. })
  390. {
  391. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  392. process.Start();
  393. try
  394. {
  395. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  396. exitCode = process.ExitCode;
  397. }
  398. catch (OperationCanceledException)
  399. {
  400. process.Kill(true);
  401. exitCode = -1;
  402. }
  403. }
  404. var failed = false;
  405. if (exitCode != 0)
  406. {
  407. failed = true;
  408. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  409. try
  410. {
  411. if (File.Exists(outputPath))
  412. {
  413. _fileSystem.DeleteFile(outputPath);
  414. }
  415. }
  416. catch (IOException ex)
  417. {
  418. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  419. }
  420. }
  421. else if (!File.Exists(outputPath))
  422. {
  423. failed = true;
  424. }
  425. if (failed)
  426. {
  427. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  428. throw new InvalidOperationException(
  429. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  430. }
  431. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  432. }
  433. private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
  434. {
  435. string filename;
  436. if (mediaSource.Protocol == MediaProtocol.File)
  437. {
  438. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  439. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  440. }
  441. else
  442. {
  443. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  444. }
  445. var prefix = filename.AsSpan(0, 1);
  446. return Path.Join(_appPaths.DataPath, "attachments", prefix, filename);
  447. }
  448. /// <inheritdoc />
  449. public void Dispose()
  450. {
  451. _semaphoreLocks.Dispose();
  452. }
  453. }
  454. }