MediaEncoder.cs 43 KB

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