AttachmentExtractor.cs 10 KB

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