AttachmentExtractor.cs 9.8 KB

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