DynamicHlsController.cs 113 KB

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