MediaEncoder.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.MediaInfo;
  4. using MediaBrowser.Model.Entities;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.ComponentModel;
  10. using System.Diagnostics;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Server.Implementations.MediaEncoder
  18. {
  19. /// <summary>
  20. /// Class MediaEncoder
  21. /// </summary>
  22. public class MediaEncoder : IMediaEncoder, IDisposable
  23. {
  24. /// <summary>
  25. /// The _logger
  26. /// </summary>
  27. private readonly ILogger _logger;
  28. /// <summary>
  29. /// The _app paths
  30. /// </summary>
  31. private readonly IApplicationPaths _appPaths;
  32. /// <summary>
  33. /// Gets the json serializer.
  34. /// </summary>
  35. /// <value>The json serializer.</value>
  36. private readonly IJsonSerializer _jsonSerializer;
  37. /// <summary>
  38. /// The video image resource pool
  39. /// </summary>
  40. private readonly SemaphoreSlim _videoImageResourcePool = new SemaphoreSlim(1, 1);
  41. /// <summary>
  42. /// The audio image resource pool
  43. /// </summary>
  44. private readonly SemaphoreSlim _audioImageResourcePool = new SemaphoreSlim(1, 1);
  45. /// <summary>
  46. /// The _subtitle extraction resource pool
  47. /// </summary>
  48. private readonly SemaphoreSlim _subtitleExtractionResourcePool = new SemaphoreSlim(2, 2);
  49. /// <summary>
  50. /// The FF probe resource pool
  51. /// </summary>
  52. private readonly SemaphoreSlim _ffProbeResourcePool = new SemaphoreSlim(1, 1);
  53. public string FFMpegPath { get; private set; }
  54. public string FFProbePath { get; private set; }
  55. public string Version { get; private set; }
  56. public MediaEncoder(ILogger logger, IApplicationPaths appPaths,
  57. IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, string version)
  58. {
  59. _logger = logger;
  60. _appPaths = appPaths;
  61. _jsonSerializer = jsonSerializer;
  62. Version = version;
  63. FFProbePath = ffProbePath;
  64. FFMpegPath = ffMpegPath;
  65. }
  66. /// <summary>
  67. /// Gets the encoder path.
  68. /// </summary>
  69. /// <value>The encoder path.</value>
  70. public string EncoderPath
  71. {
  72. get { return FFMpegPath; }
  73. }
  74. /// <summary>
  75. /// Gets the media info.
  76. /// </summary>
  77. /// <param name="inputFiles">The input files.</param>
  78. /// <param name="type">The type.</param>
  79. /// <param name="cancellationToken">The cancellation token.</param>
  80. /// <returns>Task.</returns>
  81. public Task<MediaInfoResult> GetMediaInfo(string[] inputFiles, InputType type,
  82. CancellationToken cancellationToken)
  83. {
  84. return GetMediaInfoInternal(GetInputArgument(inputFiles, type), type != InputType.AudioFile,
  85. GetProbeSizeArgument(type), cancellationToken);
  86. }
  87. /// <summary>
  88. /// Gets the input argument.
  89. /// </summary>
  90. /// <param name="inputFiles">The input files.</param>
  91. /// <param name="type">The type.</param>
  92. /// <returns>System.String.</returns>
  93. /// <exception cref="System.ArgumentException">Unrecognized InputType</exception>
  94. public string GetInputArgument(string[] inputFiles, InputType type)
  95. {
  96. string inputPath;
  97. switch (type)
  98. {
  99. case InputType.Dvd:
  100. case InputType.VideoFile:
  101. case InputType.AudioFile:
  102. inputPath = GetConcatInputArgument(inputFiles);
  103. break;
  104. case InputType.Bluray:
  105. inputPath = GetBlurayInputArgument(inputFiles[0]);
  106. break;
  107. case InputType.Url:
  108. inputPath = GetHttpInputArgument(inputFiles);
  109. break;
  110. default:
  111. throw new ArgumentException("Unrecognized InputType");
  112. }
  113. return inputPath;
  114. }
  115. /// <summary>
  116. /// Gets the HTTP input argument.
  117. /// </summary>
  118. /// <param name="inputFiles">The input files.</param>
  119. /// <returns>System.String.</returns>
  120. private string GetHttpInputArgument(string[] inputFiles)
  121. {
  122. var url = inputFiles[0];
  123. return string.Format("\"{0}\"", url);
  124. }
  125. /// <summary>
  126. /// Gets the probe size argument.
  127. /// </summary>
  128. /// <param name="type">The type.</param>
  129. /// <returns>System.String.</returns>
  130. public string GetProbeSizeArgument(InputType type)
  131. {
  132. return type == InputType.Dvd ? "-probesize 1G -analyzeduration 200M" : string.Empty;
  133. }
  134. /// <summary>
  135. /// Gets the media info internal.
  136. /// </summary>
  137. /// <param name="inputPath">The input path.</param>
  138. /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
  139. /// <param name="probeSizeArgument">The probe size argument.</param>
  140. /// <param name="cancellationToken">The cancellation token.</param>
  141. /// <returns>Task{MediaInfoResult}.</returns>
  142. /// <exception cref="System.ApplicationException"></exception>
  143. private async Task<MediaInfoResult> GetMediaInfoInternal(string inputPath, bool extractChapters,
  144. string probeSizeArgument,
  145. CancellationToken cancellationToken)
  146. {
  147. var process = new Process
  148. {
  149. StartInfo = new ProcessStartInfo
  150. {
  151. CreateNoWindow = true,
  152. UseShellExecute = false,
  153. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  154. RedirectStandardOutput = true,
  155. RedirectStandardError = true,
  156. FileName = FFProbePath,
  157. Arguments =
  158. string.Format(
  159. "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format",
  160. probeSizeArgument, inputPath).Trim(),
  161. WindowStyle = ProcessWindowStyle.Hidden,
  162. ErrorDialog = false
  163. },
  164. EnableRaisingEvents = true
  165. };
  166. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  167. process.Exited += ProcessExited;
  168. await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  169. MediaInfoResult result;
  170. string standardError = null;
  171. try
  172. {
  173. process.Start();
  174. }
  175. catch (Exception ex)
  176. {
  177. _ffProbeResourcePool.Release();
  178. _logger.ErrorException("Error starting ffprobe", ex);
  179. throw;
  180. }
  181. try
  182. {
  183. Task<string> standardErrorReadTask = null;
  184. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  185. if (extractChapters)
  186. {
  187. standardErrorReadTask = process.StandardError.ReadToEndAsync();
  188. }
  189. else
  190. {
  191. process.BeginErrorReadLine();
  192. }
  193. result = _jsonSerializer.DeserializeFromStream<MediaInfoResult>(process.StandardOutput.BaseStream);
  194. if (extractChapters)
  195. {
  196. standardError = await standardErrorReadTask.ConfigureAwait(false);
  197. }
  198. }
  199. catch
  200. {
  201. // Hate having to do this
  202. try
  203. {
  204. process.Kill();
  205. }
  206. catch (InvalidOperationException ex1)
  207. {
  208. _logger.ErrorException("Error killing ffprobe", ex1);
  209. }
  210. catch (Win32Exception ex1)
  211. {
  212. _logger.ErrorException("Error killing ffprobe", ex1);
  213. }
  214. throw;
  215. }
  216. finally
  217. {
  218. _ffProbeResourcePool.Release();
  219. }
  220. if (result == null)
  221. {
  222. throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
  223. }
  224. cancellationToken.ThrowIfCancellationRequested();
  225. if (result.streams != null)
  226. {
  227. // Normalize aspect ratio if invalid
  228. foreach (var stream in result.streams)
  229. {
  230. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  231. {
  232. stream.display_aspect_ratio = string.Empty;
  233. }
  234. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  235. {
  236. stream.sample_aspect_ratio = string.Empty;
  237. }
  238. }
  239. }
  240. if (extractChapters && !string.IsNullOrEmpty(standardError))
  241. {
  242. AddChapters(result, standardError);
  243. }
  244. return result;
  245. }
  246. /// <summary>
  247. /// The us culture
  248. /// </summary>
  249. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  250. /// <summary>
  251. /// Adds the chapters.
  252. /// </summary>
  253. /// <param name="result">The result.</param>
  254. /// <param name="standardError">The standard error.</param>
  255. private void AddChapters(MediaInfoResult result, string standardError)
  256. {
  257. var lines = standardError.Split('\n').Select(l => l.TrimStart());
  258. var chapters = new List<ChapterInfo>();
  259. ChapterInfo lastChapter = null;
  260. foreach (var line in lines)
  261. {
  262. if (line.StartsWith("Chapter", StringComparison.OrdinalIgnoreCase))
  263. {
  264. // Example:
  265. // Chapter #0.2: start 400.534, end 4565.435
  266. const string srch = "start ";
  267. var start = line.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  268. if (start == -1)
  269. {
  270. continue;
  271. }
  272. var subString = line.Substring(start + srch.Length);
  273. subString = subString.Substring(0, subString.IndexOf(','));
  274. double seconds;
  275. if (double.TryParse(subString, NumberStyles.Any, UsCulture, out seconds))
  276. {
  277. lastChapter = new ChapterInfo
  278. {
  279. StartPositionTicks = TimeSpan.FromSeconds(seconds).Ticks
  280. };
  281. chapters.Add(lastChapter);
  282. }
  283. }
  284. else if (line.StartsWith("title", StringComparison.OrdinalIgnoreCase))
  285. {
  286. if (lastChapter != null && string.IsNullOrEmpty(lastChapter.Name))
  287. {
  288. var index = line.IndexOf(':');
  289. if (index != -1)
  290. {
  291. lastChapter.Name = line.Substring(index + 1).Trim().TrimEnd('\r');
  292. }
  293. }
  294. }
  295. }
  296. result.Chapters = chapters;
  297. }
  298. /// <summary>
  299. /// Processes the exited.
  300. /// </summary>
  301. /// <param name="sender">The sender.</param>
  302. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  303. private void ProcessExited(object sender, EventArgs e)
  304. {
  305. ((Process)sender).Dispose();
  306. }
  307. /// <summary>
  308. /// Converts the text subtitle to ass.
  309. /// </summary>
  310. /// <param name="inputPath">The input path.</param>
  311. /// <param name="outputPath">The output path.</param>
  312. /// <param name="language">The language.</param>
  313. /// <param name="offset">The offset.</param>
  314. /// <param name="cancellationToken">The cancellation token.</param>
  315. /// <returns>Task.</returns>
  316. /// <exception cref="System.ArgumentNullException">inputPath
  317. /// or
  318. /// outputPath</exception>
  319. /// <exception cref="System.ApplicationException"></exception>
  320. public async Task ConvertTextSubtitleToAss(string inputPath, string outputPath, string language, TimeSpan offset,
  321. CancellationToken cancellationToken)
  322. {
  323. if (string.IsNullOrEmpty(inputPath))
  324. {
  325. throw new ArgumentNullException("inputPath");
  326. }
  327. if (string.IsNullOrEmpty(outputPath))
  328. {
  329. throw new ArgumentNullException("outputPath");
  330. }
  331. var slowSeekParam = offset.TotalSeconds > 0 ? " -ss " + offset.TotalSeconds.ToString(UsCulture) : string.Empty;
  332. var encodingParam = string.IsNullOrEmpty(language) ? string.Empty :
  333. GetSubtitleLanguageEncodingParam(language) + " ";
  334. var process = new Process
  335. {
  336. StartInfo = new ProcessStartInfo
  337. {
  338. RedirectStandardOutput = false,
  339. RedirectStandardError = true,
  340. CreateNoWindow = true,
  341. UseShellExecute = false,
  342. FileName = FFMpegPath,
  343. Arguments =
  344. string.Format("{0}-i \"{1}\"{2} \"{3}\"", encodingParam, inputPath, slowSeekParam,
  345. outputPath),
  346. WindowStyle = ProcessWindowStyle.Hidden,
  347. ErrorDialog = false
  348. }
  349. };
  350. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  351. await _subtitleExtractionResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  352. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt");
  353. var logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
  354. StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  355. try
  356. {
  357. process.Start();
  358. }
  359. catch (Exception ex)
  360. {
  361. _subtitleExtractionResourcePool.Release();
  362. logFileStream.Dispose();
  363. _logger.ErrorException("Error starting ffmpeg", ex);
  364. throw;
  365. }
  366. var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream);
  367. var ranToCompletion = process.WaitForExit(60000);
  368. if (!ranToCompletion)
  369. {
  370. try
  371. {
  372. _logger.Info("Killing ffmpeg process");
  373. process.Kill();
  374. process.WaitForExit(1000);
  375. await logTask.ConfigureAwait(false);
  376. }
  377. catch (Win32Exception ex)
  378. {
  379. _logger.ErrorException("Error killing process", ex);
  380. }
  381. catch (InvalidOperationException ex)
  382. {
  383. _logger.ErrorException("Error killing process", ex);
  384. }
  385. catch (NotSupportedException ex)
  386. {
  387. _logger.ErrorException("Error killing process", ex);
  388. }
  389. finally
  390. {
  391. logFileStream.Dispose();
  392. _subtitleExtractionResourcePool.Release();
  393. }
  394. }
  395. var exitCode = ranToCompletion ? process.ExitCode : -1;
  396. process.Dispose();
  397. var failed = false;
  398. if (exitCode == -1)
  399. {
  400. failed = true;
  401. if (File.Exists(outputPath))
  402. {
  403. try
  404. {
  405. _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
  406. File.Delete(outputPath);
  407. }
  408. catch (IOException ex)
  409. {
  410. _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
  411. }
  412. }
  413. }
  414. else if (!File.Exists(outputPath))
  415. {
  416. failed = true;
  417. }
  418. if (failed)
  419. {
  420. var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath);
  421. _logger.Error(msg);
  422. throw new ApplicationException(msg);
  423. }
  424. await SetAssFont(outputPath).ConfigureAwait(false);
  425. }
  426. /// <summary>
  427. /// Gets the subtitle language encoding param.
  428. /// </summary>
  429. /// <param name="language">The language.</param>
  430. /// <returns>System.String.</returns>
  431. private string GetSubtitleLanguageEncodingParam(string language)
  432. {
  433. switch (language.ToLower())
  434. {
  435. case "pol":
  436. case "cze":
  437. case "ces":
  438. case "slo":
  439. case "slk":
  440. case "hun":
  441. case "slv":
  442. case "srp":
  443. case "hrv":
  444. case "rum":
  445. case "ron":
  446. case "rup":
  447. case "alb":
  448. case "sqi":
  449. return "-sub_charenc windows-1250";
  450. case "ara":
  451. return "-sub_charenc windows-1256";
  452. case "heb":
  453. return "-sub_charenc windows-1255";
  454. case "grc":
  455. case "gre":
  456. return "-sub_charenc windows-1253";
  457. case "crh":
  458. case "ota":
  459. case "tur":
  460. return "-sub_charenc windows-1254";
  461. case "rus":
  462. return "-sub_charenc windows-1251";
  463. case "vie":
  464. return "-sub_charenc windows-1258";
  465. default:
  466. return "-sub_charenc windows-1252";
  467. }
  468. }
  469. /// <summary>
  470. /// Extracts the text subtitle.
  471. /// </summary>
  472. /// <param name="inputFiles">The input files.</param>
  473. /// <param name="type">The type.</param>
  474. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  475. /// <param name="offset">The offset.</param>
  476. /// <param name="outputPath">The output path.</param>
  477. /// <param name="cancellationToken">The cancellation token.</param>
  478. /// <returns>Task.</returns>
  479. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  480. public Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  481. {
  482. return ExtractTextSubtitleInternal(GetInputArgument(inputFiles, type), subtitleStreamIndex, offset, outputPath, cancellationToken);
  483. }
  484. /// <summary>
  485. /// Extracts the text subtitle.
  486. /// </summary>
  487. /// <param name="inputPath">The input path.</param>
  488. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  489. /// <param name="offset">The offset.</param>
  490. /// <param name="outputPath">The output path.</param>
  491. /// <param name="cancellationToken">The cancellation token.</param>
  492. /// <returns>Task.</returns>
  493. /// <exception cref="System.ArgumentNullException">inputPath
  494. /// or
  495. /// outputPath
  496. /// or
  497. /// cancellationToken</exception>
  498. /// <exception cref="System.ApplicationException"></exception>
  499. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  500. {
  501. if (string.IsNullOrEmpty(inputPath))
  502. {
  503. throw new ArgumentNullException("inputPath");
  504. }
  505. if (string.IsNullOrEmpty(outputPath))
  506. {
  507. throw new ArgumentNullException("outputPath");
  508. }
  509. if (cancellationToken == null)
  510. {
  511. throw new ArgumentNullException("cancellationToken");
  512. }
  513. var slowSeekParam = offset.TotalSeconds > 0 ? " -ss " + offset.TotalSeconds.ToString(UsCulture) : string.Empty;
  514. var process = new Process
  515. {
  516. StartInfo = new ProcessStartInfo
  517. {
  518. CreateNoWindow = true,
  519. UseShellExecute = false,
  520. RedirectStandardOutput = false,
  521. RedirectStandardError = true,
  522. FileName = FFMpegPath,
  523. Arguments = string.Format("-i {0}{1} -map 0:{2} -an -vn -c:s ass \"{3}\"", inputPath, slowSeekParam, subtitleStreamIndex, outputPath),
  524. WindowStyle = ProcessWindowStyle.Hidden,
  525. ErrorDialog = false
  526. }
  527. };
  528. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  529. await _subtitleExtractionResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  530. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt");
  531. var logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  532. try
  533. {
  534. process.Start();
  535. }
  536. catch (Exception ex)
  537. {
  538. _subtitleExtractionResourcePool.Release();
  539. logFileStream.Dispose();
  540. _logger.ErrorException("Error starting ffmpeg", ex);
  541. throw;
  542. }
  543. process.StandardError.BaseStream.CopyToAsync(logFileStream);
  544. var ranToCompletion = process.WaitForExit(60000);
  545. if (!ranToCompletion)
  546. {
  547. try
  548. {
  549. _logger.Info("Killing ffmpeg process");
  550. process.Kill();
  551. process.WaitForExit(1000);
  552. }
  553. catch (Win32Exception ex)
  554. {
  555. _logger.ErrorException("Error killing process", ex);
  556. }
  557. catch (InvalidOperationException ex)
  558. {
  559. _logger.ErrorException("Error killing process", ex);
  560. }
  561. catch (NotSupportedException ex)
  562. {
  563. _logger.ErrorException("Error killing process", ex);
  564. }
  565. finally
  566. {
  567. logFileStream.Dispose();
  568. _subtitleExtractionResourcePool.Release();
  569. }
  570. }
  571. var exitCode = ranToCompletion ? process.ExitCode : -1;
  572. process.Dispose();
  573. var failed = false;
  574. if (exitCode == -1)
  575. {
  576. failed = true;
  577. if (File.Exists(outputPath))
  578. {
  579. try
  580. {
  581. _logger.Info("Deleting extracted subtitle due to failure: ", outputPath);
  582. File.Delete(outputPath);
  583. }
  584. catch (IOException ex)
  585. {
  586. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  587. }
  588. }
  589. }
  590. else if (!File.Exists(outputPath))
  591. {
  592. failed = true;
  593. }
  594. if (failed)
  595. {
  596. var msg = string.Format("ffmpeg subtitle extraction failed for {0}", inputPath);
  597. _logger.Error(msg);
  598. throw new ApplicationException(msg);
  599. }
  600. await SetAssFont(outputPath).ConfigureAwait(false);
  601. }
  602. /// <summary>
  603. /// Sets the ass font.
  604. /// </summary>
  605. /// <param name="file">The file.</param>
  606. /// <returns>Task.</returns>
  607. private async Task SetAssFont(string file)
  608. {
  609. string text;
  610. Encoding encoding;
  611. using (var reader = new StreamReader(file, detectEncodingFromByteOrderMarks: true))
  612. {
  613. encoding = reader.CurrentEncoding;
  614. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  615. }
  616. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  617. if (!string.Equals(text, newText))
  618. {
  619. using (var writer = new StreamWriter(file, false, encoding))
  620. {
  621. writer.Write(newText);
  622. }
  623. }
  624. }
  625. /// <summary>
  626. /// Extracts the image.
  627. /// </summary>
  628. /// <param name="inputFiles">The input files.</param>
  629. /// <param name="type">The type.</param>
  630. /// <param name="threedFormat">The threed format.</param>
  631. /// <param name="offset">The offset.</param>
  632. /// <param name="outputPath">The output path.</param>
  633. /// <param name="cancellationToken">The cancellation token.</param>
  634. /// <returns>Task.</returns>
  635. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  636. public async Task ExtractImage(string[] inputFiles, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, string outputPath, CancellationToken cancellationToken)
  637. {
  638. var resourcePool = type == InputType.AudioFile ? _audioImageResourcePool : _videoImageResourcePool;
  639. var inputArgument = GetInputArgument(inputFiles, type);
  640. if (type != InputType.AudioFile)
  641. {
  642. try
  643. {
  644. await ExtractImageInternal(inputArgument, type, threedFormat, offset, outputPath, true, resourcePool, cancellationToken).ConfigureAwait(false);
  645. return;
  646. }
  647. catch
  648. {
  649. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  650. }
  651. }
  652. await ExtractImageInternal(inputArgument, type, threedFormat, offset, outputPath, false, resourcePool, cancellationToken).ConfigureAwait(false);
  653. }
  654. /// <summary>
  655. /// Extracts the image.
  656. /// </summary>
  657. /// <param name="inputPath">The input path.</param>
  658. /// <param name="type">The type.</param>
  659. /// <param name="threedFormat">The threed format.</param>
  660. /// <param name="offset">The offset.</param>
  661. /// <param name="outputPath">The output path.</param>
  662. /// <param name="useIFrame">if set to <c>true</c> [use I frame].</param>
  663. /// <param name="resourcePool">The resource pool.</param>
  664. /// <param name="cancellationToken">The cancellation token.</param>
  665. /// <returns>Task.</returns>
  666. /// <exception cref="System.ArgumentNullException">inputPath
  667. /// or
  668. /// outputPath</exception>
  669. /// <exception cref="System.ApplicationException"></exception>
  670. private async Task ExtractImageInternal(string inputPath, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, string outputPath, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  671. {
  672. if (string.IsNullOrEmpty(inputPath))
  673. {
  674. throw new ArgumentNullException("inputPath");
  675. }
  676. if (string.IsNullOrEmpty(outputPath))
  677. {
  678. throw new ArgumentNullException("outputPath");
  679. }
  680. var vf = "scale=iw*sar:ih, scale=600:-1";
  681. if (threedFormat.HasValue)
  682. {
  683. switch (threedFormat.Value)
  684. {
  685. case Video3DFormat.HalfSideBySide:
  686. case Video3DFormat.FullSideBySide:
  687. vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,scale=600:-1";
  688. break;
  689. case Video3DFormat.HalfTopAndBottom:
  690. case Video3DFormat.FullTopAndBottom:
  691. vf = "crop=iw:ih/2:0:0,scale=iw:(ih*2),scale=600:-1";
  692. break;
  693. }
  694. }
  695. var args = useIFrame ? string.Format("-i {0} -threads 0 -v quiet -vframes 1 -filter:v select=\"eq(pict_type\\,I)\" -vf \"{2}\" -f image2 \"{1}\"", inputPath, outputPath, vf) :
  696. string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, outputPath, vf);
  697. var probeSize = GetProbeSizeArgument(type);
  698. if (!string.IsNullOrEmpty(probeSize))
  699. {
  700. args = probeSize + " " + args;
  701. }
  702. if (offset.HasValue)
  703. {
  704. args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)).ToString(UsCulture) + args;
  705. }
  706. var process = new Process
  707. {
  708. StartInfo = new ProcessStartInfo
  709. {
  710. CreateNoWindow = true,
  711. UseShellExecute = false,
  712. FileName = FFMpegPath,
  713. Arguments = args,
  714. WindowStyle = ProcessWindowStyle.Hidden,
  715. ErrorDialog = false
  716. }
  717. };
  718. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  719. var ranToCompletion = StartAndWaitForProcess(process);
  720. resourcePool.Release();
  721. var exitCode = ranToCompletion ? process.ExitCode : -1;
  722. process.Dispose();
  723. var failed = false;
  724. if (exitCode == -1)
  725. {
  726. failed = true;
  727. if (File.Exists(outputPath))
  728. {
  729. try
  730. {
  731. _logger.Info("Deleting extracted image due to failure: ", outputPath);
  732. File.Delete(outputPath);
  733. }
  734. catch (IOException ex)
  735. {
  736. _logger.ErrorException("Error deleting extracted image {0}", ex, outputPath);
  737. }
  738. }
  739. }
  740. else if (!File.Exists(outputPath))
  741. {
  742. failed = true;
  743. }
  744. if (failed)
  745. {
  746. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  747. _logger.Error(msg);
  748. throw new ApplicationException(msg);
  749. }
  750. }
  751. /// <summary>
  752. /// Starts the and wait for process.
  753. /// </summary>
  754. /// <param name="process">The process.</param>
  755. /// <param name="timeout">The timeout.</param>
  756. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  757. private bool StartAndWaitForProcess(Process process, int timeout = 10000)
  758. {
  759. process.Start();
  760. var ranToCompletion = process.WaitForExit(timeout);
  761. if (!ranToCompletion)
  762. {
  763. try
  764. {
  765. _logger.Info("Killing ffmpeg process");
  766. process.Kill();
  767. process.WaitForExit(1000);
  768. }
  769. catch (Win32Exception ex)
  770. {
  771. _logger.ErrorException("Error killing process", ex);
  772. }
  773. catch (InvalidOperationException ex)
  774. {
  775. _logger.ErrorException("Error killing process", ex);
  776. }
  777. catch (NotSupportedException ex)
  778. {
  779. _logger.ErrorException("Error killing process", ex);
  780. }
  781. }
  782. return ranToCompletion;
  783. }
  784. /// <summary>
  785. /// Gets the file input argument.
  786. /// </summary>
  787. /// <param name="path">The path.</param>
  788. /// <returns>System.String.</returns>
  789. private string GetFileInputArgument(string path)
  790. {
  791. return string.Format("file:\"{0}\"", path);
  792. }
  793. /// <summary>
  794. /// Gets the concat input argument.
  795. /// </summary>
  796. /// <param name="playableStreamFiles">The playable stream files.</param>
  797. /// <returns>System.String.</returns>
  798. private string GetConcatInputArgument(string[] playableStreamFiles)
  799. {
  800. // Get all streams
  801. // If there's more than one we'll need to use the concat command
  802. if (playableStreamFiles.Length > 1)
  803. {
  804. var files = string.Join("|", playableStreamFiles);
  805. return string.Format("concat:\"{0}\"", files);
  806. }
  807. // Determine the input path for video files
  808. return GetFileInputArgument(playableStreamFiles[0]);
  809. }
  810. /// <summary>
  811. /// Gets the bluray input argument.
  812. /// </summary>
  813. /// <param name="blurayRoot">The bluray root.</param>
  814. /// <returns>System.String.</returns>
  815. private string GetBlurayInputArgument(string blurayRoot)
  816. {
  817. return string.Format("bluray:\"{0}\"", blurayRoot);
  818. }
  819. /// <summary>
  820. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  821. /// </summary>
  822. public void Dispose()
  823. {
  824. Dispose(true);
  825. }
  826. /// <summary>
  827. /// Releases unmanaged and - optionally - managed resources.
  828. /// </summary>
  829. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  830. protected virtual void Dispose(bool dispose)
  831. {
  832. if (dispose)
  833. {
  834. _videoImageResourcePool.Dispose();
  835. }
  836. }
  837. }
  838. }