MediaEncoder.cs 37 KB

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