2
0

AttachmentExtractor.cs 9.7 KB

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