MediaEncoder.cs 36 KB

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