MediaEncoder.cs 36 KB

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