AttachmentExtractor.cs 19 KB

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