MediaEncoder.cs 33 KB

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