AttachmentExtractor.cs 15 KB

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