AttachmentExtractor.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  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.Configuration;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.MediaEncoding;
  16. using MediaBrowser.MediaEncoding.Encoder;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.IO;
  20. using MediaBrowser.Model.MediaInfo;
  21. using Microsoft.Extensions.Logging;
  22. namespace MediaBrowser.MediaEncoding.Attachments
  23. {
  24. public sealed class AttachmentExtractor : IAttachmentExtractor, IDisposable
  25. {
  26. private readonly ILogger<AttachmentExtractor> _logger;
  27. private readonly IApplicationPaths _appPaths;
  28. private readonly IFileSystem _fileSystem;
  29. private readonly IMediaEncoder _mediaEncoder;
  30. private readonly IMediaSourceManager _mediaSourceManager;
  31. private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o =>
  32. {
  33. o.PoolSize = 20;
  34. o.PoolInitialFill = 1;
  35. });
  36. public AttachmentExtractor(
  37. ILogger<AttachmentExtractor> logger,
  38. IApplicationPaths appPaths,
  39. IFileSystem fileSystem,
  40. IMediaEncoder mediaEncoder,
  41. IMediaSourceManager mediaSourceManager)
  42. {
  43. _logger = logger;
  44. _appPaths = appPaths;
  45. _fileSystem = fileSystem;
  46. _mediaEncoder = mediaEncoder;
  47. _mediaSourceManager = mediaSourceManager;
  48. }
  49. /// <inheritdoc />
  50. public async Task<(MediaAttachment Attachment, Stream Stream)> GetAttachment(BaseItem item, string mediaSourceId, int attachmentStreamIndex, CancellationToken cancellationToken)
  51. {
  52. ArgumentNullException.ThrowIfNull(item);
  53. if (string.IsNullOrWhiteSpace(mediaSourceId))
  54. {
  55. throw new ArgumentNullException(nameof(mediaSourceId));
  56. }
  57. var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
  58. var mediaSource = mediaSources
  59. .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  60. if (mediaSource is null)
  61. {
  62. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} not found");
  63. }
  64. var mediaAttachment = mediaSource.MediaAttachments
  65. .FirstOrDefault(i => i.Index == attachmentStreamIndex);
  66. if (mediaAttachment is null)
  67. {
  68. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {attachmentStreamIndex}");
  69. }
  70. var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
  71. .ConfigureAwait(false);
  72. return (mediaAttachment, attachmentStream);
  73. }
  74. public async Task ExtractAllAttachments(
  75. string inputFile,
  76. MediaSourceInfo mediaSource,
  77. string outputPath,
  78. CancellationToken cancellationToken)
  79. {
  80. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  81. {
  82. if (!Directory.Exists(outputPath))
  83. {
  84. await ExtractAllAttachmentsInternal(
  85. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  86. outputPath,
  87. false,
  88. cancellationToken).ConfigureAwait(false);
  89. }
  90. }
  91. }
  92. public async Task ExtractAllAttachmentsExternal(
  93. string inputArgument,
  94. string id,
  95. string outputPath,
  96. CancellationToken cancellationToken)
  97. {
  98. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  99. {
  100. if (!File.Exists(Path.Join(outputPath, id)))
  101. {
  102. await ExtractAllAttachmentsInternal(
  103. inputArgument,
  104. outputPath,
  105. true,
  106. cancellationToken).ConfigureAwait(false);
  107. if (Directory.Exists(outputPath))
  108. {
  109. File.Create(Path.Join(outputPath, id));
  110. }
  111. }
  112. }
  113. }
  114. private async Task ExtractAllAttachmentsInternal(
  115. string inputPath,
  116. string outputPath,
  117. bool isExternal,
  118. CancellationToken cancellationToken)
  119. {
  120. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  121. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  122. Directory.CreateDirectory(outputPath);
  123. var processArgs = string.Format(
  124. CultureInfo.InvariantCulture,
  125. "-dump_attachment:t \"\" -y -i {0} -t 0 -f null null",
  126. inputPath);
  127. int exitCode;
  128. using (var process = new Process
  129. {
  130. StartInfo = new ProcessStartInfo
  131. {
  132. Arguments = processArgs,
  133. FileName = _mediaEncoder.EncoderPath,
  134. UseShellExecute = false,
  135. CreateNoWindow = true,
  136. WindowStyle = ProcessWindowStyle.Hidden,
  137. WorkingDirectory = outputPath,
  138. ErrorDialog = false
  139. },
  140. EnableRaisingEvents = true
  141. })
  142. {
  143. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  144. process.Start();
  145. try
  146. {
  147. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  148. exitCode = process.ExitCode;
  149. }
  150. catch (OperationCanceledException)
  151. {
  152. process.Kill(true);
  153. exitCode = -1;
  154. }
  155. }
  156. var failed = false;
  157. if (exitCode != 0)
  158. {
  159. if (isExternal && exitCode == 1)
  160. {
  161. // ffmpeg returns exitCode 1 because there is no video or audio stream
  162. // this can be ignored
  163. }
  164. else
  165. {
  166. failed = true;
  167. _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputPath, exitCode);
  168. try
  169. {
  170. Directory.Delete(outputPath);
  171. }
  172. catch (IOException ex)
  173. {
  174. _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputPath);
  175. }
  176. }
  177. }
  178. else if (!Directory.Exists(outputPath))
  179. {
  180. failed = true;
  181. }
  182. if (failed)
  183. {
  184. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  185. throw new InvalidOperationException(
  186. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  187. }
  188. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  189. }
  190. private async Task<Stream> GetAttachmentStream(
  191. MediaSourceInfo mediaSource,
  192. MediaAttachment mediaAttachment,
  193. CancellationToken cancellationToken)
  194. {
  195. var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
  196. return AsyncFile.OpenRead(attachmentPath);
  197. }
  198. private async Task<string> GetReadableFile(
  199. string mediaPath,
  200. string inputFile,
  201. MediaSourceInfo mediaSource,
  202. MediaAttachment mediaAttachment,
  203. CancellationToken cancellationToken)
  204. {
  205. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
  206. await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
  207. .ConfigureAwait(false);
  208. return outputPath;
  209. }
  210. private async Task ExtractAttachment(
  211. string inputFile,
  212. MediaSourceInfo mediaSource,
  213. int attachmentStreamIndex,
  214. string outputPath,
  215. CancellationToken cancellationToken)
  216. {
  217. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  218. {
  219. if (!File.Exists(outputPath))
  220. {
  221. await ExtractAttachmentInternal(
  222. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  223. attachmentStreamIndex,
  224. outputPath,
  225. cancellationToken).ConfigureAwait(false);
  226. }
  227. }
  228. }
  229. private async Task ExtractAttachmentInternal(
  230. string inputPath,
  231. int attachmentStreamIndex,
  232. string outputPath,
  233. CancellationToken cancellationToken)
  234. {
  235. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  236. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  237. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputPath)));
  238. var processArgs = string.Format(
  239. CultureInfo.InvariantCulture,
  240. "-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
  241. inputPath,
  242. attachmentStreamIndex,
  243. EncodingUtils.NormalizePath(outputPath));
  244. int exitCode;
  245. using (var process = new Process
  246. {
  247. StartInfo = new ProcessStartInfo
  248. {
  249. Arguments = processArgs,
  250. FileName = _mediaEncoder.EncoderPath,
  251. UseShellExecute = false,
  252. CreateNoWindow = true,
  253. WindowStyle = ProcessWindowStyle.Hidden,
  254. ErrorDialog = false
  255. },
  256. EnableRaisingEvents = true
  257. })
  258. {
  259. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  260. process.Start();
  261. try
  262. {
  263. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  264. exitCode = process.ExitCode;
  265. }
  266. catch (OperationCanceledException)
  267. {
  268. process.Kill(true);
  269. exitCode = -1;
  270. }
  271. }
  272. var failed = false;
  273. if (exitCode != 0)
  274. {
  275. failed = true;
  276. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  277. try
  278. {
  279. if (File.Exists(outputPath))
  280. {
  281. _fileSystem.DeleteFile(outputPath);
  282. }
  283. }
  284. catch (IOException ex)
  285. {
  286. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  287. }
  288. }
  289. else if (!File.Exists(outputPath))
  290. {
  291. failed = true;
  292. }
  293. if (failed)
  294. {
  295. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  296. throw new InvalidOperationException(
  297. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  298. }
  299. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  300. }
  301. private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
  302. {
  303. string filename;
  304. if (mediaSource.Protocol == MediaProtocol.File)
  305. {
  306. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  307. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  308. }
  309. else
  310. {
  311. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  312. }
  313. var prefix = filename.AsSpan(0, 1);
  314. return Path.Join(_appPaths.DataPath, "attachments", prefix, filename);
  315. }
  316. /// <inheritdoc />
  317. public void Dispose()
  318. {
  319. _semaphoreLocks.Dispose();
  320. }
  321. }
  322. }