2
0

AttachmentExtractor.cs 15 KB

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