DynamicHlsController.cs 112 KB

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