AttachmentExtractor.cs 20 KB

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