DynamicHlsController.cs 111 KB

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