BaseEncoder.cs 38 KB

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