AttachmentExtractor.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.MediaEncoding;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.MediaInfo;
  19. using Microsoft.Extensions.Logging;
  20. namespace MediaBrowser.MediaEncoding.Attachments
  21. {
  22. public class AttachmentExtractor : IAttachmentExtractor, IDisposable
  23. {
  24. private readonly ILogger<AttachmentExtractor> _logger;
  25. private readonly IApplicationPaths _appPaths;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly IMediaEncoder _mediaEncoder;
  28. private readonly IMediaSourceManager _mediaSourceManager;
  29. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  30. new ConcurrentDictionary<string, SemaphoreSlim>();
  31. private bool _disposed = false;
  32. public AttachmentExtractor(
  33. ILogger<AttachmentExtractor> logger,
  34. IApplicationPaths appPaths,
  35. IFileSystem fileSystem,
  36. IMediaEncoder mediaEncoder,
  37. IMediaSourceManager mediaSourceManager)
  38. {
  39. _logger = logger;
  40. _appPaths = appPaths;
  41. _fileSystem = fileSystem;
  42. _mediaEncoder = mediaEncoder;
  43. _mediaSourceManager = mediaSourceManager;
  44. }
  45. /// <inheritdoc />
  46. public async Task<(MediaAttachment attachment, Stream stream)> GetAttachment(BaseItem item, string mediaSourceId, int attachmentStreamIndex, CancellationToken cancellationToken)
  47. {
  48. if (item == null)
  49. {
  50. throw new ArgumentNullException(nameof(item));
  51. }
  52. if (string.IsNullOrWhiteSpace(mediaSourceId))
  53. {
  54. throw new ArgumentNullException(nameof(mediaSourceId));
  55. }
  56. var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
  57. var mediaSource = mediaSources
  58. .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  59. if (mediaSource == null)
  60. {
  61. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} not found");
  62. }
  63. var mediaAttachment = mediaSource.MediaAttachments
  64. .FirstOrDefault(i => i.Index == attachmentStreamIndex);
  65. if (mediaAttachment == null)
  66. {
  67. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {attachmentStreamIndex}");
  68. }
  69. var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
  70. .ConfigureAwait(false);
  71. return (mediaAttachment, attachmentStream);
  72. }
  73. private async Task<Stream> GetAttachmentStream(
  74. MediaSourceInfo mediaSource,
  75. MediaAttachment mediaAttachment,
  76. CancellationToken cancellationToken)
  77. {
  78. var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource.Protocol, mediaAttachment, cancellationToken).ConfigureAwait(false);
  79. return File.OpenRead(attachmentPath);
  80. }
  81. private async Task<string> GetReadableFile(
  82. string mediaPath,
  83. string inputFile,
  84. MediaProtocol protocol,
  85. MediaAttachment mediaAttachment,
  86. CancellationToken cancellationToken)
  87. {
  88. var outputPath = GetAttachmentCachePath(mediaPath, protocol, mediaAttachment.Index);
  89. await ExtractAttachment(inputFile, protocol, mediaAttachment.Index, outputPath, cancellationToken)
  90. .ConfigureAwait(false);
  91. return outputPath;
  92. }
  93. private async Task ExtractAttachment(
  94. string inputFile,
  95. MediaProtocol protocol,
  96. int attachmentStreamIndex,
  97. string outputPath,
  98. CancellationToken cancellationToken)
  99. {
  100. var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
  101. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  102. try
  103. {
  104. if (!File.Exists(outputPath))
  105. {
  106. await ExtractAttachmentInternal(
  107. _mediaEncoder.GetInputArgument(new[] { inputFile }, protocol),
  108. attachmentStreamIndex,
  109. outputPath,
  110. cancellationToken).ConfigureAwait(false);
  111. }
  112. }
  113. finally
  114. {
  115. semaphore.Release();
  116. }
  117. }
  118. private async Task ExtractAttachmentInternal(
  119. string inputPath,
  120. int attachmentStreamIndex,
  121. string outputPath,
  122. CancellationToken cancellationToken)
  123. {
  124. if (string.IsNullOrEmpty(inputPath))
  125. {
  126. throw new ArgumentNullException(nameof(inputPath));
  127. }
  128. if (string.IsNullOrEmpty(outputPath))
  129. {
  130. throw new ArgumentNullException(nameof(outputPath));
  131. }
  132. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  133. var processArgs = string.Format(
  134. CultureInfo.InvariantCulture,
  135. "-dump_attachment:{1} {2} -i {0} -t 0 -f null null",
  136. inputPath,
  137. attachmentStreamIndex,
  138. outputPath);
  139. int exitCode;
  140. using (var process = new Process
  141. {
  142. StartInfo = new ProcessStartInfo
  143. {
  144. Arguments = processArgs,
  145. FileName = _mediaEncoder.EncoderPath,
  146. UseShellExecute = false,
  147. CreateNoWindow = true,
  148. WindowStyle = ProcessWindowStyle.Hidden,
  149. ErrorDialog = false
  150. },
  151. EnableRaisingEvents = true
  152. })
  153. {
  154. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  155. process.Start();
  156. var ranToCompletion = await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  157. if (!ranToCompletion)
  158. {
  159. try
  160. {
  161. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  162. process.Kill();
  163. }
  164. catch (Exception ex)
  165. {
  166. _logger.LogError(ex, "Error killing attachment extraction process");
  167. }
  168. }
  169. exitCode = ranToCompletion ? process.ExitCode : -1;
  170. }
  171. var failed = false;
  172. if (exitCode != 0)
  173. {
  174. failed = true;
  175. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  176. try
  177. {
  178. if (File.Exists(outputPath))
  179. {
  180. _fileSystem.DeleteFile(outputPath);
  181. }
  182. }
  183. catch (IOException ex)
  184. {
  185. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  186. }
  187. }
  188. else if (!File.Exists(outputPath))
  189. {
  190. failed = true;
  191. }
  192. if (failed)
  193. {
  194. var msg = $"ffmpeg attachment extraction failed for {inputPath} to {outputPath}";
  195. _logger.LogError(msg);
  196. throw new InvalidOperationException(msg);
  197. }
  198. else
  199. {
  200. _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", inputPath, outputPath);
  201. }
  202. }
  203. private string GetAttachmentCachePath(string mediaPath, MediaProtocol protocol, int attachmentStreamIndex)
  204. {
  205. string filename;
  206. if (protocol == MediaProtocol.File)
  207. {
  208. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  209. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D");
  210. }
  211. else
  212. {
  213. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D");
  214. }
  215. var prefix = filename.Substring(0, 1);
  216. return Path.Combine(_appPaths.DataPath, "attachments", prefix, filename);
  217. }
  218. /// <inheritdoc />
  219. public void Dispose()
  220. {
  221. Dispose(true);
  222. GC.SuppressFinalize(this);
  223. }
  224. /// <summary>
  225. /// Releases unmanaged and - optionally - managed resources.
  226. /// </summary>
  227. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  228. protected virtual void Dispose(bool disposing)
  229. {
  230. if (_disposed)
  231. {
  232. return;
  233. }
  234. if (disposing)
  235. {
  236. }
  237. _disposed = true;
  238. }
  239. }
  240. }