AttachmentExtractor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  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 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 ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  32. new ConcurrentDictionary<string, SemaphoreSlim>();
  33. private bool _disposed = false;
  34. public AttachmentExtractor(
  35. ILogger<AttachmentExtractor> logger,
  36. IApplicationPaths appPaths,
  37. IFileSystem fileSystem,
  38. IMediaEncoder mediaEncoder,
  39. IMediaSourceManager mediaSourceManager)
  40. {
  41. _logger = logger;
  42. _appPaths = appPaths;
  43. _fileSystem = fileSystem;
  44. _mediaEncoder = mediaEncoder;
  45. _mediaSourceManager = mediaSourceManager;
  46. }
  47. /// <inheritdoc />
  48. public async Task<(MediaAttachment Attachment, Stream Stream)> GetAttachment(BaseItem item, string mediaSourceId, int attachmentStreamIndex, CancellationToken cancellationToken)
  49. {
  50. ArgumentNullException.ThrowIfNull(item);
  51. if (string.IsNullOrWhiteSpace(mediaSourceId))
  52. {
  53. throw new ArgumentNullException(nameof(mediaSourceId));
  54. }
  55. var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
  56. var mediaSource = mediaSources
  57. .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  58. if (mediaSource is null)
  59. {
  60. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} not found");
  61. }
  62. var mediaAttachment = mediaSource.MediaAttachments
  63. .FirstOrDefault(i => i.Index == attachmentStreamIndex);
  64. if (mediaAttachment is null)
  65. {
  66. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {attachmentStreamIndex}");
  67. }
  68. var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
  69. .ConfigureAwait(false);
  70. return (mediaAttachment, attachmentStream);
  71. }
  72. public async Task ExtractAllAttachments(
  73. string inputFile,
  74. MediaSourceInfo mediaSource,
  75. string outputPath,
  76. CancellationToken cancellationToken)
  77. {
  78. var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
  79. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  80. try
  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. finally
  92. {
  93. semaphore.Release();
  94. }
  95. }
  96. public async Task ExtractAllAttachmentsExternal(
  97. string inputArgument,
  98. string id,
  99. string outputPath,
  100. CancellationToken cancellationToken)
  101. {
  102. var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
  103. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  104. try
  105. {
  106. if (!File.Exists(Path.Join(outputPath, id)))
  107. {
  108. await ExtractAllAttachmentsInternal(
  109. inputArgument,
  110. outputPath,
  111. true,
  112. cancellationToken).ConfigureAwait(false);
  113. if (Directory.Exists(outputPath))
  114. {
  115. File.Create(Path.Join(outputPath, id));
  116. }
  117. }
  118. }
  119. finally
  120. {
  121. semaphore.Release();
  122. }
  123. }
  124. private async Task ExtractAllAttachmentsInternal(
  125. string inputPath,
  126. string outputPath,
  127. bool isExternal,
  128. CancellationToken cancellationToken)
  129. {
  130. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  131. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  132. Directory.CreateDirectory(outputPath);
  133. var processArgs = string.Format(
  134. CultureInfo.InvariantCulture,
  135. "-dump_attachment:t \"\" -y -i {0} -t 0 -f null null",
  136. inputPath);
  137. int exitCode;
  138. using (var process = new Process
  139. {
  140. StartInfo = new ProcessStartInfo
  141. {
  142. Arguments = processArgs,
  143. FileName = _mediaEncoder.EncoderPath,
  144. UseShellExecute = false,
  145. CreateNoWindow = true,
  146. WindowStyle = ProcessWindowStyle.Hidden,
  147. WorkingDirectory = outputPath,
  148. ErrorDialog = false
  149. },
  150. EnableRaisingEvents = true
  151. })
  152. {
  153. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  154. process.Start();
  155. var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
  156. if (!ranToCompletion)
  157. {
  158. try
  159. {
  160. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  161. process.Kill();
  162. }
  163. catch (Exception ex)
  164. {
  165. _logger.LogError(ex, "Error killing attachment extraction process");
  166. }
  167. }
  168. exitCode = ranToCompletion ? process.ExitCode : -1;
  169. }
  170. var failed = false;
  171. if (exitCode != 0)
  172. {
  173. if (isExternal && exitCode == 1)
  174. {
  175. // ffmpeg returns exitCode 1 because there is no video or audio stream
  176. // this can be ignored
  177. }
  178. else
  179. {
  180. failed = true;
  181. _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputPath, exitCode);
  182. try
  183. {
  184. Directory.Delete(outputPath);
  185. }
  186. catch (IOException ex)
  187. {
  188. _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputPath);
  189. }
  190. }
  191. }
  192. else if (!Directory.Exists(outputPath))
  193. {
  194. failed = true;
  195. }
  196. if (failed)
  197. {
  198. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  199. throw new InvalidOperationException(
  200. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  201. }
  202. else
  203. {
  204. _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", inputPath, outputPath);
  205. }
  206. }
  207. private async Task<Stream> GetAttachmentStream(
  208. MediaSourceInfo mediaSource,
  209. MediaAttachment mediaAttachment,
  210. CancellationToken cancellationToken)
  211. {
  212. var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
  213. return AsyncFile.OpenRead(attachmentPath);
  214. }
  215. private async Task<string> GetReadableFile(
  216. string mediaPath,
  217. string inputFile,
  218. MediaSourceInfo mediaSource,
  219. MediaAttachment mediaAttachment,
  220. CancellationToken cancellationToken)
  221. {
  222. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
  223. await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
  224. .ConfigureAwait(false);
  225. return outputPath;
  226. }
  227. private async Task ExtractAttachment(
  228. string inputFile,
  229. MediaSourceInfo mediaSource,
  230. int attachmentStreamIndex,
  231. string outputPath,
  232. CancellationToken cancellationToken)
  233. {
  234. var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
  235. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  236. try
  237. {
  238. if (!File.Exists(outputPath))
  239. {
  240. await ExtractAttachmentInternal(
  241. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  242. attachmentStreamIndex,
  243. outputPath,
  244. cancellationToken).ConfigureAwait(false);
  245. }
  246. }
  247. finally
  248. {
  249. semaphore.Release();
  250. }
  251. }
  252. private async Task ExtractAttachmentInternal(
  253. string inputPath,
  254. int attachmentStreamIndex,
  255. string outputPath,
  256. CancellationToken cancellationToken)
  257. {
  258. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  259. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  260. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  261. var processArgs = string.Format(
  262. CultureInfo.InvariantCulture,
  263. "-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
  264. inputPath,
  265. attachmentStreamIndex,
  266. EncodingUtils.NormalizePath(outputPath));
  267. int exitCode;
  268. using (var process = new Process
  269. {
  270. StartInfo = new ProcessStartInfo
  271. {
  272. Arguments = processArgs,
  273. FileName = _mediaEncoder.EncoderPath,
  274. UseShellExecute = false,
  275. CreateNoWindow = true,
  276. WindowStyle = ProcessWindowStyle.Hidden,
  277. ErrorDialog = false
  278. },
  279. EnableRaisingEvents = true
  280. })
  281. {
  282. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  283. process.Start();
  284. var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
  285. if (!ranToCompletion)
  286. {
  287. try
  288. {
  289. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  290. process.Kill();
  291. }
  292. catch (Exception ex)
  293. {
  294. _logger.LogError(ex, "Error killing attachment extraction process");
  295. }
  296. }
  297. exitCode = ranToCompletion ? process.ExitCode : -1;
  298. }
  299. var failed = false;
  300. if (exitCode != 0)
  301. {
  302. failed = true;
  303. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  304. try
  305. {
  306. if (File.Exists(outputPath))
  307. {
  308. _fileSystem.DeleteFile(outputPath);
  309. }
  310. }
  311. catch (IOException ex)
  312. {
  313. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  314. }
  315. }
  316. else if (!File.Exists(outputPath))
  317. {
  318. failed = true;
  319. }
  320. if (failed)
  321. {
  322. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  323. throw new InvalidOperationException(
  324. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  325. }
  326. else
  327. {
  328. _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", inputPath, outputPath);
  329. }
  330. }
  331. private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
  332. {
  333. string filename;
  334. if (mediaSource.Protocol == MediaProtocol.File)
  335. {
  336. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  337. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  338. }
  339. else
  340. {
  341. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  342. }
  343. var prefix = filename.Substring(0, 1);
  344. return Path.Combine(_appPaths.DataPath, "attachments", prefix, filename);
  345. }
  346. /// <inheritdoc />
  347. public void Dispose()
  348. {
  349. Dispose(true);
  350. GC.SuppressFinalize(this);
  351. }
  352. /// <summary>
  353. /// Releases unmanaged and - optionally - managed resources.
  354. /// </summary>
  355. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  356. protected virtual void Dispose(bool disposing)
  357. {
  358. if (_disposed)
  359. {
  360. return;
  361. }
  362. if (disposing)
  363. {
  364. }
  365. _disposed = true;
  366. }
  367. }
  368. }