AttachmentExtractor.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
  154. if (!ranToCompletion)
  155. {
  156. try
  157. {
  158. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  159. process.Kill();
  160. }
  161. catch (Exception ex)
  162. {
  163. _logger.LogError(ex, "Error killing attachment extraction process");
  164. }
  165. }
  166. exitCode = ranToCompletion ? process.ExitCode : -1;
  167. }
  168. var failed = false;
  169. if (exitCode != 0)
  170. {
  171. if (isExternal && exitCode == 1)
  172. {
  173. // ffmpeg returns exitCode 1 because there is no video or audio stream
  174. // this can be ignored
  175. }
  176. else
  177. {
  178. failed = true;
  179. _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputPath, exitCode);
  180. try
  181. {
  182. Directory.Delete(outputPath);
  183. }
  184. catch (IOException ex)
  185. {
  186. _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputPath);
  187. }
  188. }
  189. }
  190. else if (!Directory.Exists(outputPath))
  191. {
  192. failed = true;
  193. }
  194. if (failed)
  195. {
  196. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  197. throw new InvalidOperationException(
  198. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  199. }
  200. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  201. }
  202. private async Task<Stream> GetAttachmentStream(
  203. MediaSourceInfo mediaSource,
  204. MediaAttachment mediaAttachment,
  205. CancellationToken cancellationToken)
  206. {
  207. var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
  208. return AsyncFile.OpenRead(attachmentPath);
  209. }
  210. private async Task<string> GetReadableFile(
  211. string mediaPath,
  212. string inputFile,
  213. MediaSourceInfo mediaSource,
  214. MediaAttachment mediaAttachment,
  215. CancellationToken cancellationToken)
  216. {
  217. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
  218. await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
  219. .ConfigureAwait(false);
  220. return outputPath;
  221. }
  222. private async Task ExtractAttachment(
  223. string inputFile,
  224. MediaSourceInfo mediaSource,
  225. int attachmentStreamIndex,
  226. string outputPath,
  227. CancellationToken cancellationToken)
  228. {
  229. var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
  230. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  231. try
  232. {
  233. if (!File.Exists(outputPath))
  234. {
  235. await ExtractAttachmentInternal(
  236. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  237. attachmentStreamIndex,
  238. outputPath,
  239. cancellationToken).ConfigureAwait(false);
  240. }
  241. }
  242. finally
  243. {
  244. semaphore.Release();
  245. }
  246. }
  247. private async Task ExtractAttachmentInternal(
  248. string inputPath,
  249. int attachmentStreamIndex,
  250. string outputPath,
  251. CancellationToken cancellationToken)
  252. {
  253. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  254. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  255. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputPath)));
  256. var processArgs = string.Format(
  257. CultureInfo.InvariantCulture,
  258. "-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
  259. inputPath,
  260. attachmentStreamIndex,
  261. EncodingUtils.NormalizePath(outputPath));
  262. int exitCode;
  263. using (var process = new Process
  264. {
  265. StartInfo = new ProcessStartInfo
  266. {
  267. Arguments = processArgs,
  268. FileName = _mediaEncoder.EncoderPath,
  269. UseShellExecute = false,
  270. CreateNoWindow = true,
  271. WindowStyle = ProcessWindowStyle.Hidden,
  272. ErrorDialog = false
  273. },
  274. EnableRaisingEvents = true
  275. })
  276. {
  277. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  278. process.Start();
  279. var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
  280. if (!ranToCompletion)
  281. {
  282. try
  283. {
  284. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  285. process.Kill();
  286. }
  287. catch (Exception ex)
  288. {
  289. _logger.LogError(ex, "Error killing attachment extraction process");
  290. }
  291. }
  292. exitCode = ranToCompletion ? process.ExitCode : -1;
  293. }
  294. var failed = false;
  295. if (exitCode != 0)
  296. {
  297. failed = true;
  298. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  299. try
  300. {
  301. if (File.Exists(outputPath))
  302. {
  303. _fileSystem.DeleteFile(outputPath);
  304. }
  305. }
  306. catch (IOException ex)
  307. {
  308. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  309. }
  310. }
  311. else if (!File.Exists(outputPath))
  312. {
  313. failed = true;
  314. }
  315. if (failed)
  316. {
  317. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  318. throw new InvalidOperationException(
  319. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  320. }
  321. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  322. }
  323. private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
  324. {
  325. string filename;
  326. if (mediaSource.Protocol == MediaProtocol.File)
  327. {
  328. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  329. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  330. }
  331. else
  332. {
  333. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  334. }
  335. var prefix = filename.AsSpan(0, 1);
  336. return Path.Join(_appPaths.DataPath, "attachments", prefix, filename);
  337. }
  338. }
  339. }