MediaEncoder.cs 40 KB

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