MediaEncoder.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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 offsetParam = offset.Ticks > 0 ? "-ss " + offset.TotalSeconds + " " : string.Empty;
  478. var process = new Process
  479. {
  480. StartInfo = new ProcessStartInfo
  481. {
  482. RedirectStandardOutput = false,
  483. RedirectStandardError = true,
  484. CreateNoWindow = true,
  485. UseShellExecute = false,
  486. FileName = FFMpegPath,
  487. Arguments = string.Format("{0}-i \"{1}\" \"{2}\"", offsetParam, inputPath, outputPath),
  488. WindowStyle = ProcessWindowStyle.Hidden,
  489. ErrorDialog = false
  490. }
  491. };
  492. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  493. await _subtitleExtractionResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  494. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt");
  495. var logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  496. try
  497. {
  498. process.Start();
  499. }
  500. catch (Exception ex)
  501. {
  502. _subtitleExtractionResourcePool.Release();
  503. logFileStream.Dispose();
  504. _logger.ErrorException("Error starting ffmpeg", ex);
  505. throw;
  506. }
  507. var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream);
  508. var ranToCompletion = process.WaitForExit(60000);
  509. if (!ranToCompletion)
  510. {
  511. try
  512. {
  513. _logger.Info("Killing ffmpeg process");
  514. process.Kill();
  515. process.WaitForExit(1000);
  516. await logTask.ConfigureAwait(false);
  517. }
  518. catch (Win32Exception ex)
  519. {
  520. _logger.ErrorException("Error killing process", ex);
  521. }
  522. catch (InvalidOperationException ex)
  523. {
  524. _logger.ErrorException("Error killing process", ex);
  525. }
  526. catch (NotSupportedException ex)
  527. {
  528. _logger.ErrorException("Error killing process", ex);
  529. }
  530. finally
  531. {
  532. logFileStream.Dispose();
  533. _subtitleExtractionResourcePool.Release();
  534. }
  535. }
  536. var exitCode = ranToCompletion ? process.ExitCode : -1;
  537. process.Dispose();
  538. var failed = false;
  539. if (exitCode == -1)
  540. {
  541. failed = true;
  542. if (File.Exists(outputPath))
  543. {
  544. try
  545. {
  546. _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
  547. File.Delete(outputPath);
  548. }
  549. catch (IOException ex)
  550. {
  551. _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
  552. }
  553. }
  554. }
  555. else if (!File.Exists(outputPath))
  556. {
  557. failed = true;
  558. }
  559. if (failed)
  560. {
  561. var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath);
  562. _logger.Error(msg);
  563. throw new ApplicationException(msg);
  564. }
  565. await SetAssFont(outputPath).ConfigureAwait(false);
  566. }
  567. /// <summary>
  568. /// Extracts the text subtitle.
  569. /// </summary>
  570. /// <param name="inputFiles">The input files.</param>
  571. /// <param name="type">The type.</param>
  572. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  573. /// <param name="offset">The offset.</param>
  574. /// <param name="outputPath">The output path.</param>
  575. /// <param name="cancellationToken">The cancellation token.</param>
  576. /// <returns>Task.</returns>
  577. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  578. public Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  579. {
  580. return ExtractTextSubtitleInternal(GetInputArgument(inputFiles, type), subtitleStreamIndex, offset, outputPath, cancellationToken);
  581. }
  582. /// <summary>
  583. /// Extracts the text subtitle.
  584. /// </summary>
  585. /// <param name="inputPath">The input path.</param>
  586. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  587. /// <param name="offset">The offset.</param>
  588. /// <param name="outputPath">The output path.</param>
  589. /// <param name="cancellationToken">The cancellation token.</param>
  590. /// <returns>Task.</returns>
  591. /// <exception cref="System.ArgumentNullException">inputPath
  592. /// or
  593. /// outputPath
  594. /// or
  595. /// cancellationToken</exception>
  596. /// <exception cref="System.ApplicationException"></exception>
  597. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  598. {
  599. if (string.IsNullOrEmpty(inputPath))
  600. {
  601. throw new ArgumentNullException("inputPath");
  602. }
  603. if (string.IsNullOrEmpty(outputPath))
  604. {
  605. throw new ArgumentNullException("outputPath");
  606. }
  607. if (cancellationToken == null)
  608. {
  609. throw new ArgumentNullException("cancellationToken");
  610. }
  611. var offsetParam = offset.Ticks > 0 ? "-ss " + offset.TotalSeconds + " " : string.Empty;
  612. var process = new Process
  613. {
  614. StartInfo = new ProcessStartInfo
  615. {
  616. CreateNoWindow = true,
  617. UseShellExecute = false,
  618. RedirectStandardOutput = false,
  619. RedirectStandardError = true,
  620. FileName = FFMpegPath,
  621. Arguments = string.Format("{0}-i {1} -map 0:{2} -an -vn -c:s ass \"{3}\"", offsetParam, inputPath, subtitleStreamIndex, outputPath),
  622. WindowStyle = ProcessWindowStyle.Hidden,
  623. ErrorDialog = false
  624. }
  625. };
  626. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  627. await _subtitleExtractionResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  628. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt");
  629. var logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  630. try
  631. {
  632. process.Start();
  633. }
  634. catch (Exception ex)
  635. {
  636. _subtitleExtractionResourcePool.Release();
  637. logFileStream.Dispose();
  638. _logger.ErrorException("Error starting ffmpeg", ex);
  639. throw;
  640. }
  641. process.StandardError.BaseStream.CopyToAsync(logFileStream);
  642. var ranToCompletion = process.WaitForExit(60000);
  643. if (!ranToCompletion)
  644. {
  645. try
  646. {
  647. _logger.Info("Killing ffmpeg process");
  648. process.Kill();
  649. process.WaitForExit(1000);
  650. }
  651. catch (Win32Exception ex)
  652. {
  653. _logger.ErrorException("Error killing process", ex);
  654. }
  655. catch (InvalidOperationException ex)
  656. {
  657. _logger.ErrorException("Error killing process", ex);
  658. }
  659. catch (NotSupportedException ex)
  660. {
  661. _logger.ErrorException("Error killing process", ex);
  662. }
  663. finally
  664. {
  665. logFileStream.Dispose();
  666. _subtitleExtractionResourcePool.Release();
  667. }
  668. }
  669. var exitCode = ranToCompletion ? process.ExitCode : -1;
  670. process.Dispose();
  671. var failed = false;
  672. if (exitCode == -1)
  673. {
  674. failed = true;
  675. if (File.Exists(outputPath))
  676. {
  677. try
  678. {
  679. _logger.Info("Deleting extracted subtitle due to failure: ", outputPath);
  680. File.Delete(outputPath);
  681. }
  682. catch (IOException ex)
  683. {
  684. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  685. }
  686. }
  687. }
  688. else if (!File.Exists(outputPath))
  689. {
  690. failed = true;
  691. }
  692. if (failed)
  693. {
  694. var msg = string.Format("ffmpeg subtitle extraction failed for {0}", inputPath);
  695. _logger.Error(msg);
  696. throw new ApplicationException(msg);
  697. }
  698. await SetAssFont(outputPath).ConfigureAwait(false);
  699. }
  700. /// <summary>
  701. /// Sets the ass font.
  702. /// </summary>
  703. /// <param name="file">The file.</param>
  704. /// <returns>Task.</returns>
  705. private async Task SetAssFont(string file)
  706. {
  707. string text;
  708. Encoding encoding;
  709. using (var reader = new StreamReader(file, detectEncodingFromByteOrderMarks: true))
  710. {
  711. encoding = reader.CurrentEncoding;
  712. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  713. }
  714. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  715. if (!string.Equals(text, newText))
  716. {
  717. using (var writer = new StreamWriter(file, false, encoding))
  718. {
  719. writer.Write(newText);
  720. }
  721. }
  722. }
  723. /// <summary>
  724. /// Extracts the image.
  725. /// </summary>
  726. /// <param name="inputFiles">The input files.</param>
  727. /// <param name="type">The type.</param>
  728. /// <param name="offset">The offset.</param>
  729. /// <param name="outputPath">The output path.</param>
  730. /// <param name="cancellationToken">The cancellation token.</param>
  731. /// <returns>Task.</returns>
  732. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  733. public async Task ExtractImage(string[] inputFiles, InputType type, TimeSpan? offset, string outputPath, CancellationToken cancellationToken)
  734. {
  735. var resourcePool = type == InputType.AudioFile ? _audioImageResourcePool : _videoImageResourcePool;
  736. var inputArgument = GetInputArgument(inputFiles, type);
  737. if (type != InputType.AudioFile)
  738. {
  739. try
  740. {
  741. await ExtractImageInternal(inputArgument, type, offset, outputPath, true, resourcePool, cancellationToken).ConfigureAwait(false);
  742. return;
  743. }
  744. catch
  745. {
  746. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  747. }
  748. }
  749. await ExtractImageInternal(inputArgument, type, offset, outputPath, false, resourcePool, cancellationToken).ConfigureAwait(false);
  750. }
  751. /// <summary>
  752. /// Extracts the image.
  753. /// </summary>
  754. /// <param name="inputPath">The input path.</param>
  755. /// <param name="type">The type.</param>
  756. /// <param name="offset">The offset.</param>
  757. /// <param name="outputPath">The output path.</param>
  758. /// <param name="useIFrame">if set to <c>true</c> [use I frame].</param>
  759. /// <param name="resourcePool">The resource pool.</param>
  760. /// <param name="cancellationToken">The cancellation token.</param>
  761. /// <returns>Task.</returns>
  762. /// <exception cref="System.ArgumentNullException">inputPath
  763. /// or
  764. /// outputPath</exception>
  765. /// <exception cref="System.ApplicationException"></exception>
  766. private async Task ExtractImageInternal(string inputPath, InputType type, TimeSpan? offset, string outputPath, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  767. {
  768. if (string.IsNullOrEmpty(inputPath))
  769. {
  770. throw new ArgumentNullException("inputPath");
  771. }
  772. if (string.IsNullOrEmpty(outputPath))
  773. {
  774. throw new ArgumentNullException("outputPath");
  775. }
  776. 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) :
  777. string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"scale=iw*sar:ih, scale=600:-1\" -f image2 \"{1}\"", inputPath, outputPath);
  778. var probeSize = GetProbeSizeArgument(type);
  779. if (!string.IsNullOrEmpty(probeSize))
  780. {
  781. args = probeSize + " " + args;
  782. }
  783. if (offset.HasValue)
  784. {
  785. args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)) + args;
  786. }
  787. var process = new Process
  788. {
  789. StartInfo = new ProcessStartInfo
  790. {
  791. CreateNoWindow = true,
  792. UseShellExecute = false,
  793. FileName = FFMpegPath,
  794. Arguments = args,
  795. WindowStyle = ProcessWindowStyle.Hidden,
  796. ErrorDialog = false
  797. }
  798. };
  799. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  800. var ranToCompletion = StartAndWaitForProcess(process);
  801. resourcePool.Release();
  802. var exitCode = ranToCompletion ? process.ExitCode : -1;
  803. process.Dispose();
  804. var failed = false;
  805. if (exitCode == -1)
  806. {
  807. failed = true;
  808. if (File.Exists(outputPath))
  809. {
  810. try
  811. {
  812. _logger.Info("Deleting extracted image due to failure: ", outputPath);
  813. File.Delete(outputPath);
  814. }
  815. catch (IOException ex)
  816. {
  817. _logger.ErrorException("Error deleting extracted image {0}", ex, outputPath);
  818. }
  819. }
  820. }
  821. else if (!File.Exists(outputPath))
  822. {
  823. failed = true;
  824. }
  825. if (failed)
  826. {
  827. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  828. _logger.Error(msg);
  829. throw new ApplicationException(msg);
  830. }
  831. }
  832. /// <summary>
  833. /// Starts the and wait for process.
  834. /// </summary>
  835. /// <param name="process">The process.</param>
  836. /// <param name="timeout">The timeout.</param>
  837. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  838. private bool StartAndWaitForProcess(Process process, int timeout = 10000)
  839. {
  840. process.Start();
  841. var ranToCompletion = process.WaitForExit(timeout);
  842. if (!ranToCompletion)
  843. {
  844. try
  845. {
  846. _logger.Info("Killing ffmpeg process");
  847. process.Kill();
  848. process.WaitForExit(1000);
  849. }
  850. catch (Win32Exception ex)
  851. {
  852. _logger.ErrorException("Error killing process", ex);
  853. }
  854. catch (InvalidOperationException ex)
  855. {
  856. _logger.ErrorException("Error killing process", ex);
  857. }
  858. catch (NotSupportedException ex)
  859. {
  860. _logger.ErrorException("Error killing process", ex);
  861. }
  862. }
  863. return ranToCompletion;
  864. }
  865. /// <summary>
  866. /// Gets the file input argument.
  867. /// </summary>
  868. /// <param name="path">The path.</param>
  869. /// <returns>System.String.</returns>
  870. private string GetFileInputArgument(string path)
  871. {
  872. return string.Format("file:\"{0}\"", path);
  873. }
  874. /// <summary>
  875. /// Gets the concat input argument.
  876. /// </summary>
  877. /// <param name="playableStreamFiles">The playable stream files.</param>
  878. /// <returns>System.String.</returns>
  879. private string GetConcatInputArgument(string[] playableStreamFiles)
  880. {
  881. // Get all streams
  882. // If there's more than one we'll need to use the concat command
  883. if (playableStreamFiles.Length > 1)
  884. {
  885. var files = string.Join("|", playableStreamFiles);
  886. return string.Format("concat:\"{0}\"", files);
  887. }
  888. // Determine the input path for video files
  889. return GetFileInputArgument(playableStreamFiles[0]);
  890. }
  891. /// <summary>
  892. /// Gets the bluray input argument.
  893. /// </summary>
  894. /// <param name="blurayRoot">The bluray root.</param>
  895. /// <returns>System.String.</returns>
  896. private string GetBlurayInputArgument(string blurayRoot)
  897. {
  898. return string.Format("bluray:\"{0}\"", blurayRoot);
  899. }
  900. /// <summary>
  901. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  902. /// </summary>
  903. public void Dispose()
  904. {
  905. Dispose(true);
  906. }
  907. /// <summary>
  908. /// Releases unmanaged and - optionally - managed resources.
  909. /// </summary>
  910. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  911. protected virtual void Dispose(bool dispose)
  912. {
  913. if (dispose)
  914. {
  915. _videoImageResourcePool.Dispose();
  916. }
  917. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  918. }
  919. /// <summary>
  920. /// Sets the error mode.
  921. /// </summary>
  922. /// <param name="uMode">The u mode.</param>
  923. /// <returns>ErrorModes.</returns>
  924. [DllImport("kernel32.dll")]
  925. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  926. /// <summary>
  927. /// Enum ErrorModes
  928. /// </summary>
  929. [Flags]
  930. public enum ErrorModes : uint
  931. {
  932. /// <summary>
  933. /// The SYSTE m_ DEFAULT
  934. /// </summary>
  935. SYSTEM_DEFAULT = 0x0,
  936. /// <summary>
  937. /// The SE m_ FAILCRITICALERRORS
  938. /// </summary>
  939. SEM_FAILCRITICALERRORS = 0x0001,
  940. /// <summary>
  941. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  942. /// </summary>
  943. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  944. /// <summary>
  945. /// The SE m_ NOGPFAULTERRORBOX
  946. /// </summary>
  947. SEM_NOGPFAULTERRORBOX = 0x0002,
  948. /// <summary>
  949. /// The SE m_ NOOPENFILEERRORBOX
  950. /// </summary>
  951. SEM_NOOPENFILEERRORBOX = 0x8000
  952. }
  953. }
  954. }