DynamicHlsController.cs 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Jellyfin.Api.Attributes;
  12. using Jellyfin.Api.Extensions;
  13. using Jellyfin.Api.Helpers;
  14. using Jellyfin.Api.Models.StreamingDtos;
  15. using Jellyfin.Data.Enums;
  16. using Jellyfin.Extensions;
  17. using Jellyfin.MediaEncoding.Hls.Playlist;
  18. using MediaBrowser.Common.Configuration;
  19. using MediaBrowser.Controller.Configuration;
  20. using MediaBrowser.Controller.Library;
  21. using MediaBrowser.Controller.MediaEncoding;
  22. using MediaBrowser.Controller.Streaming;
  23. using MediaBrowser.MediaEncoding.Encoder;
  24. using MediaBrowser.Model.Configuration;
  25. using MediaBrowser.Model.Dlna;
  26. using MediaBrowser.Model.Entities;
  27. using MediaBrowser.Model.IO;
  28. using MediaBrowser.Model.Net;
  29. using Microsoft.AspNetCore.Authorization;
  30. using Microsoft.AspNetCore.Http;
  31. using Microsoft.AspNetCore.Mvc;
  32. using Microsoft.Extensions.Logging;
  33. namespace Jellyfin.Api.Controllers;
  34. /// <summary>
  35. /// Dynamic hls controller.
  36. /// </summary>
  37. [Route("")]
  38. [Authorize]
  39. public class DynamicHlsController : BaseJellyfinApiController
  40. {
  41. private const EncoderPreset DefaultVodEncoderPreset = EncoderPreset.veryfast;
  42. private const EncoderPreset DefaultEventEncoderPreset = EncoderPreset.superfast;
  43. private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls;
  44. private readonly Version _minFFmpegFlacInMp4 = new Version(6, 0);
  45. private readonly Version _minFFmpegX265BframeInFmp4 = new Version(7, 0, 1);
  46. private readonly ILibraryManager _libraryManager;
  47. private readonly IUserManager _userManager;
  48. private readonly IMediaSourceManager _mediaSourceManager;
  49. private readonly IServerConfigurationManager _serverConfigurationManager;
  50. private readonly IMediaEncoder _mediaEncoder;
  51. private readonly IFileSystem _fileSystem;
  52. private readonly ITranscodeManager _transcodeManager;
  53. private readonly ILogger<DynamicHlsController> _logger;
  54. private readonly EncodingHelper _encodingHelper;
  55. private readonly IDynamicHlsPlaylistGenerator _dynamicHlsPlaylistGenerator;
  56. private readonly DynamicHlsHelper _dynamicHlsHelper;
  57. private readonly EncodingOptions _encodingOptions;
  58. /// <summary>
  59. /// Initializes a new instance of the <see cref="DynamicHlsController"/> class.
  60. /// </summary>
  61. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  62. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  63. /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
  64. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  65. /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
  66. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  67. /// <param name="transcodeManager">Instance of the <see cref="ITranscodeManager"/> interface.</param>
  68. /// <param name="logger">Instance of the <see cref="ILogger{DynamicHlsController}"/> interface.</param>
  69. /// <param name="dynamicHlsHelper">Instance of <see cref="DynamicHlsHelper"/>.</param>
  70. /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
  71. /// <param name="dynamicHlsPlaylistGenerator">Instance of <see cref="IDynamicHlsPlaylistGenerator"/>.</param>
  72. public DynamicHlsController(
  73. ILibraryManager libraryManager,
  74. IUserManager userManager,
  75. IMediaSourceManager mediaSourceManager,
  76. IServerConfigurationManager serverConfigurationManager,
  77. IMediaEncoder mediaEncoder,
  78. IFileSystem fileSystem,
  79. ITranscodeManager transcodeManager,
  80. ILogger<DynamicHlsController> logger,
  81. DynamicHlsHelper dynamicHlsHelper,
  82. EncodingHelper encodingHelper,
  83. IDynamicHlsPlaylistGenerator dynamicHlsPlaylistGenerator)
  84. {
  85. _libraryManager = libraryManager;
  86. _userManager = userManager;
  87. _mediaSourceManager = mediaSourceManager;
  88. _serverConfigurationManager = serverConfigurationManager;
  89. _mediaEncoder = mediaEncoder;
  90. _fileSystem = fileSystem;
  91. _transcodeManager = transcodeManager;
  92. _logger = logger;
  93. _dynamicHlsHelper = dynamicHlsHelper;
  94. _encodingHelper = encodingHelper;
  95. _dynamicHlsPlaylistGenerator = dynamicHlsPlaylistGenerator;
  96. _encodingOptions = serverConfigurationManager.GetEncodingOptions();
  97. }
  98. /// <summary>
  99. /// Gets a hls live stream.
  100. /// </summary>
  101. /// <param name="itemId">The item id.</param>
  102. /// <param name="container">The audio container.</param>
  103. /// <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>
  104. /// <param name="params">The streaming parameters.</param>
  105. /// <param name="tag">The tag.</param>
  106. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  107. /// <param name="playSessionId">The play session id.</param>
  108. /// <param name="segmentContainer">The segment container.</param>
  109. /// <param name="segmentLength">The segment length.</param>
  110. /// <param name="minSegments">The minimum number of segments.</param>
  111. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  112. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  113. /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
  114. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  115. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  116. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  117. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  118. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  119. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  120. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  121. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  122. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  123. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  124. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  125. /// <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>
  126. /// <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>
  127. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  128. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  129. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  130. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  131. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  132. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  133. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  134. /// <param name="maxRefFrames">Optional.</param>
  135. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  136. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  137. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  138. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
  139. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  140. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  141. /// <param name="liveStreamId">The live stream id.</param>
  142. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  143. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
  144. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  145. /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
  146. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  147. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  148. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  149. /// <param name="streamOptions">Optional. The streaming options.</param>
  150. /// <param name="maxWidth">Optional. The max width.</param>
  151. /// <param name="maxHeight">Optional. The max height.</param>
  152. /// <param name="enableSubtitlesInManifest">Optional. Whether to enable subtitles in the manifest.</param>
  153. /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
  154. /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
  155. /// <response code="200">Hls live stream retrieved.</response>
  156. /// <returns>A <see cref="FileResult"/> containing the hls file.</returns>
  157. [HttpGet("Videos/{itemId}/live.m3u8")]
  158. [ProducesResponseType(StatusCodes.Status200OK)]
  159. [ProducesPlaylistFile]
  160. public async Task<ActionResult> GetLiveHlsStream(
  161. [FromRoute, Required] Guid itemId,
  162. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? container,
  163. [FromQuery] bool? @static,
  164. [FromQuery] string? @params,
  165. [FromQuery] string? tag,
  166. [FromQuery, ParameterObsolete] string? deviceProfileId,
  167. [FromQuery] string? playSessionId,
  168. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
  169. [FromQuery] int? segmentLength,
  170. [FromQuery] int? minSegments,
  171. [FromQuery] string? mediaSourceId,
  172. [FromQuery] string? deviceId,
  173. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
  174. [FromQuery] bool? enableAutoStreamCopy,
  175. [FromQuery] bool? allowVideoStreamCopy,
  176. [FromQuery] bool? allowAudioStreamCopy,
  177. [FromQuery] bool? breakOnNonKeyFrames,
  178. [FromQuery] int? audioSampleRate,
  179. [FromQuery] int? maxAudioBitDepth,
  180. [FromQuery] int? audioBitRate,
  181. [FromQuery] int? audioChannels,
  182. [FromQuery] int? maxAudioChannels,
  183. [FromQuery] string? profile,
  184. [FromQuery] string? level,
  185. [FromQuery] float? framerate,
  186. [FromQuery] float? maxFramerate,
  187. [FromQuery] bool? copyTimestamps,
  188. [FromQuery] long? startTimeTicks,
  189. [FromQuery] int? width,
  190. [FromQuery] int? height,
  191. [FromQuery] int? videoBitRate,
  192. [FromQuery] int? subtitleStreamIndex,
  193. [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
  194. [FromQuery] int? maxRefFrames,
  195. [FromQuery] int? maxVideoBitDepth,
  196. [FromQuery] bool? requireAvc,
  197. [FromQuery] bool? deInterlace,
  198. [FromQuery] bool? requireNonAnamorphic,
  199. [FromQuery] int? transcodingMaxAudioChannels,
  200. [FromQuery] int? cpuCoreLimit,
  201. [FromQuery] string? liveStreamId,
  202. [FromQuery] bool? enableMpegtsM2TsMode,
  203. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
  204. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
  205. [FromQuery] string? transcodeReasons,
  206. [FromQuery] int? audioStreamIndex,
  207. [FromQuery] int? videoStreamIndex,
  208. [FromQuery] EncodingContext? context,
  209. [FromQuery] Dictionary<string, string> streamOptions,
  210. [FromQuery] int? maxWidth,
  211. [FromQuery] int? maxHeight,
  212. [FromQuery] bool? enableSubtitlesInManifest,
  213. [FromQuery] bool enableAudioVbrEncoding = true,
  214. [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
  215. {
  216. VideoRequestDto streamingRequest = new VideoRequestDto
  217. {
  218. Id = itemId,
  219. Container = container,
  220. Static = @static ?? false,
  221. Params = @params,
  222. Tag = tag,
  223. PlaySessionId = playSessionId,
  224. SegmentContainer = segmentContainer,
  225. SegmentLength = segmentLength,
  226. MinSegments = minSegments,
  227. MediaSourceId = mediaSourceId,
  228. DeviceId = deviceId,
  229. AudioCodec = audioCodec,
  230. EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
  231. AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
  232. AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
  233. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  234. AudioSampleRate = audioSampleRate,
  235. MaxAudioChannels = maxAudioChannels,
  236. AudioBitRate = audioBitRate,
  237. MaxAudioBitDepth = maxAudioBitDepth,
  238. AudioChannels = audioChannels,
  239. Profile = profile,
  240. Level = level,
  241. Framerate = framerate,
  242. MaxFramerate = maxFramerate,
  243. CopyTimestamps = copyTimestamps ?? false,
  244. StartTimeTicks = startTimeTicks,
  245. Width = width,
  246. Height = height,
  247. VideoBitRate = videoBitRate,
  248. SubtitleStreamIndex = subtitleStreamIndex,
  249. SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
  250. MaxRefFrames = maxRefFrames,
  251. MaxVideoBitDepth = maxVideoBitDepth,
  252. RequireAvc = requireAvc ?? false,
  253. DeInterlace = deInterlace ?? false,
  254. RequireNonAnamorphic = requireNonAnamorphic ?? false,
  255. TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
  256. CpuCoreLimit = cpuCoreLimit,
  257. LiveStreamId = liveStreamId,
  258. EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
  259. VideoCodec = videoCodec,
  260. SubtitleCodec = subtitleCodec,
  261. TranscodeReasons = transcodeReasons,
  262. AudioStreamIndex = audioStreamIndex,
  263. VideoStreamIndex = videoStreamIndex,
  264. Context = context ?? EncodingContext.Streaming,
  265. StreamOptions = streamOptions,
  266. MaxHeight = maxHeight,
  267. MaxWidth = maxWidth,
  268. EnableSubtitlesInManifest = enableSubtitlesInManifest ?? true,
  269. EnableAudioVbrEncoding = enableAudioVbrEncoding,
  270. AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
  271. };
  272. // CTS lifecycle is managed internally.
  273. var cancellationTokenSource = new CancellationTokenSource();
  274. // Due to CTS.Token calling ThrowIfDisposed (https://github.com/dotnet/runtime/issues/29970) we have to "cache" the token
  275. // since it gets disposed when ffmpeg exits
  276. var cancellationToken = cancellationTokenSource.Token;
  277. var state = await StreamingHelpers.GetStreamingState(
  278. streamingRequest,
  279. HttpContext,
  280. _mediaSourceManager,
  281. _userManager,
  282. _libraryManager,
  283. _serverConfigurationManager,
  284. _mediaEncoder,
  285. _encodingHelper,
  286. _transcodeManager,
  287. TranscodingJobType,
  288. cancellationToken)
  289. .ConfigureAwait(false);
  290. TranscodingJob? job = null;
  291. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
  292. if (!System.IO.File.Exists(playlistPath))
  293. {
  294. using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
  295. {
  296. if (!System.IO.File.Exists(playlistPath))
  297. {
  298. // If the playlist doesn't already exist, startup ffmpeg
  299. try
  300. {
  301. job = await _transcodeManager.StartFfMpeg(
  302. state,
  303. playlistPath,
  304. GetCommandLineArguments(playlistPath, state, true, 0),
  305. Request.HttpContext.User.GetUserId(),
  306. TranscodingJobType,
  307. cancellationTokenSource)
  308. .ConfigureAwait(false);
  309. job.IsLiveOutput = true;
  310. }
  311. catch
  312. {
  313. state.Dispose();
  314. throw;
  315. }
  316. minSegments = state.MinSegments;
  317. if (minSegments > 0)
  318. {
  319. await HlsHelpers.WaitForMinimumSegmentCount(playlistPath, minSegments, _logger, cancellationToken).ConfigureAwait(false);
  320. }
  321. }
  322. }
  323. }
  324. job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  325. if (job is not null)
  326. {
  327. _transcodeManager.OnTranscodeEndRequest(job);
  328. }
  329. var playlistText = HlsHelpers.GetLivePlaylistText(playlistPath, state);
  330. return Content(playlistText, MimeTypes.GetMimeType("playlist.m3u8"));
  331. }
  332. /// <summary>
  333. /// Gets a video hls playlist stream.
  334. /// </summary>
  335. /// <param name="itemId">The item id.</param>
  336. /// <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>
  337. /// <param name="params">The streaming parameters.</param>
  338. /// <param name="tag">The tag.</param>
  339. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  340. /// <param name="playSessionId">The play session id.</param>
  341. /// <param name="segmentContainer">The segment container.</param>
  342. /// <param name="segmentLength">The segment length.</param>
  343. /// <param name="minSegments">The minimum number of segments.</param>
  344. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  345. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  346. /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
  347. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  348. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  349. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  350. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  351. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  352. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  353. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  354. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  355. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  356. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  357. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  358. /// <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>
  359. /// <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>
  360. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  361. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  362. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  363. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  364. /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
  365. /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
  366. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  367. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  368. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  369. /// <param name="maxRefFrames">Optional.</param>
  370. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  371. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  372. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  373. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
  374. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  375. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  376. /// <param name="liveStreamId">The live stream id.</param>
  377. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  378. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
  379. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  380. /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
  381. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  382. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  383. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  384. /// <param name="streamOptions">Optional. The streaming options.</param>
  385. /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
  386. /// <param name="enableTrickplay">Enable trickplay image playlists being added to master playlist.</param>
  387. /// <param name="enableAudioVbrEncoding">Whether to enable Audio Encoding.</param>
  388. /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
  389. /// <response code="200">Video stream returned.</response>
  390. /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
  391. [HttpGet("Videos/{itemId}/master.m3u8")]
  392. [HttpHead("Videos/{itemId}/master.m3u8", Name = "HeadMasterHlsVideoPlaylist")]
  393. [ProducesResponseType(StatusCodes.Status200OK)]
  394. [ProducesPlaylistFile]
  395. public async Task<ActionResult> GetMasterHlsVideoPlaylist(
  396. [FromRoute, Required] Guid itemId,
  397. [FromQuery] bool? @static,
  398. [FromQuery] string? @params,
  399. [FromQuery] string? tag,
  400. [FromQuery, ParameterObsolete] string? deviceProfileId,
  401. [FromQuery] string? playSessionId,
  402. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
  403. [FromQuery] int? segmentLength,
  404. [FromQuery] int? minSegments,
  405. [FromQuery, Required] string mediaSourceId,
  406. [FromQuery] string? deviceId,
  407. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
  408. [FromQuery] bool? enableAutoStreamCopy,
  409. [FromQuery] bool? allowVideoStreamCopy,
  410. [FromQuery] bool? allowAudioStreamCopy,
  411. [FromQuery] bool? breakOnNonKeyFrames,
  412. [FromQuery] int? audioSampleRate,
  413. [FromQuery] int? maxAudioBitDepth,
  414. [FromQuery] int? audioBitRate,
  415. [FromQuery] int? audioChannels,
  416. [FromQuery] int? maxAudioChannels,
  417. [FromQuery] string? profile,
  418. [FromQuery] string? level,
  419. [FromQuery] float? framerate,
  420. [FromQuery] float? maxFramerate,
  421. [FromQuery] bool? copyTimestamps,
  422. [FromQuery] long? startTimeTicks,
  423. [FromQuery] int? width,
  424. [FromQuery] int? height,
  425. [FromQuery] int? maxWidth,
  426. [FromQuery] int? maxHeight,
  427. [FromQuery] int? videoBitRate,
  428. [FromQuery] int? subtitleStreamIndex,
  429. [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
  430. [FromQuery] int? maxRefFrames,
  431. [FromQuery] int? maxVideoBitDepth,
  432. [FromQuery] bool? requireAvc,
  433. [FromQuery] bool? deInterlace,
  434. [FromQuery] bool? requireNonAnamorphic,
  435. [FromQuery] int? transcodingMaxAudioChannels,
  436. [FromQuery] int? cpuCoreLimit,
  437. [FromQuery] string? liveStreamId,
  438. [FromQuery] bool? enableMpegtsM2TsMode,
  439. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
  440. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
  441. [FromQuery] string? transcodeReasons,
  442. [FromQuery] int? audioStreamIndex,
  443. [FromQuery] int? videoStreamIndex,
  444. [FromQuery] EncodingContext? context,
  445. [FromQuery] Dictionary<string, string> streamOptions,
  446. [FromQuery] bool enableAdaptiveBitrateStreaming = false,
  447. [FromQuery] bool enableTrickplay = true,
  448. [FromQuery] bool enableAudioVbrEncoding = true,
  449. [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
  450. {
  451. var streamingRequest = new HlsVideoRequestDto
  452. {
  453. Id = itemId,
  454. Static = @static ?? false,
  455. Params = @params,
  456. Tag = tag,
  457. PlaySessionId = playSessionId,
  458. SegmentContainer = segmentContainer,
  459. SegmentLength = segmentLength,
  460. MinSegments = minSegments,
  461. MediaSourceId = mediaSourceId,
  462. DeviceId = deviceId,
  463. AudioCodec = audioCodec,
  464. EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
  465. AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
  466. AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
  467. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  468. AudioSampleRate = audioSampleRate,
  469. MaxAudioChannels = maxAudioChannels,
  470. AudioBitRate = audioBitRate,
  471. MaxAudioBitDepth = maxAudioBitDepth,
  472. AudioChannels = audioChannels,
  473. Profile = profile,
  474. Level = level,
  475. Framerate = framerate,
  476. MaxFramerate = maxFramerate,
  477. CopyTimestamps = copyTimestamps ?? false,
  478. StartTimeTicks = startTimeTicks,
  479. Width = width,
  480. Height = height,
  481. MaxWidth = maxWidth,
  482. MaxHeight = maxHeight,
  483. VideoBitRate = videoBitRate,
  484. SubtitleStreamIndex = subtitleStreamIndex,
  485. SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
  486. MaxRefFrames = maxRefFrames,
  487. MaxVideoBitDepth = maxVideoBitDepth,
  488. RequireAvc = requireAvc ?? false,
  489. DeInterlace = deInterlace ?? false,
  490. RequireNonAnamorphic = requireNonAnamorphic ?? false,
  491. TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
  492. CpuCoreLimit = cpuCoreLimit,
  493. LiveStreamId = liveStreamId,
  494. EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
  495. VideoCodec = videoCodec,
  496. SubtitleCodec = subtitleCodec,
  497. TranscodeReasons = transcodeReasons,
  498. AudioStreamIndex = audioStreamIndex,
  499. VideoStreamIndex = videoStreamIndex,
  500. Context = context ?? EncodingContext.Streaming,
  501. StreamOptions = streamOptions,
  502. EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
  503. EnableTrickplay = enableTrickplay,
  504. EnableAudioVbrEncoding = enableAudioVbrEncoding,
  505. AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
  506. };
  507. return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateStreaming).ConfigureAwait(false);
  508. }
  509. /// <summary>
  510. /// Gets an audio hls playlist stream.
  511. /// </summary>
  512. /// <param name="itemId">The item id.</param>
  513. /// <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>
  514. /// <param name="params">The streaming parameters.</param>
  515. /// <param name="tag">The tag.</param>
  516. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  517. /// <param name="playSessionId">The play session id.</param>
  518. /// <param name="segmentContainer">The segment container.</param>
  519. /// <param name="segmentLength">The segment length.</param>
  520. /// <param name="minSegments">The minimum number of segments.</param>
  521. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  522. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  523. /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
  524. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  525. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  526. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  527. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  528. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  529. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  530. /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
  531. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  532. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  533. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  534. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  535. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  536. /// <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>
  537. /// <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>
  538. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  539. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  540. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  541. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  542. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  543. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  544. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  545. /// <param name="maxRefFrames">Optional.</param>
  546. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  547. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  548. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  549. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
  550. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  551. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  552. /// <param name="liveStreamId">The live stream id.</param>
  553. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  554. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
  555. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  556. /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
  557. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  558. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  559. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  560. /// <param name="streamOptions">Optional. The streaming options.</param>
  561. /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
  562. /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
  563. /// <response code="200">Audio stream returned.</response>
  564. /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
  565. [HttpGet("Audio/{itemId}/master.m3u8")]
  566. [HttpHead("Audio/{itemId}/master.m3u8", Name = "HeadMasterHlsAudioPlaylist")]
  567. [ProducesResponseType(StatusCodes.Status200OK)]
  568. [ProducesPlaylistFile]
  569. public async Task<ActionResult> GetMasterHlsAudioPlaylist(
  570. [FromRoute, Required] Guid itemId,
  571. [FromQuery] bool? @static,
  572. [FromQuery] string? @params,
  573. [FromQuery] string? tag,
  574. [FromQuery, ParameterObsolete] string? deviceProfileId,
  575. [FromQuery] string? playSessionId,
  576. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
  577. [FromQuery] int? segmentLength,
  578. [FromQuery] int? minSegments,
  579. [FromQuery, Required] string mediaSourceId,
  580. [FromQuery] string? deviceId,
  581. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
  582. [FromQuery] bool? enableAutoStreamCopy,
  583. [FromQuery] bool? allowVideoStreamCopy,
  584. [FromQuery] bool? allowAudioStreamCopy,
  585. [FromQuery] bool? breakOnNonKeyFrames,
  586. [FromQuery] int? audioSampleRate,
  587. [FromQuery] int? maxAudioBitDepth,
  588. [FromQuery] int? maxStreamingBitrate,
  589. [FromQuery] int? audioBitRate,
  590. [FromQuery] int? audioChannels,
  591. [FromQuery] int? maxAudioChannels,
  592. [FromQuery] string? profile,
  593. [FromQuery] string? level,
  594. [FromQuery] float? framerate,
  595. [FromQuery] float? maxFramerate,
  596. [FromQuery] bool? copyTimestamps,
  597. [FromQuery] long? startTimeTicks,
  598. [FromQuery] int? width,
  599. [FromQuery] int? height,
  600. [FromQuery] int? videoBitRate,
  601. [FromQuery] int? subtitleStreamIndex,
  602. [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
  603. [FromQuery] int? maxRefFrames,
  604. [FromQuery] int? maxVideoBitDepth,
  605. [FromQuery] bool? requireAvc,
  606. [FromQuery] bool? deInterlace,
  607. [FromQuery] bool? requireNonAnamorphic,
  608. [FromQuery] int? transcodingMaxAudioChannels,
  609. [FromQuery] int? cpuCoreLimit,
  610. [FromQuery] string? liveStreamId,
  611. [FromQuery] bool? enableMpegtsM2TsMode,
  612. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
  613. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
  614. [FromQuery] string? transcodeReasons,
  615. [FromQuery] int? audioStreamIndex,
  616. [FromQuery] int? videoStreamIndex,
  617. [FromQuery] EncodingContext? context,
  618. [FromQuery] Dictionary<string, string> streamOptions,
  619. [FromQuery] bool enableAdaptiveBitrateStreaming = false,
  620. [FromQuery] bool enableAudioVbrEncoding = true)
  621. {
  622. var streamingRequest = new HlsAudioRequestDto
  623. {
  624. Id = itemId,
  625. Static = @static ?? false,
  626. Params = @params,
  627. Tag = tag,
  628. PlaySessionId = playSessionId,
  629. SegmentContainer = segmentContainer,
  630. SegmentLength = segmentLength,
  631. MinSegments = minSegments,
  632. MediaSourceId = mediaSourceId,
  633. DeviceId = deviceId,
  634. AudioCodec = audioCodec,
  635. EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
  636. AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
  637. AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
  638. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  639. AudioSampleRate = audioSampleRate,
  640. MaxAudioChannels = maxAudioChannels,
  641. AudioBitRate = audioBitRate ?? maxStreamingBitrate,
  642. MaxAudioBitDepth = maxAudioBitDepth,
  643. AudioChannels = audioChannels,
  644. Profile = profile,
  645. Level = level,
  646. Framerate = framerate,
  647. MaxFramerate = maxFramerate,
  648. CopyTimestamps = copyTimestamps ?? false,
  649. StartTimeTicks = startTimeTicks,
  650. Width = width,
  651. Height = height,
  652. VideoBitRate = videoBitRate,
  653. SubtitleStreamIndex = subtitleStreamIndex,
  654. SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
  655. MaxRefFrames = maxRefFrames,
  656. MaxVideoBitDepth = maxVideoBitDepth,
  657. RequireAvc = requireAvc ?? false,
  658. DeInterlace = deInterlace ?? false,
  659. RequireNonAnamorphic = requireNonAnamorphic ?? false,
  660. TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
  661. CpuCoreLimit = cpuCoreLimit,
  662. LiveStreamId = liveStreamId,
  663. EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
  664. VideoCodec = videoCodec,
  665. SubtitleCodec = subtitleCodec,
  666. TranscodeReasons = transcodeReasons,
  667. AudioStreamIndex = audioStreamIndex,
  668. VideoStreamIndex = videoStreamIndex,
  669. Context = context ?? EncodingContext.Streaming,
  670. StreamOptions = streamOptions,
  671. EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
  672. EnableAudioVbrEncoding = enableAudioVbrEncoding,
  673. AlwaysBurnInSubtitleWhenTranscoding = false
  674. };
  675. return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateStreaming).ConfigureAwait(false);
  676. }
  677. /// <summary>
  678. /// Gets a video stream using HTTP live streaming.
  679. /// </summary>
  680. /// <param name="itemId">The item id.</param>
  681. /// <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>
  682. /// <param name="params">The streaming parameters.</param>
  683. /// <param name="tag">The tag.</param>
  684. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  685. /// <param name="playSessionId">The play session id.</param>
  686. /// <param name="segmentContainer">The segment container.</param>
  687. /// <param name="segmentLength">The segment length.</param>
  688. /// <param name="minSegments">The minimum number of segments.</param>
  689. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  690. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  691. /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
  692. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  693. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  694. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  695. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  696. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  697. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  698. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  699. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  700. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  701. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  702. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  703. /// <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>
  704. /// <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>
  705. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  706. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  707. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  708. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  709. /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
  710. /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
  711. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  712. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  713. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  714. /// <param name="maxRefFrames">Optional.</param>
  715. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  716. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  717. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  718. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
  719. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  720. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  721. /// <param name="liveStreamId">The live stream id.</param>
  722. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  723. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
  724. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  725. /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
  726. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  727. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  728. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  729. /// <param name="streamOptions">Optional. The streaming options.</param>
  730. /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
  731. /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
  732. /// <response code="200">Video stream returned.</response>
  733. /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
  734. [HttpGet("Videos/{itemId}/main.m3u8")]
  735. [ProducesResponseType(StatusCodes.Status200OK)]
  736. [ProducesPlaylistFile]
  737. public async Task<ActionResult> GetVariantHlsVideoPlaylist(
  738. [FromRoute, Required] Guid itemId,
  739. [FromQuery] bool? @static,
  740. [FromQuery] string? @params,
  741. [FromQuery] string? tag,
  742. [FromQuery, ParameterObsolete] string? deviceProfileId,
  743. [FromQuery] string? playSessionId,
  744. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
  745. [FromQuery] int? segmentLength,
  746. [FromQuery] int? minSegments,
  747. [FromQuery] string? mediaSourceId,
  748. [FromQuery] string? deviceId,
  749. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
  750. [FromQuery] bool? enableAutoStreamCopy,
  751. [FromQuery] bool? allowVideoStreamCopy,
  752. [FromQuery] bool? allowAudioStreamCopy,
  753. [FromQuery] bool? breakOnNonKeyFrames,
  754. [FromQuery] int? audioSampleRate,
  755. [FromQuery] int? maxAudioBitDepth,
  756. [FromQuery] int? audioBitRate,
  757. [FromQuery] int? audioChannels,
  758. [FromQuery] int? maxAudioChannels,
  759. [FromQuery] string? profile,
  760. [FromQuery] string? level,
  761. [FromQuery] float? framerate,
  762. [FromQuery] float? maxFramerate,
  763. [FromQuery] bool? copyTimestamps,
  764. [FromQuery] long? startTimeTicks,
  765. [FromQuery] int? width,
  766. [FromQuery] int? height,
  767. [FromQuery] int? maxWidth,
  768. [FromQuery] int? maxHeight,
  769. [FromQuery] int? videoBitRate,
  770. [FromQuery] int? subtitleStreamIndex,
  771. [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
  772. [FromQuery] int? maxRefFrames,
  773. [FromQuery] int? maxVideoBitDepth,
  774. [FromQuery] bool? requireAvc,
  775. [FromQuery] bool? deInterlace,
  776. [FromQuery] bool? requireNonAnamorphic,
  777. [FromQuery] int? transcodingMaxAudioChannels,
  778. [FromQuery] int? cpuCoreLimit,
  779. [FromQuery] string? liveStreamId,
  780. [FromQuery] bool? enableMpegtsM2TsMode,
  781. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
  782. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
  783. [FromQuery] string? transcodeReasons,
  784. [FromQuery] int? audioStreamIndex,
  785. [FromQuery] int? videoStreamIndex,
  786. [FromQuery] EncodingContext? context,
  787. [FromQuery] Dictionary<string, string> streamOptions,
  788. [FromQuery] bool enableAudioVbrEncoding = true,
  789. [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
  790. {
  791. using var cancellationTokenSource = new CancellationTokenSource();
  792. var streamingRequest = new VideoRequestDto
  793. {
  794. Id = itemId,
  795. Static = @static ?? false,
  796. Params = @params,
  797. Tag = tag,
  798. PlaySessionId = playSessionId,
  799. SegmentContainer = segmentContainer,
  800. SegmentLength = segmentLength,
  801. MinSegments = minSegments,
  802. MediaSourceId = mediaSourceId,
  803. DeviceId = deviceId,
  804. AudioCodec = audioCodec,
  805. EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
  806. AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
  807. AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
  808. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  809. AudioSampleRate = audioSampleRate,
  810. MaxAudioChannels = maxAudioChannels,
  811. AudioBitRate = audioBitRate,
  812. MaxAudioBitDepth = maxAudioBitDepth,
  813. AudioChannels = audioChannels,
  814. Profile = profile,
  815. Level = level,
  816. Framerate = framerate,
  817. MaxFramerate = maxFramerate,
  818. CopyTimestamps = copyTimestamps ?? false,
  819. StartTimeTicks = startTimeTicks,
  820. Width = width,
  821. Height = height,
  822. MaxWidth = maxWidth,
  823. MaxHeight = maxHeight,
  824. VideoBitRate = videoBitRate,
  825. SubtitleStreamIndex = subtitleStreamIndex,
  826. SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
  827. MaxRefFrames = maxRefFrames,
  828. MaxVideoBitDepth = maxVideoBitDepth,
  829. RequireAvc = requireAvc ?? false,
  830. DeInterlace = deInterlace ?? false,
  831. RequireNonAnamorphic = requireNonAnamorphic ?? false,
  832. TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
  833. CpuCoreLimit = cpuCoreLimit,
  834. LiveStreamId = liveStreamId,
  835. EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
  836. VideoCodec = videoCodec,
  837. SubtitleCodec = subtitleCodec,
  838. TranscodeReasons = transcodeReasons,
  839. AudioStreamIndex = audioStreamIndex,
  840. VideoStreamIndex = videoStreamIndex,
  841. Context = context ?? EncodingContext.Streaming,
  842. StreamOptions = streamOptions,
  843. EnableAudioVbrEncoding = enableAudioVbrEncoding,
  844. AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
  845. };
  846. return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
  847. .ConfigureAwait(false);
  848. }
  849. /// <summary>
  850. /// Gets an audio stream using HTTP live streaming.
  851. /// </summary>
  852. /// <param name="itemId">The item id.</param>
  853. /// <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>
  854. /// <param name="params">The streaming parameters.</param>
  855. /// <param name="tag">The tag.</param>
  856. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  857. /// <param name="playSessionId">The play session id.</param>
  858. /// <param name="segmentContainer">The segment container.</param>
  859. /// <param name="segmentLength">The segment length.</param>
  860. /// <param name="minSegments">The minimum number of segments.</param>
  861. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  862. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  863. /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
  864. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  865. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  866. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  867. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  868. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  869. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  870. /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
  871. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  872. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  873. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  874. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  875. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  876. /// <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>
  877. /// <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>
  878. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  879. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  880. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  881. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  882. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  883. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  884. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  885. /// <param name="maxRefFrames">Optional.</param>
  886. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  887. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  888. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  889. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
  890. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  891. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  892. /// <param name="liveStreamId">The live stream id.</param>
  893. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  894. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
  895. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  896. /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
  897. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  898. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  899. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  900. /// <param name="streamOptions">Optional. The streaming options.</param>
  901. /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
  902. /// <response code="200">Audio stream returned.</response>
  903. /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
  904. [HttpGet("Audio/{itemId}/main.m3u8")]
  905. [ProducesResponseType(StatusCodes.Status200OK)]
  906. [ProducesPlaylistFile]
  907. public async Task<ActionResult> GetVariantHlsAudioPlaylist(
  908. [FromRoute, Required] Guid itemId,
  909. [FromQuery] bool? @static,
  910. [FromQuery] string? @params,
  911. [FromQuery] string? tag,
  912. [FromQuery, ParameterObsolete] string? deviceProfileId,
  913. [FromQuery] string? playSessionId,
  914. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
  915. [FromQuery] int? segmentLength,
  916. [FromQuery] int? minSegments,
  917. [FromQuery] string? mediaSourceId,
  918. [FromQuery] string? deviceId,
  919. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
  920. [FromQuery] bool? enableAutoStreamCopy,
  921. [FromQuery] bool? allowVideoStreamCopy,
  922. [FromQuery] bool? allowAudioStreamCopy,
  923. [FromQuery] bool? breakOnNonKeyFrames,
  924. [FromQuery] int? audioSampleRate,
  925. [FromQuery] int? maxAudioBitDepth,
  926. [FromQuery] int? maxStreamingBitrate,
  927. [FromQuery] int? audioBitRate,
  928. [FromQuery] int? audioChannels,
  929. [FromQuery] int? maxAudioChannels,
  930. [FromQuery] string? profile,
  931. [FromQuery] string? level,
  932. [FromQuery] float? framerate,
  933. [FromQuery] float? maxFramerate,
  934. [FromQuery] bool? copyTimestamps,
  935. [FromQuery] long? startTimeTicks,
  936. [FromQuery] int? width,
  937. [FromQuery] int? height,
  938. [FromQuery] int? videoBitRate,
  939. [FromQuery] int? subtitleStreamIndex,
  940. [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
  941. [FromQuery] int? maxRefFrames,
  942. [FromQuery] int? maxVideoBitDepth,
  943. [FromQuery] bool? requireAvc,
  944. [FromQuery] bool? deInterlace,
  945. [FromQuery] bool? requireNonAnamorphic,
  946. [FromQuery] int? transcodingMaxAudioChannels,
  947. [FromQuery] int? cpuCoreLimit,
  948. [FromQuery] string? liveStreamId,
  949. [FromQuery] bool? enableMpegtsM2TsMode,
  950. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
  951. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
  952. [FromQuery] string? transcodeReasons,
  953. [FromQuery] int? audioStreamIndex,
  954. [FromQuery] int? videoStreamIndex,
  955. [FromQuery] EncodingContext? context,
  956. [FromQuery] Dictionary<string, string> streamOptions,
  957. [FromQuery] bool enableAudioVbrEncoding = true)
  958. {
  959. using var cancellationTokenSource = new CancellationTokenSource();
  960. var streamingRequest = new StreamingRequestDto
  961. {
  962. Id = itemId,
  963. Static = @static ?? false,
  964. Params = @params,
  965. Tag = tag,
  966. PlaySessionId = playSessionId,
  967. SegmentContainer = segmentContainer,
  968. SegmentLength = segmentLength,
  969. MinSegments = minSegments,
  970. MediaSourceId = mediaSourceId,
  971. DeviceId = deviceId,
  972. AudioCodec = audioCodec,
  973. EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
  974. AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
  975. AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
  976. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  977. AudioSampleRate = audioSampleRate,
  978. MaxAudioChannels = maxAudioChannels,
  979. AudioBitRate = audioBitRate ?? maxStreamingBitrate,
  980. MaxAudioBitDepth = maxAudioBitDepth,
  981. AudioChannels = audioChannels,
  982. Profile = profile,
  983. Level = level,
  984. Framerate = framerate,
  985. MaxFramerate = maxFramerate,
  986. CopyTimestamps = copyTimestamps ?? false,
  987. StartTimeTicks = startTimeTicks,
  988. Width = width,
  989. Height = height,
  990. VideoBitRate = videoBitRate,
  991. SubtitleStreamIndex = subtitleStreamIndex,
  992. SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
  993. MaxRefFrames = maxRefFrames,
  994. MaxVideoBitDepth = maxVideoBitDepth,
  995. RequireAvc = requireAvc ?? false,
  996. DeInterlace = deInterlace ?? false,
  997. RequireNonAnamorphic = requireNonAnamorphic ?? false,
  998. TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
  999. CpuCoreLimit = cpuCoreLimit,
  1000. LiveStreamId = liveStreamId,
  1001. EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
  1002. VideoCodec = videoCodec,
  1003. SubtitleCodec = subtitleCodec,
  1004. TranscodeReasons = transcodeReasons,
  1005. AudioStreamIndex = audioStreamIndex,
  1006. VideoStreamIndex = videoStreamIndex,
  1007. Context = context ?? EncodingContext.Streaming,
  1008. StreamOptions = streamOptions,
  1009. EnableAudioVbrEncoding = enableAudioVbrEncoding,
  1010. AlwaysBurnInSubtitleWhenTranscoding = false
  1011. };
  1012. return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
  1013. .ConfigureAwait(false);
  1014. }
  1015. /// <summary>
  1016. /// Gets a video stream using HTTP live streaming.
  1017. /// </summary>
  1018. /// <param name="itemId">The item id.</param>
  1019. /// <param name="playlistId">The playlist id.</param>
  1020. /// <param name="segmentId">The segment id.</param>
  1021. /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, mpg, avi, 3gp, wmv, wtv, m2ts, mov, iso, flv. </param>
  1022. /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
  1023. /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
  1024. /// <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>
  1025. /// <param name="params">The streaming parameters.</param>
  1026. /// <param name="tag">The tag.</param>
  1027. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  1028. /// <param name="playSessionId">The play session id.</param>
  1029. /// <param name="segmentContainer">The segment container.</param>
  1030. /// <param name="segmentLength">The desired segment length.</param>
  1031. /// <param name="minSegments">The minimum number of segments.</param>
  1032. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  1033. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  1034. /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
  1035. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  1036. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  1037. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  1038. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  1039. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  1040. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  1041. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  1042. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  1043. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  1044. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  1045. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  1046. /// <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>
  1047. /// <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>
  1048. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  1049. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  1050. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  1051. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  1052. /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
  1053. /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
  1054. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  1055. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  1056. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  1057. /// <param name="maxRefFrames">Optional.</param>
  1058. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  1059. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  1060. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  1061. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
  1062. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  1063. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  1064. /// <param name="liveStreamId">The live stream id.</param>
  1065. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  1066. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
  1067. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  1068. /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
  1069. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  1070. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  1071. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  1072. /// <param name="streamOptions">Optional. The streaming options.</param>
  1073. /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
  1074. /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
  1075. /// <response code="200">Video stream returned.</response>
  1076. /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
  1077. [HttpGet("Videos/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
  1078. [ProducesResponseType(StatusCodes.Status200OK)]
  1079. [ProducesVideoFile]
  1080. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification = "Imported from ServiceStack")]
  1081. public async Task<ActionResult> GetHlsVideoSegment(
  1082. [FromRoute, Required] Guid itemId,
  1083. [FromRoute, Required] string playlistId,
  1084. [FromRoute, Required] int segmentId,
  1085. [FromRoute, Required] string container,
  1086. [FromQuery, Required] long runtimeTicks,
  1087. [FromQuery, Required] long actualSegmentLengthTicks,
  1088. [FromQuery] bool? @static,
  1089. [FromQuery] string? @params,
  1090. [FromQuery] string? tag,
  1091. [FromQuery, ParameterObsolete] string? deviceProfileId,
  1092. [FromQuery] string? playSessionId,
  1093. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
  1094. [FromQuery] int? segmentLength,
  1095. [FromQuery] int? minSegments,
  1096. [FromQuery] string? mediaSourceId,
  1097. [FromQuery] string? deviceId,
  1098. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
  1099. [FromQuery] bool? enableAutoStreamCopy,
  1100. [FromQuery] bool? allowVideoStreamCopy,
  1101. [FromQuery] bool? allowAudioStreamCopy,
  1102. [FromQuery] bool? breakOnNonKeyFrames,
  1103. [FromQuery] int? audioSampleRate,
  1104. [FromQuery] int? maxAudioBitDepth,
  1105. [FromQuery] int? audioBitRate,
  1106. [FromQuery] int? audioChannels,
  1107. [FromQuery] int? maxAudioChannels,
  1108. [FromQuery] string? profile,
  1109. [FromQuery] string? level,
  1110. [FromQuery] float? framerate,
  1111. [FromQuery] float? maxFramerate,
  1112. [FromQuery] bool? copyTimestamps,
  1113. [FromQuery] long? startTimeTicks,
  1114. [FromQuery] int? width,
  1115. [FromQuery] int? height,
  1116. [FromQuery] int? maxWidth,
  1117. [FromQuery] int? maxHeight,
  1118. [FromQuery] int? videoBitRate,
  1119. [FromQuery] int? subtitleStreamIndex,
  1120. [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
  1121. [FromQuery] int? maxRefFrames,
  1122. [FromQuery] int? maxVideoBitDepth,
  1123. [FromQuery] bool? requireAvc,
  1124. [FromQuery] bool? deInterlace,
  1125. [FromQuery] bool? requireNonAnamorphic,
  1126. [FromQuery] int? transcodingMaxAudioChannels,
  1127. [FromQuery] int? cpuCoreLimit,
  1128. [FromQuery] string? liveStreamId,
  1129. [FromQuery] bool? enableMpegtsM2TsMode,
  1130. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
  1131. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
  1132. [FromQuery] string? transcodeReasons,
  1133. [FromQuery] int? audioStreamIndex,
  1134. [FromQuery] int? videoStreamIndex,
  1135. [FromQuery] EncodingContext? context,
  1136. [FromQuery] Dictionary<string, string> streamOptions,
  1137. [FromQuery] bool enableAudioVbrEncoding = true,
  1138. [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
  1139. {
  1140. var streamingRequest = new VideoRequestDto
  1141. {
  1142. Id = itemId,
  1143. CurrentRuntimeTicks = runtimeTicks,
  1144. ActualSegmentLengthTicks = actualSegmentLengthTicks,
  1145. Container = container,
  1146. Static = @static ?? false,
  1147. Params = @params,
  1148. Tag = tag,
  1149. PlaySessionId = playSessionId,
  1150. SegmentContainer = segmentContainer,
  1151. SegmentLength = segmentLength,
  1152. MinSegments = minSegments,
  1153. MediaSourceId = mediaSourceId,
  1154. DeviceId = deviceId,
  1155. AudioCodec = audioCodec,
  1156. EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
  1157. AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
  1158. AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
  1159. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  1160. AudioSampleRate = audioSampleRate,
  1161. MaxAudioChannels = maxAudioChannels,
  1162. AudioBitRate = audioBitRate,
  1163. MaxAudioBitDepth = maxAudioBitDepth,
  1164. AudioChannels = audioChannels,
  1165. Profile = profile,
  1166. Level = level,
  1167. Framerate = framerate,
  1168. MaxFramerate = maxFramerate,
  1169. CopyTimestamps = copyTimestamps ?? false,
  1170. StartTimeTicks = startTimeTicks,
  1171. Width = width,
  1172. Height = height,
  1173. MaxWidth = maxWidth,
  1174. MaxHeight = maxHeight,
  1175. VideoBitRate = videoBitRate,
  1176. SubtitleStreamIndex = subtitleStreamIndex,
  1177. SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
  1178. MaxRefFrames = maxRefFrames,
  1179. MaxVideoBitDepth = maxVideoBitDepth,
  1180. RequireAvc = requireAvc ?? false,
  1181. DeInterlace = deInterlace ?? false,
  1182. RequireNonAnamorphic = requireNonAnamorphic ?? false,
  1183. TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
  1184. CpuCoreLimit = cpuCoreLimit,
  1185. LiveStreamId = liveStreamId,
  1186. EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
  1187. VideoCodec = videoCodec,
  1188. SubtitleCodec = subtitleCodec,
  1189. TranscodeReasons = transcodeReasons,
  1190. AudioStreamIndex = audioStreamIndex,
  1191. VideoStreamIndex = videoStreamIndex,
  1192. Context = context ?? EncodingContext.Streaming,
  1193. StreamOptions = streamOptions,
  1194. EnableAudioVbrEncoding = enableAudioVbrEncoding,
  1195. AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
  1196. };
  1197. return await GetDynamicSegment(streamingRequest, segmentId)
  1198. .ConfigureAwait(false);
  1199. }
  1200. /// <summary>
  1201. /// Gets a video stream using HTTP live streaming.
  1202. /// </summary>
  1203. /// <param name="itemId">The item id.</param>
  1204. /// <param name="playlistId">The playlist id.</param>
  1205. /// <param name="segmentId">The segment id.</param>
  1206. /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, mpg, avi, 3gp, wmv, wtv, m2ts, mov, iso, flv. </param>
  1207. /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
  1208. /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
  1209. /// <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>
  1210. /// <param name="params">The streaming parameters.</param>
  1211. /// <param name="tag">The tag.</param>
  1212. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  1213. /// <param name="playSessionId">The play session id.</param>
  1214. /// <param name="segmentContainer">The segment container.</param>
  1215. /// <param name="segmentLength">The segment length.</param>
  1216. /// <param name="minSegments">The minimum number of segments.</param>
  1217. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  1218. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  1219. /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
  1220. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  1221. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  1222. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  1223. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  1224. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  1225. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  1226. /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
  1227. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  1228. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  1229. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  1230. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  1231. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  1232. /// <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>
  1233. /// <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>
  1234. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  1235. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  1236. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  1237. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  1238. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  1239. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  1240. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  1241. /// <param name="maxRefFrames">Optional.</param>
  1242. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  1243. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  1244. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  1245. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
  1246. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  1247. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  1248. /// <param name="liveStreamId">The live stream id.</param>
  1249. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  1250. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
  1251. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  1252. /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
  1253. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  1254. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  1255. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  1256. /// <param name="streamOptions">Optional. The streaming options.</param>
  1257. /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
  1258. /// <response code="200">Video stream returned.</response>
  1259. /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
  1260. [HttpGet("Audio/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
  1261. [ProducesResponseType(StatusCodes.Status200OK)]
  1262. [ProducesAudioFile]
  1263. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification = "Imported from ServiceStack")]
  1264. public async Task<ActionResult> GetHlsAudioSegment(
  1265. [FromRoute, Required] Guid itemId,
  1266. [FromRoute, Required] string playlistId,
  1267. [FromRoute, Required] int segmentId,
  1268. [FromRoute, Required] string container,
  1269. [FromQuery, Required] long runtimeTicks,
  1270. [FromQuery, Required] long actualSegmentLengthTicks,
  1271. [FromQuery] bool? @static,
  1272. [FromQuery] string? @params,
  1273. [FromQuery] string? tag,
  1274. [FromQuery, ParameterObsolete] string? deviceProfileId,
  1275. [FromQuery] string? playSessionId,
  1276. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
  1277. [FromQuery] int? segmentLength,
  1278. [FromQuery] int? minSegments,
  1279. [FromQuery] string? mediaSourceId,
  1280. [FromQuery] string? deviceId,
  1281. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
  1282. [FromQuery] bool? enableAutoStreamCopy,
  1283. [FromQuery] bool? allowVideoStreamCopy,
  1284. [FromQuery] bool? allowAudioStreamCopy,
  1285. [FromQuery] bool? breakOnNonKeyFrames,
  1286. [FromQuery] int? audioSampleRate,
  1287. [FromQuery] int? maxAudioBitDepth,
  1288. [FromQuery] int? maxStreamingBitrate,
  1289. [FromQuery] int? audioBitRate,
  1290. [FromQuery] int? audioChannels,
  1291. [FromQuery] int? maxAudioChannels,
  1292. [FromQuery] string? profile,
  1293. [FromQuery] string? level,
  1294. [FromQuery] float? framerate,
  1295. [FromQuery] float? maxFramerate,
  1296. [FromQuery] bool? copyTimestamps,
  1297. [FromQuery] long? startTimeTicks,
  1298. [FromQuery] int? width,
  1299. [FromQuery] int? height,
  1300. [FromQuery] int? videoBitRate,
  1301. [FromQuery] int? subtitleStreamIndex,
  1302. [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
  1303. [FromQuery] int? maxRefFrames,
  1304. [FromQuery] int? maxVideoBitDepth,
  1305. [FromQuery] bool? requireAvc,
  1306. [FromQuery] bool? deInterlace,
  1307. [FromQuery] bool? requireNonAnamorphic,
  1308. [FromQuery] int? transcodingMaxAudioChannels,
  1309. [FromQuery] int? cpuCoreLimit,
  1310. [FromQuery] string? liveStreamId,
  1311. [FromQuery] bool? enableMpegtsM2TsMode,
  1312. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
  1313. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
  1314. [FromQuery] string? transcodeReasons,
  1315. [FromQuery] int? audioStreamIndex,
  1316. [FromQuery] int? videoStreamIndex,
  1317. [FromQuery] EncodingContext? context,
  1318. [FromQuery] Dictionary<string, string> streamOptions,
  1319. [FromQuery] bool enableAudioVbrEncoding = true)
  1320. {
  1321. var streamingRequest = new StreamingRequestDto
  1322. {
  1323. Id = itemId,
  1324. Container = container,
  1325. CurrentRuntimeTicks = runtimeTicks,
  1326. ActualSegmentLengthTicks = actualSegmentLengthTicks,
  1327. Static = @static ?? false,
  1328. Params = @params,
  1329. Tag = tag,
  1330. PlaySessionId = playSessionId,
  1331. SegmentContainer = segmentContainer,
  1332. SegmentLength = segmentLength,
  1333. MinSegments = minSegments,
  1334. MediaSourceId = mediaSourceId,
  1335. DeviceId = deviceId,
  1336. AudioCodec = audioCodec,
  1337. EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
  1338. AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
  1339. AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
  1340. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  1341. AudioSampleRate = audioSampleRate,
  1342. MaxAudioChannels = maxAudioChannels,
  1343. AudioBitRate = audioBitRate ?? maxStreamingBitrate,
  1344. MaxAudioBitDepth = maxAudioBitDepth,
  1345. AudioChannels = audioChannels,
  1346. Profile = profile,
  1347. Level = level,
  1348. Framerate = framerate,
  1349. MaxFramerate = maxFramerate,
  1350. CopyTimestamps = copyTimestamps ?? false,
  1351. StartTimeTicks = startTimeTicks,
  1352. Width = width,
  1353. Height = height,
  1354. VideoBitRate = videoBitRate,
  1355. SubtitleStreamIndex = subtitleStreamIndex,
  1356. SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
  1357. MaxRefFrames = maxRefFrames,
  1358. MaxVideoBitDepth = maxVideoBitDepth,
  1359. RequireAvc = requireAvc ?? false,
  1360. DeInterlace = deInterlace ?? false,
  1361. RequireNonAnamorphic = requireNonAnamorphic ?? false,
  1362. TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
  1363. CpuCoreLimit = cpuCoreLimit,
  1364. LiveStreamId = liveStreamId,
  1365. EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
  1366. VideoCodec = videoCodec,
  1367. SubtitleCodec = subtitleCodec,
  1368. TranscodeReasons = transcodeReasons,
  1369. AudioStreamIndex = audioStreamIndex,
  1370. VideoStreamIndex = videoStreamIndex,
  1371. Context = context ?? EncodingContext.Streaming,
  1372. StreamOptions = streamOptions,
  1373. EnableAudioVbrEncoding = enableAudioVbrEncoding,
  1374. AlwaysBurnInSubtitleWhenTranscoding = false
  1375. };
  1376. return await GetDynamicSegment(streamingRequest, segmentId)
  1377. .ConfigureAwait(false);
  1378. }
  1379. private async Task<ActionResult> GetVariantPlaylistInternal(StreamingRequestDto streamingRequest, CancellationTokenSource cancellationTokenSource)
  1380. {
  1381. using var state = await StreamingHelpers.GetStreamingState(
  1382. streamingRequest,
  1383. HttpContext,
  1384. _mediaSourceManager,
  1385. _userManager,
  1386. _libraryManager,
  1387. _serverConfigurationManager,
  1388. _mediaEncoder,
  1389. _encodingHelper,
  1390. _transcodeManager,
  1391. TranscodingJobType,
  1392. cancellationTokenSource.Token)
  1393. .ConfigureAwait(false);
  1394. var request = new CreateMainPlaylistRequest(
  1395. state.MediaPath,
  1396. state.SegmentLength * 1000,
  1397. state.RunTimeTicks ?? 0,
  1398. state.Request.SegmentContainer ?? string.Empty,
  1399. "hls1/main/",
  1400. Request.QueryString.ToString(),
  1401. EncodingHelper.IsCopyCodec(state.OutputVideoCodec));
  1402. var playlist = _dynamicHlsPlaylistGenerator.CreateMainPlaylist(request);
  1403. return new FileContentResult(Encoding.UTF8.GetBytes(playlist), MimeTypes.GetMimeType("playlist.m3u8"));
  1404. }
  1405. private async Task<ActionResult> GetDynamicSegment(StreamingRequestDto streamingRequest, int segmentId)
  1406. {
  1407. if ((streamingRequest.StartTimeTicks ?? 0) > 0)
  1408. {
  1409. throw new ArgumentException("StartTimeTicks is not allowed.");
  1410. }
  1411. // CTS lifecycle is managed internally.
  1412. var cancellationTokenSource = new CancellationTokenSource();
  1413. var cancellationToken = cancellationTokenSource.Token;
  1414. var state = await StreamingHelpers.GetStreamingState(
  1415. streamingRequest,
  1416. HttpContext,
  1417. _mediaSourceManager,
  1418. _userManager,
  1419. _libraryManager,
  1420. _serverConfigurationManager,
  1421. _mediaEncoder,
  1422. _encodingHelper,
  1423. _transcodeManager,
  1424. TranscodingJobType,
  1425. cancellationToken)
  1426. .ConfigureAwait(false);
  1427. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
  1428. var segmentPath = GetSegmentPath(state, playlistPath, segmentId);
  1429. var segmentExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
  1430. TranscodingJob? job;
  1431. if (System.IO.File.Exists(segmentPath))
  1432. {
  1433. job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  1434. _logger.LogDebug("returning {0} [it exists, try 1]", segmentPath);
  1435. return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
  1436. }
  1437. using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
  1438. {
  1439. var startTranscoding = false;
  1440. if (System.IO.File.Exists(segmentPath))
  1441. {
  1442. job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  1443. _logger.LogDebug("returning {0} [it exists, try 2]", segmentPath);
  1444. return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
  1445. }
  1446. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
  1447. var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
  1448. if (segmentId == -1)
  1449. {
  1450. _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
  1451. startTranscoding = true;
  1452. segmentId = 0;
  1453. }
  1454. else if (currentTranscodingIndex is null)
  1455. {
  1456. _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
  1457. startTranscoding = true;
  1458. }
  1459. else if (segmentId < currentTranscodingIndex.Value)
  1460. {
  1461. _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segmentId, currentTranscodingIndex);
  1462. startTranscoding = true;
  1463. }
  1464. else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
  1465. {
  1466. _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", segmentId - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, segmentId);
  1467. startTranscoding = true;
  1468. }
  1469. if (startTranscoding)
  1470. {
  1471. // If the playlist doesn't already exist, startup ffmpeg
  1472. try
  1473. {
  1474. await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionId, p => false)
  1475. .ConfigureAwait(false);
  1476. if (currentTranscodingIndex.HasValue)
  1477. {
  1478. await DeleteLastFile(playlistPath, segmentExtension, 0).ConfigureAwait(false);
  1479. }
  1480. streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks;
  1481. state.WaitForPath = segmentPath;
  1482. job = await _transcodeManager.StartFfMpeg(
  1483. state,
  1484. playlistPath,
  1485. GetCommandLineArguments(playlistPath, state, false, segmentId),
  1486. Request.HttpContext.User.GetUserId(),
  1487. TranscodingJobType,
  1488. cancellationTokenSource).ConfigureAwait(false);
  1489. }
  1490. catch
  1491. {
  1492. state.Dispose();
  1493. throw;
  1494. }
  1495. // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
  1496. }
  1497. else
  1498. {
  1499. job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  1500. if (job?.TranscodingThrottler is not null)
  1501. {
  1502. await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
  1503. }
  1504. }
  1505. }
  1506. _logger.LogDebug("returning {0} [general case]", segmentPath);
  1507. job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  1508. return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
  1509. }
  1510. private static double[] GetSegmentLengths(StreamState state)
  1511. => GetSegmentLengthsInternal(state.RunTimeTicks ?? 0, state.SegmentLength);
  1512. internal static double[] GetSegmentLengthsInternal(long runtimeTicks, int segmentlength)
  1513. {
  1514. var segmentLengthTicks = TimeSpan.FromSeconds(segmentlength).Ticks;
  1515. var wholeSegments = runtimeTicks / segmentLengthTicks;
  1516. var remainingTicks = runtimeTicks % segmentLengthTicks;
  1517. var segmentsLen = wholeSegments + (remainingTicks == 0 ? 0 : 1);
  1518. var segments = new double[segmentsLen];
  1519. for (int i = 0; i < wholeSegments; i++)
  1520. {
  1521. segments[i] = segmentlength;
  1522. }
  1523. if (remainingTicks != 0)
  1524. {
  1525. segments[^1] = TimeSpan.FromTicks(remainingTicks).TotalSeconds;
  1526. }
  1527. return segments;
  1528. }
  1529. private string GetCommandLineArguments(string outputPath, StreamState state, bool isEventPlaylist, int startNumber)
  1530. {
  1531. var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
  1532. var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec);
  1533. if (state.BaseRequest.BreakOnNonKeyFrames)
  1534. {
  1535. // FIXME: this is actually a workaround, as ideally it really should be the client which decides whether non-keyframe
  1536. // breakpoints are supported; but current implementation always uses "ffmpeg input seeking" which is liable
  1537. // to produce a missing part of video stream before first keyframe is encountered, which may lead to
  1538. // awkward cases like a few starting HLS segments having no video whatsoever, which breaks hls.js
  1539. _logger.LogInformation("Current HLS implementation doesn't support non-keyframe breaks but one is requested, ignoring that request");
  1540. state.BaseRequest.BreakOnNonKeyFrames = false;
  1541. }
  1542. var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty;
  1543. var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
  1544. var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
  1545. var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension);
  1546. var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
  1547. var outputTsArg = outputPrefix + "%d" + outputExtension;
  1548. var segmentFormat = string.Empty;
  1549. var segmentContainer = outputExtension.TrimStart('.');
  1550. var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions, segmentContainer);
  1551. if (string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
  1552. {
  1553. segmentFormat = "mpegts";
  1554. }
  1555. else if (string.Equals(segmentContainer, "mp4", StringComparison.OrdinalIgnoreCase))
  1556. {
  1557. var outputFmp4HeaderArg = OperatingSystem.IsWindows() switch
  1558. {
  1559. // on Windows, the path of fmp4 header file needs to be configured
  1560. true => " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\"",
  1561. // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder
  1562. false => " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\""
  1563. };
  1564. segmentFormat = "fmp4" + outputFmp4HeaderArg;
  1565. }
  1566. else
  1567. {
  1568. _logger.LogError("Invalid HLS segment container: {SegmentContainer}, default to mpegts", segmentContainer);
  1569. segmentFormat = "mpegts";
  1570. }
  1571. var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128
  1572. ? _encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture)
  1573. : "128";
  1574. var baseUrlParam = string.Empty;
  1575. if (isEventPlaylist)
  1576. {
  1577. baseUrlParam = string.Format(
  1578. CultureInfo.InvariantCulture,
  1579. " -hls_base_url \"hls/{0}/\"",
  1580. Path.GetFileNameWithoutExtension(outputPath));
  1581. }
  1582. var hlsArguments = $"-hls_playlist_type {(isEventPlaylist ? "event" : "vod")} -hls_list_size 0";
  1583. return string.Format(
  1584. CultureInfo.InvariantCulture,
  1585. "{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 {9}{10} -hls_segment_filename \"{11}\" {12} -y \"{13}\"",
  1586. inputModifier,
  1587. _encodingHelper.GetInputArgument(state, _encodingOptions, segmentContainer),
  1588. threads,
  1589. mapArgs,
  1590. GetVideoArguments(state, startNumber, isEventPlaylist, segmentContainer),
  1591. GetAudioArguments(state),
  1592. maxMuxingQueueSize,
  1593. state.SegmentLength.ToString(CultureInfo.InvariantCulture),
  1594. segmentFormat,
  1595. startNumber.ToString(CultureInfo.InvariantCulture),
  1596. baseUrlParam,
  1597. EncodingUtils.NormalizePath(outputTsArg),
  1598. hlsArguments,
  1599. EncodingUtils.NormalizePath(outputPath)).Trim();
  1600. }
  1601. /// <summary>
  1602. /// Gets the audio arguments for transcoding.
  1603. /// </summary>
  1604. /// <param name="state">The <see cref="StreamState"/>.</param>
  1605. /// <returns>The command line arguments for audio transcoding.</returns>
  1606. private string GetAudioArguments(StreamState state)
  1607. {
  1608. if (state.AudioStream is null)
  1609. {
  1610. return string.Empty;
  1611. }
  1612. var audioCodec = _encodingHelper.GetAudioEncoder(state);
  1613. var bitStreamArgs = _encodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container);
  1614. // opus, dts, truehd and flac (in FFmpeg 5 and older) are experimental in mp4 muxer
  1615. var strictArgs = string.Empty;
  1616. var actualOutputAudioCodec = state.ActualOutputAudioCodec;
  1617. if (string.Equals(actualOutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase)
  1618. || string.Equals(actualOutputAudioCodec, "dts", StringComparison.OrdinalIgnoreCase)
  1619. || string.Equals(actualOutputAudioCodec, "truehd", StringComparison.OrdinalIgnoreCase)
  1620. || (string.Equals(actualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase)
  1621. && _mediaEncoder.EncoderVersion < _minFFmpegFlacInMp4))
  1622. {
  1623. strictArgs = " -strict -2";
  1624. }
  1625. if (!state.IsOutputVideo)
  1626. {
  1627. var audioTranscodeParams = string.Empty;
  1628. // -vn to drop any video streams
  1629. audioTranscodeParams += "-vn";
  1630. if (EncodingHelper.IsCopyCodec(audioCodec))
  1631. {
  1632. return audioTranscodeParams + " -acodec copy" + bitStreamArgs + strictArgs;
  1633. }
  1634. audioTranscodeParams += " -acodec " + audioCodec + bitStreamArgs + strictArgs;
  1635. var audioBitrate = state.OutputAudioBitrate;
  1636. var audioChannels = state.OutputAudioChannels;
  1637. if (audioBitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(state.ActualOutputAudioCodec, StringComparison.OrdinalIgnoreCase))
  1638. {
  1639. var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, audioBitrate.Value, audioChannels ?? 2);
  1640. if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
  1641. {
  1642. audioTranscodeParams += vbrParam;
  1643. }
  1644. else
  1645. {
  1646. audioTranscodeParams += " -ab " + audioBitrate.Value.ToString(CultureInfo.InvariantCulture);
  1647. }
  1648. }
  1649. if (audioChannels.HasValue)
  1650. {
  1651. audioTranscodeParams += " -ac " + audioChannels.Value.ToString(CultureInfo.InvariantCulture);
  1652. }
  1653. if (state.OutputAudioSampleRate.HasValue)
  1654. {
  1655. audioTranscodeParams += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
  1656. }
  1657. return audioTranscodeParams;
  1658. }
  1659. if (EncodingHelper.IsCopyCodec(audioCodec))
  1660. {
  1661. var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
  1662. var copyArgs = "-codec:a:0 copy" + bitStreamArgs + strictArgs;
  1663. if (EncodingHelper.IsCopyCodec(videoCodec) && state.EnableBreakOnNonKeyFrames(videoCodec))
  1664. {
  1665. return copyArgs + " -copypriorss:a:0 0";
  1666. }
  1667. return copyArgs;
  1668. }
  1669. var args = "-codec:a:0 " + audioCodec + bitStreamArgs + strictArgs;
  1670. var channels = state.OutputAudioChannels;
  1671. var useDownMixAlgorithm = DownMixAlgorithmsHelper.AlgorithmFilterStrings.ContainsKey((_encodingOptions.DownMixStereoAlgorithm, DownMixAlgorithmsHelper.InferChannelLayout(state.AudioStream)));
  1672. if (channels.HasValue
  1673. && (channels.Value != 2
  1674. || (state.AudioStream?.Channels is not null && !useDownMixAlgorithm)))
  1675. {
  1676. args += " -ac " + channels.Value;
  1677. }
  1678. var bitrate = state.OutputAudioBitrate;
  1679. if (bitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(actualOutputAudioCodec, StringComparison.OrdinalIgnoreCase))
  1680. {
  1681. var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, bitrate.Value, channels ?? 2);
  1682. if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
  1683. {
  1684. args += vbrParam;
  1685. }
  1686. else
  1687. {
  1688. args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
  1689. }
  1690. }
  1691. if (state.OutputAudioSampleRate.HasValue)
  1692. {
  1693. args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
  1694. }
  1695. else if (state.AudioStream?.CodecTag is not null && state.AudioStream.CodecTag.Equals("ac-4", StringComparison.Ordinal))
  1696. {
  1697. // ac-4 audio tends to have a super weird sample rate that will fail most encoders
  1698. // force resample it to 48KHz
  1699. args += " -ar 48000";
  1700. }
  1701. args += _encodingHelper.GetAudioFilterParam(state, _encodingOptions);
  1702. return args;
  1703. }
  1704. /// <summary>
  1705. /// Gets the video arguments for transcoding.
  1706. /// </summary>
  1707. /// <param name="state">The <see cref="StreamState"/>.</param>
  1708. /// <param name="startNumber">The first number in the hls sequence.</param>
  1709. /// <param name="isEventPlaylist">Whether the playlist is EVENT or VOD.</param>
  1710. /// <param name="segmentContainer">The segment container.</param>
  1711. /// <returns>The command line arguments for video transcoding.</returns>
  1712. private string GetVideoArguments(StreamState state, int startNumber, bool isEventPlaylist, string segmentContainer)
  1713. {
  1714. if (state.VideoStream is null)
  1715. {
  1716. return string.Empty;
  1717. }
  1718. if (!state.IsOutputVideo)
  1719. {
  1720. return string.Empty;
  1721. }
  1722. var codec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
  1723. var args = "-codec:v:0 " + codec;
  1724. var isActualOutputVideoCodecAv1 = string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase);
  1725. var isActualOutputVideoCodecHevc = string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  1726. || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase);
  1727. if (isActualOutputVideoCodecHevc || isActualOutputVideoCodecAv1)
  1728. {
  1729. var requestedRange = state.GetRequestedRangeTypes(state.ActualOutputVideoCodec);
  1730. // Clients reporting Dolby Vision capabilities with fallbacks may only support the fallback layer.
  1731. // Only enable Dolby Vision remuxing if the client explicitly declares support for profiles without fallbacks.
  1732. var clientSupportsDoVi = requestedRange.Contains(VideoRangeType.DOVI.ToString(), StringComparison.OrdinalIgnoreCase);
  1733. var videoIsDoVi = EncodingHelper.IsDovi(state.VideoStream);
  1734. if (EncodingHelper.IsCopyCodec(codec)
  1735. && (videoIsDoVi && clientSupportsDoVi)
  1736. && !_encodingHelper.IsDoviRemoved(state))
  1737. {
  1738. if (isActualOutputVideoCodecHevc)
  1739. {
  1740. // Prefer dvh1 to dvhe
  1741. args += " -tag:v:0 dvh1 -strict -2";
  1742. }
  1743. else if (isActualOutputVideoCodecAv1)
  1744. {
  1745. args += " -tag:v:0 dav1 -strict -2";
  1746. }
  1747. }
  1748. else if (isActualOutputVideoCodecHevc)
  1749. {
  1750. // Prefer hvc1 to hev1
  1751. args += " -tag:v:0 hvc1";
  1752. }
  1753. }
  1754. // if (state.EnableMpegtsM2TsMode)
  1755. // {
  1756. // args += " -mpegts_m2ts_mode 1";
  1757. // }
  1758. // See if we can save come cpu cycles by avoiding encoding.
  1759. if (EncodingHelper.IsCopyCodec(codec))
  1760. {
  1761. // If h264_mp4toannexb is ever added, do not use it for live tv.
  1762. if (state.VideoStream is not null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
  1763. {
  1764. string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state, MediaStreamType.Video);
  1765. if (!string.IsNullOrEmpty(bitStreamArgs))
  1766. {
  1767. args += " " + bitStreamArgs;
  1768. }
  1769. }
  1770. args += " -start_at_zero";
  1771. }
  1772. else
  1773. {
  1774. args += _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, isEventPlaylist ? DefaultEventEncoderPreset : DefaultVodEncoderPreset);
  1775. // Set the key frame params for video encoding to match the hls segment time.
  1776. args += _encodingHelper.GetHlsVideoKeyFrameArguments(state, codec, state.SegmentLength, isEventPlaylist, startNumber);
  1777. // Currently b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now.
  1778. if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)
  1779. && _mediaEncoder.EncoderVersion < _minFFmpegX265BframeInFmp4)
  1780. {
  1781. args += " -bf 0";
  1782. }
  1783. // video processing filters.
  1784. var videoProcessParam = _encodingHelper.GetVideoProcessingFilterParam(state, _encodingOptions, codec);
  1785. var negativeMapArgs = _encodingHelper.GetNegativeMapArgsByFilters(state, videoProcessParam);
  1786. args = negativeMapArgs + args + videoProcessParam;
  1787. // -start_at_zero is necessary to use with -ss when seeking,
  1788. // otherwise the target position cannot be determined.
  1789. if (state.SubtitleStream is not null)
  1790. {
  1791. // Disable start_at_zero for external graphical subs
  1792. if (!(state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
  1793. {
  1794. args += " -start_at_zero";
  1795. }
  1796. }
  1797. }
  1798. // TODO why was this not enabled for VOD?
  1799. if (isEventPlaylist && string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
  1800. {
  1801. args += " -flags -global_header";
  1802. }
  1803. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  1804. {
  1805. args += EncodingHelper.GetVideoSyncOption(state.OutputVideoSync, _mediaEncoder.EncoderVersion);
  1806. }
  1807. args += _encodingHelper.GetOutputFFlags(state);
  1808. return args;
  1809. }
  1810. private string GetSegmentPath(StreamState state, string playlist, int index)
  1811. {
  1812. var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException($"Provided path ({playlist}) is not valid.", nameof(playlist));
  1813. var filename = Path.GetFileNameWithoutExtension(playlist);
  1814. return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer));
  1815. }
  1816. private async Task<ActionResult> GetSegmentResult(
  1817. StreamState state,
  1818. string playlistPath,
  1819. string segmentPath,
  1820. string segmentExtension,
  1821. int segmentIndex,
  1822. TranscodingJob? transcodingJob,
  1823. CancellationToken cancellationToken)
  1824. {
  1825. var segmentExists = System.IO.File.Exists(segmentPath);
  1826. if (segmentExists)
  1827. {
  1828. if (transcodingJob is not null && transcodingJob.HasExited)
  1829. {
  1830. // Transcoding job is over, so assume all existing files are ready
  1831. _logger.LogDebug("serving up {0} as transcode is over", segmentPath);
  1832. return GetSegmentResult(state, segmentPath, transcodingJob);
  1833. }
  1834. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
  1835. // If requested segment is less than transcoding position, we can't transcode backwards, so assume it's ready
  1836. if (segmentIndex < currentTranscodingIndex)
  1837. {
  1838. _logger.LogDebug("serving up {0} as transcode index {1} is past requested point {2}", segmentPath, currentTranscodingIndex, segmentIndex);
  1839. return GetSegmentResult(state, segmentPath, transcodingJob);
  1840. }
  1841. }
  1842. var nextSegmentPath = GetSegmentPath(state, playlistPath, segmentIndex + 1);
  1843. if (transcodingJob is not null)
  1844. {
  1845. while (!cancellationToken.IsCancellationRequested && !transcodingJob.HasExited)
  1846. {
  1847. // To be considered ready, the segment file has to exist AND
  1848. // either the transcoding job should be done or next segment should also exist
  1849. if (segmentExists)
  1850. {
  1851. if (transcodingJob.HasExited || System.IO.File.Exists(nextSegmentPath))
  1852. {
  1853. _logger.LogDebug("Serving up {SegmentPath} as it deemed ready", segmentPath);
  1854. return GetSegmentResult(state, segmentPath, transcodingJob);
  1855. }
  1856. }
  1857. else
  1858. {
  1859. segmentExists = System.IO.File.Exists(segmentPath);
  1860. if (segmentExists)
  1861. {
  1862. continue; // avoid unnecessary waiting if segment just became available
  1863. }
  1864. }
  1865. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  1866. }
  1867. if (!System.IO.File.Exists(segmentPath))
  1868. {
  1869. _logger.LogWarning("cannot serve {0} as transcoding quit before we got there", segmentPath);
  1870. }
  1871. else
  1872. {
  1873. _logger.LogDebug("serving {0} as it's on disk and transcoding stopped", segmentPath);
  1874. }
  1875. cancellationToken.ThrowIfCancellationRequested();
  1876. }
  1877. else
  1878. {
  1879. _logger.LogWarning("cannot serve {0} as it doesn't exist and no transcode is running", segmentPath);
  1880. }
  1881. return GetSegmentResult(state, segmentPath, transcodingJob);
  1882. }
  1883. private ActionResult GetSegmentResult(StreamState state, string segmentPath, TranscodingJob? transcodingJob)
  1884. {
  1885. var segmentEndingPositionTicks = state.Request.CurrentRuntimeTicks + state.Request.ActualSegmentLengthTicks;
  1886. Response.OnCompleted(() =>
  1887. {
  1888. _logger.LogDebug("Finished serving {SegmentPath}", segmentPath);
  1889. if (transcodingJob is not null)
  1890. {
  1891. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  1892. _transcodeManager.OnTranscodeEndRequest(transcodingJob);
  1893. }
  1894. return Task.CompletedTask;
  1895. });
  1896. return FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath));
  1897. }
  1898. private int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
  1899. {
  1900. var job = _transcodeManager.GetTranscodingJob(playlist, TranscodingJobType);
  1901. if (job is null || job.HasExited)
  1902. {
  1903. return null;
  1904. }
  1905. var file = GetLastTranscodingFile(playlist, segmentExtension, _fileSystem);
  1906. if (file is null)
  1907. {
  1908. return null;
  1909. }
  1910. var playlistFilename = Path.GetFileNameWithoutExtension(playlist.AsSpan());
  1911. var indexString = Path.GetFileNameWithoutExtension(file.Name.AsSpan()).Slice(playlistFilename.Length);
  1912. return int.Parse(indexString, NumberStyles.Integer, CultureInfo.InvariantCulture);
  1913. }
  1914. private static FileSystemMetadata? GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
  1915. {
  1916. var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException("Path can't be a root directory.", nameof(playlist));
  1917. var filePrefix = Path.GetFileNameWithoutExtension(playlist);
  1918. try
  1919. {
  1920. return fileSystem.GetFiles(folder, new[] { segmentExtension }, true, false)
  1921. .Where(i => Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase))
  1922. .MaxBy(fileSystem.GetLastWriteTimeUtc);
  1923. }
  1924. catch (IOException)
  1925. {
  1926. return null;
  1927. }
  1928. }
  1929. private async Task DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
  1930. {
  1931. var file = GetLastTranscodingFile(playlistPath, segmentExtension, _fileSystem);
  1932. if (file is null)
  1933. {
  1934. return;
  1935. }
  1936. await DeleteFile(file.FullName, retryCount).ConfigureAwait(false);
  1937. }
  1938. private async Task DeleteFile(string path, int retryCount)
  1939. {
  1940. if (retryCount >= 5)
  1941. {
  1942. return;
  1943. }
  1944. _logger.LogDebug("Deleting partial HLS file {Path}", path);
  1945. try
  1946. {
  1947. _fileSystem.DeleteFile(path);
  1948. }
  1949. catch (IOException ex)
  1950. {
  1951. _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
  1952. await Task.Delay(100).ConfigureAwait(false);
  1953. await DeleteFile(path, retryCount + 1).ConfigureAwait(false);
  1954. }
  1955. catch (Exception ex)
  1956. {
  1957. _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
  1958. }
  1959. }
  1960. }