AttachmentExtractor.cs 14 KB

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