AttachmentExtractor.cs 14 KB

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