MediaEncoder.cs 44 KB

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