DynamicHlsController.cs 111 KB

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