AttachmentExtractor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  203. }
  204. private async Task<Stream> GetAttachmentStream(
  205. MediaSourceInfo mediaSource,
  206. MediaAttachment mediaAttachment,
  207. CancellationToken cancellationToken)
  208. {
  209. var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
  210. return AsyncFile.OpenRead(attachmentPath);
  211. }
  212. private async Task<string> GetReadableFile(
  213. string mediaPath,
  214. string inputFile,
  215. MediaSourceInfo mediaSource,
  216. MediaAttachment mediaAttachment,
  217. CancellationToken cancellationToken)
  218. {
  219. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
  220. await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
  221. .ConfigureAwait(false);
  222. return outputPath;
  223. }
  224. private async Task ExtractAttachment(
  225. string inputFile,
  226. MediaSourceInfo mediaSource,
  227. int attachmentStreamIndex,
  228. string outputPath,
  229. CancellationToken cancellationToken)
  230. {
  231. var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
  232. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  233. try
  234. {
  235. if (!File.Exists(outputPath))
  236. {
  237. await ExtractAttachmentInternal(
  238. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  239. attachmentStreamIndex,
  240. outputPath,
  241. cancellationToken).ConfigureAwait(false);
  242. }
  243. }
  244. finally
  245. {
  246. semaphore.Release();
  247. }
  248. }
  249. private async Task ExtractAttachmentInternal(
  250. string inputPath,
  251. int attachmentStreamIndex,
  252. string outputPath,
  253. CancellationToken cancellationToken)
  254. {
  255. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  256. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  257. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  258. var processArgs = string.Format(
  259. CultureInfo.InvariantCulture,
  260. "-dump_attachment:{1} \"{2}\" -i {0} -t 0 -f null null",
  261. inputPath,
  262. attachmentStreamIndex,
  263. EncodingUtils.NormalizePath(outputPath));
  264. int exitCode;
  265. using (var process = new Process
  266. {
  267. StartInfo = new ProcessStartInfo
  268. {
  269. Arguments = processArgs,
  270. FileName = _mediaEncoder.EncoderPath,
  271. UseShellExecute = false,
  272. CreateNoWindow = true,
  273. WindowStyle = ProcessWindowStyle.Hidden,
  274. ErrorDialog = false
  275. },
  276. EnableRaisingEvents = true
  277. })
  278. {
  279. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  280. process.Start();
  281. var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
  282. if (!ranToCompletion)
  283. {
  284. try
  285. {
  286. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  287. process.Kill();
  288. }
  289. catch (Exception ex)
  290. {
  291. _logger.LogError(ex, "Error killing attachment extraction process");
  292. }
  293. }
  294. exitCode = ranToCompletion ? process.ExitCode : -1;
  295. }
  296. var failed = false;
  297. if (exitCode != 0)
  298. {
  299. failed = true;
  300. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  301. try
  302. {
  303. if (File.Exists(outputPath))
  304. {
  305. _fileSystem.DeleteFile(outputPath);
  306. }
  307. }
  308. catch (IOException ex)
  309. {
  310. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  311. }
  312. }
  313. else if (!File.Exists(outputPath))
  314. {
  315. failed = true;
  316. }
  317. if (failed)
  318. {
  319. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  320. throw new InvalidOperationException(
  321. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  322. }
  323. _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  324. }
  325. private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
  326. {
  327. string filename;
  328. if (mediaSource.Protocol == MediaProtocol.File)
  329. {
  330. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  331. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  332. }
  333. else
  334. {
  335. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  336. }
  337. var prefix = filename.Substring(0, 1);
  338. return Path.Combine(_appPaths.DataPath, "attachments", prefix, filename);
  339. }
  340. /// <inheritdoc />
  341. public void Dispose()
  342. {
  343. Dispose(true);
  344. GC.SuppressFinalize(this);
  345. }
  346. /// <summary>
  347. /// Releases unmanaged and - optionally - managed resources.
  348. /// </summary>
  349. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  350. protected virtual void Dispose(bool disposing)
  351. {
  352. if (_disposed)
  353. {
  354. return;
  355. }
  356. if (disposing)
  357. {
  358. }
  359. _disposed = true;
  360. }
  361. }
  362. }