VideoHlsController.cs 29 KB

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