MediaEncoder.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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).ConfigureAwait(false);
  336. }
  337. }
  338. finally
  339. {
  340. semaphore.Release();
  341. }
  342. }
  343. private const int FastSeekOffsetSeconds = 1;
  344. /// <summary>
  345. /// Converts the text subtitle to ass.
  346. /// </summary>
  347. /// <param name="inputPath">The input path.</param>
  348. /// <param name="outputPath">The output path.</param>
  349. /// <param name="language">The language.</param>
  350. /// <param name="offset">The offset.</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. {
  358. if (string.IsNullOrEmpty(inputPath))
  359. {
  360. throw new ArgumentNullException("inputPath");
  361. }
  362. if (string.IsNullOrEmpty(outputPath))
  363. {
  364. throw new ArgumentNullException("outputPath");
  365. }
  366. var slowSeekParam = GetSlowSeekCommandLineParameter(offset);
  367. var fastSeekParam = GetFastSeekCommandLineParameter(offset);
  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}{1}-i \"{2}\"{3} \"{4}\"",
  381. fastSeekParam,
  382. encodingParam,
  383. inputPath,
  384. slowSeekParam,
  385. outputPath),
  386. WindowStyle = ProcessWindowStyle.Hidden,
  387. ErrorDialog = false
  388. }
  389. };
  390. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  391. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt");
  392. var logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
  393. StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  394. try
  395. {
  396. process.Start();
  397. }
  398. catch (Exception ex)
  399. {
  400. logFileStream.Dispose();
  401. _logger.ErrorException("Error starting ffmpeg", ex);
  402. throw;
  403. }
  404. var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream);
  405. var ranToCompletion = process.WaitForExit(60000);
  406. if (!ranToCompletion)
  407. {
  408. try
  409. {
  410. _logger.Info("Killing ffmpeg subtitle conversion process");
  411. process.Kill();
  412. process.WaitForExit(1000);
  413. await logTask.ConfigureAwait(false);
  414. }
  415. catch (Exception ex)
  416. {
  417. _logger.ErrorException("Error killing subtitle conversion process", ex);
  418. }
  419. finally
  420. {
  421. logFileStream.Dispose();
  422. }
  423. }
  424. var exitCode = ranToCompletion ? process.ExitCode : -1;
  425. process.Dispose();
  426. var failed = false;
  427. if (exitCode == -1)
  428. {
  429. failed = true;
  430. if (File.Exists(outputPath))
  431. {
  432. try
  433. {
  434. _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
  435. File.Delete(outputPath);
  436. }
  437. catch (IOException ex)
  438. {
  439. _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
  440. }
  441. }
  442. }
  443. else if (!File.Exists(outputPath))
  444. {
  445. failed = true;
  446. }
  447. if (failed)
  448. {
  449. var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath);
  450. _logger.Error(msg);
  451. throw new ApplicationException(msg);
  452. }
  453. await SetAssFont(outputPath).ConfigureAwait(false);
  454. }
  455. protected string GetFastSeekCommandLineParameter(TimeSpan offset)
  456. {
  457. var seconds = offset.TotalSeconds - FastSeekOffsetSeconds;
  458. if (seconds > 0)
  459. {
  460. return string.Format("-ss {0} ", seconds.ToString(UsCulture));
  461. }
  462. return string.Empty;
  463. }
  464. protected string GetSlowSeekCommandLineParameter(TimeSpan offset)
  465. {
  466. if (offset.TotalSeconds - FastSeekOffsetSeconds > 0)
  467. {
  468. return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture));
  469. }
  470. return string.Empty;
  471. }
  472. /// <summary>
  473. /// Gets the subtitle language encoding param.
  474. /// </summary>
  475. /// <param name="language">The language.</param>
  476. /// <returns>System.String.</returns>
  477. private string GetSubtitleLanguageEncodingParam(string language)
  478. {
  479. switch (language.ToLower())
  480. {
  481. case "pol":
  482. case "cze":
  483. case "ces":
  484. case "slo":
  485. case "slk":
  486. case "hun":
  487. case "slv":
  488. case "srp":
  489. case "hrv":
  490. case "rum":
  491. case "ron":
  492. case "rup":
  493. case "alb":
  494. case "sqi":
  495. return "-sub_charenc windows-1250";
  496. case "ara":
  497. return "-sub_charenc windows-1256";
  498. case "heb":
  499. return "-sub_charenc windows-1255";
  500. case "grc":
  501. case "gre":
  502. return "-sub_charenc windows-1253";
  503. case "crh":
  504. case "ota":
  505. case "tur":
  506. return "-sub_charenc windows-1254";
  507. case "rus":
  508. return "-sub_charenc windows-1251";
  509. case "vie":
  510. return "-sub_charenc windows-1258";
  511. case "kor":
  512. return "-sub_charenc cp949";
  513. default:
  514. return "-sub_charenc windows-1252";
  515. }
  516. }
  517. /// <summary>
  518. /// Extracts the text subtitle.
  519. /// </summary>
  520. /// <param name="inputFiles">The input files.</param>
  521. /// <param name="type">The type.</param>
  522. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  523. /// <param name="offset">The offset.</param>
  524. /// <param name="outputPath">The output path.</param>
  525. /// <param name="cancellationToken">The cancellation token.</param>
  526. /// <returns>Task.</returns>
  527. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  528. public async Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  529. {
  530. var semaphore = GetLock(outputPath);
  531. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  532. try
  533. {
  534. if (!File.Exists(outputPath))
  535. {
  536. await ExtractTextSubtitleInternal(GetInputArgument(inputFiles, type), subtitleStreamIndex, offset, outputPath, cancellationToken).ConfigureAwait(false);
  537. }
  538. }
  539. finally
  540. {
  541. semaphore.Release();
  542. }
  543. }
  544. /// <summary>
  545. /// Extracts the text subtitle.
  546. /// </summary>
  547. /// <param name="inputPath">The input path.</param>
  548. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  549. /// <param name="offset">The offset.</param>
  550. /// <param name="outputPath">The output path.</param>
  551. /// <param name="cancellationToken">The cancellation token.</param>
  552. /// <returns>Task.</returns>
  553. /// <exception cref="System.ArgumentNullException">inputPath
  554. /// or
  555. /// outputPath
  556. /// or
  557. /// cancellationToken</exception>
  558. /// <exception cref="System.ApplicationException"></exception>
  559. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  560. {
  561. if (string.IsNullOrEmpty(inputPath))
  562. {
  563. throw new ArgumentNullException("inputPath");
  564. }
  565. if (string.IsNullOrEmpty(outputPath))
  566. {
  567. throw new ArgumentNullException("outputPath");
  568. }
  569. var slowSeekParam = offset.TotalSeconds > 0 ? " -ss " + offset.TotalSeconds.ToString(UsCulture) : string.Empty;
  570. var process = new Process
  571. {
  572. StartInfo = new ProcessStartInfo
  573. {
  574. CreateNoWindow = true,
  575. UseShellExecute = false,
  576. RedirectStandardOutput = false,
  577. RedirectStandardError = true,
  578. FileName = FFMpegPath,
  579. Arguments = string.Format("-i {0}{1} -map 0:{2} -an -vn -c:s ass \"{3}\"", inputPath, slowSeekParam, subtitleStreamIndex, outputPath),
  580. WindowStyle = ProcessWindowStyle.Hidden,
  581. ErrorDialog = false
  582. }
  583. };
  584. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  585. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt");
  586. var logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  587. try
  588. {
  589. process.Start();
  590. }
  591. catch (Exception ex)
  592. {
  593. logFileStream.Dispose();
  594. _logger.ErrorException("Error starting ffmpeg", ex);
  595. throw;
  596. }
  597. process.StandardError.BaseStream.CopyToAsync(logFileStream);
  598. var ranToCompletion = process.WaitForExit(60000);
  599. if (!ranToCompletion)
  600. {
  601. try
  602. {
  603. _logger.Info("Killing ffmpeg subtitle extraction process");
  604. process.Kill();
  605. process.WaitForExit(1000);
  606. }
  607. catch (Exception ex)
  608. {
  609. _logger.ErrorException("Error killing subtitle extraction process", ex);
  610. }
  611. finally
  612. {
  613. logFileStream.Dispose();
  614. }
  615. }
  616. var exitCode = ranToCompletion ? process.ExitCode : -1;
  617. process.Dispose();
  618. var failed = false;
  619. if (exitCode == -1)
  620. {
  621. failed = true;
  622. if (File.Exists(outputPath))
  623. {
  624. try
  625. {
  626. _logger.Info("Deleting extracted subtitle due to failure: ", outputPath);
  627. File.Delete(outputPath);
  628. }
  629. catch (IOException ex)
  630. {
  631. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  632. }
  633. }
  634. }
  635. else if (!File.Exists(outputPath))
  636. {
  637. failed = true;
  638. }
  639. if (failed)
  640. {
  641. var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
  642. _logger.Error(msg);
  643. throw new ApplicationException(msg);
  644. }
  645. else
  646. {
  647. var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
  648. _logger.Info(msg);
  649. }
  650. await SetAssFont(outputPath).ConfigureAwait(false);
  651. }
  652. /// <summary>
  653. /// Sets the ass font.
  654. /// </summary>
  655. /// <param name="file">The file.</param>
  656. /// <returns>Task.</returns>
  657. private async Task SetAssFont(string file)
  658. {
  659. _logger.Info("Setting ass font within {0}", file);
  660. string text;
  661. Encoding encoding;
  662. using (var reader = new StreamReader(file, detectEncodingFromByteOrderMarks: true))
  663. {
  664. encoding = reader.CurrentEncoding;
  665. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  666. }
  667. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  668. if (!string.Equals(text, newText))
  669. {
  670. using (var writer = new StreamWriter(file, false, encoding))
  671. {
  672. writer.Write(newText);
  673. }
  674. }
  675. }
  676. /// <summary>
  677. /// Extracts the image.
  678. /// </summary>
  679. /// <param name="inputFiles">The input files.</param>
  680. /// <param name="type">The type.</param>
  681. /// <param name="threedFormat">The threed format.</param>
  682. /// <param name="offset">The offset.</param>
  683. /// <param name="outputPath">The output path.</param>
  684. /// <param name="cancellationToken">The cancellation token.</param>
  685. /// <returns>Task.</returns>
  686. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  687. public async Task ExtractImage(string[] inputFiles, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, string outputPath, CancellationToken cancellationToken)
  688. {
  689. var resourcePool = type == InputType.AudioFile ? _audioImageResourcePool : _videoImageResourcePool;
  690. var inputArgument = GetInputArgument(inputFiles, type);
  691. if (type != InputType.AudioFile)
  692. {
  693. try
  694. {
  695. await ExtractImageInternal(inputArgument, type, threedFormat, offset, outputPath, true, resourcePool, cancellationToken).ConfigureAwait(false);
  696. return;
  697. }
  698. catch
  699. {
  700. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  701. }
  702. }
  703. await ExtractImageInternal(inputArgument, type, threedFormat, offset, outputPath, false, resourcePool, cancellationToken).ConfigureAwait(false);
  704. }
  705. /// <summary>
  706. /// Extracts the image.
  707. /// </summary>
  708. /// <param name="inputPath">The input path.</param>
  709. /// <param name="type">The type.</param>
  710. /// <param name="threedFormat">The threed format.</param>
  711. /// <param name="offset">The offset.</param>
  712. /// <param name="outputPath">The output path.</param>
  713. /// <param name="useIFrame">if set to <c>true</c> [use I frame].</param>
  714. /// <param name="resourcePool">The resource pool.</param>
  715. /// <param name="cancellationToken">The cancellation token.</param>
  716. /// <returns>Task.</returns>
  717. /// <exception cref="System.ArgumentNullException">inputPath
  718. /// or
  719. /// outputPath</exception>
  720. /// <exception cref="System.ApplicationException"></exception>
  721. private async Task ExtractImageInternal(string inputPath, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, string outputPath, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  722. {
  723. if (string.IsNullOrEmpty(inputPath))
  724. {
  725. throw new ArgumentNullException("inputPath");
  726. }
  727. if (string.IsNullOrEmpty(outputPath))
  728. {
  729. throw new ArgumentNullException("outputPath");
  730. }
  731. var vf = "scale=iw*sar:ih, scale=600:-1";
  732. if (threedFormat.HasValue)
  733. {
  734. switch (threedFormat.Value)
  735. {
  736. case Video3DFormat.HalfSideBySide:
  737. case Video3DFormat.FullSideBySide:
  738. vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,scale=600:-1";
  739. break;
  740. case Video3DFormat.HalfTopAndBottom:
  741. case Video3DFormat.FullTopAndBottom:
  742. vf = "crop=iw:ih/2:0:0,scale=iw:(ih*2),scale=600:-1";
  743. break;
  744. }
  745. }
  746. 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) :
  747. string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, outputPath, vf);
  748. var probeSize = GetProbeSizeArgument(type);
  749. if (!string.IsNullOrEmpty(probeSize))
  750. {
  751. args = probeSize + " " + args;
  752. }
  753. if (offset.HasValue)
  754. {
  755. args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)).ToString(UsCulture) + args;
  756. }
  757. var process = new Process
  758. {
  759. StartInfo = new ProcessStartInfo
  760. {
  761. CreateNoWindow = true,
  762. UseShellExecute = false,
  763. FileName = FFMpegPath,
  764. Arguments = args,
  765. WindowStyle = ProcessWindowStyle.Hidden,
  766. ErrorDialog = false
  767. }
  768. };
  769. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  770. var ranToCompletion = StartAndWaitForProcess(process);
  771. resourcePool.Release();
  772. var exitCode = ranToCompletion ? process.ExitCode : -1;
  773. process.Dispose();
  774. var failed = false;
  775. if (exitCode == -1)
  776. {
  777. failed = true;
  778. if (File.Exists(outputPath))
  779. {
  780. try
  781. {
  782. _logger.Info("Deleting extracted image due to failure: ", outputPath);
  783. File.Delete(outputPath);
  784. }
  785. catch (IOException ex)
  786. {
  787. _logger.ErrorException("Error deleting extracted image {0}", ex, outputPath);
  788. }
  789. }
  790. }
  791. else if (!File.Exists(outputPath))
  792. {
  793. failed = true;
  794. }
  795. if (failed)
  796. {
  797. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  798. _logger.Error(msg);
  799. throw new ApplicationException(msg);
  800. }
  801. }
  802. /// <summary>
  803. /// Starts the and wait for process.
  804. /// </summary>
  805. /// <param name="process">The process.</param>
  806. /// <param name="timeout">The timeout.</param>
  807. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  808. private bool StartAndWaitForProcess(Process process, int timeout = 10000)
  809. {
  810. process.Start();
  811. var ranToCompletion = process.WaitForExit(timeout);
  812. if (!ranToCompletion)
  813. {
  814. try
  815. {
  816. _logger.Info("Killing ffmpeg process");
  817. process.Kill();
  818. process.WaitForExit(1000);
  819. }
  820. catch (Win32Exception ex)
  821. {
  822. _logger.ErrorException("Error killing process", ex);
  823. }
  824. catch (InvalidOperationException ex)
  825. {
  826. _logger.ErrorException("Error killing process", ex);
  827. }
  828. catch (NotSupportedException ex)
  829. {
  830. _logger.ErrorException("Error killing process", ex);
  831. }
  832. }
  833. return ranToCompletion;
  834. }
  835. /// <summary>
  836. /// Gets the file input argument.
  837. /// </summary>
  838. /// <param name="path">The path.</param>
  839. /// <returns>System.String.</returns>
  840. private string GetFileInputArgument(string path)
  841. {
  842. return string.Format("file:\"{0}\"", path);
  843. }
  844. /// <summary>
  845. /// Gets the concat input argument.
  846. /// </summary>
  847. /// <param name="playableStreamFiles">The playable stream files.</param>
  848. /// <returns>System.String.</returns>
  849. private string GetConcatInputArgument(string[] playableStreamFiles)
  850. {
  851. // Get all streams
  852. // If there's more than one we'll need to use the concat command
  853. if (playableStreamFiles.Length > 1)
  854. {
  855. var files = string.Join("|", playableStreamFiles);
  856. return string.Format("concat:\"{0}\"", files);
  857. }
  858. // Determine the input path for video files
  859. return GetFileInputArgument(playableStreamFiles[0]);
  860. }
  861. /// <summary>
  862. /// Gets the bluray input argument.
  863. /// </summary>
  864. /// <param name="blurayRoot">The bluray root.</param>
  865. /// <returns>System.String.</returns>
  866. private string GetBlurayInputArgument(string blurayRoot)
  867. {
  868. return string.Format("bluray:\"{0}\"", blurayRoot);
  869. }
  870. /// <summary>
  871. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  872. /// </summary>
  873. public void Dispose()
  874. {
  875. Dispose(true);
  876. }
  877. /// <summary>
  878. /// Releases unmanaged and - optionally - managed resources.
  879. /// </summary>
  880. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  881. protected virtual void Dispose(bool dispose)
  882. {
  883. if (dispose)
  884. {
  885. _videoImageResourcePool.Dispose();
  886. }
  887. }
  888. }
  889. }