AttachmentExtractor.cs 16 KB

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