MediaEncoder.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. default:
  512. return "-sub_charenc windows-1252";
  513. }
  514. }
  515. /// <summary>
  516. /// Extracts the text subtitle.
  517. /// </summary>
  518. /// <param name="inputFiles">The input files.</param>
  519. /// <param name="type">The type.</param>
  520. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  521. /// <param name="offset">The offset.</param>
  522. /// <param name="outputPath">The output path.</param>
  523. /// <param name="cancellationToken">The cancellation token.</param>
  524. /// <returns>Task.</returns>
  525. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  526. public async Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  527. {
  528. var semaphore = GetLock(outputPath);
  529. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  530. try
  531. {
  532. if (!File.Exists(outputPath))
  533. {
  534. await ExtractTextSubtitleInternal(GetInputArgument(inputFiles, type), subtitleStreamIndex, offset, outputPath, cancellationToken).ConfigureAwait(false);
  535. }
  536. }
  537. finally
  538. {
  539. semaphore.Release();
  540. }
  541. }
  542. /// <summary>
  543. /// Extracts the text subtitle.
  544. /// </summary>
  545. /// <param name="inputPath">The input path.</param>
  546. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  547. /// <param name="offset">The offset.</param>
  548. /// <param name="outputPath">The output path.</param>
  549. /// <param name="cancellationToken">The cancellation token.</param>
  550. /// <returns>Task.</returns>
  551. /// <exception cref="System.ArgumentNullException">inputPath
  552. /// or
  553. /// outputPath
  554. /// or
  555. /// cancellationToken</exception>
  556. /// <exception cref="System.ApplicationException"></exception>
  557. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  558. {
  559. if (string.IsNullOrEmpty(inputPath))
  560. {
  561. throw new ArgumentNullException("inputPath");
  562. }
  563. if (string.IsNullOrEmpty(outputPath))
  564. {
  565. throw new ArgumentNullException("outputPath");
  566. }
  567. var slowSeekParam = offset.TotalSeconds > 0 ? " -ss " + offset.TotalSeconds.ToString(UsCulture) : string.Empty;
  568. var process = new Process
  569. {
  570. StartInfo = new ProcessStartInfo
  571. {
  572. CreateNoWindow = true,
  573. UseShellExecute = false,
  574. RedirectStandardOutput = false,
  575. RedirectStandardError = true,
  576. FileName = FFMpegPath,
  577. Arguments = string.Format("-i {0}{1} -map 0:{2} -an -vn -c:s ass \"{3}\"", inputPath, slowSeekParam, subtitleStreamIndex, outputPath),
  578. WindowStyle = ProcessWindowStyle.Hidden,
  579. ErrorDialog = false
  580. }
  581. };
  582. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  583. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt");
  584. var logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  585. try
  586. {
  587. process.Start();
  588. }
  589. catch (Exception ex)
  590. {
  591. logFileStream.Dispose();
  592. _logger.ErrorException("Error starting ffmpeg", ex);
  593. throw;
  594. }
  595. process.StandardError.BaseStream.CopyToAsync(logFileStream);
  596. var ranToCompletion = process.WaitForExit(60000);
  597. if (!ranToCompletion)
  598. {
  599. try
  600. {
  601. _logger.Info("Killing ffmpeg subtitle extraction process");
  602. process.Kill();
  603. process.WaitForExit(1000);
  604. }
  605. catch (Exception ex)
  606. {
  607. _logger.ErrorException("Error killing subtitle extraction process", ex);
  608. }
  609. finally
  610. {
  611. logFileStream.Dispose();
  612. }
  613. }
  614. var exitCode = ranToCompletion ? process.ExitCode : -1;
  615. process.Dispose();
  616. var failed = false;
  617. if (exitCode == -1)
  618. {
  619. failed = true;
  620. if (File.Exists(outputPath))
  621. {
  622. try
  623. {
  624. _logger.Info("Deleting extracted subtitle due to failure: ", outputPath);
  625. File.Delete(outputPath);
  626. }
  627. catch (IOException ex)
  628. {
  629. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  630. }
  631. }
  632. }
  633. else if (!File.Exists(outputPath))
  634. {
  635. failed = true;
  636. }
  637. if (failed)
  638. {
  639. var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
  640. _logger.Error(msg);
  641. throw new ApplicationException(msg);
  642. }
  643. else
  644. {
  645. var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
  646. _logger.Info(msg);
  647. }
  648. await SetAssFont(outputPath).ConfigureAwait(false);
  649. }
  650. /// <summary>
  651. /// Sets the ass font.
  652. /// </summary>
  653. /// <param name="file">The file.</param>
  654. /// <returns>Task.</returns>
  655. private async Task SetAssFont(string file)
  656. {
  657. _logger.Info("Setting ass font within {0}", file);
  658. string text;
  659. Encoding encoding;
  660. using (var reader = new StreamReader(file, detectEncodingFromByteOrderMarks: true))
  661. {
  662. encoding = reader.CurrentEncoding;
  663. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  664. }
  665. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  666. if (!string.Equals(text, newText))
  667. {
  668. using (var writer = new StreamWriter(file, false, encoding))
  669. {
  670. writer.Write(newText);
  671. }
  672. }
  673. }
  674. /// <summary>
  675. /// Extracts the image.
  676. /// </summary>
  677. /// <param name="inputFiles">The input files.</param>
  678. /// <param name="type">The type.</param>
  679. /// <param name="threedFormat">The threed format.</param>
  680. /// <param name="offset">The offset.</param>
  681. /// <param name="outputPath">The output path.</param>
  682. /// <param name="cancellationToken">The cancellation token.</param>
  683. /// <returns>Task.</returns>
  684. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  685. public async Task ExtractImage(string[] inputFiles, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, string outputPath, CancellationToken cancellationToken)
  686. {
  687. var resourcePool = type == InputType.AudioFile ? _audioImageResourcePool : _videoImageResourcePool;
  688. var inputArgument = GetInputArgument(inputFiles, type);
  689. if (type != InputType.AudioFile)
  690. {
  691. try
  692. {
  693. await ExtractImageInternal(inputArgument, type, threedFormat, offset, outputPath, true, resourcePool, cancellationToken).ConfigureAwait(false);
  694. return;
  695. }
  696. catch
  697. {
  698. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  699. }
  700. }
  701. await ExtractImageInternal(inputArgument, type, threedFormat, offset, outputPath, false, resourcePool, cancellationToken).ConfigureAwait(false);
  702. }
  703. /// <summary>
  704. /// Extracts the image.
  705. /// </summary>
  706. /// <param name="inputPath">The input path.</param>
  707. /// <param name="type">The type.</param>
  708. /// <param name="threedFormat">The threed format.</param>
  709. /// <param name="offset">The offset.</param>
  710. /// <param name="outputPath">The output path.</param>
  711. /// <param name="useIFrame">if set to <c>true</c> [use I frame].</param>
  712. /// <param name="resourcePool">The resource pool.</param>
  713. /// <param name="cancellationToken">The cancellation token.</param>
  714. /// <returns>Task.</returns>
  715. /// <exception cref="System.ArgumentNullException">inputPath
  716. /// or
  717. /// outputPath</exception>
  718. /// <exception cref="System.ApplicationException"></exception>
  719. private async Task ExtractImageInternal(string inputPath, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, string outputPath, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  720. {
  721. if (string.IsNullOrEmpty(inputPath))
  722. {
  723. throw new ArgumentNullException("inputPath");
  724. }
  725. if (string.IsNullOrEmpty(outputPath))
  726. {
  727. throw new ArgumentNullException("outputPath");
  728. }
  729. var vf = "scale=iw*sar:ih, scale=600:-1";
  730. if (threedFormat.HasValue)
  731. {
  732. switch (threedFormat.Value)
  733. {
  734. case Video3DFormat.HalfSideBySide:
  735. case Video3DFormat.FullSideBySide:
  736. vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,scale=600:-1";
  737. break;
  738. case Video3DFormat.HalfTopAndBottom:
  739. case Video3DFormat.FullTopAndBottom:
  740. vf = "crop=iw:ih/2:0:0,scale=iw:(ih*2),scale=600:-1";
  741. break;
  742. }
  743. }
  744. 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) :
  745. string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, outputPath, vf);
  746. var probeSize = GetProbeSizeArgument(type);
  747. if (!string.IsNullOrEmpty(probeSize))
  748. {
  749. args = probeSize + " " + args;
  750. }
  751. if (offset.HasValue)
  752. {
  753. args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)).ToString(UsCulture) + args;
  754. }
  755. var process = new Process
  756. {
  757. StartInfo = new ProcessStartInfo
  758. {
  759. CreateNoWindow = true,
  760. UseShellExecute = false,
  761. FileName = FFMpegPath,
  762. Arguments = args,
  763. WindowStyle = ProcessWindowStyle.Hidden,
  764. ErrorDialog = false
  765. }
  766. };
  767. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  768. var ranToCompletion = StartAndWaitForProcess(process);
  769. resourcePool.Release();
  770. var exitCode = ranToCompletion ? process.ExitCode : -1;
  771. process.Dispose();
  772. var failed = false;
  773. if (exitCode == -1)
  774. {
  775. failed = true;
  776. if (File.Exists(outputPath))
  777. {
  778. try
  779. {
  780. _logger.Info("Deleting extracted image due to failure: ", outputPath);
  781. File.Delete(outputPath);
  782. }
  783. catch (IOException ex)
  784. {
  785. _logger.ErrorException("Error deleting extracted image {0}", ex, outputPath);
  786. }
  787. }
  788. }
  789. else if (!File.Exists(outputPath))
  790. {
  791. failed = true;
  792. }
  793. if (failed)
  794. {
  795. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  796. _logger.Error(msg);
  797. throw new ApplicationException(msg);
  798. }
  799. }
  800. /// <summary>
  801. /// Starts the and wait for process.
  802. /// </summary>
  803. /// <param name="process">The process.</param>
  804. /// <param name="timeout">The timeout.</param>
  805. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  806. private bool StartAndWaitForProcess(Process process, int timeout = 10000)
  807. {
  808. process.Start();
  809. var ranToCompletion = process.WaitForExit(timeout);
  810. if (!ranToCompletion)
  811. {
  812. try
  813. {
  814. _logger.Info("Killing ffmpeg process");
  815. process.Kill();
  816. process.WaitForExit(1000);
  817. }
  818. catch (Win32Exception ex)
  819. {
  820. _logger.ErrorException("Error killing process", ex);
  821. }
  822. catch (InvalidOperationException ex)
  823. {
  824. _logger.ErrorException("Error killing process", ex);
  825. }
  826. catch (NotSupportedException ex)
  827. {
  828. _logger.ErrorException("Error killing process", ex);
  829. }
  830. }
  831. return ranToCompletion;
  832. }
  833. /// <summary>
  834. /// Gets the file input argument.
  835. /// </summary>
  836. /// <param name="path">The path.</param>
  837. /// <returns>System.String.</returns>
  838. private string GetFileInputArgument(string path)
  839. {
  840. return string.Format("file:\"{0}\"", path);
  841. }
  842. /// <summary>
  843. /// Gets the concat input argument.
  844. /// </summary>
  845. /// <param name="playableStreamFiles">The playable stream files.</param>
  846. /// <returns>System.String.</returns>
  847. private string GetConcatInputArgument(string[] playableStreamFiles)
  848. {
  849. // Get all streams
  850. // If there's more than one we'll need to use the concat command
  851. if (playableStreamFiles.Length > 1)
  852. {
  853. var files = string.Join("|", playableStreamFiles);
  854. return string.Format("concat:\"{0}\"", files);
  855. }
  856. // Determine the input path for video files
  857. return GetFileInputArgument(playableStreamFiles[0]);
  858. }
  859. /// <summary>
  860. /// Gets the bluray input argument.
  861. /// </summary>
  862. /// <param name="blurayRoot">The bluray root.</param>
  863. /// <returns>System.String.</returns>
  864. private string GetBlurayInputArgument(string blurayRoot)
  865. {
  866. return string.Format("bluray:\"{0}\"", blurayRoot);
  867. }
  868. /// <summary>
  869. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  870. /// </summary>
  871. public void Dispose()
  872. {
  873. Dispose(true);
  874. }
  875. /// <summary>
  876. /// Releases unmanaged and - optionally - managed resources.
  877. /// </summary>
  878. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  879. protected virtual void Dispose(bool dispose)
  880. {
  881. if (dispose)
  882. {
  883. _videoImageResourcePool.Dispose();
  884. }
  885. }
  886. }
  887. }