MediaEncoder.cs 41 KB

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