AttachmentExtractor.cs 9.9 KB

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