AttachmentExtractor.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, mediaAttachment, cancellationToken).ConfigureAwait(false);
  94. var stream = await GetAttachmentStream(fileInfo.Path, fileInfo.Protocol, cancellationToken).ConfigureAwait(false);
  95. return stream;
  96. }
  97. private async Task<Stream> GetAttachmentStream(
  98. string path,
  99. MediaProtocol protocol,
  100. CancellationToken cancellationToken)
  101. {
  102. return File.OpenRead(path);
  103. }
  104. private async Task<AttachmentInfo> GetReadableFile(
  105. string mediaPath,
  106. string[] inputFiles,
  107. MediaProtocol protocol,
  108. MediaAttachment mediaAttachment,
  109. CancellationToken cancellationToken)
  110. {
  111. var outputPath = GetAttachmentCachePath(mediaPath, protocol, mediaAttachment.Index);
  112. await ExtractAttachment(inputFiles, protocol, mediaAttachment.Index, outputPath, cancellationToken)
  113. .ConfigureAwait(false);
  114. return new AttachmentInfo(outputPath, MediaProtocol.File);
  115. }
  116. private struct AttachmentInfo
  117. {
  118. public AttachmentInfo(string path, MediaProtocol protocol)
  119. {
  120. Path = path;
  121. Protocol = protocol;
  122. }
  123. public string Path { get; set; }
  124. public MediaProtocol Protocol { get; set; }
  125. }
  126. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  127. new ConcurrentDictionary<string, SemaphoreSlim>();
  128. private SemaphoreSlim GetLock(string filename)
  129. {
  130. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  131. }
  132. private async Task ExtractAttachment(
  133. string[] inputFiles,
  134. MediaProtocol protocol,
  135. int attachmentStreamIndex,
  136. string outputPath,
  137. CancellationToken cancellationToken)
  138. {
  139. var semaphore = GetLock(outputPath);
  140. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  141. try
  142. {
  143. if (!File.Exists(outputPath))
  144. {
  145. await ExtractAttachmentInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), attachmentStreamIndex, outputPath, cancellationToken).ConfigureAwait(false);
  146. }
  147. }
  148. finally
  149. {
  150. semaphore.Release();
  151. }
  152. }
  153. private async Task ExtractAttachmentInternal(
  154. string inputPath,
  155. int attachmentStreamIndex,
  156. string outputPath,
  157. CancellationToken cancellationToken)
  158. {
  159. if (string.IsNullOrEmpty(inputPath))
  160. {
  161. throw new ArgumentNullException(nameof(inputPath));
  162. }
  163. if (string.IsNullOrEmpty(outputPath))
  164. {
  165. throw new ArgumentNullException(nameof(outputPath));
  166. }
  167. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  168. var processArgs = string.Format("-dump_attachment:{1} {2} -i {0} -t 0 -f null null", inputPath, attachmentStreamIndex, outputPath);
  169. var process = _processFactory.Create(new ProcessOptions
  170. {
  171. CreateNoWindow = true,
  172. UseShellExecute = false,
  173. EnableRaisingEvents = true,
  174. FileName = _mediaEncoder.EncoderPath,
  175. Arguments = processArgs,
  176. IsHidden = true,
  177. ErrorDialog = false
  178. });
  179. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  180. try
  181. {
  182. process.Start();
  183. }
  184. catch (Exception ex)
  185. {
  186. _logger.LogError(ex, "Error starting ffmpeg");
  187. throw;
  188. }
  189. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  190. if (!ranToCompletion)
  191. {
  192. try
  193. {
  194. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  195. process.Kill();
  196. }
  197. catch (Exception ex)
  198. {
  199. _logger.LogError(ex, "Error killing attachment extraction process");
  200. }
  201. }
  202. var exitCode = ranToCompletion ? process.ExitCode : -1;
  203. process.Dispose();
  204. var failed = false;
  205. if (exitCode != 0)
  206. {
  207. failed = true;
  208. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  209. try
  210. {
  211. _fileSystem.DeleteFile(outputPath);
  212. }
  213. catch (FileNotFoundException)
  214. {
  215. }
  216. catch (IOException ex)
  217. {
  218. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  219. }
  220. }
  221. else if (!File.Exists(outputPath))
  222. {
  223. failed = true;
  224. }
  225. if (failed)
  226. {
  227. var msg = $"ffmpeg attachment extraction failed for {inputPath} to {outputPath}";
  228. _logger.LogError(msg);
  229. throw new Exception(msg);
  230. }
  231. else
  232. {
  233. _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", inputPath, outputPath);
  234. }
  235. }
  236. private string GetAttachmentCachePath(string mediaPath, MediaProtocol protocol, int attachmentStreamIndex)
  237. {
  238. String filename;
  239. if (protocol == MediaProtocol.File)
  240. {
  241. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  242. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D");
  243. }
  244. else
  245. {
  246. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D");
  247. }
  248. var prefix = filename.Substring(0, 1);
  249. return Path.Combine(AttachmentCachePath, prefix, filename);
  250. }
  251. }
  252. }