AttachmentExtractor.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. ILogger<AttachmentExtractor> logger,
  37. IApplicationPaths appPaths,
  38. IFileSystem fileSystem,
  39. IMediaEncoder mediaEncoder,
  40. IMediaSourceManager mediaSourceManager,
  41. IProcessFactory processFactory)
  42. {
  43. _libraryManager = libraryManager;
  44. _logger = logger;
  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. var mediaSource = mediaSources
  64. .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  65. if (mediaSource == null)
  66. {
  67. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} not found");
  68. }
  69. var mediaAttachment = mediaSource.MediaAttachments
  70. .FirstOrDefault(i => i.Index == attachmentStreamIndex);
  71. if (mediaAttachment == null)
  72. {
  73. throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {attachmentStreamIndex}");
  74. }
  75. var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
  76. .ConfigureAwait(false);
  77. return (mediaAttachment, attachmentStream);
  78. }
  79. private async Task<Stream> GetAttachmentStream(
  80. MediaSourceInfo mediaSource,
  81. MediaAttachment mediaAttachment,
  82. CancellationToken cancellationToken)
  83. {
  84. var inputFiles = new[] { mediaSource.Path };
  85. var attachmentPath = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, mediaAttachment, cancellationToken).ConfigureAwait(false);
  86. var stream = await GetAttachmentStream(attachmentPath, cancellationToken).ConfigureAwait(false);
  87. return stream;
  88. }
  89. private async Task<Stream> GetAttachmentStream(
  90. string path,
  91. CancellationToken cancellationToken)
  92. {
  93. return File.OpenRead(path);
  94. }
  95. private async Task<String> GetReadableFile(
  96. string mediaPath,
  97. string[] inputFiles,
  98. MediaProtocol protocol,
  99. MediaAttachment mediaAttachment,
  100. CancellationToken cancellationToken)
  101. {
  102. var outputPath = GetAttachmentCachePath(mediaPath, protocol, mediaAttachment.Index);
  103. await ExtractAttachment(inputFiles, protocol, mediaAttachment.Index, outputPath, cancellationToken)
  104. .ConfigureAwait(false);
  105. return outputPath;
  106. }
  107. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  108. new ConcurrentDictionary<string, SemaphoreSlim>();
  109. private SemaphoreSlim GetLock(string filename)
  110. {
  111. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  112. }
  113. private async Task ExtractAttachment(
  114. string[] inputFiles,
  115. MediaProtocol protocol,
  116. int attachmentStreamIndex,
  117. string outputPath,
  118. CancellationToken cancellationToken)
  119. {
  120. var semaphore = GetLock(outputPath);
  121. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  122. try
  123. {
  124. if (!File.Exists(outputPath))
  125. {
  126. await ExtractAttachmentInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), attachmentStreamIndex, outputPath, cancellationToken).ConfigureAwait(false);
  127. }
  128. }
  129. finally
  130. {
  131. semaphore.Release();
  132. }
  133. }
  134. private async Task ExtractAttachmentInternal(
  135. string inputPath,
  136. int attachmentStreamIndex,
  137. string outputPath,
  138. CancellationToken cancellationToken)
  139. {
  140. if (string.IsNullOrEmpty(inputPath))
  141. {
  142. throw new ArgumentNullException(nameof(inputPath));
  143. }
  144. if (string.IsNullOrEmpty(outputPath))
  145. {
  146. throw new ArgumentNullException(nameof(outputPath));
  147. }
  148. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  149. var processArgs = string.Format(
  150. CultureInfo.InvariantCulture,
  151. "-dump_attachment:{1} {2} -i {0} -t 0 -f null null",
  152. inputPath,
  153. attachmentStreamIndex,
  154. outputPath);
  155. var process = _processFactory.Create(new ProcessOptions
  156. {
  157. CreateNoWindow = true,
  158. UseShellExecute = false,
  159. EnableRaisingEvents = true,
  160. FileName = _mediaEncoder.EncoderPath,
  161. Arguments = processArgs,
  162. IsHidden = true,
  163. ErrorDialog = false
  164. });
  165. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  166. try
  167. {
  168. process.Start();
  169. }
  170. catch (Exception ex)
  171. {
  172. _logger.LogError(ex, "Error starting ffmpeg");
  173. throw;
  174. }
  175. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  176. if (!ranToCompletion)
  177. {
  178. try
  179. {
  180. _logger.LogWarning("Killing ffmpeg attachment extraction process");
  181. process.Kill();
  182. }
  183. catch (Exception ex)
  184. {
  185. _logger.LogError(ex, "Error killing attachment extraction process");
  186. }
  187. }
  188. var exitCode = ranToCompletion ? process.ExitCode : -1;
  189. process.Dispose();
  190. var failed = false;
  191. if (exitCode != 0)
  192. {
  193. failed = true;
  194. _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
  195. try
  196. {
  197. if (File.Exists(outputPath))
  198. {
  199. _fileSystem.DeleteFile(outputPath);
  200. }
  201. }
  202. catch (IOException ex)
  203. {
  204. _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
  205. }
  206. }
  207. else if (!File.Exists(outputPath))
  208. {
  209. failed = true;
  210. }
  211. if (failed)
  212. {
  213. var msg = $"ffmpeg attachment extraction failed for {inputPath} to {outputPath}";
  214. _logger.LogError(msg);
  215. throw new Exception(msg);
  216. }
  217. else
  218. {
  219. _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", inputPath, outputPath);
  220. }
  221. }
  222. private string GetAttachmentCachePath(string mediaPath, MediaProtocol protocol, int attachmentStreamIndex)
  223. {
  224. string filename;
  225. if (protocol == MediaProtocol.File)
  226. {
  227. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  228. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D");
  229. }
  230. else
  231. {
  232. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D");
  233. }
  234. var prefix = filename.Substring(0, 1);
  235. return Path.Combine(AttachmentCachePath, prefix, filename);
  236. }
  237. }
  238. }