MediaEncoder.cs 44 KB

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