AttachmentExtractor.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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<AsyncKeyedLockReleaser<string>>();
  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 @outputFileLock = _semaphoreLocks.GetOrAdd(outputPath);
  227. await @outputFileLock.SemaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false);
  228. if (File.Exists(outputPath))
  229. {
  230. @outputFileLock.Dispose();
  231. continue;
  232. }
  233. outputFileLocks.Add(@outputFileLock);
  234. extractableAttachmentIds.Add(attachment.Index);
  235. }
  236. if (extractableAttachmentIds.Count > 0)
  237. {
  238. await CacheAllAttachmentsInternal(mediaPath, inputFile, mediaSource, extractableAttachmentIds, cancellationToken).ConfigureAwait(false);
  239. }
  240. }
  241. catch (Exception ex)
  242. {
  243. _logger.LogWarning(ex, "Unable to cache media attachments for File:{File}", mediaPath);
  244. }
  245. finally
  246. {
  247. foreach (var @outputFileLock in outputFileLocks)
  248. {
  249. @outputFileLock.Dispose();
  250. }
  251. }
  252. }
  253. private async Task CacheAllAttachmentsInternal(
  254. string mediaPath,
  255. string inputFile,
  256. MediaSourceInfo mediaSource,
  257. List<int> extractableAttachmentIds,
  258. CancellationToken cancellationToken)
  259. {
  260. var outputPaths = new List<string>();
  261. var processArgs = string.Empty;
  262. foreach (var attachmentId in extractableAttachmentIds)
  263. {
  264. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachmentId);
  265. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
  266. outputPaths.Add(outputPath);
  267. processArgs += string.Format(
  268. CultureInfo.InvariantCulture,
  269. " -dump_attachment:{0} \"{1}\"",
  270. attachmentId,
  271. EncodingUtils.NormalizePath(outputPath));
  272. }
  273. processArgs += string.Format(
  274. CultureInfo.InvariantCulture,
  275. " -i \"{0}\" -t 0 -f null null",
  276. inputFile);
  277. int exitCode;
  278. using (var process = new Process
  279. {
  280. StartInfo = new ProcessStartInfo
  281. {
  282. Arguments = processArgs,
  283. FileName = _mediaEncoder.EncoderPath,
  284. UseShellExecute = false,
  285. CreateNoWindow = true,
  286. WindowStyle = ProcessWindowStyle.Hidden,
  287. ErrorDialog = false
  288. },
  289. EnableRaisingEvents = true
  290. })
  291. {
  292. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  293. process.Start();
  294. try
  295. {
  296. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  297. exitCode = process.ExitCode;
  298. }
  299. catch (OperationCanceledException)
  300. {
  301. process.Kill(true);
  302. exitCode = -1;
  303. }
  304. }
  305. var failed = false;
  306. if (exitCode == -1)
  307. {
  308. failed = true;
  309. foreach (var outputPath in outputPaths)
  310. {
  311. try
  312. {
  313. _logger.LogWarning("Deleting extracted media attachment due to failure: {Path}", outputPath);
  314. _fileSystem.DeleteFile(outputPath);
  315. }
  316. catch (FileNotFoundException)
  317. {
  318. // ffmpeg failed, so it is normal that one or more expected output files do not exist.
  319. // There is no need to log anything for the user here.
  320. }
  321. catch (IOException ex)
  322. {
  323. _logger.LogError(ex, "Error deleting extracted media attachment {Path}", outputPath);
  324. }
  325. }
  326. }
  327. else
  328. {
  329. foreach (var outputPath in outputPaths)
  330. {
  331. if (!File.Exists(outputPath))
  332. {
  333. _logger.LogError("ffmpeg media attachment extraction failed for {InputPath} to {OutputPath}", inputFile, outputPath);
  334. failed = true;
  335. continue;
  336. }
  337. _logger.LogInformation("ffmpeg media attachment extraction completed for {InputPath} to {OutputPath}", inputFile, outputPath);
  338. }
  339. }
  340. if (failed)
  341. {
  342. throw new FfmpegException(
  343. string.Format(CultureInfo.InvariantCulture, "ffmpeg media attachment extraction failed for {0}", inputFile));
  344. }
  345. }
  346. private async Task ExtractAttachment(
  347. string inputFile,
  348. MediaSourceInfo mediaSource,
  349. int attachmentStreamIndex,
  350. string outputPath,
  351. CancellationToken cancellationToken)
  352. {
  353. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  354. {
  355. if (!File.Exists(outputPath))
  356. {
  357. await ExtractAttachmentInternal(
  358. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  359. attachmentStreamIndex,
  360. outputPath,
  361. cancellationToken).ConfigureAwait(false);
  362. }
  363. }
  364. }
  365. private async Task ExtractAttachmentInternal(
  366. string inputPath,
  367. int attachmentStreamIndex,
  368. string outputPath,
  369. CancellationToken cancellationToken)
  370. {
  371. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  372. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  373. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputPath)));
  374. var processArgs = string.Format(
  375. CultureInfo.InvariantCulture,
  376. "-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
  377. inputPath,
  378. attachmentStreamIndex,
  379. EncodingUtils.NormalizePath(outputPath));
  380. int exitCode;
  381. using (var process = new Process
  382. {
  383. StartInfo = new ProcessStartInfo
  384. {
  385. Arguments = processArgs,
  386. FileName = _mediaEncoder.EncoderPath,
  387. UseShellExecute = false,
  388. CreateNoWindow = true,
  389. WindowStyle = ProcessWindowStyle.Hidden,
  390. ErrorDialog = false
  391. },
  392. EnableRaisingEvents = true
  393. })
  394. {
  395. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  396. process.Start();
  397. try
  398. {
  399. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  400. exitCode = process.ExitCode;
  401. }
  402. catch (OperationCanceledException)
  403. {
  404. process.Kill(true);
  405. exitCode = -1;
  406. }
  407. }
  408. var failed = false;
  409. if (exitCode != 0)
  410. {
  411. failed = true;
  412. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  413. try
  414. {
  415. if (File.Exists(outputPath))
  416. {
  417. _fileSystem.DeleteFile(outputPath);
  418. }
  419. }
  420. catch (IOException ex)
  421. {
  422. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  423. }
  424. }
  425. else if (!File.Exists(outputPath))
  426. {
  427. failed = true;
  428. }
  429. if (failed)
  430. {
  431. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  432. throw new InvalidOperationException(
  433. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  434. }
  435. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  436. }
  437. private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
  438. {
  439. string filename;
  440. if (mediaSource.Protocol == MediaProtocol.File)
  441. {
  442. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  443. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  444. }
  445. else
  446. {
  447. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  448. }
  449. var prefix = filename.AsSpan(0, 1);
  450. return Path.Join(_appPaths.DataPath, "attachments", prefix, filename);
  451. }
  452. /// <inheritdoc />
  453. public void Dispose()
  454. {
  455. _semaphoreLocks.Dispose();
  456. }
  457. }
  458. }