MediaEncoder.cs 43 KB

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