MediaEncoder.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.MediaEncoding;
  4. using MediaBrowser.Model.Entities;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Diagnostics;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.MediaEncoding.Encoder
  17. {
  18. /// <summary>
  19. /// Class MediaEncoder
  20. /// </summary>
  21. public class MediaEncoder : IMediaEncoder, IDisposable
  22. {
  23. /// <summary>
  24. /// The _logger
  25. /// </summary>
  26. private readonly ILogger _logger;
  27. /// <summary>
  28. /// The _app paths
  29. /// </summary>
  30. private readonly IApplicationPaths _appPaths;
  31. /// <summary>
  32. /// Gets the json serializer.
  33. /// </summary>
  34. /// <value>The json serializer.</value>
  35. private readonly IJsonSerializer _jsonSerializer;
  36. /// <summary>
  37. /// The video image resource pool
  38. /// </summary>
  39. private readonly SemaphoreSlim _videoImageResourcePool = new SemaphoreSlim(1, 1);
  40. /// <summary>
  41. /// The audio image resource pool
  42. /// </summary>
  43. private readonly SemaphoreSlim _audioImageResourcePool = new SemaphoreSlim(2, 2);
  44. /// <summary>
  45. /// The FF probe resource pool
  46. /// </summary>
  47. private readonly SemaphoreSlim _ffProbeResourcePool = new SemaphoreSlim(2, 2);
  48. private readonly IFileSystem _fileSystem;
  49. public string FFMpegPath { get; private set; }
  50. public string FFProbePath { get; private set; }
  51. public string Version { get; private set; }
  52. public MediaEncoder(ILogger logger, IApplicationPaths appPaths,
  53. IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, string version,
  54. IFileSystem fileSystem)
  55. {
  56. _logger = logger;
  57. _appPaths = appPaths;
  58. _jsonSerializer = jsonSerializer;
  59. Version = version;
  60. _fileSystem = fileSystem;
  61. FFProbePath = ffProbePath;
  62. FFMpegPath = ffMpegPath;
  63. }
  64. /// <summary>
  65. /// Gets the encoder path.
  66. /// </summary>
  67. /// <value>The encoder path.</value>
  68. public string EncoderPath
  69. {
  70. get { return FFMpegPath; }
  71. }
  72. /// <summary>
  73. /// The _semaphoreLocks
  74. /// </summary>
  75. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  76. new ConcurrentDictionary<string, SemaphoreSlim>();
  77. /// <summary>
  78. /// Gets the lock.
  79. /// </summary>
  80. /// <param name="filename">The filename.</param>
  81. /// <returns>System.Object.</returns>
  82. private SemaphoreSlim GetLock(string filename)
  83. {
  84. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  85. }
  86. /// <summary>
  87. /// Gets the media info.
  88. /// </summary>
  89. /// <param name="inputFiles">The input files.</param>
  90. /// <param name="type">The type.</param>
  91. /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
  92. /// <param name="cancellationToken">The cancellation token.</param>
  93. /// <returns>Task.</returns>
  94. public Task<InternalMediaInfoResult> GetMediaInfo(string[] inputFiles, InputType type, bool isAudio,
  95. CancellationToken cancellationToken)
  96. {
  97. return GetMediaInfoInternal(GetInputArgument(inputFiles, type), !isAudio,
  98. GetProbeSizeArgument(type), cancellationToken);
  99. }
  100. /// <summary>
  101. /// Gets the input argument.
  102. /// </summary>
  103. /// <param name="inputFiles">The input files.</param>
  104. /// <param name="type">The type.</param>
  105. /// <returns>System.String.</returns>
  106. /// <exception cref="System.ArgumentException">Unrecognized InputType</exception>
  107. public string GetInputArgument(string[] inputFiles, InputType type)
  108. {
  109. return EncodingUtils.GetInputArgument(inputFiles.ToList(), type == InputType.Url);
  110. }
  111. /// <summary>
  112. /// Gets the probe size argument.
  113. /// </summary>
  114. /// <param name="type">The type.</param>
  115. /// <returns>System.String.</returns>
  116. public string GetProbeSizeArgument(InputType type)
  117. {
  118. return EncodingUtils.GetProbeSizeArgument(type == InputType.Dvd);
  119. }
  120. /// <summary>
  121. /// Gets the media info internal.
  122. /// </summary>
  123. /// <param name="inputPath">The input path.</param>
  124. /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
  125. /// <param name="probeSizeArgument">The probe size argument.</param>
  126. /// <param name="cancellationToken">The cancellation token.</param>
  127. /// <returns>Task{MediaInfoResult}.</returns>
  128. /// <exception cref="System.ApplicationException"></exception>
  129. private async Task<InternalMediaInfoResult> GetMediaInfoInternal(string inputPath, bool extractChapters,
  130. string probeSizeArgument,
  131. CancellationToken cancellationToken)
  132. {
  133. var args = extractChapters
  134. ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
  135. : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";
  136. var process = new Process
  137. {
  138. StartInfo = new ProcessStartInfo
  139. {
  140. CreateNoWindow = true,
  141. UseShellExecute = false,
  142. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  143. RedirectStandardOutput = true,
  144. RedirectStandardError = true,
  145. FileName = FFProbePath,
  146. Arguments = string.Format(args,
  147. probeSizeArgument, inputPath).Trim(),
  148. WindowStyle = ProcessWindowStyle.Hidden,
  149. ErrorDialog = false
  150. },
  151. EnableRaisingEvents = true
  152. };
  153. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  154. process.Exited += ProcessExited;
  155. await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  156. InternalMediaInfoResult result;
  157. try
  158. {
  159. process.Start();
  160. }
  161. catch (Exception ex)
  162. {
  163. _ffProbeResourcePool.Release();
  164. _logger.ErrorException("Error starting ffprobe", ex);
  165. throw;
  166. }
  167. try
  168. {
  169. process.BeginErrorReadLine();
  170. result =
  171. _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);
  172. }
  173. catch
  174. {
  175. // Hate having to do this
  176. try
  177. {
  178. process.Kill();
  179. }
  180. catch (Exception ex1)
  181. {
  182. _logger.ErrorException("Error killing ffprobe", ex1);
  183. }
  184. throw;
  185. }
  186. finally
  187. {
  188. _ffProbeResourcePool.Release();
  189. }
  190. if (result == null)
  191. {
  192. throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
  193. }
  194. cancellationToken.ThrowIfCancellationRequested();
  195. if (result.streams != null)
  196. {
  197. // Normalize aspect ratio if invalid
  198. foreach (var stream in result.streams)
  199. {
  200. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  201. {
  202. stream.display_aspect_ratio = string.Empty;
  203. }
  204. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  205. {
  206. stream.sample_aspect_ratio = string.Empty;
  207. }
  208. }
  209. }
  210. return result;
  211. }
  212. /// <summary>
  213. /// The us culture
  214. /// </summary>
  215. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  216. /// <summary>
  217. /// Processes the exited.
  218. /// </summary>
  219. /// <param name="sender">The sender.</param>
  220. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  221. private void ProcessExited(object sender, EventArgs e)
  222. {
  223. ((Process)sender).Dispose();
  224. }
  225. /// <summary>
  226. /// Converts the text subtitle to ass.
  227. /// </summary>
  228. /// <param name="inputPath">The input path.</param>
  229. /// <param name="outputPath">The output path.</param>
  230. /// <param name="language">The language.</param>
  231. /// <param name="cancellationToken">The cancellation token.</param>
  232. /// <returns>Task.</returns>
  233. public async Task ConvertTextSubtitleToAss(string inputPath, string outputPath, string language,
  234. CancellationToken cancellationToken)
  235. {
  236. var semaphore = GetLock(outputPath);
  237. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  238. try
  239. {
  240. if (!File.Exists(outputPath))
  241. {
  242. await ConvertTextSubtitleToAssInternal(inputPath, outputPath, language).ConfigureAwait(false);
  243. }
  244. }
  245. finally
  246. {
  247. semaphore.Release();
  248. }
  249. }
  250. private const int FastSeekOffsetSeconds = 1;
  251. /// <summary>
  252. /// Converts the text subtitle to ass.
  253. /// </summary>
  254. /// <param name="inputPath">The input path.</param>
  255. /// <param name="outputPath">The output path.</param>
  256. /// <param name="language">The language.</param>
  257. /// <returns>Task.</returns>
  258. /// <exception cref="System.ArgumentNullException">inputPath
  259. /// or
  260. /// outputPath</exception>
  261. /// <exception cref="System.ApplicationException"></exception>
  262. private async Task ConvertTextSubtitleToAssInternal(string inputPath, string outputPath, string language)
  263. {
  264. if (string.IsNullOrEmpty(inputPath))
  265. {
  266. throw new ArgumentNullException("inputPath");
  267. }
  268. if (string.IsNullOrEmpty(outputPath))
  269. {
  270. throw new ArgumentNullException("outputPath");
  271. }
  272. var encodingParam = string.IsNullOrEmpty(language)
  273. ? string.Empty
  274. : GetSubtitleLanguageEncodingParam(language) + " ";
  275. var process = new Process
  276. {
  277. StartInfo = new ProcessStartInfo
  278. {
  279. RedirectStandardOutput = false,
  280. RedirectStandardError = true,
  281. CreateNoWindow = true,
  282. UseShellExecute = false,
  283. FileName = FFMpegPath,
  284. Arguments =
  285. string.Format("{0} -i \"{1}\" -c:s ass \"{2}\"", encodingParam, inputPath, outputPath),
  286. WindowStyle = ProcessWindowStyle.Hidden,
  287. ErrorDialog = false
  288. }
  289. };
  290. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  291. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt");
  292. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  293. var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
  294. true);
  295. try
  296. {
  297. process.Start();
  298. }
  299. catch (Exception ex)
  300. {
  301. logFileStream.Dispose();
  302. _logger.ErrorException("Error starting ffmpeg", ex);
  303. throw;
  304. }
  305. var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream);
  306. var ranToCompletion = process.WaitForExit(60000);
  307. if (!ranToCompletion)
  308. {
  309. try
  310. {
  311. _logger.Info("Killing ffmpeg subtitle conversion process");
  312. process.Kill();
  313. process.WaitForExit(1000);
  314. await logTask.ConfigureAwait(false);
  315. }
  316. catch (Exception ex)
  317. {
  318. _logger.ErrorException("Error killing subtitle conversion process", ex);
  319. }
  320. finally
  321. {
  322. logFileStream.Dispose();
  323. }
  324. }
  325. var exitCode = ranToCompletion ? process.ExitCode : -1;
  326. process.Dispose();
  327. var failed = false;
  328. if (exitCode == -1)
  329. {
  330. failed = true;
  331. if (File.Exists(outputPath))
  332. {
  333. try
  334. {
  335. _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
  336. File.Delete(outputPath);
  337. }
  338. catch (IOException ex)
  339. {
  340. _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
  341. }
  342. }
  343. }
  344. else if (!File.Exists(outputPath))
  345. {
  346. failed = true;
  347. }
  348. if (failed)
  349. {
  350. var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath);
  351. _logger.Error(msg);
  352. throw new ApplicationException(msg);
  353. }
  354. await SetAssFont(outputPath).ConfigureAwait(false);
  355. }
  356. protected string GetFastSeekCommandLineParameter(TimeSpan offset)
  357. {
  358. var seconds = offset.TotalSeconds - FastSeekOffsetSeconds;
  359. if (seconds > 0)
  360. {
  361. return string.Format("-ss {0} ", seconds.ToString(UsCulture));
  362. }
  363. return string.Empty;
  364. }
  365. protected string GetSlowSeekCommandLineParameter(TimeSpan offset)
  366. {
  367. if (offset.TotalSeconds - FastSeekOffsetSeconds > 0)
  368. {
  369. return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture));
  370. }
  371. return string.Empty;
  372. }
  373. /// <summary>
  374. /// Gets the subtitle language encoding param.
  375. /// </summary>
  376. /// <param name="language">The language.</param>
  377. /// <returns>System.String.</returns>
  378. private string GetSubtitleLanguageEncodingParam(string language)
  379. {
  380. switch (language.ToLower())
  381. {
  382. case "pol":
  383. case "cze":
  384. case "ces":
  385. case "slo":
  386. case "slk":
  387. case "hun":
  388. case "slv":
  389. case "srp":
  390. case "hrv":
  391. case "rum":
  392. case "ron":
  393. case "rup":
  394. case "alb":
  395. case "sqi":
  396. return "-sub_charenc windows-1250";
  397. case "ara":
  398. return "-sub_charenc windows-1256";
  399. case "heb":
  400. return "-sub_charenc windows-1255";
  401. case "grc":
  402. case "gre":
  403. return "-sub_charenc windows-1253";
  404. case "crh":
  405. case "ota":
  406. case "tur":
  407. return "-sub_charenc windows-1254";
  408. case "rus":
  409. return "-sub_charenc windows-1251";
  410. case "vie":
  411. return "-sub_charenc windows-1258";
  412. case "kor":
  413. return "-sub_charenc cp949";
  414. default:
  415. return "-sub_charenc windows-1252";
  416. }
  417. }
  418. /// <summary>
  419. /// Extracts the text subtitle.
  420. /// </summary>
  421. /// <param name="inputFiles">The input files.</param>
  422. /// <param name="type">The type.</param>
  423. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  424. /// <param name="copySubtitleStream">if set to true, copy stream instead of converting.</param>
  425. /// <param name="outputPath">The output path.</param>
  426. /// <param name="cancellationToken">The cancellation token.</param>
  427. /// <returns>Task.</returns>
  428. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  429. public async Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex,
  430. bool copySubtitleStream, string outputPath, CancellationToken cancellationToken)
  431. {
  432. var semaphore = GetLock(outputPath);
  433. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  434. try
  435. {
  436. if (!File.Exists(outputPath))
  437. {
  438. await
  439. ExtractTextSubtitleInternal(GetInputArgument(inputFiles, type), subtitleStreamIndex,
  440. copySubtitleStream, outputPath, cancellationToken).ConfigureAwait(false);
  441. }
  442. }
  443. finally
  444. {
  445. semaphore.Release();
  446. }
  447. }
  448. /// <summary>
  449. /// Extracts the text subtitle.
  450. /// </summary>
  451. /// <param name="inputPath">The input path.</param>
  452. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  453. /// <param name="copySubtitleStream">if set to true, copy stream instead of converting.</param>
  454. /// <param name="outputPath">The output path.</param>
  455. /// <param name="cancellationToken">The cancellation token.</param>
  456. /// <returns>Task.</returns>
  457. /// <exception cref="System.ArgumentNullException">inputPath
  458. /// or
  459. /// outputPath
  460. /// or
  461. /// cancellationToken</exception>
  462. /// <exception cref="System.ApplicationException"></exception>
  463. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex,
  464. bool copySubtitleStream, string outputPath, CancellationToken cancellationToken)
  465. {
  466. if (string.IsNullOrEmpty(inputPath))
  467. {
  468. throw new ArgumentNullException("inputPath");
  469. }
  470. if (string.IsNullOrEmpty(outputPath))
  471. {
  472. throw new ArgumentNullException("outputPath");
  473. }
  474. string processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s ass \"{2}\"", inputPath,
  475. subtitleStreamIndex, outputPath);
  476. if (copySubtitleStream)
  477. {
  478. processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s copy \"{2}\"", inputPath,
  479. subtitleStreamIndex, outputPath);
  480. }
  481. var process = new Process
  482. {
  483. StartInfo = new ProcessStartInfo
  484. {
  485. CreateNoWindow = true,
  486. UseShellExecute = false,
  487. RedirectStandardOutput = false,
  488. RedirectStandardError = true,
  489. FileName = FFMpegPath,
  490. Arguments = processArgs,
  491. WindowStyle = ProcessWindowStyle.Hidden,
  492. ErrorDialog = false
  493. }
  494. };
  495. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  496. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt");
  497. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  498. var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
  499. true);
  500. try
  501. {
  502. process.Start();
  503. }
  504. catch (Exception ex)
  505. {
  506. logFileStream.Dispose();
  507. _logger.ErrorException("Error starting ffmpeg", ex);
  508. throw;
  509. }
  510. process.StandardError.BaseStream.CopyToAsync(logFileStream);
  511. var ranToCompletion = process.WaitForExit(60000);
  512. if (!ranToCompletion)
  513. {
  514. try
  515. {
  516. _logger.Info("Killing ffmpeg subtitle extraction process");
  517. process.Kill();
  518. process.WaitForExit(1000);
  519. }
  520. catch (Exception ex)
  521. {
  522. _logger.ErrorException("Error killing subtitle extraction process", ex);
  523. }
  524. finally
  525. {
  526. logFileStream.Dispose();
  527. }
  528. }
  529. var exitCode = ranToCompletion ? process.ExitCode : -1;
  530. process.Dispose();
  531. var failed = false;
  532. if (exitCode == -1)
  533. {
  534. failed = true;
  535. if (File.Exists(outputPath))
  536. {
  537. try
  538. {
  539. _logger.Info("Deleting extracted subtitle due to failure: ", outputPath);
  540. File.Delete(outputPath);
  541. }
  542. catch (IOException ex)
  543. {
  544. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  545. }
  546. }
  547. }
  548. else if (!File.Exists(outputPath))
  549. {
  550. failed = true;
  551. }
  552. if (failed)
  553. {
  554. var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
  555. _logger.Error(msg);
  556. throw new ApplicationException(msg);
  557. }
  558. else
  559. {
  560. var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
  561. _logger.Info(msg);
  562. }
  563. await SetAssFont(outputPath).ConfigureAwait(false);
  564. }
  565. /// <summary>
  566. /// Sets the ass font.
  567. /// </summary>
  568. /// <param name="file">The file.</param>
  569. /// <returns>Task.</returns>
  570. private async Task SetAssFont(string file)
  571. {
  572. _logger.Info("Setting ass font within {0}", file);
  573. string text;
  574. Encoding encoding;
  575. using (var reader = new StreamReader(file, detectEncodingFromByteOrderMarks: true))
  576. {
  577. encoding = reader.CurrentEncoding;
  578. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  579. }
  580. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  581. if (!string.Equals(text, newText))
  582. {
  583. using (var writer = new StreamWriter(file, false, encoding))
  584. {
  585. writer.Write(newText);
  586. }
  587. }
  588. }
  589. public Task<Stream> ExtractAudioImage(string path, CancellationToken cancellationToken)
  590. {
  591. return ExtractImage(new[] { path }, InputType.File, true, null, null, cancellationToken);
  592. }
  593. public Task<Stream> ExtractVideoImage(string[] inputFiles, InputType type, Video3DFormat? threedFormat,
  594. TimeSpan? offset, CancellationToken cancellationToken)
  595. {
  596. return ExtractImage(inputFiles, type, false, threedFormat, offset, cancellationToken);
  597. }
  598. private async Task<Stream> ExtractImage(string[] inputFiles, InputType type, bool isAudio,
  599. Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  600. {
  601. var resourcePool = isAudio ? _audioImageResourcePool : _videoImageResourcePool;
  602. var inputArgument = GetInputArgument(inputFiles, type);
  603. if (!isAudio)
  604. {
  605. try
  606. {
  607. return await ExtractImageInternal(inputArgument, type, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false);
  608. }
  609. catch
  610. {
  611. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  612. }
  613. }
  614. return await ExtractImageInternal(inputArgument, type, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false);
  615. }
  616. private async Task<Stream> ExtractImageInternal(string inputPath, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  617. {
  618. if (string.IsNullOrEmpty(inputPath))
  619. {
  620. throw new ArgumentNullException("inputPath");
  621. }
  622. // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600.
  623. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
  624. var vf = "scale=600:trunc(600/dar/2)*2";
  625. //crop=min(iw\,ih*dar):min(ih\,iw/dar):(iw-min(iw\,iw*sar))/2:(ih - min (ih\,ih/sar))/2,scale=600:(600/dar),thumbnail" -f image2
  626. if (threedFormat.HasValue)
  627. {
  628. switch (threedFormat.Value)
  629. {
  630. case Video3DFormat.HalfSideBySide:
  631. vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
  632. // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
  633. break;
  634. case Video3DFormat.FullSideBySide:
  635. vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
  636. //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
  637. break;
  638. case Video3DFormat.HalfTopAndBottom:
  639. vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
  640. //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600
  641. break;
  642. case Video3DFormat.FullTopAndBottom:
  643. vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
  644. // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
  645. break;
  646. }
  647. }
  648. // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case.
  649. var args = useIFrame ? string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2},thumbnail=80\" -f image2 \"{1}\"", inputPath, "-", vf) :
  650. string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf);
  651. var probeSize = GetProbeSizeArgument(type);
  652. if (!string.IsNullOrEmpty(probeSize))
  653. {
  654. args = probeSize + " " + args;
  655. }
  656. if (offset.HasValue)
  657. {
  658. args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)).ToString(UsCulture) + args;
  659. }
  660. var process = new Process
  661. {
  662. StartInfo = new ProcessStartInfo
  663. {
  664. CreateNoWindow = true,
  665. UseShellExecute = false,
  666. FileName = FFMpegPath,
  667. Arguments = args,
  668. WindowStyle = ProcessWindowStyle.Hidden,
  669. ErrorDialog = false,
  670. RedirectStandardOutput = true,
  671. RedirectStandardError = true
  672. }
  673. };
  674. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  675. process.Start();
  676. var memoryStream = new MemoryStream();
  677. #pragma warning disable 4014
  678. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  679. process.StandardOutput.BaseStream.CopyToAsync(memoryStream);
  680. #pragma warning restore 4014
  681. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  682. process.BeginErrorReadLine();
  683. var ranToCompletion = process.WaitForExit(10000);
  684. if (!ranToCompletion)
  685. {
  686. try
  687. {
  688. _logger.Info("Killing ffmpeg process");
  689. process.Kill();
  690. process.WaitForExit(1000);
  691. }
  692. catch (Exception ex)
  693. {
  694. _logger.ErrorException("Error killing process", ex);
  695. }
  696. }
  697. resourcePool.Release();
  698. var exitCode = ranToCompletion ? process.ExitCode : -1;
  699. process.Dispose();
  700. if (exitCode == -1 || memoryStream.Length == 0)
  701. {
  702. memoryStream.Dispose();
  703. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  704. _logger.Error(msg);
  705. throw new ApplicationException(msg);
  706. }
  707. memoryStream.Position = 0;
  708. return memoryStream;
  709. }
  710. public Task<Stream> EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken)
  711. {
  712. return new ImageEncoder(FFMpegPath, _logger, _fileSystem, _appPaths).EncodeImage(options, cancellationToken);
  713. }
  714. /// <summary>
  715. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  716. /// </summary>
  717. public void Dispose()
  718. {
  719. Dispose(true);
  720. }
  721. /// <summary>
  722. /// Releases unmanaged and - optionally - managed resources.
  723. /// </summary>
  724. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  725. protected virtual void Dispose(bool dispose)
  726. {
  727. if (dispose)
  728. {
  729. _videoImageResourcePool.Dispose();
  730. }
  731. }
  732. }
  733. }