AttachmentExtractor.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. var shouldExtractOneByOne = mediaSource.MediaAttachments.Any(a => a.FileName.Contains('/', StringComparison.OrdinalIgnoreCase) || a.FileName.Contains('\\', StringComparison.OrdinalIgnoreCase));
  82. if (shouldExtractOneByOne)
  83. {
  84. var attachmentIndexes = mediaSource.MediaAttachments.Select(a => a.Index);
  85. foreach (var i in attachmentIndexes)
  86. {
  87. var newName = Path.Join(outputPath, i.ToString(CultureInfo.InvariantCulture));
  88. await ExtractAttachment(inputFile, mediaSource, i, newName, cancellationToken).ConfigureAwait(false);
  89. }
  90. }
  91. else
  92. {
  93. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  94. {
  95. if (!Directory.Exists(outputPath))
  96. {
  97. await ExtractAllAttachmentsInternal(
  98. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  99. outputPath,
  100. false,
  101. cancellationToken).ConfigureAwait(false);
  102. }
  103. }
  104. }
  105. }
  106. public async Task ExtractAllAttachmentsExternal(
  107. string inputArgument,
  108. string id,
  109. string outputPath,
  110. CancellationToken cancellationToken)
  111. {
  112. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  113. {
  114. if (!File.Exists(Path.Join(outputPath, id)))
  115. {
  116. await ExtractAllAttachmentsInternal(
  117. inputArgument,
  118. outputPath,
  119. true,
  120. cancellationToken).ConfigureAwait(false);
  121. if (Directory.Exists(outputPath))
  122. {
  123. File.Create(Path.Join(outputPath, id));
  124. }
  125. }
  126. }
  127. }
  128. private async Task ExtractAllAttachmentsInternal(
  129. string inputPath,
  130. string outputPath,
  131. bool isExternal,
  132. CancellationToken cancellationToken)
  133. {
  134. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  135. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  136. Directory.CreateDirectory(outputPath);
  137. var processArgs = string.Format(
  138. CultureInfo.InvariantCulture,
  139. "-dump_attachment:t \"\" -y {0} -i {1} -t 0 -f null null",
  140. inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty,
  141. inputPath);
  142. int exitCode;
  143. using (var process = new Process
  144. {
  145. StartInfo = new ProcessStartInfo
  146. {
  147. Arguments = processArgs,
  148. FileName = _mediaEncoder.EncoderPath,
  149. UseShellExecute = false,
  150. CreateNoWindow = true,
  151. WindowStyle = ProcessWindowStyle.Hidden,
  152. WorkingDirectory = outputPath,
  153. ErrorDialog = false
  154. },
  155. EnableRaisingEvents = true
  156. })
  157. {
  158. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  159. process.Start();
  160. try
  161. {
  162. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  163. exitCode = process.ExitCode;
  164. }
  165. catch (OperationCanceledException)
  166. {
  167. process.Kill(true);
  168. exitCode = -1;
  169. }
  170. }
  171. var failed = false;
  172. if (exitCode != 0)
  173. {
  174. if (isExternal && exitCode == 1)
  175. {
  176. // ffmpeg returns exitCode 1 because there is no video or audio stream
  177. // this can be ignored
  178. }
  179. else
  180. {
  181. failed = true;
  182. _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputPath, exitCode);
  183. try
  184. {
  185. Directory.Delete(outputPath);
  186. }
  187. catch (IOException ex)
  188. {
  189. _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputPath);
  190. }
  191. }
  192. }
  193. else if (!Directory.Exists(outputPath))
  194. {
  195. failed = true;
  196. }
  197. if (failed)
  198. {
  199. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  200. throw new InvalidOperationException(
  201. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  202. }
  203. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  204. }
  205. private async Task<Stream> GetAttachmentStream(
  206. MediaSourceInfo mediaSource,
  207. MediaAttachment mediaAttachment,
  208. CancellationToken cancellationToken)
  209. {
  210. var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
  211. return AsyncFile.OpenRead(attachmentPath);
  212. }
  213. private async Task<string> GetReadableFile(
  214. string mediaPath,
  215. string inputFile,
  216. MediaSourceInfo mediaSource,
  217. MediaAttachment mediaAttachment,
  218. CancellationToken cancellationToken)
  219. {
  220. await CacheAllAttachments(mediaPath, inputFile, mediaSource, cancellationToken).ConfigureAwait(false);
  221. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
  222. await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
  223. .ConfigureAwait(false);
  224. return outputPath;
  225. }
  226. private async Task CacheAllAttachments(
  227. string mediaPath,
  228. string inputFile,
  229. MediaSourceInfo mediaSource,
  230. CancellationToken cancellationToken)
  231. {
  232. var outputFileLocks = new List<IDisposable>();
  233. var extractableAttachmentIds = new List<int>();
  234. try
  235. {
  236. foreach (var attachment in mediaSource.MediaAttachments)
  237. {
  238. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachment.Index);
  239. var releaser = await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false);
  240. if (File.Exists(outputPath))
  241. {
  242. releaser.Dispose();
  243. continue;
  244. }
  245. outputFileLocks.Add(releaser);
  246. extractableAttachmentIds.Add(attachment.Index);
  247. }
  248. if (extractableAttachmentIds.Count > 0)
  249. {
  250. await CacheAllAttachmentsInternal(mediaPath, inputFile, mediaSource, extractableAttachmentIds, cancellationToken).ConfigureAwait(false);
  251. }
  252. }
  253. catch (Exception ex)
  254. {
  255. _logger.LogWarning(ex, "Unable to cache media attachments for File:{File}", mediaPath);
  256. }
  257. finally
  258. {
  259. outputFileLocks.ForEach(x => x.Dispose());
  260. }
  261. }
  262. private async Task CacheAllAttachmentsInternal(
  263. string mediaPath,
  264. string inputFile,
  265. MediaSourceInfo mediaSource,
  266. List<int> extractableAttachmentIds,
  267. CancellationToken cancellationToken)
  268. {
  269. var outputPaths = new List<string>();
  270. var processArgs = string.Empty;
  271. foreach (var attachmentId in extractableAttachmentIds)
  272. {
  273. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachmentId);
  274. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
  275. outputPaths.Add(outputPath);
  276. processArgs += string.Format(
  277. CultureInfo.InvariantCulture,
  278. " -dump_attachment:{0} \"{1}\"",
  279. attachmentId,
  280. EncodingUtils.NormalizePath(outputPath));
  281. }
  282. processArgs += string.Format(
  283. CultureInfo.InvariantCulture,
  284. " -i \"{0}\" -t 0 -f null null",
  285. inputFile);
  286. int exitCode;
  287. using (var process = new Process
  288. {
  289. StartInfo = new ProcessStartInfo
  290. {
  291. Arguments = processArgs,
  292. FileName = _mediaEncoder.EncoderPath,
  293. UseShellExecute = false,
  294. CreateNoWindow = true,
  295. WindowStyle = ProcessWindowStyle.Hidden,
  296. ErrorDialog = false
  297. },
  298. EnableRaisingEvents = true
  299. })
  300. {
  301. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  302. process.Start();
  303. try
  304. {
  305. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  306. exitCode = process.ExitCode;
  307. }
  308. catch (OperationCanceledException)
  309. {
  310. process.Kill(true);
  311. exitCode = -1;
  312. }
  313. }
  314. var failed = false;
  315. if (exitCode == -1)
  316. {
  317. failed = true;
  318. foreach (var outputPath in outputPaths)
  319. {
  320. try
  321. {
  322. _logger.LogWarning("Deleting extracted media attachment due to failure: {Path}", outputPath);
  323. _fileSystem.DeleteFile(outputPath);
  324. }
  325. catch (FileNotFoundException)
  326. {
  327. // ffmpeg failed, so it is normal that one or more expected output files do not exist.
  328. // There is no need to log anything for the user here.
  329. }
  330. catch (IOException ex)
  331. {
  332. _logger.LogError(ex, "Error deleting extracted media attachment {Path}", outputPath);
  333. }
  334. }
  335. }
  336. else
  337. {
  338. foreach (var outputPath in outputPaths)
  339. {
  340. if (!File.Exists(outputPath))
  341. {
  342. _logger.LogError("ffmpeg media attachment extraction failed for {InputPath} to {OutputPath}", inputFile, outputPath);
  343. failed = true;
  344. continue;
  345. }
  346. _logger.LogInformation("ffmpeg media attachment extraction completed for {InputPath} to {OutputPath}", inputFile, outputPath);
  347. }
  348. }
  349. if (failed)
  350. {
  351. throw new FfmpegException(
  352. string.Format(CultureInfo.InvariantCulture, "ffmpeg media attachment extraction failed for {0}", inputFile));
  353. }
  354. }
  355. private async Task ExtractAttachment(
  356. string inputFile,
  357. MediaSourceInfo mediaSource,
  358. int attachmentStreamIndex,
  359. string outputPath,
  360. CancellationToken cancellationToken)
  361. {
  362. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  363. {
  364. if (!File.Exists(outputPath))
  365. {
  366. await ExtractAttachmentInternal(
  367. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  368. attachmentStreamIndex,
  369. outputPath,
  370. cancellationToken).ConfigureAwait(false);
  371. }
  372. }
  373. }
  374. private async Task ExtractAttachmentInternal(
  375. string inputPath,
  376. int attachmentStreamIndex,
  377. string outputPath,
  378. CancellationToken cancellationToken)
  379. {
  380. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  381. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  382. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputPath)));
  383. var processArgs = string.Format(
  384. CultureInfo.InvariantCulture,
  385. "-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
  386. inputPath,
  387. attachmentStreamIndex,
  388. EncodingUtils.NormalizePath(outputPath));
  389. int exitCode;
  390. using (var process = new Process
  391. {
  392. StartInfo = new ProcessStartInfo
  393. {
  394. Arguments = processArgs,
  395. FileName = _mediaEncoder.EncoderPath,
  396. UseShellExecute = false,
  397. CreateNoWindow = true,
  398. WindowStyle = ProcessWindowStyle.Hidden,
  399. ErrorDialog = false
  400. },
  401. EnableRaisingEvents = true
  402. })
  403. {
  404. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  405. process.Start();
  406. try
  407. {
  408. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  409. exitCode = process.ExitCode;
  410. }
  411. catch (OperationCanceledException)
  412. {
  413. process.Kill(true);
  414. exitCode = -1;
  415. }
  416. }
  417. var failed = false;
  418. if (exitCode != 0)
  419. {
  420. failed = true;
  421. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  422. try
  423. {
  424. if (File.Exists(outputPath))
  425. {
  426. _fileSystem.DeleteFile(outputPath);
  427. }
  428. }
  429. catch (IOException ex)
  430. {
  431. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  432. }
  433. }
  434. else if (!File.Exists(outputPath))
  435. {
  436. failed = true;
  437. }
  438. if (failed)
  439. {
  440. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  441. throw new InvalidOperationException(
  442. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  443. }
  444. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  445. }
  446. private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
  447. {
  448. string filename;
  449. if (mediaSource.Protocol == MediaProtocol.File)
  450. {
  451. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  452. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  453. }
  454. else
  455. {
  456. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  457. }
  458. var prefix = filename.AsSpan(0, 1);
  459. return Path.Join(_appPaths.DataPath, "attachments", prefix, filename);
  460. }
  461. /// <inheritdoc />
  462. public void Dispose()
  463. {
  464. _semaphoreLocks.Dispose();
  465. }
  466. }
  467. }