2
0

DynamicHlsController.cs 111 KB

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