AttachmentExtractor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 is 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 is 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. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  130. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  131. Directory.CreateDirectory(outputPath);
  132. var processArgs = string.Format(
  133. CultureInfo.InvariantCulture,
  134. "-dump_attachment:t \"\" -y -i {0} -t 0 -f null null",
  135. inputPath);
  136. int exitCode;
  137. using (var process = new Process
  138. {
  139. StartInfo = new ProcessStartInfo
  140. {
  141. Arguments = processArgs,
  142. FileName = _mediaEncoder.EncoderPath,
  143. UseShellExecute = false,
  144. CreateNoWindow = true,
  145. WindowStyle = ProcessWindowStyle.Hidden,
  146. WorkingDirectory = outputPath,
  147. ErrorDialog = false
  148. },
  149. EnableRaisingEvents = true
  150. })
  151. {
  152. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  153. process.Start();
  154. var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
  155. if (!ranToCompletion)
  156. {
  157. try
  158. {
  159. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  160. process.Kill();
  161. }
  162. catch (Exception ex)
  163. {
  164. _logger.LogError(ex, "Error killing attachment extraction process");
  165. }
  166. }
  167. exitCode = ranToCompletion ? process.ExitCode : -1;
  168. }
  169. var failed = false;
  170. if (exitCode != 0)
  171. {
  172. if (isExternal && exitCode == 1)
  173. {
  174. // ffmpeg returns exitCode 1 because there is no video or audio stream
  175. // this can be ignored
  176. }
  177. else
  178. {
  179. failed = true;
  180. _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputPath, exitCode);
  181. try
  182. {
  183. Directory.Delete(outputPath);
  184. }
  185. catch (IOException ex)
  186. {
  187. _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputPath);
  188. }
  189. }
  190. }
  191. else if (!Directory.Exists(outputPath))
  192. {
  193. failed = true;
  194. }
  195. if (failed)
  196. {
  197. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  198. throw new InvalidOperationException(
  199. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  200. }
  201. else
  202. {
  203. _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", inputPath, outputPath);
  204. }
  205. }
  206. private async Task<Stream> GetAttachmentStream(
  207. MediaSourceInfo mediaSource,
  208. MediaAttachment mediaAttachment,
  209. CancellationToken cancellationToken)
  210. {
  211. var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
  212. return AsyncFile.OpenRead(attachmentPath);
  213. }
  214. private async Task<string> GetReadableFile(
  215. string mediaPath,
  216. string inputFile,
  217. MediaSourceInfo mediaSource,
  218. MediaAttachment mediaAttachment,
  219. CancellationToken cancellationToken)
  220. {
  221. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
  222. await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
  223. .ConfigureAwait(false);
  224. return outputPath;
  225. }
  226. private async Task ExtractAttachment(
  227. string inputFile,
  228. MediaSourceInfo mediaSource,
  229. int attachmentStreamIndex,
  230. string outputPath,
  231. CancellationToken cancellationToken)
  232. {
  233. var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
  234. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  235. try
  236. {
  237. if (!File.Exists(outputPath))
  238. {
  239. await ExtractAttachmentInternal(
  240. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  241. attachmentStreamIndex,
  242. outputPath,
  243. cancellationToken).ConfigureAwait(false);
  244. }
  245. }
  246. finally
  247. {
  248. semaphore.Release();
  249. }
  250. }
  251. private async Task ExtractAttachmentInternal(
  252. string inputPath,
  253. int attachmentStreamIndex,
  254. string outputPath,
  255. CancellationToken cancellationToken)
  256. {
  257. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  258. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  259. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  260. var processArgs = string.Format(
  261. CultureInfo.InvariantCulture,
  262. "-dump_attachment:{1} {2} -i {0} -t 0 -f null null",
  263. inputPath,
  264. attachmentStreamIndex,
  265. outputPath);
  266. int exitCode;
  267. using (var process = new Process
  268. {
  269. StartInfo = new ProcessStartInfo
  270. {
  271. Arguments = processArgs,
  272. FileName = _mediaEncoder.EncoderPath,
  273. UseShellExecute = false,
  274. CreateNoWindow = true,
  275. WindowStyle = ProcessWindowStyle.Hidden,
  276. ErrorDialog = false
  277. },
  278. EnableRaisingEvents = true
  279. })
  280. {
  281. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  282. process.Start();
  283. var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
  284. if (!ranToCompletion)
  285. {
  286. try
  287. {
  288. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  289. process.Kill();
  290. }
  291. catch (Exception ex)
  292. {
  293. _logger.LogError(ex, "Error killing attachment extraction process");
  294. }
  295. }
  296. exitCode = ranToCompletion ? process.ExitCode : -1;
  297. }
  298. var failed = false;
  299. if (exitCode != 0)
  300. {
  301. failed = true;
  302. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  303. try
  304. {
  305. if (File.Exists(outputPath))
  306. {
  307. _fileSystem.DeleteFile(outputPath);
  308. }
  309. }
  310. catch (IOException ex)
  311. {
  312. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  313. }
  314. }
  315. else if (!File.Exists(outputPath))
  316. {
  317. failed = true;
  318. }
  319. if (failed)
  320. {
  321. _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  322. throw new InvalidOperationException(
  323. string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
  324. }
  325. else
  326. {
  327. _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", inputPath, outputPath);
  328. }
  329. }
  330. private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
  331. {
  332. string filename;
  333. if (mediaSource.Protocol == MediaProtocol.File)
  334. {
  335. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  336. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  337. }
  338. else
  339. {
  340. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  341. }
  342. var prefix = filename.Substring(0, 1);
  343. return Path.Combine(_appPaths.DataPath, "attachments", prefix, filename);
  344. }
  345. /// <inheritdoc />
  346. public void Dispose()
  347. {
  348. Dispose(true);
  349. GC.SuppressFinalize(this);
  350. }
  351. /// <summary>
  352. /// Releases unmanaged and - optionally - managed resources.
  353. /// </summary>
  354. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  355. protected virtual void Dispose(bool disposing)
  356. {
  357. if (_disposed)
  358. {
  359. return;
  360. }
  361. if (disposing)
  362. {
  363. }
  364. _disposed = true;
  365. }
  366. }
  367. }