MediaEncoder.cs 37 KB

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