BaseEncoder.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.MediaEncoding;
  6. using MediaBrowser.Controller.Session;
  7. using MediaBrowser.MediaEncoding.Subtitles;
  8. using MediaBrowser.Model.Configuration;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.Logging;
  13. using MediaBrowser.Model.MediaInfo;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Diagnostics;
  17. using System.Globalization;
  18. using System.IO;
  19. using System.Text;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. namespace MediaBrowser.MediaEncoding.Encoder
  23. {
  24. public abstract class BaseEncoder
  25. {
  26. protected readonly MediaEncoder MediaEncoder;
  27. protected readonly ILogger Logger;
  28. protected readonly IServerConfigurationManager ConfigurationManager;
  29. protected readonly IFileSystem FileSystem;
  30. protected readonly IIsoManager IsoManager;
  31. protected readonly ILibraryManager LibraryManager;
  32. protected readonly ISessionManager SessionManager;
  33. protected readonly ISubtitleEncoder SubtitleEncoder;
  34. protected readonly IMediaSourceManager MediaSourceManager;
  35. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  36. protected BaseEncoder(MediaEncoder mediaEncoder,
  37. ILogger logger,
  38. IServerConfigurationManager configurationManager,
  39. IFileSystem fileSystem,
  40. IIsoManager isoManager,
  41. ILibraryManager libraryManager,
  42. ISessionManager sessionManager,
  43. ISubtitleEncoder subtitleEncoder,
  44. IMediaSourceManager mediaSourceManager)
  45. {
  46. MediaEncoder = mediaEncoder;
  47. Logger = logger;
  48. ConfigurationManager = configurationManager;
  49. FileSystem = fileSystem;
  50. IsoManager = isoManager;
  51. LibraryManager = libraryManager;
  52. SessionManager = sessionManager;
  53. SubtitleEncoder = subtitleEncoder;
  54. MediaSourceManager = mediaSourceManager;
  55. }
  56. public async Task<EncodingJob> Start(EncodingJobOptions options,
  57. IProgress<double> progress,
  58. CancellationToken cancellationToken)
  59. {
  60. var encodingJob = await new EncodingJobFactory(Logger, LibraryManager, MediaSourceManager, ConfigurationManager)
  61. .CreateJob(options, IsVideoEncoder, progress, cancellationToken).ConfigureAwait(false);
  62. encodingJob.OutputFilePath = GetOutputFilePath(encodingJob);
  63. FileSystem.CreateDirectory(Path.GetDirectoryName(encodingJob.OutputFilePath));
  64. encodingJob.ReadInputAtNativeFramerate = options.ReadInputAtNativeFramerate;
  65. await AcquireResources(encodingJob, cancellationToken).ConfigureAwait(false);
  66. var commandLineArgs = GetCommandLineArguments(encodingJob);
  67. if (GetEncodingOptions().EnableDebugLogging)
  68. {
  69. commandLineArgs = "-loglevel debug " + commandLineArgs;
  70. }
  71. var process = new Process
  72. {
  73. StartInfo = new ProcessStartInfo
  74. {
  75. CreateNoWindow = true,
  76. UseShellExecute = false,
  77. // Must consume both stdout and stderr or deadlocks may occur
  78. RedirectStandardOutput = true,
  79. RedirectStandardError = true,
  80. RedirectStandardInput = true,
  81. FileName = MediaEncoder.EncoderPath,
  82. Arguments = commandLineArgs,
  83. WindowStyle = ProcessWindowStyle.Hidden,
  84. ErrorDialog = false
  85. },
  86. EnableRaisingEvents = true
  87. };
  88. var workingDirectory = GetWorkingDirectory(options);
  89. if (!string.IsNullOrWhiteSpace(workingDirectory))
  90. {
  91. process.StartInfo.WorkingDirectory = workingDirectory;
  92. }
  93. OnTranscodeBeginning(encodingJob);
  94. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  95. Logger.Info(commandLineLogMessage);
  96. var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
  97. FileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
  98. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  99. encodingJob.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  100. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  101. await encodingJob.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationToken).ConfigureAwait(false);
  102. process.Exited += (sender, args) => OnFfMpegProcessExited(process, encodingJob);
  103. try
  104. {
  105. process.Start();
  106. }
  107. catch (Exception ex)
  108. {
  109. Logger.ErrorException("Error starting ffmpeg", ex);
  110. OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob);
  111. throw;
  112. }
  113. cancellationToken.Register(() => Cancel(process, encodingJob));
  114. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  115. process.BeginOutputReadLine();
  116. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  117. new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream);
  118. // Wait for the file to exist before proceeeding
  119. while (!FileSystem.FileExists(encodingJob.OutputFilePath) && !encodingJob.HasExited)
  120. {
  121. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  122. }
  123. return encodingJob;
  124. }
  125. private void Cancel(Process process, EncodingJob job)
  126. {
  127. Logger.Info("Killing ffmpeg process for {0}", job.OutputFilePath);
  128. //process.Kill();
  129. process.StandardInput.WriteLine("q");
  130. job.IsCancelled = true;
  131. }
  132. /// <summary>
  133. /// Processes the exited.
  134. /// </summary>
  135. /// <param name="process">The process.</param>
  136. /// <param name="job">The job.</param>
  137. private void OnFfMpegProcessExited(Process process, EncodingJob job)
  138. {
  139. job.HasExited = true;
  140. Logger.Debug("Disposing stream resources");
  141. job.Dispose();
  142. var isSuccesful = false;
  143. try
  144. {
  145. var exitCode = process.ExitCode;
  146. Logger.Info("FFMpeg exited with code {0}", exitCode);
  147. isSuccesful = exitCode == 0;
  148. }
  149. catch
  150. {
  151. Logger.Error("FFMpeg exited with an error.");
  152. }
  153. if (isSuccesful && !job.IsCancelled)
  154. {
  155. job.TaskCompletionSource.TrySetResult(true);
  156. }
  157. else if (job.IsCancelled)
  158. {
  159. try
  160. {
  161. DeleteFiles(job);
  162. }
  163. catch
  164. {
  165. }
  166. try
  167. {
  168. job.TaskCompletionSource.TrySetException(new OperationCanceledException());
  169. }
  170. catch
  171. {
  172. }
  173. }
  174. else
  175. {
  176. try
  177. {
  178. DeleteFiles(job);
  179. }
  180. catch
  181. {
  182. }
  183. try
  184. {
  185. job.TaskCompletionSource.TrySetException(new ApplicationException("Encoding failed"));
  186. }
  187. catch
  188. {
  189. }
  190. }
  191. // This causes on exited to be called twice:
  192. //try
  193. //{
  194. // // Dispose the process
  195. // process.Dispose();
  196. //}
  197. //catch (Exception ex)
  198. //{
  199. // Logger.ErrorException("Error disposing ffmpeg.", ex);
  200. //}
  201. }
  202. protected virtual void DeleteFiles(EncodingJob job)
  203. {
  204. FileSystem.DeleteFile(job.OutputFilePath);
  205. }
  206. private void OnTranscodeBeginning(EncodingJob job)
  207. {
  208. job.ReportTranscodingProgress(null, null, null, null);
  209. }
  210. private void OnTranscodeFailedToStart(string path, EncodingJob job)
  211. {
  212. if (!string.IsNullOrWhiteSpace(job.Options.DeviceId))
  213. {
  214. SessionManager.ClearTranscodingInfo(job.Options.DeviceId);
  215. }
  216. }
  217. protected abstract bool IsVideoEncoder { get; }
  218. protected virtual string GetWorkingDirectory(EncodingJobOptions options)
  219. {
  220. return null;
  221. }
  222. protected EncodingOptions GetEncodingOptions()
  223. {
  224. return ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
  225. }
  226. protected abstract string GetCommandLineArguments(EncodingJob job);
  227. private string GetOutputFilePath(EncodingJob state)
  228. {
  229. var folder = string.IsNullOrWhiteSpace(state.Options.OutputDirectory) ?
  230. ConfigurationManager.ApplicationPaths.TranscodingTempPath :
  231. state.Options.OutputDirectory;
  232. var outputFileExtension = GetOutputFileExtension(state);
  233. var filename = state.Id + (outputFileExtension ?? string.Empty).ToLower();
  234. return Path.Combine(folder, filename);
  235. }
  236. protected virtual string GetOutputFileExtension(EncodingJob state)
  237. {
  238. if (!string.IsNullOrWhiteSpace(state.Options.OutputContainer))
  239. {
  240. return "." + state.Options.OutputContainer;
  241. }
  242. return null;
  243. }
  244. /// <summary>
  245. /// Gets the number of threads.
  246. /// </summary>
  247. /// <returns>System.Int32.</returns>
  248. protected int GetNumberOfThreads(EncodingJob job, bool isWebm)
  249. {
  250. return job.Options.CpuCoreLimit ?? 0;
  251. }
  252. protected string GetInputModifier(EncodingJob job, bool genPts = true)
  253. {
  254. var inputModifier = string.Empty;
  255. var probeSize = GetProbeSizeArgument(job);
  256. inputModifier += " " + probeSize;
  257. inputModifier = inputModifier.Trim();
  258. var userAgentParam = GetUserAgentParam(job);
  259. if (!string.IsNullOrWhiteSpace(userAgentParam))
  260. {
  261. inputModifier += " " + userAgentParam;
  262. }
  263. inputModifier = inputModifier.Trim();
  264. inputModifier += " " + GetFastSeekCommandLineParameter(job.Options);
  265. inputModifier = inputModifier.Trim();
  266. if (job.IsVideoRequest && genPts)
  267. {
  268. inputModifier += " -fflags +genpts";
  269. }
  270. if (!string.IsNullOrEmpty(job.InputAudioSync))
  271. {
  272. inputModifier += " -async " + job.InputAudioSync;
  273. }
  274. if (!string.IsNullOrEmpty(job.InputVideoSync))
  275. {
  276. inputModifier += " -vsync " + job.InputVideoSync;
  277. }
  278. if (job.ReadInputAtNativeFramerate)
  279. {
  280. inputModifier += " -re";
  281. }
  282. return inputModifier;
  283. }
  284. private string GetUserAgentParam(EncodingJob job)
  285. {
  286. string useragent = null;
  287. job.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  288. if (!string.IsNullOrWhiteSpace(useragent))
  289. {
  290. return "-user-agent \"" + useragent + "\"";
  291. }
  292. return string.Empty;
  293. }
  294. /// <summary>
  295. /// Gets the probe size argument.
  296. /// </summary>
  297. /// <param name="job">The job.</param>
  298. /// <returns>System.String.</returns>
  299. private string GetProbeSizeArgument(EncodingJob job)
  300. {
  301. if (job.PlayableStreamFileNames.Count > 0)
  302. {
  303. return MediaEncoder.GetProbeSizeArgument(job.PlayableStreamFileNames.ToArray(), job.InputProtocol);
  304. }
  305. return MediaEncoder.GetProbeSizeArgument(new[] { job.MediaPath }, job.InputProtocol);
  306. }
  307. /// <summary>
  308. /// Gets the fast seek command line parameter.
  309. /// </summary>
  310. /// <param name="options">The options.</param>
  311. /// <returns>System.String.</returns>
  312. /// <value>The fast seek command line parameter.</value>
  313. protected string GetFastSeekCommandLineParameter(EncodingJobOptions options)
  314. {
  315. var time = options.StartTimeTicks;
  316. if (time.HasValue && time.Value > 0)
  317. {
  318. return string.Format("-ss {0}", MediaEncoder.GetTimeParameter(time.Value));
  319. }
  320. return string.Empty;
  321. }
  322. /// <summary>
  323. /// Gets the input argument.
  324. /// </summary>
  325. /// <param name="job">The job.</param>
  326. /// <returns>System.String.</returns>
  327. protected string GetInputArgument(EncodingJob job)
  328. {
  329. var arg = "-i " + GetInputPathArgument(job);
  330. if (job.SubtitleStream != null)
  331. {
  332. if (job.SubtitleStream.IsExternal && !job.SubtitleStream.IsTextSubtitleStream)
  333. {
  334. arg += " -i \"" + job.SubtitleStream.Path + "\"";
  335. }
  336. }
  337. return arg;
  338. }
  339. private string GetInputPathArgument(EncodingJob job)
  340. {
  341. var protocol = job.InputProtocol;
  342. var inputPath = new[] { job.MediaPath };
  343. if (job.IsInputVideo)
  344. {
  345. if (!(job.VideoType == VideoType.Iso && job.IsoMount == null))
  346. {
  347. inputPath = MediaEncoderHelpers.GetInputArgument(job.MediaPath, job.InputProtocol, job.IsoMount, job.PlayableStreamFileNames);
  348. }
  349. }
  350. return MediaEncoder.GetInputArgument(inputPath, protocol);
  351. }
  352. private async Task AcquireResources(EncodingJob state, CancellationToken cancellationToken)
  353. {
  354. if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  355. {
  356. state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationToken).ConfigureAwait(false);
  357. }
  358. if (state.MediaSource.RequiresOpening)
  359. {
  360. var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
  361. {
  362. OpenToken = state.MediaSource.OpenToken
  363. }, false, cancellationToken).ConfigureAwait(false);
  364. AttachMediaStreamInfo(state, liveStreamResponse.MediaSource, state.Options);
  365. if (state.IsVideoRequest)
  366. {
  367. EncodingJobFactory.TryStreamCopy(state, state.Options);
  368. }
  369. }
  370. if (state.MediaSource.BufferMs.HasValue)
  371. {
  372. await Task.Delay(state.MediaSource.BufferMs.Value, cancellationToken).ConfigureAwait(false);
  373. }
  374. }
  375. private void AttachMediaStreamInfo(EncodingJob state,
  376. MediaSourceInfo mediaSource,
  377. EncodingJobOptions videoRequest)
  378. {
  379. EncodingJobFactory.AttachMediaStreamInfo(state, mediaSource, videoRequest);
  380. }
  381. /// <summary>
  382. /// Gets the internal graphical subtitle param.
  383. /// </summary>
  384. /// <param name="state">The state.</param>
  385. /// <param name="outputVideoCodec">The output video codec.</param>
  386. /// <returns>System.String.</returns>
  387. protected string GetGraphicalSubtitleParam(EncodingJob state, string outputVideoCodec)
  388. {
  389. var outputSizeParam = string.Empty;
  390. var request = state.Options;
  391. // Add resolution params, if specified
  392. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  393. {
  394. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec).TrimEnd('"');
  395. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  396. }
  397. var videoSizeParam = string.Empty;
  398. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  399. {
  400. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  401. }
  402. var mapPrefix = state.SubtitleStream.IsExternal ?
  403. 1 :
  404. 0;
  405. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  406. ? 0
  407. : state.SubtitleStream.Index;
  408. return string.Format(" -filter_complex \"[{0}:{1}]format=yuva444p{4},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{2}] [sub] overlay{3}\"",
  409. mapPrefix.ToString(UsCulture),
  410. subtitleStreamIndex.ToString(UsCulture),
  411. state.VideoStream.Index.ToString(UsCulture),
  412. outputSizeParam,
  413. videoSizeParam);
  414. }
  415. /// <summary>
  416. /// Gets the video bitrate to specify on the command line
  417. /// </summary>
  418. /// <param name="state">The state.</param>
  419. /// <param name="videoCodec">The video codec.</param>
  420. /// <param name="isHls">if set to <c>true</c> [is HLS].</param>
  421. /// <returns>System.String.</returns>
  422. protected string GetVideoQualityParam(EncodingJob state, string videoCodec, bool isHls)
  423. {
  424. var param = string.Empty;
  425. var isVc1 = state.VideoStream != null &&
  426. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  427. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  428. {
  429. param = "-preset superfast";
  430. param += " -crf 28";
  431. }
  432. else if (string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  433. {
  434. param = "-preset fast";
  435. param += " -crf 28";
  436. }
  437. // webm
  438. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  439. {
  440. // Values 0-3, 0 being highest quality but slower
  441. var profileScore = 0;
  442. string crf;
  443. var qmin = "0";
  444. var qmax = "50";
  445. crf = "10";
  446. if (isVc1)
  447. {
  448. profileScore++;
  449. }
  450. // Max of 2
  451. profileScore = Math.Min(profileScore, 2);
  452. // http://www.webmproject.org/docs/encoder-parameters/
  453. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  454. profileScore.ToString(UsCulture),
  455. crf,
  456. qmin,
  457. qmax);
  458. }
  459. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  460. {
  461. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  462. }
  463. // asf/wmv
  464. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  465. {
  466. param = "-qmin 2";
  467. }
  468. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  469. {
  470. param = "-mbd 2";
  471. }
  472. param += GetVideoBitrateParam(state, videoCodec, isHls);
  473. var framerate = GetFramerateParam(state);
  474. if (framerate.HasValue)
  475. {
  476. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  477. }
  478. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  479. {
  480. param += " -vsync " + state.OutputVideoSync;
  481. }
  482. if (!string.IsNullOrEmpty(state.Options.Profile))
  483. {
  484. param += " -profile:v " + state.Options.Profile;
  485. }
  486. if (state.Options.Level.HasValue)
  487. {
  488. param += " -level " + state.Options.Level.Value.ToString(UsCulture);
  489. }
  490. return "-pix_fmt yuv420p " + param;
  491. }
  492. protected string GetVideoBitrateParam(EncodingJob state, string videoCodec, bool isHls)
  493. {
  494. var bitrate = state.OutputVideoBitrate;
  495. if (bitrate.HasValue)
  496. {
  497. var hasFixedResolution = state.Options.HasFixedResolution;
  498. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  499. {
  500. if (hasFixedResolution)
  501. {
  502. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  503. }
  504. // With vpx when crf is used, b:v becomes a max rate
  505. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide. But higher bitrate source files -b:v causes judder so limite the bitrate but dont allow it to "saturate" the bitrate. So dont contrain it down just up.
  506. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  507. }
  508. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  509. {
  510. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  511. }
  512. // H264
  513. if (hasFixedResolution)
  514. {
  515. if (isHls)
  516. {
  517. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  518. }
  519. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  520. }
  521. return string.Format(" -maxrate {0} -bufsize {1}",
  522. bitrate.Value.ToString(UsCulture),
  523. (bitrate.Value * 2).ToString(UsCulture));
  524. }
  525. return string.Empty;
  526. }
  527. protected double? GetFramerateParam(EncodingJob state)
  528. {
  529. if (state.Options.Framerate.HasValue)
  530. {
  531. return state.Options.Framerate.Value;
  532. }
  533. var maxrate = state.Options.MaxFramerate;
  534. if (maxrate.HasValue && state.VideoStream != null)
  535. {
  536. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  537. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  538. {
  539. return maxrate;
  540. }
  541. }
  542. return null;
  543. }
  544. /// <summary>
  545. /// Gets the map args.
  546. /// </summary>
  547. /// <param name="state">The state.</param>
  548. /// <returns>System.String.</returns>
  549. protected virtual string GetMapArgs(EncodingJob state)
  550. {
  551. // If we don't have known media info
  552. // If input is video, use -sn to drop subtitles
  553. // Otherwise just return empty
  554. if (state.VideoStream == null && state.AudioStream == null)
  555. {
  556. return state.IsInputVideo ? "-sn" : string.Empty;
  557. }
  558. // We have media info, but we don't know the stream indexes
  559. if (state.VideoStream != null && state.VideoStream.Index == -1)
  560. {
  561. return "-sn";
  562. }
  563. // We have media info, but we don't know the stream indexes
  564. if (state.AudioStream != null && state.AudioStream.Index == -1)
  565. {
  566. return state.IsInputVideo ? "-sn" : string.Empty;
  567. }
  568. var args = string.Empty;
  569. if (state.VideoStream != null)
  570. {
  571. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  572. }
  573. else
  574. {
  575. args += "-map -0:v";
  576. }
  577. if (state.AudioStream != null)
  578. {
  579. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  580. }
  581. else
  582. {
  583. args += " -map -0:a";
  584. }
  585. if (state.SubtitleStream == null)
  586. {
  587. args += " -map -0:s";
  588. }
  589. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  590. {
  591. args += " -map 1:0 -sn";
  592. }
  593. return args;
  594. }
  595. /// <summary>
  596. /// Determines whether the specified stream is H264.
  597. /// </summary>
  598. /// <param name="stream">The stream.</param>
  599. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  600. protected bool IsH264(MediaStream stream)
  601. {
  602. var codec = stream.Codec ?? string.Empty;
  603. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  604. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  605. }
  606. /// <summary>
  607. /// If we're going to put a fixed size on the command line, this will calculate it
  608. /// </summary>
  609. /// <param name="state">The state.</param>
  610. /// <param name="outputVideoCodec">The output video codec.</param>
  611. /// <param name="allowTimeStampCopy">if set to <c>true</c> [allow time stamp copy].</param>
  612. /// <returns>System.String.</returns>
  613. protected string GetOutputSizeParam(EncodingJob state,
  614. string outputVideoCodec,
  615. bool allowTimeStampCopy = true)
  616. {
  617. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  618. var request = state.Options;
  619. var filters = new List<string>();
  620. if (state.DeInterlace)
  621. {
  622. filters.Add("yadif=0:-1:0");
  623. }
  624. // If fixed dimensions were supplied
  625. if (request.Width.HasValue && request.Height.HasValue)
  626. {
  627. var widthParam = request.Width.Value.ToString(UsCulture);
  628. var heightParam = request.Height.Value.ToString(UsCulture);
  629. filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", widthParam, heightParam));
  630. }
  631. // If Max dimensions were supplied, for width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size
  632. else if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  633. {
  634. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  635. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  636. filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/2)*2:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2", maxWidthParam, maxHeightParam));
  637. }
  638. // If a fixed width was requested
  639. else if (request.Width.HasValue)
  640. {
  641. var widthParam = request.Width.Value.ToString(UsCulture);
  642. filters.Add(string.Format("scale={0}:trunc(ow/a/2)*2", widthParam));
  643. }
  644. // If a fixed height was requested
  645. else if (request.Height.HasValue)
  646. {
  647. var heightParam = request.Height.Value.ToString(UsCulture);
  648. filters.Add(string.Format("scale=trunc(oh*a/2)*2:{0}", heightParam));
  649. }
  650. // If a max width was requested
  651. else if (request.MaxWidth.HasValue)
  652. {
  653. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  654. filters.Add(string.Format("scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam));
  655. }
  656. // If a max height was requested
  657. else if (request.MaxHeight.HasValue)
  658. {
  659. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  660. filters.Add(string.Format("scale=trunc(oh*a/2)*2:min(ih\\,{0})", maxHeightParam));
  661. }
  662. var output = string.Empty;
  663. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream)
  664. {
  665. var subParam = GetTextSubtitleParam(state);
  666. filters.Add(subParam);
  667. if (allowTimeStampCopy)
  668. {
  669. output += " -copyts";
  670. }
  671. }
  672. if (filters.Count > 0)
  673. {
  674. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  675. }
  676. return output;
  677. }
  678. /// <summary>
  679. /// Gets the text subtitle param.
  680. /// </summary>
  681. /// <param name="state">The state.</param>
  682. /// <returns>System.String.</returns>
  683. protected string GetTextSubtitleParam(EncodingJob state)
  684. {
  685. var seconds = Math.Round(TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds);
  686. if (state.SubtitleStream.IsExternal)
  687. {
  688. var subtitlePath = state.SubtitleStream.Path;
  689. var charsetParam = string.Empty;
  690. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  691. {
  692. var charenc = SubtitleEncoder.GetSubtitleFileCharacterSet(subtitlePath, state.MediaSource.Protocol, CancellationToken.None).Result;
  693. if (!string.IsNullOrEmpty(charenc))
  694. {
  695. charsetParam = ":charenc=" + charenc;
  696. }
  697. }
  698. // TODO: Perhaps also use original_size=1920x800 ??
  699. return string.Format("subtitles=filename='{0}'{1},setpts=PTS -{2}/TB",
  700. MediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  701. charsetParam,
  702. seconds.ToString(UsCulture));
  703. }
  704. return string.Format("subtitles='{0}:si={1}',setpts=PTS -{2}/TB",
  705. MediaEncoder.EscapeSubtitleFilterPath(state.MediaPath),
  706. state.InternalSubtitleStreamOffset.ToString(UsCulture),
  707. seconds.ToString(UsCulture));
  708. }
  709. protected string GetAudioFilterParam(EncodingJob state, bool isHls)
  710. {
  711. var volParam = string.Empty;
  712. var audioSampleRate = string.Empty;
  713. var channels = state.OutputAudioChannels;
  714. // Boost volume to 200% when downsampling from 6ch to 2ch
  715. if (channels.HasValue && channels.Value <= 2)
  716. {
  717. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  718. {
  719. volParam = ",volume=" + GetEncodingOptions().DownMixAudioBoost.ToString(UsCulture);
  720. }
  721. }
  722. if (state.OutputAudioSampleRate.HasValue)
  723. {
  724. audioSampleRate = state.OutputAudioSampleRate.Value + ":";
  725. }
  726. var adelay = isHls ? "adelay=1," : string.Empty;
  727. var pts = string.Empty;
  728. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream)
  729. {
  730. var seconds = TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds;
  731. pts = string.Format(",asetpts=PTS-{0}/TB", Math.Round(seconds).ToString(UsCulture));
  732. }
  733. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  734. adelay,
  735. audioSampleRate,
  736. volParam,
  737. pts,
  738. state.OutputAudioSync);
  739. }
  740. }
  741. }