< Summary - Jellyfin

Information
Class: Jellyfin.Api.Controllers.SubtitleController
Assembly: Jellyfin.Api
File(s): /srv/git/jellyfin/Jellyfin.Api/Controllers/SubtitleController.cs
Line coverage
34%
Covered lines: 77
Uncovered lines: 146
Coverable lines: 223
Total lines: 659
Line coverage: 34.5%
Branch coverage
42%
Covered branches: 30
Total branches: 70
Branch coverage: 42.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/200) Branch coverage: 0% (0/46) Total lines: 58010/29/2026 - 12:17:11 AM Line coverage: 34.5% (77/223) Branch coverage: 42.8% (30/70) Total lines: 659 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/200) Branch coverage: 0% (0/46) Total lines: 58010/29/2026 - 12:17:11 AM Line coverage: 34.5% (77/223) Branch coverage: 42.8% (30/70) Total lines: 659

Coverage delta

Coverage delta 43 -43

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
DeleteSubtitle()0%620%
SearchRemoteSubtitles()0%620%
DownloadRemoteSubtitles()0%620%
GetRemoteSubtitles()100%210%
GetSubtitle()88.88%231875%
GetSubtitleWithTicks(...)100%210%
GetSubtitlePlaylist()0%7280%
GetVttTimestampMap(...)100%11100%
GetSubtitleSegmentUrl(...)100%11100%
UploadSubtitle()0%620%
GetGraphicalSubtitlePath()70%212085%
EncodeSubtitles(...)100%11100%
GetFallbackFontList()0%4260%
GetFallbackFont(...)0%110100%

File(s)

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

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.ComponentModel.DataAnnotations;
 4using System.Diagnostics.CodeAnalysis;
 5using System.Globalization;
 6using System.IO;
 7using System.Linq;
 8using System.Net.Mime;
 9using System.Security.Cryptography;
 10using System.Text;
 11using System.Threading;
 12using System.Threading.Tasks;
 13using Jellyfin.Api.Attributes;
 14using Jellyfin.Api.Extensions;
 15using Jellyfin.Api.Helpers;
 16using Jellyfin.Api.Models.SubtitleDtos;
 17using MediaBrowser.Common.Api;
 18using MediaBrowser.Common.Configuration;
 19using MediaBrowser.Controller.Configuration;
 20using MediaBrowser.Controller.Entities;
 21using MediaBrowser.Controller.Library;
 22using MediaBrowser.Controller.MediaEncoding;
 23using MediaBrowser.Controller.Providers;
 24using MediaBrowser.Controller.Subtitles;
 25using MediaBrowser.Model.Entities;
 26using MediaBrowser.Model.IO;
 27using MediaBrowser.Model.Net;
 28using MediaBrowser.Model.Providers;
 29using MediaBrowser.Model.Subtitles;
 30using Microsoft.AspNetCore.Authorization;
 31using Microsoft.AspNetCore.Http;
 32using Microsoft.AspNetCore.Mvc;
 33using Microsoft.Extensions.Logging;
 34
 35namespace Jellyfin.Api.Controllers;
 36
 37/// <summary>
 38/// Subtitle controller.
 39/// </summary>
 40[Route("")]
 41public class SubtitleController : BaseJellyfinApiController
 42{
 43    private readonly IServerConfigurationManager _serverConfigurationManager;
 44    private readonly ILibraryManager _libraryManager;
 45    private readonly ISubtitleManager _subtitleManager;
 46    private readonly ISubtitleEncoder _subtitleEncoder;
 47    private readonly IMediaSourceManager _mediaSourceManager;
 48    private readonly IProviderManager _providerManager;
 49    private readonly IFileSystem _fileSystem;
 50    private readonly ILogger<SubtitleController> _logger;
 51
 52    /// <summary>
 53    /// The default MPEGTS value used in the WebVTT X-TIMESTAMP-MAP header, matching the legacy MPEG-TS
 54    /// segment container's 10 second PTS offset.
 55    /// </summary>
 56    internal const long DefaultVttTimestampMapMpegts = 900000;
 57
 58    /// <summary>
 59    /// Initializes a new instance of the <see cref="SubtitleController"/> class.
 60    /// </summary>
 61    /// <param name="serverConfigurationManager">Instance of <see cref="IServerConfigurationManager"/> interface.</param
 62    /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
 63    /// <param name="subtitleManager">Instance of <see cref="ISubtitleManager"/> interface.</param>
 64    /// <param name="subtitleEncoder">Instance of <see cref="ISubtitleEncoder"/> interface.</param>
 65    /// <param name="mediaSourceManager">Instance of <see cref="IMediaSourceManager"/> interface.</param>
 66    /// <param name="providerManager">Instance of <see cref="IProviderManager"/> interface.</param>
 67    /// <param name="fileSystem">Instance of <see cref="IFileSystem"/> interface.</param>
 68    /// <param name="logger">Instance of <see cref="ILogger{SubtitleController}"/> interface.</param>
 569    public SubtitleController(
 570        IServerConfigurationManager serverConfigurationManager,
 571        ILibraryManager libraryManager,
 572        ISubtitleManager subtitleManager,
 573        ISubtitleEncoder subtitleEncoder,
 574        IMediaSourceManager mediaSourceManager,
 575        IProviderManager providerManager,
 576        IFileSystem fileSystem,
 577        ILogger<SubtitleController> logger)
 78    {
 579        _serverConfigurationManager = serverConfigurationManager;
 580        _libraryManager = libraryManager;
 581        _subtitleManager = subtitleManager;
 582        _subtitleEncoder = subtitleEncoder;
 583        _mediaSourceManager = mediaSourceManager;
 584        _providerManager = providerManager;
 585        _fileSystem = fileSystem;
 586        _logger = logger;
 587    }
 88
 89    /// <summary>
 90    /// Deletes an external subtitle file.
 91    /// </summary>
 92    /// <param name="itemId">The item id.</param>
 93    /// <param name="index">The index of the subtitle file.</param>
 94    /// <response code="204">Subtitle deleted.</response>
 95    /// <response code="404">Item not found.</response>
 96    /// <returns>A <see cref="NoContentResult"/>.</returns>
 97    [HttpDelete("Videos/{itemId}/Subtitles/{index}")]
 98    [Authorize(Policy = Policies.RequiresElevation)]
 99    [ProducesResponseType(StatusCodes.Status204NoContent)]
 100    [ProducesResponseType(StatusCodes.Status404NotFound)]
 101    public async Task<ActionResult> DeleteSubtitle(
 102        [FromRoute, Required] Guid itemId,
 103        [FromRoute, Required] int index)
 104    {
 0105        var item = _libraryManager.GetItemById<BaseItem>(itemId, User.GetUserId());
 0106        if (item is null)
 107        {
 0108            return NotFound();
 109        }
 110
 0111        await _subtitleManager.DeleteSubtitles(item, index).ConfigureAwait(false);
 0112        return NoContent();
 0113    }
 114
 115    /// <summary>
 116    /// Search remote subtitles.
 117    /// </summary>
 118    /// <param name="itemId">The item id.</param>
 119    /// <param name="language">The language of the subtitles.</param>
 120    /// <param name="isPerfectMatch">Optional. Only show subtitles which are a perfect match.</param>
 121    /// <response code="200">Subtitles retrieved.</response>
 122    /// <response code="404">Item not found.</response>
 123    /// <returns>An array of <see cref="RemoteSubtitleInfo"/>.</returns>
 124    [HttpGet("Items/{itemId}/RemoteSearch/Subtitles/{language}")]
 125    [Authorize(Policy = Policies.SubtitleManagement)]
 126    [ProducesResponseType(StatusCodes.Status200OK)]
 127    [ProducesResponseType(StatusCodes.Status404NotFound)]
 128    public async Task<ActionResult<IEnumerable<RemoteSubtitleInfo>>> SearchRemoteSubtitles(
 129        [FromRoute, Required] Guid itemId,
 130        [FromRoute, Required] string language,
 131        [FromQuery] bool? isPerfectMatch)
 132    {
 0133        var item = _libraryManager.GetItemById<Video>(itemId, User.GetUserId());
 0134        if (item is null)
 135        {
 0136            return NotFound();
 137        }
 138
 0139        return await _subtitleManager.SearchSubtitles(item, language, isPerfectMatch, false, CancellationToken.None).Con
 0140    }
 141
 142    /// <summary>
 143    /// Downloads a remote subtitle.
 144    /// </summary>
 145    /// <param name="itemId">The item id.</param>
 146    /// <param name="subtitleId">The subtitle id.</param>
 147    /// <response code="204">Subtitle downloaded.</response>
 148    /// <response code="404">Item not found.</response>
 149    /// <returns>A <see cref="NoContentResult"/>.</returns>
 150    [HttpPost("Items/{itemId}/RemoteSearch/Subtitles/{subtitleId}")]
 151    [Authorize(Policy = Policies.SubtitleManagement)]
 152    [ProducesResponseType(StatusCodes.Status204NoContent)]
 153    [ProducesResponseType(StatusCodes.Status404NotFound)]
 154    public async Task<ActionResult> DownloadRemoteSubtitles(
 155        [FromRoute, Required] Guid itemId,
 156        [FromRoute, Required] string subtitleId)
 157    {
 0158        var item = _libraryManager.GetItemById<Video>(itemId, User.GetUserId());
 0159        if (item is null)
 160        {
 0161            return NotFound();
 162        }
 163
 164        try
 165        {
 0166            await _subtitleManager.DownloadSubtitles(item, subtitleId, CancellationToken.None)
 0167                .ConfigureAwait(false);
 168
 0169            _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), Refres
 0170        }
 0171        catch (Exception ex)
 172        {
 0173            _logger.LogError(ex, "Error downloading subtitles");
 0174        }
 175
 0176        return NoContent();
 0177    }
 178
 179    /// <summary>
 180    /// Gets the remote subtitles.
 181    /// </summary>
 182    /// <param name="subtitleId">The item id.</param>
 183    /// <response code="200">File returned.</response>
 184    /// <returns>A <see cref="FileStreamResult"/> with the subtitle file.</returns>
 185    [HttpGet("Providers/Subtitles/Subtitles/{subtitleId}")]
 186    [Authorize(Policy = Policies.SubtitleManagement)]
 187    [ProducesResponseType(StatusCodes.Status200OK)]
 188    [Produces(MediaTypeNames.Application.Octet)]
 189    [ProducesFile("text/*")]
 190    public async Task<ActionResult> GetRemoteSubtitles([FromRoute, Required] string subtitleId)
 191    {
 0192        var result = await _subtitleManager.GetRemoteSubtitles(subtitleId, CancellationToken.None).ConfigureAwait(false)
 193
 0194        return File(result.Stream, MimeTypes.GetMimeType("file." + result.Format));
 0195    }
 196
 197    /// <summary>
 198    /// Gets subtitles in a specified format.
 199    /// </summary>
 200    /// <param name="routeItemId">The (route) item id.</param>
 201    /// <param name="routeMediaSourceId">The (route) media source id.</param>
 202    /// <param name="routeIndex">The (route) subtitle stream index.</param>
 203    /// <param name="routeFormat">The (route) format of the returned subtitle.</param>
 204    /// <param name="itemId">The item id.</param>
 205    /// <param name="mediaSourceId">The media source id.</param>
 206    /// <param name="index">The subtitle stream index.</param>
 207    /// <param name="format">The format of the returned subtitle.</param>
 208    /// <param name="endPositionTicks">Optional. The end position of the subtitle in ticks.</param>
 209    /// <param name="copyTimestamps">Optional. Whether to copy the timestamps.</param>
 210    /// <param name="addVttTimeMap">Optional. Whether to add a VTT time map.</param>
 211    /// <param name="vttTimestampMapMpegts">Optional. The VTT timestamp map MPEGTS value.</param>
 212    /// <param name="startPositionTicks">The start position of the subtitle in ticks.</param>
 213    /// <response code="200">File returned.</response>
 214    /// <returns>A <see cref="FileContentResult"/> with the subtitle file.</returns>
 215    [HttpGet("Videos/{routeItemId}/{routeMediaSourceId}/Subtitles/{routeIndex}/Stream.{routeFormat}")]
 216    [ProducesResponseType(StatusCodes.Status200OK)]
 217    [ProducesFile("text/*")]
 218    public async Task<ActionResult> GetSubtitle(
 219        [FromRoute, Required] Guid routeItemId,
 220        [FromRoute, Required] string routeMediaSourceId,
 221        [FromRoute, Required] int routeIndex,
 222        [FromRoute, Required] string routeFormat,
 223        [FromQuery, ParameterObsolete] Guid? itemId,
 224        [FromQuery, ParameterObsolete] string? mediaSourceId,
 225        [FromQuery, ParameterObsolete] int? index,
 226        [FromQuery, ParameterObsolete] string? format,
 227        [FromQuery] long? endPositionTicks,
 228        [FromQuery] bool copyTimestamps = false,
 229        [FromQuery] bool addVttTimeMap = false,
 230        [FromQuery] long vttTimestampMapMpegts = DefaultVttTimestampMapMpegts,
 231        [FromQuery] long startPositionTicks = 0)
 232    {
 233        // Set parameters to route value if not provided via query.
 5234        itemId ??= routeItemId;
 5235        mediaSourceId ??= routeMediaSourceId;
 5236        index ??= routeIndex;
 5237        format ??= routeFormat;
 238
 5239        if (string.Equals(format, "js", StringComparison.OrdinalIgnoreCase))
 240        {
 0241            format = "json";
 242        }
 243
 244        // Graphical subtitles cannot be parsed or rewritten, so they are always delivered as the raw
 245        // stream for the client to render. Serve them straight from disk instead of piping them
 246        // through the encoder, so that range requests keep working: clients fetch these tracks
 247        // incrementally while rendering them, and they are far too large to hand over in one piece.
 5248        if (MediaStream.IsPgsFormat(format) || MediaStream.IsVobSubFormat(format))
 249        {
 4250            var subtitlePath = await GetGraphicalSubtitlePath(itemId.Value, mediaSourceId, index.Value).ConfigureAwait(f
 4251            if (!string.IsNullOrEmpty(subtitlePath))
 252            {
 2253                return PhysicalFile(subtitlePath, MimeTypes.GetMimeType(subtitlePath), true);
 254            }
 255        }
 256
 3257        if (string.Equals(format, "vtt", StringComparison.OrdinalIgnoreCase) && addVttTimeMap)
 258        {
 0259            Stream stream = await EncodeSubtitles(itemId.Value, mediaSourceId, index.Value, format, startPositionTicks, 
 0260            await using (stream.ConfigureAwait(false))
 261            {
 0262                using var reader = new StreamReader(stream);
 263
 0264                var text = await reader.ReadToEndAsync().ConfigureAwait(false);
 265
 0266                text = text.Replace("WEBVTT", "WEBVTT\n" + GetVttTimestampMap(vttTimestampMapMpegts), StringComparison.O
 267
 0268                return File(Encoding.UTF8.GetBytes(text), MimeTypes.GetMimeType("file." + format));
 269            }
 270        }
 271
 3272        return File(
 3273            await EncodeSubtitles(
 3274                itemId.Value,
 3275                mediaSourceId,
 3276                index.Value,
 3277                format,
 3278                startPositionTicks,
 3279                endPositionTicks,
 3280                copyTimestamps).ConfigureAwait(false),
 3281            MimeTypes.GetMimeType("file." + format));
 5282    }
 283
 284    /// <summary>
 285    /// Gets subtitles in a specified format.
 286    /// </summary>
 287    /// <param name="routeItemId">The (route) item id.</param>
 288    /// <param name="routeMediaSourceId">The (route) media source id.</param>
 289    /// <param name="routeIndex">The (route) subtitle stream index.</param>
 290    /// <param name="routeStartPositionTicks">The (route) start position of the subtitle in ticks.</param>
 291    /// <param name="routeFormat">The (route) format of the returned subtitle.</param>
 292    /// <param name="itemId">The item id.</param>
 293    /// <param name="mediaSourceId">The media source id.</param>
 294    /// <param name="index">The subtitle stream index.</param>
 295    /// <param name="startPositionTicks">The start position of the subtitle in ticks.</param>
 296    /// <param name="format">The format of the returned subtitle.</param>
 297    /// <param name="endPositionTicks">Optional. The end position of the subtitle in ticks.</param>
 298    /// <param name="copyTimestamps">Optional. Whether to copy the timestamps.</param>
 299    /// <param name="addVttTimeMap">Optional. Whether to add a VTT time map.</param>
 300    /// <param name="vttTimestampMapMpegts">Optional. The VTT timestamp map MPEGTS value.</param>
 301    /// <response code="200">File returned.</response>
 302    /// <returns>A <see cref="FileContentResult"/> with the subtitle file.</returns>
 303    [HttpGet("Videos/{routeItemId}/{routeMediaSourceId}/Subtitles/{routeIndex}/{routeStartPositionTicks}/Stream.{routeFo
 304    [ProducesResponseType(StatusCodes.Status200OK)]
 305    [ProducesFile("text/*")]
 306    public Task<ActionResult> GetSubtitleWithTicks(
 307        [FromRoute, Required] Guid routeItemId,
 308        [FromRoute, Required] string routeMediaSourceId,
 309        [FromRoute, Required] int routeIndex,
 310        [FromRoute, Required] long routeStartPositionTicks,
 311        [FromRoute, Required] string routeFormat,
 312        [FromQuery, ParameterObsolete] Guid? itemId,
 313        [FromQuery, ParameterObsolete] string? mediaSourceId,
 314        [FromQuery, ParameterObsolete] int? index,
 315        [FromQuery, ParameterObsolete] long? startPositionTicks,
 316        [FromQuery, ParameterObsolete] string? format,
 317        [FromQuery] long? endPositionTicks,
 318        [FromQuery] bool copyTimestamps = false,
 319        [FromQuery] bool addVttTimeMap = false,
 320        [FromQuery] long vttTimestampMapMpegts = DefaultVttTimestampMapMpegts)
 321    {
 0322        return GetSubtitle(
 0323            routeItemId,
 0324            routeMediaSourceId,
 0325            routeIndex,
 0326            routeFormat,
 0327            itemId,
 0328            mediaSourceId,
 0329            index,
 0330            format,
 0331            endPositionTicks,
 0332            copyTimestamps,
 0333            addVttTimeMap,
 0334            vttTimestampMapMpegts,
 0335            startPositionTicks ?? routeStartPositionTicks);
 336    }
 337
 338    /// <summary>
 339    /// Gets an HLS subtitle playlist.
 340    /// </summary>
 341    /// <param name="itemId">The item id.</param>
 342    /// <param name="index">The subtitle stream index.</param>
 343    /// <param name="mediaSourceId">The media source id.</param>
 344    /// <param name="segmentLength">The subtitle segment length.</param>
 345    /// <param name="vttTimestampMapMpegts">Optional. The VTT timestamp map MPEGTS value.</param>
 346    /// <response code="200">Subtitle playlist retrieved.</response>
 347    /// <response code="404">Item not found.</response>
 348    /// <returns>A <see cref="FileContentResult"/> with the HLS subtitle playlist.</returns>
 349    [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/subtitles.m3u8")]
 350    [Authorize]
 351    [ProducesResponseType(StatusCodes.Status200OK)]
 352    [ProducesResponseType(StatusCodes.Status404NotFound)]
 353    [ProducesPlaylistFile]
 354    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imp
 355    public async Task<ActionResult> GetSubtitlePlaylist(
 356        [FromRoute, Required] Guid itemId,
 357        [FromRoute, Required] int index,
 358        [FromRoute, Required] string mediaSourceId,
 359        [FromQuery, Required] int segmentLength,
 360        [FromQuery] long vttTimestampMapMpegts = DefaultVttTimestampMapMpegts)
 361    {
 0362        var item = _libraryManager.GetItemById<Video>(itemId, User.GetUserId());
 0363        if (item is null)
 364        {
 0365            return NotFound();
 366        }
 367
 0368        var mediaSource = await _mediaSourceManager.GetMediaSource(item, mediaSourceId, null, false, CancellationToken.N
 369
 0370        var runtime = mediaSource.RunTimeTicks ?? -1;
 371
 0372        if (runtime <= 0)
 373        {
 0374            throw new ArgumentException("HLS Subtitles are not supported for this media.");
 375        }
 376
 0377        var segmentLengthTicks = TimeSpan.FromSeconds(segmentLength).Ticks;
 0378        if (segmentLengthTicks <= 0)
 379        {
 0380            throw new ArgumentException("segmentLength was not given, or it was given incorrectly. (It should be bigger 
 381        }
 382
 0383        var builder = new StringBuilder();
 0384        builder.AppendLine("#EXTM3U")
 0385            .Append("#EXT-X-TARGETDURATION:")
 0386            .Append(segmentLength)
 0387            .AppendLine()
 0388            .AppendLine("#EXT-X-VERSION:3")
 0389            .AppendLine("#EXT-X-MEDIA-SEQUENCE:0")
 0390            .AppendLine("#EXT-X-PLAYLIST-TYPE:VOD");
 391
 0392        long positionTicks = 0;
 393
 0394        var accessToken = User.GetToken();
 395
 0396        while (positionTicks < runtime)
 397        {
 0398            var remaining = runtime - positionTicks;
 0399            var lengthTicks = Math.Min(remaining, segmentLengthTicks);
 400
 0401            builder.Append("#EXTINF:")
 0402                .Append(TimeSpan.FromTicks(lengthTicks).TotalSeconds)
 0403                .Append(',')
 0404                .AppendLine();
 405
 0406            var endPositionTicks = Math.Min(runtime, positionTicks + segmentLengthTicks);
 407
 0408            var url = GetSubtitleSegmentUrl(positionTicks, endPositionTicks, accessToken, vttTimestampMapMpegts);
 409
 0410            builder.AppendLine(url);
 411
 0412            positionTicks += segmentLengthTicks;
 413        }
 414
 0415        builder.AppendLine("#EXT-X-ENDLIST");
 0416        return File(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"));
 0417    }
 418
 419    /// <summary>
 420    /// Builds the WebVTT X-TIMESTAMP-MAP header for the given MPEGTS offset.
 421    /// </summary>
 422    /// <param name="mpegTimestamp">The MPEGTS offset to embed.</param>
 423    /// <returns>The X-TIMESTAMP-MAP header line.</returns>
 424    internal static string GetVttTimestampMap(long mpegTimestamp)
 425    {
 2426        return string.Format(
 2427            CultureInfo.InvariantCulture,
 2428            "X-TIMESTAMP-MAP=MPEGTS:{0},LOCAL:00:00:00.000",
 2429            mpegTimestamp);
 430    }
 431
 432    /// <summary>
 433    /// Builds the relative URL for a single WebVTT subtitle segment referenced from a subtitle HLS playlist.
 434    /// </summary>
 435    /// <param name="positionTicks">The segment start position, in ticks.</param>
 436    /// <param name="endPositionTicks">The segment end position, in ticks.</param>
 437    /// <param name="accessToken">The access token to include on the segment request.</param>
 438    /// <param name="vttTimestampMapMpegts">The MPEGTS offset to request for this segment.</param>
 439    /// <returns>The relative stream.vtt segment URL.</returns>
 440    internal static string GetSubtitleSegmentUrl(long positionTicks, long endPositionTicks, string? accessToken, long vt
 441    {
 2442        return string.Format(
 2443            CultureInfo.InvariantCulture,
 2444            "stream.vtt?CopyTimestamps=true&AddVttTimeMap=true&StartPositionTicks={0}&EndPositionTicks={1}&ApiKey={2}&Vt
 2445            positionTicks.ToString(CultureInfo.InvariantCulture),
 2446            endPositionTicks.ToString(CultureInfo.InvariantCulture),
 2447            accessToken,
 2448            vttTimestampMapMpegts.ToString(CultureInfo.InvariantCulture));
 449    }
 450
 451    /// <summary>
 452    /// Upload an external subtitle file.
 453    /// </summary>
 454    /// <param name="itemId">The item the subtitle belongs to.</param>
 455    /// <param name="body">The request body.</param>
 456    /// <response code="204">Subtitle uploaded.</response>
 457    /// <response code="404">Item not found.</response>
 458    /// <returns>A <see cref="NoContentResult"/>.</returns>
 459    [HttpPost("Videos/{itemId}/Subtitles")]
 460    [Authorize(Policy = Policies.SubtitleManagement)]
 461    [ProducesResponseType(StatusCodes.Status204NoContent)]
 462    [ProducesResponseType(StatusCodes.Status404NotFound)]
 463    public async Task<ActionResult> UploadSubtitle(
 464        [FromRoute, Required] Guid itemId,
 465        [FromBody, Required] UploadSubtitleDto body)
 466    {
 0467        var item = _libraryManager.GetItemById<Video>(itemId, User.GetUserId());
 0468        if (item is null)
 469        {
 0470            return NotFound();
 471        }
 472
 0473        var bytes = Encoding.UTF8.GetBytes(body.Data);
 0474        var memoryStream = new MemoryStream(bytes, 0, bytes.Length, false, true);
 0475        await using (memoryStream.ConfigureAwait(false))
 476        {
 0477            using var transform = new FromBase64Transform();
 0478            var stream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read);
 0479            await using (stream.ConfigureAwait(false))
 480            {
 0481                await _subtitleManager.UploadSubtitle(
 0482                    item,
 0483                    new SubtitleResponse
 0484                    {
 0485                        Format = body.Format,
 0486                        Language = body.Language,
 0487                        IsForced = body.IsForced,
 0488                        IsHearingImpaired = body.IsHearingImpaired,
 0489                        Stream = stream
 0490                    }).ConfigureAwait(false);
 0491                _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), Re
 492
 0493                return NoContent();
 494            }
 0495        }
 0496    }
 497
 498    private async Task<string?> GetGraphicalSubtitlePath(Guid id, string? mediaSourceId, int index)
 499    {
 4500        var item = _libraryManager.GetItemById<BaseItem>(id);
 4501        if (item is null)
 502        {
 0503            return null;
 504        }
 505
 4506        var idString = id.ToString("N", CultureInfo.InvariantCulture);
 4507        var mediaSource = _mediaSourceManager.GetStaticMediaSources(item, false)
 4508            .FirstOrDefault(i => string.Equals(i.Id, mediaSourceId ?? idString, StringComparison.OrdinalIgnoreCase));
 509
 4510        var subtitleStream = mediaSource?.MediaStreams
 4511            .FirstOrDefault(i => i.Type == MediaStreamType.Subtitle && i.Index == index);
 512
 4513        if (mediaSource is null || subtitleStream is null
 4514            || !(subtitleStream.IsPgsSubtitleStream || subtitleStream.IsVobSubSubtitleStream))
 515        {
 0516            return null;
 517        }
 518
 4519        var path = await _subtitleEncoder.GetSubtitleFilePath(subtitleStream, mediaSource, CancellationToken.None).Confi
 4520        if (string.IsNullOrEmpty(path))
 521        {
 0522            return null;
 523        }
 524
 525        // Only a raw PGS payload or an extracted .mks can be handed over untouched. Anything else the
 526        // encoder resolved to (e.g. a VobSub .idx/.sub pair, which it converts) is not a passthrough.
 4527        var extension = Path.GetExtension(path.AsSpan()).TrimStart('.').ToString();
 4528        if (!MediaStream.IsPgsFormat(extension)
 4529            && !string.Equals(extension, "mks", StringComparison.OrdinalIgnoreCase))
 530        {
 1531            return null;
 532        }
 533
 534        // Remotely hosted external subtitles have no local file to serve; those fall back to the encoder.
 3535        return _fileSystem.FileExists(path) ? path : null;
 4536    }
 537
 538    /// <summary>
 539    /// Encodes a subtitle in the specified format.
 540    /// </summary>
 541    /// <param name="id">The media id.</param>
 542    /// <param name="mediaSourceId">The source media id.</param>
 543    /// <param name="index">The subtitle index.</param>
 544    /// <param name="format">The format to convert to.</param>
 545    /// <param name="startPositionTicks">The start position in ticks.</param>
 546    /// <param name="endPositionTicks">The end position in ticks.</param>
 547    /// <param name="copyTimestamps">Whether to copy the timestamps.</param>
 548    /// <returns>A <see cref="Task{Stream}"/> with the new subtitle file.</returns>
 549    private Task<Stream> EncodeSubtitles(
 550        Guid id,
 551        string? mediaSourceId,
 552        int index,
 553        string format,
 554        long startPositionTicks,
 555        long? endPositionTicks,
 556        bool copyTimestamps)
 557    {
 3558        var item = _libraryManager.GetItemById<BaseItem>(id);
 559
 3560        return _subtitleEncoder.GetSubtitles(
 3561            item,
 3562            mediaSourceId,
 3563            index,
 3564            format,
 3565            startPositionTicks,
 3566            endPositionTicks ?? 0,
 3567            copyTimestamps,
 3568            CancellationToken.None);
 569    }
 570
 571    /// <summary>
 572    /// Gets a list of available fallback font files.
 573    /// </summary>
 574    /// <response code="200">Information retrieved.</response>
 575    /// <returns>An array of <see cref="FontFile"/> with the available font files.</returns>
 576    [HttpGet("FallbackFont/Fonts")]
 577    [Authorize]
 578    [ProducesResponseType(StatusCodes.Status200OK)]
 579    public IEnumerable<FontFile> GetFallbackFontList()
 580    {
 0581        var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
 0582        var fallbackFontPath = encodingOptions.FallbackFontPath;
 583
 0584        if (!string.IsNullOrEmpty(fallbackFontPath))
 585        {
 0586            var files = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false
 0587            var fontFiles = files
 0588                .Select(i => new FontFile
 0589                {
 0590                    Name = i.Name,
 0591                    Size = i.Length,
 0592                    DateCreated = _fileSystem.GetCreationTimeUtc(i),
 0593                    DateModified = _fileSystem.GetLastWriteTimeUtc(i)
 0594                })
 0595                .OrderBy(i => i.Size)
 0596                .ThenBy(i => i.Name)
 0597                .ThenByDescending(i => i.DateModified)
 0598                .ThenByDescending(i => i.DateCreated);
 599            // max total size 20M
 600            const int MaxSize = 20971520;
 0601            var sizeCounter = 0L;
 0602            foreach (var fontFile in fontFiles)
 603            {
 0604                sizeCounter += fontFile.Size;
 0605                if (sizeCounter >= MaxSize)
 606                {
 0607                    _logger.LogWarning("Some fonts will not be sent due to size limitations");
 0608                    yield break;
 609                }
 610
 0611                yield return fontFile;
 612            }
 613        }
 614        else
 615        {
 0616            _logger.LogWarning("The path of fallback font folder has not been set");
 0617            encodingOptions.EnableFallbackFont = false;
 618        }
 0619    }
 620
 621    /// <summary>
 622    /// Gets a fallback font file.
 623    /// </summary>
 624    /// <param name="name">The name of the fallback font file to get.</param>
 625    /// <response code="200">Fallback font file retrieved.</response>
 626    /// <returns>The fallback font file.</returns>
 627    [HttpGet("FallbackFont/Fonts/{name}")]
 628    [Authorize]
 629    [ProducesResponseType(StatusCodes.Status200OK)]
 630    [ProducesFile("font/*")]
 631    public ActionResult GetFallbackFont([FromRoute, Required] string name)
 632    {
 0633        var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
 0634        var fallbackFontPath = encodingOptions.FallbackFontPath;
 635
 0636        if (!string.IsNullOrEmpty(fallbackFontPath))
 637        {
 0638            var fontFile = _fileSystem.GetFiles(fallbackFontPath)
 0639                .FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
 0640            var fileSize = fontFile?.Length;
 641
 0642            if (fontFile is not null && fileSize is not null && fileSize > 0)
 643            {
 0644                _logger.LogDebug("Fallback font size is {FileSize} Bytes", fileSize);
 0645                return PhysicalFile(fontFile.FullName, MimeTypes.GetMimeType(fontFile.FullName));
 646            }
 647
 0648            _logger.LogWarning("The selected font is null or empty");
 649        }
 650        else
 651        {
 0652            _logger.LogWarning("The path of fallback font folder has not been set");
 0653            encodingOptions.EnableFallbackFont = false;
 654        }
 655
 656        // returning HTTP 204 will break the SubtitlesOctopus
 0657        return Ok();
 658    }
 659}