< Summary - Jellyfin

Information
Class: Jellyfin.Api.Controllers.HlsSegmentController
Assembly: Jellyfin.Api
File(s): /srv/git/jellyfin/Jellyfin.Api/Controllers/HlsSegmentController.cs
Line coverage
96%
Covered lines: 50
Uncovered lines: 2
Coverable lines: 52
Total lines: 194
Line coverage: 96.1%
Branch coverage
95%
Covered branches: 19
Total branches: 20
Branch coverage: 95%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 4/15/2026 - 12:14:34 AM Line coverage: 0% (0/56) Branch coverage: 0% (0/24) Total lines: 1914/30/2026 - 12:14:58 AM Line coverage: 0% (0/56) Branch coverage: 0% (0/24) Total lines: 1927/18/2026 - 12:15:19 AM Line coverage: 96.1% (50/52) Branch coverage: 95% (19/20) Total lines: 194 4/15/2026 - 12:14:34 AM Line coverage: 0% (0/56) Branch coverage: 0% (0/24) Total lines: 1914/30/2026 - 12:14:58 AM Line coverage: 0% (0/56) Branch coverage: 0% (0/24) Total lines: 1927/18/2026 - 12:15:19 AM Line coverage: 96.1% (50/52) Branch coverage: 95% (19/20) Total lines: 194

Coverage delta

Coverage delta 97 -97

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
GetHlsAudioSegmentLegacy(...)100%22100%
GetHlsPlaylistLegacy(...)100%44100%
StopEncodingProcess(...)100%210%
GetHlsVideoSegmentLegacy(...)91.66%1212100%
ValidateTranscodePath(...)100%22100%
GetFileResult(...)100%11100%

File(s)

/srv/git/jellyfin/Jellyfin.Api/Controllers/HlsSegmentController.cs

#LineLine coverage
 1using System;
 2using System.ComponentModel.DataAnnotations;
 3using System.Diagnostics.CodeAnalysis;
 4using System.IO;
 5using System.Threading.Tasks;
 6using Jellyfin.Api.Attributes;
 7using Jellyfin.Api.Helpers;
 8using MediaBrowser.Common.Configuration;
 9using MediaBrowser.Controller.Configuration;
 10using MediaBrowser.Controller.MediaEncoding;
 11using MediaBrowser.Model.IO;
 12using MediaBrowser.Model.Net;
 13using Microsoft.AspNetCore.Authorization;
 14using Microsoft.AspNetCore.Http;
 15using Microsoft.AspNetCore.Mvc;
 16
 17namespace Jellyfin.Api.Controllers;
 18
 19/// <summary>
 20/// The hls segment controller.
 21/// </summary>
 22[Route("")]
 23[ApiExplorerSettings(IgnoreApi = true)]
 24public class HlsSegmentController : BaseJellyfinApiController
 25{
 26    private readonly IFileSystem _fileSystem;
 27    private readonly IServerConfigurationManager _serverConfigurationManager;
 28    private readonly ITranscodeManager _transcodeManager;
 29
 30    /// <summary>
 31    /// Initializes a new instance of the <see cref="HlsSegmentController"/> class.
 32    /// </summary>
 33    /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
 34    /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</p
 35    /// <param name="transcodeManager">Instance of the <see cref="ITranscodeManager"/> interface.</param>
 1136    public HlsSegmentController(
 1137        IFileSystem fileSystem,
 1138        IServerConfigurationManager serverConfigurationManager,
 1139        ITranscodeManager transcodeManager)
 40    {
 1141        _fileSystem = fileSystem;
 1142        _serverConfigurationManager = serverConfigurationManager;
 1143        _transcodeManager = transcodeManager;
 1144    }
 45
 46    /// <summary>
 47    /// Gets the specified audio segment for an audio item.
 48    /// </summary>
 49    /// <param name="itemId">The item id.</param>
 50    /// <param name="segmentId">The segment id.</param>
 51    /// <response code="200">Hls audio segment returned.</response>
 52    /// <returns>A <see cref="FileStreamResult"/> containing the audio stream.</returns>
 53    // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
 54    // [Authenticated]
 55    [HttpGet("Audio/{itemId}/hls/{segmentId}/stream.mp3", Name = "GetHlsAudioSegmentLegacyMp3")]
 56    [HttpGet("Audio/{itemId}/hls/{segmentId}/stream.aac", Name = "GetHlsAudioSegmentLegacyAac")]
 57    [ProducesResponseType(StatusCodes.Status200OK)]
 58    [ProducesAudioFile]
 59    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Re
 60    public ActionResult GetHlsAudioSegmentLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string segme
 61    {
 62        // TODO: Deprecate with new iOS app
 563        var file = ValidateTranscodePath(string.Concat(segmentId, Path.GetExtension(Request.Path.Value.AsSpan())));
 564        if (file is null)
 65        {
 466            return BadRequest("Invalid segment.");
 67        }
 68
 169        return FileStreamResponseHelpers.GetStaticFileResult(file, MimeTypes.GetMimeType(file));
 70    }
 71
 72    /// <summary>
 73    /// Gets a hls video playlist.
 74    /// </summary>
 75    /// <param name="itemId">The video id.</param>
 76    /// <param name="playlistId">The playlist id.</param>
 77    /// <response code="200">Hls video playlist returned.</response>
 78    /// <returns>A <see cref="FileStreamResult"/> containing the playlist.</returns>
 79    [HttpGet("Videos/{itemId}/hls/{playlistId}/stream.m3u8")]
 80    [Authorize]
 81    [ProducesResponseType(StatusCodes.Status200OK)]
 82    [ProducesPlaylistFile]
 83    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Re
 84    public ActionResult GetHlsPlaylistLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string playlistI
 85    {
 386        var file = ValidateTranscodePath(string.Concat(playlistId, Path.GetExtension(Request.Path.Value.AsSpan())));
 387        if (file is null
 388            || !Path.GetExtension(file.AsSpan()).Equals(".m3u8", StringComparison.OrdinalIgnoreCase))
 89        {
 290            return BadRequest("Invalid segment.");
 91        }
 92
 193        return GetFileResult(file, file);
 94    }
 95
 96    /// <summary>
 97    /// Stops an active encoding.
 98    /// </summary>
 99    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 100    /// <param name="playSessionId">The play session id.</param>
 101    /// <response code="204">Encoding stopped successfully.</response>
 102    /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
 103    [HttpDelete("Videos/ActiveEncodings")]
 104    [Authorize]
 105    [ProducesResponseType(StatusCodes.Status204NoContent)]
 106    public ActionResult StopEncodingProcess(
 107        [FromQuery, Required] string deviceId,
 108        [FromQuery, Required] string playSessionId)
 109    {
 0110        _transcodeManager.KillTranscodingJobs(deviceId, playSessionId, _ => true);
 0111        return NoContent();
 112    }
 113
 114    /// <summary>
 115    /// Gets a hls video segment.
 116    /// </summary>
 117    /// <param name="itemId">The item id.</param>
 118    /// <param name="playlistId">The playlist id.</param>
 119    /// <param name="segmentId">The segment id.</param>
 120    /// <param name="segmentContainer">The segment container.</param>
 121    /// <response code="200">Hls video segment returned.</response>
 122    /// <response code="404">Hls segment not found.</response>
 123    /// <returns>A <see cref="FileStreamResult"/> containing the video segment.</returns>
 124    // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
 125    // [Authenticated]
 126    [HttpGet("Videos/{itemId}/hls/{playlistId}/{segmentId}.{segmentContainer}")]
 127    [ProducesResponseType(StatusCodes.Status200OK)]
 128    [ProducesResponseType(StatusCodes.Status404NotFound)]
 129    [ProducesVideoFile]
 130    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Re
 131    public ActionResult GetHlsVideoSegmentLegacy(
 132        [FromRoute, Required] string itemId,
 133        [FromRoute, Required] string playlistId,
 134        [FromRoute, Required] string segmentId,
 135        [FromRoute, Required] string segmentContainer)
 136    {
 3137        var file = ValidateTranscodePath(string.Concat(segmentId, Path.GetExtension(Request.Path.Value.AsSpan())));
 3138        if (file is null)
 139        {
 1140            return BadRequest("Invalid segment.");
 141        }
 142
 2143        var transcodeFolderPath = _serverConfigurationManager.GetTranscodePath();
 2144        var filePaths = _fileSystem.GetFilePaths(transcodeFolderPath);
 145        // Add . to start of segment container for future use.
 2146        segmentContainer = segmentContainer.Insert(0, ".");
 2147        string? playlistPath = null;
 5148        foreach (var path in filePaths)
 149        {
 1150            var pathExtension = Path.GetExtension(path);
 1151            if ((string.Equals(pathExtension, segmentContainer, StringComparison.OrdinalIgnoreCase)
 1152                 || string.Equals(pathExtension, ".m3u8", StringComparison.OrdinalIgnoreCase))
 1153                && path.Contains(playlistId, StringComparison.OrdinalIgnoreCase))
 154            {
 1155                playlistPath = path;
 1156                break;
 157            }
 158        }
 159
 2160        return playlistPath is null
 2161            ? NotFound("Hls segment not found.")
 2162            : GetFileResult(file, playlistPath);
 163    }
 164
 165    private string? ValidateTranscodePath(string filename)
 166    {
 11167        var transcodePath = Path.TrimEndingDirectorySeparator(Path.GetFullPath(_serverConfigurationManager.GetTranscodeP
 11168        var file = Path.GetFullPath(filename, transcodePath);
 169        // Require a separator after the transcode path so a sibling like "<transcodePath>-evil" can't pass.
 11170        if (!file.StartsWith(transcodePath + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
 171        {
 6172            return null;
 173        }
 174
 5175        return file;
 176    }
 177
 178    private ActionResult GetFileResult(string path, string playlistPath)
 179    {
 2180        var transcodingJob = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
 181
 2182        Response.OnCompleted(() =>
 2183        {
 2184            if (transcodingJob is not null)
 2185            {
 2186                _transcodeManager.OnTranscodeEndRequest(transcodingJob);
 2187            }
 2188
 2189            return Task.CompletedTask;
 2190        });
 191
 2192        return FileStreamResponseHelpers.GetStaticFileResult(path, MimeTypes.GetMimeType(path));
 193    }
 194}