DynamicHlsController.cs 112 KB

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