DynamicHlsController.cs 110 KB

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