MediaEncoder.cs 39 KB

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