AttachmentExtractor.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. private async Task<Stream> GetAttachmentStream(
  75. MediaSourceInfo mediaSource,
  76. MediaAttachment mediaAttachment,
  77. CancellationToken cancellationToken)
  78. {
  79. var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
  80. return File.OpenRead(attachmentPath);
  81. }
  82. private async Task<string> GetReadableFile(
  83. string mediaPath,
  84. string inputFile,
  85. MediaSourceInfo mediaSource,
  86. MediaAttachment mediaAttachment,
  87. CancellationToken cancellationToken)
  88. {
  89. var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
  90. await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
  91. .ConfigureAwait(false);
  92. return outputPath;
  93. }
  94. private async Task ExtractAttachment(
  95. string inputFile,
  96. MediaSourceInfo mediaSource,
  97. int attachmentStreamIndex,
  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(outputPath))
  106. {
  107. await ExtractAttachmentInternal(
  108. _mediaEncoder.GetInputArgument(inputFile, mediaSource),
  109. attachmentStreamIndex,
  110. outputPath,
  111. cancellationToken).ConfigureAwait(false);
  112. }
  113. }
  114. finally
  115. {
  116. semaphore.Release();
  117. }
  118. }
  119. private async Task ExtractAttachmentInternal(
  120. string inputPath,
  121. int attachmentStreamIndex,
  122. string outputPath,
  123. CancellationToken cancellationToken)
  124. {
  125. if (string.IsNullOrEmpty(inputPath))
  126. {
  127. throw new ArgumentNullException(nameof(inputPath));
  128. }
  129. if (string.IsNullOrEmpty(outputPath))
  130. {
  131. throw new ArgumentNullException(nameof(outputPath));
  132. }
  133. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  134. var processArgs = string.Format(
  135. CultureInfo.InvariantCulture,
  136. "-dump_attachment:{1} {2} -i {0} -t 0 -f null null",
  137. inputPath,
  138. attachmentStreamIndex,
  139. outputPath);
  140. int exitCode;
  141. using (var process = new Process
  142. {
  143. StartInfo = new ProcessStartInfo
  144. {
  145. Arguments = processArgs,
  146. FileName = _mediaEncoder.EncoderPath,
  147. UseShellExecute = false,
  148. CreateNoWindow = true,
  149. WindowStyle = ProcessWindowStyle.Hidden,
  150. ErrorDialog = false
  151. },
  152. EnableRaisingEvents = true
  153. })
  154. {
  155. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  156. process.Start();
  157. var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
  158. if (!ranToCompletion)
  159. {
  160. try
  161. {
  162. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  163. process.Kill();
  164. }
  165. catch (Exception ex)
  166. {
  167. _logger.LogError(ex, "Error killing attachment extraction process");
  168. }
  169. }
  170. exitCode = ranToCompletion ? process.ExitCode : -1;
  171. }
  172. var failed = false;
  173. if (exitCode != 0)
  174. {
  175. failed = true;
  176. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  177. try
  178. {
  179. if (File.Exists(outputPath))
  180. {
  181. _fileSystem.DeleteFile(outputPath);
  182. }
  183. }
  184. catch (IOException ex)
  185. {
  186. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  187. }
  188. }
  189. else if (!File.Exists(outputPath))
  190. {
  191. failed = true;
  192. }
  193. if (failed)
  194. {
  195. var msg = $"ffmpeg attachment extraction failed for {inputPath} to {outputPath}";
  196. _logger.LogError(msg);
  197. throw new InvalidOperationException(msg);
  198. }
  199. else
  200. {
  201. _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", inputPath, outputPath);
  202. }
  203. }
  204. private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
  205. {
  206. string filename;
  207. if (mediaSource.Protocol == MediaProtocol.File)
  208. {
  209. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  210. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  211. }
  212. else
  213. {
  214. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  215. }
  216. var prefix = filename.Substring(0, 1);
  217. return Path.Combine(_appPaths.DataPath, "attachments", prefix, filename);
  218. }
  219. /// <inheritdoc />
  220. public void Dispose()
  221. {
  222. Dispose(true);
  223. GC.SuppressFinalize(this);
  224. }
  225. /// <summary>
  226. /// Releases unmanaged and - optionally - managed resources.
  227. /// </summary>
  228. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  229. protected virtual void Dispose(bool disposing)
  230. {
  231. if (_disposed)
  232. {
  233. return;
  234. }
  235. if (disposing)
  236. {
  237. }
  238. _disposed = true;
  239. }
  240. }
  241. }