VideoHlsController.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Api.Attributes;
  9. using Jellyfin.Api.Constants;
  10. using Jellyfin.Api.Helpers;
  11. using Jellyfin.Api.Models.PlaybackDtos;
  12. using Jellyfin.Api.Models.StreamingDtos;
  13. using MediaBrowser.Common.Configuration;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Devices;
  16. using MediaBrowser.Controller.Dlna;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.MediaEncoding;
  19. using MediaBrowser.Controller.Net;
  20. using MediaBrowser.Model.Configuration;
  21. using MediaBrowser.Model.Dlna;
  22. using MediaBrowser.Model.IO;
  23. using MediaBrowser.Model.Net;
  24. using Microsoft.AspNetCore.Authorization;
  25. using Microsoft.AspNetCore.Http;
  26. using Microsoft.AspNetCore.Mvc;
  27. using Microsoft.Extensions.Configuration;
  28. using Microsoft.Extensions.Logging;
  29. namespace Jellyfin.Api.Controllers
  30. {
  31. /// <summary>
  32. /// The video hls controller.
  33. /// </summary>
  34. [Route("")]
  35. [Authorize(Policy = Policies.DefaultAuthorization)]
  36. public class VideoHlsController : BaseJellyfinApiController
  37. {
  38. private const string DefaultEncoderPreset = "superfast";
  39. private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls;
  40. private readonly EncodingHelper _encodingHelper;
  41. private readonly IDlnaManager _dlnaManager;
  42. private readonly IAuthorizationContext _authContext;
  43. private readonly IUserManager _userManager;
  44. private readonly ILibraryManager _libraryManager;
  45. private readonly IMediaSourceManager _mediaSourceManager;
  46. private readonly IServerConfigurationManager _serverConfigurationManager;
  47. private readonly IMediaEncoder _mediaEncoder;
  48. private readonly IFileSystem _fileSystem;
  49. private readonly ISubtitleEncoder _subtitleEncoder;
  50. private readonly IConfiguration _configuration;
  51. private readonly IDeviceManager _deviceManager;
  52. private readonly TranscodingJobHelper _transcodingJobHelper;
  53. private readonly ILogger<VideoHlsController> _logger;
  54. private readonly EncodingOptions _encodingOptions;
  55. /// <summary>
  56. /// Initializes a new instance of the <see cref="VideoHlsController"/> class.
  57. /// </summary>
  58. /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
  59. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  60. /// <param name="subtitleEncoder">Instance of the <see cref="ISubtitleEncoder"/> interface.</param>
  61. /// <param name="configuration">Instance of the <see cref="IConfiguration"/> interface.</param>
  62. /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
  63. /// <param name="userManger">Instance of the <see cref="IUserManager"/> interface.</param>
  64. /// <param name="authorizationContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
  65. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  66. /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
  67. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  68. /// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
  69. /// <param name="transcodingJobHelper">The <see cref="TranscodingJobHelper"/> singleton.</param>
  70. /// <param name="logger">Instance of the <see cref="ILogger{VideoHlsController}"/>.</param>
  71. public VideoHlsController(
  72. IMediaEncoder mediaEncoder,
  73. IFileSystem fileSystem,
  74. ISubtitleEncoder subtitleEncoder,
  75. IConfiguration configuration,
  76. IDlnaManager dlnaManager,
  77. IUserManager userManger,
  78. IAuthorizationContext authorizationContext,
  79. ILibraryManager libraryManager,
  80. IMediaSourceManager mediaSourceManager,
  81. IServerConfigurationManager serverConfigurationManager,
  82. IDeviceManager deviceManager,
  83. TranscodingJobHelper transcodingJobHelper,
  84. ILogger<VideoHlsController> logger)
  85. {
  86. _encodingHelper = new EncodingHelper(mediaEncoder, fileSystem, subtitleEncoder, configuration);
  87. _dlnaManager = dlnaManager;
  88. _authContext = authorizationContext;
  89. _userManager = userManger;
  90. _libraryManager = libraryManager;
  91. _mediaSourceManager = mediaSourceManager;
  92. _serverConfigurationManager = serverConfigurationManager;
  93. _mediaEncoder = mediaEncoder;
  94. _fileSystem = fileSystem;
  95. _subtitleEncoder = subtitleEncoder;
  96. _configuration = configuration;
  97. _deviceManager = deviceManager;
  98. _transcodingJobHelper = transcodingJobHelper;
  99. _logger = logger;
  100. _encodingOptions = serverConfigurationManager.GetEncodingOptions();
  101. }
  102. /// <summary>
  103. /// Gets a hls live stream.
  104. /// </summary>
  105. /// <param name="itemId">The item id.</param>
  106. /// <param name="container">The audio container.</param>
  107. /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
  108. /// <param name="params">The streaming parameters.</param>
  109. /// <param name="tag">The tag.</param>
  110. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  111. /// <param name="playSessionId">The play session id.</param>
  112. /// <param name="segmentContainer">The segment container.</param>
  113. /// <param name="segmentLength">The segment lenght.</param>
  114. /// <param name="minSegments">The minimum number of segments.</param>
  115. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  116. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  117. /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param>
  118. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  119. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  120. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  121. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  122. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  123. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  124. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  125. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  126. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  127. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  128. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  129. /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
  130. /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
  131. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  132. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  133. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  134. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  135. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  136. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  137. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  138. /// <param name="maxRefFrames">Optional.</param>
  139. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  140. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  141. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  142. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param>
  143. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  144. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  145. /// <param name="liveStreamId">The live stream id.</param>
  146. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  147. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param>
  148. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  149. /// <param name="transcodingReasons">Optional. The transcoding reason.</param>
  150. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  151. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  152. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  153. /// <param name="streamOptions">Optional. The streaming options.</param>
  154. /// <param name="maxWidth">Optional. The max width.</param>
  155. /// <param name="maxHeight">Optional. The max height.</param>
  156. /// <param name="enableSubtitlesInManifest">Optional. Whether to enable subtitles in the manifest.</param>
  157. /// <response code="200">Hls live stream retrieved.</response>
  158. /// <returns>A <see cref="FileResult"/> containing the hls file.</returns>
  159. [HttpGet("Videos/{itemId}/live.m3u8")]
  160. [ProducesResponseType(StatusCodes.Status200OK)]
  161. [ProducesPlaylistFile]
  162. public async Task<ActionResult> GetLiveHlsStream(
  163. [FromRoute, Required] Guid itemId,
  164. [FromQuery] string? container,
  165. [FromQuery] bool? @static,
  166. [FromQuery] string? @params,
  167. [FromQuery] string? tag,
  168. [FromQuery] string? deviceProfileId,
  169. [FromQuery] string? playSessionId,
  170. [FromQuery] string? segmentContainer,
  171. [FromQuery] int? segmentLength,
  172. [FromQuery] int? minSegments,
  173. [FromQuery] string? mediaSourceId,
  174. [FromQuery] string? deviceId,
  175. [FromQuery] string? audioCodec,
  176. [FromQuery] bool? enableAutoStreamCopy,
  177. [FromQuery] bool? allowVideoStreamCopy,
  178. [FromQuery] bool? allowAudioStreamCopy,
  179. [FromQuery] bool? breakOnNonKeyFrames,
  180. [FromQuery] int? audioSampleRate,
  181. [FromQuery] int? maxAudioBitDepth,
  182. [FromQuery] int? audioBitRate,
  183. [FromQuery] int? audioChannels,
  184. [FromQuery] int? maxAudioChannels,
  185. [FromQuery] string? profile,
  186. [FromQuery] string? level,
  187. [FromQuery] float? framerate,
  188. [FromQuery] float? maxFramerate,
  189. [FromQuery] bool? copyTimestamps,
  190. [FromQuery] long? startTimeTicks,
  191. [FromQuery] int? width,
  192. [FromQuery] int? height,
  193. [FromQuery] int? videoBitRate,
  194. [FromQuery] int? subtitleStreamIndex,
  195. [FromQuery] SubtitleDeliveryMethod subtitleMethod,
  196. [FromQuery] int? maxRefFrames,
  197. [FromQuery] int? maxVideoBitDepth,
  198. [FromQuery] bool? requireAvc,
  199. [FromQuery] bool? deInterlace,
  200. [FromQuery] bool? requireNonAnamorphic,
  201. [FromQuery] int? transcodingMaxAudioChannels,
  202. [FromQuery] int? cpuCoreLimit,
  203. [FromQuery] string? liveStreamId,
  204. [FromQuery] bool? enableMpegtsM2TsMode,
  205. [FromQuery] string? videoCodec,
  206. [FromQuery] string? subtitleCodec,
  207. [FromQuery] string? transcodingReasons,
  208. [FromQuery] int? audioStreamIndex,
  209. [FromQuery] int? videoStreamIndex,
  210. [FromQuery] EncodingContext context,
  211. [FromQuery] Dictionary<string, string> streamOptions,
  212. [FromQuery] int? maxWidth,
  213. [FromQuery] int? maxHeight,
  214. [FromQuery] bool? enableSubtitlesInManifest)
  215. {
  216. VideoRequestDto streamingRequest = new VideoRequestDto
  217. {
  218. Id = itemId,
  219. Container = container,
  220. Static = @static ?? true,
  221. Params = @params,
  222. Tag = tag,
  223. DeviceProfileId = deviceProfileId,
  224. PlaySessionId = playSessionId,
  225. SegmentContainer = segmentContainer,
  226. SegmentLength = segmentLength,
  227. MinSegments = minSegments,
  228. MediaSourceId = mediaSourceId,
  229. DeviceId = deviceId,
  230. AudioCodec = audioCodec,
  231. EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
  232. AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
  233. AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
  234. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  235. AudioSampleRate = audioSampleRate,
  236. MaxAudioChannels = maxAudioChannels,
  237. AudioBitRate = audioBitRate,
  238. MaxAudioBitDepth = maxAudioBitDepth,
  239. AudioChannels = audioChannels,
  240. Profile = profile,
  241. Level = level,
  242. Framerate = framerate,
  243. MaxFramerate = maxFramerate,
  244. CopyTimestamps = copyTimestamps ?? true,
  245. StartTimeTicks = startTimeTicks,
  246. Width = width,
  247. Height = height,
  248. VideoBitRate = videoBitRate,
  249. SubtitleStreamIndex = subtitleStreamIndex,
  250. SubtitleMethod = subtitleMethod,
  251. MaxRefFrames = maxRefFrames,
  252. MaxVideoBitDepth = maxVideoBitDepth,
  253. RequireAvc = requireAvc ?? true,
  254. DeInterlace = deInterlace ?? true,
  255. RequireNonAnamorphic = requireNonAnamorphic ?? true,
  256. TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
  257. CpuCoreLimit = cpuCoreLimit,
  258. LiveStreamId = liveStreamId,
  259. EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true,
  260. VideoCodec = videoCodec,
  261. SubtitleCodec = subtitleCodec,
  262. TranscodeReasons = transcodingReasons,
  263. AudioStreamIndex = audioStreamIndex,
  264. VideoStreamIndex = videoStreamIndex,
  265. Context = context,
  266. StreamOptions = streamOptions,
  267. MaxHeight = maxHeight,
  268. MaxWidth = maxWidth,
  269. EnableSubtitlesInManifest = enableSubtitlesInManifest ?? true
  270. };
  271. var cancellationTokenSource = new CancellationTokenSource();
  272. using var state = await StreamingHelpers.GetStreamingState(
  273. streamingRequest,
  274. Request,
  275. _authContext,
  276. _mediaSourceManager,
  277. _userManager,
  278. _libraryManager,
  279. _serverConfigurationManager,
  280. _mediaEncoder,
  281. _fileSystem,
  282. _subtitleEncoder,
  283. _configuration,
  284. _dlnaManager,
  285. _deviceManager,
  286. _transcodingJobHelper,
  287. TranscodingJobType,
  288. cancellationTokenSource.Token)
  289. .ConfigureAwait(false);
  290. TranscodingJobDto? job = null;
  291. var playlist = state.OutputFilePath;
  292. if (!System.IO.File.Exists(playlist))
  293. {
  294. var transcodingLock = _transcodingJobHelper.GetTranscodingLock(playlist);
  295. await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  296. try
  297. {
  298. if (!System.IO.File.Exists(playlist))
  299. {
  300. // If the playlist doesn't already exist, startup ffmpeg
  301. try
  302. {
  303. job = await _transcodingJobHelper.StartFfMpeg(
  304. state,
  305. playlist,
  306. GetCommandLineArguments(playlist, state),
  307. Request,
  308. TranscodingJobType,
  309. cancellationTokenSource)
  310. .ConfigureAwait(false);
  311. job.IsLiveOutput = true;
  312. }
  313. catch
  314. {
  315. state.Dispose();
  316. throw;
  317. }
  318. minSegments = state.MinSegments;
  319. if (minSegments > 0)
  320. {
  321. await HlsHelpers.WaitForMinimumSegmentCount(playlist, minSegments, _logger, cancellationTokenSource.Token).ConfigureAwait(false);
  322. }
  323. }
  324. }
  325. finally
  326. {
  327. transcodingLock.Release();
  328. }
  329. }
  330. job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlist, TranscodingJobType);
  331. if (job != null)
  332. {
  333. _transcodingJobHelper.OnTranscodeEndRequest(job);
  334. }
  335. var playlistText = HlsHelpers.GetLivePlaylistText(playlist, state.SegmentLength);
  336. return Content(playlistText, MimeTypes.GetMimeType("playlist.m3u8"));
  337. }
  338. /// <summary>
  339. /// Gets the command line arguments for ffmpeg.
  340. /// </summary>
  341. /// <param name="outputPath">The output path of the file.</param>
  342. /// <param name="state">The <see cref="StreamState"/>.</param>
  343. /// <returns>The command line arguments as a string.</returns>
  344. private string GetCommandLineArguments(string outputPath, StreamState state)
  345. {
  346. var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
  347. var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec);
  348. var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions);
  349. var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts";
  350. var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format;
  351. var segmentFormat = format.TrimStart('.');
  352. if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase))
  353. {
  354. segmentFormat = "mpegts";
  355. }
  356. var baseUrlParam = string.Format(
  357. CultureInfo.InvariantCulture,
  358. "\"hls{0}\"",
  359. Path.GetFileNameWithoutExtension(outputPath));
  360. return string.Format(
  361. CultureInfo.InvariantCulture,
  362. "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -f segment -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero -segment_time {6} {7} -individual_header_trailer 0 -segment_format {8} -segment_list_entry_prefix {9} -segment_list_type m3u8 -segment_start_number 0 -segment_list \"{10}\" -y \"{11}\"",
  363. inputModifier,
  364. _encodingHelper.GetInputArgument(state, _encodingOptions),
  365. threads,
  366. _encodingHelper.GetMapArgs(state),
  367. GetVideoArguments(state),
  368. GetAudioArguments(state),
  369. state.SegmentLength.ToString(CultureInfo.InvariantCulture),
  370. string.Empty,
  371. segmentFormat,
  372. baseUrlParam,
  373. outputPath,
  374. outputTsArg)
  375. .Trim();
  376. }
  377. /// <summary>
  378. /// Gets the audio arguments for transcoding.
  379. /// </summary>
  380. /// <param name="state">The <see cref="StreamState"/>.</param>
  381. /// <returns>The command line arguments for audio transcoding.</returns>
  382. private string GetAudioArguments(StreamState state)
  383. {
  384. var codec = _encodingHelper.GetAudioEncoder(state);
  385. if (EncodingHelper.IsCopyCodec(codec))
  386. {
  387. return "-codec:a:0 copy";
  388. }
  389. var args = "-codec:a:0 " + codec;
  390. var channels = state.OutputAudioChannels;
  391. if (channels.HasValue)
  392. {
  393. args += " -ac " + channels.Value;
  394. }
  395. var bitrate = state.OutputAudioBitrate;
  396. if (bitrate.HasValue)
  397. {
  398. args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
  399. }
  400. if (state.OutputAudioSampleRate.HasValue)
  401. {
  402. args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
  403. }
  404. args += " " + _encodingHelper.GetAudioFilterParam(state, _encodingOptions, true);
  405. return args;
  406. }
  407. /// <summary>
  408. /// Gets the video arguments for transcoding.
  409. /// </summary>
  410. /// <param name="state">The <see cref="StreamState"/>.</param>
  411. /// <returns>The command line arguments for video transcoding.</returns>
  412. private string GetVideoArguments(StreamState state)
  413. {
  414. if (!state.IsOutputVideo)
  415. {
  416. return string.Empty;
  417. }
  418. var codec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
  419. var args = "-codec:v:0 " + codec;
  420. // if (state.EnableMpegtsM2TsMode)
  421. // {
  422. // args += " -mpegts_m2ts_mode 1";
  423. // }
  424. // See if we can save come cpu cycles by avoiding encoding
  425. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  426. {
  427. // if h264_mp4toannexb is ever added, do not use it for live tv
  428. if (state.VideoStream != null &&
  429. !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
  430. {
  431. string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.VideoStream);
  432. if (!string.IsNullOrEmpty(bitStreamArgs))
  433. {
  434. args += " " + bitStreamArgs;
  435. }
  436. }
  437. }
  438. else
  439. {
  440. var keyFrameArg = string.Format(
  441. CultureInfo.InvariantCulture,
  442. " -force_key_frames \"expr:gte(t,n_forced*{0})\"",
  443. state.SegmentLength.ToString(CultureInfo.InvariantCulture));
  444. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  445. args += " " + _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset) + keyFrameArg;
  446. // Add resolution params, if specified
  447. if (!hasGraphicalSubs)
  448. {
  449. args += _encodingHelper.GetOutputSizeParam(state, _encodingOptions, codec);
  450. }
  451. // This is for internal graphical subs
  452. if (hasGraphicalSubs)
  453. {
  454. args += _encodingHelper.GetGraphicalSubtitleParam(state, _encodingOptions, codec);
  455. }
  456. }
  457. args += " -flags -global_header";
  458. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  459. {
  460. args += " -vsync " + state.OutputVideoSync;
  461. }
  462. args += _encodingHelper.GetOutputFFlags(state);
  463. return args;
  464. }
  465. }
  466. }