From 1aa427b1e2896852943a34986d8821e3f6f441d7 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 13 Oct 2026 20:14:12 +0300 Subject: [PATCH 01/77] Removes track path editing from the music track update flow Stops Track.UpdateDetails and Artist.UpdateTrackInAlbum from assigning a path, so a track path can be set only when the track is created. Removes Path from UpdateTrackRequest, UpdateTrackCommand, UpdateTrackCommandValidator and UpdateMusicTrackRequest, and removes the path containment check and IPathService dependency from UpdateTrackCommandHandler. The path stays visible in TrackResponse, MusicTrackDto and the read-only field of the track page. Updates the endpoint summary, request and API docs, and the affected tests. --- .../audio-library/music-library/Api.Tracks.md | 1 - .../music-library/tracks/UpdateTrack.http | 1 - .../Artists/UpdateArtistCommandMapping.cs | 1 - .../Tracks/AudioMetadataDtoMapping.cs | 1 - .../Tracks/UpdateTrackCommandMapping.cs | 1 - .../Tracks/UpdateTrackRequestMapping.cs | 1 - .../UpdateTrack/UpdateTrackCommand.cs | 2 - .../UpdateTrack/UpdateTrackCommandHandler.cs | 22 +------ .../UpdateTrackCommandValidator.cs | 6 -- .../MusicLibrary/Tracks/UpdateTrackRequest.cs | 2 - .../MusicLibraryAggregate/Artist.cs | 6 +- .../MusicLibraryAggregate/Entities/Track.cs | 9 +-- .../UpdateTrack/UpdateTrackEndpointSummary.cs | 9 +-- .../Tracks/UpdateMusicTrackRequest.cs | 2 - .../MusicLibrary/Tracks/Item.cshtml | 8 +-- .../UpdateTrack/UpdateTrackCommandFixture.cs | 5 -- .../Tracks/UpdateTrackRequestFixture.cs | 5 -- .../Tracks/UpdateMusicTrackRequestFixture.cs | 5 -- .../UpdateTrack/UpdateTrackEndpointTests.cs | 58 ++--------------- .../SaveMusicTrackEndpointTests.cs | 2 +- .../UpdateTrack/UpdateTrackEndpointTests.cs | 1 - .../UpdateArtistCommandMappingTests.cs | 9 ++- .../Tracks/UpdateTrackCommandMappingTests.cs | 14 ++-- .../Tracks/UpdateTrackRequestMappingTests.cs | 1 - .../UpdateTrackCommandHandlerTests.cs | 35 ++-------- .../UpdateTrackCommandValidatorTests.cs | 65 ------------------- .../MusicLibraryAggregate/ArtistTests.cs | 8 +-- .../Entities/TrackTests.cs | 9 ++- .../UpdateTrack/UpdateTrackEndpointTests.cs | 1 - 29 files changed, 47 insertions(+), 243 deletions(-) diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index 4cf0d71c..fa5e6b17 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -320,7 +320,6 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- ```json { - "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http index e8bd3ec3..8553d97a 100644 --- a/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http +++ b/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http @@ -3,7 +3,6 @@ Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json { - "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs index 076e5672..ebcc9b38 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs @@ -158,7 +158,6 @@ public static class UpdateArtistCommandMapping Result updateTrackResult = artist.UpdateTrackInAlbum( existingAlbum, existingTrack, - domainTrack.Path, domainTrack.Metadata, domainTrack.Disambiguation, domainTrack.TrackNumber, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs index 76393ef8..fdab831b 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs @@ -111,7 +111,6 @@ public static class AudioMetadataDtoMapping return artist.UpdateTrackInAlbum( album, track, - track.Path, metadataResult.Value, disambiguation, track.TrackNumber, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs index c7ff1519..ee882104 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs @@ -85,7 +85,6 @@ public static class UpdateTrackCommandMapping Result updateResult = artist.UpdateTrackInAlbum( album, track, - command.Path!, metadataResult.Value, Optional.FromNullable(metadata.Disambiguation), command.TrackNumber!.Value, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs index 257e2bf1..62d1d6da 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs @@ -26,7 +26,6 @@ public static class UpdateTrackRequestMapping artistId, albumId, trackId, - request.Path, request.Metadata, request.TrackNumber, request.DiscNumber, diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs index 9f5c15f0..6230619f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs @@ -19,7 +19,6 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks. /// The unique identifier of the artist this track belongs to, taken from the route. /// The unique identifier of the album this track belongs to, taken from the route. /// The unique identifier of the track, taken from the route. -/// The file system path of the track. /// The audio metadata of the track. /// The number of the track on its disc. /// The number of the disc the track belongs to, if applicable. @@ -39,7 +38,6 @@ public record UpdateTrackCommand( string? ArtistId, string? AlbumId, string? TrackId, - string? Path, MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs index bced0f6d..edf2a6ad 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs @@ -26,7 +26,6 @@ using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIden using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; @@ -48,7 +47,6 @@ public class UpdateTrackCommandHandler : ICommandHandler _validator; - private readonly IPathService _pathService; /// /// Initializes a new instance of the class. @@ -57,14 +55,12 @@ public class UpdateTrackCommandHandler : ICommandHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - /// Injected service for file system path related functionality. - public UpdateTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator, IPathService pathService) + public UpdateTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; - _pathService = pathService; } /// @@ -127,11 +123,6 @@ public class UpdateTrackCommandHandler : ICommandHandler> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); if (getContributorsResult.IsFailure) @@ -164,17 +155,6 @@ public class UpdateTrackCommandHandler : ICommandHandler - /// Determines whether the track path referenced by is stored inside one of the content locations of . - /// - /// The media library that owns the track. - /// The command carrying the referenced track. - /// when the referenced track path is within a content location of the library; otherwise, . - private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, UpdateTrackCommand command) - { - return library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path!, contentLocation.Path)); - } - /// /// Gets the media contributors referenced by , requiring each referenced Id to already exist. /// diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs index aee75a3e..04ae999c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs @@ -57,12 +57,6 @@ public class UpdateTrackCommandValidator : AbstractValidator .When(command => command.TrackId is not null && command.TrackId.Length > 0) .WithError(Errors.Music.TrackIdCannotBeEmpty); - RuleFor(command => command.Path) - .NotEmpty() - .WithError(Errors.Music.TrackPathCannotBeEmpty) - .MaximumLength(2048) - .WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); - // Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags. RuleFor(command => command.Metadata) .NotNull() diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs index 34cb73d8..c2e624ad 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs @@ -14,7 +14,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Track /// /// Represents a request to update an existing track. /// -/// The file system path of the track. Required. /// The audio metadata of the track. Required. /// The number of the track on its disc. Required. /// The number of the disc the track belongs to. Optional. @@ -30,7 +29,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Track /// The list of ratings for this track. Required. [DebuggerDisplay("Title: {Metadata.Title}")] public record UpdateTrackRequest( - string? Path, MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs index 5a5043f2..9fda2db6 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs @@ -638,11 +638,11 @@ public sealed class Artist : AggregateRoot /// /// A track is a child entity of the artist aggregate, not an aggregate root, so it is mutated through its owning artist, /// which is the consistency boundary. Book is itself an aggregate root, so its update flow reconstitutes it directly - /// with its own Create method instead. This difference is intentional. + /// with its own Create method instead. This difference is intentional. The file system path of the track is never updated + /// here: a track path is set only when the track is created by the scanner. /// /// The album the track belongs to. /// The track to update. - /// The file system path of the track. /// The audio metadata of the track. /// The optional disambiguation comment of the track. /// The number of the track on its disc. @@ -662,7 +662,6 @@ public sealed class Artist : AggregateRoot public Result UpdateTrackInAlbum( Album album, Track track, - string path, AudioMetadata metadata, Optional disambiguation, int trackNumber, @@ -686,7 +685,6 @@ public sealed class Artist : AggregateRoot return Errors.Music.TrackNotFound; track.UpdateDetails( - path, metadata, disambiguation, trackNumber, diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs index 0f3842a4..78703c91 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs @@ -343,9 +343,12 @@ public sealed class Track : Entity } /// - /// Updates the details of the track, without touching the moods, the ISRCs, the media contributors, and the ratings. + /// Updates the details of the track, without touching the file system path, the moods, the ISRCs, the media contributors, and the ratings. /// - /// The file system path of the track. + /// + /// The file system path is intentionally not editable here: it is set only when the track is created by the scanner, so that a client + /// can never point an existing track at an arbitrary file of the host. + /// /// The audio metadata of the track. /// The optional disambiguation comment of the track. /// The number of the track on its disc. @@ -359,7 +362,6 @@ public sealed class Track : Entity /// The optional MusicBrainz identifier of the track. /// An representing either a successful operation, or an error. internal Result UpdateDetails( - string path, AudioMetadata metadata, Optional disambiguation, int trackNumber, @@ -372,7 +374,6 @@ public sealed class Track : Entity Optional musicBrainzRecordingId, Optional musicBrainzTrackId) { - Path = path; Metadata = metadata; Disambiguation = disambiguation; TrackNumber = trackNumber; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs index e873a6d6..38595b03 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs @@ -31,7 +31,6 @@ public class UpdateTrackEndpointSummary : Summary r.Path, "The file system path of the track. Required."); RequestParam(r => r.Metadata, "The audio metadata of the track. Required."); RequestParam(r => r.Metadata!.Title, "The title of the track. Required."); RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the track. Optional."); @@ -397,7 +395,7 @@ public class UpdateTrackEndpointSummary : Summary /// Represents a request to update an existing track of an album of a music artist. /// -/// The file system path of the track. Required. /// The audio metadata of the track. Required. /// The number of the track on its disc. Required. /// The number of the disc the track belongs to. Optional. @@ -30,7 +29,6 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibr /// The list of ratings for this track. Required. [DebuggerDisplay("Title: {Metadata?.Title}")] public record UpdateMusicTrackRequest( - string? Path, MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.cshtml index 133310d4..976870a1 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.cshtml @@ -95,10 +95,10 @@

@_localizer["GeneralInformation"]

- +
-
:
-
+
@_localizer["TrackPath"]:
+
@(Model.Path ?? string.Empty)
@_localizer["TrackPathDescription"]
@@ -793,9 +793,9 @@ } // Builds the payload of the edited track, matching the update request of the API. + // The file system path is not included: a track path is set only by the scanner and can never be edited. function buildPayload() { return { - Path: readValue('track-path') || null, Metadata: { Title: readValue('track-title'), OriginalTitle: readValue('track-original-title') || null, diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs index 2638718d..db2e3fc2 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs @@ -39,7 +39,6 @@ public class UpdateTrackCommandFixture /// Optional. The Id of the artist the track belongs to. /// Optional. The Id of the album the track belongs to. /// Optional. The Id of the track to update. - /// Optional. The file system path of the track. /// Optional. The audio metadata of the track. /// Optional. The number of the track on its disc. /// Optional. The number of the disc the track belongs to. @@ -69,7 +68,6 @@ public class UpdateTrackCommandFixture /// Whether the artist Id should be included, or forced to . /// Whether the album Id should be included, or forced to . /// Whether the track Id should be included, or forced to . - /// Whether the path should be included, or forced to . /// Whether the track number should be included, or forced to . /// The created command to update a track. public UpdateTrackCommand Create( @@ -77,7 +75,6 @@ public class UpdateTrackCommandFixture string? artistId = null, string? albumId = null, string? trackId = null, - string? path = null, MusicTrackMetadataDto? metadata = null, int? trackNumber = null, int? discNumber = null, @@ -107,7 +104,6 @@ public class UpdateTrackCommandFixture bool includeArtistId = true, bool includeAlbumId = true, bool includeTrackId = true, - bool includePath = true, bool includeTrackNumber = true) { return new UpdateTrackCommand( @@ -115,7 +111,6 @@ public class UpdateTrackCommandFixture includeArtistId ? (artistId ?? _faker.Random.Guid().ToString()) : null, includeAlbumId ? (albumId ?? _faker.Random.Guid().ToString()) : null, includeTrackId ? (trackId ?? _faker.Random.Guid().ToString()) : null, - includePath ? (path ?? _faker.System.FilePath()) : null, includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null, includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 20)) : null, includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs index bdf7e052..a2f239ed 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs @@ -35,7 +35,6 @@ public class UpdateTrackRequestFixture /// /// Creates a random valid request to update a track. /// - /// Optional. The file system path of the track. /// Optional. The audio metadata of the track. /// Optional. The number of the track on its disc. /// Optional. The number of the disc the track belongs to. @@ -60,12 +59,10 @@ public class UpdateTrackRequestFixture /// Whether the ISRC codes should be included, or forced to . /// Whether the contributors list should be included, or forced to . /// Whether the ratings list should be included, or forced to . - /// Whether the path should be included, or forced to . /// Whether the metadata should be included, or forced to . /// Whether the track number should be included, or forced to . /// The created request to update a track. public UpdateTrackRequest Create( - string? path = null, MusicTrackMetadataDto? metadata = null, int? trackNumber = null, int? discNumber = null, @@ -90,12 +87,10 @@ public class UpdateTrackRequestFixture bool includeIsrcs = true, bool includeContributors = true, bool includeRatings = true, - bool includePath = true, bool includeMetadata = true, bool includeTrackNumber = true) { return new UpdateTrackRequest( - includePath ? (path ?? _faker.System.FilePath()) : null, includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null, includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 20)) : null, includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null, diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/UpdateMusicTrackRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/UpdateMusicTrackRequestFixture.cs index b34db133..3f17a46b 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/UpdateMusicTrackRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/UpdateMusicTrackRequestFixture.cs @@ -35,7 +35,6 @@ public class UpdateMusicTrackRequestFixture /// /// Creates a new instance with randomized test data. /// - /// Optional. The file system path of the track. /// Optional. The audio metadata of the track. /// Optional. The number of the track on its disc. /// Optional. The number of the disc the track belongs to. @@ -49,7 +48,6 @@ public class UpdateMusicTrackRequestFixture /// Optional. The ISRC codes of the track. /// Optional. The references to the media contributors that performed on the track. /// Optional. The ratings of the track. - /// Whether the path should be included, or forced to . /// Whether the metadata should be included, or forced to . /// Whether the track number should be included, or forced to . /// Whether the disc number should be included, or forced to . @@ -65,7 +63,6 @@ public class UpdateMusicTrackRequestFixture /// Whether the ratings should be included, or forced to . /// A configured instance. public UpdateMusicTrackRequest Create( - string? path = null, MusicTrackMetadataDto? metadata = null, int? trackNumber = null, int? discNumber = null, @@ -79,7 +76,6 @@ public class UpdateMusicTrackRequestFixture List? isrcs = null, List? contributors = null, List? ratings = null, - bool includePath = true, bool includeMetadata = true, bool includeTrackNumber = true, bool includeDiscNumber = true, @@ -95,7 +91,6 @@ public class UpdateMusicTrackRequestFixture bool includeRatings = true) { return new UpdateMusicTrackRequest( - Path: includePath ? (path ?? _faker.System.FilePath()) : null, Metadata: includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null, TrackNumber: includeTrackNumber ? (trackNumber ?? _faker.Random.Number(1, 30)) : null, DiscNumber: includeDiscNumber ? (discNumber ?? _faker.Random.Number(1, 4)) : null, diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs index c7f0ebc8..9a28581d 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs @@ -56,7 +56,6 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioL public class UpdateTrackEndpointTests : IClassFixture, IAsyncLifetime { private static readonly string s_contentRootPath = Path.Combine(Path.GetTempPath(), "lumina-update-track-tests"); - private static readonly string s_outsideContentRootPath = Path.Combine(Path.GetTempPath(), "lumina-update-track-outside"); private HttpClient _client; private readonly AuthenticatedLuminaApiFactory _apiFactory; @@ -115,10 +114,9 @@ public class UpdateTrackEndpointTests : IClassFixture(); TrackEntity storedTrack = dbContext.Tracks.Single(track => track.Id == trackId); Assert.Equal("Somebody to Love", storedTrack.Title); - Assert.Equal(updatedPath, storedTrack.Path); + Assert.Equal(originalPath, storedTrack.Path); } [Fact] @@ -160,7 +159,6 @@ public class UpdateTrackEndpointTests : IClassFixture link.Role == MediaContributorRole.Guitar); } - [Fact] - public async Task UpdateTrack_WhenPathIsNull_ShouldReturnUnprocessableEntity() - { - // Arrange - UpdateTrackRequest request = _updateTrackRequestFixture.Create(includePath: false); - - // Act - HttpResponseMessage response = await PutTrackAsync(request); - - // Assert - await AssertUnprocessableEntityWithValidationErrors(response, "TrackPathCannotBeEmpty"); - } - - [Fact] - public async Task UpdateTrack_WhenPathExceeds2048Characters_ShouldReturnUnprocessableEntity() - { - // Arrange - UpdateTrackRequest request = _updateTrackRequestFixture.Create(path: new Faker().Random.String2(2049)); - - // Act - HttpResponseMessage response = await PutTrackAsync(request); - - // Assert - await AssertUnprocessableEntityWithValidationErrors(response, "TrackPathMustBeMaximum2048CharactersLong"); - } - [Fact] public async Task UpdateTrack_WhenMetadataIsNull_ShouldReturnUnprocessableEntity() { @@ -1004,7 +958,7 @@ public class UpdateTrackEndpointTests : IClassFixture using JsonDocument json = JsonDocument.Parse(content); Assert.True(json.RootElement.GetProperty("success").GetBoolean()); Assert.Equal(trackId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" && putRequest.Data is UpdateMusicTrackRequest forwarded && forwarded.Metadata!.Title == request.Metadata!.Title && forwarded.Path == request.Path); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" && putRequest.Data is UpdateMusicTrackRequest forwarded && forwarded.Metadata!.Title == request.Metadata!.Title); } [Fact] diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs index eafa1ec8..a66b6385 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs @@ -94,7 +94,6 @@ public class UpdateTrackEndpointTests : IClassFixture, IDispos SeedLibrary(libraryId, userId); (Guid artistId, Guid albumId, Guid trackId) = SeedArtistGraph(libraryId); UpdateTrackRequest request = _updateTrackRequestFixture.Create( - path: Path.Combine(s_contentRootPath, $"injected-{Guid.NewGuid():N}.flac"), metadata: _musicTrackMetadataDtoFixture.Create(title: maliciousTitle), moods: [], isrcs: [], diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs index 4d78854a..a3463b17 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs @@ -44,8 +44,9 @@ public class UpdateArtistCommandMappingTests // Arrange Guid libraryId = Guid.NewGuid(); (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); - string updatedPath = "/music/queen/a-night-at-the-opera/03-you-re-my-best-friend.flac"; - AddTrackCommand trackCommand = _addTrackCommandFixture.Create(trackId: trackId, path: updatedPath, trackNumber: 7); + string originalPath = artist.Albums.SelectMany(album => album.Tracks).First(track => track.Id.Value == trackId).Path; + string attemptedPath = "/music/queen/a-night-at-the-opera/03-you-re-my-best-friend.flac"; + AddTrackCommand trackCommand = _addTrackCommandFixture.Create(trackId: trackId, path: attemptedPath, trackNumber: 7); AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [trackCommand]); UpdateArtistCommand command = _updateArtistCommandFixture.Create( libraryId: libraryId.ToString(), @@ -67,7 +68,9 @@ public class UpdateArtistCommandMappingTests Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId); Assert.Equal(albumCommand.Metadata!.Title, updatedAlbum.Metadata.Title); Track updatedTrack = updatedAlbum.Tracks.First(track => track.Id.Value == trackId); - Assert.Equal(updatedPath, updatedTrack.Path); + // the file system path of an existing track is never changed by the update, it is set only when the track is created + Assert.Equal(originalPath, updatedTrack.Path); + Assert.NotEqual(attemptedPath, updatedTrack.Path); Assert.Equal(7, updatedTrack.TrackNumber); Assert.True(updatedTrack.DiscNumber.HasValue); Assert.Equal(trackCommand.DiscNumber, updatedTrack.DiscNumber.Value); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs index f43c1870..5033efa8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs @@ -45,8 +45,8 @@ public class UpdateTrackCommandMappingTests // Arrange Guid libraryId = Guid.NewGuid(); (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); - string updatedPath = "/music/queen/a-night-at-the-opera/02-love-of-my-life.flac"; - UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), path: updatedPath); + string originalPath = artist.Albums.SelectMany(album => album.Tracks).First(track => track.Id.Value == trackId).Path; + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString()); // Act Result result = command.ToDomainEntity(artist); @@ -55,7 +55,8 @@ public class UpdateTrackCommandMappingTests Assert.False(result.IsFailure); Assert.Same(artist, result.Value); Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); - Assert.Equal(updatedPath, updatedTrack.Path); + // The file system path is never changed by the update, it is set only when the track is created. + Assert.Equal(originalPath, updatedTrack.Path); Assert.Equal(command.Metadata!.Title, updatedTrack.Metadata.Title); Assert.Equal(command.TrackNumber, updatedTrack.TrackNumber); Assert.True(updatedTrack.DiscNumber.HasValue); @@ -83,8 +84,8 @@ public class UpdateTrackCommandMappingTests // Arrange Guid libraryId = Guid.NewGuid(); (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); - string updatedPath = "/music/queen/a-night-at-the-opera/03-you-re-my-best-friend.flac"; - UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), path: updatedPath, includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false, contributors: [], ratings: []); + string originalPath = artist.Albums.SelectMany(album => album.Tracks).First(track => track.Id.Value == trackId).Path; + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false, contributors: [], ratings: []); // Act Result result = command.ToDomainEntity(artist); @@ -92,7 +93,8 @@ public class UpdateTrackCommandMappingTests // Assert Assert.False(result.IsFailure); Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); - Assert.Equal(updatedPath, updatedTrack.Path); + // the file system path is never changed by the update, it is set only when the track is created + Assert.Equal(originalPath, updatedTrack.Path); Assert.Equal(command.TrackNumber, updatedTrack.TrackNumber); Assert.False(updatedTrack.DiscNumber.HasValue); Assert.False(updatedTrack.Script.HasValue); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMappingTests.cs index c19f7f36..b4bc293c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMappingTests.cs @@ -38,7 +38,6 @@ public class UpdateTrackRequestMappingTests Assert.Equal(artistId.ToString(), result.ArtistId); Assert.Equal(albumId.ToString(), result.AlbumId); Assert.Equal(trackId.ToString(), result.TrackId); - Assert.Equal(request.Path, result.Path); Assert.Equal(request.Metadata, result.Metadata); Assert.Equal(request.TrackNumber, result.TrackNumber); Assert.Equal(request.DiscNumber, result.DiscNumber); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandlerTests.cs index a470115e..d8f9ed42 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandlerTests.cs @@ -26,7 +26,6 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using NSubstitute; using System; @@ -54,7 +53,6 @@ public class UpdateTrackCommandHandlerTests private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; - private readonly IPathService _mockPathService; private readonly UpdateTrackCommandHandler _sut; private readonly Guid _userId; private readonly UpdateTrackCommandFixture _updateTrackCommandFixture = new(); @@ -86,16 +84,14 @@ public class UpdateTrackCommandHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); - _mockPathService = Substitute.For(); _userId = Guid.NewGuid(); // Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes, - // the track path is within the library content locations, the artist is updated and the library and contributors exist. + // the artist is updated and the library and contributors exist. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); _mockValidator.Validate(Arg.Any()).Returns([]); - _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(true); _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -109,7 +105,7 @@ public class UpdateTrackCommandHandlerTests return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); }); - _sut = new UpdateTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); + _sut = new UpdateTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } [Fact] @@ -118,6 +114,7 @@ public class UpdateTrackCommandHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + string originalPath = existingArtist.Albums.SelectMany(album => album.Tracks).First(track => track.Id == trackId).Path; UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString()); ArtistEntity? updatedArtist = null; TrackEntity? updatedTrack = null; @@ -139,7 +136,8 @@ public class UpdateTrackCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(trackId, result.Value.Id); - Assert.Equal(command.Path, result.Value.Path); + // The file system path is preserved by the update, it is set only when the track is created. + Assert.Equal(originalPath, result.Value.Path); Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title); Assert.Equal(command.Contributors!.Count, result.Value.Contributors!.Count); await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); @@ -338,29 +336,6 @@ public class UpdateTrackCommandHandlerTests await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); } - [Fact] - public async Task HandleAsync_WhenPathIsNotWithinLibraryContentLocations_ShouldReturnPathError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); - UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString()); - _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From(existingArtist)); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(_ => Result.From(_libraryEntityFixture.Create(contentLocations: ["/music/queen"]))); - _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(false); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError); - _mockPathService.Received(1).IsPathWithin(command.Path!, Arg.Any()); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); - } - [Fact] public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidatorTests.cs index b0bfe69a..49c76aa2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidatorTests.cs @@ -353,71 +353,6 @@ public class UpdateTrackCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); } - [Fact] - public void Validate_WhenPathIsNull_ShouldHaveValidationError() - { - // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(includePath: false); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() - { - // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: string.Empty); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() - { - // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: " "); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPathExceeds2048Characters_ShouldHaveValidationError() - { - // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: new Faker().Random.String2(2049)); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); - } - - [Fact] - public void Validate_WhenPathIs2048Characters_ShouldNotHaveValidationError() - { - // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: new Faker().Random.String2(2048)); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); - } - [Fact] public void Validate_WhenMetadataIsNull_ShouldHaveValidationError() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs index 7b557286..02e0add9 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs @@ -661,7 +661,7 @@ public class ArtistTests Track track = _trackFixture.Create(); Album album = _albumFixture.Create(tracks: [track]); Artist artist = _artistFixture.Create(albums: [album]); - string path = "C:\\Music\\queen\\bohemian-rhapsody.flac"; + string originalPath = track.Path; AudioMetadata metadata = _audioMetadataFixture.Create(); Optional disambiguation = Optional.Some("remastered"); Optional discNumber = Optional.Some(1); @@ -681,7 +681,6 @@ public class ArtistTests Result result = artist.UpdateTrackInAlbum( album, track, - path, metadata, disambiguation, 11, @@ -700,7 +699,8 @@ public class ArtistTests // Assert Assert.False(result.IsFailure); - Assert.Equal(path, track.Path); + // The file system path is not part of the track update, it is set only when the track is created. + Assert.Equal(originalPath, track.Path); Assert.Equal(metadata, track.Metadata); Assert.Equal(disambiguation, track.Disambiguation); Assert.Equal(11, track.TrackNumber); @@ -735,7 +735,6 @@ public class ArtistTests Result result = artist.UpdateTrackInAlbum( foreignAlbum, track, - "C:\\Music\\queen\\bohemian-rhapsody.flac", _audioMetadataFixture.Create(), Optional.None(), 11, @@ -773,7 +772,6 @@ public class ArtistTests Result result = artist.UpdateTrackInAlbum( album, track, - "C:\\Music\\queen\\bohemian-rhapsody.flac", _audioMetadataFixture.Create(), Optional.None(), 11, diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs index a9413b05..1487b4b6 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs @@ -190,8 +190,8 @@ public class TrackTests { // Arrange Track track = _trackFixture.Create(); + string originalPath = track.Path; List originalMoods = [.. track.Moods]; - string path = "C:\\Music\\queen\\bohemian-rhapsody.flac"; AudioMetadata metadata = _audioMetadataFixture.Create(); Optional disambiguation = Optional.Some("remastered"); Optional discNumber = Optional.Some(2); @@ -206,7 +206,6 @@ public class TrackTests // Act Result result = track.UpdateDetails( - path, metadata, disambiguation, 7, @@ -221,7 +220,6 @@ public class TrackTests // Assert Assert.False(result.IsFailure); - Assert.Equal(path, track.Path); Assert.Equal(metadata, track.Metadata); Assert.Equal(disambiguation, track.Disambiguation); Assert.Equal(7, track.TrackNumber); @@ -235,7 +233,9 @@ public class TrackTests Assert.Equal(trackId, track.MusicBrainzTrackId); Assert.True(track.UpdatedOnUtc.HasValue); Assert.True(track.UpdatedOnUtc.Value >= beforeUpdate); - // the collections are not part of the details update + // The file system path is not part of the details update, it is set only when the track is created. + Assert.Equal(originalPath, track.Path); + // The collections are not part of the details update. Assert.Equal(originalMoods, track.Moods); } @@ -376,7 +376,6 @@ public class TrackTests // Act Result result = track.UpdateDetails( - "C:\\Music\\queen\\bohemian-rhapsody.flac", _audioMetadataFixture.Create(), Optional.None(), 11, diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs index 31623a6d..b52b6df2 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs @@ -158,7 +158,6 @@ public class UpdateTrackEndpointTests command.ArtistId == artistId.ToString() && command.AlbumId == albumId.ToString() && command.TrackId == trackId.ToString() && - command.Path == request.Path && command.Metadata == request.Metadata && command.TrackNumber == request.TrackNumber && command.DiscNumber == request.DiscNumber && From 4bcd37898c8baf487e4158da4c27cb6ea060c5da Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 13 Oct 2026 22:16:57 +0300 Subject: [PATCH 02/77] Renames the image MIME resolver and organizes the MIME resolvers Renames MimeTypes to ImageMimeTypes and moves it into Common/MimeTypes, updates the thumbnail endpoint and its tests, and aligns ThemeMimeTypes on the same frozen dictionary, initializer style and field naming. --- .../Core/Themes/ThemeMimeTypes.cs | 39 ++++++++++--------- .../ImageMimeTypes.cs} | 6 +-- .../GetThumbnail/GetThumbnailEndpoint.cs | 4 +- .../ImageMimeTypesTests.cs} | 12 +++--- .../Thumbnails/GetThumbnailEndpointTests.cs | 4 +- 5 files changed, 33 insertions(+), 32 deletions(-) rename src/Lumina.Presentation.Api/Common/{Utilities/MimeTypes.cs => MimeTypes/ImageMimeTypes.cs} (90%) rename tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/{Utilities/MimeTypesTests.cs => MimeTypes/ImageMimeTypesTests.cs} (79%) diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs index 12b00303..7ea04b74 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using System; +using System.Collections.Frozen; using System.Collections.Generic; using System.IO; #endregion @@ -11,25 +12,25 @@ namespace Lumina.Infrastructure.Core.Themes; /// internal static class ThemeMimeTypes { - private static readonly Dictionary s_mimeByExtension = new(StringComparer.OrdinalIgnoreCase) + private static readonly FrozenDictionary s_fileExtensionToMimeType = new Dictionary { - [".htm"] = "text/html", - [".html"] = "text/html", - [".css"] = "text/css", - [".js"] = "application/javascript", - [".json"] = "application/json", - [".png"] = "image/png", - [".jpg"] = "image/jpeg", - [".jpeg"] = "image/jpeg", - [".gif"] = "image/gif", - [".webp"] = "image/webp", - [".svg"] = "image/svg+xml", - [".ico"] = "image/x-icon", - [".woff"] = "font/woff", - [".woff2"] = "font/woff2", - [".ttf"] = "font/ttf", - [".txt"] = "text/plain" - }; + { ".htm", "text/html" }, + { ".html", "text/html" }, + { ".css", "text/css" }, + { ".js", "application/javascript" }, + { ".json", "application/json" }, + { ".png", "image/png" }, + { ".jpg", "image/jpeg" }, + { ".jpeg", "image/jpeg" }, + { ".gif", "image/gif" }, + { ".webp", "image/webp" }, + { ".svg", "image/svg+xml" }, + { ".ico", "image/x-icon" }, + { ".woff", "font/woff" }, + { ".woff2", "font/woff2" }, + { ".ttf", "font/ttf" }, + { ".txt", "text/plain" } + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); /// /// Gets the MIME content type of a file based on its extension. @@ -38,6 +39,6 @@ internal static class ThemeMimeTypes /// The MIME content type, or application/octet-stream when the extension is unknown. public static string GetMimeType(string filePath) { - return s_mimeByExtension.TryGetValue(Path.GetExtension(filePath), out string? mimeType) ? mimeType : "application/octet-stream"; + return s_fileExtensionToMimeType.TryGetValue(Path.GetExtension(filePath), out string? mimeType) ? mimeType : "application/octet-stream"; } } diff --git a/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs b/src/Lumina.Presentation.Api/Common/MimeTypes/ImageMimeTypes.cs similarity index 90% rename from src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs rename to src/Lumina.Presentation.Api/Common/MimeTypes/ImageMimeTypes.cs index c68cee65..af1205a5 100644 --- a/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs +++ b/src/Lumina.Presentation.Api/Common/MimeTypes/ImageMimeTypes.cs @@ -4,12 +4,12 @@ using System.Collections.Frozen; using System.Collections.Generic; #endregion -namespace Lumina.Presentation.Api.Common.Utilities; +namespace Lumina.Presentation.Api.Common.MimeTypes; /// -/// Utility class for converting from domain image types to known image mime types. +/// Resolves the MIME content type of image types. /// -public static class MimeTypes +public static class ImageMimeTypes { private static readonly FrozenDictionary s_imageTypeToMimeType = new Dictionary { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs index 91e37b15..4940e42d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs @@ -7,8 +7,8 @@ using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbna using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.MimeTypes; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; -using Lumina.Presentation.Api.Common.Utilities; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; using System.Threading; @@ -52,6 +52,6 @@ public class GetThumbnailEndpoint : BaseEndpoint public override async Task ExecuteAsync(GetThumbnailRequest request, CancellationToken cancellationToken) { Result result = await _getThumbnailQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.File(success.Bytes, MimeTypes.GetMimeType(success.Type)), Problem); + return result.Match(success => TypedResults.File(success.Bytes, ImageMimeTypes.GetMimeType(success.Type)), Problem); } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Utilities/MimeTypesTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/ImageMimeTypesTests.cs similarity index 79% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Utilities/MimeTypesTests.cs rename to tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/ImageMimeTypesTests.cs index 50ad9587..7764d573 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Utilities/MimeTypesTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/ImageMimeTypesTests.cs @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Presentation.Api.Common.Utilities; +using Lumina.Presentation.Api.Common.MimeTypes; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Presentation.Api.UnitTests.Common.Utilities; +namespace Lumina.Presentation.Api.UnitTests.Common.MimeTypes; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class MimeTypesTests +public class ImageMimeTypesTests { [Theory] [InlineData(ImageType.BMP, "image/bmp")] // bmp image type @@ -21,7 +21,7 @@ public class MimeTypesTests public void GetMimeType_WhenTypeIsKnown_ShouldReturnTheMappedMimeType(ImageType type, string expectedMimeType) { // Act - string result = MimeTypes.GetMimeType(type); + string result = ImageMimeTypes.GetMimeType(type); // Assert Assert.Equal(expectedMimeType, result); @@ -33,7 +33,7 @@ public class MimeTypesTests public void GetMimeType_WhenTypeIsUnknown_ShouldReturnOpaqueBinaryMimeType(ImageType type) { // Act - string result = MimeTypes.GetMimeType(type); + string result = ImageMimeTypes.GetMimeType(type); // Assert Assert.Equal("application/octet-stream", result); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs index ae8a0b8d..c6cdb624 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -7,7 +7,7 @@ using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Thumbnails; using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Utilities; +using Lumina.Presentation.Api.Common.MimeTypes; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -56,7 +56,7 @@ public class GetThumbnailEndpointTests // Assert FileContentHttpResult fileResult = Assert.IsType(result); Assert.Equal(expectedResponse.Bytes, fileResult.FileContents.ToArray()); - Assert.Equal(MimeTypes.GetMimeType(expectedResponse.Type), fileResult.ContentType); + Assert.Equal(ImageMimeTypes.GetMimeType(expectedResponse.Type), fileResult.ContentType); } [Fact] From eecf4315c6be39f921c54f1ff8957acb16922e80 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 13 Oct 2026 22:17:32 +0300 Subject: [PATCH 03/77] Adds an audio file format enumeration and music MIME resolution Introduces AudioFileFormat in the shared kernel, resolves it from a file path in AudioFileFormatUtilities, and maps it to a MIME content type in MusicMimeTypes, mirroring the image MIME resolver. --- .../Utilities/AudioFileFormatUtilities.cs | 40 +++++++++ .../Enums/AudioLibrary/AudioFileFormat.cs | 82 +++++++++++++++++++ .../Common/MimeTypes/MusicMimeTypes.cs | 41 ++++++++++ .../AudioFileFormatUtilitiesTests.cs | 78 ++++++++++++++++++ .../AudioLibrary/AudioFileFormatTests.cs | 25 ++++++ .../Common/MimeTypes/MusicMimeTypesTests.cs | 48 +++++++++++ 6 files changed, 314 insertions(+) create mode 100644 src/Lumina.Application/Common/Utilities/AudioFileFormatUtilities.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/AudioFileFormat.cs create mode 100644 src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/AudioFileFormatUtilitiesTests.cs create mode 100644 tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioFileFormatTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/MusicMimeTypesTests.cs diff --git a/src/Lumina.Application/Common/Utilities/AudioFileFormatUtilities.cs b/src/Lumina.Application/Common/Utilities/AudioFileFormatUtilities.cs new file mode 100644 index 00000000..242edcf5 --- /dev/null +++ b/src/Lumina.Application/Common/Utilities/AudioFileFormatUtilities.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.IO; +#endregion + +namespace Lumina.Application.Common.Utilities; + +/// +/// Provides helpers for the enumeration. +/// +public static class AudioFileFormatUtilities +{ + /// + /// Gets the audio file format of the file stored at the provided , derived from its file extension. + /// + /// The path of the audio file whose file format is resolved. + /// The audio file format of the file, or when the extension is not a recognized audio extension. + public static AudioFileFormat ToAudioFileFormat(this string filePath) + { + return Path.GetExtension(filePath).ToLowerInvariant() switch + { + ".mp3" => AudioFileFormat.MP3, + ".flac" => AudioFileFormat.FLAC, + ".m4a" => AudioFileFormat.M4A, + ".aac" => AudioFileFormat.AAC, + ".ogg" => AudioFileFormat.OGG, + ".opus" => AudioFileFormat.OPUS, + ".wav" => AudioFileFormat.WAV, + ".wma" => AudioFileFormat.WMA, + ".aiff" or ".aif" => AudioFileFormat.AIFF, + ".ape" => AudioFileFormat.APE, + ".wv" => AudioFileFormat.WAVPACK, + ".dsf" => AudioFileFormat.DSF, + ".dff" => AudioFileFormat.DFF, + ".mka" => AudioFileFormat.MATROSKA, + _ => AudioFileFormat.None + }; + } +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/AudioFileFormat.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/AudioFileFormat.cs new file mode 100644 index 00000000..4e9a121c --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/AudioFileFormat.cs @@ -0,0 +1,82 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the file formats of audio files. +/// +public enum AudioFileFormat +{ + /// + /// No audio file format specified. + /// + None, + + /// + /// MPEG-1 Audio Layer III. + /// + MP3, + + /// + /// Free Lossless Audio Codec. + /// + FLAC, + + /// + /// MPEG-4 Part 14 audio. + /// + M4A, + + /// + /// Advanced Audio Coding. + /// + AAC, + + /// + /// The Ogg container format. + /// + OGG, + + /// + /// Opus. + /// + OPUS, + + /// + /// Waveform Audio File Format. + /// + WAV, + + /// + /// Windows Media Audio. + /// + WMA, + + /// + /// Audio Interchange File Format. + /// + AIFF, + + /// + /// Monkey's Audio. + /// + APE, + + /// + /// WavPack. + /// + WAVPACK, + + /// + /// Direct Stream Digital. + /// + DSF, + + /// + /// Direct Stream Digital Interchange File Format. + /// + DFF, + + /// + /// Matroska audio. + /// + MATROSKA, +} diff --git a/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs b/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs new file mode 100644 index 00000000..1102517f --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Collections.Frozen; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Common.MimeTypes; + +/// +/// Resolves the MIME content type of audio file formats. +/// +public static class MusicMimeTypes +{ + private static readonly FrozenDictionary s_audioFileFormatToMimeType = new Dictionary + { + { AudioFileFormat.MP3, "audio/mpeg" }, + { AudioFileFormat.FLAC, "audio/flac" }, + { AudioFileFormat.M4A, "audio/mp4" }, + { AudioFileFormat.AAC, "audio/aac" }, + { AudioFileFormat.OGG, "audio/ogg" }, + { AudioFileFormat.OPUS, "audio/ogg" }, + { AudioFileFormat.WAV, "audio/wav" }, + { AudioFileFormat.WMA, "audio/x-ms-wma" }, + { AudioFileFormat.AIFF, "audio/aiff" }, + { AudioFileFormat.APE, "audio/x-ape" }, + { AudioFileFormat.WAVPACK, "audio/x-wavpack" }, + { AudioFileFormat.DSF, "audio/x-dsf" }, + { AudioFileFormat.DFF, "audio/x-dff" }, + { AudioFileFormat.MATROSKA, "audio/x-matroska" } + }.ToFrozenDictionary(); + + /// + /// Gets the MIME content type of . + /// + /// The audio file format for which to get the MIME content type. + /// The MIME content type of , or application/octet-stream when the format is unknown. + public static string GetMimeType(AudioFileFormat format) + { + return s_audioFileFormatToMimeType.TryGetValue(format, out string? mimeType) ? mimeType : "application/octet-stream"; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/AudioFileFormatUtilitiesTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/AudioFileFormatUtilitiesTests.cs new file mode 100644 index 00000000..37ef8412 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/AudioFileFormatUtilitiesTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Utilities; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Utilities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AudioFileFormatUtilitiesTests +{ + [Theory] + [InlineData("track.mp3", AudioFileFormat.MP3)] // mp3 audio file + [InlineData("track.flac", AudioFileFormat.FLAC)] // flac audio file + [InlineData("track.m4a", AudioFileFormat.M4A)] // m4a audio file + [InlineData("track.aac", AudioFileFormat.AAC)] // aac audio file + [InlineData("track.ogg", AudioFileFormat.OGG)] // ogg audio file + [InlineData("track.opus", AudioFileFormat.OPUS)] // opus audio file + [InlineData("track.wav", AudioFileFormat.WAV)] // wav audio file + [InlineData("track.wma", AudioFileFormat.WMA)] // wma audio file + [InlineData("track.aiff", AudioFileFormat.AIFF)] // aiff audio file + [InlineData("track.aif", AudioFileFormat.AIFF)] // aif audio file + [InlineData("track.ape", AudioFileFormat.APE)] // ape audio file + [InlineData("track.wv", AudioFileFormat.WAVPACK)] // wavpack audio file + [InlineData("track.dsf", AudioFileFormat.DSF)] // dsf audio file + [InlineData("track.dff", AudioFileFormat.DFF)] // dff audio file + [InlineData("track.mka", AudioFileFormat.MATROSKA)] // matroska audio file + public void ToAudioFileFormat_WhenExtensionIsKnown_ShouldReturnMappedFormat(string filePath, AudioFileFormat expectedFormat) + { + // Act + AudioFileFormat result = filePath.ToAudioFileFormat(); + + // Assert + Assert.Equal(expectedFormat, result); + } + + [Fact] + public void ToAudioFileFormat_WhenExtensionIsUnknown_ShouldReturnNone() + { + // Arrange + string filePath = "track.unknown"; + + // Act + AudioFileFormat result = filePath.ToAudioFileFormat(); + + // Assert + Assert.Equal(AudioFileFormat.None, result); + } + + [Fact] + public void ToAudioFileFormat_WhenFileHasNoExtension_ShouldReturnNone() + { + // Arrange + string filePath = "track"; + + // Act + AudioFileFormat result = filePath.ToAudioFileFormat(); + + // Assert + Assert.Equal(AudioFileFormat.None, result); + } + + [Fact] + public void ToAudioFileFormat_WhenExtensionIsMixedCase_ShouldResolveCaseInsensitively() + { + // Arrange + string filePath = "Track.MP3"; + + // Act + AudioFileFormat result = filePath.ToAudioFileFormat(); + + // Assert + Assert.Equal(AudioFileFormat.MP3, result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioFileFormatTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioFileFormatTests.cs new file mode 100644 index 00000000..388b354f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioFileFormatTests.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.AudioLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class AudioFileFormatTests +{ + [Fact] + public void AudioFileFormat_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + AudioFileFormat[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/MusicMimeTypesTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/MusicMimeTypesTests.cs new file mode 100644 index 00000000..c357f6a0 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/MusicMimeTypesTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Presentation.Api.Common.MimeTypes; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Common.MimeTypes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMimeTypesTests +{ + [Theory] + [InlineData(AudioFileFormat.MP3, "audio/mpeg")] // mp3 audio format + [InlineData(AudioFileFormat.FLAC, "audio/flac")] // flac audio format + [InlineData(AudioFileFormat.M4A, "audio/mp4")] // m4a audio format + [InlineData(AudioFileFormat.AAC, "audio/aac")] // aac audio format + [InlineData(AudioFileFormat.OGG, "audio/ogg")] // ogg audio format + [InlineData(AudioFileFormat.OPUS, "audio/ogg")] // opus audio format + [InlineData(AudioFileFormat.WAV, "audio/wav")] // wav audio format + [InlineData(AudioFileFormat.WMA, "audio/x-ms-wma")] // wma audio format + [InlineData(AudioFileFormat.AIFF, "audio/aiff")] // aiff audio format + [InlineData(AudioFileFormat.APE, "audio/x-ape")] // ape audio format + [InlineData(AudioFileFormat.WAVPACK, "audio/x-wavpack")] // wavpack audio format + [InlineData(AudioFileFormat.DSF, "audio/x-dsf")] // dsf audio format + [InlineData(AudioFileFormat.DFF, "audio/x-dff")] // dff audio format + [InlineData(AudioFileFormat.MATROSKA, "audio/x-matroska")] // matroska audio format + public void GetMimeType_WhenFormatIsKnown_ShouldReturnMappedMimeType(AudioFileFormat format, string expectedMimeType) + { + // Act + string result = MusicMimeTypes.GetMimeType(format); + + // Assert + Assert.Equal(expectedMimeType, result); + } + + [Fact] + public void GetMimeType_WhenFormatIsNone_ShouldReturnOpaqueBinaryMimeType() + { + // Act + string result = MusicMimeTypes.GetMimeType(AudioFileFormat.None); + + // Assert + Assert.Equal("application/octet-stream", result); + } +} From 0ad6e1307bb9d855ced2915d7dd81a9e2636d2f0 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 13 Oct 2026 22:17:46 +0300 Subject: [PATCH 04/77] Names the rate limiting policies with constants Replaces the literal authentication rate limiting policy name with a constant on PresentationApiLayerServices, adds the track stream policy constant next to it, and uses both from the endpoints that register them. --- .../PresentationApiLayerServices.cs | 20 ++++++++++++++++++- .../Authentication/Login/LoginEndpoint.cs | 3 ++- .../RecoverPasswordEndpoint.cs | 3 ++- .../Register/RegisterEndpoint.cs | 3 ++- 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index b5a4de98..7a8823db 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -17,6 +17,7 @@ using Microsoft.IdentityModel.Tokens; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Security.Claims; using System.Text; using System.Text.Json.Serialization; using System.Threading.RateLimiting; @@ -31,6 +32,9 @@ namespace Lumina.Presentation.Api.Common.DependencyInjection; [ExcludeFromCodeCoverage] public static class PresentationApiLayerServices { + public const string AUTHENTICATION_RATE_LIMIT_POLICY = "authenticationPolicy"; + public const string TRACK_STREAM_RATE_LIMIT_POLICY = "trackStreamPolicy"; + /// /// Registers the services of the Presentation Api layer into the Dependency Injection container. /// @@ -94,7 +98,7 @@ public static class PresentationApiLayerServices await onRejectedContext.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken); }; - rateLimiterOptions.AddPolicy("authenticationPolicy", httpContext => + rateLimiterOptions.AddPolicy(AUTHENTICATION_RATE_LIMIT_POLICY, httpContext => { string clientIp = httpContext.Request.Headers["X-Forwarded-For"] // First check forwarded headers, in case this is behind a reverse proxy. .FirstOrDefault()?.Split(',')[0].Trim() // Take first IP, if multiple available, to avoid IP spoofing attempts, @@ -110,6 +114,20 @@ public static class PresentationApiLayerServices AutoReplenishment = true // Automatically reset rate limiter tokens. }); }); + rateLimiterOptions.AddPolicy(TRACK_STREAM_RATE_LIMIT_POLICY, httpContext => + { + // The track stream is limited per user, so that a single user cannot hold an unbounded number of long lived audio streams open at once. + // This is deliberately not the login policy: it is a concurrency limit, partitioned per authenticated user, not a per IP attempt window. + string userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous"; + return RateLimitPartition.GetConcurrencyLimiter( + partitionKey: $"trackStream_{userId}", + factory: _ => new ConcurrencyLimiterOptions + { + PermitLimit = 4, // Allow 4 concurrent audio streams per user. + QueueLimit = 0, // Don't queue requests, a request beyond the limit is rejected instead of waiting. + QueueProcessingOrder = QueueProcessingOrder.OldestFirst + }); + }); }); // Add authentication and specify the JWT scheme to check tokens against. diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs index d3bd7ea2..e6f568d1 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs @@ -6,6 +6,7 @@ using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; @@ -42,7 +43,7 @@ public class LoginEndpoint : BaseEndpoint Version(1); AllowAnonymous(); DontCatchExceptions(); - Options(x => x.RequireRateLimiting("authenticationPolicy")); + Options(x => x.RequireRateLimiting(PresentationApiLayerServices.AUTHENTICATION_RATE_LIMIT_POLICY)); } /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs index 2077b918..f83a6b69 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs @@ -5,6 +5,7 @@ using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPas using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; @@ -41,7 +42,7 @@ public class RecoverPasswordEndpoint : BaseEndpoint x.RequireRateLimiting("authenticationPolicy")); + Options(x => x.RequireRateLimiting(PresentationApiLayerServices.AUTHENTICATION_RATE_LIMIT_POLICY)); } /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs index 0af9ce38..d74178f9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs @@ -5,6 +5,7 @@ using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUs using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; @@ -41,7 +42,7 @@ public class RegisterEndpoint : BaseEndpoint Version(1); AllowAnonymous(); DontCatchExceptions(); - Options(x => x.RequireRateLimiting("authenticationPolicy")); + Options(x => x.RequireRateLimiting(PresentationApiLayerServices.AUTHENTICATION_RATE_LIMIT_POLICY)); } /// From 4ffa81fffefd8436c5c5e114d80bcb9c76fbbf11 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 13 Oct 2026 22:18:36 +0300 Subject: [PATCH 05/77] Adds the music track stream endpoint Adds the track stream route, its query, validator and handler, a flat stream projection in the track repository, and an endpoint that streams the audio file with HTTP range support. Excludes the route from the eventual consistency pipeline through endpoint metadata and limits it per user with a concurrency limiter. Missing, unreadable and out of scope files are reported as not found without leaking the path. Adds the API and request documentation and the stream tests. --- .../audio-library/music-library/Api.Tracks.md | 32 ++ .../music-library/tracks/StreamTrack.http | 3 + .../MusicLibrary/Tracks/TrackStreamDto.cs | 61 ++++ .../MusicLibrary/ITrackRepository.cs | 16 + .../GetTrackStream/GetTrackStreamQuery.cs | 21 ++ .../GetTrackStreamQueryHandler.cs | 124 +++++++ .../GetTrackStreamQueryValidator.cs | 60 ++++ .../MusicLibrary/Tracks/TrackStreamDataDto.cs | 22 ++ .../MusicLibrary/TrackRepository.cs | 37 +++ .../Common/Errors/Errors.Music.cs | 1 + .../Http/SkipEventualConsistencyMetadata.cs | 8 + .../EventualConsistencyMiddleware.cs | 9 + .../MusicLibrary/ApiRoutes.Tracks.cs | 1 + .../GetTrackStream/GetTrackStreamEndpoint.cs | 86 +++++ .../GetTrackStreamEndpointSummary.cs | 138 ++++++++ src/Lumina.sln | 1 + .../GetTrackStreamEndpointTests.cs | 310 ++++++++++++++++++ .../EventualConsistencyMiddlewareTests.cs | 55 ++++ 18 files changed, 985 insertions(+) create mode 100644 docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs create mode 100644 src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index fa5e6b17..929ab62b 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -8,6 +8,9 @@ - [Get Track](#get-track) - [Get Track Request](#get-track-request) - [Get Track Response](#get-track-response) + - [Stream Track](#stream-track) + - [Stream Track Request](#stream-track-request) + - [Stream Track Response](#stream-track-response) - [Update Track](#update-track) - [Update Track Request](#update-track-request) - [Update Track Response](#update-track-response) @@ -310,6 +313,35 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- ``` +### Stream Track + +#### Stream Track Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream +Authorization: Bearer +Range: bytes=0-1048575 +``` + +Streams the audio file of the track identified by the route, with HTTP range support. The `Range` header is optional: without it the whole file is streamed, and with it only the requested range is streamed, so that a player can start playback before the whole file is downloaded and can seek within the file. The audio file is streamed to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track. + +#### Stream Track Response + +```js +200 Ok +``` + +or, when a range is requested: + +```js +206 Partial Content +Content-Range: bytes 0-1048575/3542771 +Accept-Ranges: bytes +``` + +The response is the raw bytes of the audio file, served with the media type of the file when it is an audio type, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private` and `Vary: Authorization`, together with a `Last-Modified` and an `ETag` derived from the size and the modification time of the file. + + ### Update Track #### Update Track Request diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http new file mode 100644 index 00000000..bd5cf3df --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http @@ -0,0 +1,3 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}/stream +Authorization: Bearer {{ACCESS_TOKEN}} +Range: bytes=0-1048575 diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs new file mode 100644 index 00000000..3ecc0f97 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for a track, containing the data needed to stream, or to describe the streaming of, its audio file. +/// +public sealed record TrackStreamDto +{ + /// + /// Gets the file system path of the track. + /// + public required string Path { get; init; } + + /// + /// Gets the Id of the media library the track belongs to. + /// + public required Guid LibraryId { get; init; } + + /// + /// Gets the Id of the album the track belongs to. + /// + public required Guid AlbumId { get; init; } + + /// + /// Gets the Id of the artist that owns the album the track belongs to. + /// + public required Guid ArtistId { get; init; } + + /// + /// Gets the audio codec used by the audio file of the track, if applicable. + /// + public string? AudioCodec { get; init; } + + /// + /// Gets the duration of the audio of the track in seconds. + /// + public int DurationInSeconds { get; init; } + + /// + /// Gets the sample rate of the audio of the track in Hz. + /// + public int SampleRate { get; init; } + + /// + /// Gets the number of audio channels of the track. + /// + public int Channels { get; init; } + + /// + /// Gets the bit depth of the audio of the track, if applicable. + /// + public int? BitDepth { get; init; } + + /// + /// Gets the bitrate of the audio of the track in kbps, if applicable. + /// + public int? Bitrate { get; init; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs index 72f1b185..5a1eda26 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs @@ -58,6 +58,22 @@ public interface ITrackRepository : IRepository, /// An containing either the stored at the provided path, or an error. Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken); + /// + /// Gets the data needed to stream the audio file of the track identified by , when it belongs to the album identified by + /// and to the media library identified by , and that album belongs to the artist identified by + /// . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose streaming data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track matches the + /// provided identifiers, or an error. + /// + Task> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken); + /// /// Resets the enrichment state of the tracks stored at the provided in the media library identified by /// , together with their albums and artists, so that they are re-enriched, because their content changed since the last scan. diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs new file mode 100644 index 00000000..6f6f2506 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; + +/// +/// Query for getting the audio file of a track, for streaming. +/// +/// The unique identifier of the media library the track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track whose audio file is streamed, taken from the route. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetTrackStreamQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs new file mode 100644 index 00000000..d5c56f6c --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; + +/// +/// Handler for the query to get the audio file of a track, for streaming. +/// +public class GetTrackStreamQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IPathService _pathService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for file system path related functionality. + /// Injected validator for application validation rules. + public GetTrackStreamQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _pathService = pathService; + _validator = validator; + } + + /// + /// Handles the query to get the audio file of a track, for streaming. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the data of the audio file of the track, or an error message. + /// + public async Task> HandleAsync(GetTrackStreamQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + + // Admins can stream the tracks of all libraries; for everyone else, only the tracks of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The projection is filtered by the library, the album and the artist named by the route as well as by the track, so a null row + // means the track either does not exist or is not in scope for the route, which is reported as not found without disclosing anything further. + Result getTrackResult = await _unitOfWork.TrackRepository.GetTrackStreamInfoAsync(libraryId, albumId, artistId, trackId, cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + return Errors.Music.TrackNotFound; + TrackStreamDto track = getTrackResult.Value; + + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(track.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return Errors.Library.LibraryNotFound; + LibraryEntity library = getLibraryResult.Value; + + // The audio file is only served when it is stored inside one of the content locations of its library, so that a stored path can never + // be used to read an arbitrary file of the host; the failure is reported as not found, and it never includes the path. + if (!library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(track.Path, contentLocation.Path))) + return Errors.Music.TrackFileNotFound; + + try + { + // The file is read once, before the response starts, so that the response can be streamed without any further database or file system work. + FileInfo fileInformation = new(track.Path); + if (!fileInformation.Exists) + return Errors.Music.TrackFileNotFound; + + long length = fileInformation.Length; + DateTimeOffset lastModified = new(fileInformation.LastWriteTimeUtc, TimeSpan.Zero); + return new TrackStreamDataDto(track.Path, track.Path.ToAudioFileFormat(), length, lastModified); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + // A file that cannot be read is indistinguishable, to the caller, from a file that does not exist, so the same not found error is returned. + return Errors.Music.TrackFileNotFound; + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs new file mode 100644 index 00000000..4eec9b17 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; + +/// +/// Validates the needed validation rules for . +/// +public class GetTrackStreamQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackStreamQueryValidator() + { + // Validates the identifier of the media library the track belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track whose audio file is streamed, taken from the route. + RuleFor(query => query.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(query => query.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(query => query.TrackId is not null && query.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs new file mode 100644 index 00000000..08f594ae --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for the data of the audio file of a track, needed to stream it. +/// +/// The file system path of the audio file of the track. +/// The file format of the audio file of the track. +/// The length of the audio file of the track, in bytes. +/// The date and time when the audio file of the track was last modified. +[DebuggerDisplay("Format: {Format} Length: {Length}")] +public sealed record TrackStreamDataDto( + string Path, + AudioFileFormat Format, + long Length, + DateTimeOffset LastModified +); diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index a4bbe4ad..aceafa55 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -320,6 +320,43 @@ internal sealed class TrackRepository : ITrackRepository return track; } + /// + /// Gets the data needed to stream the audio file of the track identified by , when it belongs to the album identified by + /// and to the media library identified by , and that album belongs to the artist identified by + /// . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose streaming data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track matches the + /// provided identifiers, or an error. + /// + public async Task> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken) + { + // The projection is flat and untracked, and the album is joined both to scope the track by its artist and to project the artist Id, so a track + // that is not in the named library, album and artist simply yields no row. + return await _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) + .Select(track => new TrackStreamDto + { + Path = track.Path, + LibraryId = track.LibraryId, + AlbumId = track.AlbumId, + ArtistId = track.Album!.ArtistId, + AudioCodec = track.AudioCodec, + DurationInSeconds = track.DurationInSeconds, + SampleRate = track.SampleRate, + Channels = track.Channels, + BitDepth = track.BitDepth, + Bitrate = track.Bitrate + }) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + /// /// Deletes the track identified by , together with its owned collections and contributions, by the database cascade. /// diff --git a/src/Lumina.Domain/Common/Errors/Errors.Music.cs b/src/Lumina.Domain/Common/Errors/Errors.Music.cs index b636930d..a0724fde 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Music.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Music.cs @@ -38,6 +38,7 @@ public static partial class Errors public static Error UnknownMusicKey => Error.Validation(description: nameof(UnknownMusicKey)); public static Error CatalogNumberMustBeMaximum50CharactersLong => Error.Validation(description: nameof(CatalogNumberMustBeMaximum50CharactersLong)); public static Error TrackNotFound => Error.NotFound(description: nameof(TrackNotFound)); + public static Error TrackFileNotFound => Error.NotFound(description: nameof(TrackFileNotFound)); public static Error TrackAlreadyExists => Error.Conflict(description: nameof(TrackAlreadyExists)); public static Error TrackIdCannotBeEmpty => Error.Validation(description: nameof(TrackIdCannotBeEmpty)); public static Error TracksListCannotBeNull => Error.Validation(description: nameof(TracksListCannotBeNull)); diff --git a/src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs b/src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs new file mode 100644 index 00000000..ba878a82 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs @@ -0,0 +1,8 @@ +namespace Lumina.Presentation.Api.Common.Http; + +/// +/// Marker metadata that opts an endpoint out of the eventual consistency pipeline, so that a long lived response (for example a track stream) never holds the request's database transaction open. +/// +public sealed class SkipEventualConsistencyMetadata +{ +} diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs index 7f16b977..76fe9689 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DomainEvents; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; +using Lumina.Presentation.Api.Common.Http; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Logging; @@ -39,6 +40,14 @@ public class EventualConsistencyMiddleware /// In memory queue containing the queued domain events. public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue) { + // Endpoints that serve long lived responses (for example a track stream) opt out through endpoint metadata, so that their response never + // holds the request's database transaction open; the opt out is metadata based, so it follows the endpoint even when its route changes. + if (context.GetEndpoint()?.Metadata.GetMetadata() is not null) + { + await _next(context).ConfigureAwait(false); + return; + } + // begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation IDbContextTransaction transaction = await dbContext.Database.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false); // register an action to be executed once the response is completed (the user already received a response for the request) diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs index b17a5043..eb235189 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs @@ -14,5 +14,6 @@ public static partial class ApiRoutes public const string GET_TRACK_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string UPDATE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + public const string STREAM_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs new file mode 100644 index 00000000..89971766 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.DependencyInjection; +using Lumina.Presentation.Api.Common.Http; +using Lumina.Presentation.Api.Common.MimeTypes; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream route. +/// +public class GetTrackStreamEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getTrackStreamQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get track stream queries. + public GetTrackStreamEndpoint(IQueryHandler> getTrackStreamQueryHandler) + { + _getTrackStreamQueryHandler = getTrackStreamQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Tracks.STREAM_TRACK); + Version(1); + DontCatchExceptions(); + // The stream is limited per user with a concurrency limiter (never with the login rate limit policy), and it is excluded from the eventual + // consistency pipeline, because a long lived audio response would otherwise hold the request's database transaction open for its whole duration. + Options(builder => builder + .RequireRateLimiting(PresentationApiLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY) + .WithMetadata(new SkipEventualConsistencyMetadata())); + } + + /// + /// Streams the audio file of the track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + GetTrackStreamQuery query = new(libraryId, artistId, albumId, trackId); + Result result = await _getTrackStreamQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + if (result.IsFailure) + return Problem(result.Errors); + + // Audio is inert content, but it is still served with content sniffing disabled, so that a file with an unexpected extension is never interpreted as active content. + HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff"; + // The audio is private to the authenticated user and its bytes must never be stored by an intermediary, so it is not publicly cacheable and it varies by the bearer token. + HttpContext.Response.Headers["Cache-Control"] = "private"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + + // The entity tag is derived from the size and the last modification time of the file, never from its path or its name, so no file system detail is exposed, and no download name is passed, so no Content-Disposition is emitted. + EntityTagHeaderValue entityTag = new($"\"{result.Value.LastModified.ToUnixTimeSeconds()}-{result.Value.Length}\""); + return TypedResults.PhysicalFile( + result.Value.Path, + MusicMimeTypes.GetMimeType(result.Value.Format), + fileDownloadName: null, + enableRangeProcessing: true, + lastModified: result.Value.LastModified, + entityTag: entityTag); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs new file mode 100644 index 00000000..a6d03136 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackStreamEndpointSummary() + { + Summary = "Streams the audio file of a track."; + Description = "Streams the audio file of the track identified by the route, with HTTP range support, so that a player can start playback before the whole file is downloaded and can seek within it. The audio file is streamed to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track."; + + Response(200, "The audio file of the track is streamed, with the media type of the file when it is an audio type, or application/octet-stream otherwise, and with the length of the file as its content length.", "*/*"); + + Response(206, "The requested range of the audio file of the track is streamed, with the range in the Content-Range header and its length as the content length.", "*/*"); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the track or its media library does not exist, the track does not belong to the library, album and artist named by the route, or the audio file of the track is outside the content locations of its library, missing, or unreadable.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackFileNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(416, "The request failed because the requested range is not satisfiable for the size of the audio file.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.17", + title = "RangeNotSatisfiable", + status = 416, + detail = "The requested range is not satisfiable.", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.sln b/src/Lumina.sln index 2614a640..9de2e1b3 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -286,6 +286,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657 ..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http + ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http EndProjectSection EndProject diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs new file mode 100644 index 00000000..94c3dfea --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs @@ -0,0 +1,310 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-tests-{Guid.NewGuid():N}"); + private readonly List _temporaryFiles = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetTrackStreamEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client and the temporary content root of the test. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + Directory.CreateDirectory(_contentRootPath); + } + + [Fact] + public async Task GetTrackStream_WhenTrackBelongsToAnOwnedLibrary_ShouldStreamTheWholeAudioFile() + { + // Arrange + Guid userId = GetCurrentUserId(); + byte[] audioBytes = CreateAudioBytes(); + string trackPath = WriteContentFile("bohemian-rhapsody.mp3", audioBytes); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType); + Assert.Equal((long)audioBytes.Length, response.Content.Headers.ContentLength!.Value); + Assert.Contains("bytes", response.Headers.AcceptRanges); + Assert.NotNull(response.Headers.ETag); + Assert.NotNull(response.Content.Headers.LastModified); + Assert.Contains("nosniff", response.Headers.GetValues("X-Content-Type-Options")); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + Assert.Equal(audioBytes, await response.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task GetTrackStream_WhenARangeIsRequested_ShouldStreamOnlyTheRequestedRange() + { + // Arrange + Guid userId = GetCurrentUserId(); + byte[] audioBytes = CreateAudioBytes(); + string trackPath = WriteContentFile("love-of-my-life.mp3", audioBytes); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + using HttpRequestMessage request = new(HttpMethod.Get, $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + request.Headers.Range = new RangeHeaderValue(100, 199); + + // Act + HttpResponseMessage response = await _client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode); + Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType); + Assert.Equal(100L, response.Content.Headers.ContentLength!.Value); + Assert.Contains("bytes", response.Headers.AcceptRanges); + Assert.Equal(100L, response.Content.Headers.ContentRange!.From!.Value); + Assert.Equal(199L, response.Content.Headers.ContentRange!.To!.Value); + Assert.Equal((long)audioBytes.Length, response.Content.Headers.ContentRange!.Length!.Value); + Assert.Equal(audioBytes[100..200], await response.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task GetTrackStream_WhenTrackIsRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + string trackPath = WriteContentFile("you-re-my-best-friend.mp3", CreateAudioBytes()); + (Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenAudioFileIsMissing_ShouldReturnTrackFileNotFoundProblemWithoutLeakingThePath() + { + // Arrange + Guid userId = GetCurrentUserId(); + string trackPath = Path.Combine(_contentRootPath, "missing-file.mp3"); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain(trackPath, content, StringComparison.OrdinalIgnoreCase); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackFileNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenAudioFileIsOutsideTheLibraryContentLocations_ShouldReturnTrackFileNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + byte[] audioBytes = CreateAudioBytes(); + string outsideFilePath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-outside-{Guid.NewGuid():N}.mp3"); + await File.WriteAllBytesAsync(outsideFilePath, audioBytes); + _temporaryFiles.Add(outsideFilePath); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, outsideFilePath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain(outsideFilePath, content, StringComparison.OrdinalIgnoreCase); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackFileNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + (Guid otherUserId, _) = await SeedOtherUserAsync(); + string trackPath = WriteContentFile("news-of-the-world.mp3", CreateAudioBytes()); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, trackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Dictionary? problemDetails = JsonSerializer.Deserialize>(await response.Content.ReadAsStringAsync(), _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetTrackStream_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album. + /// + /// The Id of the user that owns the library. + /// The file system path of the seeded track. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen")); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera")); + dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: trackPath, title: "A Track", includeMetadata: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId, trackId); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user and its username. + private async Task<(Guid userId, string username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return (userId, username); + } + + /// + /// Writes an audio file with the provided inside the content root of the test, and returns its full path. + /// + /// The name of the audio file to write. + /// The bytes of the audio file to write. + /// The full path of the written audio file. + private string WriteContentFile(string fileName, byte[] audioBytes) + { + string filePath = Path.Combine(_contentRootPath, fileName); + File.WriteAllBytes(filePath, audioBytes); + return filePath; + } + + /// + /// Creates a deterministic byte array that stands in for the content of an audio file. + /// + /// The created bytes. + private static byte[] CreateAudioBytes() + { + return [.. Enumerable.Range(0, 4096).Select(index => (byte)(index % 256))]; + } + + /// + /// Reads the problem details of a response. + /// + /// The HTTP response to read. + /// The deserialized problem details. + private async Task ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources and the temporary files of the test. + /// + public async Task DisposeAsync() + { + if (Directory.Exists(_contentRootPath)) + Directory.Delete(_contentRootPath, recursive: true); + foreach (string temporaryFile in _temporaryFiles) + { + if (File.Exists(temporaryFile)) + File.Delete(temporaryFile); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs new file mode 100644 index 00000000..a0a644be --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Common.Http; +using Lumina.Presentation.Api.Common.Middlewares; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Common.Middlewares; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EventualConsistencyMiddlewareTests +{ + private readonly EventualConsistencyMiddleware _sut; + private bool _nextInvoked; + + /// + /// Initializes a new instance of the class. + /// + public EventualConsistencyMiddlewareTests() + { + ILogger mockLogger = Substitute.For>(); + _sut = new EventualConsistencyMiddleware( + context => + { + _nextInvoked = true; + return Task.CompletedTask; + }, + mockLogger); + } + + [Fact] + public async Task InvokeAsync_WhenEndpointOptsOutThroughMetadata_ShouldInvokeNextWithoutTouchingTheDatabase() + { + // Arrange + DefaultHttpContext context = new(); + context.SetEndpoint(new Endpoint( + requestDelegate: null, + new EndpointMetadataCollection(new SkipEventualConsistencyMetadata()), + displayName: "GetTrackStream")); + + // Act + // The database, the domain event publisher and the domain events queue are deliberately not supplied: an endpoint that opted out through + // metadata must invoke the next delegate without touching any of them, which is exactly what a long lived stream needs. + await _sut.InvokeAsync(context, null!, null!, null!); + + // Assert + Assert.True(_nextInvoked); + } +} From f29f89f31f56df44a32147372327c85cc7a71cd5 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 14 Oct 2026 13:40:28 +0300 Subject: [PATCH 06/77] Captures the audio container of the music tracks Adds a Container to the audio metadata, captured with TagLibSharp from the concrete type of the parsed file during the music library scan and stored on the track through a new column and an EF migration. The container is refreshed when a file changes, survives track and artist edits and provider enrichment, and is exposed read-only in the track responses, never settable through a request. Extracts the container resolution into a testable resolver used by the scan pipeline and the ID3 plugin, refuses to read a file that is itself a reparse point during extraction, and updates the endpoint summaries, the API and domain documentation, and the tests. --- .../audio-library/music-library/Api.Albums.md | 9 + .../music-library/Api.Artists.md | 8 + .../audio-library/music-library/Api.Tracks.md | 3 + .../domain/Aggregates.AudioLibrary.md | 1 + .../Common/Models/DTO/Tags/Id3TagDto.cs | 5 + .../Core/Mapping/Id3TagMapper.cs | 1 + .../Core/Tags/AudioContainerResolver.cs | 57 + .../Core/Tags/Id3TagReader.cs | 1 + .../Core/Mapping/MusicBrainzMapper.cs | 1 + .../MusicLibraryScanItemMetadataEntity.cs | 5 + .../AudioLibrary/MusicLibrary/TrackEntity.cs | 5 + .../Tracks/AudioMetadataDtoMapping.cs | 4 + .../Tracks/MusicTrackMetadataDtoMapping.cs | 2 + .../MusicLibrary/Tracks/TrackEntityMapping.cs | 4 +- .../MusicLibrary/Tracks/TrackMapping.cs | 1 + .../MusicLibrary/AudioMetadataDto.cs | 2 + .../MusicLibrary/Tracks/TrackResponse.cs | 4 +- ...sicLibraryScanItemMetadataConfiguration.cs | 3 + .../Configuration/TrackConfiguration.cs | 3 + ...sAudioContainerToMusicMetadata.Designer.cs | 3435 +++++++++++++++++ ...95657_AddsAudioContainerToMusicMetadata.cs | 42 + .../LuminaDbContextModelSnapshot.cs | 10 + .../Common/ValueObjects/AudioMetadata.cs | 44 + .../MusicLibraryAggregate/Entities/Track.cs | 14 +- .../Metadata/AudioContainerResolver.cs | 57 + .../Metadata/MusicMetadataAggregator.cs | 1 + .../MusicMediaLibraryScanItemMaterializer.cs | 1 + .../Audio/Music/MusicMetadataExtractionJob.cs | 127 +- .../AddAlbum/AddAlbumEndpointSummary.cs | 2 + .../GetAlbum/GetAlbumEndpointSummary.cs | 2 + .../GetAlbumTracksEndpointSummary.cs | 3 + .../UpdateAlbum/UpdateAlbumEndpointSummary.cs | 2 + .../AddArtist/AddArtistEndpointSummary.cs | 2 + .../GetArtist/GetArtistEndpointSummary.cs | 1 + .../GetArtistAlbumsEndpointSummary.cs | 2 + .../GetArtists/GetArtistsEndpointSummary.cs | 2 + .../UpdateArtistEndpointSummary.cs | 2 + .../AddTrack/AddTrackEndpointSummary.cs | 2 + .../GetTrack/GetTrackEndpointSummary.cs | 2 + .../UpdateTrack/UpdateTrackEndpointSummary.cs | 2 + ...sicLibraryScanItemMetadataEntityFixture.cs | 5 +- .../MusicLibrary/TrackEntityFixture.cs | 5 + .../MusicLibrary/AudioMetadataDtoFixture.cs | 5 + .../Tracks/TrackResponseFixture.cs | 9 +- .../ValueObjects/AudioMetadataFixture.cs | 3 + .../Music/MusicMetadataExtractionJobTests.cs | 309 ++ .../Core/Id3TrackMetadataProviderTests.cs | 1 + .../Core/Tags/Id3TagReaderTests.cs | 22 + .../UpdateArtistCommandMappingTests.cs | 26 +- .../Tracks/AudioMetadataDtoMappingTests.cs | 4 + .../MusicTrackMetadataDtoMappingTests.cs | 14 +- .../Tracks/TrackEntityMappingTests.cs | 16 + .../MusicLibrary/Tracks/TrackMappingTests.cs | 3 + .../Tracks/UpdateTrackCommandMappingTests.cs | 28 +- .../Common/ValueObjects/AudioMetadataTests.cs | 58 + .../Entities/TrackTests.cs | 56 + .../Metadata/AudioContainerResolverTests.cs | 29 + .../Metadata/MusicMetadataAggregatorTests.cs | 28 + ...icMediaLibraryScanItemMaterializerTests.cs | 27 + .../Core/Tags/AudioContainerResolverTests.cs | 29 + 60 files changed, 4483 insertions(+), 68 deletions(-) create mode 100644 plugins/Lumina.Plugins.ID3/Core/Tags/AudioContainerResolver.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolver.cs create mode 100644 tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolverTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/AudioContainerResolverTests.cs diff --git a/docs/technical/api/library/audio-library/music-library/Api.Albums.md b/docs/technical/api/library/audio-library/music-library/Api.Albums.md index cbe5d852..571214d8 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Albums.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Albums.md @@ -376,6 +376,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -454,6 +455,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -639,6 +641,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -717,6 +720,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -941,6 +945,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -1019,6 +1024,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -1283,6 +1289,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -1361,6 +1368,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -1511,6 +1519,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", diff --git a/docs/technical/api/library/audio-library/music-library/Api.Artists.md b/docs/technical/api/library/audio-library/music-library/Api.Artists.md index 3a5fe443..fec7c403 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Artists.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Artists.md @@ -518,6 +518,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -596,6 +597,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -865,6 +867,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1& "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -943,6 +946,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1& "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -1252,6 +1256,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -1330,6 +1335,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -1916,6 +1922,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -1994,6 +2001,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index 929ab62b..199d8291 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -129,6 +129,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -231,6 +232,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -452,6 +454,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", diff --git a/docs/technical/domain/Aggregates.AudioLibrary.md b/docs/technical/domain/Aggregates.AudioLibrary.md index f4df0db0..7c334620 100644 --- a/docs/technical/domain/Aggregates.AudioLibrary.md +++ b/docs/technical/domain/Aggregates.AudioLibrary.md @@ -286,6 +286,7 @@ class Track "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", + "container": "FLAC", "bitrate": 980, "acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f", "replayGainTrackGain": -7.5, diff --git a/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs b/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs index 02897507..7c8103b5 100644 --- a/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs +++ b/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs @@ -216,6 +216,11 @@ internal sealed class Id3TagDto /// public string? AudioCodec { get; init; } + /// + /// Gets or initializes the container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV. + /// + public string? Container { get; init; } + /// /// Gets or initializes the official website associated with the artist. /// diff --git a/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs b/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs index df197b9a..6986686f 100644 --- a/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs +++ b/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs @@ -164,6 +164,7 @@ internal static class Id3TagMapper Channels: data.Channels, BitDepth: data.BitDepth, AudioCodec: NullIfWhiteSpace(data.AudioCodec), + Container: NullIfWhiteSpace(data.Container), Bitrate: data.Bitrate, MusicBrainzRecordingId: ParseGuid(data.MusicBrainzRecordingId), MusicBrainzTrackId: ParseGuid(data.MusicBrainzReleaseTrackId), diff --git a/plugins/Lumina.Plugins.ID3/Core/Tags/AudioContainerResolver.cs b/plugins/Lumina.Plugins.ID3/Core/Tags/AudioContainerResolver.cs new file mode 100644 index 00000000..3c2b4e1e --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Tags/AudioContainerResolver.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Plugins.ID3.Core.Tags; + +/// +/// Resolves the canonical name of the container of an audio file from the concrete type the tagging library parsed it as. +/// +internal static class AudioContainerResolver +{ + /// + /// Resolves the container of the audio file parsed by . + /// + /// The parsed audio file whose container is resolved. + /// The canonical name of the container, for example MP3, FLAC, OGG, AAC, MP4 or WAV, or when the container cannot be recognized. + public static string? Resolve(TagLib.File tagFile) + { + // The concrete type of the parsed file is the most reliable description of its container, because it is chosen by the parser from the + // actual bytes of the file, while the mime type only describes the extension. The scanning pipeline resolves the container the same way, + // so that the container captured during a scan and the one captured during metadata enrichment always agree. + return tagFile switch + { + TagLib.Mpeg.File => "MP3", + TagLib.Flac.File => "FLAC", + TagLib.Mpeg4.File => "MP4", + TagLib.Aac.File => "AAC", + TagLib.Ogg.File => "OGG", + TagLib.Riff.File => "WAV", + TagLib.Aiff.File => "AIFF", + TagLib.Ape.File => "APE", + TagLib.WavPack.File => "WAVPACK", + TagLib.Asf.File => "WMA", + TagLib.Dsf.File => "DSF", + TagLib.Matroska.File => "MATROSKA", + TagLib.MusePack.File => "MPC", + TagLib.Audible.File => "AA", + _ => ResolveFromMimeType(tagFile.MimeType) + }; + } + + /// + /// Resolves the container from the mime type reported by the tagging library, for the containers that have no dedicated parser. + /// + /// The mime type reported by the tagging library. + /// The name of the container, or when it cannot be derived. + public static string? ResolveFromMimeType(string? mimeType) + { + if (string.IsNullOrWhiteSpace(mimeType)) + return null; + + // The library reports its mime types with the "taglib/" prefix, so only the last segment names the container. + string[] segments = mimeType.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + string? container = segments.Length > 0 ? segments[^1] : null; + return string.IsNullOrWhiteSpace(container) ? null : container.ToUpperInvariant(); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs b/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs index 4f86de83..d2f80301 100644 --- a/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs +++ b/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs @@ -166,6 +166,7 @@ internal sealed class Id3TagReader BitDepth = audioProperties.BitsPerSample > 0 ? audioProperties.BitsPerSample : null, Bitrate = audioProperties.AudioBitrate > 0 ? audioProperties.AudioBitrate : null, AudioCodec = NullIfWhiteSpace(audioProperties.Description), + Container = AudioContainerResolver.Resolve(tagFile), Website = NullIfWhiteSpace(GetExtendedField(extendedFields, "WOAR", "website")), MusicBrainzArtistId = NullIfWhiteSpace(tag.MusicBrainzArtistId), MusicBrainzReleaseArtistId = NullIfWhiteSpace(tag.MusicBrainzReleaseArtistId), diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs index 5b6a363a..81b40249 100644 --- a/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs @@ -183,6 +183,7 @@ internal static partial class MusicBrainzMapper Channels: null, BitDepth: null, AudioCodec: null, + Container: null, Bitrate: null, MusicBrainzRecordingId: ParseGuid(recording.Id), MusicBrainzTrackId: null, diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs index 8b943070..02661eae 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs @@ -94,6 +94,11 @@ public class MusicLibraryScanItemMetadataEntity : IStorageEntity /// public string? AudioCodec { get; set; } + /// + /// Gets or sets the container of the audio file, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. + /// + public string? Container { get; set; } + /// /// Gets or sets the bitrate of the audio in kbps, if applicable. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs index 23a2794e..246685ca 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs @@ -141,6 +141,11 @@ public class TrackEntity : IStorageEntity, IAuditableEntity /// public string? AudioCodec { get; set; } + /// + /// Gets or sets the container of the audio file, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. + /// + public string? Container { get; set; } + /// /// Gets or sets the bitrate of the audio in kbps, if applicable. /// diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs index fdab831b..379acd51 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs @@ -202,6 +202,9 @@ public static class AudioMetadataDtoMapping Optional audioCodec = Optional.FromNullable(dto.AudioCodec); if (!audioCodec.HasValue) audioCodec = track.Metadata.AudioCodec; + // The container is captured from the file itself: a provider that re-reads the file supplies it, and when it is absent the track keeps the stored + // container, which the domain enforces when the metadata is applied. The preserve rule therefore lives in one place, the domain update. + Optional container = Optional.FromNullable(dto.Container); Optional bitrate = Optional.FromNullable(dto.Bitrate); if (!bitrate.HasValue) bitrate = track.Metadata.Bitrate; @@ -220,6 +223,7 @@ public static class AudioMetadataDtoMapping originalLanguage, bitDepth, audioCodec, + container, bitrate, track.Metadata.AcoustId, track.Metadata.ReplayGainTrackGain, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs index 4d05db8a..721998ed 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs @@ -63,6 +63,7 @@ public static class MusicTrackMetadataDtoMapping if (dto.OriginalLanguage is not null && dto.OriginalLanguage.LanguageCode is not null && dto.OriginalLanguage.LanguageName is not null) originalLanguage = LanguageInfo.Create(dto.OriginalLanguage.LanguageCode, dto.OriginalLanguage.LanguageName, Optional.FromNullable(dto.OriginalLanguage.NativeName)); + // The container is captured from the file itself and is never settable through a request; on an edit the track keeps the container it already has. return AudioMetadata.Create( dto.Title!, Optional.FromNullable(dto.OriginalTitle), @@ -77,6 +78,7 @@ public static class MusicTrackMetadataDtoMapping originalLanguage, Optional.FromNullable(dto.BitDepth), Optional.FromNullable(dto.AudioCodec), + Optional.None(), Optional.FromNullable(dto.Bitrate), Optional.FromNullable(dto.AcoustId), Optional.FromNullable(dto.ReplayGainTrackGain), diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs index 82a08ab2..8de4d57d 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs @@ -84,6 +84,7 @@ public static class TrackEntityMapping originalLanguage, Optional.FromNullable(repositoryEntity.BitDepth), Optional.FromNullable(repositoryEntity.AudioCodec), + Optional.FromNullable(repositoryEntity.Container), Optional.FromNullable(repositoryEntity.Bitrate), Optional.FromNullable(repositoryEntity.AcoustId), Optional.FromNullable(repositoryEntity.ReplayGainTrackGain), @@ -259,7 +260,8 @@ public static class TrackEntityMapping [.. repositoryEntity.Moods.ToResponses()], [.. repositoryEntity.Isrcs.ToResponses()], [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], - [.. repositoryEntity.Ratings.ToResponses()]); + [.. repositoryEntity.Ratings.ToResponses()], + repositoryEntity.Container); } /// diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs index c666917c..60efeef1 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs @@ -52,6 +52,7 @@ public static class TrackMapping Channels = domainEntity.Metadata.Channels, BitDepth = domainEntity.Metadata.BitDepth.HasValue ? domainEntity.Metadata.BitDepth.Value : null, AudioCodec = domainEntity.Metadata.AudioCodec.HasValue ? domainEntity.Metadata.AudioCodec.Value : null, + Container = domainEntity.Metadata.Container.HasValue ? domainEntity.Metadata.Container.Value : null, Bitrate = domainEntity.Metadata.Bitrate.HasValue ? domainEntity.Metadata.Bitrate.Value : null, AcoustId = domainEntity.Metadata.AcoustId.HasValue ? domainEntity.Metadata.AcoustId.Value : null, ReplayGainTrackGain = domainEntity.Metadata.ReplayGainTrackGain.HasValue ? domainEntity.Metadata.ReplayGainTrackGain.Value : null, diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs index 35114938..028e1f4b 100644 --- a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs @@ -34,6 +34,7 @@ namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; /// The number of audio channels of the track. Required. /// The bit depth of the audio of the track. Optional. /// The audio codec used by the track. Optional. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional. /// The bitrate of the audio of the track in kbps. Optional. /// The MusicBrainz identifier of the recording. Optional. /// The MusicBrainz identifier of the track. Optional. @@ -62,6 +63,7 @@ public sealed record AudioMetadataDto( int? Channels, int? BitDepth, string? AudioCodec, + string? Container, int? Bitrate, Guid? MusicBrainzRecordingId, Guid? MusicBrainzTrackId, diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs index b6e64f64..160c0265 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs @@ -33,6 +33,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Trac /// The list of ISRC (International Standard Recording Code) of the track. /// The list of references to the media contributors that performed on the track, each with the role they played. /// The list of ratings for this track. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, captured from the file itself. Read only, and not settable through a request. Optional. [DebuggerDisplay("Title: {Metadata.Title}")] public record TrackResponse( Guid Id, @@ -53,5 +54,6 @@ public record TrackResponse( List? Moods, List? Isrcs, List? Contributors, - List? Ratings + List? Ratings, + string? Container = null ); diff --git a/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs index 7cc8aa53..a7d60eae 100644 --- a/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs @@ -98,6 +98,9 @@ public class MusicLibraryScanItemMetadataConfiguration : IEntityTypeConfiguratio .HasColumnOrder(29); builder.PrimitiveCollection(musicMetadata => musicMetadata.Moods) .HasColumnOrder(30); + builder.Property(musicMetadata => musicMetadata.Container) + .HasMaxLength(50) + .HasColumnOrder(31); builder.HasIndex(musicMetadata => new { musicMetadata.LibraryScanId, musicMetadata.Path }) .IsUnique(); // the metadata of the same physical file cannot be staged twice during the same scan diff --git a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs index 733def1b..1999f0fa 100644 --- a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs @@ -152,6 +152,9 @@ public class TrackConfiguration : IEntityTypeConfiguration builder.Property(track => track.ReplayGainAlbumPeak) .HasColumnType("decimal(8,6)") .HasColumnOrder(48); + builder.Property(track => track.Container) + .HasMaxLength(50) + .HasColumnOrder(49); builder.HasOne(track => track.Album) .WithMany(album => album.Tracks) diff --git a/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.Designer.cs new file mode 100644 index 00000000..cf1cd3a9 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.Designer.cs @@ -0,0 +1,3435 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261013195657_AddsAudioContainerToMusicMetadata")] + partial class AddsAudioContainerToMusicMetadata + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.cs b/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.cs new file mode 100644 index 00000000..43d0edff --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.cs @@ -0,0 +1,42 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsAudioContainerToMusicMetadata : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Container", + table: "Tracks", + type: "TEXT", + maxLength: 50, + nullable: true) + .Annotation("Relational:ColumnOrder", 49); + + migrationBuilder.AddColumn( + name: "Container", + table: "MusicLibraryScanItemMetadata", + type: "TEXT", + maxLength: 50, + nullable: true) + .Annotation("Relational:ColumnOrder", 31); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Container", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "Container", + table: "MusicLibraryScanItemMetadata"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index d2db1993..ad7bbe21 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -844,6 +844,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(13); + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + b.Property("DiscNumber") .HasColumnType("INTEGER") .HasColumnOrder(10); @@ -1037,6 +1042,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(22); + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + b.Property("CreatedBy") .HasColumnType("TEXT") .HasColumnOrder(38); diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs index 27db4eda..9b16e989 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs @@ -38,6 +38,11 @@ public class AudioMetadata : BaseMetadata /// public Optional AudioCodec { get; } + /// + /// Gets the container of the audio, as read from the file itself, for example MP3, FLAC, OGG, AAC, MP4 or WAV. + /// + public Optional Container { get; } + /// /// Gets the bitrate of the audio in kbps. /// @@ -82,6 +87,7 @@ public class AudioMetadata : BaseMetadata /// The optional original language of the audio. /// The bit depth of the audio. /// The audio codec used. + /// The container of the audio. /// The genres of the audio. /// The tags associated with the audio. /// The bitrate of the audio in kbps. @@ -104,6 +110,7 @@ public class AudioMetadata : BaseMetadata Optional originalLanguage, Optional bitDepth, Optional audioCodec, + Optional container, Optional bitrate, Optional acoustId, Optional replayGainTrackGain, @@ -117,6 +124,7 @@ public class AudioMetadata : BaseMetadata Channels = channels; BitDepth = bitDepth; AudioCodec = audioCodec; + Container = container; Bitrate = bitrate; AcoustId = acoustId; ReplayGainTrackGain = replayGainTrackGain; @@ -139,6 +147,7 @@ public class AudioMetadata : BaseMetadata /// The optional original language of the audio. /// The bit depth of the audio. /// The audio codec used. + /// The container of the audio. /// The genres of the audio. /// The tags associated with the audio. /// The bitrate of the audio in kbps. @@ -164,6 +173,7 @@ public class AudioMetadata : BaseMetadata Optional originalLanguage, Optional bitDepth, Optional audioCodec, + Optional container, Optional bitrate, Optional acoustId, Optional replayGainTrackGain, @@ -185,6 +195,7 @@ public class AudioMetadata : BaseMetadata originalLanguage, bitDepth, audioCodec, + container, bitrate, acoustId, replayGainTrackGain, @@ -193,6 +204,38 @@ public class AudioMetadata : BaseMetadata replayGainAlbumPeak); } + /// + /// Creates a copy of this audio metadata with the provided , keeping every other property unchanged. + /// + /// The container of the audio. + /// + /// An containing either a copy of this audio metadata with the provided container, or an error message. + /// + internal Result WithContainer(Optional container) + { + return Create( + Title, + OriginalTitle, + DurationInSeconds, + SampleRate, + Channels, + ReleaseInfo, + Description, + [.. Genres], + [.. Tags], + Language, + OriginalLanguage, + BitDepth, + AudioCodec, + container, + Bitrate, + AcoustId, + ReplayGainTrackGain, + ReplayGainTrackPeak, + ReplayGainAlbumGain, + ReplayGainAlbumPeak); + } + /// /// Gets the list of items that define equality of the object. /// @@ -206,6 +249,7 @@ public class AudioMetadata : BaseMetadata yield return Channels; yield return BitDepth; yield return AudioCodec; + yield return Container; yield return Bitrate; yield return AcoustId; yield return ReplayGainTrackGain; diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs index 78703c91..196f5276 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs @@ -347,7 +347,8 @@ public sealed class Track : Entity /// /// /// The file system path is intentionally not editable here: it is set only when the track is created by the scanner, so that a client - /// can never point an existing track at an arbitrary file of the host. + /// can never point an existing track at an arbitrary file of the host. The container is captured from the file itself and is not part of + /// an edit either, so an update that does not carry one keeps the container already stored for the track. /// /// The audio metadata of the track. /// The optional disambiguation comment of the track. @@ -374,7 +375,16 @@ public sealed class Track : Entity Optional musicBrainzRecordingId, Optional musicBrainzTrackId) { - Metadata = metadata; + // The container is captured from the file itself and is never part of an edit, so an update that does not carry one keeps the stored container. + if (metadata.Container.HasValue) + Metadata = metadata; + else + { + Result metadataWithStoredContainerResult = metadata.WithContainer(Metadata.Container); + if (metadataWithStoredContainerResult.IsFailure) + return metadataWithStoredContainerResult.Errors; + Metadata = metadataWithStoredContainerResult.Value; + } Disambiguation = disambiguation; TrackNumber = trackNumber; DiscNumber = discNumber; diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolver.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolver.cs new file mode 100644 index 00000000..e0054c32 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolver.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; + +/// +/// Resolves the canonical name of the container of an audio file from the concrete type the tagging library parsed it as. +/// +internal static class AudioContainerResolver +{ + /// + /// Resolves the container of the audio file parsed by . + /// + /// The parsed audio file whose container is resolved. + /// The canonical name of the container, for example MP3, FLAC, OGG, AAC, MP4 or WAV, or when the container cannot be recognized. + public static string? Resolve(TagLib.File tagFile) + { + // The concrete type of the parsed file is the most reliable description of its container, because it is chosen by the parser from the + // actual bytes of the file, while the mime type only describes the extension. Containers that share a parser (for example the Opus and + // Vorbis streams parsed by the Ogg parser) are reported under the name of their container, and the codec column carries the difference. + return tagFile switch + { + TagLib.Mpeg.File => "MP3", + TagLib.Flac.File => "FLAC", + TagLib.Mpeg4.File => "MP4", + TagLib.Aac.File => "AAC", + TagLib.Ogg.File => "OGG", + TagLib.Riff.File => "WAV", + TagLib.Aiff.File => "AIFF", + TagLib.Ape.File => "APE", + TagLib.WavPack.File => "WAVPACK", + TagLib.Asf.File => "WMA", + TagLib.Dsf.File => "DSF", + TagLib.Matroska.File => "MATROSKA", + TagLib.MusePack.File => "MPC", + TagLib.Audible.File => "AA", + _ => ResolveFromMimeType(tagFile.MimeType) + }; + } + + /// + /// Resolves the container from the mime type reported by the tagging library, for the containers that have no dedicated parser. + /// + /// The mime type reported by the tagging library. + /// The name of the container, or when it cannot be derived. + public static string? ResolveFromMimeType(string? mimeType) + { + if (string.IsNullOrWhiteSpace(mimeType)) + return null; + + // The library reports its mime types with the "taglib/" prefix, so only the last segment names the container. + string[] segments = mimeType.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + string? container = segments.Length > 0 ? segments[^1] : null; + return string.IsNullOrWhiteSpace(container) ? null : container.ToUpperInvariant(); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs index 000eb03c..6a335bc1 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs @@ -111,6 +111,7 @@ internal static class MusicMetadataAggregator First(first.Channels, second.Channels), First(first.BitDepth, second.BitDepth), First(first.AudioCodec, second.AudioCodec), + First(first.Container, second.Container), First(first.Bitrate, second.Bitrate), First(first.MusicBrainzRecordingId, second.MusicBrainzRecordingId), First(first.MusicBrainzTrackId, second.MusicBrainzTrackId), diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs index 1eaf37a6..7c23fbe0 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs @@ -306,6 +306,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI Channels = stagedItem.Channels, BitDepth = stagedItem.BitDepth, AudioCodec = stagedItem.AudioCodec, + Container = stagedItem.Container, Bitrate = stagedItem.Bitrate, AcoustId = stagedItem.AcoustId, ReplayGainTrackGain = stagedItem.ReplayGainTrackGain, diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs index f96b6d29..f04ffff6 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs @@ -17,6 +17,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -232,6 +233,7 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe int channels = 0; int? bitDepth = null; string? audioCodec = null; + string? container = null; int? bitrate = null; string? acoustId = null; decimal? replayGainTrackGain = null; @@ -242,64 +244,71 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe try { - using (TagLib.File tagFile = TagLib.File.Create(path)) + // A file that is itself a link is not read, so its target outside the content locations is never opened. A linked directory is a separate + // discovery level concern, so this is a defense in depth for the leaf file rather than a complete containment guarantee. + if (!IsReparsePoint(path)) { - TagLib.Tag tag = tagFile.Tag; - if (!string.IsNullOrWhiteSpace(tag.Title)) - trackTitle = tag.Title; - if (!string.IsNullOrWhiteSpace(tag.Album)) - releaseName = tag.Album; - // The album artist is preferred over the track artist, because it is the artist the release belongs to. - string? tagArtist = !string.IsNullOrWhiteSpace(tag.FirstAlbumArtist) ? tag.FirstAlbumArtist : tag.FirstPerformer; - if (!string.IsNullOrWhiteSpace(tagArtist)) - artistName = tagArtist; - if (tag.Track > 0) - trackNumber = (int)tag.Track; - if (tag.Disc > 0) - discNumber = (int)tag.Disc; - if (tag.Year > 0) - releaseYear = (int)tag.Year; + using (TagLib.File tagFile = TagLib.File.Create(path)) + { + TagLib.Tag tag = tagFile.Tag; + if (!string.IsNullOrWhiteSpace(tag.Title)) + trackTitle = tag.Title; + if (!string.IsNullOrWhiteSpace(tag.Album)) + releaseName = tag.Album; + // The album artist is preferred over the track artist, because it is the artist the release belongs to. + string? tagArtist = !string.IsNullOrWhiteSpace(tag.FirstAlbumArtist) ? tag.FirstAlbumArtist : tag.FirstPerformer; + if (!string.IsNullOrWhiteSpace(tagArtist)) + artistName = tagArtist; + if (tag.Track > 0) + trackNumber = (int)tag.Track; + if (tag.Disc > 0) + discNumber = (int)tag.Disc; + if (tag.Year > 0) + releaseYear = (int)tag.Year; - TagLib.Properties audioProperties = tagFile.Properties; - durationInSeconds = (int)audioProperties.Duration.TotalSeconds; - sampleRate = audioProperties.AudioSampleRate; - channels = audioProperties.AudioChannels; - if (audioProperties.BitsPerSample > 0) - bitDepth = audioProperties.BitsPerSample; - if (audioProperties.AudioBitrate > 0) - bitrate = audioProperties.AudioBitrate; - if (!string.IsNullOrWhiteSpace(audioProperties.Description)) - audioCodec = audioProperties.Description; + TagLib.Properties audioProperties = tagFile.Properties; + durationInSeconds = (int)audioProperties.Duration.TotalSeconds; + sampleRate = audioProperties.AudioSampleRate; + channels = audioProperties.AudioChannels; + // The container is the format of the file itself, so it is resolved from the concrete type of the parsed file and not from its tags. + container = AudioContainerResolver.Resolve(tagFile); + if (audioProperties.BitsPerSample > 0) + bitDepth = audioProperties.BitsPerSample; + if (audioProperties.AudioBitrate > 0) + bitrate = audioProperties.AudioBitrate; + if (!string.IsNullOrWhiteSpace(audioProperties.Description)) + audioCodec = audioProperties.Description; - // The text frames of the ID3v2 tag are read once for the whole file, so that the extended tag lookups below do not walk all the frames - // of the tag again for every key. - IReadOnlyDictionary id3v2ExtendedFields = GetId3v2ExtendedFields(tagFile); + // The text frames of the ID3v2 tag are read once for the whole file, so that the extended tag lookups below do not walk all the frames + // of the tag again for every key. + IReadOnlyDictionary id3v2ExtendedFields = GetId3v2ExtendedFields(tagFile); - // The MusicBrainz identifiers written by taggers like Picard are read here, so that the enrichment can look the items up directly, - // instead of guessing them through searches. The work identifier and title are not exposed as properties by the tagging library, so - // they are read from the extended tags of the container, and they only serve as a fallback for recordings that MusicBrainz leaves unlinked to a work. - musicBrainzArtistId = ParseGuid(tag.MusicBrainzArtistId); - musicBrainzReleaseArtistId = ParseGuid(tag.MusicBrainzReleaseArtistId); - musicBrainzReleaseGroupId = ParseGuid(tag.MusicBrainzReleaseGroupId); - musicBrainzReleaseId = ParseGuid(tag.MusicBrainzReleaseId); - musicBrainzRecordingId = ParseGuid(tag.MusicBrainzTrackId); - musicBrainzTrackId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID")); - musicBrainzWorkId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID")); - string? extendedWorkTitle = GetExtendedField(tagFile, id3v2ExtendedFields, "WORK", "MUSICBRAINZ_WORK"); - if (!string.IsNullOrWhiteSpace(extendedWorkTitle)) - workTitle = extendedWorkTitle; + // The MusicBrainz identifiers written by taggers like Picard are read here, so that the enrichment can look the items up directly, + // instead of guessing them through searches. The work identifier and title are not exposed as properties by the tagging library, so + // they are read from the extended tags of the container, and they only serve as a fallback for recordings that MusicBrainz leaves unlinked to a work. + musicBrainzArtistId = ParseGuid(tag.MusicBrainzArtistId); + musicBrainzReleaseArtistId = ParseGuid(tag.MusicBrainzReleaseArtistId); + musicBrainzReleaseGroupId = ParseGuid(tag.MusicBrainzReleaseGroupId); + musicBrainzReleaseId = ParseGuid(tag.MusicBrainzReleaseId); + musicBrainzRecordingId = ParseGuid(tag.MusicBrainzTrackId); + musicBrainzTrackId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID")); + musicBrainzWorkId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID")); + string? extendedWorkTitle = GetExtendedField(tagFile, id3v2ExtendedFields, "WORK", "MUSICBRAINZ_WORK"); + if (!string.IsNullOrWhiteSpace(extendedWorkTitle)) + workTitle = extendedWorkTitle; - // The AcoustID, the moods and the ReplayGain values written by taggers like Picard are read here as well. The moods can be a single - // slash separated value or several distinct values, depending on the container, so all of them are read and split before being de-duplicated. - acoustId = GetExtendedField(tagFile, id3v2ExtendedFields, "Acoustid Id", "ACOUSTID_ID"); - moods = [.. GetExtendedFields(tagFile, id3v2ExtendedFields, "mood", "MOOD", "MOODS") - .SelectMany(mood => mood.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) - .Where(mood => !string.IsNullOrWhiteSpace(mood)) - .Distinct(StringComparer.OrdinalIgnoreCase)]; - replayGainTrackGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_GAIN", "replaygain_track_gain")); - replayGainTrackPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_PEAK", "replaygain_track_peak")); - replayGainAlbumGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_GAIN", "replaygain_album_gain")); - replayGainAlbumPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_PEAK", "replaygain_album_peak")); + // The AcoustID, the moods and the ReplayGain values written by taggers like Picard are read here as well. The moods can be a single + // slash separated value or several distinct values, depending on the container, so all of them are read and split before being de-duplicated. + acoustId = GetExtendedField(tagFile, id3v2ExtendedFields, "Acoustid Id", "ACOUSTID_ID"); + moods = [.. GetExtendedFields(tagFile, id3v2ExtendedFields, "mood", "MOOD", "MOODS") + .SelectMany(mood => mood.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + .Where(mood => !string.IsNullOrWhiteSpace(mood)) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + replayGainTrackGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_GAIN", "replaygain_track_gain")); + replayGainTrackPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_PEAK", "replaygain_track_peak")); + replayGainAlbumGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_GAIN", "replaygain_album_gain")); + replayGainAlbumPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_PEAK", "replaygain_album_peak")); + } } } catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException) @@ -330,6 +339,7 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe Channels = channels, BitDepth = bitDepth, AudioCodec = audioCodec, + Container = container, Bitrate = bitrate, AcoustId = acoustId, ReplayGainTrackGain = replayGainTrackGain, @@ -348,6 +358,17 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe }; } + /// + /// Determines whether the file stored at is a reparse point, such as a symbolic link. + /// + /// The file system path of the file to check. + /// when the file is a reparse point, otherwise . + private static bool IsReparsePoint(string path) + { + // This only detects a leaf file that is itself a link; a linked directory encountered during discovery is not caught here. + return (File.GetAttributes(path) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint; + } + /// /// Parses the provided tag as a globally unique identifier. /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs index fedd2b40..1aeb6945 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs @@ -460,6 +460,7 @@ public class AddAlbumEndpointSummary : Summary AlbumId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Container: "FLAC", Metadata: new( Title: "Bohemian Rhapsody", OriginalTitle: "Bohemian Rhapsody", @@ -244,6 +245,7 @@ public class GetAlbumEndpointSummary : Summary AlbumId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + Container: "FLAC", Metadata: new( Title: "You're My Best Friend", OriginalTitle: "You're My Best Friend", diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs index e9c3f688..55af03b5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs @@ -33,6 +33,7 @@ public class GetAlbumTracksEndpointSummary : Summary(r => r.AlbumId, "The Id of the album the track belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Container, "The container of the audio file of the track, if applicable."); ResponseParam(r => r.Metadata!.Title, "The title of the track."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); @@ -80,6 +81,7 @@ public class GetAlbumTracksEndpointSummary : Summary AlbumId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Container: "FLAC", Metadata: new( Title: "Bohemian Rhapsody", OriginalTitle: "Bohemian Rhapsody", diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs index 4d4546b0..0bf63d72 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs @@ -154,6 +154,7 @@ public class GetArtistAlbumsEndpointSummary : Summary(r => r.AlbumId, "The Id of the album the track belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Container, "The container of the audio file of the track, if applicable."); ResponseParam(r => r.Metadata!.Title, "The title of the track."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); @@ -215,6 +216,7 @@ public class AddTrackEndpointSummary : Summary ResponseParam(r => r.AlbumId, "The Id of the album the track belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Container, "The container of the audio file of the track, if applicable."); ResponseParam(r => r.Metadata!.Title, "The title of the track."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); @@ -78,6 +79,7 @@ public class GetTrackEndpointSummary : Summary AlbumId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Container: "FLAC", Metadata: new MusicTrackMetadataDto( Title: "Bohemian Rhapsody", OriginalTitle: "Bohemian Rhapsody", diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs index 38595b03..6544de1b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs @@ -168,6 +168,7 @@ public class UpdateTrackEndpointSummary : Summary(r => r.AlbumId, "The Id of the album the track belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Container, "The container of the audio file of the track, if applicable."); ResponseParam(r => r.Metadata!.Title, "The title of the track."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); @@ -213,6 +214,7 @@ public class UpdateTrackEndpointSummary : SummaryOptional. The MusicBrainz identifier of the work. /// Optional. The title of the work. /// Whether the MusicBrainz identifiers and the work title should be included, or forced to . + /// Whether the container should be included, or forced to . /// The created . public MusicLibraryScanItemMetadataEntity Create( Guid? id = null, @@ -58,7 +59,8 @@ public class MusicLibraryScanItemMetadataEntityFixture Guid? musicBrainzTrackId = null, Guid? musicBrainzWorkId = null, string? workTitle = null, - bool includeMusicBrainzTags = true) + bool includeMusicBrainzTags = true, + bool includeContainer = true) { return new MusicLibraryScanItemMetadataEntity { @@ -78,6 +80,7 @@ public class MusicLibraryScanItemMetadataEntityFixture Channels = _faker.PickRandom(1, 2, 6), BitDepth = Random.Shared.Next(8, 32), AudioCodec = _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC"), + Container = includeContainer ? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV") : null, Bitrate = Random.Shared.Next(96, 1411), MusicBrainzArtistId = includeMusicBrainzTags ? musicBrainzArtistId ?? Guid.NewGuid() : null, MusicBrainzReleaseArtistId = includeMusicBrainzTags ? musicBrainzReleaseArtistId ?? Guid.NewGuid() : null, diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs index 2fda1e88..77cc1a55 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs @@ -37,6 +37,7 @@ public class TrackEntityFixture /// Optional. The Id of the media library that owns the track. /// Optional. The file system path of the track. /// Optional. The title of the track. + /// Optional. The container of the audio file of the track. /// Optional. The number of the track on its disc. /// Optional. The original release date of the track. /// Optional. The original release year of the track. @@ -47,6 +48,7 @@ public class TrackEntityFixture /// Whether the original release year should be included, or forced to . /// Whether the re-release date should be included, or forced to . /// Whether the re-release year should be included, or forced to . + /// Whether the container should be included, or forced to . /// Optional. The metadata enrichment status of the track. /// The created . public TrackEntity Create( @@ -55,6 +57,7 @@ public class TrackEntityFixture Guid? libraryId = null, string? path = null, string? title = null, + string? container = null, int? trackNumber = null, DateOnly? originalReleaseDate = null, int? originalReleaseYear = null, @@ -65,6 +68,7 @@ public class TrackEntityFixture bool includeOriginalReleaseYear = true, bool includeReReleaseDate = true, bool includeReReleaseYear = true, + bool includeContainer = true, MetadataStatus? metadataStatus = null) { Guid resolvedId = id ?? Guid.NewGuid(); @@ -111,6 +115,7 @@ public class TrackEntityFixture .RuleFor(x => x.Channels, f => f.PickRandom(1, 2, 6)) .RuleFor(x => x.BitDepth, Random.Shared.Next(8, 32)) .RuleFor(x => x.AudioCodec, f => f.PickRandom("FLAC", "MP3", "AAC", "ALAC")) + .RuleFor(x => x.Container, f => includeContainer ? (container ?? f.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV")) : null) .RuleFor(x => x.Bitrate, Random.Shared.Next(96, 1411)) .RuleFor(x => x.TrackNumber, f => trackNumber ?? f.Random.Int(1, 20)) .RuleFor(x => x.DiscNumber, Random.Shared.Next(1, 3)) diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs index bc191ac6..0baf2b54 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs @@ -61,6 +61,7 @@ public class AudioMetadataDtoFixture /// Optional. The number of audio channels. /// Optional. The bit depth of the audio. /// Optional. The audio codec used. + /// Optional. The container of the audio file. /// Optional. The bitrate of the audio, in kbps. /// Optional. The MusicBrainz identifier of the recording. /// Optional. The MusicBrainz identifier of the track. @@ -86,6 +87,7 @@ public class AudioMetadataDtoFixture /// Whether the channels should be included, or forced to . /// Whether the bit depth should be included, or forced to . /// Whether the audio codec should be included, or forced to . + /// Whether the container should be included, or forced to . /// Whether the bitrate should be included, or forced to . /// Whether the MusicBrainz recording Id should be included, or forced to . /// Whether the MusicBrainz track Id should be included, or forced to . @@ -114,6 +116,7 @@ public class AudioMetadataDtoFixture int? channels = null, int? bitDepth = null, string? audioCodec = null, + string? container = null, int? bitrate = null, Guid? musicBrainzRecordingId = null, Guid? musicBrainzTrackId = null, @@ -139,6 +142,7 @@ public class AudioMetadataDtoFixture bool includeChannels = true, bool includeBitDepth = true, bool includeAudioCodec = true, + bool includeContainer = true, bool includeBitrate = true, bool includeMusicBrainzRecordingId = true, bool includeMusicBrainzTrackId = true, @@ -167,6 +171,7 @@ public class AudioMetadataDtoFixture includeChannels ? (channels ?? _faker.Random.Int(1, 8)) : null, includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null, includeAudioCodec ? (audioCodec ?? _faker.Random.ArrayElement(["FLAC", "MP3", "AAC", "ALAC"])) : null, + includeContainer ? (container ?? _faker.Random.ArrayElement(["MP3", "FLAC", "OGG", "MP4", "AAC", "WAV"])) : null, includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null, includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null, includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs index b79eb390..b575d2ab 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs @@ -39,6 +39,7 @@ public class TrackResponseFixture /// Optional. The Id of the album the track belongs to. /// Optional. The Id of the media library this track belongs to. /// Optional. The file system path of the track. + /// Optional. The container of the audio file of the track. /// Optional. The audio metadata of the track. /// Optional. The number of the track on its disc. /// Optional. The number of the disc the track belongs to. @@ -56,6 +57,7 @@ public class TrackResponseFixture /// Optional. The list of ratings of the track. /// Whether the MusicBrainz recording Id should be included, or forced to . /// Whether the MusicBrainz track Id should be included, or forced to . + /// Whether the container should be included, or forced to . /// The created . public TrackResponse Create( Guid? id = null, @@ -78,7 +80,9 @@ public class TrackResponseFixture List? contributors = null, List? ratings = null, bool includeMusicBrainzRecordingId = true, - bool includeMusicBrainzTrackId = true) + bool includeMusicBrainzTrackId = true, + bool includeContainer = true, + string? container = null) { return new TrackResponse( id ?? Guid.NewGuid(), @@ -99,7 +103,8 @@ public class TrackResponseFixture moods ?? _moodDtoFixture.CreateMany(1), isrcs ?? _isrcDtoFixture.CreateMany(1), contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1), - ratings ?? _audioRatingDtoFixture.CreateMany(1)); + ratings ?? _audioRatingDtoFixture.CreateMany(1), + includeContainer ? (container ?? _faker.Random.ArrayElement(["MP3", "FLAC", "OGG", "MP4", "AAC", "WAV"])) : null); } /// diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataFixture.cs index f8c4be25..6f695795 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataFixture.cs @@ -39,6 +39,7 @@ public class AudioMetadataFixture /// Optional. The original language of the audio. /// Optional. The bit depth of the audio. /// Optional. The audio codec used. + /// Optional. The container of the audio. /// Optional. The bitrate of the audio, in kbps. /// Optional. The AcoustID fingerprint identifier of the audio file. /// Optional. The ReplayGain track gain, in decibels. @@ -60,6 +61,7 @@ public class AudioMetadataFixture Optional? originalLanguage = null, Optional? bitDepth = null, Optional? audioCodec = null, + Optional? container = null, Optional? bitrate = null, Optional? acoustId = null, Optional? replayGainTrackGain = null, @@ -81,6 +83,7 @@ public class AudioMetadataFixture originalLanguage ?? Optional.None(), bitDepth ?? Optional.Some(_faker.Random.Int(8, 32)), audioCodec ?? Optional.Some("PCM"), + container ?? Optional.Some(_faker.PickRandom("MP3", "FLAC", "OGG", "MP4", "AAC", "WAV")), bitrate ?? Optional.Some(_faker.Random.Int(128, 320)), acoustId ?? Optional.None(), replayGainTrackGain ?? Optional.None(), diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs new file mode 100644 index 00000000..c5524ced --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs @@ -0,0 +1,309 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains integration tests for the class, probing real audio containers through the tagging library. +/// +[ExcludeFromCodeCoverage] +public class MusicMetadataExtractionJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMusicLibraryScanItemMetadataRepository _mockMusicMetadataRepository; + private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; + private readonly ILibraryPathTemplateService _mockPathTemplateService; + private readonly IPathService _mockPathService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly MusicMetadataExtractionJob _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryId _libraryId; + private readonly ScanId _scanId; + private readonly UserId _userId; + + /// + /// Initializes a new instance of the class. + /// + public MusicMetadataExtractionJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository = Substitute.For(); + _mockMusicMetadataRepository = Substitute.For(); + _mockStagingResultsRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicMetadataRepository); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockPathTemplateService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + _mockServiceProvider.GetService(typeof(ILibraryPathTemplateService)).Returns(_mockPathTemplateService); + _mockServiceProvider.GetService(typeof(IPathService)).Returns(_mockPathService); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + // Default stubs that keep the happy path working, overridden per test where needed. + _mockMusicMetadataRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Created); + _mockPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(_libraryPathTemplateFixture.Create())); + _mockPathTemplateService.Parse(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.From>(Optional.None())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(true); + _mockPathService.GetFileNameWithoutExtension(Arg.Any()).Returns("tone"); + _mockPathService.GetFileName(Arg.Any()).Returns("tone.wav"); + + _libraryId = _libraryIdFixture.Create(); + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _sut = new MusicMetadataExtractionJob(_mockServiceScopeFactory, Substitute.For>()) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenTheFileIsARealAudioFile_ShouldCaptureItsContainerAndAudioProperties() + { + // Arrange + using TemporaryMediaDirectory temporaryMediaDirectory = new(); + string audioFilePath = temporaryMediaDirectory.CreateWavFile("tone.wav"); + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Music, + contentLocations: [temporaryMediaDirectory.Path]); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([audioFilePath])); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockMusicMetadataRepository.Received(1).InsertRangeAsync( + Arg.Is>(items => items.Count == 1 + && items.First().Container == "WAV" + && items.First().SampleRate == 8000 + && items.First().Channels == 1 + && items.First().BitDepth == 16), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheContainerHasNoDedicatedParser_ShouldFallBackToTheMimeTypeName() + { + // Arrange + using TemporaryMediaDirectory temporaryMediaDirectory = new(); + string imageFilePath = temporaryMediaDirectory.CreatePngFile("cover.png"); + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Music, + contentLocations: [temporaryMediaDirectory.Path]); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([imageFilePath])); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockMusicMetadataRepository.Received(1).InsertRangeAsync( + Arg.Is>(items => items.Count == 1 + && items.First().Container == "PNG"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFileIsAReparsePoint_ShouldNotReadTheLinkedFile() + { + // Arrange + using TemporaryMediaDirectory temporaryMediaDirectory = new(); + using TemporaryMediaDirectory outsideMediaDirectory = new(); + string targetFilePath = outsideMediaDirectory.CreateWavFile("target.wav"); + string linkFilePath = System.IO.Path.Combine(temporaryMediaDirectory.Path, "link.wav"); + if (!TryCreateFileSymbolicLink(linkFilePath, targetFilePath)) + return; // The environment does not support creating file symbolic links. + + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Music, + contentLocations: [temporaryMediaDirectory.Path]); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([linkFilePath])); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // The linked file lives outside the content location, so its audio metadata must not be read: the container stays unrecognized. + await _mockMusicMetadataRepository.Received(1).InsertRangeAsync( + Arg.Is>(items => items.Count == 1 + && items.First().Container == null + && items.First().SampleRate == 0), + Arg.Any()); + } + + /// + /// Creates a file system symbolic link that points to the target file. + /// + /// The file system path of the symbolic link to create. + /// The file system path of the file the link points to. + /// when the link was created, otherwise. + private static bool TryCreateFileSymbolicLink(string linkPath, string targetPath) + { + try + { + File.CreateSymbolicLink(linkPath, targetPath); + return true; + } + catch (Exception) + { + // Creating a file symbolic link requires elevated privileges on Windows, so the environment may not support it. + return false; + } + } + + /// + /// Test helper managing a temporary directory holding real media files, deleted when the test finishes. + /// + private sealed class TemporaryMediaDirectory : IDisposable + { + /// + /// A minimal, valid, one by one pixel PNG image, used to exercise a container that has no dedicated parser. + /// + private const string PNG_BYTES = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAANSURBVBhXY2BgYGAAAAAFAAGKM+MAAAAAAElFTkSuQmCC"; + + private bool _disposed; + + /// + /// Initializes a new instance of the class. + /// + public TemporaryMediaDirectory() + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-music-probe-{Guid.NewGuid():N}"); + Directory.CreateDirectory(Path); + } + + /// + /// Gets the full path of the temporary directory. + /// + public string Path { get; } + + /// + /// Writes a minimal, valid, one second long 16 bit PCM mono 8000 Hz WAV file into the temporary directory. + /// + /// The name of the WAV file to create. + /// The full path of the created WAV file. + public string CreateWavFile(string fileName) + { + const int SAMPLE_RATE = 8000; + const short CHANNELS = 1; + const short BITS_PER_SAMPLE = 16; + int blockAlign = CHANNELS * (BITS_PER_SAMPLE / 8); + int dataSize = SAMPLE_RATE * blockAlign; + string filePath = System.IO.Path.Combine(Path, fileName); + + using (FileStream stream = new(filePath, FileMode.Create, FileAccess.Write)) + using (BinaryWriter writer = new(stream)) + { + writer.Write("RIFF"u8.ToArray()); + writer.Write(36 + dataSize); + writer.Write("WAVE"u8.ToArray()); + writer.Write("fmt "u8.ToArray()); + writer.Write(16); + writer.Write((short)1); + writer.Write(CHANNELS); + writer.Write(SAMPLE_RATE); + writer.Write(SAMPLE_RATE * blockAlign); + writer.Write((short)blockAlign); + writer.Write(BITS_PER_SAMPLE); + writer.Write("data"u8.ToArray()); + writer.Write(dataSize); + writer.Write(new byte[dataSize]); + } + return filePath; + } + + /// + /// Writes a minimal, valid PNG image into the temporary directory. + /// + /// The name of the PNG file to create. + /// The full path of the created PNG file. + public string CreatePngFile(string fileName) + { + string filePath = System.IO.Path.Combine(Path, fileName); + File.WriteAllBytes(filePath, Convert.FromBase64String(PNG_BYTES)); + return filePath; + } + + /// + /// Deletes the temporary directory, ignoring the failures of the files that are still in use. + /// + public void Dispose() + { + if (_disposed) + return; + try + { + Directory.Delete(Path, recursive: true); + } + catch (IOException) + { + // Best effort cleanup of the temporary directory. + } + _disposed = true; + } + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs index e2b37e9b..1e103b8c 100644 --- a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs @@ -56,6 +56,7 @@ public class Id3TrackMetadataProviderTests : IDisposable Assert.Equal("The Track", result.Title); Assert.Equal(MusicKey.CSharpMinor, result.Key); Assert.Equal(128, result.Bpm); + Assert.Equal("WAV", result.Container); Assert.NotNull(result.Contributors); Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Artist"); } diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs index 60a4a815..c2510756 100644 --- a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs @@ -15,6 +15,11 @@ namespace Lumina.Plugins.ID3.IntegrationTests.Core.Tags; [ExcludeFromCodeCoverage] public class Id3TagReaderTests : IDisposable { + /// + /// A minimal, valid, one by one pixel PNG image, used to exercise a container that has no dedicated parser. + /// + private const string PNG_BYTES = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAANSURBVBhXY2BgYGAAAAAFAAGKM+MAAAAAAElFTkSuQmCC"; + private readonly Id3TagReader _sut = new(); private readonly string _temporaryDirectory; @@ -131,6 +136,7 @@ public class Id3TagReaderTests : IDisposable Assert.Equal(16, result.BitDepth); Assert.True(result.Bitrate > 0); Assert.Equal("PCM Audio", result.AudioCodec); + Assert.Equal("WAV", result.Container); Assert.Equal("https://artist.example", result.Website); Assert.Equal(artistId.ToString(), result.MusicBrainzArtistId); Assert.Equal(releaseArtistId.ToString(), result.MusicBrainzReleaseArtistId); @@ -192,6 +198,7 @@ public class Id3TagReaderTests : IDisposable Assert.Equal(1, result.Channels); Assert.Equal(16, result.BitDepth); Assert.Equal("PCM Audio", result.AudioCodec); + Assert.Equal("WAV", result.Container); Assert.Null(result.Website); Assert.Null(result.MusicBrainzArtistId); Assert.Null(result.MusicBrainzReleaseArtistId); @@ -216,6 +223,21 @@ public class Id3TagReaderTests : IDisposable Assert.Null(result); } + [Fact] + public void Read_WhenTheContainerHasNoDedicatedParser_ShouldFallBackToTheMimeTypeName() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "cover.png"); + File.WriteAllBytes(path, Convert.FromBase64String(PNG_BYTES)); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("PNG", result.Container); + } + [Fact] public void Read_WhenCalledTwiceForTheSamePath_ShouldReturnTheCachedSnapshot() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs index a3463b17..d373afcf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs @@ -284,6 +284,30 @@ public class UpdateArtistCommandMappingTests Assert.Equal(disambiguation, updatedTrack.Disambiguation.Value); } + [Fact] + public void ToDomainEntity_WhenTheTrackMetadataCarriesNoContainer_ShouldKeepTheTrackContainer() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddTrackCommand trackCommand = _addTrackCommandFixture.Create(trackId: trackId); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [trackCommand]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); + // The stored container is pinned to a known value, so the assertion cannot pass by coincidence. + // The container is captured from the file itself, so reconciling a track during an artist edit keeps the stored container. + Assert.Equal("FLAC", updatedTrack.Metadata.Container.Value); + } + /// /// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to . /// @@ -296,7 +320,7 @@ public class UpdateArtistCommandMappingTests AlbumEntity albumEntity = _albumEntityFixture.Create( id: albumId, libraryId: libraryId, - tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]); + tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, container: "FLAC")]); ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]); Result artistResult = artistEntity.ToDomainEntity(); return (artistResult.Value, albumId, trackId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMappingTests.cs index bebae835..0dac3fd4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMappingTests.cs @@ -50,6 +50,7 @@ public class AudioMetadataDtoMappingTests Assert.Equal(dto.Channels, track.Metadata.Channels); Assert.Equal(dto.BitDepth, track.Metadata.BitDepth.Value); Assert.Equal(dto.AudioCodec, track.Metadata.AudioCodec.Value); + Assert.Equal(dto.Container, track.Metadata.Container.Value); Assert.Equal(dto.Bitrate, track.Metadata.Bitrate.Value); Assert.True(track.Script.HasValue); Assert.Equal(dto.Script, track.Script.Value); @@ -80,12 +81,14 @@ public class AudioMetadataDtoMappingTests int storedChannels = track.Metadata.Channels; bool hadStoredWork = track.Work.HasValue; int storedIsrcCount = track.Isrcs.Count; + string? storedContainer = track.Metadata.Container.HasValue ? track.Metadata.Container.Value : null; AudioMetadataDto dto = _audioMetadataDtoFixture.Create( includeDurationInSeconds: false, includeSampleRate: false, includeChannels: false, includeBitDepth: false, includeAudioCodec: false, + includeContainer: false, includeBitrate: false, includeWork: false, includeIsrcs: false, @@ -99,6 +102,7 @@ public class AudioMetadataDtoMappingTests Assert.Equal(storedDuration, track.Metadata.DurationInSeconds); Assert.Equal(storedSampleRate, track.Metadata.SampleRate); Assert.Equal(storedChannels, track.Metadata.Channels); + Assert.Equal(storedContainer, track.Metadata.Container.HasValue ? track.Metadata.Container.Value : null); Assert.Equal(hadStoredWork, track.Work.HasValue); Assert.Equal(storedIsrcCount, track.Isrcs.Count); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMappingTests.cs index 43fb03f8..140ecfe7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMappingTests.cs @@ -27,7 +27,7 @@ public class MusicTrackMetadataDtoMappingTests private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly() + public void ToDomainValueObject_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly() { // Arrange MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(); @@ -70,6 +70,8 @@ public class MusicTrackMetadataDtoMappingTests Assert.Equal(dto.BitDepth, metadata.BitDepth.Value); Assert.True(metadata.AudioCodec.HasValue); Assert.Equal(dto.AudioCodec, metadata.AudioCodec.Value); + // The container is captured locally from the file itself, so it can never be set through the metadata of a request. + Assert.False(metadata.Container.HasValue); Assert.True(metadata.Bitrate.HasValue); Assert.Equal(dto.Bitrate, metadata.Bitrate.Value); Assert.Equal(dto.Genres!.Select(genre => genre.Name), metadata.Genres.Select(genre => genre.Name)); @@ -77,7 +79,7 @@ public class MusicTrackMetadataDtoMappingTests } [Fact] - public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults() + public void ToDomainValueObject_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults() { // Arrange MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create( @@ -123,7 +125,7 @@ public class MusicTrackMetadataDtoMappingTests } [Fact] - public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone() + public void ToDomainValueObject_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone() { // Arrange LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false); @@ -141,7 +143,7 @@ public class MusicTrackMetadataDtoMappingTests } [Fact] - public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError() + public void ToDomainValueObject_WhenReleaseInfoIsInvalid_ShouldReturnError() { // Arrange ReleaseInfoDto releaseInfo = _releaseInfoDtoFixture.Create( @@ -158,7 +160,7 @@ public class MusicTrackMetadataDtoMappingTests } [Fact] - public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError() + public void ToDomainValueObject_WhenGenreIsInvalid_ShouldReturnError() { // Arrange MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]); @@ -172,7 +174,7 @@ public class MusicTrackMetadataDtoMappingTests } [Fact] - public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError() + public void ToDomainValueObject_WhenTagIsInvalid_ShouldReturnError() { // Arrange MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMappingTests.cs index bf746994..88e4dfbb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMappingTests.cs @@ -74,6 +74,7 @@ public class TrackEntityMappingTests Assert.Equal(entity.Channels, track.Metadata.Channels); Assert.Equal(entity.BitDepth, track.Metadata.BitDepth.Value); Assert.Equal(entity.AudioCodec, track.Metadata.AudioCodec.Value); + Assert.Equal(entity.Container, track.Metadata.Container.Value); Assert.Equal(entity.Bitrate, track.Metadata.Bitrate.Value); Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), track.Metadata.Genres.Select(genre => genre.Name).OrderBy(name => name)); Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), track.Metadata.Tags.Select(tag => tag.Name).OrderBy(name => name)); @@ -95,6 +96,20 @@ public class TrackEntityMappingTests Assert.Equal(entity.UpdatedOnUtc, track.UpdatedOnUtc.Value); } + [Fact] + public void ToDomainEntity_WhenTheEntityHasNoContainer_ShouldMapMetadataWithoutAContainer() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create(includeContainer: false); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Metadata.Container.HasValue); + } + [Fact] public void ToDomainEntity_WhenReleaseDateAndYearDoNotMatch_ShouldReturnError() { @@ -226,6 +241,7 @@ public class TrackEntityMappingTests Assert.Equal(entity.Bitrate, result.Metadata.Bitrate); Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), result.Metadata.Tags!.Select(tag => tag.Name).OrderBy(name => name)); Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), result.Metadata.Genres!.Select(genre => genre.Name).OrderBy(name => name)); + Assert.Equal(entity.Container, result.Container); Assert.Equal(entity.TrackNumber, result.TrackNumber); Assert.Equal(entity.DiscNumber, result.DiscNumber); Assert.Equal(entity.Script, result.Script); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMappingTests.cs index 0483a1f4..03dfd3aa 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMappingTests.cs @@ -68,6 +68,7 @@ public class TrackMappingTests Assert.Equal(track.Metadata.Channels, result.Channels); Assert.Equal(track.Metadata.BitDepth.HasValue ? track.Metadata.BitDepth.Value : null, result.BitDepth); Assert.Equal(track.Metadata.AudioCodec.HasValue ? track.Metadata.AudioCodec.Value : null, result.AudioCodec); + Assert.Equal(track.Metadata.Container.HasValue ? track.Metadata.Container.Value : null, result.Container); Assert.Equal(track.Metadata.Bitrate.HasValue ? track.Metadata.Bitrate.Value : null, result.Bitrate); Assert.Equal(track.TrackNumber, result.TrackNumber); Assert.Equal(track.DiscNumber.HasValue ? track.DiscNumber.Value : null, result.DiscNumber); @@ -134,6 +135,7 @@ public class TrackMappingTests originalLanguage: Optional.None(), bitDepth: Optional.None(), audioCodec: Optional.None(), + container: Optional.None(), bitrate: Optional.None()); Track track = _trackFixture.Create( metadata: metadata, @@ -169,6 +171,7 @@ public class TrackMappingTests Assert.Null(result.OriginalLanguageNativeName); Assert.Null(result.BitDepth); Assert.Null(result.AudioCodec); + Assert.Null(result.Container); Assert.Null(result.Bitrate); Assert.Null(result.DiscNumber); Assert.Null(result.Script); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs index 5033efa8..1957b668 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs @@ -286,6 +286,32 @@ public class UpdateTrackCommandMappingTests Assert.False(updatedTrack.Disambiguation.HasValue); } + [Fact] + public void ToDomainEntity_WhenTheMetadataCarriesNoContainer_ShouldKeepTheTrackContainer() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + Track storedTrack = artist.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); + Optional storedContainer = storedTrack.Metadata.Container; + UpdateTrackCommand command = _updateTrackCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albumId: albumId.ToString(), + trackId: trackId.ToString()); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); + // The stored container is pinned to a known value, so the assertion cannot pass by coincidence. + Assert.Equal("FLAC", storedContainer.Value); + // The container is captured from the file itself and is never part of the edit metadata, so an update keeps the stored container. + Assert.Equal("FLAC", updatedTrack.Metadata.Container.Value); + } + /// /// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to . /// @@ -298,7 +324,7 @@ public class UpdateTrackCommandMappingTests AlbumEntity albumEntity = _albumEntityFixture.Create( id: albumId, libraryId: libraryId, - tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]); + tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, container: "FLAC")]); ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]); Result artistResult = artistEntity.ToDomainEntity(); return (artistResult.Value, albumId, trackId); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataTests.cs index 94947845..284893f1 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataTests.cs @@ -41,6 +41,7 @@ public class AudioMetadataTests Optional.None(), Optional.Some(16), Optional.Some("PCM"), + Optional.Some("WAV"), Optional.Some(1411), Optional.Some("f0e9c1a2-0000-0000-0000-000000000000"), Optional.Some(-6.53m), @@ -57,6 +58,7 @@ public class AudioMetadataTests Assert.Equal("A song by the British rock band Queen.", result.Value.Description.Value); Assert.Equal(16, result.Value.BitDepth.Value); Assert.Equal("PCM", result.Value.AudioCodec.Value); + Assert.Equal("WAV", result.Value.Container.Value); Assert.Equal(1411, result.Value.Bitrate.Value); Assert.Single(result.Value.Genres); Assert.Single(result.Value.Tags); @@ -80,6 +82,7 @@ public class AudioMetadataTests Optional.None(), Optional.None(), Optional.None(), + Optional.None(), Optional.None(), Optional.None(), Optional.None(), @@ -91,6 +94,7 @@ public class AudioMetadataTests Assert.False(result.IsFailure); Assert.False(result.Value.BitDepth.HasValue); Assert.False(result.Value.AudioCodec.HasValue); + Assert.False(result.Value.Container.HasValue); Assert.False(result.Value.Bitrate.HasValue); } @@ -115,6 +119,7 @@ public class AudioMetadataTests originalLanguage: Optional.None(), bitDepth: Optional.None(), audioCodec: Optional.None(), + container: Optional.None(), bitrate: Optional.None()); AudioMetadata secondResult = _audioMetadataFixture.Create( title: "Bohemian Rhapsody", @@ -130,6 +135,7 @@ public class AudioMetadataTests originalLanguage: Optional.None(), bitDepth: Optional.None(), audioCodec: Optional.None(), + container: Optional.None(), bitrate: Optional.None()); // Assert @@ -157,6 +163,7 @@ public class AudioMetadataTests originalLanguage: Optional.None(), bitDepth: Optional.None(), audioCodec: Optional.None(), + container: Optional.None(), bitrate: Optional.None()); AudioMetadata secondResult = _audioMetadataFixture.Create( title: "Bohemian Rhapsody", @@ -172,6 +179,7 @@ public class AudioMetadataTests originalLanguage: Optional.None(), bitDepth: Optional.None(), audioCodec: Optional.None(), + container: Optional.None(), bitrate: Optional.None()); // Assert @@ -200,6 +208,7 @@ public class AudioMetadataTests Optional.Some(originalLanguage), Optional.Some(16), Optional.Some("PCM"), + Optional.Some("WAV"), Optional.Some(1411), Optional.Some("f0e9c1a2-0000-0000-0000-000000000000"), Optional.Some(-6.53m), @@ -237,6 +246,7 @@ public class AudioMetadataTests Optional.None(), Optional.None(), Optional.None(), + Optional.None(), Optional.None(), Optional.None(), Optional.None(), @@ -271,6 +281,7 @@ public class AudioMetadataTests originalLanguage: Optional.None(), bitDepth: Optional.None(), audioCodec: Optional.None(), + container: Optional.None(), bitrate: Optional.None()); AudioMetadata secondResult = _audioMetadataFixture.Create( title: "Love of My Life", @@ -286,6 +297,7 @@ public class AudioMetadataTests originalLanguage: Optional.None(), bitDepth: Optional.None(), audioCodec: Optional.None(), + container: Optional.None(), bitrate: Optional.None()); // Assert @@ -334,6 +346,50 @@ public class AudioMetadataTests Assert.NotEqual(firstResult, secondResult); } + [Fact] + public void Equals_WithDifferentContainer_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AudioMetadata firstResult = _audioMetadataFixture.Create( + title: "Bohemian Rhapsody", + originalTitle: Optional.None(), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + container: Optional.Some("MP3"), + bitrate: Optional.None()); + AudioMetadata secondResult = _audioMetadataFixture.Create( + title: "Bohemian Rhapsody", + originalTitle: Optional.None(), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + container: Optional.Some("FLAC"), + bitrate: Optional.None()); + + // Assert + Assert.NotEqual(firstResult, secondResult); + } + [Fact] public void Equals_WithDifferentGenres_ShouldReturnFalse() { @@ -355,6 +411,7 @@ public class AudioMetadataTests originalLanguage: Optional.None(), bitDepth: Optional.None(), audioCodec: Optional.None(), + container: Optional.None(), bitrate: Optional.None()); AudioMetadata secondResult = _audioMetadataFixture.Create( title: "Bohemian Rhapsody", @@ -370,6 +427,7 @@ public class AudioMetadataTests originalLanguage: Optional.None(), bitDepth: Optional.None(), audioCodec: Optional.None(), + container: Optional.None(), bitrate: Optional.None()); // Assert diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs index 1487b4b6..7c7d26d8 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs @@ -239,6 +239,62 @@ public class TrackTests Assert.Equal(originalMoods, track.Moods); } + [Fact] + public void UpdateDetails_WhenTheMetadataCarriesNoContainer_ShouldKeepTheStoredContainer() + { + // Arrange + Track track = _trackFixture.Create(); + Optional storedContainer = track.Metadata.Container; + AudioMetadata metadata = _audioMetadataFixture.Create(container: Optional.None()); + + // Act + Result result = track.UpdateDetails( + metadata, + track.Disambiguation, + track.TrackNumber, + track.DiscNumber, + track.Script, + track.Key, + track.Bpm, + track.IsVideo, + track.Work, + track.MusicBrainzRecordingId, + track.MusicBrainzTrackId); + + // Assert + Assert.False(result.IsFailure); + // The container is captured from the file itself and is never part of an edit, so an update that does not carry one keeps the stored container. + Assert.Equal(storedContainer, track.Metadata.Container); + // The rest of the metadata still comes from the update. + Assert.Equal(metadata.Title, track.Metadata.Title); + } + + [Fact] + public void UpdateDetails_WhenTheMetadataCarriesAContainer_ShouldReplaceTheStoredContainer() + { + // Arrange + Track track = _trackFixture.Create(); + AudioMetadata metadata = _audioMetadataFixture.Create(container: Optional.Some("OGG")); + + // Act + Result result = track.UpdateDetails( + metadata, + track.Disambiguation, + track.TrackNumber, + track.DiscNumber, + track.Script, + track.Key, + track.Bpm, + track.IsVideo, + track.Work, + track.MusicBrainzRecordingId, + track.MusicBrainzTrackId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("OGG", track.Metadata.Container.Value); + } + [Fact] public void Create_WhenOptionalValuesAndCollectionsAreEmpty_ShouldCreateTrackWithoutThem() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolverTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolverTests.cs new file mode 100644 index 00000000..4899ef66 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolverTests.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AudioContainerResolverTests +{ + [Theory] + [InlineData(null, null)] // an absent mime type leaves the container unrecognized + [InlineData("", null)] // an empty mime type leaves the container unrecognized + [InlineData(" ", null)] // a blank mime type leaves the container unrecognized + [InlineData("taglib/wav", "WAV")] // the taglib prefix is dropped and the container is upper cased + [InlineData("taglib/png", "PNG")] // a container the resolver has no dedicated parser for still yields its name + [InlineData("audio/x-wavpack", "X-WAVPACK")] // the last segment of a standard mime type names the container + public void ResolveFromMimeType_WhenCalled_ShouldReturnTheContainerNamedByTheMimeType(string? mimeType, string? expectedContainer) + { + // Act + string? container = AudioContainerResolver.ResolveFromMimeType(mimeType); + + // Assert + Assert.Equal(expectedContainer, container); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs index ecd0616c..18351b82 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs @@ -91,6 +91,34 @@ public class MusicMetadataAggregatorTests Assert.Equal(360, merged.DurationInSeconds); } + [Fact] + public void Merge_WhenTheFirstAudioMetadataHasAContainer_ShouldKeepTheFirstContainer() + { + // Arrange + AudioMetadataDto first = _audioMetadataDtoFixture.Create(container: "MP3"); + AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC"); + + // Act + AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("MP3", merged.Container); + } + + [Fact] + public void Merge_WhenTheFirstAudioMetadataHasNoContainer_ShouldTakeTheSecondContainer() + { + // Arrange + AudioMetadataDto first = _audioMetadataDtoFixture.Create(includeContainer: false); + AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC"); + + // Act + AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("FLAC", merged.Container); + } + [Fact] public void Merge_WhenTheFirstMetadataHasOnlyAReleaseYearAndTheSecondHasAReleaseDate_ShouldDeriveTheYearFromTheDate() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs index 1b2a54ac..4d00580e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs @@ -116,6 +116,33 @@ public class MusicMediaLibraryScanItemMaterializerTests AlbumEntity secondAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == secondReleaseId); Assert.Equal(firstRecordingId, Assert.Single(firstAlbum.Tracks).MusicBrainzRecordingId); Assert.Equal(secondRecordingId, Assert.Single(secondAlbum.Tracks).MusicBrainzRecordingId); + // The container read from the file itself is carried from the staged metadata to the materialized track. + Assert.Equal(firstStagedItem.Container, Assert.Single(firstAlbum.Tracks).Container); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenTheStagedItemHasNoContainer_ShouldMaterializeTheTrackWithoutAContainer() + { + // Arrange + MusicLibraryScanItemMetadataEntity stagedItem = _musicLibraryScanItemMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Some Artist", + releaseName: "Some Release", + path: "/music/some-artist/some-release/track.mp3", + includeMusicBrainzTags: false, + includeContainer: false); + _mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any()) + .Returns(Result.From>([stagedItem])); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [stagedItem.Path], CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + ArtistEntity artist = Assert.Single(_insertedArtists); + AlbumEntity album = Assert.Single(artist.Albums); + // A file whose container the scan could not recognize materializes its track without a container, rather than failing the scan. + Assert.Null(Assert.Single(album.Tracks).Container); } [Fact] diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/AudioContainerResolverTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/AudioContainerResolverTests.cs new file mode 100644 index 00000000..009a26da --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/AudioContainerResolverTests.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.ID3.Core.Tags; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core.Tags; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AudioContainerResolverTests +{ + [Theory] + [InlineData(null, null)] // an absent mime type leaves the container unrecognized + [InlineData("", null)] // an empty mime type leaves the container unrecognized + [InlineData(" ", null)] // a blank mime type leaves the container unrecognized + [InlineData("taglib/wav", "WAV")] // the taglib prefix is dropped and the container is upper cased + [InlineData("taglib/png", "PNG")] // a container the resolver has no dedicated parser for still yields its name + [InlineData("audio/x-wavpack", "X-WAVPACK")] // the last segment of a standard mime type names the container + public void ResolveFromMimeType_WhenCalled_ShouldReturnTheContainerNamedByTheMimeType(string? mimeType, string? expectedContainer) + { + // Act + string? container = AudioContainerResolver.ResolveFromMimeType(mimeType); + + // Assert + Assert.Equal(expectedContainer, container); + } +} From f97c5bed474b4c96deec04effbcef315c1a08ccd Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 14 Oct 2026 13:40:44 +0300 Subject: [PATCH 07/77] Removes redundant qualifiers and a cast from the track stream endpoint Drops the redundant FastEndpoints namespace qualification of EmptyRequest and the redundant cast of the audio byte array length in the stream endpoint and its tests. --- .../Tracks/GetTrackStream/GetTrackStreamEndpoint.cs | 4 ++-- .../Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs index 89971766..5e930410 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs @@ -21,7 +21,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra /// /// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream route. /// -public class GetTrackStreamEndpoint : BaseEndpoint +public class GetTrackStreamEndpoint : BaseEndpoint { private readonly IQueryHandler> _getTrackStreamQueryHandler; @@ -55,7 +55,7 @@ public class GetTrackStreamEndpoint : BaseEndpoint /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { // Take unique identifiers from the route. string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs index 94c3dfea..272bf56a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs @@ -80,7 +80,7 @@ public class GetTrackStreamEndpointTests : IClassFixture Date: Thu, 15 Oct 2026 09:19:36 +0300 Subject: [PATCH 08/77] Adds the playback delivery decision service --- .../architecture-decision-record-0016.md | 84 ++++++ docs/technical/domain/UbiquitousLanguage.md | 5 + .../Playback/PlaybackCapabilityDto.cs | 16 + .../Playback/PlaybackDeliveryDecisionDto.cs | 23 ++ .../Playback/PlaybackSourceFormatDto.cs | 16 + .../Playback/IPlaybackFormatService.cs | 25 ++ .../Playback/PlaybackCapabilitiesParser.cs | 76 +++++ .../Enums/Playback/PlaybackDeliveryMode.cs | 22 ++ .../Enums/Playback/PlaybackDeliveryShape.cs | 18 ++ .../Common/Errors/Errors.Playback.cs | 16 + .../InfrastructureLayerServices.cs | 6 + .../Playback/PlaybackFormatService.cs | 182 +++++++++++ src/Lumina.sln | 1 + .../Playback/PlaybackCapabilityDtoFixture.cs | 43 +++ .../PlaybackSourceFormatDtoFixture.cs | 47 +++ .../PlaybackCapabilitiesParserTests.cs | 86 ++++++ .../InfrastructureLayerServicesTests.cs | 3 + .../Playback/PlaybackFormatServiceTests.cs | 283 ++++++++++++++++++ 18 files changed, 952 insertions(+) create mode 100644 docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs create mode 100644 src/Lumina.Domain/Common/Errors/Errors.Playback.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDtoFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParserTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatServiceTests.cs diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md new file mode 100644 index 00000000..d7a638a7 --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md @@ -0,0 +1,84 @@ +# Architecture Decision Record (ADR): 0016 - Playback Delivery Decision and Player Capability Negotiation + +## Status + +**Accepted** (2026-10-14) + +## Context + +Lumina's music player is implemented from scratch, on WebCodecs for decoding and the Web Audio API for output, with no `HTMLMediaElement` and no Media Source Extensions. That player can only demux a curated set of containers and decode a curated set of codecs, so the server has to tell it, before it fetches any audio, whether a track can be played as stored or whether the server has to change the container or the codec first. + +The server already has each track's stored probe result (the container and the codec, plus the sample rate, the channels, the bit depth, the duration and the ReplayGain values) and a stream endpoint with HTTP range support that serves the original file. What is missing is the decision itself and a way for the player to state what it can play. + +## Decision + +Introduce a playback format service (`IPlaybackFormatService`, `PlaybackFormatService`) that, given the container and the codec of a track as read from its stored probe result and the capabilities a player advertises, decides one of three delivery modes: direct play, remux, or transcode. It stays in the Application layer (interface) and the Infrastructure layer (implementation), as a service: the byte and codec pipeline is not part of the playback domain aggregate. + +### Delivery modes + +| Mode | Condition | Delivery format | Delivery shape | +|---|---|---|---| +| Direct play | The player can demux the stored container and decode the stored codec | The stored container and codec, unchanged | Byte range seekable | +| Remux | The player can decode the stored codec but has no demuxer for the stored container | The stored codec, repackaged into a server container the player can demux | Time addressed segments | +| Transcode | The player cannot decode the stored codec | The most preferred codec the server can produce that the player advertises | Time addressed segments | + +- The stored codec is the free form description reported by the probe (for example `MPEG-1 Layer 3`), so it is canonicalized to the codec name players advertise (for example `MP3`) before it is compared. The MPEG layer is matched by its layer number only (`LAYER 3`/`LAYER III`), so `MPEG-1 Layer 1` and `MPEG-1 Layer 2` are not mistaken for `MP3`, and a description that names no recognizable codec is left as it is, which keeps it from matching any advertised codec and forces a transcode. Containers are canonicalized by casing. +- The container a normalized delivery is produced in is always chosen from the containers the server can produce for the codec, never from the container the player names: the player only selects among the server's known containers, so a container supplied by a client never reaches the transcoder or a cache name. The containers the server produces each codec in are, in order of preference: `PCM` in `WAV`, `MP3` in `MP3`, `FLAC` in `FLAC`, `Opus` and `Vorbis` in `OGG`, `AAC` in `MP4` then `AAC`. +- The server can produce, in order of preference, `AAC`, `OPUS`, `MP3`, `VORBIS`, `FLAC` and `PCM` (the efficient lossy codecs before the lossless ones, and uncompressed last), so a transcode re-encodes to the first of these the player advertises in one of its containers. When the player advertises no producible codec, the decision fails with `NoSupportedPlaybackFormat`, which is a forbidden outcome (HTTP 403) rather than a malformed request, and no delivery is attempted. + +### Capability input convention + +The capabilities a player can demux and decode directly are carried on the playback manifest request as a query parameter named `capabilities`, whose value is a comma separated list of `container/codec` pairs: + +``` +GET /api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac +``` + +- The container and the codec of a pair are matched case insensitively, and surrounding whitespace is ignored. +- A pair must name both a container and a codec, with neither empty (for example `flac`, `a/b/c` and `a//b` are ignored). +- At most 32 pairs are read from one request, so the parsing work stays bounded regardless of the input length. +- When the parameter is absent, empty, or lists no valid pair, the server applies the default capabilities of the bundled player, so a request that advertises nothing still gets a playable decision: + `mp3/mp3`, `flac/flac`, `ogg/opus`, `ogg/vorbis`, `wav/pcm`, `aac/aac`. The default set is the bundled player's demuxer set (MP3, AAC/ADTS, FLAC, OGG and WAV, from work order 14), so it deliberately contains no `mp4/aac` pair: a track stored in MP4 is remuxed to raw AAC for a request that advertises nothing, rather than being marked direct play for a container the bundled player cannot demux. +- The convention is a query parameter rather than a request header, so that it is part of the request's own contract, is trivially testable, and is forwarded by the web app's manifest proxy without depending on header forwarding. + +### Delivery shape + +The `TimeAddressedSegments` delivery shape is a sequence of fixed duration segments addressed and seeked by time, so that finding a time never requires mapping a byte range to it. The segment duration is 6 seconds, and it is carried in the delivery decision so that the producer of the segments and the player agree on it. Direct play is `ByteRangeSeekable`, because the original file is served by the existing range-capable stream endpoint. + +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|---|---| +| Decoupling | The player states what it can play and never has to know the server's codecs; the server states the delivery and never has to know the player's implementation | +| Efficiency | A container a player cannot demux but a codec it can decode is repackaged instead of re-encoded, and only a genuinely unsupported codec is re-encoded | +| Determinism | The containers the server produces each codec in and the transcode preference order are fixed, so the same input always yields the same delivery | +| Seekability | Time addressed segments make a normalized delivery seekable without a byte to time index | +| Testability | The decision is a pure function of the stored container and codec and the advertised capabilities | + +### Risks and Mitigations + +| Risk | Mitigation Strategy | +|---|---| +| The probe reports a codec as a free form description that does not name the codec the player advertises | The stored description is canonicalized to the advertised codec names before comparison, and the MPEG layer is matched by its layer number, so a description that names no decodable codec is left unmatched and forces a transcode | +| A player advertises a container the server cannot produce | The delivered container is always chosen from the containers the server produces the codec in, never from the container the player names, so a client supplied container never reaches the transcoder or a cache name; a codec the player cannot be served in any server container is not used | +| The segment duration drifts between the server and the player | It is part of the delivery decision carried by the manifest, not a constant duplicated on both sides | + +## Alternatives Considered + +### 1. Decide the delivery from the container only + +**Rejected**: a container can carry several codecs (for example `OGG` carries both Vorbis and Opus), so the container alone cannot tell whether the player can decode the audio, and the difference between a remux and a transcode would be lost. + +### 2. Let the player decide, by sending its full codec support to the server and reading the probe result itself + +**Rejected**: it leaks the server's storage and probe details to the client and duplicates the decision on both sides. The server owns the probe result and the producible formats. + +### 3. Carry the capabilities in a request header + +**Rejected**: a header has to be explicitly forwarded by the web app's manifest proxy and is harder to exercise from a browser or a request file than a query parameter, with no benefit that a query parameter does not already provide. + +### 4. Deliver a remuxed track as a single byte range seekable file instead of segments + +**Rejected**: it makes remuxed and transcoded tracks two different delivery shapes for the player to consume, and it reintroduces the byte to time mapping the time addressed shape exists to avoid. Both normalized deliveries use the same shape. diff --git a/docs/technical/domain/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md index 9bae25bd..ee4eefe1 100644 --- a/docs/technical/domain/UbiquitousLanguage.md +++ b/docs/technical/domain/UbiquitousLanguage.md @@ -11,6 +11,11 @@ - _**Stream**_: A media item accessed via streaming rather than local storage - _**Language Track**_: An audio or text track in a specific language - _**Media Contributor**_: A person, group, or organization that contributed to a media item, together with the role they played +- _**Direct Play**_: Delivery of a track's audio as stored, because the player can demux its container and decode its codec +- _**Remux**_: Delivery of a track's audio with its codec repackaged into a container the player can demux, without re-encoding it +- _**Transcode**_: Delivery of a track's audio re-encoded into a codec the player can decode +- _**Playback Capabilities**_: The container and codec combinations a player advertises it can demux and decode directly +- _**Delivery Shape**_: The way delivered audio is addressed and seeked, by byte range or as fixed duration, time addressed segments ## Video Content - _**TV Show**_: A series of episodes typically organized into seasons diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs new file mode 100644 index 00000000..49bffeb5 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for a single container and codec combination that a player advertises it can demux and decode directly. +/// +/// The container the player can demux, for example MP3, FLAC, OGG, WAV or MP4. +/// The codec the player can decode, for example MP3, FLAC, Opus, Vorbis, PCM or AAC. +[DebuggerDisplay("Container: {Container} Codec: {Codec}")] +public sealed record PlaybackCapabilityDto( + string Container, + string Codec +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs new file mode 100644 index 00000000..72fb25db --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the decision of how the audio of a track is delivered to a player: as the original file, as the same codec repackaged, or re-encoded. +/// +/// The way the audio is delivered. +/// The container of the delivered audio, which is the stored container of the track for a direct play. +/// The codec of the delivered audio, which is the stored codec of the track for a direct play. +/// The shape the delivered audio is addressed and seeked by. +/// The duration of each segment of the delivered audio, in seconds, or zero when the shape is not time addressed. +[DebuggerDisplay("Mode: {Mode} Container: {Container} Codec: {Codec} Shape: {Shape}")] +public sealed record PlaybackDeliveryDecisionDto( + PlaybackDeliveryMode Mode, + string Container, + string Codec, + PlaybackDeliveryShape Shape, + int SegmentDurationSeconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs new file mode 100644 index 00000000..2c3810ec --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the stored format of a track's audio, that a playback delivery decision is made on. +/// +/// The container of the audio file of the track, for example MP3, FLAC, OGG, MP4 or WAV. +/// The codec of the audio of the track, as reported by the probe, for example AAC, FLAC, Opus or PCM. +[DebuggerDisplay("Container: {Container} Codec: {Codec}")] +public sealed record PlaybackSourceFormatDto( + string? Container, + string? Codec +); diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs new file mode 100644 index 00000000..6f83888b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Interface for the service that decides whether the audio of a track can be played as stored by a player, or has to be +/// repackaged into another container or re-encoded into another codec before the player can play it. +/// +public interface IPlaybackFormatService +{ + /// + /// Decides how the audio of a track, described by , is delivered to a player that advertises . + /// + /// The container and codec of the audio of the track, read from its stored probe result. + /// The container and codec combinations the player advertises it can demux and decode directly. + /// + /// An containing either the delivery decision, or an error when the server cannot produce any + /// format the player advertises it supports. + /// + Result DecideDelivery(PlaybackSourceFormatDto sourceFormat, IReadOnlyList capabilities); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs new file mode 100644 index 00000000..1eab4384 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Parses the capabilities input of a playback manifest request into the container and codec combinations a player advertises it +/// can demux and decode directly. +/// +/// +/// The input is a comma separated list of container/codec pairs, for example +/// mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac. The container and the codec of a pair are matched case +/// insensitively, and a pair that does not name both, with a non-empty container and codec, is ignored. The number of pairs is +/// capped, so a request cannot force an unbounded amount of parsing work. When the input is absent or lists no valid pair, the +/// capabilities of the bundled player apply. +/// +public static class PlaybackCapabilitiesParser +{ + /// + /// The maximum number of capability pairs that are read from a single request, so that the parsing work stays bounded. + /// + public const int MAX_CAPABILITY_COUNT = 32; + + /// + /// The character that separates the container from the codec of a single capability pair. + /// + public const char CONTAINER_CODEC_SEPARATOR = '/'; + + /// + /// The character that separates the capability pairs of a capability set. + /// + public const char CAPABILITY_SEPARATOR = ','; + + /// + /// Gets the capability set the bundled player advertises, used when a request does not advertise any capability. + /// + public static IReadOnlyList Default { get; } = + [ + new PlaybackCapabilityDto("MP3", "MP3"), + new PlaybackCapabilityDto("FLAC", "FLAC"), + new PlaybackCapabilityDto("OGG", "OPUS"), + new PlaybackCapabilityDto("OGG", "VORBIS"), + new PlaybackCapabilityDto("WAV", "PCM"), + new PlaybackCapabilityDto("AAC", "AAC") + ]; + + /// + /// Parses the capabilities input of a playback manifest request into a capability set. + /// + /// The value of the capabilities input, a comma separated list of container/codec pairs. + /// The parsed capabilities, or when the input is absent, empty or lists no valid pair. + public static IReadOnlyList Parse(string? capabilitiesInput) + { + if (string.IsNullOrWhiteSpace(capabilitiesInput)) + return Default; + + List capabilities = []; + foreach (string entry in capabilitiesInput.Split(CAPABILITY_SEPARATOR, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + // The number of pairs is capped, so a single request cannot force an unbounded amount of parsing work. + if (capabilities.Count >= MAX_CAPABILITY_COUNT) + break; + + // Both parts must be named: a container or a codec that is empty (for example "a//b" or "/wav") does not name a pair. + string[] parts = entry.Split(CONTAINER_CODEC_SEPARATOR, StringSplitOptions.TrimEntries); + if (parts.Length != 2 || parts[0].Length == 0 || parts[1].Length == 0) + continue; + capabilities.Add(new PlaybackCapabilityDto(parts[0], parts[1])); + } + + return capabilities.Count == 0 ? Default : capabilities; + } +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs new file mode 100644 index 00000000..134e976e --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs @@ -0,0 +1,22 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Enumeration for the ways in which a track's audio is delivered to a player. +/// +public enum PlaybackDeliveryMode +{ + /// + /// The original audio file is delivered unchanged, because the player can demux its container and decode its codec as stored. + /// + DirectPlay, + + /// + /// The audio is repackaged into a container the player can demux, without re-encoding its codec. + /// + Remux, + + /// + /// The audio is re-encoded into a codec the player can decode, because the stored codec is not one the player supports. + /// + Transcode, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs new file mode 100644 index 00000000..dfbad916 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs @@ -0,0 +1,18 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Enumeration for the shapes in which delivered audio is addressed and seeked. +/// +public enum PlaybackDeliveryShape +{ + /// + /// The delivered media is the original file itself, addressed and seeked by byte range. + /// + ByteRangeSeekable, + + /// + /// The delivered media is a sequence of fixed duration segments, addressed and seeked by time, so that finding a time never + /// requires mapping a byte range to it. + /// + TimeAddressedSegments, +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs new file mode 100644 index 00000000..8e4662fc --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Domain playback related error types. +/// +public static partial class Errors +{ + public static class Playback + { + public static Error NoSupportedPlaybackFormat => Error.Forbidden(description: nameof(NoSupportedPlaybackFormat)); + } +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 10e7c307..4154b4a9 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -13,6 +13,7 @@ using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; @@ -38,6 +39,7 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenCo using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Infrastructure.Core.Plugins; @@ -146,6 +148,10 @@ public static class InfrastructureLayerServices // Music artwork: stores the artwork of the albums into the internal media directory. services.AddScoped(); + // Music playback: decides, for a track and the capabilities a player advertises, whether the track is played as stored, + // repackaged into another container, or re-encoded into another codec. + services.AddSingleton(); + // Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents. // The enablement cache lets the reading service skip the per-request database read of the reader configurations. services.AddSingleton(); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs new file mode 100644 index 00000000..3afe9bf2 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs @@ -0,0 +1,182 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Service that decides whether the audio of a track can be played as stored by a player, or has to be repackaged into another container (remuxed) or re-encoded into another codec (transcoded). +/// +/// +/// The decision uses the container and the codec of the stored probe result together with the container and codec pairs the player advertises it can demux and decode directly: +/// a pair the player advertises as stored is a direct play, a codec the player decodes but a container it cannot demux is a remux into a container it can demux, and a codec the player cannot decode +/// is a transcode to the most preferred codec the server can produce and the player advertises. Everything that is not a direct play is delivered as fixed duration, time addressed segments, so that seeking never requires mapping a byte range to a time. +/// +internal sealed class PlaybackFormatService : IPlaybackFormatService +{ + // The duration of each segment of a normalized (remuxed or transcoded) delivery, in seconds: short enough to seek quickly, long enough to keep the request overhead low. + private const int SEGMENT_DURATION_SECONDS = 6; + + // The order in which the codecs the server can produce are tried when a transcode is needed, most preferred first: the + // efficient lossy codecs come before the lossless ones, so a transcode stays small unless the player only supports lossless. + private static readonly IReadOnlyList s_transcodeCodecPreference = ["AAC", "OPUS", "MP3", "VORBIS", "FLAC", "PCM"]; + + // The containers the server can produce each codec in, in order of preference. The delivered container is always chosen from + // this list, so a container the player named is only ever matched against it and never becomes the delivered container itself. + private static readonly FrozenDictionary> s_producibleContainersByCodec = new Dictionary>(StringComparer.OrdinalIgnoreCase) + { + { "AAC", ["MP4", "AAC"] }, + { "OPUS", ["OGG"] }, + { "VORBIS", ["OGG"] }, + { "MP3", ["MP3"] }, + { "FLAC", ["FLAC"] }, + { "PCM", ["WAV"] } + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + + /// + /// Decides how the audio of a track, described by , is delivered to a player that advertises . + /// + /// The container and codec of the audio of the track, read from its stored probe result. + /// The container and codec combinations the player advertises it can demux and decode directly. + /// + /// An containing either the delivery decision, or an error when the server cannot produce any format the player advertises it supports. + /// + public Result DecideDelivery(PlaybackSourceFormatDto sourceFormat, IReadOnlyList capabilities) + { + string container = CanonicalizeContainer(sourceFormat.Container); + string codec = CanonicalizeCodec(sourceFormat.Codec); + + // Direct play: the player can demux the stored container and decode the stored codec, so the file is delivered unchanged, and it is addressed and seeked by byte range. + // The delivered container and codec are the stored ones, not the player's. + if (IsFormatAdvertised(capabilities, container, codec)) + return new PlaybackDeliveryDecisionDto(PlaybackDeliveryMode.DirectPlay, container, codec, PlaybackDeliveryShape.ByteRangeSeekable, 0); + + // Remux: the player can decode the stored codec but has no demuxer for the stored container, so the codec is repackaged + // into a container the server can produce and the player can demux, without re-encoding it; the normalized output is delivered as time addressed segments. + PlaybackCapabilityDto? remuxFormat = SelectFormatForCodec(capabilities, codec); + if (remuxFormat is not null) + return new PlaybackDeliveryDecisionDto(PlaybackDeliveryMode.Remux, remuxFormat.Container, remuxFormat.Codec, PlaybackDeliveryShape.TimeAddressedSegments, SEGMENT_DURATION_SECONDS); + + // Transcode: the player cannot decode the stored codec, so the audio is re-encoded into the most preferred codec the server can produce and the player advertises, + // and the normalized output is delivered as time addressed segments. + PlaybackCapabilityDto? transcodeFormat = SelectTranscodeFormat(capabilities); + if (transcodeFormat is null) + return Errors.Playback.NoSupportedPlaybackFormat; + + return new PlaybackDeliveryDecisionDto(PlaybackDeliveryMode.Transcode, transcodeFormat.Container, transcodeFormat.Codec, PlaybackDeliveryShape.TimeAddressedSegments, SEGMENT_DURATION_SECONDS); + } + + /// + /// Checks whether the player advertises the provided and as a combination it can demux and decode directly. + /// + /// The capabilities advertised by the player. + /// The canonical container that is looked for. + /// The canonical codec that is looked for. + /// when the player advertises the combination, otherwise . + private static bool IsFormatAdvertised(IReadOnlyList capabilities, string container, string codec) + { + if (container.Length == 0 || codec.Length == 0) + return false; + + return capabilities.Any(capability => + string.Equals(CanonicalizeContainer(capability.Container), container, StringComparison.OrdinalIgnoreCase) + && string.Equals(CanonicalizeCodec(capability.Codec), codec, StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Selects the container the server produces the provided in, preferring the server's canonical one, among the containers the player advertises it can demux for that codec. + /// + /// The capabilities advertised by the player. + /// The canonical codec that is delivered. + /// + /// The container and codec the server delivers in, or when the server cannot produce the codec in any container the player advertises it can demux. + /// + private static PlaybackCapabilityDto? SelectFormatForCodec(IReadOnlyList capabilities, string codec) + { + if (codec.Length == 0 || !s_producibleContainersByCodec.TryGetValue(codec, out IReadOnlyList? producibleContainers)) + return null; + + IReadOnlyList advertisedContainers = [.. capabilities + .Where(capability => string.Equals(CanonicalizeCodec(capability.Codec), codec, StringComparison.OrdinalIgnoreCase)) + .Select(capability => CanonicalizeContainer(capability.Container))]; + + // The delivered container is one of the server's own containers, chosen as the first one the player advertises: the player + // only selects among the containers the server knows, so a container the player names never reaches the transcoder itself. + foreach (string producibleContainer in producibleContainers) + if (advertisedContainers.Contains(producibleContainer, StringComparer.OrdinalIgnoreCase)) + return new PlaybackCapabilityDto(producibleContainer, codec); + + return null; + } + + /// + /// Selects the most preferred codec the server can produce that the player advertises it can decode. + /// + /// The capabilities advertised by the player. + /// The preferred producible container and codec, or when the player supports no producible codec. + private static PlaybackCapabilityDto? SelectTranscodeFormat(IReadOnlyList capabilities) + { + foreach (string preferredCodec in s_transcodeCodecPreference) + { + PlaybackCapabilityDto? format = SelectFormatForCodec(capabilities, preferredCodec); + if (format is not null) + return format; + } + + return null; + } + + /// + /// Canonicalizes the container of an audio file, so that containers compare regardless of casing. + /// + /// The container to canonicalize. + /// The canonical container, or an empty string when there is none. + private static string CanonicalizeContainer(string? container) + { + return string.IsNullOrWhiteSpace(container) ? string.Empty : container.Trim().ToUpperInvariant(); + } + + /// + /// Canonicalizes the codec of an audio file, mapping the free form descriptions reported by the probe to the canonical codec + /// names the players advertise, and leaving a description it does not recognize as unplayable. + /// + /// The codec to canonicalize. + /// The canonical codec, or an empty string when there is none. + private static string CanonicalizeCodec(string? codec) + { + if (string.IsNullOrWhiteSpace(codec)) + return string.Empty; + + // The probe reports the codec as the description the tagging library parsed from the file, for example "MPEG-1 Layer 3" rather than "MP3", + // so the known descriptions are recognized by their distinctive token, most specific ones first. The MPEG layer is matched by its layer number only, + // so MPEG-1 Layer 1 and Layer 2 are not mistaken for MP3, and a description that names no recognizable codec is left as it is, + // which keeps it from matching any advertised codec and forces a transcode. + string normalized = codec.Trim().ToUpperInvariant(); + if (normalized.Contains("VORBIS", StringComparison.Ordinal)) + return "VORBIS"; + if (normalized.Contains("OPUS", StringComparison.Ordinal)) + return "OPUS"; + if (normalized.Contains("FLAC", StringComparison.Ordinal)) + return "FLAC"; + if (normalized.Contains("ALAC", StringComparison.Ordinal) || normalized.Contains("APPLE LOSSLESS", StringComparison.Ordinal)) + return "ALAC"; + if (normalized.Contains("AAC", StringComparison.Ordinal)) + return "AAC"; + if (normalized.Contains("MP3", StringComparison.Ordinal) || normalized.Contains("LAYER 3", StringComparison.Ordinal) || normalized.Contains("LAYER III", StringComparison.Ordinal)) + return "MP3"; + if (normalized.Contains("PCM", StringComparison.Ordinal) || normalized.Contains("UNCOMPRESSED", StringComparison.Ordinal) || normalized.Contains("LINEAR", StringComparison.Ordinal)) + return "PCM"; + if (normalized.Contains("WINDOWS MEDIA", StringComparison.Ordinal) || normalized.Contains("WMA", StringComparison.Ordinal)) + return "WMA"; + + return normalized; + } +} diff --git a/src/Lumina.sln b/src/Lumina.sln index 9de2e1b3..2de7403b 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -176,6 +176,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0015.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0015.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0016.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0016.md EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{3EE8EFDF-4D55-4EA3-BEE2-74D00CB50570}" diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDtoFixture.cs new file mode 100644 index 00000000..b147f02d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaybackCapabilityDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The container the player can demux. + /// Optional. The codec the player can decode. + /// The created . + public PlaybackCapabilityDto Create( + string? container = null, + string? codec = null) + { + return new PlaybackCapabilityDto( + container ?? _faker.Random.AlphaNumeric(4).ToUpperInvariant(), + codec ?? _faker.Random.AlphaNumeric(4).ToUpperInvariant()); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDtoFixture.cs new file mode 100644 index 00000000..66b702a6 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDtoFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaybackSourceFormatDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The container of the audio file of the track. + /// Optional. The codec of the audio of the track. + /// Whether the container should be included, or forced to . + /// Whether the codec should be included, or forced to . + /// The created . + public PlaybackSourceFormatDto Create( + string? container = null, + string? codec = null, + bool includeContainer = true, + bool includeCodec = true) + { + return new PlaybackSourceFormatDto( + includeContainer ? (container ?? _faker.Random.AlphaNumeric(4).ToUpperInvariant()) : null, + includeCodec ? (codec ?? _faker.Random.AlphaNumeric(4).ToUpperInvariant()) : null); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParserTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParserTests.cs new file mode 100644 index 00000000..7b46ce58 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParserTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaybackCapabilitiesParserTests +{ + private readonly PlaybackCapabilityDtoFixture _playbackCapabilityDtoFixture = new(); + + [Theory] + [InlineData(null)] // an absent input falls back to the default capabilities + [InlineData("")] // an empty input falls back to the default capabilities + [InlineData(" ")] // a blank input falls back to the default capabilities + [InlineData("not-a-pair")] // an input that does not name both a container and a codec falls back to the default capabilities + [InlineData("a/b/c")] // an input with more than two segments falls back to the default capabilities + [InlineData("a//b")] // an input whose container or codec is empty falls back to the default capabilities + public void Parse_WhenInputIsNotAValidCapabilitySet_ShouldReturnDefaultCapabilities(string? input) + { + // Act + IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse(input); + + // Assert + Assert.Same(PlaybackCapabilitiesParser.Default, capabilities); + } + + [Fact] + public void Parse_WhenInputListsPairs_ShouldReturnThosePairs() + { + // Act + IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse("mp3/mp3,flac/flac"); + + // Assert + Assert.NotSame(PlaybackCapabilitiesParser.Default, capabilities); + Assert.Equal(2, capabilities.Count); + Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "mp3", codec: "mp3"), capabilities); + Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "flac", codec: "flac"), capabilities); + } + + [Fact] + public void Parse_WhenEntriesArePadded_ShouldTrimThem() + { + // Act + IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse(" mp3 / mp3 , flac / flac "); + + // Assert + Assert.Equal(2, capabilities.Count); + Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "mp3", codec: "mp3"), capabilities); + Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "flac", codec: "flac"), capabilities); + } + + [Fact] + public void Parse_WhenInputContainsInvalidEntriesAmongValidOnes_ShouldIgnoreTheInvalidOnes() + { + // Act + IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse("mp3/mp3,,not-a-pair,/wav,wav/,wav/pcm"); + + // Assert + Assert.Equal(2, capabilities.Count); + Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "mp3", codec: "mp3"), capabilities); + Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "wav", codec: "pcm"), capabilities); + } + + [Fact] + public void Parse_WhenMorePairsThanTheMaximumAreListed_ShouldKeepOnlyTheFirstMaximum() + { + // Arrange + List pairs = []; + for (int index = 0; index < PlaybackCapabilitiesParser.MAX_CAPABILITY_COUNT + 5; index++) + pairs.Add($"container{index}/codec{index}"); + + // Act + IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse(string.Join(',', pairs)); + + // Assert + Assert.Equal(PlaybackCapabilitiesParser.MAX_CAPABILITY_COUNT, capabilities.Count); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs index d38f7e75..b9e25ec0 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs @@ -5,11 +5,13 @@ using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; using Lumina.Infrastructure.Common.DependencyInjection; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Infrastructure.Core.Plugins; using Lumina.Infrastructure.Core.Security; using Lumina.Infrastructure.Core.Time; @@ -43,6 +45,7 @@ public class InfrastructureLayerServicesTests // Assert Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IFileHashService) && descriptor.ImplementationType == typeof(FileHashService)); Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDateTimeProvider) && descriptor.ImplementationType == typeof(DateTimeProvider)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPlaybackFormatService) && descriptor.ImplementationType == typeof(PlaybackFormatService)); Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginManager)); Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginSettingsStore)); Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDomainEventsQueue)); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatServiceTests.cs new file mode 100644 index 00000000..17c4a78e --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatServiceTests.cs @@ -0,0 +1,283 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaybackFormatServiceTests +{ + private readonly PlaybackFormatService _sut; + private readonly PlaybackSourceFormatDtoFixture _playbackSourceFormatDtoFixture = new(); + private readonly PlaybackCapabilityDtoFixture _playbackCapabilityDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public PlaybackFormatServiceTests() + { + _sut = new PlaybackFormatService(); + } + + [Fact] + public void DecideDelivery_WhenPlayerAdvertisesTheStoredFormat_ShouldReturnDirectPlay() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "FLAC", codec: "FLAC"); + IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC")]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode); + Assert.Equal("FLAC", result.Value.Container); + Assert.Equal("FLAC", result.Value.Codec); + Assert.Equal(PlaybackDeliveryShape.ByteRangeSeekable, result.Value.Shape); + Assert.Equal(0, result.Value.SegmentDurationSeconds); + } + + [Fact] + public void DecideDelivery_WhenPlayerDecodesTheCodecButNotTheContainer_ShouldReturnRemux() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM"); + IReadOnlyList capabilities = + [ + _playbackCapabilityDtoFixture.Create(container: "WAV", codec: "PCM"), + _playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC") + ]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode); + Assert.Equal("WAV", result.Value.Container); + Assert.Equal("PCM", result.Value.Codec); + Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.Shape); + Assert.Equal(6, result.Value.SegmentDurationSeconds); + } + + [Fact] + public void DecideDelivery_WhenPlayerCannotDecodeTheStoredCodec_ShouldReturnTranscode() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "WMA", codec: "WMA"); + IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode); + Assert.Equal("MP3", result.Value.Container); + Assert.Equal("MP3", result.Value.Codec); + Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.Shape); + Assert.Equal(6, result.Value.SegmentDurationSeconds); + } + + [Fact] + public void DecideDelivery_WhenTheDefaultCapabilitiesAreUsed_ShouldReturnDirectPlay() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP3", codec: "MP3"); + + // Act + Result result = _sut.DecideDelivery(sourceFormat, PlaybackCapabilitiesParser.Default); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode); + } + + [Fact] + public void DecideDelivery_WhenDefaultCapabilitiesAreUsedForAnAacTrackInMp4_ShouldReturnRemuxToRawAac() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP4", codec: "AAC"); + + // Act + Result result = _sut.DecideDelivery(sourceFormat, PlaybackCapabilitiesParser.Default); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode); + Assert.Equal("AAC", result.Value.Container); + Assert.Equal("AAC", result.Value.Codec); + } + + [Theory] + [InlineData("MP3", "MPEG-1 Layer 3", "MP3")] // the free form description of an MPEG-1 Layer 3 stream + [InlineData("MP3", "MP3", "MP3")] // a codec that is already named canonically + [InlineData("FLAC", "Flac", "FLAC")] // the description of a FLAC stream + [InlineData("OGG", "Vorbis I", "VORBIS")] // the description of a Vorbis stream + [InlineData("OGG", "Opus", "OPUS")] // the description of an Opus stream + [InlineData("MP4", "Apple Lossless", "ALAC")] // the description of an Apple Lossless stream + [InlineData("AAC", "MPEG-4 AAC", "AAC")] // a description naming both MPEG and AAC is AAC, not MP3 + [InlineData("WAV", "PCM", "PCM")] // the description of an uncompressed stream + [InlineData("WAV", "Uncompressed", "PCM")] // another description of an uncompressed stream + [InlineData("WMA", "Windows Media Audio", "WMA")] // the description of a Windows Media stream + public void DecideDelivery_WhenTheStoredCodecDescriptionIsRecognizable_ShouldCanonicalizeItAndDirectPlay(string container, string codecDescription, string canonicalCodec) + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: container, codec: codecDescription); + IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: container, codec: canonicalCodec)]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode); + Assert.Equal(canonicalCodec, result.Value.Codec); + } + + [Theory] + [InlineData("MPEG-1 Layer 2")] // MP2 shares the MP3 container but an MP3 decoder cannot decode it + [InlineData("MPEG-1 Layer 1")] // MP1 shares the MP3 container but an MP3 decoder cannot decode it + [InlineData("MPEG-4 Audio")] // a description that names no decodable codec is not mistaken for MP3 + public void DecideDelivery_WhenAnMpegDescriptionIsNotLayer3_ShouldReturnTranscode(string codecDescription) + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP3", codec: codecDescription); + IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode); + } + + [Theory] + [InlineData(null, null)] // an absent probe result names no codec + [InlineData("", "")] // an empty probe result names no codec + [InlineData("MP3", "AC-3")] // a codec description the server does not recognize + public void DecideDelivery_WhenTheStoredFormatIsUnknown_ShouldReturnTranscode(string? container, string? codec) + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create( + container: container, + codec: codec, + includeContainer: container is not null, + includeCodec: codec is not null); + IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode); + } + + [Fact] + public void DecideDelivery_WhenSeveralProducibleCodecsAreAdvertised_ShouldTranscodeToTheMostPreferredOne() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "OGG", codec: "OPUS"); + IReadOnlyList capabilities = + [ + _playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC"), + _playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC") + ]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode); + Assert.Equal("AAC", result.Value.Codec); + } + + [Fact] + public void DecideDelivery_WhenSeveralContainersAreAdvertisedForTheSameCodec_ShouldRemuxToThePreferredContainer() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MATROSKA", codec: "AAC"); + IReadOnlyList capabilities = + [ + _playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC"), + _playbackCapabilityDtoFixture.Create(container: "MP4", codec: "AAC") + ]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode); + Assert.Equal("MP4", result.Value.Container); + Assert.Equal("AAC", result.Value.Codec); + } + + [Fact] + public void DecideDelivery_WhenThePreferredContainerForTheCodecIsNotAdvertised_ShouldRemuxToTheOtherProducibleContainer() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MATROSKA", codec: "AAC"); + IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC")]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode); + Assert.Equal("AAC", result.Value.Container); + Assert.Equal("AAC", result.Value.Codec); + } + + [Fact] + public void DecideDelivery_WhenThePlayerNamesAContainerTheServerDoesNotProduce_ShouldDeliverTheServerContainer() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM"); + IReadOnlyList capabilities = + [ + _playbackCapabilityDtoFixture.Create(container: "evil;$(x)", codec: "PCM"), + _playbackCapabilityDtoFixture.Create(container: "wav", codec: "pcm") + ]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode); + Assert.Equal("WAV", result.Value.Container); + Assert.Equal("PCM", result.Value.Codec); + } + + [Fact] + public void DecideDelivery_WhenThePlayerOnlyNamesContainersTheServerDoesNotProduce_ShouldReturnNoSupportedPlaybackFormat() + { + // Arrange + PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM"); + IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "evil;$(x)", codec: "PCM")]; + + // Act + Result result = _sut.DecideDelivery(sourceFormat, capabilities); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.NoSupportedPlaybackFormat, result.FirstError); + } +} From d7c1ae60c2c40b42774e428cf07d01da57f01517 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 15 Oct 2026 14:58:57 +0300 Subject: [PATCH 09/77] Adds the playback manifest endpoint --- .../audio-library/music-library/Api.Tracks.md | 46 +++ .../tracks/GetPlaybackManifest.http | 2 + .../Tracks/TrackPlaybackManifestDto.cs | 62 ++++ .../MusicLibrary/ITrackRepository.cs | 16 + .../Playback/PlaybackCapabilitiesParser.cs | 30 +- .../GetPlaybackManifestQuery.cs | 25 ++ .../GetPlaybackManifestQueryHandler.cs | 125 ++++++++ .../GetPlaybackManifestQueryValidator.cs | 60 ++++ .../Playback/PlaybackManifestResponse.cs | 51 ++++ .../MusicLibrary/TrackRepository.cs | 37 +++ .../PlaybackDeliveryShapeExtensions.cs | 21 ++ .../MusicLibrary/ApiRoutes.Tracks.cs | 1 + .../GetPlaybackManifestEndpoint.cs | 69 +++++ .../GetPlaybackManifestEndpointSummary.cs | 161 ++++++++++ src/Lumina.sln | 1 + .../MusicLibrary/TrackEntityFixture.cs | 22 +- .../GetPlaybackManifestEndpointTests.cs | 274 ++++++++++++++++++ 17 files changed, 993 insertions(+), 10 deletions(-) create mode 100644 docs/technical/requests/library/audio-library/music-library/tracks/GetPlaybackManifest.http create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidator.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShapeExtensions.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index 199d8291..a518e8a3 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -11,6 +11,9 @@ - [Stream Track](#stream-track) - [Stream Track Request](#stream-track-request) - [Stream Track Response](#stream-track-response) + - [Get Playback Manifest](#get-playback-manifest) + - [Get Playback Manifest Request](#get-playback-manifest-request) + - [Get Playback Manifest Response](#get-playback-manifest-response) - [Update Track](#update-track) - [Update Track Request](#update-track-request) - [Update Track Response](#update-track-response) @@ -344,6 +347,49 @@ Accept-Ranges: bytes The response is the raw bytes of the audio file, served with the media type of the file when it is an audio type, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private` and `Vary: Authorization`, together with a `Last-Modified` and an `ETag` derived from the size and the modification time of the file. +### Get Playback Manifest + +#### Get Playback Manifest Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/playback-manifest?capabilities=mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac +Authorization: Bearer +``` + +Returns the playback manifest of the track identified by the route: the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream, so that a player is told what to fetch and how before it fetches any audio. The `capabilities` query parameter is optional, and its value is a comma separated list of the `container/codec` pairs the player advertises it can demux and decode directly, matched case insensitively, with at most 32 pairs read from one request. When the parameter is absent, empty, or lists no valid pair, the default capabilities of the bundled player apply. The manifest is returned to an Admin, who can build the manifest of the tracks of all libraries, or to the owner of the library of the track. + +#### Get Playback Manifest Response + +```js +200 Ok +``` + +```json +{ + "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "durationInSeconds": 354, + "sourceContainer": "FLAC", + "sourceCodec": "FLAC", + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "replayGainTrackGain": -7.5, + "replayGainTrackPeak": 0.9877, + "replayGainAlbumGain": -6.8, + "replayGainAlbumPeak": 0.9999, + "directPlay": true, + "deliveryContainer": null, + "deliveryCodec": null, + "deliveryShape": null, + "segmentDurationSeconds": null, + "seekable": true, + "streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream" +} +``` + +When the player can play the stored audio as it is, `directPlay` is `true`, and `deliveryContainer`, `deliveryCodec`, `deliveryShape` and `segmentDurationSeconds` are `null`, because the delivery is the stored file itself. When it cannot, `directPlay` is `false`, and those fields name the container, the codec, the addressing the server produces instead, and the length in seconds of each of its time addressed segments. A normalized delivery is always addressed as `TimeAddressedSegments`, and `segmentDurationSeconds` is the length of each of its segments, so that the server that produces the segments and the player that consumes them agree on it without duplicating the value on both sides. `seekable` reports whether the delivered audio can be seeked by the player. `streamPath` is relative to the API, without a host or a scheme, so that a client reaches the stream through its own application rather than the API server directly. + + ### Update Track #### Update Track Request diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/GetPlaybackManifest.http b/docs/technical/requests/library/audio-library/music-library/tracks/GetPlaybackManifest.http new file mode 100644 index 00000000..b6afd735 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/GetPlaybackManifest.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}/playback-manifest?capabilities=mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs new file mode 100644 index 00000000..08a3d50a --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for the stored probe result of a track, containing only the fields a playback manifest is built from. +/// +[DebuggerDisplay("Container: {Container} Codec: {AudioCodec}")] +public sealed record TrackPlaybackManifestDto +{ + /// + /// Gets the container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. + /// + public string? Container { get; init; } + + /// + /// Gets the audio codec used by the audio file of the track, if applicable. + /// + public string? AudioCodec { get; init; } + + /// + /// Gets the duration of the audio of the track in seconds. + /// + public int DurationInSeconds { get; init; } + + /// + /// Gets the sample rate of the audio of the track in Hz. + /// + public int SampleRate { get; init; } + + /// + /// Gets the number of audio channels of the track. + /// + public int Channels { get; init; } + + /// + /// Gets the bit depth of the audio of the track, if applicable. + /// + public int? BitDepth { get; init; } + + /// + /// Gets the ReplayGain track gain of the track, in decibels, if applicable. + /// + public decimal? ReplayGainTrackGain { get; init; } + + /// + /// Gets the ReplayGain track peak of the track, if applicable. + /// + public decimal? ReplayGainTrackPeak { get; init; } + + /// + /// Gets the ReplayGain album gain of the track, in decibels, if applicable. + /// + public decimal? ReplayGainAlbumGain { get; init; } + + /// + /// Gets the ReplayGain album peak of the track, if applicable. + /// + public decimal? ReplayGainAlbumPeak { get; init; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs index 5a1eda26..8b7d42ce 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs @@ -74,6 +74,22 @@ public interface ITrackRepository : IRepository, /// Task> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken); + /// + /// Gets the stored probe result needed to build the playback manifest of the track identified by , when it belongs to + /// the album identified by and to the media library identified by , and that album belongs + /// to the artist identified by . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose playback manifest data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track + /// matches the provided identifiers, or an error. + /// + Task> GetPlaybackManifestInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken); + /// /// Resets the enrichment state of the tracks stored at the provided in the media library identified by /// , together with their albums and artists, so that they are re-enriched, because their content changed since the last scan. diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs index 1eab4384..6739cd9a 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs @@ -14,8 +14,9 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playbac /// The input is a comma separated list of container/codec pairs, for example /// mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac. The container and the codec of a pair are matched case /// insensitively, and a pair that does not name both, with a non-empty container and codec, is ignored. The number of pairs is -/// capped, so a request cannot force an unbounded amount of parsing work. When the input is absent or lists no valid pair, the -/// capabilities of the bundled player apply. +/// capped, and the input is scanned entry by entry over its own characters, so a request never materializes an array of all its +/// entries and never yields more than a fixed number of capabilities, regardless of its length. When the input is absent or lists no +/// valid pair, the capabilities of the bundled player apply. /// public static class PlaybackCapabilitiesParser { @@ -58,17 +59,30 @@ public static class PlaybackCapabilitiesParser return Default; List capabilities = []; - foreach (string entry in capabilitiesInput.Split(CAPABILITY_SEPARATOR, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + // The input is scanned entry by entry over its own characters, so the entries are never all materialized at once: only the + // container and the codec of an accepted pair are allocated, and the number of accepted pairs is capped. + ReadOnlySpan remainingEntries = capabilitiesInput.AsSpan(); + while (!remainingEntries.IsEmpty) { - // The number of pairs is capped, so a single request cannot force an unbounded amount of parsing work. + // The number of accepted pairs is capped, so a request never yields more than a fixed number of capabilities. if (capabilities.Count >= MAX_CAPABILITY_COUNT) break; - // Both parts must be named: a container or a codec that is empty (for example "a//b" or "/wav") does not name a pair. - string[] parts = entry.Split(CONTAINER_CODEC_SEPARATOR, StringSplitOptions.TrimEntries); - if (parts.Length != 2 || parts[0].Length == 0 || parts[1].Length == 0) + int entrySeparatorIndex = remainingEntries.IndexOf(CAPABILITY_SEPARATOR); + ReadOnlySpan entry = entrySeparatorIndex < 0 ? remainingEntries : remainingEntries[..entrySeparatorIndex]; + remainingEntries = entrySeparatorIndex < 0 ? ReadOnlySpan.Empty : remainingEntries[(entrySeparatorIndex + 1)..]; + + // A pair names exactly one container and one codec, so exactly one separator must be present, and both parts must be + // named: a container or a codec that is empty (for example "a//b" or "/wav") does not name a pair. + int containerCodecSeparatorIndex = entry.IndexOf(CONTAINER_CODEC_SEPARATOR); + if (containerCodecSeparatorIndex < 0) continue; - capabilities.Add(new PlaybackCapabilityDto(parts[0], parts[1])); + ReadOnlySpan container = entry[..containerCodecSeparatorIndex].Trim(); + ReadOnlySpan codec = entry[(containerCodecSeparatorIndex + 1)..].Trim(); + if (container.IsEmpty || codec.IsEmpty || codec.Contains(CONTAINER_CODEC_SEPARATOR)) + continue; + + capabilities.Add(new PlaybackCapabilityDto(container.ToString(), codec.ToString())); } return capabilities.Count == 0 ? Default : capabilities; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs new file mode 100644 index 00000000..d72cda22 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; + +/// +/// Query for getting the playback manifest of a track. +/// +/// The unique identifier of the media library the track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track whose playback manifest is retrieved, taken from the route. +/// The container and codec pairs the player advertises it can demux and decode directly, taken from the request, or when it advertises none. +/// The path of the track stream, relative to the API, taken from the endpoint so that it always matches the stream route. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetPlaybackManifestQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId, + string? Capabilities, + string StreamPath +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs new file mode 100644 index 00000000..9c20966e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; + +/// +/// Handler for the query to get the playback manifest of a track. +/// +public class GetPlaybackManifestQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IPlaybackFormatService _playbackFormatService; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for deciding how a track's audio is delivered to a player. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _playbackFormatService = playbackFormatService; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the playback manifest of a track. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playback manifest of the track, or an error message. + /// + public async Task> HandleAsync(GetPlaybackManifestQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + + // Admins can build the manifest of the tracks of all libraries; for everyone else, only the tracks of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The projection is filtered by the library, the album and the artist named by the route as well as by the track, so a null row + // means the track either does not exist or is not in scope for the route, which is reported as not found without disclosing anything further. + Result getTrackResult = await _unitOfWork.TrackRepository.GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + return Errors.Music.TrackNotFound; + TrackPlaybackManifestDto track = getTrackResult.Value; + + // The stored container and codec of the probe result are the source format the delivery is decided on, and the capabilities + // the player advertises, or the default capabilities of the bundled player when it advertises none, decide the delivery. + IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse(query.Capabilities); + Result decisionResult = _playbackFormatService.DecideDelivery(new PlaybackSourceFormatDto(track.Container, track.AudioCodec), capabilities); + if (decisionResult.IsFailure) + return decisionResult.Errors; + PlaybackDeliveryDecisionDto decision = decisionResult.Value; + + bool isDirectPlay = decision.Mode == PlaybackDeliveryMode.DirectPlay; + // Whether the delivered audio can be seeked is a property of the shape it is delivered in, so the rule lives on the shape itself. + bool isSeekable = decision.Shape.IsSeekable(); + + return new PlaybackManifestResponse( + trackId, + track.DurationInSeconds, + track.Container, + track.AudioCodec, + track.SampleRate, + track.Channels, + track.BitDepth, + track.ReplayGainTrackGain, + track.ReplayGainTrackPeak, + track.ReplayGainAlbumGain, + track.ReplayGainAlbumPeak, + isDirectPlay, + isDirectPlay ? null : decision.Container, + isDirectPlay ? null : decision.Codec, + isDirectPlay ? null : decision.Shape, + decision.Shape == PlaybackDeliveryShape.TimeAddressedSegments ? decision.SegmentDurationSeconds : null, + isSeekable, + query.StreamPath); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidator.cs new file mode 100644 index 00000000..b61d0496 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidator.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; + +/// +/// Validates the needed validation rules for . +/// +public class GetPlaybackManifestQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackManifestQueryValidator() + { + // Validates the identifier of the media library the track belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track whose playback manifest is retrieved, taken from the route. + RuleFor(query => query.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(query => query.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(query => query.TrackId is not null && query.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs new file mode 100644 index 00000000..d817359d --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents a response for the playback manifest of a track, containing the format of its stored audio, the delivery the server decided on for the +/// requesting player, and the path of the track stream, so that a player is told what to fetch and how before it fetches any audio. +/// +/// The Id of the track the manifest describes. +/// The duration of the audio of the track, in seconds. +/// The container of the audio file of the track, as stored by the probe, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional. +/// The codec of the audio of the track, as stored by the probe. Optional. +/// The sample rate of the audio of the track, in Hz. +/// The number of audio channels of the track. +/// The bit depth of the audio of the track. Optional. +/// The ReplayGain track gain of the track, in decibels. Optional. +/// The ReplayGain track peak of the track. Optional. +/// The ReplayGain album gain of the track, in decibels. Optional. +/// The ReplayGain album peak of the track. Optional. +/// Whether the player can play the stored audio as it is, without the server changing its container or its codec. +/// The container of the audio the server delivers, when the delivery is not a direct play. for a direct play. +/// The codec of the audio the server delivers, when the delivery is not a direct play. for a direct play. +/// The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play. for a direct play. +/// The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments. otherwise. +/// Whether the delivered audio can be seeked by the player. +/// The path of the track stream, relative to the API, without a host or a scheme, so that a client never reaches the API directly. +[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")] +public sealed record PlaybackManifestResponse( + Guid TrackId, + int DurationInSeconds, + string? SourceContainer, + string? SourceCodec, + int SampleRate, + int Channels, + int? BitDepth, + decimal? ReplayGainTrackGain, + decimal? ReplayGainTrackPeak, + decimal? ReplayGainAlbumGain, + decimal? ReplayGainAlbumPeak, + bool DirectPlay, + string? DeliveryContainer, + string? DeliveryCodec, + PlaybackDeliveryShape? DeliveryShape, + int? SegmentDurationSeconds, + bool Seekable, + string StreamPath +); diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index aceafa55..5151f37a 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -357,6 +357,43 @@ internal sealed class TrackRepository : ITrackRepository .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); } + /// + /// Gets the stored probe result needed to build the playback manifest of the track identified by , when it belongs to + /// the album identified by and to the media library identified by , and that album belongs + /// to the artist identified by . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose playback manifest data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track + /// matches the provided identifiers, or an error. + /// + public async Task> GetPlaybackManifestInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken) + { + // The projection is flat and untracked, and the album is joined both to scope the track by its artist and to project the artist Id, so a track + // that is not in the named library, album and artist simply yields no row. + return await _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) + .Select(track => new TrackPlaybackManifestDto + { + Container = track.Container, + AudioCodec = track.AudioCodec, + DurationInSeconds = track.DurationInSeconds, + SampleRate = track.SampleRate, + Channels = track.Channels, + BitDepth = track.BitDepth, + ReplayGainTrackGain = track.ReplayGainTrackGain, + ReplayGainTrackPeak = track.ReplayGainTrackPeak, + ReplayGainAlbumGain = track.ReplayGainAlbumGain, + ReplayGainAlbumPeak = track.ReplayGainAlbumPeak + }) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + /// /// Deletes the track identified by , together with its owned collections and contributions, by the database cascade. /// diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShapeExtensions.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShapeExtensions.cs new file mode 100644 index 00000000..27e6672e --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShapeExtensions.cs @@ -0,0 +1,21 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Extension methods for . +/// +public static class PlaybackDeliveryShapeExtensions +{ + /// + /// Gets whether the audio delivered in the provided can be seeked by a player. + /// + /// The shape the delivered audio is addressed and seeked by. + /// + /// when the shape can be seeked, otherwise . Audio delivered as the original file is + /// seeked by byte range, and audio delivered as time addressed segments is seeked by segment, so both of the shapes the server + /// produces are seekable; a future shape that cannot be seeked reports . + /// + public static bool IsSeekable(this PlaybackDeliveryShape shape) + { + return shape is PlaybackDeliveryShape.ByteRangeSeekable or PlaybackDeliveryShape.TimeAddressedSegments; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs index eb235189..34ab9696 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs @@ -15,5 +15,6 @@ public static partial class ApiRoutes public const string UPDATE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string STREAM_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + public const string GET_PLAYBACK_MANIFEST = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs new file mode 100644 index 00000000..ddef6938 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest route. +/// +public class GetPlaybackManifestEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getPlaybackManifestQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get playback manifest queries. + public GetPlaybackManifestEndpoint(IQueryHandler> getPlaybackManifestQueryHandler) + { + _getPlaybackManifestQueryHandler = getPlaybackManifestQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Tracks.GET_PLAYBACK_MANIFEST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the playback manifest of the track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + // The capabilities the player advertises are optional; an absent parameter is an empty value, which the handler treats as no capabilities. + string capabilities = HttpContext.Request.Query["capabilities"].ToString(); + // The stream path is filled in from the stream route itself, so that the manifest and the stream can never disagree on the shape of the route. + // It is kept relative, without a host, a scheme or the version prefix, so that a client reaches the stream through its own application. + string streamPath = ApiRoutes.Tracks.STREAM_TRACK + .Replace("{libraryId}", libraryId, StringComparison.Ordinal) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + GetPlaybackManifestQuery query = new(libraryId, artistId, albumId, trackId, capabilities, streamPath); + Result result = await _getPlaybackManifestQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs new file mode 100644 index 00000000..b5e5c781 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackManifestEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackManifestEndpointSummary() + { + Summary = "Retrieves the playback manifest of a track."; + Description = "Retrieves the playback manifest of a track, containing the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream. The player advertises the container and codec pairs it can demux and decode directly in the optional capabilities query parameter, as a comma separated list of container/codec pairs; when the parameter is absent, empty or lists no valid pair, the default capabilities of the bundled player apply. The manifest is returned to an Admin, who can build the manifest of the tracks of all libraries, or to the owner of the library of the track."; + + ResponseParam(r => r.TrackId, "The Id of the track the manifest describes."); + ResponseParam(r => r.DurationInSeconds, "The duration of the audio of the track, in seconds."); + ResponseParam(r => r.SourceContainer, "The container of the stored audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV."); + ResponseParam(r => r.SourceCodec, "The codec of the stored audio of the track."); + ResponseParam(r => r.SampleRate, "The sample rate of the audio of the track, in Hz."); + ResponseParam(r => r.Channels, "The number of audio channels of the track."); + ResponseParam(r => r.BitDepth, "The bit depth of the audio of the track, if applicable."); + ResponseParam(r => r.ReplayGainTrackGain, "The ReplayGain track gain of the track, in decibels, if applicable."); + ResponseParam(r => r.ReplayGainTrackPeak, "The ReplayGain track peak of the track, if applicable."); + ResponseParam(r => r.ReplayGainAlbumGain, "The ReplayGain album gain of the track, in decibels, if applicable."); + ResponseParam(r => r.ReplayGainAlbumPeak, "The ReplayGain album peak of the track, if applicable."); + ResponseParam(r => r.DirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec."); + ResponseParam(r => r.DeliveryContainer, "The container of the audio the server delivers, when the delivery is not a direct play."); + ResponseParam(r => r.DeliveryCodec, "The codec of the audio the server delivers, when the delivery is not a direct play."); + ResponseParam(r => r.DeliveryShape, "The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play."); + ResponseParam(r => r.SegmentDurationSeconds, "The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments."); + ResponseParam(r => r.Seekable, "Whether the delivered audio can be seeked by the player."); + ResponseParam(r => r.StreamPath, "The path of the track stream, relative to the API, without a host or a scheme."); + + Response(200, "The playback manifest of the track is returned.", + example: new PlaybackManifestResponse( + TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + DurationInSeconds: 354, + SourceContainer: "FLAC", + SourceCodec: "FLAC", + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + ReplayGainTrackGain: -7.5m, + ReplayGainTrackPeak: 0.9877m, + ReplayGainAlbumGain: -6.8m, + ReplayGainAlbumPeak: 0.9999m, + DirectPlay: false, + DeliveryContainer: "MP3", + DeliveryCodec: "MP3", + DeliveryShape: PlaybackDeliveryShape.TimeAddressedSegments, + SegmentDurationSeconds: 6, + Seekable: true, + StreamPath: "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream" + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library, or because the server cannot produce any format the player advertises it supports.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "NoSupportedPlaybackFormat", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(404, "The request failed because the track or its media library does not exist, or the track does not belong to the library, album and artist named by the route.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.sln b/src/Lumina.sln index 2de7403b..8a3f9d13 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -286,6 +286,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657 ProjectSection(SolutionItems) = preProject ..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http + ..\docs\technical\requests\library\audio-library\music-library\tracks\GetPlaybackManifest.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetPlaybackManifest.http ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs index 77cc1a55..abd1b116 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs @@ -50,6 +50,13 @@ public class TrackEntityFixture /// Whether the re-release year should be included, or forced to . /// Whether the container should be included, or forced to . /// Optional. The metadata enrichment status of the track. + /// Optional. The audio codec of the track. + /// Whether the audio codec should be included, or forced to . + /// Optional. The ReplayGain track gain of the track, in decibels. + /// Optional. The ReplayGain track peak of the track. + /// Optional. The ReplayGain album gain of the track, in decibels. + /// Optional. The ReplayGain album peak of the track. + /// Whether the ReplayGain values should be included, or forced to . /// The created . public TrackEntity Create( Guid? id = null, @@ -69,7 +76,14 @@ public class TrackEntityFixture bool includeReReleaseDate = true, bool includeReReleaseYear = true, bool includeContainer = true, - MetadataStatus? metadataStatus = null) + MetadataStatus? metadataStatus = null, + string? audioCodec = null, + bool includeAudioCodec = true, + decimal? replayGainTrackGain = null, + decimal? replayGainTrackPeak = null, + decimal? replayGainAlbumGain = null, + decimal? replayGainAlbumPeak = null, + bool includeReplayGain = true) { Guid resolvedId = id ?? Guid.NewGuid(); Guid resolvedAlbumId = albumId ?? Guid.NewGuid(); @@ -114,8 +128,12 @@ public class TrackEntityFixture .RuleFor(x => x.SampleRate, f => f.PickRandom(44100, 48000, 96000)) .RuleFor(x => x.Channels, f => f.PickRandom(1, 2, 6)) .RuleFor(x => x.BitDepth, Random.Shared.Next(8, 32)) - .RuleFor(x => x.AudioCodec, f => f.PickRandom("FLAC", "MP3", "AAC", "ALAC")) + .RuleFor(x => x.AudioCodec, f => includeAudioCodec ? (audioCodec ?? f.PickRandom("FLAC", "MP3", "AAC", "ALAC")) : null) .RuleFor(x => x.Container, f => includeContainer ? (container ?? f.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV")) : null) + .RuleFor(x => x.ReplayGainTrackGain, f => includeReplayGain ? (replayGainTrackGain ?? f.Random.Decimal(-20m, 0m)) : null) + .RuleFor(x => x.ReplayGainTrackPeak, f => includeReplayGain ? (replayGainTrackPeak ?? f.Random.Decimal(0m, 1.5m)) : null) + .RuleFor(x => x.ReplayGainAlbumGain, f => includeReplayGain ? (replayGainAlbumGain ?? f.Random.Decimal(-20m, 0m)) : null) + .RuleFor(x => x.ReplayGainAlbumPeak, f => includeReplayGain ? (replayGainAlbumPeak ?? f.Random.Decimal(0m, 1.5m)) : null) .RuleFor(x => x.Bitrate, Random.Shared.Next(96, 1411)) .RuleFor(x => x.TrackNumber, f => trackNumber ?? f.Random.Int(1, 20)) .RuleFor(x => x.DiscNumber, Random.Shared.Next(1, 3)) diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs new file mode 100644 index 00000000..04d2d75a --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs @@ -0,0 +1,274 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackManifestEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter() } + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPlaybackManifestEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client of the test. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetPlaybackManifest_WhenTrackBelongsToAnOwnedLibrary_ShouldReturnDirectPlayManifest() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync( + userId, + container: "FLAC", + audioCodec: "FLAC", + replayGainTrackGain: -7.5m, + replayGainTrackPeak: 0.9877m, + replayGainAlbumGain: -6.8m, + replayGainAlbumPeak: 0.9999m); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaybackManifestResponse? manifest = await ReadManifestAsync(response); + Assert.NotNull(manifest); + Assert.Equal(trackId, manifest!.TrackId); + Assert.True(manifest.DirectPlay); + Assert.Equal("FLAC", manifest.SourceContainer); + Assert.Equal("FLAC", manifest.SourceCodec); + Assert.Equal(-7.5m, manifest.ReplayGainTrackGain); + Assert.Equal(0.9877m, manifest.ReplayGainTrackPeak); + Assert.Equal(-6.8m, manifest.ReplayGainAlbumGain); + Assert.Equal(0.9999m, manifest.ReplayGainAlbumPeak); + Assert.Null(manifest.DeliveryContainer); + Assert.Null(manifest.DeliveryCodec); + Assert.Null(manifest.DeliveryShape); + Assert.Null(manifest.SegmentDurationSeconds); + Assert.True(manifest.Seekable); + Assert.Equal($"/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream", manifest.StreamPath); + Assert.DoesNotContain("http", manifest.StreamPath, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task GetPlaybackManifest_WhenPlayerCannotDecodeTheStoredCodec_ShouldReturnTranscodedDelivery() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "OGG", audioCodec: "OPUS"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaybackManifestResponse? manifest = await ReadManifestAsync(response); + Assert.NotNull(manifest); + Assert.Equal(trackId, manifest!.TrackId); + Assert.False(manifest.DirectPlay); + Assert.Equal("MP3", manifest.DeliveryContainer); + Assert.Equal("MP3", manifest.DeliveryCodec); + Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, manifest.DeliveryShape); + Assert.Equal(6, manifest.SegmentDurationSeconds); + Assert.True(manifest.Seekable); + } + + [Fact] + public async Task GetPlaybackManifest_WhenTrackIsRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "FLAC", audioCodec: "FLAC"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{trackId}/playback-manifest"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetPlaybackManifest_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + (Guid otherUserId, _) = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, container: "FLAC", audioCodec: "FLAC"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Dictionary? problemDetails = JsonSerializer.Deserialize>(await response.Content.ReadAsStringAsync(), _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetPlaybackManifest_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album. + /// + /// The Id of the user that owns the library. + /// The container of the audio file of the seeded track. + /// The codec of the audio of the seeded track. + /// Optional. The ReplayGain track gain of the seeded track, in decibels. + /// Optional. The ReplayGain track peak of the seeded track. + /// Optional. The ReplayGain album gain of the seeded track, in decibels. + /// Optional. The ReplayGain album peak of the seeded track. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync( + Guid userId, + string container, + string audioCodec, + decimal? replayGainTrackGain = null, + decimal? replayGainTrackPeak = null, + decimal? replayGainAlbumGain = null, + decimal? replayGainAlbumPeak = null) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music)); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen")); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera")); + dbContext.Tracks.Add(_trackEntityFixture.Create( + id: trackId, + albumId: albumId, + libraryId: libraryId, + container: container, + audioCodec: audioCodec, + title: "A Track", + includeMetadata: false, + replayGainTrackGain: replayGainTrackGain, + replayGainTrackPeak: replayGainTrackPeak, + replayGainAlbumGain: replayGainAlbumGain, + replayGainAlbumPeak: replayGainAlbumPeak)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId, trackId); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user and its username. + private async Task<(Guid userId, string username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return (userId, username); + } + + /// + /// Reads the playback manifest of a response. + /// + /// The HTTP response to read. + /// The deserialized playback manifest. + private async Task ReadManifestAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Reads the problem details of a response. + /// + /// The HTTP response to read. + /// The deserialized problem details. + private async Task ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Removes the test user created for the tests. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} From aab36dcd29874b66020ff1d93a41ce1a747e2e4c Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 15 Oct 2026 18:52:23 +0300 Subject: [PATCH 10/77] Adds the web track streaming proxy and streaming HTTP client --- .../Common/Api/ApiStreamResult.cs | 104 ++++++++++++ .../Common/Api/IStreamingApiHttpClient.cs | 23 +++ .../Common/Api/StreamingApiHttpClient.cs | 125 ++++++++++++++ .../MusicLibrary/PlaybackManifestDto.cs | 105 ++++++++++++ .../PresentationWebLayerServices.cs | 40 +++++ .../AudioLibrary/PlaybackDeliveryShape.cs | 23 +++ .../ExceptionHandlingMiddleware.cs | 157 ++++++++++++++---- .../Tracks/GetPlaybackManifestRequest.cs | 23 +++ .../Tracks/StreamMusicTrackRequest.cs | 21 +++ .../Common/Routes/ApiRoutes.Music.cs | 2 + .../Common/Routes/WebRoutes.Music.cs | 2 + .../GetPlaybackManifestEndpoint.cs | 141 ++++++++++++++++ .../GetPlaybackManifestEndpointSummary.cs | 31 ++++ .../StreamMusicTrackEndpoint.cs | 152 +++++++++++++++++ .../StreamMusicTrackEndpointSummary.cs | 38 +++++ src/Lumina.Presentation.Web/Program.cs | 2 + .../wwwroot/js/site.js | 9 +- 17 files changed, 969 insertions(+), 29 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs create mode 100644 src/Lumina.Presentation.Web/Common/Api/IStreamingApiHttpClient.cs create mode 100644 src/Lumina.Presentation.Web/Common/Api/StreamingApiHttpClient.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackDeliveryShape.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequest.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointSummary.cs diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs b/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs new file mode 100644 index 00000000..b7889d22 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Api; + +/// +/// Represents the streamed response of a remote API request. It exposes the status code, the range related headers and the +/// content stream of the response, so that a caller can forward the response to a client without ever buffering its content. +/// +public sealed class ApiStreamResult : IAsyncDisposable +{ + private readonly HttpResponseMessage _response; + + /// + /// Gets the status code of the response. + /// + public HttpStatusCode StatusCode { get; } + + /// + /// Gets the content stream of the response. + /// + public Stream Content { get; } + + /// + /// Gets the media type of the content of the response, or when the response declares none. + /// + public string? ContentType { get; } + + /// + /// Gets the length of the content of the response, or when the response declares none. + /// + public long? ContentLength { get; } + + /// + /// Gets the range of the content of the response, when the response is a partial content response. + /// + public string? ContentRange { get; } + + /// + /// Gets the ranges the remote API accepts, when the response declares them. + /// + public string? AcceptRanges { get; } + + /// + /// Gets the entity tag of the content of the response, when the response declares one. + /// + public string? ETag { get; } + + /// + /// Gets the date and time the content of the response was last modified, when the response declares it. + /// + public DateTimeOffset? LastModified { get; } + + /// + /// Gets the caching instructions of the response, when the response declares them. + /// + public string? CacheControl { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The response returned by the remote API. + /// The content stream of the response. + private ApiStreamResult(HttpResponseMessage response, Stream content) + { + _response = response; + Content = content; + StatusCode = response.StatusCode; + ContentType = response.Content.Headers.ContentType?.ToString(); + ContentLength = response.Content.Headers.ContentLength; + ContentRange = response.Content.Headers.ContentRange?.ToString(); + AcceptRanges = response.Headers.AcceptRanges.Count > 0 ? string.Join(", ", response.Headers.AcceptRanges) : null; + ETag = response.Headers.ETag?.ToString(); + LastModified = response.Content.Headers.LastModified; + CacheControl = response.Headers.CacheControl?.ToString(); + } + + /// + /// Creates a from a response, without buffering the content of the response. + /// + /// The response returned by the remote API. + /// Cancellation token that can be used to stop the execution. + /// The streamed response. + public static async Task CreateAsync(HttpResponseMessage response, CancellationToken cancellationToken) + { + Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + return new ApiStreamResult(response, content); + } + + /// + /// Disposes the content stream and the response it belongs to. + /// + public async ValueTask DisposeAsync() + { + await Content.DisposeAsync().ConfigureAwait(false); + _response.Dispose(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Api/IStreamingApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IStreamingApiHttpClient.cs new file mode 100644 index 00000000..756ccf15 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Api/IStreamingApiHttpClient.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Api; + +/// +/// Interface for typed clients that stream responses from the remote API without buffering their content. +/// +public interface IStreamingApiHttpClient +{ + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the response as a stream, without ever buffering its content in memory. + /// + /// The API endpoint where the request is being sent. + /// The range and conditional headers of the incoming request to forward, so that the API, + /// which is the only party that knows the entity tag and the modification time of the resource, validates them itself. + /// Cancellation token that can be used to stop the execution. + /// The streamed response of the API request, which the caller must dispose once it has finished copying it. + Task GetStreamAsync(string endpoint, IReadOnlyDictionary requestHeaders, CancellationToken cancellationToken = default); +} diff --git a/src/Lumina.Presentation.Web/Common/Api/StreamingApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/StreamingApiHttpClient.cs new file mode 100644 index 00000000..0b8b3227 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Api/StreamingApiHttpClient.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Exceptions; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Api; + +/// +/// Typed client for streaming API access. Unlike , it never buffers a response in memory and is +/// intentionally free of any retry or circuit breaker policy, because a stream is meant to be handed to the client as a whole. +/// +public class StreamingApiHttpClient : IStreamingApiHttpClient +{ + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly HttpClient _httpClient; + private readonly HttpContext? _httpContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected HttpClient for interacting with the API. + /// Injected service for providing the current HTTP context. + /// Injected server configuration application settings. + public StreamingApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot serverConfigurationOptions) + { + _httpClient = httpClient; + _httpContext = httpContextAccessor.HttpContext; + // Read the API server configuration values from the configuration, and assign them to the injected client. + ServerConfigurationDto serverConfiguration = serverConfigurationOptions.Value; + httpClient.BaseAddress = new Uri($"{serverConfiguration.BaseAddress}:{serverConfiguration.Port}/api/v{serverConfiguration.ApiVersion}/"); + // A streamed response stays open for as long as the client keeps reading it, so the timeout is generously large, but it is bounded: + // an upstream that accepts the request and never answers must not hold a connection and a stream permit open forever. No track, and + // no movie, is longer than this. + httpClient.Timeout = TimeSpan.FromHours(12); + } + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the response + /// as a stream, without ever buffering its content in memory. + /// + /// The API endpoint where the request is being sent. + /// The range and conditional headers of the incoming request to forward, so that the API, which is the only party that knows the entity tag and the modification time of the resource, validates them itself. + /// Cancellation token that can be used to stop the execution. + /// The streamed response of the API request, which the caller must dispose once it has finished copying it. + /// Thrown if the response is not successful, with the if available. + public async Task GetStreamAsync(string endpoint, IReadOnlyDictionary requestHeaders, CancellationToken cancellationToken = default) + { + using (HttpRequestMessage request = new(HttpMethod.Get, endpoint)) + { + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; + // The range and the conditional headers are forwarded as they are, so that the API, and never this client, decides what a partial response contains. + foreach (KeyValuePair header in requestHeaders) + request.Headers.TryAddWithoutValidation(header.Key, header.Value); + + // Only the headers of the response are awaited, so that its content is streamed to the client instead of being copied into memory first. + HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + // A not modified response and a range not satisfiable response are valid outcomes of a conditional or ranged request, and their + // headers (the entity tag, the last modified date, the content range) are the whole answer, so they are passed through instead of + // being turned into an error, which would drop the very headers the caller needs to revalidate or recover. + if (!response.IsSuccessStatusCode && response.StatusCode != HttpStatusCode.NotModified && response.StatusCode != HttpStatusCode.RequestedRangeNotSatisfiable) + { + HttpStatusCode statusCode = response.StatusCode; + string content; + try + { + content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + // The response is turned into an exception, so it is disposed even when reading its error body fails, otherwise its connection would leak. + response.Dispose(); + } + ProblemDetailsDto? problemDetails = null; + try + { + problemDetails = JsonSerializer.Deserialize(content, s_jsonOptions); + } + catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } + throw new ApiException(problemDetails, statusCode, request.RequestUri?.AbsolutePath); + } + try + { + return await ApiStreamResult.CreateAsync(response, cancellationToken).ConfigureAwait(false); + } + catch + { + // The response was already received, so it must be disposed if its content stream could not be obtained, otherwise its connection would leak. + response.Dispose(); + throw; + } + } + } + + /// + /// Retrieves the authentication header for the current user, if available. + /// + /// + /// An with a Bearer token if the user's token is found, otherwise. + /// + private AuthenticationHeaderValue? GetAuthenticationHeader() + { + string? token = _httpContext?.User?.FindFirst("Token")?.Value; + return !string.IsNullOrEmpty(token) ? new AuthenticationHeaderValue("Bearer", token) : null; + } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs new file mode 100644 index 00000000..0e4b2a53 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.AudioLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for the playback manifest of a track, describing the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream. +/// +[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")] +public class PlaybackManifestDto +{ + /// + /// Gets or sets the Id of the track the manifest describes. + /// + public Guid TrackId { get; set; } + + /// + /// Gets or sets the duration of the audio of the track, in seconds. + /// + public int DurationInSeconds { get; set; } + + /// + /// Gets or sets the container of the audio file of the track, as stored by the probe. + /// + public string? SourceContainer { get; set; } + + /// + /// Gets or sets the codec of the audio of the track, as stored by the probe. + /// + public string? SourceCodec { get; set; } + + /// + /// Gets or sets the sample rate of the audio of the track, in Hz. + /// + public int SampleRate { get; set; } + + /// + /// Gets or sets the number of audio channels of the track. + /// + public int Channels { get; set; } + + /// + /// Gets or sets the bit depth of the audio of the track. + /// + public int? BitDepth { get; set; } + + /// + /// Gets or sets the ReplayGain track gain of the track, in decibels. + /// + public decimal? ReplayGainTrackGain { get; set; } + + /// + /// Gets or sets the ReplayGain track peak of the track. + /// + public decimal? ReplayGainTrackPeak { get; set; } + + /// + /// Gets or sets the ReplayGain album gain of the track, in decibels. + /// + public decimal? ReplayGainAlbumGain { get; set; } + + /// + /// Gets or sets the ReplayGain album peak of the track. + /// + public decimal? ReplayGainAlbumPeak { get; set; } + + /// + /// Gets or sets whether the player can play the stored audio as it is, without the server changing its container or its codec. + /// + public bool DirectPlay { get; set; } + + /// + /// Gets or sets the container of the audio the server delivers, when the delivery is not a direct play. + /// + public string? DeliveryContainer { get; set; } + + /// + /// Gets or sets the codec of the audio the server delivers, when the delivery is not a direct play. + /// + public string? DeliveryCodec { get; set; } + + /// + /// Gets or sets the shape the delivered audio is addressed and seeked by, when the delivery is not a direct play. + /// + public PlaybackDeliveryShape? DeliveryShape { get; set; } + + /// + /// Gets or sets the duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments. + /// + public int? SegmentDurationSeconds { get; set; } + + /// + /// Gets or sets whether the delivered audio can be seeked by the player. + /// + public bool Seekable { get; set; } + + /// + /// Gets or sets the path of the track stream. The API returns it relative to itself; this web application replaces it with + /// the URL of its own streaming proxy, so that the browser never reaches the API server directly. + /// + public string StreamPath { get; set; } = string.Empty; +} diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index ddd8275a..8c424fe3 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -20,6 +20,7 @@ using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization.Routing; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Razor; +using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.DependencyInjection; using Polly; using Polly.CircuitBreaker; @@ -31,7 +32,9 @@ using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; +using System.Security.Claims; using System.Text.Json.Serialization; +using System.Threading.RateLimiting; using System.Threading.Tasks; #endregion @@ -43,6 +46,11 @@ namespace Lumina.Presentation.Web.Common.DependencyInjection; [ExcludeFromCodeCoverage] public static class PresentationWebLayerServices { + /// + /// The name of the rate limiting policy that bounds the number of concurrent track streams held by a single user. + /// + public const string TRACK_STREAM_RATE_LIMIT_POLICY = "trackStreamPolicy"; + /// /// Registers the services of the Presentation Web layer into the Dependency Injection container. /// @@ -288,6 +296,26 @@ public static class PresentationWebLayerServices AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); + // Bound the number of long lived streams a single user can hold open at once, mirroring the concurrency limit the API server applies to + // its own stream route. Without it, an authenticated user could make this application open an unbounded number of parallel streams, each + // pinning a connection towards the API for the whole duration of a track, turning this application into an exhaustion amplifier. + services.AddRateLimiter(rateLimiterOptions => + { + rateLimiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + rateLimiterOptions.AddPolicy(TRACK_STREAM_RATE_LIMIT_POLICY, httpContext => + { + // The limit is partitioned per authenticated user, and it is a concurrency limit, not a per IP attempt window, so it is deliberately separate from any login throttling. + string userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous"; + return RateLimitPartition.GetConcurrencyLimiter( + partitionKey: $"trackStream_{userId}", + factory: _ => new ConcurrencyLimiterOptions + { + PermitLimit = 4, // Allow 4 concurrent audio streams per user, matching the API server. + QueueLimit = 0 // Don't queue requests, a request beyond the limit is rejected instead of waiting. + }); + }); + }); + // Register the HTTP typed client used for the API interaction. services.AddHttpClient() .AddHttpMessageHandler() @@ -295,6 +323,18 @@ public static class PresentationWebLayerServices .AddPolicyHandler(retryPolicy) .AddPolicyHandler(circuitBreakerPolicy); + // Register the HTTP typed client used for streaming responses from the API. It deliberately has no retry and no circuit breaker policy, + // because a stream cannot be transparently retried once its content has started reaching the client. It configures a bounded, generous + // timeout itself, because a stream stays open for as long as the client keeps reading it, yet a stalled one must never be held forever. + services.AddHttpClient() + // Cap the connections a stream can pin towards the API, as a backstop on top of the per user concurrency limit of the stream route. + .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler + { + // A blackholed connection attempt must fail on its own, well before the request timeout, instead of holding a stream permit. + ConnectTimeout = TimeSpan.FromSeconds(30), + MaxConnectionsPerServer = 64 + }); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackDeliveryShape.cs b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackDeliveryShape.cs new file mode 100644 index 00000000..d1c6a97a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackDeliveryShape.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the shapes in which delivered audio is addressed and seeked. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaybackDeliveryShape +{ + /// + /// The delivered media is the original file itself, addressed and seeked by byte range. + /// + ByteRangeSeekable, + + /// + /// The delivered media is a sequence of fixed duration segments, addressed and seeked by time, so that finding a time never + /// requires mapping a byte range to it. + /// + TimeAddressedSegments, +} diff --git a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs index 5be0b61e..5dff1bc5 100644 --- a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Net; using System.Text; using System.Text.Json; +using System.Threading; using System.Threading.Tasks; #endregion @@ -47,6 +48,11 @@ public class ExceptionHandlingMiddleware { await _next(context); } + catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) + { + // The client went away while its request or response was being processed, so there is nobody left to answer. + context.Abort(); + } catch (ApiException apiException) // threat API exceptions differently - they contain Problem Details properties { await HandleApiExceptionAsync(context, apiException); @@ -54,6 +60,13 @@ public class ExceptionHandlingMiddleware catch (Exception ex) // other cases - { _logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message); + // Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection + // is aborted instead, so that the client sees a failed transfer rather than a success response it cannot trust. + if (context.Response.HasStarted) + { + context.Abort(); + return; + } // return a JSON result with the error details await WriteJsonResponseAsync(context, new { @@ -77,34 +90,23 @@ public class ExceptionHandlingMiddleware apiException.ProblemDetails?.Detail, apiException.ProblemDetails?.Extensions); + // Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection + // is aborted instead, so that the client sees a failed transfer rather than a redirect it could not follow or a body it would misread. + if (context.Response.HasStarted) + { + context.Abort(); + return; + } + // handle unauthorized errors by prompting the user to re-login if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in) await HandleUnauthorizedAsync(context); else if (apiException.HttpStatusCode == HttpStatusCode.NotFound) // await HandleNotFoundAsync(context, apiException); else if (apiException.HttpStatusCode == HttpStatusCode.Forbidden) - { - if (IsApiRequest(context)) - { - string errorMessage = BuildErrorMessage(apiException); - await WriteJsonResponseAsync(context, new - { - success = false, - errorMessage - }); - } - else - await context.ForbidAsync(); - } + await HandleForbiddenAsync(context, apiException); else - { - string errorMessage = BuildErrorMessage(apiException); - await WriteJsonResponseAsync(context, new - { - success = false, - errorMessage - }); - } + await HandleGenericApiErrorAsync(context, apiException); } /// @@ -120,7 +122,7 @@ public class ExceptionHandlingMiddleware return; } - if (IsApiRequest(context)) + if (IsJsonRequest(context)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; await WriteJsonResponseAsync(context, new @@ -129,7 +131,7 @@ public class ExceptionHandlingMiddleware errorMessage = "NotFound" }); } - else + else if (IsNavigationRequest(context)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; @@ -138,6 +140,48 @@ public class ExceptionHandlingMiddleware _logger.LogInformation("Redirecting user to NotFound url"); context.Response.Redirect(notFoundUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too } + else + await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.NotFound).ConfigureAwait(false); + } + + /// + /// Handles forbidden exceptions. + /// + private async Task HandleForbiddenAsync(HttpContext context, ApiException apiException) + { + if (IsJsonRequest(context)) + { + string errorMessage = BuildErrorMessage(apiException); + await WriteJsonResponseAsync(context, new + { + success = false, + errorMessage + }); + } + else if (IsNavigationRequest(context)) + await context.ForbidAsync(); + else + await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.Forbidden).ConfigureAwait(false); + } + + /// + /// Handles the API exceptions that are neither authentication, authorization, nor not found failures. + /// + private async Task HandleGenericApiErrorAsync(HttpContext context, ApiException apiException) + { + // JSON callers and page navigations get the localized error message; any other caller, like an audio request, is answered with + // a bare status code, because a JSON body is not a representation such a caller can consume. + if (IsJsonRequest(context) || IsNavigationRequest(context)) + { + string errorMessage = BuildErrorMessage(apiException); + await WriteJsonResponseAsync(context, new + { + success = false, + errorMessage + }); + } + else + await WriteStatusOnlyResponseAsync(context, (int)apiException.HttpStatusCode).ConfigureAwait(false); } /// @@ -149,7 +193,7 @@ public class ExceptionHandlingMiddleware await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false); context.Response.Cookies.Delete("Token"); - if (IsApiRequest(context)) + if (IsJsonRequest(context)) { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await WriteJsonResponseAsync(context, new @@ -158,7 +202,7 @@ public class ExceptionHandlingMiddleware errorMessage = "Unauthorized" }); } - else + else if (IsNavigationRequest(context)) { string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us"; string returnUrl = $"{context.Request.Path}{context.Request.QueryString}"; @@ -166,6 +210,8 @@ public class ExceptionHandlingMiddleware _logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl); context.Response.Redirect(loginUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too } + else + await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.Unauthorized).ConfigureAwait(false); } /// @@ -203,11 +249,38 @@ public class ExceptionHandlingMiddleware } /// - /// Checks if the current request is an API request. + /// Checks if the current request is a programmatic request that expects a JSON response. /// - private static bool IsApiRequest(HttpContext context) + /// + /// Every request is classified into exactly one of three kinds: a JSON request, which this method detects, a browser navigation, which + /// detects, and a raw request, which is neither of the two and is answered with a bare status code. + /// + /// The for the current request. + /// when the request expects JSON, otherwise. + private static bool IsJsonRequest(HttpContext context) { - return context.Request.Headers.Accept.Any(x => x?.Contains("application/json") == true) || context.Request.Headers.XRequestedWith == "XMLHttpRequest"; + return context.Request.Headers.Accept.Any(accept => accept?.Contains("application/json", StringComparison.OrdinalIgnoreCase) == true) + || context.Request.Headers.XRequestedWith == "XMLHttpRequest"; + } + + /// + /// Checks if the current request is a browser navigation, which is the only kind of request that can follow a redirect. + /// + /// + /// A request that explicitly asks for something other than HTML, like an audio or a media request, is answered with a bare status + /// code: treating it as a page would redirect it to an HTML login or not-found page, which its caller cannot consume. A request that + /// states no preference at all keeps the historical page behavior, so that callers that send no Accept header are not silently + /// changed, but a request that carries no Accept yet asks for a byte range is treated as a raw request, because a headerless + /// range request comes from a media client or a probe, not from a browser. + /// + /// The for the current request. + /// when the request is a navigation, otherwise. + private static bool IsNavigationRequest(HttpContext context) + { + return (context.Request.Headers.Accept.Count == 0 && context.Request.Headers.Range.Count == 0) + || context.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true) + || string.Equals(context.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase) + || string.Equals(context.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase); } /// @@ -219,6 +292,34 @@ public class ExceptionHandlingMiddleware await context.Response.WriteAsJsonAsync(response); } + /// + /// Writes the response of a raw request, which is a status code and no body. + /// + /// + /// This is the third branch of the request classification, the one that answers a request that is neither a JSON request, which + /// detects, nor a browser navigation, which detects. + /// + /// The for the current request. + /// The status code to answer with. + private async Task WriteStatusOnlyResponseAsync(HttpContext context, int statusCode) + { + context.Response.StatusCode = statusCode; + context.Response.ContentLength = 0; + try + { + // Starting the response commits the status code and the headers, so that no outer middleware replaces this decision with a page, + // and so that a caller that asked for content never receives HTML instead. A token that is never cancelled is used on purpose, + // because a request whose token is already cancelled would otherwise throw here, inside the exception handler, and escape it. + await context.Response.StartAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception startException) + { + // There is nobody left to answer, so the connection is aborted, and the failure is only recorded for diagnostics. + _logger.LogDebug(startException, "Could not commit the status only response, the client has likely disconnected."); + context.Abort(); + } + } + /// /// Determines whether the API exception originated from the authorization check of the currently logged in user. /// diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequest.cs new file mode 100644 index 00000000..4ed17207 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequest.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to get the playback manifest of a track. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. Required. +/// The unique identifier of the album the track belongs to, taken from the route. Required. +/// The unique identifier of the track whose manifest is requested, taken from the route. Required. +/// The Id of the media library the track belongs to. Required. +/// The comma separated list of the container and codec pairs the player advertises it can play directly. Optional. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetPlaybackManifestRequest( + string ArtistId, + string AlbumId, + string TrackId, + Guid LibraryId, + string? Capabilities +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequest.cs new file mode 100644 index 00000000..8a0dfbbd --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to stream the audio file of a track. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. Required. +/// The unique identifier of the album the track belongs to, taken from the route. Required. +/// The unique identifier of the track to stream, taken from the route. Required. +/// The Id of the media library the track belongs to. Required. +[DebuggerDisplay("TrackId: {TrackId}")] +public record StreamMusicTrackRequest( + string ArtistId, + string AlbumId, + string TrackId, + Guid LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs index e1778db2..ad360ddd 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs @@ -24,5 +24,7 @@ public static partial class ApiRoutes public const string GET_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string UPDATE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + public const string STREAM_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + public const string GET_PLAYBACK_MANIFEST = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs index dd707299..490c65fb 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs @@ -28,5 +28,7 @@ public static partial class WebRoutes public const string GET_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-track"; public const string SAVE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track"; public const string DELETE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-delete-track"; + public const string STREAM_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track"; + public const string GET_PLAYBACK_MANIFEST = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest"; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs new file mode 100644 index 00000000..9048d86c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest route. +/// +public class GetPlaybackManifestEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPlaybackManifestEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Music.GET_PLAYBACK_MANIFEST); + DontAutoTag(); + Options(options => options.WithTags("Music")); + } + + /// + /// Retrieves the playback manifest of the track identified by , with the stream path of this application. + /// + /// The request containing the Ids of the artist, album, track and media library to get the manifest of, and the capabilities of the player. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPlaybackManifestRequest request, CancellationToken cancellationToken) + { + // The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted route value can never + // escape its URL segment, and an unparseable id is reported by the API as a missing id. + string normalizedArtistId = Guid.TryParse(request.ArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string normalizedAlbumId = Guid.TryParse(request.AlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString(); + string normalizedTrackId = Guid.TryParse(request.TrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString(); + string endpoint = ApiRoutes.Music.GET_PLAYBACK_MANIFEST + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", normalizedArtistId) + .Replace("{albumId}", normalizedAlbumId) + .Replace("{trackId}", normalizedTrackId); + // The capabilities the player advertises are optional and are forwarded only when the player sent them. + if (!string.IsNullOrWhiteSpace(request.Capabilities)) + endpoint = $"{endpoint}?capabilities={Uri.EscapeDataString(request.Capabilities)}"; + + PlaybackManifestDto? manifest = await _apiHttpClient.GetAsync(endpoint, cancellationToken).ConfigureAwait(false) ?? throw new ApiException(new ProblemDetailsDto + { + Title = "General.Failure", + Detail = "InternalServerError", + Status = StatusCodes.Status502BadGateway + }, HttpStatusCode.BadGateway, endpoint); + // The API only knows the relative path of its own stream endpoint, and the browser only reaches this application, so the path is + // replaced with the path of the streaming proxy of this application, which is the URL the player actually consumes. + manifest.StreamPath = BuildBrowserStreamPath(request.LibraryId, normalizedArtistId, normalizedAlbumId, normalizedTrackId); + return JsonSuccess(manifest); + } + + /// + /// Builds the browser facing relative path of the streaming proxy of this application for the track identified by the given Ids. + /// + /// + /// The path is built from the route template of this application, and never from the host, the scheme, or the port of the incoming request. + /// The path base is derived from a forwarded header that a caller can spoof, so it is only used when it is a plain absolute path, and the + /// culture is confined to a single path segment, so that no part of the result can introduce an authority, which would make the browser + /// resolve the stream from another origin. + /// + /// The Id of the media library the track belongs to. + /// The normalized Id of the artist the album belongs to. + /// The normalized Id of the album the track belongs to. + /// The normalized Id of the track. + /// The root relative path the browser fetches the stream from, on its own origin. + private string BuildBrowserStreamPath(Guid libraryId, string artistId, string albumId, string trackId) + { + string culture = IsSafePathSegment(Culture) ? Culture : "en-US"; + string pathBase = IsSafePathBase(HttpContext.Request.PathBase.ToString()) ? HttpContext.Request.PathBase.ToString().TrimEnd('/') : string.Empty; + string streamPath = WebRoutes.Music.STREAM_TRACK + .Replace("{culture}", culture, StringComparison.OrdinalIgnoreCase) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + return $"{pathBase}/{streamPath}?libraryId={libraryId}"; + } + + /// + /// Checks whether a value can be used safely as a single segment of a path the browser resolves against its own origin. + /// + /// The value to check. + /// when the value cannot introduce a path separator, a query, a fragment, or a control character, otherwise. + private static bool IsSafePathSegment(string value) + { + if (string.IsNullOrEmpty(value)) + return false; + foreach (char character in value) + if (character == '/' || character == '\\' || character == '?' || character == '#' || character == '%' || char.IsControl(character)) + return false; + return true; + } + + /// + /// Checks whether a value can be used safely as the path base of a path the browser resolves against its own origin. + /// + /// The path base to check. + /// when the value is a plain absolute path, otherwise. + private static bool IsSafePathBase(string pathBase) + { + if (string.IsNullOrEmpty(pathBase)) + return true; + // A path base that does not start with a single slash, or that contains a backslash or a control character, can be normalized by a + // browser into a protocol relative or absolute reference, which would point the stream fetch at another origin. A query or a fragment + // (or an escape that decodes into one) would truncate the built path instead. + if (!pathBase.StartsWith('/') || pathBase.StartsWith("//", StringComparison.Ordinal)) + return false; + foreach (char character in pathBase) + if (character == '\\' || character == '?' || character == '#' || character == '%' || char.IsControl(character)) + return false; + return !pathBase.Contains("//", StringComparison.Ordinal); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs new file mode 100644 index 00000000..8b201df0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackManifestEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackManifestEndpointSummary() + { + Summary = "Retrieves the playback manifest of a music track."; + Description = "Retrieves the playback manifest of the music track identified by the route, with the stream path replaced by the URL of the streaming proxy of this application."; + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to. Required."); + RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required."); + RequestParam(r => r.TrackId, "The unique identifier of the track whose manifest is requested. Required."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required."); + RequestParam(r => r.Capabilities, "The comma separated list of the container and codec pairs the player advertises it can play directly. Optional."); + + Response(200, "The playback manifest of the track is retrieved."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs new file mode 100644 index 00000000..eb8b455b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs @@ -0,0 +1,152 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; +using System; +using System.Collections.Generic; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track route. +/// +public class StreamMusicTrackEndpoint : BaseEndpoint +{ + private readonly IStreamingApiHttpClient _streamingApiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for streaming interactions with the API. + public StreamMusicTrackEndpoint(IStreamingApiHttpClient streamingApiHttpClient) + { + _streamingApiHttpClient = streamingApiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Music.STREAM_TRACK); + DontAutoTag(); + // The stream is bounded per user with a concurrency limit, exactly like the stream route of the API server, so that a single user can + // never hold an unbounded number of long lived streams open at once and exhaust the connections towards the API. + Options(options => options + .WithTags("Music") + .RequireRateLimiting(PresentationWebLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY)); + } + + /// + /// Streams the audio file of the track identified by through the API, without buffering it. + /// + /// The request containing the Ids of the artist, album, track and media library to stream. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StreamMusicTrackRequest request, CancellationToken cancellationToken) + { + // The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted route value can never + // escape its URL segment, and an unparseable id is reported by the API as a missing id. + string normalizedArtistId = Guid.TryParse(request.ArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string normalizedAlbumId = Guid.TryParse(request.AlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString(); + string normalizedTrackId = Guid.TryParse(request.TrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString(); + string endpoint = ApiRoutes.Music.STREAM_TRACK + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", normalizedArtistId) + .Replace("{albumId}", normalizedAlbumId) + .Replace("{trackId}", normalizedTrackId); + // The range and the conditional headers that revalidate it are forwarded as they are, so that the API, which is the only party that + // knows the entity tag and the modification time of the file, answers a partial, a resumed, or an unchanged request by itself. + Dictionary forwardHeaders = []; + AddHeader(forwardHeaders, "Range", HttpContext.Request.Headers.Range); + AddHeader(forwardHeaders, "If-Range", HttpContext.Request.Headers.IfRange); + AddHeader(forwardHeaders, "If-None-Match", HttpContext.Request.Headers.IfNoneMatch); + AddHeader(forwardHeaders, "If-Modified-Since", HttpContext.Request.Headers.IfModifiedSince); + + // The API response is disposed once the copy ends, so that the underlying connection is released as soon as the client stops reading. + await using (ApiStreamResult streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, forwardHeaders, cancellationToken).ConfigureAwait(false)) + { + HttpContext.Response.StatusCode = (int)streamResult.StatusCode; + CopyResponseHeaders(HttpContext.Response, streamResult); + // The caching instructions of the API are forwarded, so that the web hop never silently ignores a caching decision the API made, + // but the response is always private to the user, and it varies by the cookie that authenticates this hop: the browser never sends + // the bearer token the API sees. + HttpContext.Response.Headers["Cache-Control"] = BuildCacheControl(streamResult.CacheControl); + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The body is copied straight from the API to the client, with no intermediate buffering, and the copy is abandoned when the client disconnects. + await streamResult.Content.CopyToAsync(HttpContext.Response.Body, cancellationToken).ConfigureAwait(false); + } + return Results.Empty; + } + + /// + /// Adds a request header to the set of headers forwarded to the API, unless the incoming request did not carry it. + /// + /// The set of headers forwarded to the API. + /// The name of the header. + /// The value of the header in the incoming request, which is empty when the header was not sent. + private static void AddHeader(Dictionary headers, string name, StringValues value) + { + if (value.Count > 0 && !string.IsNullOrWhiteSpace(value.ToString())) + headers[name] = value.ToString(); + } + + /// + /// Copies the status and resource headers of the streamed API response to the response sent to the browser. + /// + /// The response sent to the browser. + /// The streamed response of the API. + private static void CopyResponseHeaders(HttpResponse response, ApiStreamResult streamResult) + { + if (!string.IsNullOrEmpty(streamResult.ContentType)) + response.ContentType = streamResult.ContentType; + if (streamResult.ContentLength.HasValue) + response.ContentLength = streamResult.ContentLength.Value; + SetHeader(response, "Content-Range", streamResult.ContentRange); + SetHeader(response, "Accept-Ranges", streamResult.AcceptRanges); + SetHeader(response, "ETag", streamResult.ETag); + SetHeader(response, "Last-Modified", streamResult.LastModified?.ToString("R")); + } + + /// + /// Sets a response header to the given value, unless the value is missing. + /// + /// The response to set the header on. + /// The name of the header. + /// The value of the header, or when the API did not send it. + private static void SetHeader(HttpResponse response, string name, string? value) + { + if (!string.IsNullOrEmpty(value)) + response.Headers[name] = value; + } + + /// + /// Builds the caching instructions of the response sent to the browser from the instructions of the API. + /// + /// + /// A stream is specific to the authenticated user, so it must never be stored by a shared cache. Every other instruction of the API, + /// like a maximum age for the private cache of the browser or a no-store, is kept, so that the web hop never silently ignores a caching + /// decision the API made for the resource. + /// + /// The caching instructions of the API response, or when it declared none. + /// The caching instructions of the response sent to the browser. + private static string BuildCacheControl(string? apiCacheControl) + { + if (!CacheControlHeaderValue.TryParse(apiCacheControl, out CacheControlHeaderValue? cacheControl)) + cacheControl = new CacheControlHeaderValue(); + cacheControl.Public = false; + cacheControl.Private = true; + return cacheControl.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointSummary.cs new file mode 100644 index 00000000..bcbcef3f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointSummary.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StreamMusicTrackEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StreamMusicTrackEndpointSummary() + { + Summary = "Streams the audio file of a music track."; + Description = "Streams the audio file of the music track identified by the route, forwarding the range and the conditional headers the browser sends, so that the player can start playback before the whole file is downloaded, resume a partial download, and revalidate a cached copy."; + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to. Required."); + RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required."); + RequestParam(r => r.TrackId, "The unique identifier of the track to stream. Required."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required."); + + Response(200, "The whole audio file of the track is streamed."); + Response(206, "The requested range of the audio file of the track is streamed, with its content range."); + Response(304, "The audio file of the track did not change since the copy the browser already holds, and its validators are returned."); + Response(416, "The requested range cannot be satisfied, and the total length of the audio file is returned in the content range."); + Response(401, "The user is not authenticated."); + Response(403, "The user is not allowed to stream the track of the media library."); + Response(404, "The track, the album, the artist, or the media library was not found, or is out of the scope of the route."); + Response(429, "The user is already holding the maximum number of concurrent track streams."); + Response(502, "The remote API did not return the audio file of the track."); + } +} diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index c6d9dc6d..671b7230 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -100,6 +100,8 @@ public class Program app.UseSession(); app.UseAuthentication(); app.UseAuthorization(); + // The rate limiting policies are evaluated after authentication, because the track stream limit is partitioned per authenticated user. + app.UseRateLimiter(); // validate the antiforgery token after authentication, because the token is bound to the authenticated user and // validating it before the user is known would reject every request made by a logged-in user app.UseAntiforgeryFE(additionalContentTypes: ["application/json"]); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index 14428d1a..27911a61 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -366,7 +366,14 @@ async function updateContentAsync(url, addToHistory) { window.viewCleanups = {}; } - const response = await fetch(url); + // The in-place navigation is a page load performed through fetch, so it declares that it expects HTML. Without this header, the + // server cannot tell it apart from a media request, since both send Accept: */*, and a failed navigation (an expired session, for + // example) would be answered with a bare status code instead of the redirect to the login page this code follows. + const response = await fetch(url, { + headers: { + 'Accept': 'text/html' + } + }); if (response.redirected) // if a redirect is requested, perform it window.location.href = response.url; else { From dd76309ded31fef39561c30f71dc2918dc76974c Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 15 Oct 2026 21:09:38 +0300 Subject: [PATCH 11/77] Adds playback preferences and auto-persisted playback state to user settings --- docs/manual/using-lumina/index.md | 2 +- .../api/users-management/Api.Settings.md | 70 +- .../settings/GetPlaybackState.http | 2 + .../settings/UpdatePlaybackState.http | 8 + .../settings/UpdateUserSettings.http | 9 +- .../UsersManagement/UserSettingsEntity.cs | 36 + .../UpdatePlaybackStateRequestMapping.cs | 25 + .../Users/UpdateUserSettingsRequestMapping.cs | 7 +- .../Users/UserSettingsEntityMapping.cs | 16 +- .../Users/UserSettingsMapping.cs | 16 +- .../UpdatePlaybackStateCommand.cs | 15 + .../UpdatePlaybackStateCommandHandler.cs | 104 + .../UpdatePlaybackStateCommandValidator.cs | 31 + .../UpdateUserSettingsCommand.cs | 13 +- .../UpdateUserSettingsCommandHandler.cs | 52 +- .../UpdateUserSettingsCommandValidator.cs | 30 + .../GetPlaybackState/GetPlaybackStateQuery.cs | 10 + .../GetPlaybackStateQueryHandler.cs | 68 + .../GetUserSettingsQueryHandler.cs | 6 +- .../Settings/UpdatePlaybackStateRequest.cs | 16 + .../Settings/UpdateUserSettingsRequest.cs | 13 +- .../Settings/PlaybackStateResponse.cs | 16 + .../Settings/UserSettingsResponse.cs | 13 +- .../UserSettingsConfiguration.cs | 28 + ...ferencesAndStateToUserSettings.Designer.cs | 3463 +++++++++++++++++ ...aybackPreferencesAndStateToUserSettings.cs | 102 + .../LuminaDbContextModelSnapshot.cs | 28 + .../Playback/PlaybackStreamingQuality.cs | 30 + .../Common/Enums/Playback/ReplayGainMode.cs | 23 + .../Common/Errors/Errors.UserSettings.cs | 10 + .../UserSettingsAggregate/UserSettings.cs | 195 +- .../Routes/UsersManagement/ApiRoutes.Users.cs | 2 + .../GetPlaybackStateEndpoint.cs | 55 + .../GetPlaybackStateEndpointSummary.cs | 59 + .../GetUserSettingsEndpointSummary.cs | 8 +- .../UpdatePlaybackStateEndpoint.cs | 56 + .../UpdatePlaybackStateEndpointSummary.cs | 87 + .../UpdateUserSettingsEndpointSummary.cs | 22 +- .../DTO/UsersManagement/PlaybackStateDto.cs | 22 + .../DTO/UsersManagement/UserSettingsDto.cs | 26 + .../AudioLibrary/PlaybackStreamingQuality.cs | 35 + .../Enums/AudioLibrary/ReplayGainMode.cs | 28 + .../Common/Routes/ApiRoutes.Users.cs | 2 + .../Common/Routes/WebRoutes.Settings.cs | 2 + .../GetPlaybackStateEndpoint.cs | 53 + .../GetPlaybackStateEndpointSummary.cs | 26 + .../UpdatePlaybackStateEndpoint.cs | 54 + .../UpdatePlaybackStateEndpointSummary.cs | 30 + .../ExceptionHandlingMiddleware.ar-SA.resx | 30 + .../ExceptionHandlingMiddleware.de-DE.resx | 30 + .../ExceptionHandlingMiddleware.en-US.resx | 30 + .../ExceptionHandlingMiddleware.es-ES.resx | 30 + .../ExceptionHandlingMiddleware.fr-FR.resx | 30 + .../ExceptionHandlingMiddleware.it-IT.resx | 30 + .../ExceptionHandlingMiddleware.ja-JP.resx | 30 + .../ExceptionHandlingMiddleware.resx | 30 + .../ExceptionHandlingMiddleware.ro-RO.resx | 30 + .../ExceptionHandlingMiddleware.uk-UA.resx | 30 + .../ExceptionHandlingMiddleware.zh-CN.resx | 30 + .../Resources/Views/Tools/Settings.ar-SA.resx | 54 + .../Resources/Views/Tools/Settings.de-DE.resx | 54 + .../Resources/Views/Tools/Settings.en-US.resx | 54 + .../Resources/Views/Tools/Settings.es-ES.resx | 54 + .../Resources/Views/Tools/Settings.fr-FR.resx | 54 + .../Resources/Views/Tools/Settings.it-IT.resx | 54 + .../Resources/Views/Tools/Settings.ja-JP.resx | 54 + .../Core/Resources/Views/Tools/Settings.resx | 54 + .../Resources/Views/Tools/Settings.ro-RO.resx | 54 + .../Resources/Views/Tools/Settings.uk-UA.resx | 54 + .../Resources/Views/Tools/Settings.zh-CN.resx | 54 + .../Core/Views/Tools/Settings.cshtml | 89 +- src/Lumina.sln | 2 + .../UserSettingsEntityFixture.cs | 26 +- .../UpdateUserSettingsCommandFixture.cs | 20 +- .../UpdateUserSettingsRequestFixture.cs | 20 +- .../Settings/UserSettingsResponseFixture.cs | 20 +- .../UserSettingsFixture.cs | 26 +- .../UsersManagement/UserSettingsDtoFixture.cs | 20 +- .../UpdateUserSettingsCommandHandlerTests.cs | 37 - .../Common/Errors/ErrorsTests.cs | 12 +- .../UserSettingsTests.cs | 55 +- 81 files changed, 6102 insertions(+), 173 deletions(-) create mode 100644 docs/technical/requests/users-management/settings/GetPlaybackState.http create mode 100644 docs/technical/requests/users-management/settings/UpdatePlaybackState.http create mode 100644 src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMapping.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommand.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandler.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidator.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQuery.cs create mode 100644 src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandler.cs create mode 100644 src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdatePlaybackStateRequest.cs create mode 100644 src/Lumina.Contracts/Responses/UsersManagement/Settings/PlaybackStateResponse.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/Playback/ReplayGainMode.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/UsersManagement/PlaybackStateDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs create mode 100644 src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/ReplayGainMode.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs diff --git a/docs/manual/using-lumina/index.md b/docs/manual/using-lumina/index.md index 62a45c37..a5496021 100644 --- a/docs/manual/using-lumina/index.md +++ b/docs/manual/using-lumina/index.md @@ -87,6 +87,6 @@ Wherever Lumina needs a folder or a file from the server, it opens the file syst The tools section holds your settings and the language picker. -Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md). +Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. A final group of options shapes playback: whether the player keeps downloading while it is paused, whether it continues automatically at the end of an album or artist, whether consecutive tracks play without a gap, how ReplayGain normalizes loudness, and the quality cap used when the server has to normalize a track. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md). The **language** picker switches the interface between the languages Lumina ships with, and remembers your choice. diff --git a/docs/technical/api/users-management/Api.Settings.md b/docs/technical/api/users-management/Api.Settings.md index 53993dee..0808961a 100644 --- a/docs/technical/api/users-management/Api.Settings.md +++ b/docs/technical/api/users-management/Api.Settings.md @@ -8,6 +8,12 @@ - [Update User Settings](#update-user-settings) - [Update User Settings Request](#update-user-settings-request) - [Update User Settings Response](#update-user-settings-response) + - [Get Playback State](#get-playback-state) + - [Get Playback State Request](#get-playback-state-request) + - [Get Playback State Response](#get-playback-state-response) + - [Update Playback State](#update-playback-state) + - [Update Playback State Request](#update-playback-state-request) + - [Update Playback State Response](#update-playback-state-response) ## Settings @@ -32,11 +38,16 @@ Returns the settings of the currently authenticated user. "userId": "2cff0c0f-3a67-4e30-b94f-f4e948a3b64f", "isPaginationEnabled": true, "itemsPerPage": 50, - "ignoreThePrefixForAlphaPicker": true, + "shouldIgnoreThePrefixForAlphaPicker": true, "isThemeCachingEnabled": true, "shouldAggregateMetadataWhenMissing": true, "shouldRenderPdfAsImages": false, - "shouldPreserveBookStyles": true + "shouldPreserveBookStyles": true, + "shouldKeepDownloadingWhilePaused": true, + "shouldAutoplay": true, + "isGaplessPlaybackEnabled": true, + "replayGainMode": "Off", + "streamingQuality": "Auto" } ``` @@ -54,11 +65,16 @@ Updates the settings of the currently authenticated user. { "isPaginationEnabled": true, "itemsPerPage": 50, - "ignoreThePrefixForAlphaPicker": true, + "shouldIgnoreThePrefixForAlphaPicker": true, "isThemeCachingEnabled": true, "shouldAggregateMetadataWhenMissing": true, "shouldRenderPdfAsImages": false, - "shouldPreserveBookStyles": true + "shouldPreserveBookStyles": true, + "shouldKeepDownloadingWhilePaused": true, + "shouldAutoplay": true, + "isGaplessPlaybackEnabled": true, + "replayGainMode": "Off", + "streamingQuality": "Auto" } ``` @@ -67,3 +83,49 @@ Updates the settings of the currently authenticated user. ```js 200 Ok ``` + +### Get Playback State + +#### Get Playback State Request + +```js +GET api/v1/users/me/settings/playback-state +``` + +Returns the playback state (the last volume and mute state) the player reported for the currently authenticated user. The values are written automatically by the player and are never surfaced as settings fields. + +#### Get Playback State Response + +```js +200 Ok +``` + +```json +{ + "volume": 0.75, + "isMuted": false +} +``` + +### Update Playback State + +#### Update Playback State Request + +```js +PUT api/v1/users/me/settings/playback-state +``` + +Updates the playback state the player reported for the currently authenticated user. Both fields are required: the volume is a value between 0 and 1, and the mute state is a boolean. A request that omits either field, or sends a volume outside that range, is rejected with a `422 Unprocessable Entity`. + +```json +{ + "volume": 0.75, + "isMuted": false +} +``` + +#### Update Playback State Response + +```js +200 Ok +``` diff --git a/docs/technical/requests/users-management/settings/GetPlaybackState.http b/docs/technical/requests/users-management/settings/GetPlaybackState.http new file mode 100644 index 00000000..12b6f7cb --- /dev/null +++ b/docs/technical/requests/users-management/settings/GetPlaybackState.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/users/me/settings/playback-state +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/users-management/settings/UpdatePlaybackState.http b/docs/technical/requests/users-management/settings/UpdatePlaybackState.http new file mode 100644 index 00000000..0b712520 --- /dev/null +++ b/docs/technical/requests/users-management/settings/UpdatePlaybackState.http @@ -0,0 +1,8 @@ +PUT {{host}}/api/v1/users/me/settings/playback-state +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "volume": 0.75, + "isMuted": false +} diff --git a/docs/technical/requests/users-management/settings/UpdateUserSettings.http b/docs/technical/requests/users-management/settings/UpdateUserSettings.http index 58cb8c67..c65e30c9 100644 --- a/docs/technical/requests/users-management/settings/UpdateUserSettings.http +++ b/docs/technical/requests/users-management/settings/UpdateUserSettings.http @@ -5,9 +5,14 @@ Content-Type: application/json { "isPaginationEnabled": true, "itemsPerPage": 50, - "ignoreThePrefixForAlphaPicker": true, + "shouldIgnoreThePrefixForAlphaPicker": true, "isThemeCachingEnabled": true, "shouldAggregateMetadataWhenMissing": true, "shouldRenderPdfAsImages": false, - "shouldPreserveBookStyles": true + "shouldPreserveBookStyles": true, + "shouldKeepDownloadingWhilePaused": true, + "shouldAutoplay": true, + "isGaplessPlaybackEnabled": true, + "replayGainMode": "Off", + "streamingQuality": "Auto" } diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs index 877e541b..cf6ed5a2 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Diagnostics; #endregion @@ -65,6 +66,41 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity /// public bool ShouldPreserveBookStyles { get; set; } + /// + /// Gets or sets whether the player keeps downloading a track while playback is paused, or not, up to the entire file. + /// + public bool ShouldKeepDownloadingWhilePaused { get; set; } = true; + + /// + /// Gets or sets whether the player continues playback at the end of an album or artist, or not. + /// + public bool ShouldAutoplay { get; set; } = true; + + /// + /// Gets or sets whether the player transitions between consecutive tracks without a gap, or not. + /// + public bool IsGaplessPlaybackEnabled { get; set; } = true; + + /// + /// Gets or sets the way ReplayGain normalization is applied to the tracks the user plays. + /// + public ReplayGainMode ReplayGainMode { get; set; } + + /// + /// Gets or sets the quality cap applied to the audio the server normalizes for the user. + /// + public PlaybackStreamingQuality StreamingQuality { get; set; } + + /// + /// Gets or sets the last volume the player reported for the user. Written automatically by the player, and not part of the settings the user edits. + /// + public double Volume { get; set; } = 1.0; + + /// + /// Gets or sets the last mute state the player reported for the user. Written automatically by the player, and not part of the settings the user edits. + /// + public bool IsMuted { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMapping.cs new file mode 100644 index 00000000..31e45f8a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; +using Lumina.Contracts.Requests.UsersManagement.Settings; +#endregion + +namespace Lumina.Application.Common.Mapping.UsersManagement.Users; + +/// +/// Extension methods for converting . +/// +public static class UpdatePlaybackStateRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static UpdatePlaybackStateCommand ToCommand(this UpdatePlaybackStateRequest request) + { + return new UpdatePlaybackStateCommand( + request.Volume, + request.IsMuted + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs index a936d1b2..6f6060af 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs @@ -25,7 +25,12 @@ public static class UpdateUserSettingsRequestMapping request.ShouldAggregateMetadataWhenMissing, request.ShouldAggregateArtworkWhenMissing, request.ShouldRenderPdfAsImages, - request.ShouldPreserveBookStyles + request.ShouldPreserveBookStyles, + request.ShouldKeepDownloadingWhilePaused, + request.ShouldAutoplay, + request.IsGaplessPlaybackEnabled, + request.ReplayGainMode, + request.StreamingQuality ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs index 4da52a6f..d5e9da55 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs @@ -33,7 +33,14 @@ public static class UserSettingsEntityMapping repositoryEntity.ShouldAggregateMetadataWhenMissing, repositoryEntity.ShouldAggregateArtworkWhenMissing, repositoryEntity.ShouldRenderPdfAsImages, - repositoryEntity.ShouldPreserveBookStyles + repositoryEntity.ShouldPreserveBookStyles, + repositoryEntity.ShouldKeepDownloadingWhilePaused, + repositoryEntity.ShouldAutoplay, + repositoryEntity.IsGaplessPlaybackEnabled, + repositoryEntity.ReplayGainMode, + repositoryEntity.StreamingQuality, + repositoryEntity.Volume, + repositoryEntity.IsMuted ); } @@ -53,7 +60,12 @@ public static class UserSettingsEntityMapping repositoryEntity.ShouldAggregateMetadataWhenMissing, repositoryEntity.ShouldAggregateArtworkWhenMissing, repositoryEntity.ShouldRenderPdfAsImages, - repositoryEntity.ShouldPreserveBookStyles + repositoryEntity.ShouldPreserveBookStyles, + repositoryEntity.ShouldKeepDownloadingWhilePaused, + repositoryEntity.ShouldAutoplay, + repositoryEntity.IsGaplessPlaybackEnabled, + repositoryEntity.ReplayGainMode, + repositoryEntity.StreamingQuality ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs index aabba107..edef94fc 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs @@ -29,7 +29,14 @@ public static class UserSettingsMapping ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing, ShouldAggregateArtworkWhenMissing = domainEntity.ShouldAggregateArtworkWhenMissing, ShouldRenderPdfAsImages = domainEntity.ShouldRenderPdfAsImages, - ShouldPreserveBookStyles = domainEntity.ShouldPreserveBookStyles + ShouldPreserveBookStyles = domainEntity.ShouldPreserveBookStyles, + ShouldKeepDownloadingWhilePaused = domainEntity.ShouldKeepDownloadingWhilePaused, + ShouldAutoplay = domainEntity.ShouldAutoplay, + IsGaplessPlaybackEnabled = domainEntity.IsGaplessPlaybackEnabled, + ReplayGainMode = domainEntity.ReplayGainMode, + StreamingQuality = domainEntity.StreamingQuality, + Volume = domainEntity.Volume, + IsMuted = domainEntity.IsMuted }; } @@ -49,7 +56,12 @@ public static class UserSettingsMapping domainEntity.ShouldAggregateMetadataWhenMissing, domainEntity.ShouldAggregateArtworkWhenMissing, domainEntity.ShouldRenderPdfAsImages, - domainEntity.ShouldPreserveBookStyles + domainEntity.ShouldPreserveBookStyles, + domainEntity.ShouldKeepDownloadingWhilePaused, + domainEntity.ShouldAutoplay, + domainEntity.IsGaplessPlaybackEnabled, + domainEntity.ReplayGainMode, + domainEntity.StreamingQuality ); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommand.cs new file mode 100644 index 00000000..285eb67b --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommand.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; + +/// +/// Command for updating the playback state the player reports for the current user automatically. These values are not part of the settings the user edits. +/// +/// The last volume the player reported, as a value between 0 and 1. +/// The last mute state the player reported. +public record UpdatePlaybackStateCommand( + double? Volume, + bool? IsMuted +) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandler.cs new file mode 100644 index 00000000..d9b429bd --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandler.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; + +/// +/// Handler for the command to update the playback state the player reports for the current user automatically. +/// +public class UpdatePlaybackStateCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public UpdatePlaybackStateCommandHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the command to update the playback state the player reports for the current user automatically. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful update, or an error message. + /// + public async Task> HandleAsync(UpdatePlaybackStateCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return Errors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Get the existing settings of the current user, if any. + Result getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getSettingsResult.IsFailure) + return getSettingsResult.Errors; + + if (getSettingsResult.Value is null) + { + // Create the settings of the current user, since they are not stored yet, keeping the settings the user edits by hand at their default. + Result createSettingsResult = UserSettings.Create(UserId.Create(userId)); + if (createSettingsResult.IsFailure) + return createSettingsResult.Errors; + + Result applyResult = createSettingsResult.Value.UpdatePlaybackState(command.Volume!.Value, command.IsMuted!.Value); + if (applyResult.IsFailure) + return applyResult.Errors; + + Result insertResult = await _unitOfWork.UserSettingsRepository.InsertAsync(createSettingsResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + return insertResult.Errors; + } + else + { + // Update the stored settings of the current user. + Result toDomainEntityResult = getSettingsResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + + Result applyResult = toDomainEntityResult.Value.UpdatePlaybackState(command.Volume!.Value, command.IsMuted!.Value); + if (applyResult.IsFailure) + return applyResult.Errors; + + Result updateResult = await _unitOfWork.UserSettingsRepository.UpdateAsync(toDomainEntityResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + } + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Updated; + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidator.cs new file mode 100644 index 00000000..43edb206 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidator.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; + +/// +/// Validates the needed validation rules for . +/// +public class UpdatePlaybackStateCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaybackStateCommandValidator() + { + RuleFor(command => command.Volume) + .NotNull() + .WithError(Errors.UserSettings.VolumeCannotBeNull); + + RuleFor(command => command.Volume) + .Must(volume => volume is null || (volume.Value >= 0.0 && volume.Value <= 1.0)) + .WithError(Errors.UserSettings.VolumeMustBeBetweenZeroAndOne); + + RuleFor(command => command.IsMuted) + .NotNull() + .WithError(Errors.UserSettings.IsMutedCannotBeNull); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs index 7dbaa12e..8fccc1a4 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; #endregion namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; @@ -15,6 +16,11 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. +/// Whether the player keeps downloading a track while playback is paused, or not. +/// Whether the player continues playback at the end of an album or artist, or not. +/// Whether the player transitions between consecutive tracks without a gap, or not. +/// The way ReplayGain normalization is applied to the tracks the user plays. +/// The quality cap applied to the audio the server normalizes for the user. public record UpdateUserSettingsCommand( bool IsPaginationEnabled, int ItemsPerPage, @@ -23,5 +29,10 @@ public record UpdateUserSettingsCommand( bool ShouldAggregateMetadataWhenMissing, bool ShouldAggregateArtworkWhenMissing, bool ShouldRenderPdfAsImages, - bool ShouldPreserveBookStyles + bool ShouldPreserveBookStyles, + bool? ShouldKeepDownloadingWhilePaused, + bool? ShouldAutoplay, + bool? IsGaplessPlaybackEnabled, + ReplayGainMode? ReplayGainMode, + PlaybackStreamingQuality? StreamingQuality ) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs index 73317f73..9298f87a 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -66,20 +66,16 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler createSettingsResult = UserSettings.Create( - UserId.Create(userId), - command.IsPaginationEnabled, - command.ItemsPerPage, - command.ShouldIgnoreThePrefixForAlphaPicker, - command.IsThemeCachingEnabled, - command.ShouldAggregateMetadataWhenMissing, - command.ShouldAggregateArtworkWhenMissing, - command.ShouldRenderPdfAsImages, - command.ShouldPreserveBookStyles); + // Create the settings of the current user, since they are not stored yet. The playback state the player reports automatically is left + // at its default, because this command only carries the settings the user edits by hand. + Result createSettingsResult = UserSettings.Create(UserId.Create(userId)); if (createSettingsResult.IsFailure) return createSettingsResult.Errors; + Result applySettingsResult = ApplySettings(createSettingsResult.Value, command); + if (applySettingsResult.IsFailure) + return applySettingsResult.Errors; + Result insertResult = await _unitOfWork.UserSettingsRepository.InsertAsync(createSettingsResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (insertResult.IsFailure) return insertResult.Errors; @@ -91,15 +87,7 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler updateSettingsResult = toDomainEntityResult.Value.UpdateSettings( - command.IsPaginationEnabled, - command.ItemsPerPage, - command.ShouldIgnoreThePrefixForAlphaPicker, - command.IsThemeCachingEnabled, - command.ShouldAggregateMetadataWhenMissing, - command.ShouldAggregateArtworkWhenMissing, - command.ShouldRenderPdfAsImages, - command.ShouldPreserveBookStyles); + Result updateSettingsResult = ApplySettings(toDomainEntityResult.Value, command); if (updateSettingsResult.IsFailure) return updateSettingsResult.Errors; @@ -114,4 +102,28 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler + /// Applies the values carried by to the settings of the current user. + /// + /// The settings of the current user to update. + /// The command carrying the new values of the settings. + /// An representing either a successful update, or an error. + private static Result ApplySettings(UserSettings settings, UpdateUserSettingsCommand command) + { + return settings.UpdateSettings( + command.IsPaginationEnabled, + command.ItemsPerPage, + command.ShouldIgnoreThePrefixForAlphaPicker, + command.IsThemeCachingEnabled, + command.ShouldAggregateMetadataWhenMissing, + command.ShouldAggregateArtworkWhenMissing, + command.ShouldRenderPdfAsImages, + command.ShouldPreserveBookStyles, + command.ShouldKeepDownloadingWhilePaused!.Value, + command.ShouldAutoplay!.Value, + command.IsGaplessPlaybackEnabled!.Value, + command.ReplayGainMode!.Value, + command.StreamingQuality!.Value); + } } diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs index ba8ff630..86608f8b 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs @@ -19,5 +19,35 @@ public class UpdateUserSettingsCommandValidator : AbstractValidator command.ItemsPerPage) .GreaterThan(0) .WithError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero); + + RuleFor(command => command.ShouldKeepDownloadingWhilePaused) + .NotNull() + .WithError(Errors.UserSettings.ShouldKeepDownloadingWhilePausedCannotBeNull); + + RuleFor(command => command.ShouldAutoplay) + .NotNull() + .WithError(Errors.UserSettings.ShouldAutoplayCannotBeNull); + + RuleFor(command => command.IsGaplessPlaybackEnabled) + .NotNull() + .WithError(Errors.UserSettings.IsGaplessPlaybackEnabledCannotBeNull); + + RuleFor(command => command.ReplayGainMode) + .NotNull() + .WithError(Errors.UserSettings.ReplayGainModeCannotBeNull); + + RuleFor(command => command.ReplayGainMode) + .IsInEnum() + .WithError(Errors.UserSettings.InvalidReplayGainMode) + .When(command => command.ReplayGainMode is not null); + + RuleFor(command => command.StreamingQuality) + .NotNull() + .WithError(Errors.UserSettings.StreamingQualityCannotBeNull); + + RuleFor(command => command.StreamingQuality) + .IsInEnum() + .WithError(Errors.UserSettings.InvalidStreamingQuality) + .When(command => command.StreamingQuality is not null); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQuery.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQuery.cs new file mode 100644 index 00000000..d18d4f83 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQuery.cs @@ -0,0 +1,10 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState; + +/// +/// Query for getting the playback state the player reported for the current user automatically. These values are not part of the settings the user edits. +/// +public record GetPlaybackStateQuery : IQuery; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandler.cs new file mode 100644 index 00000000..2039eb5b --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandler.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState; + +/// +/// Handler for the query to get the playback state the player reported for the current user automatically. +/// +public class GetPlaybackStateQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetPlaybackStateQueryHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get the playback state the player reported for the current user automatically. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully retrieved , or an error message. + /// + public async Task> HandleAsync(GetPlaybackStateQuery query, CancellationToken cancellationToken) + { + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return Errors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Get the settings of the current user from the repository. + Result getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getSettingsResult.IsFailure) + return getSettingsResult.Errors; + + // When no settings are stored for the current user yet, return the default playback state. + if (getSettingsResult.Value is null) + { + Result defaultSettingsResult = UserSettings.Create(); + if (defaultSettingsResult.IsFailure) + return defaultSettingsResult.Errors; + return new PlaybackStateResponse(defaultSettingsResult.Value.Volume, defaultSettingsResult.Value.IsMuted); + } + + return new PlaybackStateResponse(getSettingsResult.Value.Volume, getSettingsResult.Value.IsMuted); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs index 0d40b9df..94b1d97c 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs @@ -46,18 +46,18 @@ public class GetUserSettingsQueryHandler : IQueryHandler public async Task> HandleAsync(GetUserSettingsQuery query, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the settings of the current user from the repository + // Get the settings of the current user from the repository. Result getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getSettingsResult.IsFailure) return getSettingsResult.Errors; - // when no settings are stored for the current user yet, return the default settings + // When no settings are stored for the current user yet, return the default settings. if (getSettingsResult.Value is null) { Result defaultSettingsResult = UserSettings.Create(); diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdatePlaybackStateRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdatePlaybackStateRequest.cs new file mode 100644 index 00000000..bfd0de94 --- /dev/null +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdatePlaybackStateRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.UsersManagement.Settings; + +/// +/// Represents a request to report the playback state of the current user. The player sends this automatically, and these values are not part of the settings the user edits. +/// +/// The last volume the player reported, as a value between 0 and 1. Required. +/// The last mute state the player reported. Required. +[DebuggerDisplay("Volume: {Volume}; IsMuted: {IsMuted}")] +public sealed record UpdatePlaybackStateRequest( + double? Volume, + bool? IsMuted +); diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs index f42474fa..53c5ec79 100644 --- a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Diagnostics; #endregion @@ -15,6 +16,11 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings; /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. Required. /// Whether PDF books are rendered as page images for the user, or not. Required. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. Required. +/// Whether the player keeps downloading a track while playback is paused, or not. Required. +/// Whether the player continues playback at the end of an album or artist, or not. Required. +/// Whether the player transitions between consecutive tracks without a gap, or not. Required. +/// The way ReplayGain normalization is applied to the tracks the user plays. Required. +/// The quality cap applied to the audio the server normalizes for the user. Required. [DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")] public sealed record UpdateUserSettingsRequest( bool IsPaginationEnabled, @@ -24,5 +30,10 @@ public sealed record UpdateUserSettingsRequest( bool ShouldAggregateMetadataWhenMissing, bool ShouldAggregateArtworkWhenMissing, bool ShouldRenderPdfAsImages, - bool ShouldPreserveBookStyles + bool ShouldPreserveBookStyles, + bool? ShouldKeepDownloadingWhilePaused, + bool? ShouldAutoplay, + bool? IsGaplessPlaybackEnabled, + ReplayGainMode? ReplayGainMode, + PlaybackStreamingQuality? StreamingQuality ); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/PlaybackStateResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/PlaybackStateResponse.cs new file mode 100644 index 00000000..2884c7a7 --- /dev/null +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/PlaybackStateResponse.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.UsersManagement.Settings; + +/// +/// Represents the playback state of a user, as last reported by the player. The player writes these values automatically, and they are not part of the settings the user edits. +/// +/// The last volume the player reported, as a value between 0 and 1. +/// The last mute state the player reported. +[DebuggerDisplay("Volume: {Volume}; IsMuted: {IsMuted}")] +public sealed record PlaybackStateResponse( + double Volume, + bool IsMuted +); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs index 11bdbf60..c4ea9fad 100644 --- a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Diagnostics; #endregion @@ -17,6 +18,11 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings; /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. +/// Whether the player keeps downloading a track while playback is paused, or not. +/// Whether the player continues playback at the end of an album or artist, or not. +/// Whether the player transitions between consecutive tracks without a gap, or not. +/// The way ReplayGain normalization is applied to the tracks the user plays. +/// The quality cap applied to the audio the server normalizes for the user. [DebuggerDisplay("UserId: {UserId}")] public sealed record UserSettingsResponse( Guid UserId, @@ -27,5 +33,10 @@ public sealed record UserSettingsResponse( bool ShouldAggregateMetadataWhenMissing, bool ShouldAggregateArtworkWhenMissing, bool ShouldRenderPdfAsImages, - bool ShouldPreserveBookStyles + bool ShouldPreserveBookStyles, + bool ShouldKeepDownloadingWhilePaused, + bool ShouldAutoplay, + bool IsGaplessPlaybackEnabled, + ReplayGainMode ReplayGainMode, + PlaybackStreamingQuality StreamingQuality ); diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs index d6713dc8..c60b07e8 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs @@ -66,6 +66,34 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration settings.ShouldKeepDownloadingWhilePaused) + .IsRequired() + .HasColumnOrder(14); + + builder.Property(settings => settings.ShouldAutoplay) + .IsRequired() + .HasColumnOrder(15); + + builder.Property(settings => settings.IsGaplessPlaybackEnabled) + .IsRequired() + .HasColumnOrder(16); + + builder.Property(settings => settings.ReplayGainMode) + .IsRequired() + .HasColumnOrder(17); + + builder.Property(settings => settings.StreamingQuality) + .IsRequired() + .HasColumnOrder(18); + + builder.Property(settings => settings.Volume) + .IsRequired() + .HasColumnOrder(19); + + builder.Property(settings => settings.IsMuted) + .IsRequired() + .HasColumnOrder(20); + // audit builder.Property(settings => settings.CreatedOnUtc) .IsRequired() diff --git a/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.Designer.cs new file mode 100644 index 00000000..3188be44 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.Designer.cs @@ -0,0 +1,3463 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261015160422_AddsPlaybackPreferencesAndStateToUserSettings")] + partial class AddsPlaybackPreferencesAndStateToUserSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(19); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.cs b/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.cs new file mode 100644 index 00000000..9b74da5d --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.cs @@ -0,0 +1,102 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsPlaybackPreferencesAndStateToUserSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsGaplessPlaybackEnabled", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: true) + .Annotation("Relational:ColumnOrder", 16); + + migrationBuilder.AddColumn( + name: "IsMuted", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 20); + + migrationBuilder.AddColumn( + name: "ReplayGainMode", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: 0) + .Annotation("Relational:ColumnOrder", 17); + + migrationBuilder.AddColumn( + name: "ShouldAutoplay", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: true) + .Annotation("Relational:ColumnOrder", 15); + + migrationBuilder.AddColumn( + name: "ShouldKeepDownloadingWhilePaused", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: true) + .Annotation("Relational:ColumnOrder", 14); + + migrationBuilder.AddColumn( + name: "StreamingQuality", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: 0) + .Annotation("Relational:ColumnOrder", 18); + + migrationBuilder.AddColumn( + name: "Volume", + table: "UserSettings", + type: "REAL", + nullable: false, + defaultValue: 1.0) + .Annotation("Relational:ColumnOrder", 19); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsGaplessPlaybackEnabled", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "IsMuted", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "ReplayGainMode", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "ShouldAutoplay", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "ShouldKeepDownloadingWhilePaused", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "StreamingQuality", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "Volume", + table: "UserSettings"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index ad7bbe21..9d12074b 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -2359,6 +2359,14 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(5); + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + b.Property("IsPaginationEnabled") .HasColumnType("INTEGER") .HasColumnOrder(2); @@ -2371,6 +2379,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(3); + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + b.Property("ShouldAggregateArtworkWhenMissing") .HasColumnType("INTEGER") .HasColumnOrder(13); @@ -2379,10 +2391,18 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(10); + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + b.Property("ShouldIgnoreThePrefixForAlphaPicker") .HasColumnType("INTEGER") .HasColumnOrder(4); + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + b.Property("ShouldPreserveBookStyles") .HasColumnType("INTEGER") .HasColumnOrder(12); @@ -2391,6 +2411,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(11); + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + b.Property("UpdatedBy") .HasColumnType("TEXT") .HasColumnOrder(8); @@ -2403,6 +2427,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(1); + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(19); + b.HasKey("Id"); b.HasIndex("UserId") diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs new file mode 100644 index 00000000..6350f42b --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs @@ -0,0 +1,30 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Enumeration for the quality cap applied to the audio the server normalizes (remuxes or transcodes) for a user. +/// +/// +/// The caps apply only to audio the server has to change; a track that is played directly is always delivered as it was stored. +/// +public enum PlaybackStreamingQuality +{ + /// + /// The server chooses the quality, with no explicit cap. + /// + Auto, + + /// + /// Normalized audio is capped at 96 kbps. + /// + Low, + + /// + /// Normalized audio is capped at 160 kbps. + /// + Medium, + + /// + /// Normalized audio is capped at 320 kbps. + /// + High, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/ReplayGainMode.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/ReplayGainMode.cs new file mode 100644 index 00000000..fea96752 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/ReplayGainMode.cs @@ -0,0 +1,23 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Enumeration for the ways ReplayGain normalization is applied to the tracks a user plays. +/// +public enum ReplayGainMode +{ + /// + /// ReplayGain is not applied. Tracks play at the loudness at which they were stored. + /// + Off, + + /// + /// Each track is normalized using its own ReplayGain track gain, so tracks from different albums play at a similar loudness. + /// + Track, + + /// + /// Each track is normalized using the ReplayGain album gain of the album it belongs to, so an album keeps its relative loudness + /// while albums play at a similar loudness to each other. + /// + Album, +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs b/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs index 4778b3f2..06219906 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs @@ -14,5 +14,15 @@ public static partial class Errors public static Error UserSettingsAlreadyExists => Error.Conflict(description: nameof(UserSettingsAlreadyExists)); public static Error UserSettingsNotFound => Error.NotFound(description: nameof(UserSettingsNotFound)); public static Error ItemsPerPageMustBeGreaterThanZero => Error.Validation(description: nameof(ItemsPerPageMustBeGreaterThanZero)); + public static Error VolumeCannotBeNull => Error.Validation(description: nameof(VolumeCannotBeNull)); + public static Error VolumeMustBeBetweenZeroAndOne => Error.Validation(description: nameof(VolumeMustBeBetweenZeroAndOne)); + public static Error IsMutedCannotBeNull => Error.Validation(description: nameof(IsMutedCannotBeNull)); + public static Error ShouldKeepDownloadingWhilePausedCannotBeNull => Error.Validation(description: nameof(ShouldKeepDownloadingWhilePausedCannotBeNull)); + public static Error ShouldAutoplayCannotBeNull => Error.Validation(description: nameof(ShouldAutoplayCannotBeNull)); + public static Error IsGaplessPlaybackEnabledCannotBeNull => Error.Validation(description: nameof(IsGaplessPlaybackEnabledCannotBeNull)); + public static Error ReplayGainModeCannotBeNull => Error.Validation(description: nameof(ReplayGainModeCannotBeNull)); + public static Error StreamingQualityCannotBeNull => Error.Validation(description: nameof(StreamingQualityCannotBeNull)); + public static Error InvalidReplayGainMode => Error.Validation(description: nameof(InvalidReplayGainMode)); + public static Error InvalidStreamingQuality => Error.Validation(description: nameof(InvalidStreamingQuality)); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs index 59f22083..5f151cf3 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Diagnostics; #endregion @@ -23,6 +23,13 @@ public class UserSettings : AggregateRoot private const bool DEFAULT_AGGREGATE_ARTWORK_WHEN_MISSING = false; private const bool DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES = false; private const bool DEFAULT_SHOULD_PRESERVE_BOOK_STYLES = true; + private const bool DEFAULT_SHOULD_KEEP_DOWNLOADING_WHILE_PAUSED = true; + private const bool DEFAULT_SHOULD_AUTOPLAY = true; + private const bool DEFAULT_IS_GAPLESS_PLAYBACK_ENABLED = true; + private const ReplayGainMode DEFAULT_REPLAY_GAIN_MODE = ReplayGainMode.Off; + private const PlaybackStreamingQuality DEFAULT_STREAMING_QUALITY = PlaybackStreamingQuality.Auto; + private const double DEFAULT_VOLUME = 1.0; + private const bool DEFAULT_IS_MUTED = false; /// /// Gets the object representing the unique identifier of the user that owns these settings. @@ -72,6 +79,41 @@ public class UserSettings : AggregateRoot /// public bool ShouldPreserveBookStyles { get; private set; } + /// + /// Gets whether the player keeps downloading a track while playback is paused, or not, up to the entire file. + /// + public bool ShouldKeepDownloadingWhilePaused { get; private set; } + + /// + /// Gets whether the player continues playback at the end of an album or artist, or not. + /// + public bool ShouldAutoplay { get; private set; } + + /// + /// Gets whether the player transitions between consecutive tracks without a gap, or not. + /// + public bool IsGaplessPlaybackEnabled { get; private set; } + + /// + /// Gets the way ReplayGain normalization is applied to the tracks the user plays. + /// + public ReplayGainMode ReplayGainMode { get; private set; } + + /// + /// Gets the quality cap applied to the audio the server normalizes for the user. + /// + public PlaybackStreamingQuality StreamingQuality { get; private set; } + + /// + /// Gets the last volume the player reported for the user. It is written automatically by the player, and is not part of the settings the user edits. + /// + public double Volume { get; private set; } + + /// + /// Gets the last mute state the player reported for the user. It is written automatically by the player, and is not part of the settings the user edits. + /// + public bool IsMuted { get; private set; } + /// /// Initializes a new instance of the class. /// @@ -85,6 +127,13 @@ public class UserSettings : AggregateRoot /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. + /// Whether the player keeps downloading a track while playback is paused, or not. + /// Whether the player continues playback at the end of an album or artist, or not. + /// Whether the player transitions between consecutive tracks without a gap, or not. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. + /// The last volume the player reported for the user. + /// The last mute state the player reported for the user. private UserSettings( UserSettingsId id, UserId userId, @@ -95,7 +144,14 @@ public class UserSettings : AggregateRoot bool shouldAggregateMetadataWhenMissing, bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, - bool shouldPreserveBookStyles) : base(id) + bool shouldPreserveBookStyles, + bool shouldKeepDownloadingWhilePaused, + bool shouldAutoplay, + bool isGaplessPlaybackEnabled, + ReplayGainMode replayGainMode, + PlaybackStreamingQuality streamingQuality, + double volume, + bool isMuted) : base(id) { UserId = userId; IsPaginationEnabled = isPaginationEnabled; @@ -106,6 +162,13 @@ public class UserSettings : AggregateRoot ShouldAggregateArtworkWhenMissing = shouldAggregateArtworkWhenMissing; ShouldRenderPdfAsImages = shouldRenderPdfAsImages; ShouldPreserveBookStyles = shouldPreserveBookStyles; + ShouldKeepDownloadingWhilePaused = shouldKeepDownloadingWhilePaused; + ShouldAutoplay = shouldAutoplay; + IsGaplessPlaybackEnabled = isGaplessPlaybackEnabled; + ReplayGainMode = replayGainMode; + StreamingQuality = streamingQuality; + Volume = volume; + IsMuted = isMuted; } /// @@ -117,15 +180,22 @@ public class UserSettings : AggregateRoot public static Result Create() { return Create( - UserId.CreateUnique(), - DEFAULT_IS_PAGINATION_ENABLED, - DEFAULT_ITEMS_PER_PAGE, - DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, - DEFAULT_IS_THEME_CACHING_ENABLED, - DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, + UserId.CreateUnique(), + DEFAULT_IS_PAGINATION_ENABLED, + DEFAULT_ITEMS_PER_PAGE, + DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, + DEFAULT_IS_THEME_CACHING_ENABLED, + DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, DEFAULT_AGGREGATE_ARTWORK_WHEN_MISSING, DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES, - DEFAULT_SHOULD_PRESERVE_BOOK_STYLES + DEFAULT_SHOULD_PRESERVE_BOOK_STYLES, + DEFAULT_SHOULD_KEEP_DOWNLOADING_WHILE_PAUSED, + DEFAULT_SHOULD_AUTOPLAY, + DEFAULT_IS_GAPLESS_PLAYBACK_ENABLED, + DEFAULT_REPLAY_GAIN_MODE, + DEFAULT_STREAMING_QUALITY, + DEFAULT_VOLUME, + DEFAULT_IS_MUTED ); } @@ -139,15 +209,22 @@ public class UserSettings : AggregateRoot public static Result Create(UserId userId) { return Create( - userId, - DEFAULT_IS_PAGINATION_ENABLED, - DEFAULT_ITEMS_PER_PAGE, - DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, - DEFAULT_IS_THEME_CACHING_ENABLED, - DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, + userId, + DEFAULT_IS_PAGINATION_ENABLED, + DEFAULT_ITEMS_PER_PAGE, + DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, + DEFAULT_IS_THEME_CACHING_ENABLED, + DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, DEFAULT_AGGREGATE_ARTWORK_WHEN_MISSING, DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES, - DEFAULT_SHOULD_PRESERVE_BOOK_STYLES + DEFAULT_SHOULD_PRESERVE_BOOK_STYLES, + DEFAULT_SHOULD_KEEP_DOWNLOADING_WHILE_PAUSED, + DEFAULT_SHOULD_AUTOPLAY, + DEFAULT_IS_GAPLESS_PLAYBACK_ENABLED, + DEFAULT_REPLAY_GAIN_MODE, + DEFAULT_STREAMING_QUALITY, + DEFAULT_VOLUME, + DEFAULT_IS_MUTED ); } @@ -163,6 +240,13 @@ public class UserSettings : AggregateRoot /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. + /// Whether the player keeps downloading a track while playback is paused, or not. + /// Whether the player continues playback at the end of an album or artist, or not. + /// Whether the player transitions between consecutive tracks without a gap, or not. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. + /// The last volume the player reported for the user. + /// The last mute state the player reported for the user. /// /// An containing either a successfully created , or an error message. /// @@ -175,11 +259,15 @@ public class UserSettings : AggregateRoot bool shouldAggregateMetadataWhenMissing, bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, - bool shouldPreserveBookStyles) + bool shouldPreserveBookStyles, + bool shouldKeepDownloadingWhilePaused, + bool shouldAutoplay, + bool isGaplessPlaybackEnabled, + ReplayGainMode replayGainMode, + PlaybackStreamingQuality streamingQuality, + double volume, + bool isMuted) { - if (itemsPerPage <= 0) - return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - return new UserSettings( UserSettingsId.CreateUnique(), userId, @@ -190,7 +278,14 @@ public class UserSettings : AggregateRoot shouldAggregateMetadataWhenMissing, shouldAggregateArtworkWhenMissing, shouldRenderPdfAsImages, - shouldPreserveBookStyles); + shouldPreserveBookStyles, + shouldKeepDownloadingWhilePaused, + shouldAutoplay, + isGaplessPlaybackEnabled, + replayGainMode, + streamingQuality, + volume, + isMuted); } /// @@ -206,6 +301,13 @@ public class UserSettings : AggregateRoot /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. + /// Whether the player keeps downloading a track while playback is paused, or not. + /// Whether the player continues playback at the end of an album or artist, or not. + /// Whether the player transitions between consecutive tracks without a gap, or not. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. + /// The last volume the player reported for the user. + /// The last mute state the player reported for the user. /// /// An containing either a successfully created , or an error message. /// @@ -219,17 +321,25 @@ public class UserSettings : AggregateRoot bool shouldAggregateMetadataWhenMissing, bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, - bool shouldPreserveBookStyles) + bool shouldPreserveBookStyles, + bool shouldKeepDownloadingWhilePaused, + bool shouldAutoplay, + bool isGaplessPlaybackEnabled, + ReplayGainMode replayGainMode, + PlaybackStreamingQuality streamingQuality, + double volume, + bool isMuted) { - if (itemsPerPage <= 0) - return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - - return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing, shouldAggregateArtworkWhenMissing, shouldRenderPdfAsImages, shouldPreserveBookStyles); + return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing, shouldAggregateArtworkWhenMissing, shouldRenderPdfAsImages, shouldPreserveBookStyles, shouldKeepDownloadingWhilePaused, shouldAutoplay, isGaplessPlaybackEnabled, replayGainMode, streamingQuality, volume, isMuted); } /// /// Updates the settings of the user. /// + /// + /// The playback state the player reports automatically (the volume and the mute state) is not part of the settings the user edits, so + /// this method neither accepts nor changes it. + /// /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. @@ -238,6 +348,11 @@ public class UserSettings : AggregateRoot /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. + /// Whether the player keeps downloading a track while playback is paused, or not. + /// Whether the player continues playback at the end of an album or artist, or not. + /// Whether the player transitions between consecutive tracks without a gap, or not. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. /// An representing either a successful update, or an error. public Result UpdateSettings( bool isPaginationEnabled, @@ -247,11 +362,13 @@ public class UserSettings : AggregateRoot bool shouldAggregateMetadataWhenMissing, bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, - bool shouldPreserveBookStyles) + bool shouldPreserveBookStyles, + bool shouldKeepDownloadingWhilePaused, + bool shouldAutoplay, + bool isGaplessPlaybackEnabled, + ReplayGainMode replayGainMode, + PlaybackStreamingQuality streamingQuality) { - if (itemsPerPage <= 0) - return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - IsPaginationEnabled = isPaginationEnabled; ItemsPerPage = itemsPerPage; ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; @@ -260,6 +377,24 @@ public class UserSettings : AggregateRoot ShouldAggregateArtworkWhenMissing = shouldAggregateArtworkWhenMissing; ShouldRenderPdfAsImages = shouldRenderPdfAsImages; ShouldPreserveBookStyles = shouldPreserveBookStyles; + ShouldKeepDownloadingWhilePaused = shouldKeepDownloadingWhilePaused; + ShouldAutoplay = shouldAutoplay; + IsGaplessPlaybackEnabled = isGaplessPlaybackEnabled; + ReplayGainMode = replayGainMode; + StreamingQuality = streamingQuality; + return Result.Updated; + } + + /// + /// Updates the playback state the player reports automatically. + /// + /// The last volume the player reported for the user. + /// The last mute state the player reported for the user. + /// An representing either a successful update, or an error. + public Result UpdatePlaybackState(double volume, bool isMuted) + { + Volume = volume; + IsMuted = isMuted; return Result.Updated; } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs index 1be6e11b..3a24a202 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs @@ -13,5 +13,7 @@ public static partial class ApiRoutes public const string GET_USER_BY_ID = "/users/{id}"; public const string GET_USER_SETTINGS = "/users/me/settings"; // uses "me" because it is always for the currently authenticated user public const string UPDATE_USER_SETTINGS = "/users/me/settings"; + public const string GET_PLAYBACK_STATE = "/users/me/settings/playback-state"; + public const string UPDATE_PLAYBACK_STATE = "/users/me/settings/playback-state"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs new file mode 100644 index 00000000..aebd1029 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetPlaybackState; + +/// +/// API endpoint for the /users/me/settings/playback-state route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetPlaybackStateEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getPlaybackStateQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get playback state queries. + public GetPlaybackStateEndpoint(IQueryHandler> getPlaybackStateQueryHandler) + { + _getPlaybackStateQueryHandler = getPlaybackStateQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Users.GET_PLAYBACK_STATE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the playback state the player reported for the current user automatically. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + Result result = await _getPlaybackStateQueryHandler.HandleAsync(new GetPlaybackStateQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs new file mode 100644 index 00000000..1ee71e41 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetPlaybackState; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackStateEndpointSummary() + { + Summary = "Retrieves the playback state the player reported for the current user."; + Description = "Retrieves the last volume and mute state the player reported for the current user. When no settings are stored for the user yet, the default values are returned."; + + Response(200, "The playback state of the current user is returned.", + example: new PlaybackStateResponse( + Volume: 1.0, + IsMuted: false + )); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/settings/playback-state" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/settings/playback-state" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/settings/playback-state" + } + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs index 708a3959..5be9415c 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -31,7 +32,12 @@ public class GetUserSettingsEndpointSummary : Summary +/// API endpoint for the /users/me/settings/playback-state route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class UpdatePlaybackStateEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updatePlaybackStateCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update playback state commands. + public UpdatePlaybackStateEndpoint(ICommandHandler> updatePlaybackStateCommandHandler) + { + _updatePlaybackStateCommandHandler = updatePlaybackStateCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Users.UPDATE_PLAYBACK_STATE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the playback state the player reported for the current user automatically. + /// + /// The request containing the latest playback state of the current user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdatePlaybackStateRequest request, CancellationToken cancellationToken) + { + Result result = await _updatePlaybackStateCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs new file mode 100644 index 00000000..03a9c9fa --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaybackStateEndpointSummary() + { + Summary = "Updates the playback state the player reported for the current user."; + Description = "Updates the last volume and mute state the player reported for the current user. This is written automatically by the player and is not part of the settings the user edits. When no settings are stored for the user yet, they are created with the provided playback state."; + + ExampleRequest = new UpdatePlaybackStateRequest( + Volume: 0.75, + IsMuted: false + ); + + RequestParam(r => r.Volume, "The last volume the player reported, as a value between 0 and 1. Required."); + RequestParam(r => r.IsMuted, "The last mute state the player reported. Required."); + + Response(200, "The playback state of the current user was successfully updated."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/settings/playback-state" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/settings/playback-state" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/settings/playback-state" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/settings/playback-state", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "VolumeCannotBeNull", + "VolumeMustBeBetweenZeroAndOne", + "IsMutedCannotBeNull" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs index 7e78c199..0b96e4ad 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -29,7 +30,12 @@ public class UpdateUserSettingsEndpointSummary : Summary r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Required."); @@ -40,6 +46,11 @@ public class UpdateUserSettingsEndpointSummary : Summary r.ShouldAggregateArtworkWhenMissing, "Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. Required."); RequestParam(r => r.ShouldRenderPdfAsImages, "Whether PDF books are rendered as page images for the user, or not. Required."); RequestParam(r => r.ShouldPreserveBookStyles, "Whether the styles of the book content are preserved when it is rendered for the user, or not. Required."); + RequestParam(r => r.ShouldKeepDownloadingWhilePaused, "Whether the player keeps downloading a track while playback is paused, or not. Required."); + RequestParam(r => r.ShouldAutoplay, "Whether the player continues playback at the end of an album or artist, or not. Required."); + RequestParam(r => r.IsGaplessPlaybackEnabled, "Whether the player transitions between consecutive tracks without a gap, or not. Required."); + RequestParam(r => r.ReplayGainMode, "The way ReplayGain normalization is applied to the tracks the user plays. Required."); + RequestParam(r => r.StreamingQuality, "The quality cap applied to the audio the server normalizes for the user. Required."); Response(200, "The settings of the current user were successfully updated."); @@ -86,7 +97,14 @@ public class UpdateUserSettingsEndpointSummary : Summary +/// Data transfer object for the playback state a user last reported to the player. The player writes these values automatically, and they are not part of the settings the user edits. +/// +[DebuggerDisplay("Volume: {Volume}; IsMuted: {IsMuted}")] +public class PlaybackStateDto +{ + /// + /// Gets or sets the last volume the player reported, as a value between 0 and 1. + /// + public double? Volume { get; set; } + + /// + /// Gets or sets the last mute state the player reported. + /// + public bool? IsMuted { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs index 4290cf87..c27e04d9 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.AudioLibrary; using System; using System.Diagnostics; #endregion @@ -58,4 +59,29 @@ public class UserSettingsDto /// external servers, which those servers could observe; stripping them removes that possibility, at the cost of the look of the book. /// public bool ShouldPreserveBookStyles { get; set; } + + /// + /// Gets or sets whether the player keeps downloading a track while playback is paused, or not, up to the entire file. + /// + public bool? ShouldKeepDownloadingWhilePaused { get; set; } + + /// + /// Gets or sets whether the player continues playback at the end of an album or artist, or not. + /// + public bool? ShouldAutoplay { get; set; } + + /// + /// Gets or sets whether the player transitions between consecutive tracks without a gap, or not. + /// + public bool? IsGaplessPlaybackEnabled { get; set; } + + /// + /// Gets or sets the way ReplayGain normalization is applied to the tracks the user plays. + /// + public ReplayGainMode? ReplayGainMode { get; set; } + + /// + /// Gets or sets the quality cap applied to the audio the server normalizes for the user. + /// + public PlaybackStreamingQuality? StreamingQuality { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs new file mode 100644 index 00000000..283aabfe --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the quality cap applied to the audio the server normalizes (remuxes or transcodes) for a user. +/// +/// +/// The caps apply only to audio the server has to change; a track that is played directly is always delivered as it was stored. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaybackStreamingQuality +{ + /// + /// The server chooses the quality, with no explicit cap. + /// + Auto, + + /// + /// Normalized audio is capped at 96 kbps. + /// + Low, + + /// + /// Normalized audio is capped at 160 kbps. + /// + Medium, + + /// + /// Normalized audio is capped at 320 kbps. + /// + High, +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/ReplayGainMode.cs b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/ReplayGainMode.cs new file mode 100644 index 00000000..ebcd97ec --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/ReplayGainMode.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the ways ReplayGain normalization is applied to the tracks a user plays. +/// +[DebuggerDisplay("{ToString()}")] +public enum ReplayGainMode +{ + /// + /// ReplayGain is not applied. Tracks play at the loudness at which they were stored. + /// + Off, + + /// + /// Each track is normalized using its own ReplayGain track gain, so tracks from different albums play at a similar loudness. + /// + Track, + + /// + /// Each track is normalized using the ReplayGain album gain of the album it belongs to, so an album keeps its relative loudness + /// while albums play at a similar loudness to each other. + /// + Album, +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs index 7ef9fa39..dbcfecf3 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs @@ -12,5 +12,7 @@ public static partial class ApiRoutes { public const string GET_USER_SETTINGS = "users/me/settings"; public const string UPDATE_USER_SETTINGS = "users/me/settings"; + public const string GET_PLAYBACK_STATE = "users/me/settings/playback-state"; + public const string UPDATE_PLAYBACK_STATE = "users/me/settings/playback-state"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs index 267383c8..3806b805 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs @@ -13,5 +13,7 @@ public static partial class WebRoutes public const string INDEX = "{culture}/tools/settings"; public const string GET_USER_SETTINGS = "{culture}/tools/settings/api-get-user-settings"; public const string UPDATE_USER_SETTINGS = "{culture}/tools/settings/api-update-user-settings"; + public const string GET_PLAYBACK_STATE = "{culture}/tools/settings/api-get-playback-state"; + public const string UPDATE_PLAYBACK_STATE = "{culture}/tools/settings/api-update-playback-state"; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs new file mode 100644 index 00000000..ed497ad3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetPlaybackState; + +/// +/// API endpoint for the /{culture}/tools/settings/api-get-playback-state route. +/// +public class GetPlaybackStateEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPlaybackStateEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Settings.GET_PLAYBACK_STATE); + DontAutoTag(); + Options(options => options.WithTags("Settings")); + } + + /// + /// Retrieves the playback state the player reported for the current user automatically. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + PlaybackStateDto response = await _apiHttpClient.GetAsync(ApiRoutes.Users.GET_PLAYBACK_STATE, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs new file mode 100644 index 00000000..5984cb06 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetPlaybackState; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackStateEndpointSummary() + { + Summary = "Retrieves the playback state the player reported for the current user."; + Description = "Retrieves the last volume and mute state the player reported for the current user. These values are not part of the settings the user edits."; + + Response(200, "The playback state of the current user is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs new file mode 100644 index 00000000..8c0be3be --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; + +/// +/// API endpoint for the /{culture}/tools/settings/api-update-playback-state route. +/// +public class UpdatePlaybackStateEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdatePlaybackStateEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Settings.UPDATE_PLAYBACK_STATE); + DontAutoTag(); + Options(options => options.WithTags("Settings")); + EnableAntiforgery(); + } + + /// + /// Updates the playback state the player reported for the current user automatically. + /// + /// The request containing the latest playback state of the current user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(PlaybackStateDto request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { isUpdated = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs new file mode 100644 index 00000000..d68c0530 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaybackStateEndpointSummary() + { + Summary = "Updates the playback state the player reported for the current user."; + Description = "Updates the last volume and mute state the player reported for the current user. This is written automatically by the player and is not part of the settings the user edits."; + + RequestParam(r => r.Volume, "The last volume the player reported, as a value between 0 and 1. Required."); + RequestParam(r => r.IsMuted, "The last mute state the player reported. Required."); + + ExampleRequest = new PlaybackStateDto { Volume = 1.0, IsMuted = false }; + + Response(200, "The playback state of the current user is updated.", example: new { success = true, data = new { isUpdated = true } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx index ac29e5d3..d2251bd8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx @@ -813,4 +813,34 @@ نوع الجدول غير صالح! + + وضع ReplayGain غير صالح! + + + جودة البث غير صالحة! + + + لا يمكن أن تكون حالة الكتم فارغة! + + + لا يمكن أن يكون مستوى الصوت فارغًا! + + + يجب أن يكون مستوى الصوت بين 0 و 1! + + + لا يمكن أن يكون إعداد متابعة التنزيل أثناء الإيقاف المؤقت فارغًا! + + + لا يمكن أن يكون إعداد التشغيل التلقائي فارغًا! + + + لا يمكن أن يكون إعداد التشغيل دون فواصل فارغًا! + + + لا يمكن أن يكون وضع ReplayGain فارغًا! + + + لا يمكن أن تكون جودة البث فارغة! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index c8647bcc..36820a5d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -813,4 +813,34 @@ Der Zeitplantyp ist ungültig! + + Ungültiger ReplayGain-Modus! + + + Ungültige Streaming-Qualität! + + + Der Stummschaltungsstatus darf nicht null sein! + + + Die Lautstärke darf nicht null sein! + + + Die Lautstärke muss zwischen 0 und 1 liegen! + + + Die Einstellung zum Weiterherunterladen beim Pausieren darf nicht null sein! + + + Die Einstellung für die automatische Wiedergabe darf nicht null sein! + + + Die Einstellung für die lückenlose Wiedergabe darf nicht null sein! + + + Der ReplayGain-Modus darf nicht null sein! + + + Die Streaming-Qualität darf nicht null sein! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index f13e7548..93aaeaaa 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -813,4 +813,34 @@ The schedule type is invalid! + + Invalid ReplayGain mode! + + + Invalid streaming quality! + + + The mute state cannot be null! + + + The volume cannot be null! + + + The volume must be between 0 and 1! + + + The keep-downloading-while-paused preference cannot be null! + + + The autoplay preference cannot be null! + + + The gapless playback preference cannot be null! + + + The ReplayGain mode cannot be null! + + + The streaming quality cannot be null! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index faafc50f..d7c88159 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -813,4 +813,34 @@ El tipo de programación no es válido! + + ¡Modo ReplayGain no válido! + + + ¡Calidad de transmisión no válida! + + + ¡El estado de silencio no puede ser nulo! + + + ¡El volumen no puede ser nulo! + + + ¡El volumen debe estar entre 0 y 1! + + + ¡La preferencia de seguir descargando en pausa no puede ser nula! + + + ¡La preferencia de reproducción automática no puede ser nula! + + + ¡La preferencia de reproducción sin pausas no puede ser nula! + + + ¡El modo ReplayGain no puede ser nulo! + + + ¡La calidad de transmisión no puede ser nula! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index 1d433f85..4cb0b921 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -813,4 +813,34 @@ Le type de planification n'est pas valide ! + + Mode ReplayGain non valide ! + + + Qualité de diffusion non valide ! + + + L'état de sourdine ne peut pas être nul ! + + + Le volume ne peut pas être nul ! + + + Le volume doit être compris entre 0 et 1 ! + + + La préférence de téléchargement en pause ne peut pas être nulle ! + + + La préférence de lecture automatique ne peut pas être nulle ! + + + La préférence de lecture sans interruption ne peut pas être nulle ! + + + Le mode ReplayGain ne peut pas être nul ! + + + La qualité de diffusion ne peut pas être nulle ! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index e41878ca..065a0846 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -813,4 +813,34 @@ Il tipo di pianificazione non è valido! + + Modalità ReplayGain non valida! + + + Qualità dello streaming non valida! + + + Lo stato di silenziamento non può essere nullo! + + + Il volume non può essere nullo! + + + Il volume deve essere compreso tra 0 e 1! + + + La preferenza di continuare il download in pausa non può essere nulla! + + + La preferenza di riproduzione automatica non può essere nulla! + + + La preferenza di riproduzione senza interruzioni non può essere nulla! + + + La modalità ReplayGain non può essere nulla! + + + La qualità dello streaming non può essere nulla! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index 2cd57da7..44d8928f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -813,4 +813,34 @@ スケジュールタイプが無効です! + + ReplayGain モードが無効です。 + + + ストリーミング品質が無効です。 + + + ミュート状態は null にできません。 + + + 音量は null にできません。 + + + 音量は 0 から 1 の間でなければなりません。 + + + 一時停止中のダウンロード継続の設定は null にできません。 + + + 自動再生の設定は null にできません。 + + + ギャップレス再生の設定は null にできません。 + + + ReplayGain モードは null にできません。 + + + ストリーミング品質は null にできません。 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index fe193be8..922d0096 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -813,4 +813,34 @@ The schedule type is invalid! + + Invalid ReplayGain mode! + + + Invalid streaming quality! + + + The mute state cannot be null! + + + The volume cannot be null! + + + The volume must be between 0 and 1! + + + The keep-downloading-while-paused preference cannot be null! + + + The autoplay preference cannot be null! + + + The gapless playback preference cannot be null! + + + The ReplayGain mode cannot be null! + + + The streaming quality cannot be null! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index 2aa1c5dd..4eb8295a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -813,4 +813,34 @@ Tipul de programare este invalid! + + Mod ReplayGain invalid! + + + Calitate de streaming invalidă! + + + Starea de mut nu poate fi nulă! + + + Volumul nu poate fi nul! + + + Volumul trebuie să fie între 0 și 1! + + + Preferința de a continua descărcarea în pauză nu poate fi nulă! + + + Preferința de redare automată nu poate fi nulă! + + + Preferința de redare fără întreruperi nu poate fi nulă! + + + Modul ReplayGain nu poate fi nul! + + + Calitatea fluxului nu poate fi nulă! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx index ea2e4393..4743fff4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx @@ -813,4 +813,34 @@ Тип розкладу недійсний! + + Неприпустимий режим ReplayGain! + + + Неприпустима якість потокового передавання! + + + Стан без звуку не може бути порожнім! + + + Гучність не може бути порожньою! + + + Гучність має бути між 0 і 1! + + + Налаштування продовження завантаження на паузі не може бути порожнім! + + + Налаштування автовідтворення не може бути порожнім! + + + Налаштування відтворення без пауз не може бути порожнім! + + + Режим ReplayGain не може бути порожнім! + + + Якість потокового передавання не може бути порожньою! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index 0b05709e..9045e36d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -813,4 +813,34 @@ 调度类型无效! + + 无效的 ReplayGain 模式! + + + 无效的流媒体质量! + + + 静音状态不能为空! + + + 音量不能为空! + + + 音量必须介于 0 和 1 之间! + + + 暂停时继续下载的偏好设置不能为空! + + + 自动播放的偏好设置不能为空! + + + 无缝播放的偏好设置不能为空! + + + ReplayGain 模式不能为空! + + + 流媒体质量不能为空! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx index 96b79082..a506eef3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx @@ -69,4 +69,58 @@ عند التفعيل، تُستكمل الأعمال الفنية لعناصر المكتبة التي لا يوفرها مزود الأعمال الفنية الأول من المزودين التاليين. + + التشغيل + + + متابعة التنزيل أثناء الإيقاف المؤقت + + + ما إذا كان المشغل يواصل تنزيل المقطع أثناء إيقاف التشغيل مؤقتًا، حتى الملف كاملاً، بحيث لا ينتظر الاستئناف البيانات أبدًا. + + + التشغيل التلقائي + + + ما إذا كان التشغيل يستمر تلقائيًا بالمقاطع التالية عند انتهاء الألبوم أو الفنان. + + + تشغيل دون فواصل + + + ما إذا كانت المقاطع المتتالية تُشغَّل دون صمت بينها. + + + ReplayGain + + + كيفية تطبيق تسوية ReplayGain على المقاطع التي تشغّلها. + + + إيقاف + + + لكل مقطع + + + لكل ألبوم + + + جودة البث + + + حد الجودة الذي يُطبَّق عندما يضطر الخادم إلى تسوية مقطع للتشغيل. لا يتغير التشغيل المباشر أبدًا. + + + تلقائي + + + منخفضة (96 kbps) + + + متوسطة (160 kbps) + + + عالية (320 kbps) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx index e2d3bb19..e3767eb2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx @@ -69,4 +69,58 @@ Wenn aktiviert, wird das Artwork von Bibliothekselementen, das der erste Artwork-Anbieter nicht liefert, aus den nachfolgenden Anbietern ergänzt. + + Wiedergabe + + + Beim Pausieren weiter herunterladen + + + Ob der Player den Titel auch bei pausierter Wiedergabe weiter herunterlädt, bis zur gesamten Datei, damit die Fortsetzung nie auf Daten warten muss. + + + Automatische Wiedergabe + + + Ob die Wiedergabe am Ende eines Albums oder Interpreten automatisch mit den folgenden Titeln fortgesetzt wird. + + + Lückenlose Wiedergabe + + + Ob aufeinanderfolgende Titel ohne stille Lücke zwischen ihnen abgespielt werden. + + + ReplayGain + + + Wie die ReplayGain-Normalisierung auf die abgespielten Titel angewendet wird. + + + Aus + + + Pro Titel + + + Pro Album + + + Streaming-Qualität + + + Die Qualitätsobergrenze, die angewendet wird, wenn der Server einen Titel für die Wiedergabe normalisieren muss. Die direkte Wiedergabe wird nie verändert. + + + Automatisch + + + Niedrig (96 kbit/s) + + + Mittel (160 kbit/s) + + + Hoch (320 kbit/s) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx index 2778bb63..27a71a6f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx @@ -69,4 +69,58 @@ When enabled, the artwork of library items that the first artwork provider does not supply is filled in from the following providers. + + Playback + + + Keep downloading while paused + + + Whether the player keeps downloading the track while playback is paused, up to the entire file, so resuming never waits for data. + + + Autoplay + + + Whether playback continues automatically with the following tracks when an album or artist finishes. + + + Gapless playback + + + Whether consecutive tracks play without a silent gap between them. + + + ReplayGain + + + How ReplayGain normalization is applied to the tracks you play. + + + Off + + + Per track + + + Per album + + + Streaming quality + + + The quality cap applied when the server has to normalize a track for playback. Direct playback is never changed. + + + Automatic + + + Low (96 kbps) + + + Medium (160 kbps) + + + High (320 kbps) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx index fc36ab24..c4ad3366 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx @@ -69,4 +69,58 @@ Cuando está habilitado, las ilustraciones de los elementos de la biblioteca que el primer proveedor de ilustraciones no proporciona se completan desde los proveedores siguientes. + + Reproducción + + + Seguir descargando en pausa + + + Indica si el reproductor sigue descargando la pista mientras la reproducción está en pausa, hasta el archivo completo, para que reanudar nunca espere datos. + + + Reproducción automática + + + Indica si la reproducción continúa automáticamente con las pistas siguientes al terminar un álbum o un artista. + + + Reproducción sin pausas + + + Indica si las pistas consecutivas se reproducen sin un silencio entre ellas. + + + ReplayGain + + + Cómo se aplica la normalización ReplayGain a las pistas que reproduces. + + + Desactivado + + + Por pista + + + Por álbum + + + Calidad de transmisión + + + El límite de calidad que se aplica cuando el servidor tiene que normalizar una pista para reproducirla. La reproducción directa nunca se modifica. + + + Automática + + + Baja (96 kbps) + + + Media (160 kbps) + + + Alta (320 kbps) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx index 0366f7b8..5b327b98 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx @@ -69,4 +69,58 @@ Lorsque cette option est activée, les illustrations des éléments de la bibliothèque que le premier fournisseur d'illustrations ne fournit pas sont complétées par les fournisseurs suivants. + + Lecture + + + Continuer le téléchargement en pause + + + Indique si le lecteur continue de télécharger le morceau lorsque la lecture est en pause, jusqu'au fichier entier, afin que la reprise n'attende jamais les données. + + + Lecture automatique + + + Indique si la lecture se poursuit automatiquement avec les morceaux suivants à la fin d'un album ou d'un artiste. + + + Lecture sans interruption + + + Indique si les morceaux consécutifs sont lus sans silence entre eux. + + + ReplayGain + + + La manière dont la normalisation ReplayGain est appliquée aux morceaux que vous écoutez. + + + Désactivé + + + Par morceau + + + Par album + + + Qualité de diffusion + + + Le plafond de qualité appliqué lorsque le serveur doit normaliser un morceau pour la lecture. La lecture directe n'est jamais modifiée. + + + Automatique + + + Basse (96 kbit/s) + + + Moyenne (160 kbit/s) + + + Élevée (320 kbit/s) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx index 70ab422f..82a30343 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx @@ -69,4 +69,58 @@ Se abilitato, le illustrazioni degli elementi della libreria che il primo provider di illustrazioni non fornisce vengono integrate dai provider successivi. + + Riproduzione + + + Continua il download in pausa + + + Indica se il lettore continua a scaricare il brano mentre la riproduzione è in pausa, fino all'intero file, così che la ripresa non debba mai attendere i dati. + + + Riproduzione automatica + + + Indica se la riproduzione continua automaticamente con i brani successivi al termine di un album o di un artista. + + + Riproduzione senza interruzioni + + + Indica se i brani consecutivi vengono riprodotti senza un silenzio tra loro. + + + ReplayGain + + + Come la normalizzazione ReplayGain viene applicata ai brani che riproduci. + + + Disattivato + + + Per brano + + + Per album + + + Qualità dello streaming + + + Il limite di qualità applicato quando il server deve normalizzare un brano per la riproduzione. La riproduzione diretta non viene mai modificata. + + + Automatica + + + Bassa (96 kbps) + + + Media (160 kbps) + + + Alta (320 kbps) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx index 6b24406d..0114337d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx @@ -69,4 +69,58 @@ 有効にすると、最初のアートワークプロバイダーが提供しないライブラリ項目のアートワークが、後続のプロバイダーから補完されます。 + + 再生 + + + 一時停止中もダウンロードを続ける + + + 再生を一時停止している間もプレーヤーがトラックのダウンロードをファイル全体まで続けるかどうか。再開時にデータを待たずに済みます。 + + + 自動再生 + + + アルバムまたはアーティストの再生が終わったときに、続くトラックを自動的に再生するかどうか。 + + + ギャップレス再生 + + + 連続するトラックを間に無音を挟まずに再生するかどうか。 + + + ReplayGain + + + 再生するトラックに ReplayGain の正規化をどのように適用するか。 + + + オフ + + + トラックごと + + + アルバムごと + + + ストリーミング品質 + + + サーバーが再生のためにトラックを正規化する必要がある場合に適用される品質の上限。直接再生は決して変更されません。 + + + 自動 + + + 低 (96 kbps) + + + 中 (160 kbps) + + + 高 (320 kbps) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx index 2778bb63..27a71a6f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx @@ -69,4 +69,58 @@ When enabled, the artwork of library items that the first artwork provider does not supply is filled in from the following providers. + + Playback + + + Keep downloading while paused + + + Whether the player keeps downloading the track while playback is paused, up to the entire file, so resuming never waits for data. + + + Autoplay + + + Whether playback continues automatically with the following tracks when an album or artist finishes. + + + Gapless playback + + + Whether consecutive tracks play without a silent gap between them. + + + ReplayGain + + + How ReplayGain normalization is applied to the tracks you play. + + + Off + + + Per track + + + Per album + + + Streaming quality + + + The quality cap applied when the server has to normalize a track for playback. Direct playback is never changed. + + + Automatic + + + Low (96 kbps) + + + Medium (160 kbps) + + + High (320 kbps) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx index 1a6e38b5..cf66fa31 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx @@ -69,4 +69,58 @@ Când este activat, ilustrațiile elementelor din bibliotecă pe care primul furnizor de ilustrații nu le oferă sunt completate de la furnizorii următori. + + Redare + + + Continuă descărcarea în pauză + + + Dacă playerul continuă să descarce piesa în timp ce redarea este în pauză, până la întregul fișier, astfel încât reluarea să nu aștepte niciodată datele. + + + Redare automată + + + Dacă redarea continuă automat cu piesele următoare la sfârșitul unui album sau al unui artist. + + + Redare fără întreruperi + + + Dacă piesele consecutive sunt redate fără o pauză de sunet între ele. + + + ReplayGain + + + Modul în care normalizarea ReplayGain este aplicată pieselor pe care le redai. + + + Dezactivat + + + Per piesă + + + Per album + + + Calitatea fluxului + + + Limita de calitate aplicată atunci când serverul trebuie să normalizeze o piesă pentru redare. Redarea directă nu este niciodată modificată. + + + Automată + + + Redusă (96 kbps) + + + Medie (160 kbps) + + + Ridicată (320 kbps) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx index 74bf06a6..6bbf73e6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx @@ -69,4 +69,58 @@ Коли ввімкнено, ілюстрації елементів бібліотеки, які не надає перший постачальник ілюстрацій, доповнюються від наступних постачальників. + + Відтворення + + + Продовжувати завантаження на паузі + + + Чи продовжує програвач завантажувати трек, поки відтворення призупинено, аж до всього файлу, щоб відновлення ніколи не чекало на дані. + + + Автовідтворення + + + Чи продовжується відтворення автоматично наступними треками після завершення альбому або виконавця. + + + Відтворення без пауз + + + Чи відтворюються послідовні треки без тихої паузи між ними. + + + ReplayGain + + + Як нормалізація ReplayGain застосовується до треків, які ви відтворюєте. + + + Вимкнено + + + Для кожного треку + + + Для кожного альбому + + + Якість потокового передавання + + + Обмеження якості, що застосовується, коли сервер має нормалізувати трек для відтворення. Пряме відтворення ніколи не змінюється. + + + Автоматично + + + Низька (96 kbps) + + + Середня (160 kbps) + + + Висока (320 kbps) + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx index 592699f7..08aa28b9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx @@ -69,4 +69,58 @@ 启用后,首个图片提供程序未提供的媒体库项目图片将由后续提供程序补齐。 + + 播放 + + + 暂停时继续下载 + + + 播放暂停时播放器是否继续下载曲目直到整个文件,这样恢复播放时无需等待数据。 + + + 自动播放 + + + 专辑或艺术家播放结束后是否自动继续播放后续曲目。 + + + 无缝播放 + + + 连续曲目之间是否无静默间隔地播放。 + + + ReplayGain + + + 如何对您播放的曲目应用 ReplayGain 音量标准化。 + + + 关闭 + + + 按曲目 + + + 按专辑 + + + 流媒体质量 + + + 当服务器需要为播放对曲目进行标准化时应用的质量上限。直接播放永远不会被更改。 + + + 自动 + + + 低 (96 kbps) + + + 中 (160 kbps) + + + 高 (320 kbps) + diff --git a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml index 904b8a2d..0a38b2b1 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml @@ -130,6 +130,78 @@
@_localizer["DescriptionShouldAggregateArtworkWhenMissing"] + +
+

@_localizer["Playback"]

+
+ +
+
+ : +
+
+ +
+ @_localizer["DescriptionShouldKeepDownloadingWhilePaused"] +
+ +
+
+ : +
+
+ +
+ @_localizer["DescriptionShouldAutoplay"] +
+ +
+
+ : +
+
+ +
+ @_localizer["DescriptionIsGaplessPlaybackEnabled"] +
+ +
+
+ : +
+
+ +
+ @_localizer["DescriptionReplayGainMode"] +
+ +
+
+ : +
+
+ +
+ @_localizer["DescriptionStreamingQuality"] +
@@ -154,6 +226,11 @@ const checkboxShouldPreserveBookStyles = document.getElementById('ShouldPreserveBookStyles'); const checkboxShouldAggregateMetadataWhenMissing = document.getElementById('ShouldAggregateMetadataWhenMissing'); const checkboxShouldAggregateArtworkWhenMissing = document.getElementById('ShouldAggregateArtworkWhenMissing'); + const checkboxShouldKeepDownloadingWhilePaused = document.getElementById('ShouldKeepDownloadingWhilePaused'); + const checkboxShouldAutoplay = document.getElementById('ShouldAutoplay'); + const checkboxIsGaplessPlaybackEnabled = document.getElementById('IsGaplessPlaybackEnabled'); + const selectReplayGainMode = document.getElementById('ReplayGainMode'); + const selectStreamingQuality = document.getElementById('StreamingQuality'); // Toggle the enabled state of the items per page input based on the pagination checkbox. function updateItemsPerPageEnabledState() { @@ -172,6 +249,11 @@ checkboxShouldPreserveBookStyles.checked = data.shouldPreserveBookStyles === true; checkboxShouldAggregateMetadataWhenMissing.checked = data.shouldAggregateMetadataWhenMissing === true; checkboxShouldAggregateArtworkWhenMissing.checked = data.shouldAggregateArtworkWhenMissing === true; + checkboxShouldKeepDownloadingWhilePaused.checked = data.shouldKeepDownloadingWhilePaused === true; + checkboxShouldAutoplay.checked = data.shouldAutoplay === true; + checkboxIsGaplessPlaybackEnabled.checked = data.isGaplessPlaybackEnabled === true; + selectReplayGainMode.value = data.replayGainMode ?? 'Off'; + selectStreamingQuality.value = data.streamingQuality ?? 'Auto'; updateItemsPerPageEnabledState(); } } @@ -186,7 +268,12 @@ ShouldAggregateMetadataWhenMissing: checkboxShouldAggregateMetadataWhenMissing.checked, ShouldAggregateArtworkWhenMissing: checkboxShouldAggregateArtworkWhenMissing.checked, ShouldRenderPdfAsImages: checkboxShouldRenderPdfAsImages.checked, - ShouldPreserveBookStyles: checkboxShouldPreserveBookStyles.checked + ShouldPreserveBookStyles: checkboxShouldPreserveBookStyles.checked, + ShouldKeepDownloadingWhilePaused: checkboxShouldKeepDownloadingWhilePaused.checked, + ShouldAutoplay: checkboxShouldAutoplay.checked, + IsGaplessPlaybackEnabled: checkboxIsGaplessPlaybackEnabled.checked, + ReplayGainMode: selectReplayGainMode.value, + StreamingQuality: selectStreamingQuality.value }; const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_USER_SETTINGS)', formData); if (data && data.isUpdated === true) diff --git a/src/Lumina.sln b/src/Lumina.sln index 8a3f9d13..f9cafda0 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -412,7 +412,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "authorization", "authorizat EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "settings", "settings", "{240E1B2A-08A3-439D-B8B2-4D9C18B4AF8A}" ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\users-management\settings\GetPlaybackState.http = ..\docs\technical\requests\users-management\settings\GetPlaybackState.http ..\docs\technical\requests\users-management\settings\GetUserSettings.http = ..\docs\technical\requests\users-management\settings\GetUserSettings.http + ..\docs\technical\requests\users-management\settings\UpdatePlaybackState.http = ..\docs\technical\requests\users-management\settings\UpdatePlaybackState.http ..\docs\technical\requests\users-management\settings\UpdateUserSettings.http = ..\docs\technical\requests\users-management\settings\UpdateUserSettings.http EndProjectSection EndProject diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs index 721527a2..9997a6ae 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -27,6 +28,13 @@ public class UserSettingsEntityFixture /// Optional. Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. /// Optional. Whether PDF books are rendered as page images for the user, or not. /// Optional. Whether the styles of the book content are preserved when it is rendered for the user, or not. + /// Optional. Whether the player keeps downloading a track while playback is paused, or not. + /// Optional. Whether the player continues playback at the end of an album or artist, or not. + /// Optional. Whether the player transitions between consecutive tracks without a gap, or not. + /// Optional. The way ReplayGain normalization is applied to the tracks the user plays. + /// Optional. The quality cap applied to the audio the server normalizes for the user. + /// Optional. The last volume the player reported for the user. + /// Optional. The last mute state the player reported for the user. /// The created user settings entity. public UserSettingsEntity Create( Guid? id = null, @@ -37,7 +45,14 @@ public class UserSettingsEntityFixture bool? isThemeCachingEnabled = null, bool? shouldAggregateMetadataWhenMissing = null, bool? shouldRenderPdfAsImages = null, - bool? shouldPreserveBookStyles = null) + bool? shouldPreserveBookStyles = null, + bool? shouldKeepDownloadingWhilePaused = null, + bool? shouldAutoplay = null, + bool? isGaplessPlaybackEnabled = null, + ReplayGainMode? replayGainMode = null, + PlaybackStreamingQuality? streamingQuality = null, + double? volume = null, + bool? isMuted = null) { return new Faker() .CustomInstantiator(f => new UserSettingsEntity @@ -50,7 +65,14 @@ public class UserSettingsEntityFixture IsThemeCachingEnabled = isThemeCachingEnabled ?? f.Random.Bool(), ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing ?? f.Random.Bool(), ShouldRenderPdfAsImages = shouldRenderPdfAsImages ?? f.Random.Bool(), - ShouldPreserveBookStyles = shouldPreserveBookStyles ?? f.Random.Bool() + ShouldPreserveBookStyles = shouldPreserveBookStyles ?? f.Random.Bool(), + ShouldKeepDownloadingWhilePaused = shouldKeepDownloadingWhilePaused ?? f.Random.Bool(), + ShouldAutoplay = shouldAutoplay ?? f.Random.Bool(), + IsGaplessPlaybackEnabled = isGaplessPlaybackEnabled ?? f.Random.Bool(), + ReplayGainMode = replayGainMode ?? f.PickRandom(), + StreamingQuality = streamingQuality ?? f.PickRandom(), + Volume = volume ?? f.Random.Double(0.0, 1.0), + IsMuted = isMuted ?? f.Random.Bool() }) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs index 36b56f5f..73f32c90 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -25,6 +26,11 @@ public class UpdateUserSettingsCommandFixture /// Optional. Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Optional. Whether PDF books are rendered as page images for the user. /// Optional. Whether the styles of the book content are preserved when it is rendered for the user. + /// Optional. Whether the player keeps downloading a track while playback is paused, or not. + /// Optional. Whether the player continues playback at the end of an album or artist, or not. + /// Optional. Whether the player transitions between consecutive tracks without a gap, or not. + /// Optional. The way ReplayGain normalization is applied to the tracks the user plays. + /// Optional. The quality cap applied to the audio the server normalizes for the user. /// The created command. public UpdateUserSettingsCommand Create( bool? isPaginationEnabled = null, @@ -34,10 +40,15 @@ public class UpdateUserSettingsCommandFixture bool? shouldAggregateMetadataWhenMissing = null, bool? shouldAggregateArtworkWhenMissing = null, bool? shouldRenderPdfAsImages = null, - bool? shouldPreserveBookStyles = null) + bool? shouldPreserveBookStyles = null, + bool? shouldKeepDownloadingWhilePaused = null, + bool? shouldAutoplay = null, + bool? isGaplessPlaybackEnabled = null, + ReplayGainMode? replayGainMode = null, + PlaybackStreamingQuality? streamingQuality = null) { return new Faker() - .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default, default, default, default, default)) + .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default, default, default, default, default, default, default, default, default, default)) .RuleFor(x => x.IsPaginationEnabled, f => isPaginationEnabled ?? f.Random.Bool()) .RuleFor(x => x.ItemsPerPage, f => itemsPerPage ?? f.Random.Int(1, 100)) .RuleFor(x => x.ShouldIgnoreThePrefixForAlphaPicker, f => shouldIgnoreThePrefixForAlphaPicker ?? f.Random.Bool()) @@ -46,6 +57,11 @@ public class UpdateUserSettingsCommandFixture .RuleFor(x => x.ShouldAggregateArtworkWhenMissing, f => shouldAggregateArtworkWhenMissing ?? f.Random.Bool()) .RuleFor(x => x.ShouldRenderPdfAsImages, f => shouldRenderPdfAsImages ?? f.Random.Bool()) .RuleFor(x => x.ShouldPreserveBookStyles, f => shouldPreserveBookStyles ?? f.Random.Bool()) + .RuleFor(x => x.ShouldKeepDownloadingWhilePaused, f => shouldKeepDownloadingWhilePaused ?? f.Random.Bool()) + .RuleFor(x => x.ShouldAutoplay, f => shouldAutoplay ?? f.Random.Bool()) + .RuleFor(x => x.IsGaplessPlaybackEnabled, f => isGaplessPlaybackEnabled ?? f.Random.Bool()) + .RuleFor(x => x.ReplayGainMode, f => replayGainMode ?? f.PickRandom()) + .RuleFor(x => x.StreamingQuality, f => streamingQuality ?? f.PickRandom()) .Generate(); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs index 6240d10e..44c56f6b 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -27,6 +28,11 @@ public class UpdateUserSettingsRequestFixture /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Whether PDF books are rendered as page images for the user. /// Whether the styles of the book content are preserved when it is rendered for the user. + /// Whether the player keeps downloading a track while playback is paused. + /// Whether the player continues playback at the end of an album or artist. + /// Whether the player transitions between consecutive tracks without a gap. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. /// The created . public UpdateUserSettingsRequest Create( bool? isPaginationEnabled = null, @@ -36,7 +42,12 @@ public class UpdateUserSettingsRequestFixture bool? shouldAggregateMetadataWhenMissing = null, bool? shouldAggregateArtworkWhenMissing = null, bool? shouldRenderPdfAsImages = null, - bool? shouldPreserveBookStyles = null) + bool? shouldPreserveBookStyles = null, + bool? shouldKeepDownloadingWhilePaused = null, + bool? shouldAutoplay = null, + bool? isGaplessPlaybackEnabled = null, + ReplayGainMode? replayGainMode = null, + PlaybackStreamingQuality? streamingQuality = null) { return new UpdateUserSettingsRequest( isPaginationEnabled ?? _faker.Random.Bool(), @@ -46,7 +57,12 @@ public class UpdateUserSettingsRequestFixture shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool(), shouldAggregateArtworkWhenMissing ?? _faker.Random.Bool(), shouldRenderPdfAsImages ?? _faker.Random.Bool(), - shouldPreserveBookStyles ?? _faker.Random.Bool()); + shouldPreserveBookStyles ?? _faker.Random.Bool(), + shouldKeepDownloadingWhilePaused ?? _faker.Random.Bool(), + shouldAutoplay ?? _faker.Random.Bool(), + isGaplessPlaybackEnabled ?? _faker.Random.Bool(), + replayGainMode ?? _faker.PickRandom(), + streamingQuality ?? _faker.PickRandom()); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs index 0723a9d2..504e3b92 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -29,6 +30,11 @@ public class UserSettingsResponseFixture /// Optional. Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Optional. Whether PDF books are rendered as page images for the user. /// Optional. Whether the styles of the book content are preserved when it is rendered for the user. + /// Optional. Whether the player keeps downloading a track while playback is paused. + /// Optional. Whether the player continues playback at the end of an album or artist. + /// Optional. Whether the player transitions between consecutive tracks without a gap. + /// Optional. The way ReplayGain normalization is applied to the tracks the user plays. + /// Optional. The quality cap applied to the audio the server normalizes for the user. /// The created . public UserSettingsResponse Create( Guid? userId = null, @@ -39,7 +45,12 @@ public class UserSettingsResponseFixture bool? shouldAggregateMetadataWhenMissing = null, bool? shouldAggregateArtworkWhenMissing = null, bool? shouldRenderPdfAsImages = null, - bool? shouldPreserveBookStyles = null) + bool? shouldPreserveBookStyles = null, + bool? shouldKeepDownloadingWhilePaused = null, + bool? shouldAutoplay = null, + bool? isGaplessPlaybackEnabled = null, + ReplayGainMode? replayGainMode = null, + PlaybackStreamingQuality? streamingQuality = null) { return new UserSettingsResponse( userId ?? Guid.NewGuid(), @@ -50,7 +61,12 @@ public class UserSettingsResponseFixture shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool(), shouldAggregateArtworkWhenMissing ?? _faker.Random.Bool(), shouldRenderPdfAsImages ?? _faker.Random.Bool(), - shouldPreserveBookStyles ?? _faker.Random.Bool()); + shouldPreserveBookStyles ?? _faker.Random.Bool(), + shouldKeepDownloadingWhilePaused ?? _faker.Random.Bool(), + shouldAutoplay ?? _faker.Random.Bool(), + isGaplessPlaybackEnabled ?? _faker.Random.Bool(), + replayGainMode ?? _faker.PickRandom(), + streamingQuality ?? _faker.PickRandom()); } /// diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs index 066592cc..5ed4e956 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs @@ -2,6 +2,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -28,6 +29,13 @@ public class UserSettingsFixture /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Whether PDF books are rendered as page images for the user. /// Whether the styles of the book content are preserved when it is rendered for the user. + /// Whether the player keeps downloading a track while playback is paused. + /// Whether the player continues playback at the end of an album or artist. + /// Whether the player transitions between consecutive tracks without a gap. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. + /// The last volume the player reported for the user. + /// The last mute state the player reported for the user. /// The created . public UserSettings Create( Guid? userId = null, @@ -38,7 +46,14 @@ public class UserSettingsFixture bool shouldAggregateMetadataWhenMissing = false, bool shouldAggregateArtworkWhenMissing = false, bool shouldRenderPdfAsImages = false, - bool shouldPreserveBookStyles = true) + bool shouldPreserveBookStyles = true, + bool shouldKeepDownloadingWhilePaused = true, + bool shouldAutoplay = true, + bool isGaplessPlaybackEnabled = true, + ReplayGainMode replayGainMode = ReplayGainMode.Off, + PlaybackStreamingQuality streamingQuality = PlaybackStreamingQuality.Auto, + double volume = 1.0, + bool isMuted = false) { Result settings = UserSettings.Create( userId is null ? UserId.CreateUnique() : UserId.Create(userId.Value), @@ -49,7 +64,14 @@ public class UserSettingsFixture shouldAggregateMetadataWhenMissing, shouldAggregateArtworkWhenMissing, shouldRenderPdfAsImages, - shouldPreserveBookStyles); + shouldPreserveBookStyles, + shouldKeepDownloadingWhilePaused, + shouldAutoplay, + isGaplessPlaybackEnabled, + replayGainMode, + streamingQuality, + volume, + isMuted); return settings.Value; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs index 29004a70..90317ec5 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Enums.AudioLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -28,6 +29,11 @@ public class UserSettingsDtoFixture /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. /// Whether PDF books are rendered as page images for the user. /// Whether the styles of the book content are preserved when it is rendered for the user. + /// Whether the player keeps downloading a track while playback is paused. + /// Whether the player continues playback at the end of an album or artist. + /// Whether the player transitions between consecutive tracks without a gap. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. /// A configured instance. public UserSettingsDto Create( Guid? userId = null, @@ -37,7 +43,12 @@ public class UserSettingsDtoFixture bool? isThemeCachingEnabled = null, bool? shouldAggregateMetadataWhenMissing = null, bool? shouldRenderPdfAsImages = null, - bool? shouldPreserveBookStyles = null) + bool? shouldPreserveBookStyles = null, + bool? shouldKeepDownloadingWhilePaused = null, + bool? shouldAutoplay = null, + bool? isGaplessPlaybackEnabled = null, + ReplayGainMode? replayGainMode = null, + PlaybackStreamingQuality? streamingQuality = null) { return new UserSettingsDto { @@ -48,7 +59,12 @@ public class UserSettingsDtoFixture IsThemeCachingEnabled = isThemeCachingEnabled ?? _faker.Random.Bool(), ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool(), ShouldRenderPdfAsImages = shouldRenderPdfAsImages ?? _faker.Random.Bool(), - ShouldPreserveBookStyles = shouldPreserveBookStyles ?? _faker.Random.Bool() + ShouldPreserveBookStyles = shouldPreserveBookStyles ?? _faker.Random.Bool(), + ShouldKeepDownloadingWhilePaused = shouldKeepDownloadingWhilePaused ?? _faker.Random.Bool(), + ShouldAutoplay = shouldAutoplay ?? _faker.Random.Bool(), + IsGaplessPlaybackEnabled = isGaplessPlaybackEnabled ?? _faker.Random.Bool(), + ReplayGainMode = replayGainMode ?? _faker.PickRandom(), + StreamingQuality = streamingQuality ?? _faker.PickRandom() }; } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs index 9b4c7a08..08c37f4d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs @@ -192,43 +192,6 @@ public class UpdateUserSettingsCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } - [Fact] - public async Task HandleAsync_WhenToDomainEntityFails_ShouldReturnErrorAndNotUpdate() - { - // Arrange - UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(); - // An entity carrying an invalid items-per-page value fails to convert to its domain aggregate. - UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId, itemsPerPage: 0); - _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) - .Returns(Result.From(existingSettings)); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUpdateSettingsFails_ShouldReturnErrorAndNotPersist() - { - // Arrange - UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(itemsPerPage: 0); - UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId); - _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) - .Returns(Result.From(existingSettings)); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - [Fact] public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotSaveChanges() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 7cd1e9a8..672d78cb 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -79,10 +79,20 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(3, typeof(DomainErrors.UserSettings).GetProperties().Length); + Assert.Equal(13, typeof(DomainErrors.UserSettings).GetProperties().Length); AssertError(DomainErrors.UserSettings.UserSettingsAlreadyExists, ErrorType.Conflict); AssertError(DomainErrors.UserSettings.UserSettingsNotFound, ErrorType.NotFound); AssertError(DomainErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.VolumeCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.VolumeMustBeBetweenZeroAndOne, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.IsMutedCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.ShouldKeepDownloadingWhilePausedCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.ShouldAutoplayCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.IsGaplessPlaybackEnabledCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.ReplayGainModeCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.StreamingQualityCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.InvalidReplayGainMode, ErrorType.Validation); + AssertError(DomainErrors.UserSettings.InvalidStreamingQuality, ErrorType.Validation); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs index 49092a2e..fbb27861 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; @@ -7,6 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettin using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Diagnostics.CodeAnalysis; #endregion @@ -80,7 +80,7 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true, shouldAggregateArtworkWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true); + Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true, shouldAggregateArtworkWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true, shouldKeepDownloadingWhilePaused: true, shouldAutoplay: true, isGaplessPlaybackEnabled: true, replayGainMode: ReplayGainMode.Off, streamingQuality: PlaybackStreamingQuality.Auto, volume: 1.0, isMuted: false); // Assert Assert.False(result.IsFailure); @@ -108,22 +108,6 @@ public class UserSettingsTests Assert.NotEqual(result.Value.Id.Value, result.Value.UserId.Value); } - [Theory] - [InlineData(0)] - [InlineData(-1)] - public void Create_WhenItemsPerPageIsNotPositive_ShouldReturnError(int itemsPerPage) - { - // Arrange - UserId userId = _userIdFixture.Create(); - - // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); - } - [Fact] public void Create_WhenCalledWithPreExistingIdAndValidValues_ShouldCreateSettingsWithThatId() { @@ -132,7 +116,7 @@ public class UserSettingsTests UserSettingsId id = _userSettingsIdFixture.Create(); // Act - Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: true); + Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: true, shouldKeepDownloadingWhilePaused: true, shouldAutoplay: true, isGaplessPlaybackEnabled: true, replayGainMode: ReplayGainMode.Off, streamingQuality: PlaybackStreamingQuality.Auto, volume: 1.0, isMuted: false); // Assert Assert.False(result.IsFailure); @@ -141,21 +125,6 @@ public class UserSettingsTests Assert.Equal(24, result.Value.ItemsPerPage); } - [Fact] - public void Create_WhenCalledWithPreExistingIdAndNonPositiveItemsPerPage_ShouldReturnError() - { - // Arrange - UserId userId = _userIdFixture.Create(); - UserSettingsId id = _userSettingsIdFixture.Create(); - - // Act - Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); - } - [Fact] public void UpdateSettings_WhenCalledWithValidValues_ShouldUpdateSettings() { @@ -163,7 +132,7 @@ public class UserSettingsTests UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true, shouldAggregateArtworkWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true); + Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true, shouldAggregateArtworkWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true, shouldKeepDownloadingWhilePaused: true, shouldAutoplay: true, isGaplessPlaybackEnabled: true, replayGainMode: ReplayGainMode.Off, streamingQuality: PlaybackStreamingQuality.Auto); // Assert Assert.False(result.IsFailure); @@ -175,20 +144,4 @@ public class UserSettingsTests Assert.True(userSettings.ShouldRenderPdfAsImages); Assert.True(userSettings.ShouldPreserveBookStyles); } - - [Theory] - [InlineData(0)] - [InlineData(-5)] - public void UpdateSettings_WhenItemsPerPageIsNotPositive_ShouldReturnError(int itemsPerPage) - { - // Arrange - UserSettings userSettings = _userSettingsFixture.Create(); - - // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); - } } From b7ed83c82f283838bb0c3e6631939fed5af30f08 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 15 Oct 2026 23:13:26 +0300 Subject: [PATCH 12/77] Adds the audio player core module, control API, capability detection and bar. --- docs/technical/theming/Theming.md | 37 + .../Core/Views/Shared/_AudioPlayer.cshtml | 61 +- .../Core/Views/Shared/_Layout.cshtml | 4 +- .../Views/Shared/_ThemeLayoutScripts.cshtml | 14 + .../wwwroot/css/site.css | 201 ++- .../audio-player/audio-player-capabilities.js | 190 +++ .../js/audio-player/audio-player-engine.js | 203 +++ .../js/audio-player/audio-player-errors.js | 65 + .../js/audio-player/audio-player-events.js | 135 ++ .../wwwroot/js/audio-player/audio-player.js | 1313 +++++++++++++++++ .../wwwroot/js/site.js | 25 +- 11 files changed, 2225 insertions(+), 23 deletions(-) create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index 3712232a..b22ec44a 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -13,6 +13,7 @@ The web client of Lumina is a themed shell: every page is rendered inside the te - [Safety Limits](#safety-limits) - [Template Resolution](#template-resolution) - [The Layout Template (shared/layout)](#the-layout-template-sharedlayout) + - [The Audio Player Bar](#the-audio-player-bar) - [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu) - [Page Templates](#page-templates) - [The Scripts Section](#the-scripts-section) @@ -222,6 +223,42 @@ The layout template of the bundled theme shows the intended shape: The rendered page content, navigation and scripts are inserted unescaped with `{{&...}}`, because they are trusted application HTML. The layout is best effort: when the theme cannot be loaded or rendered, the application falls back to its built-in layout, so a broken theme never takes the whole site down. +### The Audio Player Bar + +Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar is hidden until the user starts playback of a track, album or artist, and the global audio player script shows it, expands it and hides it again. The theming work that turns the bar into a theme template (a `shared/audio-player` page key with sub templates) is not part of this contract yet; until it lands, the bar is the application fallback markup, passed in as the `audioPlayer` field. + +The bar is fixed to the bottom of the viewport, so the theme owns the room reserved for it on the main content element. A layout must keep these element hooks, which the audio player drives (the two id controls are bound by the global site script, which routes them to the audio player): + +| Element | Hook | Meaning | +| --- | --- | --- | +| The bar container, with the `audio-player-container` class | `not-shown` class | The bar is hidden, and its height collapses. | +| The bar container | `full-height` class | The bar is expanded to its full height form. | +| The main content element | `audio-player-not-shown` class | The bar is hidden, so the content area uses the full height. | +| The main content element | `audio-player-full-height` class | The bar is expanded, so the content area gives it the full height. | +| The full height control | `id="audio-player-full-height-toggle"` | Expands or collapses the bar. | +| The close control | `id="audio-player-close"` | Stops playback, and hides the bar while it is condensed. | + +A theme must reserve the space for the bar itself, as the bundled themes do: + +```css +main { + bottom: 50px; + transition: bottom 1s ease, height 1s ease; +} + +main.audio-player-not-shown { + bottom: 0; +} + +main.audio-player-full-height { + bottom: calc(100% - 22px); /* full height minus the menu height */ +} +``` + +The application fallback layout, which renders when the active theme cannot be loaded, reserves the room itself, because the application stylesheet does not position the content area of a theme. A theme that omits the rules above leaves the fixed bar overlapping the bottom of the page. + +The markup inside the bar exposes the hook attributes the audio player script binds, such as `data-audio-player-play-pause`, `data-audio-player-progress`, `data-audio-player-current-time` and `data-audio-player-track-name`. A theme that replaces the bar markup must keep those attributes, and the play affordances of the pages use the `data-audio-player-play` trigger attribute. + ### The Navigation Template (shared/nav-menu) The navigation template renders the menu of the active theme. Its model contains the site name and two menu structures, one for the mobile menu and one for the desktop menu bar: diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml index 65f7ceaa..61363d5b 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml @@ -1,4 +1,4 @@ -@using Microsoft.Extensions.Localization +@using Microsoft.Extensions.Localization @inject IStringLocalizerFactory _stringLocalizerFactory @@ -6,12 +6,55 @@ IStringLocalizer localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web"); } -
- - @localizer["ToggleFullHeight"] - @localizer["ToggleVisibility"] +@* + APPLICATION FALLBACK AUDIO PLAYER BAR - READ BEFORE EDITING + + This partial renders the audio player bar into the layout of the application and of every theme, for an + authenticated visitor. It is only the markup: the behavior lives in the global audio player script + (wwwroot/js/audio-player/), which binds to the hooks documented below. + + The bar is hidden by default. The 'hidden' attribute keeps it unrendered until the audio player script takes over, + so a page load never shows the bar, not even for a frame while the stylesheets settle. The script then hands the bar + to the 'not-shown' class, which keeps it hidden until playback starts. + + The DOM contract a theme must preserve is: + - The container element with the 'audio-player-container' class, carrying 'not-shown' while the bar is hidden, + and 'full-height' while it is expanded. The audio player toggles both classes. + - The main content element, carrying 'audio-player-not-shown' while the bar is hidden, and 'audio-player-full-height' + while it is expanded. The audio player toggles both classes on it as well. + - The elements with the ids 'audio-player-full-height-toggle' and 'audio-player-close', which the global site script + binds and routes to the audio player. + - The hook attributes the audio player binds: 'data-audio-player-play-pause', '-progress', '-progress-played', + '-progress-downloaded', '-current-time', '-total-time', '-track-name', '-cover-thumbnail', '-cover-image' and '-queue'. + + The play affordances the pages hand to the player use the 'data-audio-player-play' trigger attribute. The + 'The Audio Player Bar' section of docs/technical/theming/Theming.md documents this contract for theme authors. +*@ + + diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml index 538e66af..f04be11b 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml @@ -46,12 +46,12 @@ else @ViewData["Title"] - Lumina @await Html.PartialAsync("_ThemeLayoutHead") - +
@await Html.PartialAsync("_NavMenu")
-
+
@Html.Raw(bodyHtml)
diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 436d303c..499c5a2d 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -1,9 +1,12 @@ @using Lumina.Presentation.Web.Common.DTO.Configuration +@using Lumina.Presentation.Web.Common.Routes +@using Lumina.Presentation.Web.Common.Services @using Microsoft.Extensions.Localization @using Microsoft.Extensions.Options @inject IStringLocalizerFactory _stringLocalizerFactory @inject IOptions _serverConfigurationModel +@inject IUrlService _urlService @{ IStringLocalizer localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web"); @@ -30,9 +33,20 @@ error: '@localizer["Error"]', information: '@localizer["Information"]' }; + // The endpoints the audio player reads the stored playback preferences of the user from. The routes are the culture + // aware web routes, so the player never hardcodes a path, and it never reaches the API server directly. + var audioPlayerConfiguration = { + getUserSettingsUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)', + getPlaybackStateUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_PLAYBACK_STATE)' + }; + + + + + diff --git a/src/Lumina.Presentation.Web/wwwroot/css/site.css b/src/Lumina.Presentation.Web/wwwroot/css/site.css index a0b95d58..a53b68e9 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/site.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/site.css @@ -1,4 +1,4 @@ -html, +html, body { margin: 0px; padding: 0px; @@ -1250,3 +1250,202 @@ body { .artwork-carousel-item:hover { border-color: #FFFFFF; } + +/* Audio player bar. This is the application fallback styling: the themes own the final look, and the + audio player script owns the state. The 'not-shown' and 'full-height' classes on the container, and + the matching 'audio-player-not-shown' and 'audio-player-full-height' classes on main, are the contract. */ +.audio-player-container { + position: fixed; + left: 0px; + right: 0px; + bottom: 0px; + z-index: 997; + display: flex; + flex-direction: column; + height: 50px; + overflow: hidden; + background-color: #1C1C1C; + border-top: 1px solid #444444; + transition: height 0.4s ease; +} + +.audio-player-container.not-shown { + height: 0px; + border-top-width: 0px; +} + +/* The 'hidden' attribute keeps the bar unrendered until the audio player script takes over, so that a page load + never shows it, not even for a frame while the stylesheets settle. The script removes it once the bar is already + in its hidden state, so the removal is never visible. */ +.audio-player-container[hidden] { + display: none !important; +} + +/* While the audio player applies its initial hidden state, its transitions, and the offset transition of the content + area, are suppressed, so that a page load never slides the bar or the content into place. The player removes the + marker once it is initialized, and later show, hide and expand transitions work normally. */ +html.audio-player-initializing main, +html.audio-player-initializing .audio-player-container { + transition: none !important; +} + +/* The fallback layout has no theme to position the content area, so it reserves room for the bar itself, consuming the + same classes a theme consumes on main. A themed layout positions main itself and does not carry this class. */ +.application-fallback-layout main { + padding-bottom: 50px; + transition: padding-bottom 0.4s ease; +} + +.application-fallback-layout main.audio-player-not-shown { + padding-bottom: 0px; +} + +.audio-player-container.full-height { + height: calc(100% - 22px); /* full height minus the height of the menu bar */ +} + +.audio-player-bar { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: 8px; + height: 50px; + padding: 0px 10px; + color: #E6E6E6; +} + +.audio-player-cover-thumbnail { + flex: 0 0 auto; + width: 36px; + height: 36px; + object-fit: cover; +} + +.audio-player-track-name { + flex: 1 1 20%; + min-width: 0px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.audio-player-time { + flex: 0 0 auto; + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +.audio-player-progress { + position: relative; + flex: 2 1 40%; + min-width: 40px; + height: 6px; + background-color: #333333; + cursor: pointer; +} + +/* The bar exposes three distinct states a theme can style: the not yet downloaded track, the downloaded + part ('audio-player-progress-downloaded'), and the played part ('audio-player-progress-played'). */ +.audio-player-progress-played, +.audio-player-progress-downloaded { + position: absolute; + top: 0px; + left: 0px; + width: 0%; + height: 100%; +} + +.audio-player-progress-downloaded { + background-color: #5A6B78; +} + +.audio-player-progress-played { + background-color: #6DCBFE; +} + +.audio-player-transport { + flex: 0 0 auto; + display: flex; + align-items: center; +} + +.audio-player-play-pause { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0px; + background-color: transparent; + border: 0px; + cursor: pointer; +} + +/* The play affordance is a right pointing triangle, and the pause affordance two bars, both drawn with CSS + so that a theme can restyle them without an image. */ +.audio-player-play-pause-icon { + display: block; + width: 0px; + height: 0px; + border-style: solid; + border-width: 6px 0px 6px 10px; + border-color: transparent transparent transparent #E6E6E6; +} + +.audio-player-play-pause.is-playing .audio-player-play-pause-icon { + width: 10px; + height: 12px; + border-width: 0px; + border-right: 3px solid #E6E6E6; + border-left: 3px solid #E6E6E6; +} + +.audio-player-controls { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 10px; +} + +.audio-player-expanded { + display: none; + flex: 1 1 auto; + min-height: 0px; + gap: 16px; + padding: 16px; + overflow-y: auto; +} + +.audio-player-container.full-height .audio-player-expanded { + display: flex; + flex-direction: row; +} + +.audio-player-cover-image { + flex: 0 0 auto; + width: 240px; + height: 240px; + object-fit: cover; +} + +.audio-player-queue { + flex: 1 1 auto; + margin: 0px; + padding: 0px; + overflow-y: auto; + list-style: none; +} + +.audio-player-queue-item { + display: flex; + justify-content: space-between; + gap: 12px; + padding: 6px 8px; + border-bottom: 1px solid #333333; +} + +.audio-player-queue-item-title { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js new file mode 100644 index 00000000..5a33dcdb --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js @@ -0,0 +1,190 @@ +/** + * Capability detection of the audio player. + * + * The player decodes with WebCodecs and outputs through the Web Audio API, so before it can play anything it must know which of those browser capabilities exist, and which audio codecs the + * browser can decode. The report is produced once, is cached, and is published through the event bus, so that a consumer can present a clear failure instead of a silent, broken player. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Enum-like object for the browser capabilities the player requires. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerCapability = Object.freeze({ + // The WebCodecs API, the family of decoders the player feeds. + WEB_CODECS: 'webCodecs', + // WebCodecs.AudioDecoder, the audio decoder the player actually consumes. + AUDIO_DECODER: 'audioDecoder', + // The Web Audio API, used for output. + AUDIO_CONTEXT: 'audioContext' + }); + + /** + * The codec configurations probed with AudioDecoder.isConfigSupported, one per audio codec the demuxers of the player can recognize. + * Each entry is a representative configuration; the returned report says whether the browser can decode that codec at all. + * @readonly + * @type {ReadonlyArray<{ name: string, config: Object }>} + */ + LuminaAudioPlayer.PROBED_AUDIO_CODECS = Object.freeze([ + Object.freeze({ name: 'mp3', config: Object.freeze({ codec: 'mp3', sampleRate: 44100, numberOfChannels: 2 }) }), + Object.freeze({ name: 'flac', config: Object.freeze({ codec: 'flac', sampleRate: 44100, numberOfChannels: 2 }) }), + Object.freeze({ name: 'opus', config: Object.freeze({ codec: 'opus', sampleRate: 48000, numberOfChannels: 2 }) }), + Object.freeze({ name: 'aac', config: Object.freeze({ codec: 'mp4a.40.2', sampleRate: 44100, numberOfChannels: 2 }) }), + Object.freeze({ name: 'vorbis', config: Object.freeze({ codec: 'vorbis', sampleRate: 44100, numberOfChannels: 2 }) }), + Object.freeze({ name: 'pcm', config: Object.freeze({ codec: 'pcm-s16', sampleRate: 44100, numberOfChannels: 2 }) }) + ]); + + /** + * Detects the browser capabilities the audio player relies on, and caches the result. + */ + class PlayerCapabilities { + /** + * Creates an instance of PlayerCapabilities. + * @param {Window} [targetWindow] - The window whose capabilities are inspected. Defaults to the current window. + */ + constructor(targetWindow = window) { + this.window = targetWindow; + /** @type {Object|null} */ + this.report = null; + /** @type {Promise|null} */ + this.pendingReport = null; + } + + /** + * Checks whether the WebCodecs API is present. + * @returns {boolean} True when the browser exposes at least one WebCodecs decoder. + */ + hasWebCodecs() { + // The audio side of WebCodecs is what the player feeds, but any decoder of the family implies the API is exposed + // at all; the precise check of the decoder the player consumes is hasAudioDecoder below. + return typeof this.window.AudioDecoder === 'function' || typeof this.window.VideoDecoder === 'function'; + } + + /** + * Checks whether WebCodecs.AudioDecoder is present. + * @returns {boolean} True when the audio decoder the player consumes exists. + */ + hasAudioDecoder() { + return typeof this.window.AudioDecoder === 'function'; + } + + /** + * Checks whether the Web Audio API is present. + * @returns {boolean} True when an AudioContext constructor exists. + */ + hasAudioContext() { + return typeof this.window.AudioContext === 'function' || typeof this.window.webkitAudioContext === 'function'; + } + + /** + * Asks the browser whether it can decode a single audio configuration. + * @param {Object} config - An AudioDecoderConfig like value, with codec, sampleRate and numberOfChannels. + * @returns {Promise} True when the configuration is decodable, false otherwise or when it cannot be probed. + */ + async supportsAudioConfigAsync(config) { + if (!this.hasAudioDecoder()) + return false; + try { + const result = await this.window.AudioDecoder.isConfigSupported(config); + // The isConfigSupported call resolves with a result object; a missing result and a false supported flag both + // mean the browser cannot decode this configuration, so the answer is returned as a single boolean. + return result !== null && result !== undefined && result.supported === true; + } catch (error) { + // An unsupported codec string can make isConfigSupported reject; that is a "no", not a failure of the player. + console.debug('Audio player: the codec configuration was rejected by the browser.', config, error); + return false; + } + } + + /** + * Reports whether the browser can decode a codec, by probing it with AudioDecoder.isConfigSupported. + * @param {Object} config - An AudioDecoderConfig like value, with codec, sampleRate and numberOfChannels. + * @returns {Promise} True when the configuration is decodable, false otherwise. + */ + async supportsCodecAsync(config) { + return await this.supportsAudioConfigAsync(config); + } + + /** + * Detects every capability the player needs, in parallel, and caches the report. + * + * The returned report has the shape: + * { webCodecs, audioDecoder, audioContext, codecs, missing, supported }, where codecs maps each probed codec name to a boolean, missing lists the + * {@link LuminaAudioPlayer.PlayerCapability} values that are absent, and supported is true only when every required capability is present. + * @returns {Promise} The capability report. + */ + async detectAsync() { + // The report is immutable and expensive to build, so it is cached for the life of the player; while the first + // detection is still running, later callers share its promise instead of starting a second round of probes. + if (this.report) + return this.report; + if (this.pendingReport) + return this.pendingReport; + this.pendingReport = this.runDetectionAsync(); + try { + this.report = await this.pendingReport; + } finally { + this.pendingReport = null; + } + return this.report; + } + + /** + * Runs the actual detection, once. + * @returns {Promise} The capability report. + */ + async runDetectionAsync() { + const webCodecs = this.hasWebCodecs(); + const audioDecoder = this.hasAudioDecoder(); + const audioContext = this.hasAudioContext(); + + const codecs = {}; + if (audioDecoder) { + // Each isConfigSupported is an independent round trip to the browser, so they are probed in parallel; the + // results are folded in afterwards, in probe order, so the report never depends on which probe finishes first. + const probeResults = await Promise.all(LuminaAudioPlayer.PROBED_AUDIO_CODECS.map(async (probe) => { + return { name: probe.name, supported: await this.supportsAudioConfigAsync(probe.config) }; + })); + for (const probeResult of probeResults) + codecs[probeResult.name] = probeResult.supported; + } else { + // Without a decoder nothing can be probed, but every codec key is still reported as false, so that a + // consumer reads the same shape whether the decoder exists or not, instead of testing for a missing key. + for (const probe of LuminaAudioPlayer.PROBED_AUDIO_CODECS) + codecs[probe.name] = false; + } + + // Only the three hard capabilities decide whether the player can run at all; a codec the browser cannot decode is + // not fatal here, because the server can normalize such a track, which the delivery decision handles at play time. + const missing = []; + if (!webCodecs) + missing.push(LuminaAudioPlayer.PlayerCapability.WEB_CODECS); + if (!audioDecoder) + missing.push(LuminaAudioPlayer.PlayerCapability.AUDIO_DECODER); + if (!audioContext) + missing.push(LuminaAudioPlayer.PlayerCapability.AUDIO_CONTEXT); + + // The report is shared and cached, so it is frozen to stop one consumer from mutating what every other consumer reads. + return Object.freeze({ + webCodecs, + audioDecoder, + audioContext, + codecs: Object.freeze(codecs), + missing: Object.freeze(missing), + supported: missing.length === 0 + }); + } + + /** + * Gets the cached capability report, or null when detection has not run yet. + * @returns {Object|null} The capability report, or null. + */ + getReport() { + return this.report; + } + } + + LuminaAudioPlayer.PlayerCapabilities = PlayerCapabilities; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js new file mode 100644 index 00000000..f74f6723 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js @@ -0,0 +1,203 @@ +/** + * Engine interface of the audio player, and the registry of its implementations. + * + * The player controller owns the state machine, the play descriptor, the queue and the bar, but it + * produces no audio itself. Audio is produced by an engine, a swappable implementation of the + * interface documented below. This keeps the controller stable while the audio pipeline is built up, + * and lets a test drive the controller with a scripted engine instead of a real sound card. + * + * The engine interface + * -------------------- + * An engine is created by a factory that receives the engine host (see below) and returns an object + * with these methods, all of them returning a Promise: + * - loadAsync(descriptor): prepares the resources of a track (opens its stream, configures a decoder). + * - playAsync(): starts, or resumes, audible playback. + * - pauseAsync(): suspends audible playback, keeping the current position. + * - seekAsync(seconds): moves the playhead to the given position, in seconds. + * - setVolumeAsync(volume): sets the output volume, as a value between 0 and 1, with 0 meaning silence. + * - destroyAsync(): releases every resource the engine holds, including any audio context. + * + * The engine host + * --------------- + * The factory also receives a host object that the engine uses to talk back to the controller, so + * that the controller stays the single source of truth: + * - host.events: the player event bus, for {@link LuminaAudioPlayer.PlayerEvent} values the engine emits itself. + * - host.reportTime(currentTime, duration): reports the playhead and the known duration. + * - host.reportDuration(duration): reports a duration discovered after loading. + * - host.reportProgress(downloadedFraction): reports how much of the track has been downloaded, between 0 and 1. + * - host.reportEnded(): reports that the current track reached its end. + * - host.reportError(error): reports an engine failure, wrapped into a {@link LuminaAudioPlayer.PlayerError}. + * + * Registering and selecting an engine + * ----------------------------------- + * Engines are registered on a registry by name, and the player runs the engine selected by name. The silent engine + * is registered under NULL_ENGINE_NAME and is the default, so the player is usable before the real pipeline exists. + * The singleton is created automatically when the module loads, so the way to plug a real engine into the running + * application is the instance seam: + * - window.LuminaAudioPlayer.instance.registerEngine(name, factory) registers a factory of the shape (host) => engine. + * - window.LuminaAudioPlayer.instance.useEngine(name) selects a registered engine; it takes effect on the next load, + * and it returns the player to idle when an engine instance is already running. + * A player can also be created directly with a selected engine and a populated registry through the constructor + * ({ engineName, engineRegistry }); LuminaAudioPlayer.createDefaultPlayer(options) forwards those options only for the + * first creation of the singleton, for a composition that creates the player itself, such as a test. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The name under which the silent engine that ships with the core module is registered. + * @readonly + * @type {string} + */ + LuminaAudioPlayer.NULL_ENGINE_NAME = 'null'; + + /** + * An engine that fulfills the engine interface without producing any audio. + * + * It is the default engine of the core module, so that the control API, the state machine, the + * lifecycle and the bar are fully callable before the download, decode and render pipeline is + * wired up. It tracks a playhead so that a seek, a pause and a resume report the position the + * player expects, but it never loads, decodes or plays a byte. + */ + class NullPlayerEngine { + /** + * Creates an instance of NullPlayerEngine. + * @param {Object} host - The engine host provided by the player controller. + */ + constructor(host) { + this.host = host; + this.descriptor = null; + this.currentTime = 0; + } + + /** + * Accepts a play descriptor without preparing any resource, and resets the tracked playhead. + * @param {Object} descriptor - The play descriptor of the requested track. + * @returns {Promise} A promise that always resolves. + */ + async loadAsync(descriptor) { + this.descriptor = descriptor; + this.currentTime = 0; + } + + /** + * Reports the tracked playhead without producing any audio, so that a resume keeps the position a pause left. + * @returns {Promise} A promise that always resolves. + */ + async playAsync() { + this.host.reportTime(this.currentTime, this.getDuration()); + } + + /** + * Reports the suspension of playback without producing any audio, keeping the tracked playhead. + * @returns {Promise} A promise that always resolves. + */ + async pauseAsync() { + } + + /** + * Records and reports the requested playhead without producing any audio. + * @param {number} seconds - The requested position, in seconds. + * @returns {Promise} A promise that always resolves. + */ + async seekAsync(seconds) { + const position = Number(seconds); + this.currentTime = Number.isFinite(position) && position > 0 ? position : 0; + this.host.reportTime(this.currentTime, this.getDuration()); + } + + /** + * Accepts an output volume without applying it to any output. + * @param {number} volume - The requested output volume, between 0 and 1. + * @returns {Promise} A promise that always resolves. + */ + async setVolumeAsync(volume) { + } + + /** + * Releases nothing, because nothing was acquired. + * @returns {Promise} A promise that always resolves. + */ + async destroyAsync() { + this.descriptor = null; + this.currentTime = 0; + } + + /** + * Gets the duration of the loaded descriptor, or zero when nothing is loaded. + * @returns {number} The known duration, in seconds. + */ + getDuration() { + return this.descriptor && Number.isFinite(this.descriptor.durationInSeconds) + ? this.descriptor.durationInSeconds + : 0; + } + } + + /** + * A registry of engine factories, keyed by name, used to resolve the engine the player runs with. + * The later stages of the player register the real download, decode and render engine here; the + * core module only registers the silent engine. + */ + class PlayerEngineRegistry { + /** + * Creates an instance of PlayerEngineRegistry. + */ + constructor() { + /** @type {Map} */ + this.factories = new Map(); + } + + /** + * Registers an engine factory. + * @param {string} name - The name the engine is resolved by. + * @param {Function} factory - A factory that receives the engine host and returns an engine. + * @returns {LuminaAudioPlayer.PlayerEngineRegistry} This registry, for chaining. + */ + register(name, factory) { + if (typeof factory !== 'function') + throw new TypeError('A player engine factory must be a function.'); + this.factories.set(name, factory); + return this; + } + + /** + * Checks whether an engine is registered under the given name. + * @param {string} name - The name of the engine. + * @returns {boolean} True when an engine is registered under that name, false otherwise. + */ + hasEngine(name) { + return this.factories.has(name); + } + + /** + * Creates an engine by name. + * @param {string} name - The name of the engine. + * @param {Object} host - The engine host provided by the player controller. + * @returns {Object|null} The created engine, or null when no engine with that name is registered. + */ + create(name, host) { + const factory = this.factories.get(name); + return factory ? factory(host) : null; + } + + /** + * Lists the names of the registered engines. + * @returns {Array} The registered engine names. + */ + getNames() { + return [...this.factories.keys()]; + } + } + + /** + * Creates a registry holding only the silent engine, the default of the core module. + * @returns {LuminaAudioPlayer.PlayerEngineRegistry} The default engine registry. + */ + LuminaAudioPlayer.createDefaultEngineRegistry = function () { + return new PlayerEngineRegistry().register(LuminaAudioPlayer.NULL_ENGINE_NAME, (host) => new NullPlayerEngine(host)); + }; + + LuminaAudioPlayer.NullPlayerEngine = NullPlayerEngine; + LuminaAudioPlayer.PlayerEngineRegistry = PlayerEngineRegistry; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js new file mode 100644 index 00000000..da237cf1 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -0,0 +1,65 @@ +/** + * Typed errors of the audio player. + * + * The player never throws raw strings: every failure is reported through the event bus as a + * {@link LuminaAudioPlayer.PlayerError}, so that a consumer can branch on a stable code instead of + * matching a message, and so that a UI can present the failure without the player leaking + * implementation details, file paths, or secrets. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Enum-like object for the stable codes carried by a {@link LuminaAudioPlayer.PlayerError}. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerErrorCode = Object.freeze({ + // The browser is missing a capability the player requires (WebCodecs, AudioDecoder or AudioContext). + CAPABILITY_MISSING: 'capability-missing', + // The play descriptor handed to the player is missing a required value, or carries an invalid one. + INVALID_DESCRIPTOR: 'invalid-descriptor', + // The requested operation is not valid in the current player state. + INVALID_STATE: 'invalid-state', + // The engine could not be created, loaded or configured. + ENGINE_LOAD_FAILED: 'engine-load-failed', + // The engine reported a failure while decoding, buffering or rendering audio. + ENGINE_ERROR: 'engine-error', + // The stored playback preferences of the user could not be read. + PREFERENCES_LOAD_FAILED: 'preferences-load-failed' + }); + + /** + * An error raised by the player, carrying a stable code and optional structured details. + */ + class PlayerError extends Error { + /** + * Creates an instance of PlayerError. + * @param {string} code - One of the {@link LuminaAudioPlayer.PlayerErrorCode} values. + * @param {string} message - A developer facing description of the failure. It must never contain a file path, a token, or any other value that must not reach a log. + * @param {Object} [details] - Optional structured details about the failure, for example the missing capabilities. + */ + constructor(code, message, details = null) { + super(message); + this.name = 'PlayerError'; + this.code = code; + this.details = details; + } + + /** + * Wraps any value into a {@link LuminaAudioPlayer.PlayerError}, so that reported failures are always typed. + * @param {*} error - The value to wrap, typically an Error, a rejection reason, or a string. + * @param {string} [fallbackCode] - The code to use when the value is not already a player error. + * @returns {LuminaAudioPlayer.PlayerError} The typed player error. + */ + static from(error, fallbackCode = LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) { + if (error instanceof PlayerError) + return error; + if (error instanceof Error) + return new PlayerError(fallbackCode, error.message, { cause: error }); + return new PlayerError(fallbackCode, String(error)); + } + } + + LuminaAudioPlayer.PlayerError = PlayerError; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js new file mode 100644 index 00000000..eb325ddf --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js @@ -0,0 +1,135 @@ +/** + * Event bus of the audio player. + * + * The player is decoupled from its consumers (the player bar, the transport UI, the queue panel, themes) through a single observable. + * Every module of the player publishes to this bus, and every consumer subscribes to it, so that no module needs a direct reference to another one. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Enum-like object for the events published by the player. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerEvent = Object.freeze({ + // The state machine moved to another state. Payload: { previousState, state }. + STATE_CHANGED: 'statechange', + // The currently playing track changed. Payload: the play descriptor. + DESCRIPTOR_CHANGED: 'descriptorchange', + // The queue changed. Payload: the ordered list of play descriptors. + QUEUE_CHANGED: 'queuechange', + // The playhead moved. Payload: { currentTime, duration }. + TIME_UPDATE: 'timeupdate', + // The duration of the current track became known or changed. Payload: { duration }. + DURATION_CHANGED: 'durationchange', + // The output volume changed. Payload: { volume, muted, effectiveVolume }. + VOLUME_CHANGED: 'volumechange', + // The mute state changed. Payload: { volume, muted, effectiveVolume }. + MUTE_CHANGED: 'mutechange', + // The downloaded fraction of the current track changed. Payload: { downloadedFraction }. + PROGRESS: 'progress', + // The current track reached its end. + ENDED: 'ended', + // A {@link LuminaAudioPlayer.PlayerError} was raised. Payload: the player error. + ERROR: 'error', + // Capability detection completed. Payload: the capability report. + CAPABILITIES_CHANGED: 'capabilitieschange', + // The stored playback preferences of the user were loaded. Payload: the preferences object. + PREFERENCES_CHANGED: 'preferenceschange', + // The player bar became visible or hidden. Payload: { visible }. The value is deliberately not 'visibilitychange', + // which is the name of the DOM page visibility event, so that the two can never be confused. + VISIBILITY_CHANGED: 'barvisibilitychange' + }); + + /** + * A minimal synchronous event bus with subscribe, unsubscribe and one-shot subscribe. + */ + class PlayerEventBus { + /** + * Creates an instance of PlayerEventBus. + */ + constructor() { + /** @type {Map>} */ + this.listeners = new Map(); + } + + /** + * Subscribes a handler to an event. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler invoked with the event payload. + * @returns {Function} A function that unsubscribes the handler. + */ + on(event, handler) { + if (typeof handler !== 'function') + throw new TypeError('The player event handler must be a function.'); + let handlers = this.listeners.get(event); + if (!handlers) { + handlers = new Set(); + this.listeners.set(event, handlers); + } + handlers.add(handler); + return () => this.off(event, handler); + } + + /** + * Subscribes a handler to an event, removing it after the first emission. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler invoked once with the event payload. + * @returns {Function} A function that unsubscribes the handler. + */ + once(event, handler) { + const unsubscribe = this.on(event, (payload) => { + unsubscribe(); + handler(payload); + }); + return unsubscribe; + } + + /** + * Unsubscribes a handler from an event. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler to remove. + */ + off(event, handler) { + const handlers = this.listeners.get(event); + if (handlers) + handlers.delete(handler); + } + + /** + * Publishes an event to every subscribed handler. + * + * A handler that throws does not prevent the remaining handlers from running: the failure is + * logged and swallowed, because a misbehaving consumer must never break the player. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {*} [payload] - The payload passed to each handler. + */ + emit(event, payload) { + const handlers = this.listeners.get(event); + if (!handlers || handlers.size === 0) + return; + // Copy the set, so that a handler that subscribes or unsubscribes during the emission does not affect this run. + for (const handler of [...handlers]) { + try { + handler(payload); + } catch (error) { + console.error(`Audio player: a handler of '${event}' threw.`, error); + } + } + } + + /** + * Removes every handler of an event, or of every event when none is provided. + * @param {string} [event] - One of the {@link LuminaAudioPlayer.PlayerEvent} values, or nothing to clear all. + */ + clear(event) { + if (event === undefined) + this.listeners.clear(); + else + this.listeners.delete(event); + } + } + + LuminaAudioPlayer.PlayerEventBus = PlayerEventBus; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js new file mode 100644 index 00000000..fdecfbf3 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -0,0 +1,1313 @@ +/** + * The audio player of Lumina: state machine, play descriptor, lifecycle, bar and the public control API. + * + * The player is a singleton created once, in the application layout, outside the content area that the + * in-place navigation manager swaps. Because it is never torn down by a page swap, playback and its + * UI survive navigation. It produces no audio itself: audio is delegated to a swappable engine that + * fulfills the interface documented in audio-player-engine.js. This module only owns the state machine, the + * event bus, capability detection, the play descriptor, the bar and the public API; the download, + * decode and render pipeline is plugged in as an engine by the later stages. + * + * Public control API (window.LuminaAudioPlayer.instance) + * ---------------------------------------- + * Methods: + * - playAsync(descriptor): starts playback of a track. The descriptor is documented by createPlayDescriptor. + * When the descriptor carries a queue, that queue becomes the player queue. + * - pauseAsync(): suspends playback, keeping the position. + * - resumeAsync(): resumes playback from the current position. + * - toggleAsync(): pauses when playing, resumes otherwise. + * - stopAsync(): stops playback. While the bar is condensed, it also hides the bar; while the bar is + * expanded, it stays on screen. + * - seekAsync(seconds): moves the playhead to an absolute position, in seconds. + * - setVolumeAsync(volume): sets the output volume, between 0 and 1. + * - setMutedAsync(muted): sets the mute state. Volume and mute are independent: unmuting restores the volume. + * - toggleMuteAsync(): flips the mute state. + * - toggleFullHeight(): expands or collapses the bar. + * - toggleVisibility(): shows or hides the bar. + * - on(event, handler): subscribes to a player event, returns an unsubscribe function. + * - once(event, handler), off(event, handler): one shot subscribe, and unsubscribe. + * - getState(), getDescriptor(), getQueue(), getCurrentTime(), getDuration(), + * getVolume(), isMuted(), getPreferences(), getCapabilities(), getLastError(). + * - destroyAsync(): releases every resource of the player. It is only used for an explicit teardown, never + * by a navigation, because the navigation manager never recreates the player. + * - registerEngine(name, factory): registers an engine factory on this player, by name. + * - useEngine(name): selects a registered engine; it takes effect on the next load. + * - getEngineName(): the name of the engine the player runs with. + * Properties: + * - capabilitiesReady: a Promise resolving to the capability report. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Enum-like object for the states of the player state machine. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerState = Object.freeze({ + // Nothing is loaded. This is also the state a stop returns to. + IDLE: 'idle', + // A track is being prepared. The download engine opens its stream here. + LOADING: 'loading', + // A track is prepared and can start producing audio. + READY: 'ready', + // Audio is being produced. + PLAYING: 'playing', + // Playback is suspended, and the position is kept. + PAUSED: 'paused', + // The current track reached its end. + ENDED: 'ended', + // A failure moved the player out of a normal state. + ERROR: 'error' + }); + + /** + * The states each state may move to. A transition outside this map is applied anyway, but it is + * logged, because it signals a bug in the caller rather than a recoverable condition. + * @readonly + * @type {Object>} + */ + const STATE_TRANSITIONS = Object.freeze({ + idle: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.ERROR], + loading: [LuminaAudioPlayer.PlayerState.READY, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + ready: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.PLAYING, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + playing: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.PAUSED, LuminaAudioPlayer.PlayerState.ENDED, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + paused: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.PLAYING, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + ended: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.PLAYING, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + error: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR] + }); + + /** + * The result of a background request whose answer was a redirect, which means the session expired and the page is + * being sent to the sign in page. It is distinct from a missing value, which is a failure, so that a caller does not + * report an error for a redirect it is already handling. + * @readonly + * @type {Object} + */ + const REDIRECTED = Object.freeze({ redirected: true }); + + /** + * The attribute that marks an element as a play trigger the player handles by event delegation. + * @readonly + * @type {string} + */ + LuminaAudioPlayer.PLAY_DESCRIPTOR_ATTRIBUTE = 'data-audio-player-play'; + + /** + * Maps each play descriptor field to the data attribute the pages set on a play trigger, so the + * pages and the player share a single documented set of names. + * @readonly + * @type {Object} + */ + LuminaAudioPlayer.PLAY_DESCRIPTOR_DATA_KEYS = Object.freeze({ + trackId: 'trackId', + albumId: 'albumId', + artistId: 'artistId', + libraryId: 'libraryId', + title: 'title', + durationInSeconds: 'duration', + coverArtPath: 'coverArtPath', + coverArtUrl: 'coverArtUrl' + }); + + /** + * The marker shown in place of a duration that is not known, so that an absent duration reads as unknown + * instead of as a real zero. + * @readonly + * @type {string} + */ + const UNKNOWN_TIME = '--:--'; + + /** + * Formats a known, positive time in seconds as m:ss, or h:mm:ss when it is an hour or longer. + * @param {number} totalSeconds - The time to format, in seconds. + * @returns {string} The formatted time. + */ + function formatClock(totalSeconds) { + const seconds = Math.floor(totalSeconds % 60); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const hours = Math.floor(totalSeconds / 3600); + const paddedSeconds = String(seconds).padStart(2, '0'); + if (hours > 0) + return `${hours}:${String(minutes).padStart(2, '0')}:${paddedSeconds}`; + return `${minutes}:${paddedSeconds}`; + } + + /** + * Formats a playhead in seconds as m:ss, or h:mm:ss when it is an hour or longer. A playhead is always known, + * so a missing or negative value is the start of the track, and it is formatted as 0:00. + * @param {number} totalSeconds - The playhead to format, in seconds. + * @returns {string} The formatted playhead. + */ + function formatTime(totalSeconds) { + const value = Number(totalSeconds); + return Number.isFinite(value) && value > 0 ? formatClock(value) : '0:00'; + } + + /** + * Formats a duration in seconds as m:ss, or h:mm:ss when it is an hour or longer, and shows the unknown time + * marker while the duration is not known. + * @param {number} totalSeconds - The duration to format, in seconds. + * @returns {string} The formatted duration, or --:-- when the duration is not known. + */ + function formatDuration(totalSeconds) { + const value = Number(totalSeconds); + return Number.isFinite(value) && value > 0 ? formatClock(value) : UNKNOWN_TIME; + } + + /** + * Clamps a number into an inclusive range. + * @param {number} value - The value to clamp. + * @param {number} minimum - The inclusive lower bound. + * @param {number} maximum - The inclusive upper bound. + * @returns {number} The clamped value. + */ + function clamp(value, minimum, maximum) { + if (!Number.isFinite(value)) + return minimum; + return Math.min(maximum, Math.max(minimum, value)); + } + + /** + * Resolves the cover art of a track against the base URL of the API server, using the same artwork path the album page uses. + * + * Artwork is served by the API server, so a value is resolved against the API server base (or, when no base is + * configured, against the origin of the page) and is accepted only when it ends up on that same origin. A value on + * any other origin, a protocol relative value, any scheme other than http or https, and any value carrying a control + * character are rejected. This keeps a crafted cover art value from making the page fetch an image from a third + * party, which would leak the location of the user, and, by association, what they listen to. + * @param {string} value - The relative artwork path, or an absolute cover art URL on the API server. + * @returns {string} The normalized cover art URL, or an empty string when the value is missing or rejected. + */ + function resolveCoverArtUrl(value) { + if (!value) + return ''; + const raw = String(value).trim(); + if (raw === '') + return ''; + // A control character is rejected, a protocol relative value is rejected, and any scheme that is not http or + // https is rejected: the URL parser strips leading control characters, so a value such as "\0//host" would + // otherwise be treated as a different reference than the checks above see. + if (/[\u0000-\u001f\u007f]/.test(raw) || raw.startsWith('//') || (/^[a-z][a-z0-9+.-]*:/i.test(raw) && !/^https?:/i.test(raw))) + return ''; + const configuredBase = (window.globalConfiguration && window.globalConfiguration.serverBasePath) || ''; + const base = configuredBase || (window.location && window.location.origin) || ''; + // Without a base there is nothing to check the value against, so it is rejected rather than trusted. + if (!base) + return ''; + try { + const resolved = new URL(raw, base); + if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') + return ''; + // The artwork of a library must stay on the server that serves it, so the resolved origin is compared to the + // origin of the base the value was resolved against, and anything else is dropped instead of being loaded. + const allowedOrigin = new URL(base).origin; + return resolved.origin === allowedOrigin ? resolved.href : ''; + } catch (error) { + console.debug('Audio player: a cover art value could not be resolved.', error); + return ''; + } + } + + /** + * Normalizes a play descriptor, a plain object that describes what to play. + * + * Field rules: + * - libraryId (string, required): the Id of the media library the context belongs to. + * - trackId (string, required for a single track): the Id of the track. + * - albumId (string, optional): the Id of the album. A descriptor without a track Id describes an album play context. + * - artistId (string, optional): the Id of the artist. A descriptor without a track or album Id describes an artist play context. + * - title (string, optional): the display title of the track or context. + * - durationInSeconds (number, optional): the duration of the track, in seconds. + * - coverArtPath (string, optional): the relative artwork path of the album, resolved against the server base path. + * - coverArtUrl (string, optional): an absolute cover art URL, or a relative artwork path. + * - queue (Array, optional): the ordered track descriptors of the play context, used to render the expanded bar. + * @param {Object} input - The descriptor to normalize. + * @returns {Object|null} The normalized descriptor, or null when it identifies no library, or no track, album or artist. + */ + function createPlayDescriptor(input) { + if (!input || typeof input !== 'object') + return null; + const trackId = toIdString(input.trackId); + const albumId = toIdString(input.albumId); + const artistId = toIdString(input.artistId); + const libraryId = toIdString(input.libraryId); + // A track descriptor carries its track Id, while an album or artist context descriptor carries only the Id it is built from. + if (!libraryId || (!trackId && !albumId && !artistId)) + return null; + const coverArtSource = input.coverArtUrl || input.coverArtPath || ''; + const descriptor = { + trackId, + libraryId, + albumId, + artistId, + title: typeof input.title === 'string' ? input.title : '', + durationInSeconds: Number.isFinite(Number(input.durationInSeconds)) ? Number(input.durationInSeconds) : 0, + coverArtPath: typeof input.coverArtPath === 'string' ? input.coverArtPath : '', + coverArtUrl: resolveCoverArtUrl(coverArtSource) + }; + if (Array.isArray(input.queue)) { + const queue = input.queue.map(item => createPlayDescriptor(item)).filter(item => item !== null); + descriptor.queue = Object.freeze(queue); + } + return Object.freeze(descriptor); + } + + /** + * Coerces an Id into a non empty string, or an empty string when it carries no value. + * @param {*} value - The Id to coerce. + * @returns {string} The Id as a string, or an empty string. + */ + function toIdString(value) { + if (value === null || value === undefined) + return ''; + const text = String(value).trim(); + return text === '' ? '' : text; + } + + /** + * Reads a play descriptor from the data attributes of a play trigger element, per + * {@link LuminaAudioPlayer.PLAY_DESCRIPTOR_DATA_KEYS}. + * @param {Element} element - The element carrying the descriptor attributes. + * @returns {Object|null} The normalized descriptor, or null when the element does not describe a valid track. + */ + function readPlayDescriptorFromElement(element) { + if (!element || !element.dataset) + return null; + const keys = LuminaAudioPlayer.PLAY_DESCRIPTOR_DATA_KEYS; + return createPlayDescriptor({ + trackId: element.dataset[keys.trackId], + albumId: element.dataset[keys.albumId], + artistId: element.dataset[keys.artistId], + libraryId: element.dataset[keys.libraryId], + title: element.dataset[keys.title], + durationInSeconds: element.dataset[keys.durationInSeconds], + coverArtPath: element.dataset[keys.coverArtPath], + coverArtUrl: element.dataset[keys.coverArtUrl] + }); + } + + /** + * The audio player. See the module documentation for the public control API. + */ + class AudioPlayer { + /** + * Creates an instance of AudioPlayer. + * @param {Object} [options] - The player options. + * @param {HTMLElement} [options.container] - The player bar element. Defaults to the first element with the audio-player-container class. + * @param {HTMLElement} [options.main] - The main content element, whose class tracks the bar visibility. Defaults to the first main element. + * @param {LuminaAudioPlayer.PlayerEventBus} [options.events] - The event bus to publish to. A new one is created when omitted. + * @param {LuminaAudioPlayer.PlayerCapabilities} [options.capabilities] - The capability detector. A new one is created when omitted. + * @param {LuminaAudioPlayer.PlayerEngineRegistry} [options.engineRegistry] - The engine registry. The default registry is created when omitted. + * @param {string} [options.engineName] - The name of the engine to run. Defaults to the silent engine. + * @param {Object} [options.configuration] - The endpoints configuration. Defaults to window.audioPlayerConfiguration. + */ + constructor(options = {}) { + this.options = options; + this.events = options.events || new LuminaAudioPlayer.PlayerEventBus(); + this.capabilities = options.capabilities || new LuminaAudioPlayer.PlayerCapabilities(); + this.engineRegistry = options.engineRegistry || LuminaAudioPlayer.createDefaultEngineRegistry(); + this.engineName = options.engineName || LuminaAudioPlayer.NULL_ENGINE_NAME; + + this.state = LuminaAudioPlayer.PlayerState.IDLE; + this.descriptor = null; + this.queue = []; + this.currentIndex = 0; + this.currentTime = 0; + this.duration = 0; + this.downloadedFraction = 0; + this.volume = 1; + this.muted = false; + this.lastError = null; + this.preferences = { + shouldKeepDownloadingWhilePaused: false, + shouldAutoplay: false, + isGaplessPlaybackEnabled: false, + replayGainMode: 'Off', + streamingQuality: 'Auto' + }; + this.capabilityReport = null; + this.capabilitiesReady = null; + this.engine = null; + this.available = false; + this.initialized = false; + this.container = null; + this.main = null; + this.dom = {}; + this.descriptorClickHandler = null; + this.controlHandlers = []; + this.progressRenderScheduled = false; + } + + /** + * Binds the player to the bar in the layout, prepares the hidden state, and starts capability + * detection and the load of the stored playback preferences. + * + * The method is idempotent: a second call returns immediately. When the layout does not render + * a bar (an unauthenticated visitor), the player marks itself unavailable and every control + * method becomes a no-op. + * @returns {LuminaAudioPlayer.AudioPlayer} This player, for chaining. + */ + initialize() { + if (this.initialized) + return this; + this.initialized = true; + + this.container = this.options.container || document.querySelector('.audio-player-container'); + this.main = this.options.main || document.querySelector('main'); + if (!this.container) { + this.available = false; + return this; + } + this.available = true; + + this.collectDomReferences(); + this.bindPlaybackControls(); + this.bindDescriptorDelegation(); + // The bar is hidden until the user starts playback, so a refresh never flashes an empty player. + this.suppressInitialTransitions(); + this.applyHiddenState(); + this.releaseInitialHiddenState(); + + this.capabilitiesReady = this.detectCapabilitiesAsync(); + // The stored preferences are read in the background; a slow or failing request never blocks the bar. + this.loadPreferencesAsync(); + return this; + } + + /** + * Collects the references to the bar elements the player drives, once, so that a navigation + * that swaps the content area never invalidates them. + */ + collectDomReferences() { + const query = (selector) => this.container.querySelector(selector); + this.dom.trackName = query('[data-audio-player-track-name]'); + this.dom.coverThumbnail = query('[data-audio-player-cover-thumbnail]'); + this.dom.coverImage = query('[data-audio-player-cover-image]'); + this.dom.currentTime = query('[data-audio-player-current-time]'); + this.dom.totalTime = query('[data-audio-player-total-time]'); + this.dom.progress = query('[data-audio-player-progress]'); + this.dom.progressPlayed = query('[data-audio-player-progress-played]'); + this.dom.progressDownloaded = query('[data-audio-player-progress-downloaded]'); + this.dom.playPause = query('[data-audio-player-play-pause]'); + this.dom.queue = query('[data-audio-player-queue]'); + } + + /** + * Binds the transport controls the player owns. The full height and close affordances are bound + * by the global site script, which delegates them to this player, so that a single click never + * toggles them twice. + */ + bindPlaybackControls() { + if (this.dom.playPause) + this.addControlHandler(this.dom.playPause, 'click', () => this.toggleAsync()); + if (this.dom.progress) + this.addControlHandler(this.dom.progress, 'click', (event) => this.handleProgressClick(event)); + } + + /** + * Adds a click handler to a bar element, and remembers it so that an explicit teardown can remove it. + * @param {HTMLElement} element - The element to bind. + * @param {string} event - The DOM event to listen to. + * @param {Function} handler - The handler to invoke. + */ + addControlHandler(element, event, handler) { + element.addEventListener(event, handler); + this.controlHandlers.push({ element, event, handler }); + } + + /** + * Binds the global click delegation that turns an element carrying the play trigger attribute + * into a play request, so that pages never need a direct reference to the player. + */ + bindDescriptorDelegation() { + this.descriptorClickHandler = (event) => { + if (!(event.target instanceof Element)) + return; + const trigger = event.target.closest(`[${LuminaAudioPlayer.PLAY_DESCRIPTOR_ATTRIBUTE}]`); + if (!trigger) + return; + event.preventDefault(); + const descriptor = readPlayDescriptorFromElement(trigger); + this.playAsync(descriptor).catch((error) => this.raiseError(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR)); + }; + document.addEventListener('click', this.descriptorClickHandler); + } + + /** + * Starts playback of a track, and shows the bar. + * @param {Object} descriptorInput - The play descriptor to play, per {@link LuminaAudioPlayer.createPlayDescriptor}. + * @returns {Promise} True when playback started, false when the request was rejected. + */ + async playAsync(descriptorInput) { + // The player is only available when the layout rendered the bar, so a caller on a page without one is ignored instead of failing. + if (!this.available) + return false; + const descriptor = createPlayDescriptor(descriptorInput); + if (!descriptor) { + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, 'The play descriptor identifies no library, or no track, album or artist.')); + return false; + } + // Capability detection runs in the background while the page loads, so the first play waits for its answer instead + // of starting a track the browser may not be able to decode. + const report = await this.capabilitiesReady; + if (report && !report.supported) { + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'The browser is missing a capability the player requires.', + { missing: report.missing })); + return false; + } + + // A new descriptor starts a new timeline, so the playhead and the progress of the previous track are dropped. + this.descriptor = descriptor; + this.duration = descriptor.durationInSeconds; + this.currentTime = 0; + this.downloadedFraction = 0; + // An album or artist descriptor carries no track id of its own, so the queue starts at its first item in that case. + this.queue = descriptor.queue && descriptor.queue.length > 0 ? [...descriptor.queue] : [descriptor]; + this.currentIndex = Math.max(0, this.queue.findIndex(item => item.trackId === descriptor.trackId)); + + // The bar is shown and the state moves to loading before the engine is touched, so a slow engine still gives the user + // immediate feedback that the request was accepted. + this.renderDescriptor(); + this.renderProgress(); + this.renderQueue(); + this.showBar(); + this.setState(LuminaAudioPlayer.PlayerState.LOADING); + this.events.emit(LuminaAudioPlayer.PlayerEvent.DESCRIPTOR_CHANGED, descriptor); + this.events.emit(LuminaAudioPlayer.PlayerEvent.QUEUE_CHANGED, this.queue); + + try { + // The state follows the engine step by step, so a consumer can tell preparation apart from actual playback. + const engine = await this.ensureEngineAsync(); + await engine.loadAsync(descriptor); + this.setState(LuminaAudioPlayer.PlayerState.READY); + await engine.playAsync(); + this.setState(LuminaAudioPlayer.PlayerState.PLAYING); + this.renderTransportState(); + } catch (error) { + // A failure before playback starts is a load failure; later failures are reported by the engine through its host. + this.fail(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED); + return false; + } + return true; + } + + /** + * Suspends playback, keeping the current position. + * @returns {Promise} A promise that completes when the engine paused. + */ + async pauseAsync() { + // Pausing anything that is not playing is a no-op, so the pause and close controls stay harmless when clicked twice. + if (this.state !== LuminaAudioPlayer.PlayerState.PLAYING) + return; + if (this.engine) + await this.engine.pauseAsync(); + this.setState(LuminaAudioPlayer.PlayerState.PAUSED); + this.renderTransportState(); + } + + /** + * Resumes playback from the current position. + * @returns {Promise} A promise that completes when the engine resumed. + */ + async resumeAsync() { + // A ready track has not started yet, and a paused one keeps its position, so both can resume. + if (this.state !== LuminaAudioPlayer.PlayerState.PAUSED && this.state !== LuminaAudioPlayer.PlayerState.READY) + return; + // Without an engine there is nothing to resume; the next play builds one and applies the stored volume. + if (!this.engine) + return; + await this.engine.playAsync(); + this.setState(LuminaAudioPlayer.PlayerState.PLAYING); + this.renderTransportState(); + } + + /** + * Pauses when playing, resumes when paused or ready, and replays the current track when idle. + * @returns {Promise} A promise that completes when the toggle was applied. + */ + async toggleAsync() { + if (this.state === LuminaAudioPlayer.PlayerState.PLAYING) + await this.pauseAsync(); + else if (this.state === LuminaAudioPlayer.PlayerState.PAUSED || this.state === LuminaAudioPlayer.PlayerState.READY) + await this.resumeAsync(); + else if (this.descriptor) + await this.playAsync(this.descriptor); + } + + /** + * Stops playback. While the bar is condensed, it slides out of view; while the bar is expanded, + * it stays on screen with the current track, and only playback stops. + * @returns {Promise} A promise that completes when playback stopped. + */ + async stopAsync() { + if (this.engine) { + try { + // The engine is paused rather than destroyed, because it is reused for the next track and rebuilding it would + // drop resources such as the audio context that a user gesture is needed to resume. + await this.engine.pauseAsync(); + } catch (error) { + // A failure while stopping must not prevent the player from returning to idle. + console.error('Audio player: the engine failed while stopping.', error); + } + } + // The playhead and the progress are reset while the descriptor is kept, so the bar can still show what was stopped. + this.currentTime = 0; + this.downloadedFraction = 0; + this.renderProgress(); + this.setState(LuminaAudioPlayer.PlayerState.IDLE); + this.renderTransportState(); + // A condensed bar slides out when playback stops, while an expanded one stays so the user keeps the track and its queue in view. + if (!this.isExpanded()) + this.hideBar(); + } + + /** + * Moves the playhead to an absolute position. + * @param {number} seconds - The target position, in seconds. + * @returns {Promise} A promise that completes when the seek was requested. + */ + async seekAsync(seconds) { + // Without a descriptor there is no timeline to seek in. + if (!this.descriptor) + return; + // A known duration bounds the target, while without one the position is only kept non negative, so a seek is never + // silently snapped to zero just because the duration has not been reported yet. + const request = Number(seconds); + const position = this.duration > 0 + ? clamp(request, 0, this.duration) + : Math.max(0, Number.isFinite(request) ? request : 0); + this.currentTime = position; + if (this.engine) { + try { + await this.engine.seekAsync(position); + } catch (error) { + this.raiseError(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + } + } + // The engine reports the new playhead itself, so the render is coalesced with that report instead of racing it. + this.scheduleProgressRender(); + } + + /** + * Sets the output volume. Mute is independent of the volume: a muted player remembers the volume. + * @param {number} volume - The output volume, between 0 and 1. + * @returns {Promise} The applied volume. + */ + async setVolumeAsync(volume) { + const value = clamp(Number(volume), 0, 1); + this.volume = value; + await this.applyVolumeAsync(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.VOLUME_CHANGED, this.buildVolumePayload()); + return this.volume; + } + + /** + * Sets the mute state. + * @param {boolean} muted - True to mute the output, false to unmute it. + * @returns {Promise} A promise that completes when the mute was applied. + */ + async setMutedAsync(muted) { + this.muted = muted === true; + await this.applyVolumeAsync(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.MUTE_CHANGED, this.buildVolumePayload()); + } + + /** + * Flips the mute state. + * @returns {Promise} A promise that completes when the mute was applied. + */ + async toggleMuteAsync() { + await this.setMutedAsync(!this.muted); + } + + /** + * Expands the bar into its full height form, or collapses it back to the condensed bar. + * @returns {boolean} True when the bar is expanded after the toggle. + */ + toggleFullHeight() { + if (!this.container) + return false; + const expanded = this.container.classList.toggle('full-height'); + if (this.main) + this.main.classList.toggle('audio-player-full-height', expanded); + return expanded; + } + + /** + * Shows the bar when it is hidden, and hides it when it is visible. + * @returns {boolean} True when the bar is visible after the toggle. + */ + toggleVisibility() { + if (!this.container) + return false; + if (this.container.classList.contains('not-shown')) + this.showBar(); + else + this.hideBar(); + return !this.container.classList.contains('not-shown'); + } + + /** + * Shows the bar and reflows the content area around it. A bar that is already shown is left untouched, and no + * visibility event is emitted, so a consumer is never asked to animate a change that did not happen. + */ + showBar() { + if (!this.container) + return; + const wasHidden = this.container.classList.contains('not-shown'); + this.container.removeAttribute('hidden'); + this.container.classList.remove('not-shown'); + if (this.main) + this.main.classList.remove('audio-player-not-shown'); + if (wasHidden) + this.events.emit(LuminaAudioPlayer.PlayerEvent.VISIBILITY_CHANGED, { visible: true }); + } + + /** + * Hides the bar and reflows the content area over it. A bar that is already hidden is left untouched, and no + * visibility event is emitted, so a consumer is never asked to animate a change that did not happen. + */ + hideBar() { + if (!this.container) + return; + if (this.container.classList.contains('not-shown')) + return; + this.container.classList.add('not-shown'); + if (this.main) + this.main.classList.add('audio-player-not-shown'); + this.events.emit(LuminaAudioPlayer.PlayerEvent.VISIBILITY_CHANGED, { visible: false }); + } + + /** + * Checks whether the bar is in its expanded form. + * @returns {boolean} True when the bar is expanded. + */ + isExpanded() { + return this.container !== null && this.container.classList.contains('full-height'); + } + + /** + * Gets the current state of the state machine. + * @returns {string} One of the {@link LuminaAudioPlayer.PlayerState} values. + */ + getState() { + return this.state; + } + + /** + * Gets the descriptor of the track the player last started. + * @returns {Object|null} The play descriptor, or null. + */ + getDescriptor() { + return this.descriptor; + } + + /** + * Gets the ordered queue of the current play context. + * @returns {Array} The ordered play descriptors. + */ + getQueue() { + return [...this.queue]; + } + + /** + * Gets the playhead of the current track. + * @returns {number} The playhead, in seconds. + */ + getCurrentTime() { + return this.currentTime; + } + + /** + * Gets the known duration of the current track. + * @returns {number} The duration, in seconds. + */ + getDuration() { + return this.duration; + } + + /** + * Gets the output volume, which is independent of the mute state. + * @returns {number} The volume, between 0 and 1. + */ + getVolume() { + return this.volume; + } + + /** + * Gets the mute state. + * @returns {boolean} True when the output is muted. + */ + isMuted() { + return this.muted; + } + + /** + * Gets the stored playback preferences loaded for the user. + * @returns {Object} The preferences. + */ + getPreferences() { + return this.preferences; + } + + /** + * Gets the last capability report, or null when detection has not completed yet. + * @returns {Object|null} The capability report. + */ + getCapabilities() { + return this.capabilityReport; + } + + /** + * Gets the last typed error the player raised. + * @returns {LuminaAudioPlayer.PlayerError|null} The last error, or null. + */ + getLastError() { + return this.lastError; + } + + /** + * Subscribes to a player event. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler invoked with the event payload. + * @returns {Function} A function that unsubscribes the handler. + */ + on(event, handler) { + return this.events.on(event, handler); + } + + /** + * Subscribes to a player event once. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler invoked once with the event payload. + * @returns {Function} A function that unsubscribes the handler. + */ + once(event, handler) { + return this.events.once(event, handler); + } + + /** + * Unsubscribes a handler from a player event. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler to remove. + */ + off(event, handler) { + this.events.off(event, handler); + } + + /** + * Releases every resource the player holds. It is intended for an explicit teardown only: the + * in-place navigation manager never destroys the player, so that playback survives navigation. + * @returns {Promise} A promise that completes when the engine was destroyed. + */ + async destroyAsync() { + if (this.descriptorClickHandler) { + document.removeEventListener('click', this.descriptorClickHandler); + this.descriptorClickHandler = null; + } + for (const control of this.controlHandlers) + control.element.removeEventListener(control.event, control.handler); + this.controlHandlers = []; + if (this.engine) { + try { + await this.engine.destroyAsync(); + } catch (error) { + console.error('Audio player: the engine failed to destroy itself.', error); + } + this.engine = null; + } + this.events.clear(); + this.setState(LuminaAudioPlayer.PlayerState.IDLE); + // The singleton is no longer usable, so it is cleared, and a later createDefaultPlayer builds a fresh one. + if (LuminaAudioPlayer.instance === this) + LuminaAudioPlayer.instance = null; + } + + //+======================================================================================+ + //| Internal helpers | + //+======================================================================================+ + + /** + * Moves the state machine to another state and publishes the change. + * @param {string} nextState - One of the {@link LuminaAudioPlayer.PlayerState} values. + */ + setState(nextState) { + if (this.state === nextState) + return; + const previousState = this.state; + const allowed = STATE_TRANSITIONS[previousState] || []; + if (!allowed.includes(nextState)) + console.warn(`Audio player: the transition '${previousState}' -> '${nextState}' is not part of the state machine.`); + this.state = nextState; + this.events.emit(LuminaAudioPlayer.PlayerEvent.STATE_CHANGED, { previousState, state: nextState }); + } + + /** + * Raises a typed error without moving the state machine. + * @param {*} error - The error to raise, wrapped into a {@link LuminaAudioPlayer.PlayerError}. + * @param {string} [code] - The code to use when the error is not already typed. + * @returns {LuminaAudioPlayer.PlayerError} The raised typed error. + */ + raiseError(error, code = LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) { + const typed = LuminaAudioPlayer.PlayerError.from(error, code); + this.lastError = typed; + console.error(`Audio player: ${typed.code}.`, typed.message); + this.events.emit(LuminaAudioPlayer.PlayerEvent.ERROR, typed); + return typed; + } + + /** + * Raises a typed error and moves the state machine to the error state. + * @param {*} error - The error to raise. + * @param {string} [code] - The code to use when the error is not already typed. + * @returns {LuminaAudioPlayer.PlayerError} The raised typed error. + */ + fail(error, code = LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) { + const typed = this.raiseError(error, code); + this.setState(LuminaAudioPlayer.PlayerState.ERROR); + return typed; + } + + /** + * Registers an engine factory on this player, by name. + * + * This is the documented seam through which the later stages plug the real download, decode and render + * engine into the player, without reaching into its internals. + * @param {string} name - The name the engine is selected by, later passed to {@link LuminaAudioPlayer.AudioPlayer#useEngine}. + * @param {Function} factory - A factory that receives the engine host and returns an engine. + * @returns {LuminaAudioPlayer.AudioPlayer} This player, for chaining. + */ + registerEngine(name, factory) { + this.engineRegistry.register(name, factory); + return this; + } + + /** + * Selects the registered engine the player runs with. The selection takes effect on the next load. + * + * When an engine instance is already created, it is destroyed and dropped, so that the next load builds the + * newly selected engine. Selecting an engine while a track plays therefore stops that track and returns the + * player to its idle state, so it is meant to be called during setup, before playback starts. + * @param {string} name - The name of a registered engine. + * @returns {LuminaAudioPlayer.AudioPlayer} This player, for chaining. + * @throws {LuminaAudioPlayer.PlayerError} When no engine with that name is registered. + */ + useEngine(name) { + if (name === this.engineName) + return this; + if (!this.engineRegistry.hasEngine(name)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, `No player engine named '${name}' is registered.`); + this.engineName = name; + if (this.engine) { + const previous = this.engine; + this.engine = null; + // The engine that was playing is gone, so the player returns to idle instead of claiming it is still playing. + if (this.state !== LuminaAudioPlayer.PlayerState.IDLE) { + this.setState(LuminaAudioPlayer.PlayerState.IDLE); + this.renderTransportState(); + } + try { + Promise.resolve(previous.destroyAsync()).catch((error) => console.error('Audio player: the previous engine failed to destroy itself.', error)); + } catch (error) { + console.error('Audio player: the previous engine failed to destroy itself.', error); + } + } + return this; + } + + /** + * Gets the name of the engine the player runs with. + * @returns {string} The selected engine name. + */ + getEngineName() { + return this.engineName; + } + + /** + * Ensures an engine exists, creating it from the registry on first use. + * @returns {Promise} The engine. + */ + async ensureEngineAsync() { + if (this.engine) + return this.engine; + this.engine = this.engineRegistry.create(this.engineName, this.createEngineHost()); + if (!this.engine) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, `No player engine named '${this.engineName}' is registered.`); + // The stored volume is applied at creation, so the very first track starts at the volume the user last chose. + await this.applyVolumeAsync(); + return this.engine; + } + + /** + * Builds the host object through which an engine reports back to the player. + * @returns {Object} The engine host. + */ + createEngineHost() { + return { + events: this.events, + reportTime: (currentTime, duration) => this.handleEngineTime(currentTime, duration), + reportDuration: (duration) => this.handleEngineDuration(duration), + reportProgress: (fraction) => this.handleEngineProgress(fraction), + reportEnded: () => this.handleEngineEnded(), + reportError: (error) => this.fail(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) + }; + } + + /** + * Handles a playhead report from the engine. + * + * The report only updates the player state and schedules the render, so that a burst of reports coalesces into + * a single set of DOM writes and a single event emission per animation frame. + * @param {number} currentTime - The current playhead, in seconds. + * @param {number} duration - The known duration, in seconds. + */ + handleEngineTime(currentTime, duration) { + this.handleEngineDuration(duration); + const position = Number(currentTime); + this.currentTime = Number.isFinite(position) && position > 0 ? position : 0; + this.scheduleProgressRender(); + } + + /** + * Handles a duration report from the engine. + * @param {number} duration - The known duration, in seconds. + */ + handleEngineDuration(duration) { + const value = Number(duration); + if (!Number.isFinite(value) || value <= 0 || value === this.duration) + return; + this.duration = value; + // The total time is written by the coalesced progress render, so it is not written twice for one report. + this.scheduleProgressRender(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.DURATION_CHANGED, { duration: this.duration }); + } + + /** + * Handles a download progress report from the engine. + * @param {number} fraction - The downloaded fraction, between 0 and 1. + */ + handleEngineProgress(fraction) { + const value = clamp(Number(fraction), 0, 1); + this.downloadedFraction = value; + this.scheduleProgressRender(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.PROGRESS, { downloadedFraction: value }); + } + + /** + * Coalesces the progress bar DOM writes and the playhead event into a single animation frame, so that a + * high frequency stream of engine reports does not turn into a high frequency stream of DOM writes. + */ + scheduleProgressRender() { + if (this.progressRenderScheduled) + return; + this.progressRenderScheduled = true; + const render = () => { + this.progressRenderScheduled = false; + this.renderProgress(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.TIME_UPDATE, { currentTime: this.currentTime, duration: this.duration }); + }; + if (typeof requestAnimationFrame === 'function') + requestAnimationFrame(render); + else + render(); + } + + /** + * Handles the end of the current track reported by the engine. + */ + handleEngineEnded() { + this.setState(LuminaAudioPlayer.PlayerState.ENDED); + this.renderTransportState(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.ENDED); + } + + /** + * Detects the browser capabilities and publishes a typed error when one is missing. + * @returns {Promise} The capability report. + */ + async detectCapabilitiesAsync() { + const report = await this.capabilities.detectAsync(); + this.capabilityReport = report; + this.events.emit(LuminaAudioPlayer.PlayerEvent.CAPABILITIES_CHANGED, report); + if (!report.supported) { + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'The browser is missing a capability the player requires.', + { missing: report.missing })); + } + return report; + } + + /** + * Reads the stored playback preferences of the user: the behavior preferences from the user + * settings endpoint, and the last volume and mute state from the playback state endpoint. + * @returns {Promise} A promise that completes when the preferences were read. + */ + async loadPreferencesAsync() { + const configuration = this.getConfiguration(); + const [settings, playbackState] = await Promise.all([ + this.fetchJsonAsync(configuration.getUserSettingsUrl), + this.fetchJsonAsync(configuration.getPlaybackStateUrl) + ]); + // A redirect means the session expired and the page is already navigating to the sign in page, so nothing is + // reported and nothing is applied, instead of treating an expected outcome as a failure. + if (settings === REDIRECTED || playbackState === REDIRECTED) + return; + if (settings === undefined || playbackState === undefined) + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.PREFERENCES_LOAD_FAILED, 'The stored playback preferences of the user could not be read.')); + if (settings) { + this.preferences = { + shouldKeepDownloadingWhilePaused: settings.shouldKeepDownloadingWhilePaused === true, + shouldAutoplay: settings.shouldAutoplay === true, + isGaplessPlaybackEnabled: settings.isGaplessPlaybackEnabled === true, + replayGainMode: settings.replayGainMode || 'Off', + streamingQuality: settings.streamingQuality || 'Auto' + }; + this.events.emit(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, this.preferences); + } + if (playbackState) { + if (Number.isFinite(Number(playbackState.volume))) + await this.setVolumeAsync(clamp(Number(playbackState.volume), 0, 1)); + if (typeof playbackState.isMuted === 'boolean') + await this.setMutedAsync(playbackState.isMuted); + } + } + + /** + * Gets the endpoints configuration of the player. + * @returns {Object} The endpoints configuration. + */ + getConfiguration() { + return this.options.configuration || window.audioPlayerConfiguration || {}; + } + + /** + * Reads a JSON payload from a web endpoint, without surfacing a notification on failure, because + * the request is a background one that must never disturb the page. + * + * An expired session is answered by the server with a redirect to the login page, so the redirect is followed + * here, exactly like the application API helper does it, instead of being mistaken for a failed request. + * @param {string} url - The endpoint URL. Nothing is requested when it is empty. + * @returns {Promise<*|null|undefined|Object>} The unwrapped data, null when the endpoint answered without data, undefined when the request failed, or the REDIRECTED marker when the session expired and the page is navigating away. + */ + async fetchJsonAsync(url) { + if (!url) + return null; + try { + const response = await fetch(url, { + headers: { + 'Accept': 'application/json', + 'X-Requested-With': 'XMLHttpRequest' + } + }); + if (response.redirected) { + // The session expired and the server answered with the login page; follow it, and report the redirect, not a failure. + window.location.href = response.url; + return REDIRECTED; + } + if (!response.ok) + return undefined; + const payload = await response.json(); + return payload && payload.success === true ? payload.data : null; + } catch (error) { + console.error('Audio player: a preferences request failed.', error); + return undefined; + } + } + + /** + * Applies the effective volume to the engine. + * @returns {Promise} A promise that completes when the engine received the volume. + */ + async applyVolumeAsync() { + // Before the first play there is no engine to receive the volume, so it is remembered and applied when the engine is + // created, which keeps a volume set before playback from being lost. + if (!this.engine) + return; + try { + await this.engine.setVolumeAsync(this.getEffectiveVolume()); + } catch (error) { + this.raiseError(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + } + } + + /** + * Gets the volume actually sent to the output, which is zero while muted. + * @returns {number} The effective volume, between 0 and 1. + */ + getEffectiveVolume() { + return this.muted ? 0 : this.volume; + } + + /** + * Builds the payload shared by the volume and mute events. + * @returns {Object} The volume payload. + */ + buildVolumePayload() { + return { volume: this.volume, muted: this.muted, effectiveVolume: this.getEffectiveVolume() }; + } + + /** + * Handles a click on the progress bar as a seek to the clicked ratio. + * @param {MouseEvent} event - The click event on the progress bar. + */ + handleProgressClick(event) { + if (!this.descriptor || this.duration <= 0 || !this.dom.progress) + return; + const bounds = this.dom.progress.getBoundingClientRect(); + if (bounds.width <= 0) + return; + const ratio = clamp((event.clientX - bounds.left) / bounds.width, 0, 1); + this.seekAsync(ratio * this.duration); + } + + /** + * Ensures the bar starts hidden, so that a page load never flashes an empty player. + */ + applyHiddenState() { + this.container.classList.add('not-shown'); + if (this.main) + this.main.classList.add('audio-player-not-shown'); + } + + /** + * Suppresses the transitions of the bar and of the content area while the initial hidden state is applied, so + * that a page load never slides either of them into place. The suppression is removed after the next frame, + * once the hidden state is already in effect, so later show and hide transitions keep working. + */ + suppressInitialTransitions() { + const root = document.documentElement; + if (!root || !root.classList) + return; + root.classList.add('audio-player-initializing'); + const release = () => root.classList.remove('audio-player-initializing'); + if (typeof requestAnimationFrame === 'function') + requestAnimationFrame(() => requestAnimationFrame(release)); + else + release(); + } + + /** + * Removes the initial 'hidden' attribute of the bar, now that the 'not-shown' class already keeps it hidden. + * + * The markup ships the bar with the 'hidden' attribute, so that it cannot be painted before this script runs, + * no matter how the stylesheets settle. By the time the attribute is removed the bar is already at its hidden + * height, so the removal is never visible; the class that remains is what later show and hide transitions act on. + */ + releaseInitialHiddenState() { + const release = () => { + if (this.container) + this.container.removeAttribute('hidden'); + }; + if (typeof requestAnimationFrame === 'function') + requestAnimationFrame(release); + else + release(); + } + + /** + * Renders the track name, the cover art and the total time of the current descriptor. + */ + renderDescriptor() { + const descriptor = this.descriptor; + if (this.dom.trackName) + this.dom.trackName.textContent = descriptor ? descriptor.title : ''; + const coverArtUrl = descriptor && descriptor.coverArtUrl + ? descriptor.coverArtUrl + : '/images/ui/music-placeholder.svg'; + if (this.dom.coverThumbnail) + this.dom.coverThumbnail.src = coverArtUrl; + if (this.dom.coverImage) + this.dom.coverImage.src = coverArtUrl; + if (this.dom.totalTime) + this.dom.totalTime.textContent = formatDuration(this.duration); + this.renderTransportState(); + } + + /** + * Renders the three state progress bar: the played part, the downloaded part, and the remainder. + */ + renderProgress() { + if (this.dom.currentTime) + this.dom.currentTime.textContent = formatTime(this.currentTime); + if (this.dom.totalTime) + this.dom.totalTime.textContent = formatDuration(this.duration); + const playedRatio = this.duration > 0 ? clamp(this.currentTime / this.duration, 0, 1) : 0; + const downloadedRatio = clamp(this.downloadedFraction, 0, 1); + if (this.dom.progressPlayed) + this.dom.progressPlayed.style.width = `${playedRatio * 100}%`; + if (this.dom.progressDownloaded) + this.dom.progressDownloaded.style.width = `${downloadedRatio * 100}%`; + } + + /** + * Renders the play or pause affordance of the transport control. + */ + renderTransportState() { + const playing = this.state === LuminaAudioPlayer.PlayerState.PLAYING; + if (this.dom.playPause) + this.dom.playPause.classList.toggle('is-playing', playing); + } + + /** + * Renders the ordered queue in the expanded bar. The list is only shown when the play context + * holds more than one track, so that a single track never renders a one item list. + */ + renderQueue() { + if (!this.dom.queue) + return; + this.dom.queue.innerHTML = ''; + const items = this.queue.length > 1 ? this.queue : []; + for (const item of items) { + const entry = document.createElement('li'); + entry.className = 'audio-player-queue-item'; + entry.dataset.trackId = item.trackId; + const title = document.createElement('span'); + title.className = 'audio-player-queue-item-title'; + title.textContent = item.title || ''; + const duration = document.createElement('span'); + duration.className = 'audio-player-queue-item-duration'; + duration.textContent = formatDuration(item.durationInSeconds); + entry.appendChild(title); + entry.appendChild(duration); + this.dom.queue.appendChild(entry); + } + } + } + + LuminaAudioPlayer.AudioPlayer = AudioPlayer; + + // Expose the descriptor helpers on the namespace, so that a page or a test builds a descriptor the same way the player does. + LuminaAudioPlayer.createPlayDescriptor = createPlayDescriptor; + LuminaAudioPlayer.resolveCoverArtUrl = resolveCoverArtUrl; + LuminaAudioPlayer.readPlayDescriptorFromElement = readPlayDescriptorFromElement; + LuminaAudioPlayer.formatPlayerTime = formatTime; + LuminaAudioPlayer.formatPlayerDuration = formatDuration; + LuminaAudioPlayer.UNKNOWN_TIME = UNKNOWN_TIME; + + /** + * Creates the singleton player of the application, binds it to the layout bar, and exposes it as + * window.LuminaAudioPlayer.instance. The player is created exactly once: the in-place navigation + * manager swaps the content area only, so the player and its playback survive every navigation. + * + * This function is invoked automatically when the module loads, so the singleton is already created before any + * other script runs. The instance seam is therefore the way to configure it afterwards: + * window.LuminaAudioPlayer.instance.registerEngine(name, factory).useEngine(name). The optional + * options are honored only when this is the first creation of the player, for a composition that creates the + * player itself, such as a test. + * @param {Object} [options] - The player options, per the {@link LuminaAudioPlayer.AudioPlayer} constructor. Honored only on the first creation. + * @returns {LuminaAudioPlayer.AudioPlayer} The singleton player. + */ + LuminaAudioPlayer.createDefaultPlayer = function (options) { + if (LuminaAudioPlayer.instance) + return LuminaAudioPlayer.instance; + const player = new AudioPlayer(options); + player.initialize(); + LuminaAudioPlayer.instance = player; + return player; + }; + + if (document.readyState === 'loading') + document.addEventListener('DOMContentLoaded', () => LuminaAudioPlayer.createDefaultPlayer()); + else + LuminaAudioPlayer.createDefaultPlayer(); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index 27911a61..6b278ab1 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -1,4 +1,4 @@ -const scrollbarHeight = getScrollbarHeight(); +const scrollbarHeight = getScrollbarHeight(); const scrollbarWidth = getScrollbarWidth(); const progressIndicator = document.getElementById('progress-indicator'); const progressIndicatorValue = document.getElementById('progress-indicator-value'); @@ -648,23 +648,26 @@ function getElementOffset(id) { } /** - * Toggles the visibility of the audio player. + * Closes the audio player, by routing to the audio player that owns the bar. + * + * The player bar is the single owner of its own classes, its state and its visibility, so this control, and the full + * height control below, only route to it. The two controls exist only when the bar is rendered, which is only for an + * authenticated visitor, for whom the audio player is always created, so there is no separate no-player fallback to + * keep in sync with the player. */ function toggleAudioPlayerVisibility() { - const playerContainer = document.querySelector('.audio-player-container'); - const contentContainer = document.querySelector('main'); - playerContainer.classList.toggle('not-shown'); - contentContainer.classList.toggle('audio-player-not-shown'); + const player = window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance; + if (player && typeof player.stopAsync === 'function') + player.stopAsync(); } /** - * Toggles the display of the audio player as collapsed player, or full height player. + * Expands the audio player into its full height form, or collapses it back, by routing to the audio player that owns the bar. */ function toggleAudioPlayerFullHeight() { - const playerContainer = document.querySelector('.audio-player-container'); - const contentContainer = document.querySelector('main'); - playerContainer.classList.toggle('full-height'); - contentContainer.classList.toggle('audio-player-full-height'); + const player = window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance; + if (player && typeof player.toggleFullHeight === 'function') + player.toggleFullHeight(); } if (audioPlayerFullHeightToggle) From 687371bfd2ab462cd26263f203d912de408f2bc0 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 16 Oct 2026 00:46:36 +0300 Subject: [PATCH 13/77] Adds the audio player download engine with range fetching, resume and streaming progress. --- .../Views/Shared/_ThemeLayoutScripts.cshtml | 2 + .../audio-player/audio-player-capabilities.js | 30 +- .../js/audio-player/audio-player-download.js | 1379 +++++++++++++++++ .../js/audio-player/audio-player-engine.js | 6 +- .../js/audio-player/audio-player-errors.js | 4 + .../js/audio-player/audio-player-events.js | 2 +- .../js/audio-player/audio-player-utils.js | 24 + .../wwwroot/js/audio-player/audio-player.js | 73 +- 8 files changed, 1477 insertions(+), 43 deletions(-) create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 499c5a2d..89faf6c9 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -45,8 +45,10 @@ + + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js index 5a33dcdb..38e5b477 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js @@ -111,8 +111,8 @@ * Detects every capability the player needs, in parallel, and caches the report. * * The returned report has the shape: - * { webCodecs, audioDecoder, audioContext, codecs, missing, supported }, where codecs maps each probed codec name to a boolean, missing lists the - * {@link LuminaAudioPlayer.PlayerCapability} values that are absent, and supported is true only when every required capability is present. + * { hasWebCodecs, hasAudioDecoder, hasAudioContext, codecs, missing, isSupported }, where codecs maps each probed codec name to a boolean, missing lists the + * {@link LuminaAudioPlayer.PlayerCapability} values that are absent, and isSupported is true only when every required capability is present. * @returns {Promise} The capability report. */ async detectAsync() { @@ -136,19 +136,19 @@ * @returns {Promise} The capability report. */ async runDetectionAsync() { - const webCodecs = this.hasWebCodecs(); - const audioDecoder = this.hasAudioDecoder(); - const audioContext = this.hasAudioContext(); + const hasWebCodecs = this.hasWebCodecs(); + const hasAudioDecoder = this.hasAudioDecoder(); + const hasAudioContext = this.hasAudioContext(); const codecs = {}; - if (audioDecoder) { + if (hasAudioDecoder) { // Each isConfigSupported is an independent round trip to the browser, so they are probed in parallel; the // results are folded in afterwards, in probe order, so the report never depends on which probe finishes first. const probeResults = await Promise.all(LuminaAudioPlayer.PROBED_AUDIO_CODECS.map(async (probe) => { - return { name: probe.name, supported: await this.supportsAudioConfigAsync(probe.config) }; + return { name: probe.name, isSupported: await this.supportsAudioConfigAsync(probe.config) }; })); for (const probeResult of probeResults) - codecs[probeResult.name] = probeResult.supported; + codecs[probeResult.name] = probeResult.isSupported; } else { // Without a decoder nothing can be probed, but every codec key is still reported as false, so that a // consumer reads the same shape whether the decoder exists or not, instead of testing for a missing key. @@ -159,21 +159,21 @@ // Only the three hard capabilities decide whether the player can run at all; a codec the browser cannot decode is // not fatal here, because the server can normalize such a track, which the delivery decision handles at play time. const missing = []; - if (!webCodecs) + if (!hasWebCodecs) missing.push(LuminaAudioPlayer.PlayerCapability.WEB_CODECS); - if (!audioDecoder) + if (!hasAudioDecoder) missing.push(LuminaAudioPlayer.PlayerCapability.AUDIO_DECODER); - if (!audioContext) + if (!hasAudioContext) missing.push(LuminaAudioPlayer.PlayerCapability.AUDIO_CONTEXT); // The report is shared and cached, so it is frozen to stop one consumer from mutating what every other consumer reads. return Object.freeze({ - webCodecs, - audioDecoder, - audioContext, + hasWebCodecs, + hasAudioDecoder, + hasAudioContext, codecs: Object.freeze(codecs), missing: Object.freeze(missing), - supported: missing.length === 0 + isSupported: missing.length === 0 }); } diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js new file mode 100644 index 00000000..7777203d --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js @@ -0,0 +1,1379 @@ +/** + * Download engine of the audio player. + * + * The player never uses a native audio element, so it fetches the bytes of a track itself and keeps them until the track + * ends. This module performs that fetch: it issues HTTP range requests against the same origin streaming proxy of the web + * application, reads the body through a ReadableStream, and stores the bytes in a buffer that the UI and the decode + * pipeline can query. It produces no audio; it only brings the bytes into the page. + * + * What it guarantees + * ------------------ + * - It handles both a 200 (the whole resource) and a 206 (a partial response) answer, so a server that ignores the + * range header still ends up with a correct buffer. + * - Overlapping and adjacent ranges are merged, so a byte that was already downloaded is never downloaded twice, and + * seeking back into an already downloaded range does not fetch it again. + * - It never discards bytes: seeking to a new position keeps everything that was already downloaded and continues from + * the requested position. The buffer is only released when the track ends (destroyAsync). + * - It supports open ended ranges ('bytes=start-'), bounded ranges ('bytes=start-end') and suffix ranges ('bytes=-n'). + * - It supports abort and resume: an in flight request is cancelled through an AbortController, and resuming issues a + * new request from the first byte that is still missing, so no work is lost. + * - It maps downloaded byte positions to time through the manifest duration, so the fraction it reports is + * time accurate and can drive the streamed indicator of the player bar directly. + * + * Continue while paused + * --------------------- + * The player keeps downloading while playback is paused only when the user turned the 'keep downloading while paused' + * setting on. The downloader therefore tracks two independent inputs: whether playback is paused (setPlaybackPaused) and + * the setting itself (setKeepDownloadingWhilePaused). When playback is paused and the setting is off, the in flight + * request is aborted and the download stops; when the setting is on, the download runs to the end of the file regardless + * of the paused state. The setting is also read from the player event bus, so a preference that changes mid track is + * honored without the caller having to push it again. + * + * Using it + * -------- + * The engine of a track creates the downloader with the stream path and the duration of the playback manifest, seeds the + * 'keep downloading while paused' setting from the player preferences, wires the progress callback to host.reportProgress, + * and drives the paused state from its own play and pause methods: + * + * const preferences = host.getPreferences(); + * const downloader = LuminaAudioPlayer.createTrackDownloader({ + * url: manifest.streamPath, + * durationInSeconds: manifest.durationInSeconds, + * shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, + * events: host.events, + * onProgress: (progress) => host.reportProgress(progress.downloadedFraction), + * onError: (error) => host.reportError(error) + * }); + * // Fire and forget: the promise settles only when the loop stops, which is when the whole file is downloaded, the region + * // from the target on is fully buffered, playback is paused with keep-downloading off, a failure or a no-progress + * // response stops it, or it is aborted or destroyed. Awaiting it in loadAsync would stall the engine, and the first + * // audio, until the entire file is in the buffer. Observe progress and completion through the callbacks. + * downloader.startAsync(); + * + * The option is the creation-time snapshot and the event is the update. The player starts loading the stored preferences + * without awaiting the request, so a play that lands before that load resolves creates the engine, and its downloader, + * first; the engine therefore seeds the value it holds at that moment through getPreferences, and the subscription is what + * makes a change that arrives afterwards, including the load that finishes late, win. From then on PREFERENCES_CHANGED + * (and setKeepDownloadingWhilePaused) override the seed, so a preference that changes mid track is applied without + * recreating the downloader. + * + * Reporting a failure + * ------------------- + * The downloader is a sub component, so it never moves the player state machine and never emits on the event bus itself. + * A stream or configuration failure is reported to the onError callback as a {@link LuminaAudioPlayer.PlayerError} + * carrying {@link LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED}, and kept on the downloader for polling through + * getError. The engine must forward that callback to host.reportError(error), exactly as above, so the failure + * reaches the player and the event bus; an engine that wires only onProgress leaves the failure unobserved. + * + * An intentional stop is not a failure: abort and destroyAsync never call onError and never set getError. They only reject + * the reads that are waiting for a window, with {@link LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED}, so a seek + * teardown is never mistaken for a stream failure. A read therefore resolves once the buffer covers its window, and is + * rejected when the window can no longer be filled: on a destroy or an abort (DOWNLOAD_ABORTED), with the recorded failure + * when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason === 'window-unavailable' when + * the file completed or the loop ended with no gap left to fill. A read that is waiting while the download is merely + * paused, or before it has started, is left pending, because a resume or a start can still fill it. The loop callbacks and + * getError only ever see DOWNLOAD_FAILED. + * + * Rejection policy + * ---------------- + * One rule, everywhere in this module: the control surface never throws and never rejects. startAsync and destroyAsync + * return a promise that only ever resolves; seek, setPlaybackPaused, setKeepDownloadingWhilePaused and abort are + * synchronous and return nothing. A failure reaches a caller through the error callback and getError, never through a + * rejected control promise. The awaited reads are the exception and do reject: readBytesAsync and whenRangeAvailableAsync + * reject with a typed error when the window can never arrive. A caller awaits a read to get an error, and observes the + * loop through its callbacks, never by catching its promise. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Clamps a number into an inclusive range, through the shared helper on the namespace. The reference is resolved on + * every call rather than captured at load time, so this module does not depend on the load order of the util. + * @param {number} value - The value to clamp. + * @param {number} minimum - The inclusive lower bound. + * @param {number} maximum - The inclusive upper bound. + * @returns {number} The clamped value. + */ + function clamp(value, minimum, maximum) { + return LuminaAudioPlayer.clamp(value, minimum, maximum); + } + + /** + * Parses the total byte count of a Content-Length header. + * @param {string|null} value - The header value. + * @returns {number|null} The length in bytes, or null when it is absent or malformed. + */ + function parseContentLength(value) { + if (!value) + return null; + const length = Number(value); + return Number.isInteger(length) && length >= 0 ? length : null; + } + + /** + * Parses a Content-Range header of the form 'bytes start-end/total', where the total may be '*' when the server does + * not know it. + * @param {string|null} value - The header value. + * @returns {{ start: number, end: number, total: number|null }|null} The parsed range, or null when the header is absent or malformed. + */ + function parseContentRange(value) { + if (!value) + return null; + const match = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i.exec(value.trim()); + if (!match) + return null; + const start = Number(match[1]); + const end = Number(match[2]); + const total = match[3] === '*' ? null : Number(match[3]); + if (!Number.isInteger(start) || !Number.isInteger(end) || start > end) + return null; + return { start, end, total }; + } + + /** + * Checks whether a value is the AbortError a cancelled fetch or stream read rejects with. + * @param {*} error - The value to check. + * @returns {boolean} True when the value is an AbortError. + */ + function isAbortError(error) { + return error instanceof Error && error.name === 'AbortError'; + } + + /** + * Checks whether a Content-Type is one the track stream may answer with: an audio type, or the generic binary type + * the stream endpoint falls back to for a container it cannot name. Any other type, in particular the text/html of a + * sign in page, is not the track. + * @param {string|null} value - The Content-Type header value. + * @returns {boolean} True when the value is an audio type or application/octet-stream. + */ + function isStreamContentType(value) { + if (!value) + return false; + const type = value.split(';', 1)[0].trim().toLowerCase(); + return type.startsWith('audio/') || type === 'application/octet-stream'; + } + + /** + * A byte buffer that stores downloaded chunks as merged, contiguous segments. + * + * A segment is a contiguous run of downloaded bytes, held as the list of chunks it was assembled from. Chunks are kept + * by reference, never re-copied, so a sequential download appends in constant time and the memory cost is the file + * itself. A chunk that is already covered adds nothing, a chunk that is only partly new contributes just its new bytes, + * and touching runs are merged, so segment boundaries are exactly the gaps in the download, which makes the range + * reporting and the byte count exact. It is the structure the UI queries for the downloaded ranges and the fraction, + * and the structure the decode pipeline reads bytes from. + */ + class ByteBufferStore { + /** + * Creates an instance of ByteBufferStore. + */ + constructor() { + /** @type {Array<{ start: number, length: number, chunks: Array }>} */ + this.segments = []; + /** @type {{ segmentIndex: number, chunkIndex: number, chunkStart: number }|null} */ + this.readHint = null; + } + + /** + * Appends a chunk at the given byte offset, keeping only the bytes that are not stored yet and merging them with + * the segments they touch. + * + * A sequential download, the common case, extends the last segment in constant time. A chunk that is fully covered + * by the buffer adds nothing and is dropped without a copy, and a chunk that is only partly new contributes just its + * new sub-ranges. There is therefore no path that copies a whole downloaded span, which matters when a server + * answers a range request with the entire resource while the buffer already holds a large prefix. + * @param {number} offset - The byte offset the chunk starts at. + * @param {Uint8Array} bytes - The chunk to store. + */ + append(offset, bytes) { + if (!bytes || bytes.byteLength === 0) + return; + const start = Math.max(0, Math.floor(offset)); + const end = start + bytes.byteLength; + const last = this.segments[this.segments.length - 1]; + if (last && last.start + last.length === start) { + last.chunks.push(bytes); + last.length += bytes.byteLength; + return; + } + for (const range of this.subtract(start, end)) + this.insertSegment(range.start, bytes.subarray(range.start - start, range.end - start)); + } + + /** + * Computes the sub-ranges of a span that are not stored yet. + * @param {number} start - The first byte of the span. + * @param {number} end - The exclusive end of the span. + * @returns {Array<{ start: number, end: number }>} The uncovered sub-ranges, in ascending order. + */ + subtract(start, end) { + // Reducing a chunk to only its new bytes is what keeps an overlapping append cheap: the buffer never has to copy + // or rebuild the span a refill overlaps, because the already stored part is simply not handed on. + const result = []; + let position = start; + for (const segment of this.segments) { + const segmentEnd = segment.start + segment.length; + if (segmentEnd <= position) + continue; + if (segment.start >= end) + break; + if (segment.start > position) + result.push({ start: position, end: Math.min(segment.start, end) }); + position = Math.max(position, segmentEnd); + if (position >= end) + break; + } + if (position < end) + result.push({ start: position, end }); + return result; + } + + /** + * Inserts a run of bytes that is known not to overlap any stored byte, merging it with the segments it touches. + * @param {number} start - The first byte of the run. + * @param {Uint8Array} bytes - The bytes of the run. + */ + insertSegment(start, bytes) { + // The run is known to be new, so merging only concatenates chunk references; no byte is copied into a new buffer. + const end = start + bytes.byteLength; + const kept = []; + const parts = [{ start, length: bytes.byteLength, chunks: [bytes] }]; + let mergedStart = start; + let mergedEnd = end; + for (const segment of this.segments) { + const segmentEnd = segment.start + segment.length; + // Touching segments are merged as well: the comparison is strict, so a segment that ends exactly where + // another begins joins the run instead of leaving a one byte gap. + if (segmentEnd < mergedStart || segment.start > mergedEnd) { + kept.push(segment); + continue; + } + mergedStart = Math.min(mergedStart, segment.start); + mergedEnd = Math.max(mergedEnd, segmentEnd); + parts.push(segment); + } + parts.sort((left, right) => left.start - right.start); + // The parts are non-overlapping by construction, so their chunks concatenate in offset order into the run. + const chunks = []; + for (const part of parts) + for (const chunk of part.chunks) + chunks.push(chunk); + kept.push({ start: mergedStart, length: mergedEnd - mergedStart, chunks }); + kept.sort((left, right) => left.start - right.start); + this.segments = kept; + this.readHint = null; + } + + /** + * Lists the downloaded byte ranges, as half open intervals. + * @returns {Array<{ start: number, end: number }>} The downloaded ranges, in ascending order. + */ + getRanges() { + return this.segments.map((segment) => ({ start: segment.start, end: segment.start + segment.length })); + } + + /** + * Gets the number of distinct bytes held by the buffer. + * @returns {number} The byte count. + */ + getByteCount() { + let count = 0; + for (const segment of this.segments) + count += segment.length; + return count; + } + + /** + * Checks whether the whole window is already stored, without copying its bytes. + * @param {number} offset - The first byte of the window. + * @param {number} length - The length of the window, in bytes. + * @returns {boolean} True when the window is fully stored. + */ + covers(offset, length) { + const start = Math.max(0, Math.floor(offset)); + const size = Math.max(0, Math.floor(length)); + if (size === 0) + return true; + for (const segment of this.segments) { + const segmentEnd = segment.start + segment.length; + if (start < segment.start) + return false; + if (start < segmentEnd) + return start + size <= segmentEnd; + } + return false; + } + + /** + * Copies a window of bytes out of the buffer. + * @param {number} offset - The first byte of the window. + * @param {number} length - The length of the window, in bytes. + * @returns {Uint8Array|null} A copy of the bytes, or null when any byte of the window is missing. + */ + read(offset, length) { + const start = Math.max(0, Math.floor(offset)); + const size = Math.max(0, Math.floor(length)); + if (size === 0) + return new Uint8Array(0); + let segmentIndex = -1; + for (let index = 0; index < this.segments.length; index++) { + const candidate = this.segments[index]; + if (start < candidate.start) + return null; + if (start < candidate.start + candidate.length) { + if (start + size > candidate.start + candidate.length) + return null; + segmentIndex = index; + break; + } + } + if (segmentIndex === -1) + return null; + const segment = this.segments[segmentIndex]; + const local = start - segment.start; + const result = new Uint8Array(size); + let filled = 0; + let position = 0; + let chunkIndex = 0; + // A sequential reader continues where the previous read stopped, so the chunk search resumes at that chunk + // instead of walking the whole segment again. + if (this.readHint && this.readHint.segmentIndex === segmentIndex && this.readHint.chunkStart <= local) { + chunkIndex = this.readHint.chunkIndex; + position = this.readHint.chunkStart; + } + for (; chunkIndex < segment.chunks.length; chunkIndex++) { + const chunk = segment.chunks[chunkIndex]; + if (position + chunk.byteLength <= local) { + position += chunk.byteLength; + continue; + } + const from = Math.max(0, local - position); + const take = Math.min(chunk.byteLength - from, size - filled); + result.set(chunk.subarray(from, from + take), filled); + filled += take; + if (filled >= size) { + this.readHint = { segmentIndex, chunkIndex, chunkStart: position }; + return result; + } + position += chunk.byteLength; + } + return null; + } + + /** + * Finds the first byte at or after an offset that is not stored yet. + * @param {number} offset - The byte to start from. + * @param {number|null} limit - The exclusive upper bound, or null when it is unknown. + * @returns {number|null} The first missing byte, or null when every byte up to the limit is stored. + */ + findFirstGap(offset, limit) { + // This is the loop's scheduling primitive: it answers both "which byte do I fetch next" (a number) and "is there + // anything left to fetch" (null). The limit is the known end of the file; with it the search can prove there is + // no gap left, while a null limit (an unknown total) can only ever point at the next byte to try. + let position = Math.max(0, Math.floor(offset)); + for (const segment of this.segments) { + const segmentEnd = segment.start + segment.length; + if (segmentEnd <= position) + continue; + if (segment.start > position) + return position; + // The position is inside this segment, so the search continues at its end. + position = segmentEnd; + if (limit !== null && position >= limit) + return null; + } + if (limit !== null && position >= limit) + return null; + return position; + } + + /** + * Gets the end of the contiguous run of stored bytes that starts at or after an offset. + * @param {number} offset - The byte to start from. + * @returns {number} The exclusive end of the contiguous run. + */ + getContiguousEnd(offset) { + let position = Math.max(0, Math.floor(offset)); + for (const segment of this.segments) { + const segmentEnd = segment.start + segment.length; + if (segmentEnd <= position) + continue; + if (segment.start > position) + break; + position = Math.max(position, segmentEnd); + } + return position; + } + + /** + * Gets the exclusive end of the last stored byte. It is the end of the file only when an open ended read proved it + * (streamComplete); otherwise it is merely the end of what has been downloaded so far. + * @returns {number} The exclusive end of the stored data, or zero when nothing is stored. + */ + getEnd() { + if (this.segments.length === 0) + return 0; + const last = this.segments[this.segments.length - 1]; + return last.start + last.length; + } + + /** + * Releases every stored byte. + */ + clear() { + this.segments = []; + this.readHint = null; + } + } + + /** + * Downloads a single track into a buffer, with range support, abort and resume, and time accurate progress. + */ + class TrackDownloader { + /** + * Creates an instance of TrackDownloader. + * @param {Object} options - The downloader options. + * @param {string} options.url - The stream path of the track, relative to the page or absolute on the same origin. Nothing is fetched when it is empty. + * @param {number} options.durationInSeconds - The duration of the track, in seconds, from the playback manifest. It maps byte positions to time. + * @param {number} [options.totalBytes] - The known size of the file, in bytes. It is discovered from the first response when omitted. + * @param {Function} [options.fetch] - The fetch implementation to use, for injection in a test. Defaults to window.fetch. + * @param {string} [options.credentials] - The credentials mode of the request. Defaults to 'same-origin', so the session cookie is sent. + * @param {Object} [options.events] - The player event bus. When provided, the 'keep downloading while paused' preference is kept current from it. + * @param {boolean} [options.shouldKeepDownloadingWhilePaused] - The value of the 'keep downloading while paused' setting, seeded by the engine from host.getPreferences(). It is the initial value; later PREFERENCES_CHANGED events and setKeepDownloadingWhilePaused override it. + * @param {Function} [options.onProgress] - Called with the progress snapshot every time the buffer grows. + * @param {Function} [options.onComplete] - Called once when every byte of the file has been downloaded. + * @param {Function} [options.onError] - Called with a {@link LuminaAudioPlayer.PlayerError} when the download fails. + */ + constructor(options = {}) { + this.url = typeof options.url === 'string' ? options.url : ''; + this.duration = Number.isFinite(Number(options.durationInSeconds)) && Number(options.durationInSeconds) > 0 + ? Number(options.durationInSeconds) + : 0; + this.buffer = new ByteBufferStore(); + this.fetchImpl = typeof options.fetch === 'function' + ? options.fetch + : (typeof window !== 'undefined' && typeof window.fetch === 'function' ? window.fetch.bind(window) : null); + this.credentials = typeof options.credentials === 'string' && options.credentials !== '' ? options.credentials : 'same-origin'; + this.events = options.events || null; + this.shouldKeepDownloadingWhilePaused = options.shouldKeepDownloadingWhilePaused === true; + this.onProgress = typeof options.onProgress === 'function' ? options.onProgress : null; + this.onComplete = typeof options.onComplete === 'function' ? options.onComplete : null; + this.onError = typeof options.onError === 'function' ? options.onError : null; + this.totalBytes = Number.isInteger(options.totalBytes) && options.totalBytes >= 0 ? options.totalBytes : null; + this.targetByte = 0; + this.pendingSeekSeconds = null; + this.isPlaybackPaused = false; + this.isAborted = false; + // Boolean state keeps its conventional is/has prefix, except where a public is*() accessor already owns that name: + // isDestroyed() is that accessor here, so the backing field keeps the participle instead of shadowing the method. + this.destroyed = false; + this.isFinished = false; + // True once the loop stopped with no gap left to fill from the target and without completing the file: from + // then on, the loop can no longer append anything for the current target, so a reader waiting for a window that + // is not covered can never be filled. It is cleared whenever a new loop starts. + this.isDrained = false; + // True once an open ended read both delivered its whole declared range and reached the end of its body, which is + // what proves the end of the file when the server never reported a total size. + this.isStreamComplete = false; + // True when the downloader can never fetch, because it has no url or no fetch implementation, so a start does + // not keep re-reporting the same configuration failure. + this.isUnusable = false; + this.error = null; + // A downloader may have one loop request and, at most, an explicit one shot range request in flight at the same + // time, so every controller is tracked and an abort or a destroy cancels all of them, not just the newest. + this.abortControllers = new Set(); + this.loopPromise = null; + this.waiters = []; + this.unsubscribePreferences = null; + this.subscribeToPreferences(); + } + + //+======================================================================================+ + //| Control surface | + //+======================================================================================+ + + /** + * Starts, or continues, the download loop from the current target position. + * + * The loop keeps downloading ahead until the whole file is stored, playback is paused with the 'keep downloading + * while paused' setting off, or the downloader is aborted or destroyed. Bytes that are already stored are never + * fetched again, so a call after a seek only fetches what is still missing. + * + * A caller starts it without awaiting it: the returned promise settles only when the loop stops, which can be the + * end of the whole track. Progress and completion are observed through the callbacks. + * @param {Object} [options] - The optional starting position. + * @param {number} [options.fromByte] - A byte position to start from, overriding the current target. + * @param {number} [options.fromSeconds] - A time position to start from, overriding the current target. It is mapped to a byte through the duration. + * @returns {Promise} A promise that resolves when the loop stops. It never rejects; a failure is reported through the error callback and getError. + */ + startAsync(options = {}) { + // A destroyed downloader, or one that can never fetch (no url, no fetch implementation), resolves without + // starting a loop, so a reconcile does not keep re-reporting the same configuration failure. + if (this.destroyed || this.isUnusable) + return Promise.resolve(); + this.isAborted = false; + let isRepositioned = false; + if (Number.isFinite(Number(options.fromByte))) { + this.targetByte = Math.max(0, Math.floor(Number(options.fromByte))); + // A new target makes a previous drain stale, exactly as a seek does. + this.isDrained = false; + isRepositioned = true; + } else if (Number.isFinite(Number(options.fromSeconds))) { + this.setTargetFromSeconds(Number(options.fromSeconds)); + isRepositioned = true; + } + if (this.loopPromise) { + // The loop re-evaluates the target at every iteration, so aborting the in flight request makes it pivot to + // the new position right away instead of waiting for the current response to reach its end. + if (isRepositioned) + this.cancelActiveRequest(); + return this.loopPromise; + } + // A restart clears the previous failure, so getError does not report a stale one after a successful retry, and it + // clears the drained state, because the new loop may fill windows the previous one left alone. + this.error = null; + this.isDrained = false; + const loop = this.runLoopAsync(); + this.loopPromise = loop; + // The handle is cleared only while it still points at this loop, so a retry started from a callback (onError or + // onComplete) keeps its own handle instead of having it nulled by the loop that just stopped. + loop.finally(() => { + if (this.loopPromise === loop) + this.loopPromise = null; + }); + return loop; + } + + /** + * Records a playback position and downloads from it when the download loop is allowed to run. + * + * It never discards stored bytes: a position inside an already downloaded range continues from the first missing + * byte after it, so seeking back into downloaded data never fetches it again. A seek over an incomplete download + * aborts the in flight request, so the loop fetches the new position first instead of finishing the bytes it was + * already reading. + * @param {number} seconds - The playback position, in seconds. + */ + seek(seconds) { + this.setTargetFromSeconds(seconds); + if (!this.shouldKeepRunning()) + return; + if (this.loopPromise) + this.cancelActiveRequest(); + else + this.startAsync(); + } + + /** + * Maps a playback position to a byte position, remembering it for later when the total size is not known yet. + * @param {number} seconds - The playback position, in seconds. + */ + setTargetFromSeconds(seconds) { + const position = Math.max(0, Number(seconds) || 0); + if (this.duration > 0 && this.totalBytes !== null) { + this.targetByte = Math.round(clamp(position / this.duration, 0, 1) * this.totalBytes); + this.pendingSeekSeconds = null; + } else { + // The size of the file is not known yet, so the position is remembered and mapped once the first response reveals it. + this.pendingSeekSeconds = position; + } + // A reposition makes the previous drain stale: the target moved, so a window that the previous drain could not + // fill may now be the very window a resume or a later start fetches. A read must not be rejected against it. + this.isDrained = false; + } + + /** + * Sets whether playback is paused, and reconciles the download loop with the 'keep downloading while paused' setting. + * @param {boolean} paused - True when playback is paused, false when it is playing. + */ + setPlaybackPaused(paused) { + const next = paused === true; + if (next === this.isPlaybackPaused) + return; + this.isPlaybackPaused = next; + this.reconcile(); + } + + /** + * Sets the 'keep downloading while paused' setting, and reconciles the download loop. + * @param {boolean} value - True to keep downloading while playback is paused, false to stop while paused. + */ + setKeepDownloadingWhilePaused(value) { + const next = value === true; + if (next === this.shouldKeepDownloadingWhilePaused) + return; + this.shouldKeepDownloadingWhilePaused = next; + this.reconcile(); + } + + /** + * Aborts the in flight requests and stops the loop, keeping every byte that was already downloaded. It is + * synchronous, like the other immediate controls, and it never returns a promise. + * + * The downloader stays usable: a later startAsync resumes from the first missing byte, because the abort only + * cancels the requests, never the buffer. destroyAsync is the operation that releases the buffer. + */ + abort() { + this.isAborted = true; + this.cancelActiveRequest(); + // The download is stopping and no byte will append until it is started again, so a reader that is waiting for a + // byte window is released with the aborted code instead of waiting forever. + this.rejectWaiters(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The track download was aborted.')); + } + + /** + * Releases every resource of the downloader: it aborts the in flight request, clears the buffer, and stops + * listening to the preference bus. It is used when the track ends, never when playback merely pauses. + * @returns {Promise} A promise that resolves when the loop has stopped. + */ + async destroyAsync() { + this.destroyed = true; + this.isAborted = true; + this.cancelActiveRequest(); + if (this.unsubscribePreferences) { + this.unsubscribePreferences(); + this.unsubscribePreferences = null; + } + this.rejectWaiters(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The track download was destroyed.')); + if (this.loopPromise) { + try { + await this.loopPromise; + } catch (error) { + // The loop reports its own failures; a teardown must not surface one. + } + } + this.buffer.clear(); + } + + //+======================================================================================+ + //| Query surface | + //+======================================================================================+ + + /** + * Gets the downloaded byte ranges, as half open intervals. This is the structure the UI queries to draw the + * downloaded parts of a progress bar. + * @returns {Array<{ start: number, end: number }>} The downloaded ranges, in ascending order. + */ + getRanges() { + return this.buffer.getRanges(); + } + + /** + * Gets the downloaded time ranges, mapped through either the known total size and the duration or, when the size + * is not known yet, through the bytes themselves once the whole file is in the buffer. + * @returns {Array<{ start: number, end: number }>} The downloaded time ranges, in seconds. + */ + getTimeRanges() { + // The duration and the total size give a single average rate, so a byte position maps to a time by proportion. A + // variable bit rate makes this an approximation, but it stays monotonic and it is all the manifest offers, which + // is why the streamed indicator is described as time accurate rather than exact. + const total = this.resolveTotalForMapping(); + if (total === null || this.duration <= 0) + return []; + return this.buffer.getRanges().map((range) => ({ + start: (range.start / total) * this.duration, + end: (range.end / total) * this.duration + })); + } + + /** + * Gets the fraction of the track that has been downloaded, between 0 and 1. + * + * The fraction is time accurate because a byte position maps linearly to a time through the known total size and + * the manifest duration. + * @returns {number} The downloaded fraction. + */ + getDownloadedFraction() { + const total = this.resolveTotalForMapping(); + if (total !== null && total > 0) + return clamp(this.buffer.getByteCount() / total, 0, 1); + return this.isComplete() ? 1 : 0; + } + + /** + * Gets the time, in seconds, up to which the track has been downloaded contiguously from its start. It is the + * value a single handed streamed indicator shows, while getTimeRanges is what a segmented bar uses. + * @returns {number} The contiguous downloaded time, in seconds. + */ + getDownloadedSeconds() { + const total = this.resolveTotalForMapping(); + if (total === null || total <= 0 || this.duration <= 0) + return 0; + const end = this.buffer.getContiguousEnd(0); + return clamp((end / total) * this.duration, 0, this.duration); + } + + /** + * Gets the number of distinct bytes in the buffer. + * @returns {number} The downloaded byte count. + */ + getDownloadedBytes() { + return this.buffer.getByteCount(); + } + + /** + * Gets the total size of the file, in bytes, once it is known. + * @returns {number|null} The total size, or null when the first response has not revealed it yet. + */ + getTotalBytes() { + return this.totalBytes; + } + + /** + * Gets the duration the downloader maps bytes to, in seconds. + * @returns {number} The duration, in seconds, or zero when it is unknown. + */ + getDuration() { + return this.duration; + } + + /** + * Checks whether the whole file is stored. + * @returns {boolean} True when every byte of the file is in the buffer. + */ + isComplete() { + if (this.isFinished) + return true; + if (this.totalBytes !== null && this.totalBytes > 0) + return this.buffer.findFirstGap(0, this.totalBytes) === null; + // The total size was never reported, so the file is complete only when an open ended read reached the end of + // the body and the buffer covers a single contiguous run that starts at the beginning of the file. + return this.isStreamComplete && this.buffer.segments.length === 1 && this.buffer.segments[0].start === 0; + } + + /** + * Checks whether the downloader was destroyed. + * @returns {boolean} True when the downloader was destroyed. + */ + isDestroyed() { + return this.destroyed; + } + + /** + * Gets the last failure, or null when there was none. + * @returns {LuminaAudioPlayer.PlayerError|null} The last failure. + */ + getError() { + return this.error; + } + + /** + * Builds a snapshot of the download progress. + * @returns {Object} The progress snapshot, with the downloaded byte count, the total size, the downloaded fraction, the downloaded time ranges, and the contiguous downloaded seconds. + */ + getProgress() { + return Object.freeze({ + downloadedBytes: this.buffer.getByteCount(), + totalBytes: this.totalBytes, + downloadedFraction: this.getDownloadedFraction(), + downloadedSeconds: this.getDownloadedSeconds(), + durationInSeconds: this.duration, + timeRanges: this.getTimeRanges() + }); + } + + /** + * Reads a window of bytes out of the buffer, waiting for it when it has not been downloaded yet. + * @param {number} offset - The first byte of the window. + * @param {number} length - The length of the window, in bytes. + * @returns {Promise} A copy of the requested bytes. + * @throws {LuminaAudioPlayer.PlayerError} The rejection of {@link LuminaAudioPlayer.TrackDownloader#whenRangeAvailableAsync}, which a read propagates, or DOWNLOAD_FAILED with details.reason === 'window-unavailable' if the window was released without ever arriving. + */ + async readBytesAsync(offset, length) { + const direct = this.buffer.read(offset, length); + if (direct !== null) + return direct; + await this.whenRangeAvailableAsync(offset, length); + const resolved = this.buffer.read(offset, length); + if (resolved === null) + throw this.createWindowUnavailableError(); + return resolved; + } + + /** + * Resolves once a window of bytes has been downloaded. + * @param {number} offset - The first byte of the window. + * @param {number} length - The length of the window, in bytes. + * @returns {Promise} A promise that resolves once the buffer covers the window. It is rejected when the window can no longer be filled: on a destroy or an abort, with the recorded failure when the loop stopped after a failure, or with the window-unavailable error when the file completed or the loop ended with no gap left to fill. A read issued while the download is merely paused, or before it has started, stays pending, because a resume or a start can still fill it. + * @throws {LuminaAudioPlayer.PlayerError} With DOWNLOAD_ABORTED when the downloader is destroyed or was aborted, with the recorded failure when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason === 'window-unavailable' when the file completed or the loop ended with no gap left to fill. + */ + whenRangeAvailableAsync(offset, length) { + if (this.buffer.covers(offset, length)) + return Promise.resolve(); + if (this.destroyed) + return Promise.reject(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The track download was destroyed.')); + // A window that is not buffered and a download that is intentionally stopped or has failed can never be filled, + // so the read is rejected now instead of waiting forever. + if (this.isAborted) + return Promise.reject(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The track download was aborted.')); + if (this.error && !this.loopPromise) + return Promise.reject(this.error); + // A completed file, or a loop that stopped with nothing left to fetch, can never fill an uncovered window, so the + // read is rejected instead of waiting. A pause leaves both unset, so a read issued during a pause still waits. + if ((this.isFinished || this.isDrained) && !this.loopPromise) + return Promise.reject(this.createWindowUnavailableError()); + return new Promise((resolve, reject) => { + this.waiters.push({ offset: Math.max(0, Math.floor(offset)), length: Math.max(0, Math.floor(length)), resolve, reject }); + }); + } + + //+======================================================================================+ + //| Range requests | + //+======================================================================================+ + + /** + * Downloads a bounded byte range and stores it. It never throws: a failure is returned as { isFailed: true, error } + * and, unlike the download loop, it never runs the complete or error callbacks, because it is an explicit request + * whose outcome the caller inspects. + * @param {number} start - The first byte of the range. + * @param {number} end - The last byte of the range, inclusive, as HTTP defines the end of a Range header. + * @returns {Promise} The outcome, per {@link LuminaAudioPlayer.TrackDownloader#performFetchAsync}. + */ + downloadRangeAsync(start, end) { + return this.performFetchAsync({ start, end }); + } + + /** + * Downloads an open ended byte range, from a position to the end of the file, and stores it. It never throws: a + * failure is returned as { isFailed: true, error } and it never runs the complete or error callbacks. + * @param {number} start - The first byte of the range. + * @returns {Promise} The outcome, per {@link LuminaAudioPlayer.TrackDownloader#performFetchAsync}. + */ + downloadOpenEndedAsync(start) { + return this.performFetchAsync({ start, openEnded: true }); + } + + /** + * Downloads a suffix byte range, the last bytes of the file, and stores it. It never throws: a failure is returned + * as { isFailed: true, error } and it never runs the complete or error callbacks. + * @param {number} length - The number of trailing bytes to request. + * @returns {Promise} The outcome, per {@link LuminaAudioPlayer.TrackDownloader#performFetchAsync}. + */ + downloadSuffixAsync(length) { + return this.performFetchAsync({ suffix: length }); + } + + //+======================================================================================+ + //| Internal helpers | + //+======================================================================================+ + + /** + * Subscribes to the preference changes of the player, so that a 'keep downloading while paused' setting that + * changes mid track is applied without the caller pushing it again. The initial value is never delivered by this + * subscription, because the player loads the stored preferences before any downloader exists, so the engine seeds + * it through the constructor option. + */ + subscribeToPreferences() { + if (!this.events || !LuminaAudioPlayer.PlayerEvent || typeof this.events.on !== 'function') + return; + this.unsubscribePreferences = this.events.on(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, (preferences) => { + if (preferences && typeof preferences.shouldKeepDownloadingWhilePaused === 'boolean') + this.setKeepDownloadingWhilePaused(preferences.shouldKeepDownloadingWhilePaused); + }); + } + + /** + * Reconciles the download loop with the current paused state and setting: it starts the loop when the download is + * allowed to run, and aborts the in flight request when it is not. + */ + reconcile() { + if (this.destroyed) + return; + if (this.shouldKeepRunning()) + this.startAsync(); + else + this.cancelActiveRequest(); + } + + /** + * Checks whether the download loop is allowed to run right now. + * @returns {boolean} True when the loop may run. + */ + shouldKeepRunning() { + if (this.destroyed || this.isAborted) + return false; + if (this.isPlaybackPaused) + return this.shouldKeepDownloadingWhilePaused; + return true; + } + + /** + * Cancels every in flight request through its AbortController. A pause, a pivot, an abort and a destroy all route + * here, so no request, and no connection, is left open behind one that another controller replaced. + */ + cancelActiveRequest() { + if (this.abortControllers.size === 0) + return; + for (const controller of [...this.abortControllers]) { + try { + controller.abort(); + } catch (error) { + console.debug('Audio player: the in flight download request could not be aborted.', error); + } + } + } + + /** + * Runs the download loop: it fetches from the first missing byte at or after the target until the loop is no + * longer allowed to run, or the whole file is stored. + * @returns {Promise} A promise that resolves when the loop stops. + */ + async runLoopAsync() { + // The body is deferred past a microtask so that it can never run to completion (drain, fail or complete) inside + // the synchronous prologue of startAsync, before startAsync has taken the handle. Without this a loop that ends + // at once would let startAsync re-arm its handle after the loop already released its readers, reopening a window + // in which a read waits for a loop that has finished. Awaiting a resolved promise, rather than a bare value, + // keeps the microtask yield without the "await has no effect on the type" hint an IDE raises for `await null`. + await Promise.resolve(); + if (this.fetchImpl === null) { + // A missing fetch implementation is a permanent configuration failure, so the downloader is marked unusable + // and later starts resolve without re-reporting it. + this.isUnusable = true; + this.fail(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'This environment provides no fetch implementation for the player download.')); + return; + } + if (this.url === '') { + this.isUnusable = true; + this.fail(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The play descriptor carries no stream path.')); + return; + } + let hasDrained = false; + try { + while (this.shouldKeepRunning()) { + // Completion is re-checked every iteration, not only through the gap, because with an unknown total a + // gap search against a null limit can never return null: without this the loop would request one byte + // past the end, get a 416, and report a failure on a file that is in fact fully buffered. + if (this.isComplete()) + break; + const gap = this.buffer.findFirstGap(this.targetByte, this.resolveKnownEnd()); + if (gap === null) { + // There is no gap left to fill from the target, so the loop has nothing more to do for this run. + hasDrained = true; + break; + } + const bytesBefore = this.buffer.getByteCount(); + const result = await this.performFetchAsync({ start: gap, openEnded: true, stopOnPause: true }); + if (this.destroyed || result.isDestroyed) + break; + if (result.isFailed) { + this.fail(result.error); + return; + } + if (result.isAborted) { + // The request was aborted to pivot to a new target while the loop is still allowed to run, so the + // loop re-evaluates the target instead of stopping; any other abort is caught by the loop condition. + if (this.shouldKeepRunning()) + continue; + break; + } + // A response that added no byte can fill nothing: either the file is already complete, or the download + // stalled. A stall is reported so the loop does not spin and every reader waiting for a window is + // released with the failure instead of hanging. + if (this.buffer.getByteCount() <= bytesBefore) { + if (this.isComplete()) + break; + this.fail(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The download made no progress.')); + return; + } + } + // Completion is reported inside the guarded block, so nothing the loop does can reject its promise. + if (this.destroyed) { + // A destroyed downloader releases its own waiters in destroyAsync. + } else if (this.isComplete()) { + this.complete(); + } else if (hasDrained) { + // The loop stopped with nothing left to fetch for the current target and without completing the file, so + // nothing will append again and a reader waiting for a window that is not covered can never be filled. + // The handle is cleared first, so a read issued after this point is rejected at once instead of waiting + // for a loop that is no longer running. + this.isDrained = true; + this.loopPromise = null; + this.rejectWaiters(this.createWindowUnavailableError()); + } + } catch (error) { + // No failure may escape the loop as a rejected promise, because a caller starts it without awaiting it. + this.fail(error); + return; + } + } + + /** + * Performs a single range request, reads its body, and stores the bytes. + * @param {Object} spec - The range specification. + * @param {number} [spec.start] - The first byte of the range. + * @param {number} [spec.end] - The last byte of the range, inclusive. + * @param {number} [spec.suffix] - The number of trailing bytes to request. + * @param {boolean} [spec.openEnded] - True to request an open ended range, from start to the end of the file. + * @param {boolean} [spec.stopOnPause] - True when a paused player must stop this request at the next chunk. The download loop sets it; a one shot range request does not, so an explicit request always completes. + * @returns {Promise} The outcome, one of: { isFailed: true, error } when the request failed, { isAborted: true } when it was aborted, { isDestroyed: true } when the downloader was destroyed, { isSatisfied: true } when the range was already satisfied, or { isAborted, isFailed: false, isDestroyed, isStopped } for a read that ended. It never rejects. + */ + async performFetchAsync(spec = {}) { + if (this.destroyed) + return { isDestroyed: true, isAborted: false, isFailed: false }; + if (this.fetchImpl === null || this.url === '') { + this.isUnusable = true; + return { isFailed: true, error: new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The download request could not be built.') }; + } + const controller = new AbortController(); + this.abortControllers.add(controller); + let response = null; + try { + response = await this.fetchImpl(this.url, { + method: 'GET', + headers: { 'Range': this.buildRangeHeader(spec) }, + credentials: this.credentials, + signal: controller.signal + }); + const resolved = this.resolveResponseRange(response); + if (resolved === null) { + // The requested range is already satisfied, so the response body, which may be a small error document, + // is discarded instead of being left open until it is garbage collected. + this.discardResponseBody(response); + return { isAborted: false, isFailed: false, isDestroyed: this.destroyed, isSatisfied: true }; + } + this.noteTotal(resolved.total); + return await this.readResponseIntoBufferAsync(response, resolved, controller, spec.stopOnPause === true, spec.openEnded === true); + } catch (error) { + if (isAbortError(error)) + return { isAborted: true, isFailed: false, isDestroyed: this.destroyed }; + // The failure left the response body unread, so it is discarded and the request is aborted to release the + // connection instead of waiting for the browser to drop the stream. + this.discardResponseBody(response); + try { + if (!controller.signal.aborted) + controller.abort(); + } catch (abortError) { + console.debug('Audio player: the failed download request could not be aborted.', abortError); + } + return { isFailed: true, error: LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED) }; + } finally { + this.abortControllers.delete(controller); + } + } + + /** + * Cancels the body of a response that is not going to be read, so its connection is released right away. + * @param {Response|null} response - The response whose body is discarded. Nothing is done when it has no body. + */ + discardResponseBody(response) { + if (!response || !response.body || typeof response.body.cancel !== 'function') + return; + try { + const cancellation = response.body.cancel(); + // Cancel returns a promise; a rejection is only a stream already being gone, so it is swallowed. + if (cancellation && typeof cancellation.catch === 'function') + cancellation.catch(() => {}); + } catch (error) { + console.debug('Audio player: the discarded download response body could not be cancelled.', error); + } + } + + /** + * Builds the Range header of a request. + * @param {Object} spec - The range specification. + * @returns {string} The Range header value. + */ + buildRangeHeader(spec) { + // A suffix wins over an explicit span, and an open ended request ignores an end even when one is present, so a + // caller that sets openEnded always gets 'start-', never a bounded range. + if (Number.isFinite(Number(spec.suffix)) && Number(spec.suffix) > 0) + return `bytes=-${Math.floor(Number(spec.suffix))}`; + const start = Number.isFinite(Number(spec.start)) ? Math.max(0, Math.floor(Number(spec.start))) : 0; + if (!spec.openEnded && Number.isFinite(Number(spec.end))) { + const end = Math.max(start, Math.floor(Number(spec.end))); + return `bytes=${start}-${end}`; + } + return `bytes=${start}-`; + } + + /** + * Resolves what a response says about the requested range, handling both a 206 partial response and a 200 full + * response, and rejecting an unusable answer. + * @param {Response} response - The response to inspect. + * @returns {{ start: number, endInclusive: number|null, total: number|null }|null} The resolved range, or null when the request is already satisfied. + * @throws {LuminaAudioPlayer.PlayerError} When the response was a followed redirect, carries a content type that is not audio, or is an error that is not a 'range not satisfiable'. + */ + resolveResponseRange(response) { + // An expired or cleared session makes the authenticated stream route answer with a redirect to the sign in + // page, and fetch follows it by default, so the followed redirect is rejected before any byte is stored. The + // request never asked for a redirect to a track, so a redirect is always a failure, never audio. + if (response.redirected) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The stream request was redirected, which means the session expired.'); + if (response.status === 416) { + // A range not satisfiable means the request started at or past the end of the file. It is only "already + // satisfied" when the buffer really covers the whole file, which is what isComplete measures, whether the + // total was reported or an open ended read already proved the end of the file. A one shot range whose start + // differs from the current target, or a file that was replaced or truncated, can answer 416 while bytes are + // still missing, and that must be a failure, not a silent end. + if (this.isComplete()) + return null; + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The stream rejected the requested byte range.', { status: response.status }); + } + if (response.status !== 200 && response.status !== 206) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, `The stream answered with status ${response.status}.`, { status: response.status }); + // A success that does not carry an audio type is not the track either, so the sign in page, or any other HTML + // or JSON answer of the same status, is rejected before its body is read into the buffer. + if (!isStreamContentType(response.headers.get('Content-Type'))) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The stream answered with a content type that is not audio.'); + if (response.status === 206) { + const parsed = parseContentRange(response.headers.get('Content-Range')); + if (parsed === null) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The stream answered a partial response without a usable Content-Range.', { status: response.status }); + return { start: parsed.start, endInclusive: parsed.end, total: parsed.total }; + } + // A 200 means the server ignored the range and sent the whole resource, so the buffer is filled from its start. + return { start: 0, endInclusive: null, total: parseContentLength(response.headers.get('Content-Length')) }; + } + + /** + * Reads the body of a response into the buffer, chunk by chunk, through its ReadableStream. + * @param {Response} response - The response whose body is read. + * @param {{ start: number, endInclusive: number|null }} range - The resolved range of the response. + * @param {AbortController} controller - The controller of the request, aborted when the loop must stop. + * @param {boolean} stopOnPause - True when a paused player must stop the read at the next chunk boundary. + * @param {boolean} openEnded - True when the request asked for a range that runs to the end of the file. Such a read is driven to the end of the body, and that end proves the end of the file, rather than the range the response happens to declare. + * @returns {Promise} The outcome of the read. + * @throws {LuminaAudioPlayer.PlayerError} When the response carries no readable body. + */ + async readResponseIntoBufferAsync(response, range, controller, stopOnPause, openEnded) { + if (!response.body || typeof response.body.getReader !== 'function') + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The stream response carried no readable body.'); + const reader = response.body.getReader(); + let offset = range.start; + let isStopped = false; + let hasReachedEnd = false; + // True when a bounded request read its whole declared range and stopped before the body ended, so any remaining + // bytes are discarded. An open ended request instead reads the body to its end, because that end, and not the + // range the response happens to declare, is the only signal that proves the end of the file. + let isStoppedAtRangeEnd = false; + try { + while (true) { + if (stopOnPause && !this.shouldKeepRunning()) { + isStopped = true; + break; + } + let result; + try { + result = await reader.read(); + } catch (error) { + if (isAbortError(error)) { + isStopped = true; + break; + } + throw error; + } + if (result.done) { + hasReachedEnd = true; + break; + } + const value = result.value; + if (!value || value.byteLength === 0) + continue; + this.buffer.append(offset, value); + offset += value.byteLength; + this.notifyProgress(); + this.resolveWaiters(); + // A bounded request stops once it has read the range it asked for, while an open ended request reads on + // to the end of the body, so a capped response is not mistaken for the end of the file. + if (!openEnded && range.endInclusive !== null && offset > range.endInclusive) { + isStoppedAtRangeEnd = true; + break; + } + } + } finally { + try { + reader.releaseLock(); + } catch (error) { + console.debug('Audio player: the download stream reader could not be released.', error); + } + // When the loop stops before the body ended, the request is aborted so the connection is released, and a + // later resume issues a fresh request from the first missing byte. + if (isStopped && !controller.signal.aborted) { + try { + controller.abort(); + } catch (error) { + console.debug('Audio player: the paused download request could not be aborted.', error); + } + } + // A bounded request that read its whole declared range may leave unread bytes in the body, so the body is + // discarded to release the connection. + if (isStoppedAtRangeEnd) + this.discardResponseBody(response); + } + // The whole declared range was delivered. A response with no declared end (a plain 200) always counts as covered. + const isDeclaredRangeCovered = range.endInclusive === null || offset > range.endInclusive; + // A response that read from the start of the resource to the end of its full declared range tells the total size + // even when the server reported none, which is what lets the fraction reach one for a server that answers with a + // plain 200. A short body is not the end of the file, so it does not set a bogus total. + if (hasReachedEnd && this.totalBytes === null && range.start === 0 && offset > 0 && isDeclaredRangeCovered) + this.totalBytes = offset; + // An open ended request proves the end of the file only when its body actually ended and it delivered the whole + // range it declared, which is what lets isComplete recognize a fully buffered file when the server never + // reported a total size. Requiring the body end rejects a short body (a stalled or truncated download), and + // requiring the declared range rejects a response that stopped early without ending its body. The residual + // assumption of this path is that the server did not cap an open ended answer to a shorter range, which is + // indistinguishable from the end of the file while the total is unknown. + if (openEnded && hasReachedEnd && isDeclaredRangeCovered) + this.isStreamComplete = true; + // A stopped read whose controller was aborted is reported as an abort, so the loop can tell a pivot from a stall. + return { isAborted: controller.signal.aborted, isFailed: false, isDestroyed: this.destroyed, isStopped }; + } + + /** + * Records the total size of the file when a response reveals it, and applies a seek that was waiting for it. + * @param {number|null} total - The total size reported by the response, or null when it is unknown. + */ + noteTotal(total) { + // The size is latched on the first response that reports it and never overwritten afterwards: a later response + // that disagrees would mean the file changed under the download, and re-deriving the mapping from it would move + // the playhead and the fraction instead of surfacing the change. + if (Number.isInteger(total) && total >= 0 && this.totalBytes === null) + this.totalBytes = total; + if (this.pendingSeekSeconds !== null && this.totalBytes !== null && this.duration > 0) { + this.targetByte = Math.round(clamp(this.pendingSeekSeconds / this.duration, 0, 1) * this.totalBytes); + this.pendingSeekSeconds = null; + // The waiting seek just landed on a byte position, so a previous drain is stale. + this.isDrained = false; + } + } + + /** + * Gets the exclusive end of the file when it is known, used as the limit of the loop's gap search. + * + * It is the reported total when there is one, or, when the server never reported a total, the end of the stored + * data once an open ended read has proved it (streamComplete). A null result means the end of the file is still + * unknown, so the loop searches open ended. + * @returns {number|null} The exclusive end of the file, or null when it is unknown. + */ + resolveKnownEnd() { + if (this.totalBytes !== null) + return this.totalBytes; + if (this.isStreamComplete) + return this.buffer.getEnd(); + return null; + } + + /** + * Gets the total size used to map bytes to time: the known size, or the downloaded byte count once the whole file + * is in the buffer and the server never reported a size. + * @returns {number|null} The size to map against, or null when it is still unknown. + */ + resolveTotalForMapping() { + if (this.totalBytes !== null && this.totalBytes > 0) + return this.totalBytes; + if (this.isComplete()) + return this.buffer.getByteCount() || null; + return null; + } + + /** + * Reports the current progress to the progress callback. A callback that throws is logged and swallowed, so a + * misbehaving consumer can neither stop the download nor turn its own failure into a download failure. + */ + notifyProgress() { + if (!this.onProgress) + return; + try { + this.onProgress(this.getProgress()); + } catch (error) { + console.error('Audio player: the download progress callback threw.', error); + } + } + + /** + * Marks the download as complete and reports the final progress. A callback that throws is logged and swallowed. + */ + complete() { + const isFirstCompletion = !this.isFinished; + this.isFinished = true; + if (isFirstCompletion) { + // The loop is stopping, so its handle is cleared before the callback: a retry started from onComplete then + // takes the fresh loop path instead of being dropped by a still pending loop promise. + this.loopPromise = null; + this.notifyProgress(); + } + // A completed file can never fill a window that is still missing, so every remaining reader is released, even + // on a later completion call that has no progress or callback left to report. + this.rejectWaiters(this.createWindowUnavailableError()); + if (!isFirstCompletion || !this.onComplete) + return; + try { + this.onComplete(this.getProgress()); + } catch (error) { + console.error('Audio player: the download complete callback threw.', error); + } + } + + /** + * Records a failure and reports it to the error callback. The callback is guarded, so a throwing consumer does not + * escape as a rejected promise from a loop entry point. + * @param {*} error - The failure to record. + */ + fail(error) { + const typed = LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED); + this.error = typed; + // The loop that failed has returned and no byte will append until a restart, so every reader waiting for a byte + // window is released with the failure instead of hanging. The loop handle is cleared before the callback, so a + // retry started from onError is not dropped by the loop promise that is still pending at this point. + this.loopPromise = null; + this.rejectWaiters(typed); + if (!this.onError) + return; + try { + this.onError(typed); + } catch (callbackError) { + console.error('Audio player: the download error callback threw.', callbackError); + } + } + + /** + * Resolves every waiter whose byte window is now available. + */ + resolveWaiters() { + // Called after every append, so a reader is released the moment its window is covered instead of polling the + // buffer. A waiter whose window is still partial stays queued and is checked again after the next chunk. + if (this.waiters.length === 0) + return; + const remaining = []; + for (const waiter of this.waiters) { + if (this.buffer.covers(waiter.offset, waiter.length)) + waiter.resolve(); + else + remaining.push(waiter); + } + this.waiters = remaining; + } + + /** + * Rejects and clears every pending byte window waiter, so a reader never waits for a download that has stopped. + * @param {LuminaAudioPlayer.PlayerError} error - The reason to reject the waiters with. + */ + rejectWaiters(error) { + if (this.waiters.length === 0) + return; + for (const waiter of this.waiters.splice(0)) + waiter.reject(error); + } + + /** + * Builds the single error used whenever a byte window can no longer be filled: a completed file, a loop that + * drained with nothing left to fetch, or a window that was released without ever arriving. Every path that reports + * this outcome uses it, so a consumer sees one consistent code and reason. + * @returns {LuminaAudioPlayer.PlayerError} The window unavailable error, with details.reason === 'window-unavailable'. + */ + createWindowUnavailableError() { + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The requested byte window can no longer be filled.', { reason: 'window-unavailable' }); + } + } + + LuminaAudioPlayer.ByteBufferStore = ByteBufferStore; + LuminaAudioPlayer.TrackDownloader = TrackDownloader; + + /** + * Creates a track downloader. See {@link LuminaAudioPlayer.TrackDownloader} for the options. + * @param {Object} options - The downloader options. + * @returns {LuminaAudioPlayer.TrackDownloader} The created downloader. + */ + LuminaAudioPlayer.createTrackDownloader = function (options) { + return new TrackDownloader(options); + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js index f74f6723..ea66d23c 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js @@ -22,11 +22,15 @@ * The factory also receives a host object that the engine uses to talk back to the controller, so * that the controller stays the single source of truth: * - host.events: the player event bus, for {@link LuminaAudioPlayer.PlayerEvent} values the engine emits itself. + * - host.getPreferences(): the playback preferences of the user the player currently holds, for example the + * 'keep downloading while paused' setting an engine's downloader honors. * - host.reportTime(currentTime, duration): reports the playhead and the known duration. * - host.reportDuration(duration): reports a duration discovered after loading. * - host.reportProgress(downloadedFraction): reports how much of the track has been downloaded, between 0 and 1. * - host.reportEnded(): reports that the current track reached its end. - * - host.reportError(error): reports an engine failure, wrapped into a {@link LuminaAudioPlayer.PlayerError}. + * - host.reportError(error): reports an engine failure, wrapped into a {@link LuminaAudioPlayer.PlayerError}. A download + * engine must forward its downloader's onError here, because the downloader only reports to its own callback and + * never emits on the event bus, so a failure that is not forwarded stays unobserved. * * Registering and selecting an engine * ----------------------------------- diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js index da237cf1..ebc06ce6 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -25,6 +25,10 @@ ENGINE_LOAD_FAILED: 'engine-load-failed', // The engine reported a failure while decoding, buffering or rendering audio. ENGINE_ERROR: 'engine-error', + // The download of a track failed, or was rejected by the stream. + DOWNLOAD_FAILED: 'download-failed', + // The download of a track was intentionally stopped, by an abort or a destroy, so a reader can tell a teardown apart from a stream failure. + DOWNLOAD_ABORTED: 'download-aborted', // The stored playback preferences of the user could not be read. PREFERENCES_LOAD_FAILED: 'preferences-load-failed' }); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js index eb325ddf..2804731d 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js @@ -37,7 +37,7 @@ CAPABILITIES_CHANGED: 'capabilitieschange', // The stored playback preferences of the user were loaded. Payload: the preferences object. PREFERENCES_CHANGED: 'preferenceschange', - // The player bar became visible or hidden. Payload: { visible }. The value is deliberately not 'visibilitychange', + // The player bar became visible or hidden. Payload: { isVisible }. The value is deliberately not 'visibilitychange', // which is the name of the DOM page visibility event, so that the two can never be confused. VISIBILITY_CHANGED: 'barvisibilitychange' }); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js new file mode 100644 index 00000000..d77a2463 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js @@ -0,0 +1,24 @@ +/** + * Shared helpers of the audio player. + * + * This module has no dependency on any other player module, and it is loaded before them, so it is the home of the small + * numeric helpers several modules need. Keeping one implementation here avoids the copies that otherwise drift apart, and + * because this file is a dedicated, dependency free util, no consumer depends on the load order of a feature module such + * as the event bus or the download engine. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Clamps a number into an inclusive range, defaulting a non finite value to the lower bound. + * @param {number} value - The value to clamp. + * @param {number} minimum - The inclusive lower bound. + * @param {number} maximum - The inclusive upper bound. + * @returns {number} The clamped value. + */ + LuminaAudioPlayer.clamp = function clamp(value, minimum, maximum) { + if (!Number.isFinite(value)) + return minimum; + return Math.min(maximum, Math.max(minimum, value)); + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js index fdecfbf3..64b05f4e 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -156,16 +156,15 @@ } /** - * Clamps a number into an inclusive range. + * Clamps a number into an inclusive range, through the shared helper on the namespace. The reference is resolved on + * every call rather than captured at load time, so this module does not depend on the load order of the util. * @param {number} value - The value to clamp. * @param {number} minimum - The inclusive lower bound. * @param {number} maximum - The inclusive upper bound. * @returns {number} The clamped value. */ function clamp(value, minimum, maximum) { - if (!Number.isFinite(value)) - return minimum; - return Math.min(maximum, Math.max(minimum, value)); + return LuminaAudioPlayer.clamp(value, minimum, maximum); } /** @@ -317,6 +316,8 @@ this.duration = 0; this.downloadedFraction = 0; this.volume = 1; + // Boolean state keeps its conventional is/has prefix, except where a public is*() accessor already owns that name: + // isMuted() is that accessor here, so the backing field keeps the participle instead of shadowing the method. this.muted = false; this.lastError = null; this.preferences = { @@ -329,14 +330,14 @@ this.capabilityReport = null; this.capabilitiesReady = null; this.engine = null; - this.available = false; - this.initialized = false; + this.isAvailable = false; + this.isInitialized = false; this.container = null; this.main = null; this.dom = {}; this.descriptorClickHandler = null; this.controlHandlers = []; - this.progressRenderScheduled = false; + this.isProgressRenderScheduled = false; } /** @@ -349,17 +350,17 @@ * @returns {LuminaAudioPlayer.AudioPlayer} This player, for chaining. */ initialize() { - if (this.initialized) + if (this.isInitialized) return this; - this.initialized = true; + this.isInitialized = true; this.container = this.options.container || document.querySelector('.audio-player-container'); this.main = this.options.main || document.querySelector('main'); if (!this.container) { - this.available = false; + this.isAvailable = false; return this; } - this.available = true; + this.isAvailable = true; this.collectDomReferences(); this.bindPlaybackControls(); @@ -421,6 +422,9 @@ * into a play request, so that pages never need a direct reference to the player. */ bindDescriptorDelegation() { + // One listener on the document rather than one per affordance, because the pages and their theme templates are + // swapped in place by the navigation manager and never re-bound, and because a trigger can be rendered at any + // time without the player being told about it. this.descriptorClickHandler = (event) => { if (!(event.target instanceof Element)) return; @@ -441,7 +445,7 @@ */ async playAsync(descriptorInput) { // The player is only available when the layout rendered the bar, so a caller on a page without one is ignored instead of failing. - if (!this.available) + if (!this.isAvailable) return false; const descriptor = createPlayDescriptor(descriptorInput); if (!descriptor) { @@ -451,7 +455,7 @@ // Capability detection runs in the background while the page loads, so the first play waits for its answer instead // of starting a track the browser may not be able to decode. const report = await this.capabilitiesReady; - if (report && !report.supported) { + if (report && !report.isSupported) { this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'The browser is missing a capability the player requires.', { missing: report.missing })); return false; @@ -628,10 +632,10 @@ toggleFullHeight() { if (!this.container) return false; - const expanded = this.container.classList.toggle('full-height'); + const isExpanded = this.container.classList.toggle('full-height'); if (this.main) - this.main.classList.toggle('audio-player-full-height', expanded); - return expanded; + this.main.classList.toggle('audio-player-full-height', isExpanded); + return isExpanded; } /** @@ -661,7 +665,7 @@ if (this.main) this.main.classList.remove('audio-player-not-shown'); if (wasHidden) - this.events.emit(LuminaAudioPlayer.PlayerEvent.VISIBILITY_CHANGED, { visible: true }); + this.events.emit(LuminaAudioPlayer.PlayerEvent.VISIBILITY_CHANGED, { isVisible: true }); } /** @@ -676,7 +680,7 @@ this.container.classList.add('not-shown'); if (this.main) this.main.classList.add('audio-player-not-shown'); - this.events.emit(LuminaAudioPlayer.PlayerEvent.VISIBILITY_CHANGED, { visible: false }); + this.events.emit(LuminaAudioPlayer.PlayerEvent.VISIBILITY_CHANGED, { isVisible: false }); } /** @@ -748,7 +752,8 @@ * @returns {Object} The preferences. */ getPreferences() { - return this.preferences; + // A shallow frozen copy, so a consumer cannot mutate the preferences the player uses. + return Object.freeze({ ...this.preferences }); } /** @@ -944,8 +949,12 @@ * @returns {Object} The engine host. */ createEngineHost() { + // The host is the only channel an engine uses to talk back, so the player stays the single source of truth and + // an engine never reaches into the controller state; a report is routed to the matching handler here. return { events: this.events, + // A shallow frozen copy, so an engine or a test cannot mutate the controller state through the host. + getPreferences: () => Object.freeze({ ...this.preferences }), reportTime: (currentTime, duration) => this.handleEngineTime(currentTime, duration), reportDuration: (duration) => this.handleEngineDuration(duration), reportProgress: (fraction) => this.handleEngineProgress(fraction), @@ -974,6 +983,8 @@ * @param {number} duration - The known duration, in seconds. */ handleEngineDuration(duration) { + // An invalid, non positive or unchanged value is ignored: an engine may report its duration repeatedly, and + // re-rendering or re-emitting for a value that did not move would churn the bar and its subscribers for nothing. const value = Number(duration); if (!Number.isFinite(value) || value <= 0 || value === this.duration) return; @@ -999,11 +1010,11 @@ * high frequency stream of engine reports does not turn into a high frequency stream of DOM writes. */ scheduleProgressRender() { - if (this.progressRenderScheduled) + if (this.isProgressRenderScheduled) return; - this.progressRenderScheduled = true; + this.isProgressRenderScheduled = true; const render = () => { - this.progressRenderScheduled = false; + this.isProgressRenderScheduled = false; this.renderProgress(); this.events.emit(LuminaAudioPlayer.PlayerEvent.TIME_UPDATE, { currentTime: this.currentTime, duration: this.duration }); }; @@ -1030,7 +1041,7 @@ const report = await this.capabilities.detectAsync(); this.capabilityReport = report; this.events.emit(LuminaAudioPlayer.PlayerEvent.CAPABILITIES_CHANGED, report); - if (!report.supported) { + if (!report.isSupported) { this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'The browser is missing a capability the player requires.', { missing: report.missing })); } @@ -1062,7 +1073,8 @@ replayGainMode: settings.replayGainMode || 'Off', streamingQuality: settings.streamingQuality || 'Auto' }; - this.events.emit(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, this.preferences); + // The payload is a frozen copy, so a subscriber that mutates it cannot change the preferences the player uses. + this.events.emit(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, Object.freeze({ ...this.preferences })); } if (playbackState) { if (Number.isFinite(Number(playbackState.volume))) @@ -1077,6 +1089,9 @@ * @returns {Object} The endpoints configuration. */ getConfiguration() { + // Options win, so a composition or a test can inject endpoints; otherwise the global object the layout emits is + // used, and an empty object is returned when neither exists, so a read of a missing endpoint is a no-op rather + // than a crash. return this.options.configuration || window.audioPlayerConfiguration || {}; } @@ -1135,6 +1150,8 @@ * @returns {number} The effective volume, between 0 and 1. */ getEffectiveVolume() { + // Mute is a flag of its own, so the volume is kept untouched and only the value sent to the output is zeroed; + // that is what lets unmuting restore the volume the user had set rather than a default. return this.muted ? 0 : this.volume; } @@ -1151,6 +1168,8 @@ * @param {MouseEvent} event - The click event on the progress bar. */ handleProgressClick(event) { + // Without a track, without a known duration, without the bar, or with a zero width bar there is no position to + // map the click to, and dividing by the width would produce a NaN seek, so the click is ignored instead. if (!this.descriptor || this.duration <= 0 || !this.dom.progress) return; const bounds = this.dom.progress.getBoundingClientRect(); @@ -1227,6 +1246,8 @@ * Renders the three state progress bar: the played part, the downloaded part, and the remainder. */ renderProgress() { + // Only widths are written here, as percentages; the colors, shape and layering of the three states belong to the + // theme's CSS, which selects them through the classes on the bar elements, so the player never hardcodes a look. if (this.dom.currentTime) this.dom.currentTime.textContent = formatTime(this.currentTime); if (this.dom.totalTime) @@ -1243,9 +1264,9 @@ * Renders the play or pause affordance of the transport control. */ renderTransportState() { - const playing = this.state === LuminaAudioPlayer.PlayerState.PLAYING; + const isPlaying = this.state === LuminaAudioPlayer.PlayerState.PLAYING; if (this.dom.playPause) - this.dom.playPause.classList.toggle('is-playing', playing); + this.dom.playPause.classList.toggle('is-playing', isPlaying); } /** From a8e85d067314c9d58368825492691f42d3b033fd Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 16 Oct 2026 10:02:55 +0300 Subject: [PATCH 14/77] Adds the themeable audio player bar and its theming contract. --- docs/technical/theming/Theming.md | 40 +++++- .../Core/Themes/Bundled/editorial-paper.zip | Bin 373601 -> 374932 bytes .../Core/Themes/Bundled/lumina-default.zip | Bin 373064 -> 374395 bytes .../Common/DTO/Themes/ThemeAudioPlayerDto.cs | 23 ++++ .../PresentationWebLayerServices.cs | 2 + .../Core/Themes/ThemeAudioPlayerBuilder.cs | 78 ++++++++++++ .../Core/Themes/ThemeAudioPlayerRenderer.cs | 102 +++++++++++++++ .../Core/Themes/ThemeLayoutRenderer.cs | 24 +++- .../Core/Views/Shared/_AudioPlayer.cshtml | 14 ++- .../Views/Shared/_ThemeLayoutScripts.cshtml | 1 + .../wwwroot/css/site.css | 9 ++ .../wwwroot/js/audio-player/audio-player.js | 119 +++++++++++++++--- .../js/theme-client-template-engine.js | 4 +- .../Core/Themes/ThemeLayoutRendererTests.cs | 4 +- 14 files changed, 392 insertions(+), 28 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAudioPlayerDto.cs create mode 100644 src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs create mode 100644 src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerRenderer.cs diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index b22ec44a..d774e536 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -14,6 +14,7 @@ The web client of Lumina is a themed shell: every page is rendered inside the te - [Template Resolution](#template-resolution) - [The Layout Template (shared/layout)](#the-layout-template-sharedlayout) - [The Audio Player Bar](#the-audio-player-bar) + - [The audio player sub templates](#the-audio-player-sub-templates) - [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu) - [Page Templates](#page-templates) - [The Scripts Section](#the-scripts-section) @@ -162,6 +163,9 @@ Known page keys: | `shared/layout` | The layout that wraps the shell of every page. | | `shared/nav-menu` | The navigation menu of the theme. | | `shared/not-found` | The 404 page. | +| `shared/audio-player` | The audio player bar shell. | +| `shared/audio-player/queue-item` | The queue item of the audio player bar. | +| `shared/audio-player/playlist-item` | The playlist item of the audio player bar. | | `library/written-content-library/book-library/books/index` | The books browsing page. | | `shared/file-system-browser` | The file system browser component shell. | | `shared/file-system-browser/tree-node` | The tree view node of the file system browser. | @@ -225,7 +229,7 @@ The rendered page content, navigation and scripts are inserted unescaped with `{ ### The Audio Player Bar -Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar is hidden until the user starts playback of a track, album or artist, and the global audio player script shows it, expands it and hides it again. The theming work that turns the bar into a theme template (a `shared/audio-player` page key with sub templates) is not part of this contract yet; until it lands, the bar is the application fallback markup, passed in as the `audioPlayer` field. +Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar is hidden until the user starts playback of a track, album or artist, and the global audio player script shows it, expands it and hides it again. The markup comes from the `shared/audio-player` template of the active theme; when the theme does not provide that template, the application renders its own fallback markup, so the player always has a bar to bind to. The bar is fixed to the bottom of the viewport, so the theme owns the room reserved for it on the main content element. A layout must keep these element hooks, which the audio player drives (the two id controls are bound by the global site script, which routes them to the audio player): @@ -235,8 +239,18 @@ The bar is fixed to the bottom of the viewport, so the theme owns the room reser | The bar container | `full-height` class | The bar is expanded to its full height form. | | The main content element | `audio-player-not-shown` class | The bar is hidden, so the content area uses the full height. | | The main content element | `audio-player-full-height` class | The bar is expanded, so the content area gives it the full height. | -| The full height control | `id="audio-player-full-height-toggle"` | Expands or collapses the bar. | -| The close control | `id="audio-player-close"` | Stops playback, and hides the bar while it is condensed. | +| The full height control | `id="audio-player-full-height-toggle"` | A focusable control, such as a `button`, that expands or collapses the bar. | +| The close control | `id="audio-player-close"` | A focusable control, such as a `button`, that stops playback and hides the bar while it is condensed. | + +The `shared/audio-player` template receives the following model: + +| Field | Content | +| --- | --- | +| `appBase` | The absolute base URL of the Web application, used to reference the application scripts. | +| `assetBase` | The base URL of the theme assets, used by the theme template to reference its own assets. | +| `queueItemTemplate` | The raw source of the `shared/audio-player/queue-item` sub template, inlined by the application into a plain text script element. | +| `playlistItemTemplate` | The raw source of the `shared/audio-player/playlist-item` sub template, inlined by the application into a plain text script element. | +| `strings` | The localized strings of the bar, keyed by their resource names. | A theme must reserve the space for the bar itself, as the bundled themes do: @@ -257,7 +271,25 @@ main.audio-player-full-height { The application fallback layout, which renders when the active theme cannot be loaded, reserves the room itself, because the application stylesheet does not position the content area of a theme. A theme that omits the rules above leaves the fixed bar overlapping the bottom of the page. -The markup inside the bar exposes the hook attributes the audio player script binds, such as `data-audio-player-play-pause`, `data-audio-player-progress`, `data-audio-player-current-time` and `data-audio-player-track-name`. A theme that replaces the bar markup must keep those attributes, and the play affordances of the pages use the `data-audio-player-play` trigger attribute. +The markup inside the bar exposes the ten hook attributes the audio player script binds: `data-audio-player-play-pause`, `data-audio-player-progress`, `data-audio-player-progress-played`, `data-audio-player-progress-downloaded`, `data-audio-player-current-time`, `data-audio-player-total-time`, `data-audio-player-track-name`, `data-audio-player-cover-thumbnail`, `data-audio-player-cover-image` and `data-audio-player-queue`. A theme that replaces the bar markup must keep all of them; the part of the bar whose hook is missing stays inert. The play affordances of the pages use the `data-audio-player-play` trigger attribute. + +#### The audio player sub templates + +Like the file system browser, the audio player is split into a shell template and the sub templates of its dynamic content, all provided as mirrored files under `templates/shared/audio-player/`. The shell template inlines the raw source of each sub template into a plain text script element, so that the browser never parses the theme markup into live elements and requests their resources before the player renders them: + +```html + + +``` + +The sub templates are rendered client side by the audio player script with the same Mustache syntax as the server side engine. They receive the following fields: + +| Template | Fields | +| --- | --- | +| `queue-item` | `index` (the one based position in the queue), `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration` (the formatted `m:ss` duration), `durationSeconds`, `coverArtUrl`, `isCurrent`, `isPlayed` and `isLast`. The item root must keep the `audio-player-queue-item` class, the stylesheet hook of a queue item: the player appends the rendered element as-is, so the class is what lets the theme style it. | +| `playlist-item` | `index`, `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration`, `durationSeconds`, `coverArtUrl` and `isCurrent`. The item root must keep the `audio-player-playlist-item` class, the stylesheet hook of a playlist item. Saved playlists do not exist yet, so the shell inlines this sub template for theme authors, but nothing renders it yet; the playlist feature renders the entries of a playlist from it. | + +A theme can omit either sub template: the player then renders that part with its own built-in markup. When a theme replaces the shell, it must keep the two plain text script element ids above, the element hooks of the bar, and the `audio-player-container`, `not-shown` and `full-height` classes the player toggles. ### The Navigation Template (shared/nav-menu) diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index 7fd8df7e1038f8cc438c5349992a03a783b47139..8085208a85d9cd4f3f449750f4066d812f6d7774 100644 GIT binary patch delta 5831 zcma)A2~dr0TEf;g9a4|LBv6uVUb}` zKvo@fa1Ce_B1DC+CQ$@IBICesC>x-T|C$y;h?WY zqiZ&LO~0f=5JyK5gtf5gojEEOQOc5!35_}!*ns9R8v12>^syxO(w-4`FuLtKE*_M3 z>M(=L@6s?>x>%jnhTW37n6l1d+tN4AtO^X17R_LNH;mSl+OA-k8sgFUMAipJ*C&=0 z%IKcWW~pN@qz#p<4kL`Ky2h$eR;N8bs21n8VmLuq*do?MmZh}t7AtNz#u#_A)-zoD zNp=FZUZiitW~dD9*i}3XYxH6_8Q_sPh<%!Ia_Kg95o3sh*n1h-zA|<%4qdwUGCP6M zP;X%`)55x8FWH$4PKm?eGBynKIcyDjw#e9mV})V7xtz&rc;vr?)5*ZR!Z{NeKNELw z4l`y)XK_?DG0wS^bDJ@%eu?AvHI}XW%+X$rM+pI>4o(HBD3G+kxqxZ~WDA}Y2a#4x z>RbyZd3aL#GL+O{Mtx!A6=t?Bg3M<|;gRG$oPAP{STcnnzPpKBL1I3a?W8p`66_>9 zm|2hAq%1wv63N||MH0;OVAAuXd9os{DVb)|$4F*4@EJ=sC8VPYp4&546FVdkIWqo8 zR*mmvoCuJR?q)OyrSB#G#6IxGQ|GMlX!dqWqOUsOFiFoUQ-NdfT&o`yWP(R!x5+ci z@`ZGg-p28C%6Kf=)9A(~h&DxnFoUBQBZycZzA8o#?GPQZYJ*^n!>ZUdp^R+-jT0UhtA-S67B^Ul+uo=KcE2ot zxJ*o}ON$gcR>tgH-lrC$cG2zay};D<;Xbp+iKo|Gov4xGd&w=#_Q1Zdv6-Kj_w5vQ$)J_SGUi;wMtMA#1bZ+?z+yYm-R2Pqymilw8 z%SIW#zx@?mwm_f?@l$9Xl_v7d`sJx6{uAhUNUte>&>0~H@-rzfP9Bvv;KOYAaT*I zw5ZSXk2P;J8*N#fnBLyr7^wyr+#zWQxB z_U3CQUV%p3by^zpTkgC5>2X{^aNox!__74{|%Kkkxv z7^2!fyPOtJi}+90iTs?jXRo?9tC&04syC#r+IjPG^rw+upMG?`fD^rU>&)zsjQTO< z`d%Lr-}{S?m@c<=SA0-7^(zC_`qH4^JPrhOY~$wHJlpoQGAHiE7@NubM@ENke;>Za zzAbEYXqRM%<_Z4n9xL}B6%st>eBJ&zHz6#&Aoa!1Wm)lb<&XbT`u)7W$vC$Yvab*R z$NsM@bfA+lJTyASE)=pA=j6eZaq5?OYBPJY*-eH~tV_)$byYiR$5?1NPZvb>PRl=b z|JatE5AXjiX(*nikpIo}z|o!a65Z?*@E^~y#va@n#Wh}UZiE9 zwpeLnLeyw%bvN(hw;={DRxc9+roFm;{c_)kqi$Xbau}PDY$OK%;(bmJ{b6i+La!IC?p<`n51r}+E$c0R84ap*JF?Eig zL%Oh(=&Ca#K%)wI6_dR9j~eD{6&uo83O&>8ciZ&pRKGFn(Qd3TU;4Rshx-V(o!8H7 z%(yqB@R&&J?XLNL-#<@zb8lWwgg5nKlwRFui|ARt8hS3`hE%?LU3{poSJcw0wtvmL zn(*+D%5VQhihmqv7Tuj-ZM4QTv~7B-vx8$%b8@cd`ZPtq+;b%tT%Z1W*{|kIKx}nf zmhkapv2}_5 z-0k3>+EgjYkJP*ITn@E&%TV(0BlfAd*?azb2d54rYFR zN9#%jMGzwmA(P}3v^mHjgBrb(rWHPaxa|g1@Ud(GII)V`3uL z*#|~P4>nToR}qv3UUh<3(DV%W-l(F$bjp<8PISJK8qTTa66kIv#lvRz*Y9ng3_8b^ z2b&FnwUL=!6S^uqGWeg&K5NUVw*;>jst||U81HjXu*({2$=ZG=y~J=W9;ZUS{St+gf>GQ_4SUbXMvRr=*;A; zY}tjad_-zUGgIcMNhUB|$-wmfFvj%TXyLp{jJ|nEd58(CCwph|xddSkJ2+Y{kY5`x zlXez`+bU$81xzb`$4srA>O+`jlWR}8gR}c!N$ASe|801TnSRQmaC?d#&`b&+u+Su1 zCY+oN!lztRn?sqQE!h-qJWw_*Jz~yC?`2cCSw`<^>7sFr)Fp?)9U$_~0qMOtwA37> z=1|&rr#45=y?F-Qx&Urj_4@>)zEw2T0(B>{NaTK4cGeVD3oDGZAu)IaF-{KuDUQbT zF>B6liQQE|{RyW_KG@JC#(~akmfDat(rUBXBLbCTcp%uzk#EUn)IL?RxQB9OJF1Zj z5v`QcGiGRBE~SHQ_xI||mDkT>R*QD#QmzMp+_COby4- z-%q-DI>RGJ3bn;i4$ALgph05F2tyl2DPAvvxGzEwu5!>T3MeffSUru{M(BZ97Qrj9 z!LB!?r>xP0JPJ3FXkH#jw@zZD>3P&h%zek|ZgUv8(K2#yT;2;9=!ZN?4@2+q>P{^M z7knUP<%3fSWuQy*DFX~W__}@1Bw)P+`!5eYkw8P;Fv@9u{+1%BCdW+(VuD;;Q$!5m z@B-NqI7KBt9dAGo(WV43UJg33ih&utodn-};>jEj~##bEVCWeDD?kJ^eN?#mFEmq$a zLcwSPKjgEYJ5z>DJ}Qgx=yw~&bOE*y@=!kIKQ2KvM=AUkLw!fVkaGkF^<+|}$hC;l z$A%oQ=KB5wx6=>91{c6z6J^+?S)8Gj_IMG{{efhV?jj1mkdaC;h%Z!Nu^yUIEGs=r zX|eGOnfQldndc|MBO+VinpmPh5U@c5K1VN9TTJ0c66ykF_8cG7UP9@hktLKa&L_o; zv%DhExDWrZNCUq0^BJh1gu*Xfw7mofAj5$`7gYcYCYZV=x$^~FuB*wx1e+Jq(9w9; z)Q*8}_9BK+V=bwLypGAzZUsG6v4olW;TSax(?+bByD}JPwIMFv0IvulZW#l87C~wZ zsav%MVSQrgCp=XLs|{a)v`Q&^Ox`3kJm~`$yARx}W^&~3Rx#w^vEZUdF{Nfgr;%gx z!pKn&Ung`M@@-8L@}*bf<0euKT`!eIbiWiLdK!v+%b*&LD3k4y-Hw;d`C#-Y?2`Ot zuDgzgI$_sh+?uYXK-^pi0&;1<_b!TYOwiiY>gKlDcE98HH(N%T9=;SBjeOOBBS9{C)Ht-h~J8KZ#llm>cQA=~fH6R;5xkC}O6 z2{jgZmQyO2uYE*VxAGW*i1>vd_ycSbgw3Zfe0Kd*J7}sjD>Uu|u>5jDR^2XEf%N?> zTB?g)RmrXbmdb~VU2xv->?4R-a@?o=80d}Lq%GPHUjO6oApI&zTdDu!SCK(o;*b|@ zKVQ=JL41aTe`fjez(uVUl>SUQp9ViD`{|Z^JBV%w8-874DxA|9DLz6z#9rQo{--lJvSWVA>dxW1^fw^**dH1H&dQ{M^$8(>y3j&T_CL zsTgL74(CGQm|H2!jOFy3;>mv5+ygPGj>`X@t1O4P+i4Us6_Lj1Ik)jlpx|inPLk~ delta 4711 zcmZu#2~?Cv67K(KMvh^)Z-fznRW4CuB3_WhM1=%A;{g#6bU_gbheslasKAOSA+Z4& zZiArQ>O@4Mxt7&Uj6}^7@p&c00~3wrTGz1kcmL`Pv(4kZqWY_^s;jH3`{#oPcGm~& zlo6qVXoC=TX(={BnbDqOXHi%m^-dT2#80e)AgMjMeX&Y>W! zW`np>Ax&z1wunPa=eJFqLAkVbyG09Tp)C@>V7jbg@pmj)v?=qL#}aNE6WoNGbf!Z! z?k!vDF=6I48!Ch?4X~p^<~k#$$=x=~#u8|v-W>2PnQDhnpc_H~#p=f%?3aspy`?#8}Tl=e$ z>$Ii58t#m`y+VnQmj^=QNJ=0#nry1XD(yoLE{RfVR|Ilf?IkbTTeCQ|Bb7|na|w*e zES7sr!`EiybLQ4`Hn*I+;Y6i1TJEGVl>$z2_0Ckf)X%MB7GV##92Uiy(TcC@A=+*y zgr?IKN7v$!TD5|2V{R@u@~!UFJTHhp=Rl>%`TS9uRIP0SU(XzVlEddQ-JDYXcbYEk ztF3$vvpC(uFSVq$-hF%-!+riUuVi7L=LKFR&DLMC6uc>{|0Q9H8I_!73WE%0yhM1B z#s5l@P{G`OpDUPJ(0rEPn^LqJ_O2TC&WEm~uo0VT{Y!*W7R~8qA!;h69D7%=ilx$w zH$-bzX$vDnPg-AO^E|PiPDaiby;-5{SRlHy;%itWs+e?q@zXNQSt`~r+}|R_%e3sY zMzP{9M!Yv(j1(!~uLof>A-+Qm+IM4iT*#w6_^x0#+q>fnWs}hem(0+phN`wMGM8ZYtY1_f ziHb9edh0@qzMk3m$ok{oMm@0l_u5fQ{`!4On`=n+*T>eEJbbmTvDESp)BT+`7o6`+ z(gay-a2d5mDq45t+b-=PvLo^Y1tO4P2Mh!HxYi$57llg6=#p4 zlHzrI%#KQ*Md5H)D!ueXTrrkPU0vewF;uGX#w*>Zv}r)>uyf{k8}zJ&MHSz<`QBL` zp+przmSjc=c9;~Ko|cxp)_+B6YDB0$xF@Q4Wf6zapn#AybiwE2FP@~7V)b&V9qj4J zyFLXFZN@{{XF0k14i9ygpYc)+uzagP$Ww;{p-ryE)BU{3ZD4Vi!u{js#Uuv^ zcakYW_Ik*r?qqqo=t%Cg$PWK(0f+S-C)iB1WmV(mYn_xe|Xt@2xafqnfu$x+PWAvNi zNg2Ry!XhkmoFG&%9+8+f>?)lUlHCUJEtrT%WgDg~odlM^a^4Igl_l7Y#K9jlA7SAZ zC&Pg5GSIo|(OsG%L47FOSCVb?v|@k3#US_Zt~B;k+9FgY-6?tuuf0-yy~LjQ?!#Wx zSE=jPlci9M(Jl!2>LIHZ19DVx*-SH1wNFle%Rca#lO#=$pFpO8n3aR_NDf7}tTQ$U zW^Q;&4+kzvoQJ#UCe-NTZDypoTy}9nVlzGj6M@83BP*RWpnU&RP!uZxLCW<#)rkPkmSqoaRPqt*c> zNv@FN%B+AK%rWOkNCh5EPF7&r^~ohk?W?A058_lQ?|)DwsBcf=NOn0^lZ}xkTwDBL1twQm)+W(62q-0TVk?g;PC@djuo-ov+1}yzB{+HnSGRt8n#yH^`g~4l zut9UHA@1%L8M3Du)0>nuN$T3uvRb3%6b2!FXqFKY366llQ)<)pbo2P#a;C7>s<}Uu7Bk4Sc_LO=-xUx)V4Yx2z!rd=OpkdgG&7H z;q@IsK=vu@%>=!L|F)NzE!;0Rj0y8tU-+?Q{Vy zf?)ZaHo|QGviXCg8l|Zu5gUVsqns?Oj(rC3|?bF-i%w;JW_M^|>H z_QfEy^B=?SnwY<2gYdh8vB9xyUz3#F54Y-KxEW!ibw)3#4PC2X|s=^3`!mCCfwLF=T&xsTb8`QNXa6c`bAuO8Zt7BX< zXusOPw9(CS5xgsDeK#}h!Dc*~I`-RgueS!C4j;kR=s&y`XFr3g0yF&Atu=V?q=lS2 zy$hD6guwNmV$-%W+l4Kdex#8^=_xj}gK5iJF#T#IChefj%_H9JcoaRT4~{^gX6B1T zbrescHG0Hnb*L+(ZkA$r>4>Ew*`vi{s9~2D443T_NuL(`P{RzhXU!1gTL5F|bUI_a zMkMZgvAbcJ=G)#c0iY|a=|vp_gw|GwBtQ$7K*3Qwk~(ZUDmko_)wgzIOM^pgDaE9z zqLAP$_|%Eo+;P!63liN5eN_KJzO!0<`qW;LoD`cJo4jH8WBchR(s78)4I+g1w$7Mx zKtySOk57vCPfSf-t9y0B2T4@-hM?YgBf#Q-4?@s1bjHYrXP#3N(&C4Eg^w804Np;i zeh0bShJB?k6Ef5RE33R9lC};wq~i|b5H+ZyIFrZSKf(FFScuSTIxY}eHuxOtORC%9 zR7(ceT~^;W9*a=YSMc8mJ%c7=Qgj&GkgHvyE7|Zwv>*-baI_`oVN%gpPkc7-OQ+l< zKH&-fqY^f|V;}slK#%Vn*>f1W4A8ldYaMV;NpL$d^+`0`gy$Cyzo&vWKcjagodcq! WT|_8`jYB93e&&OVKZ>E~(flVo`-y47jl)4rHH)3pp! z{D({!c`=5x$)F7N=M{zi=XZWT|GIU3uFuo=Sg!( zE31#P;(s#kG{(}ai zDGv0-4YUyTE)gGPb&o~h!ODClp8Q0S^)+P-dk2bqNHcIKkLHW*a`8LLC|ad1v!mJC z7*=U49PBp*f928B#IE&tsW!6rq7`qJMO4jQyka_{*1g8}us&J|A^}BJu~L&zLCn>b zM58{Us1-!JCZZk&5>0IIr}q;Ttlmjm$b?cu^@)VKWt}60A z>vmZ)xp^VN&U_-3w;}4HAEkndLEOHTGC_L}J_b-7i1{#(GGmK}*iPvqrr0EiQedfh zA=GaycPx}DVX3m6)MFZ@yIrXDlQ)TB-qOG>h|&NXt7s+h&k>X_iP-jczuRq0Vc07f zaP||a3eHr~3SyUilnsSEhsRPDER`Qe^|Ar}kU(*z{B0tYi2R9m=zFlG{FBj1X+~4z zYB|Ot-`YB}F?m-|_Hu}K)J_qFF3PqaMyEuac$RWEWO(4_QR*FXz0{t*Xo0A(SX!jc zn{eL5UD9;GOcX!)nRw3E!!S`U@V2MtfS(#^Me&;NX$?K3+WsHvJe&07erlDj5>uWY zK1XjZCNQi^8p8}hdlID@w>2s-c(?VQu&ptIy*5FSJHztVwWK}Pm%sF8eWjCaZr<$U zw)xSIVk`D-Q_Z!I(iq%6JNr{CJwMd! zK}LIlXR`WFLpQ(qyOI}FrdZi#R@C*L7clrw-BaHpY}e`CMfMGm@telv<09oRFaGd2 zAazfex7)0uCC%67DI~AHvN+T#EhW@0=gS7a&oTHlDcgvlp6>I@quYI&{=33PRb6P^ za29J>v?C&<`}a2|2p^SueuBjT+Z@hSnu}}v_!hP1NwPb(@PDh*J>B#?T1ELm{p<&B zzO}3WxU+HXrbru2V?)xSDCQ(DE3VkH&3(wL>-9Gvq#$dbP{$#q`cz`7fk<)hw3vI! ztMLG(val+bdHDMWCGS@Yz5GjT|IGdGNP@^gxxu8h*e}ZHrlGlMWm0-iPrH*#epZIC zLe$}vu6J>{>G0riubEs=^7D`;`O>Dqu&WPyXZ|w0EZptN<>Agd-#SE{vrO}j>&rFJ z>b&cs_h6_~kf8gs*hz1#edo5ck#ipgYgJk-@?w71^9s=B?^04&)A7XVoyS=z!4q%G ztP4IH(w~do`t(1#R3>~A_|_=rdmFu{pN@z;v_Q+4b$*AZ$!Cis=ls(z-wejc8O^qu z)|R?8{?65i&odS__1!KdBaX!`%?rwkYn@rA?lqb;;#X8|u*t$*y1UF}z9z4=X8S{r zH2>ZM{9?L=Cvhek*KSJYPNDpj&> z$;orsi>}VTA0RNE+xpUA@8SzhzH56r)zV~lD4yMt=%b`5zg}ivLil|{>8{=vpGvMR zod2l!)1e?u2eW^Y{9WJNzI}B}=j=NFj^FS7@-blV+|n(6lIxjO7%80!*P)GLnDx|S zWE&nOh!RW)KV>}pzj}!yeni2bDuR7aaFXx|{Ui{W7amljoBkysCzU>xk@NQerXUt4UOX0_qMw z9#l)`+9ZD^pUfEqxMJD}FGy|^%&y2p0A=v>MH zmtp$N;YD}>IC6$EiIdxWK{h3&_e)s)oKs~c?ls;cUALr{Yur%2eLm*R_Bzd{m-YN# z;Lq;|#az#ETy63+W8g1yPq*V5w;TtS%PIgIY!}NEO`pYG{A~?rH!TA#IFY*$N?Gr7bLy(+6QfF3MO2G_;1G z8mJS}GmzxsOb8No0MErWKvX7eiqHZE{eCHf8iFU8w5C22UTr{m+%q){Gnj#4w&Sru z%Gno*3O|M_SWQaU=H`7~ORm7xoH52Q3kj|8J*<}H53(R1zRi&9S^!<|Kf=0(FE-Zo z%D=6$7OG>|EO?_yy8bPTH4;}n)wPmJW}mALh8e@QBI$Z%1M8q9i$-r6a3Kr2{j-fl zKW5SBxdIfknLPZ(qN}oL^mGAX47&Gk*00qEJ~)?6%cBehzH`zC@PX&71&_YOTBSx= zBhB(S-+FS2zPm|?!(d`{VPa=XsJ-ChAYKoj1N=%j7gha+F9Y}(W@^NC%W?5?BT$q> zJE1K0>WF7BBFOpc3Kord$|i1nh+W?8@B?f$IFpZ0}z!p^B^32oP*&j7rlr<4g>Gc<6!u_)kZ~ctMp^jAz2LD zG;MMmTg05~H~E}H&wOaYumuNOEeR9QeHWJpIr&`SR584p9USi!^A~gK7EnFz|0u1Z%0TfHpiXi-B0;f`3 zM5D(!_=SNNWpnVCYGN8tEap`7iXm@aBggyDLhuzPRRD-*L@u==5fji@0-JftBN$Eh zR~v5_0qsW<1qKEPEmVvsxjRdsfcVY0z&r%^Gw^kSWRr^wyOeUp;a>`QH~i9S;s|iWp`kkrVKXIs%-u;c2hIQt9wOy{Z8_(|sT|t*Gl}CJET=V*oxFb* zoKA&psTj5;O9?yA04G~mMe?R(euy!5sUC@_fzW1>4??OqS1xBDPj`UhwS9uiIdF#K zon(0SUKA6e8tC?;WTv!Rxf{8I9C}?aE)Pk zKCBzJAWCUU%-E&!H7QVyPh%Kt*AqVV8(6iCArucBs^rp;TnU{=`?9P{@DEgVj~R6O z_bke*;!q1n;2*)z85k!V@z@R(13}`rfEBH(;x3uDmREb9!N?!LD_HWnco7VGs%W;j zr&mK=)m;o=2z;w)G#!Io4EiygwOCM1E2DfI`S-=WE8)W4!>{DRE=I7TPpfJ4%K^9z zZ)b8z6a`+vOB@x~tepC2AGnKrcq_nKo$xvJFAB^`=XPRKI#ir-m;y2B-0fe)Ao@or za5LfO{i79R;oq7Jl}Jr{dl^40D+fHinh=A=xE>-$0{@ z7o;#I0!9%$AM`bFg)~0BVwjVJi5n(hknslRSsmoJvu;UU#PaH~uw(b=K+D@5_Cw12;W6ik9 zme@)5v?m)JpK`#eMp|td6Q9IbF>VY}rw&ZAH^m$~av)o1C!K3x9zqV%V5opHQAJbK zr0_vZEfg92Hxe-gmuk89VkZMXN#@}D`IOR>3-LTDFwKWyMZuz%e9h>kBE30NR0@}6b&{4N_R>N?Pit`kVb=sY)TL4)^a;+#l+{BP6Llx+RBy58#858 s!ElUWIC2tsi_U;~3li)U*n~vv-sSB{!*h>eTj0ML`mmNVVK>754?sh=&Hw-a delta 4416 zcmZWs2~<=^7OmgEN)~ArS!A`lSp`LKjUbVrGAd|nmx!`tL70fBh-frAK_iG5cZj}5 zS&Slx0)n7FMiVthCydKX!X%!!jiX7-L{Z}yH4_pu@7Mo^{_r`R^Ukez-%|DJ)$7g< zkG5MLdUK*k-3TGJB-b&xh1qrLL|G6WP6}LD>h`9{g&Td7l%*)|M}0UF5q_N`l6fgj z;7U@(a=O7rUX%u`roSs#cp;7DwxsGU)LCIj+vrm!>ox0(6+afCP!SB`H+-eVDKg2O z`^k#`w;LBGB}aI0A%9UX1zA@(!OaEDq`iE5pe4qGkiiB*B1%o20WD(LD~fW;p(0<- z`u6-9y<+gPt0Jtrz0J*0rf2*#+6a9JiS>ea*9*Zd<2oC8j?!bj@R2+BPyGmMl-#p)wTjo11-fDdODNMl<=Z8VYtj`c zjB{(<`xmsS|Zh@@nm67cqpZT^lKma^RA8yx5_r+07PTP?8wC zK&({Ue!EWW?aVi|{NAW-TkzOEz+)RAry~Ve#A+pwbB$tJ47V0`SL~C{rP#^TRjI01 z%ruDC61+2wUgL|Y(`krOXhk!qQ7N>#nbb*WN7r&I@Y^x^6DKTthZXQGk-WFE>5AJ$CG1PZ z+4%QaluFph?r_4LO-#8OFmMaID|$=}X*sKJ=w<7hpO_{N2@Qqf?JQ{3dxNgi@#Aw> zjY#sI&|XsgO8?&;+!m`hWY~Rw?ZmQ{85?tNJdXTn^`m)BCo(5j>@RtE?s3NZ`#wIi zA=q#Eh#d|k$1^``ObNL;s`jtu;D^2M4r{w~;oZO&htDcLZcMP$eD1Vx=pDx)@fS~y zIN|bUZj5_O^ac9|g}rSf_tp@@7k%Oy`ZEhR98oWATEEHJ>7j(2 zIRQ6=*f3b##GIwE$Lah~u6QYk{n@~!!{5>t551ssBY!k2hz91PBLtFw8RYGRw`Jg& z4t4-DaiCKMPEqi*s2b501j1}f@AvhD91G*c3i&cvXb-zAY#^tdlYtd}rK7_`z_Co# zy4-+ZvJqZeO1;3TQAPVTB3c^&^~5DzK>l;3RKw%>b zs;}AmL$ji%Ik{7XLZsvl_LG$vu2X`yBRiA)9e#QW?rCEJNBe(emfn^7CFv?yg zO>sUo2^FuRqMwx-AuiFSwSr+_cgv41xtwjpu=;rsf^Ev`vy1{KVEuX4er33G`EjK; zEqzOeM|wl{^Nn61FMK@{7yL_i#ydb%xf)3QoPDdlb0@^q4|}|oRYHzu!^1N6BDXtu zC(`e|E7M`oPUg;Ym^vl5O~A^r_z*HsLw&NHJNmHDp+_E?H$_8=JAkCY5V=dOg4kW? z^V}%}17OuI=Ei-7d|w%0=+m$B=)OWt9&(3F|N0IG2b42!P9IO_9hrzB zZ}uf5TtmPARMsqQx~=a~ab53NchVXM0Zx~*XzuV?IaXYTfg=GBTfzJ|{8|OVrr{hm zL1hKw?N%8PXOocd30coI^I)f1u#FezEpom$EGD*z`d(ZtF;74EEL ze%!>{d6ParhBQZsoQl2 zmpynUPZL!=^Bxw&ZC(nw(w>b`U&Gs~-Kz5$);2%c!`wOHs`0ZUv+)qkcv-Z2RJg*L zFgZ)-0R8tqKaoc_i=xrZr&vN-)}ZZOELT|noG^6So)xt?ax~+}F)NM8~E2= z#-|nN+>80OoVH&3OOs9yFITHYnO2PoQCCz2K9B9LR=eDJd2PqtZfmZPb4BL`;Wes- ziTkht3>9G8e&(;7B^q#rs(mbw_ky^e&*oHNjoM)eP0++V)~!3qw?@6qF*Rs(LO}QR zk{b0|H_PjZ3CjA9HH;5^(7P7V^)szlQ{qLt9=)+<&El~8*x0JEptUz{`8+G`=-Hxu z53cn=hiS4ooUd?&{fy6m;JqKCnO-KNfsleI-ww^xs4?(Hova$gyV*sV8+A$sJa*JE zK97TM9fD=QauBA}sik*#{(_uqI7-aI_ZI8O>T7(J$~Vj%cGjuQx*079XTVg?+~6jH zymoCY9~o`gkr_z({Nkg1+?q2mCHMb17J|ia(#;9QV`>w2;W-uIzF=>&`bx^MSdOp(JfsJ*k*r-DaRuX1 zwE!bp5#Co$VR9=Q$0LiL@$BJ!v|_{p9ARaRkdg`>SuhwkGZ*-wRo(1kVrFm!DlWw! zv@P$;N|g|E1e+KBoPdvT0v125qVP2^W7qGBxTDO&Z*dJJ&!@wjh1P8yhk3XwPqt%g z!S)b7*7B_W$kFq(GZsQpefPYVH)EDSwUeMsxw749RucBwCrN~i*Q9plpI~mnn(mj% z2EyieW(SiFMG<8yE$Zp16(f*XcU&b0= zBZqK8BDcOmHt{5dBN6afGd4rnX;l-#udVE|Y-?DUk-2=(+$9U$2 JUkP3$@_+4tli~mX diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAudioPlayerDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAudioPlayerDto.cs new file mode 100644 index 00000000..923565b8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAudioPlayerDto.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the model available to the themed audio player template. +/// +/// The absolute base URL of the Web application, used to reference application scripts from the theme template. +/// The base URL of the theme assets, used by the theme template to reference its own assets. +/// The raw template source of a queue item, rendered client side for each track of the play context. +/// The raw template source of a playlist item, rendered client side for each entry of a saved playlist. +/// The localized strings of the audio player, keyed by resource name. +[DebuggerDisplay("AssetBase: {AssetBase}")] +public sealed record ThemeAudioPlayerDto( + string AppBase, + string AssetBase, + string QueueItemTemplate, + string PlaylistItemTemplate, + IReadOnlyDictionary Strings +); diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 8c424fe3..1f78ce97 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -351,6 +351,8 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs new file mode 100644 index 00000000..6f00a28f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Builds the audio player model for the themed component template, resolving the localized strings and theme asset URLs server side. +/// +public sealed class ThemeAudioPlayerBuilder +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Shared._Layout"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory used to create the localizer of the audio player resources. + /// Injected accessor for the current HTTP context. + public ThemeAudioPlayerBuilder(IStringLocalizerFactory stringLocalizerFactory, IHttpContextAccessor httpContextAccessor) + { + _httpContextAccessor = httpContextAccessor; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Builds the model of the audio player for the given theme. + /// + /// The base URL of the assets of the active theme. + /// The raw template source of a queue item, or an empty string when the theme does not provide one. + /// The raw template source of a playlist item, or an empty string when the theme does not provide one. + /// The model available to the themed audio player template. + public ThemeAudioPlayerDto Build(string assetBase, string queueItemTemplate, string playlistItemTemplate) + { + Dictionary strings = new() + { + ["toggleFullHeight"] = Localize("ToggleFullHeight"), + ["toggleVisibility"] = Localize("ToggleVisibility") + }; + + return new ThemeAudioPlayerDto( + AppBase: GetAppBaseUrl(), + AssetBase: assetBase, + QueueItemTemplate: queueItemTemplate, + PlaylistItemTemplate: playlistItemTemplate, + Strings: strings); + } + + /// + /// Gets the absolute base URL of the current Web application request, used to reference the application scripts from a static theme template. + /// + /// The absolute base URL with a trailing slash, or an empty string when the current HTTP context is unavailable. + private string GetAppBaseUrl() + { + HttpRequest? request = _httpContextAccessor.HttpContext?.Request; + if (request is null) + return string.Empty; + + return $"{request.Scheme}://{request.Host}{request.PathBase}/"; + } + + /// + /// Resolves a localized audio player string. + /// + /// The resource key of the string. + /// The localized string. + private string Localize(string key) + { + return _localizer[key].Value; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerRenderer.cs new file mode 100644 index 00000000..f7b71542 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerRenderer.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Renders the audio player bar with a theme, inlining the sub templates of its dynamic content so that the client script can render queue items and playlist items from theme markup. +/// +public class ThemeAudioPlayerRenderer +{ + // The page keys mirror the template files of the theme packs, pinned in each theme manifest so that a missing sub template does not resolve to the component shell template. + private const string SHELL_PAGE_KEY = "shared/audio-player"; + private const string QUEUE_ITEM_PAGE_KEY = "shared/audio-player/queue-item"; + private const string PLAYLIST_ITEM_PAGE_KEY = "shared/audio-player/playlist-item"; + + private readonly ThemeService _themeService; + private readonly ThemeTemplateEngine _templateEngine; + private readonly ThemeAudioPlayerBuilder _builder; + + /// + /// Initializes a new instance of the class. + /// + /// The service that resolves the render documents. + /// The template engine used to render the component shell template. + /// The builder used to produce the component model. + public ThemeAudioPlayerRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, ThemeAudioPlayerBuilder builder) + { + _themeService = themeService; + _templateEngine = templateEngine; + _builder = builder; + } + + /// + /// Renders the themed audio player bar with the specified theme. + /// + /// The manifest id of the theme to render the bar with, normally the theme the layout was resolved with. + /// Cancellation token that can be used to stop the execution. + /// An containing either the component HTML, or an error. + public virtual async Task> RenderAsync(string themeId, CancellationToken cancellationToken) + { + try + { + ThemeRenderDocumentDto shellDocument = await _themeService.GetRenderDocumentAsync(SHELL_PAGE_KEY, themeId, cancellationToken).ConfigureAwait(false); + string assetBase = $"/theme-assets/{themeId}/assets"; + + string queueItemTemplate = await GetSubTemplateAsync(themeId, shellDocument.Template, QUEUE_ITEM_PAGE_KEY, cancellationToken).ConfigureAwait(false); + string playlistItemTemplate = await GetSubTemplateAsync(themeId, shellDocument.Template, PLAYLIST_ITEM_PAGE_KEY, cancellationToken).ConfigureAwait(false); + + ThemeAudioPlayerDto model = _builder.Build(assetBase, queueItemTemplate, playlistItemTemplate); + Result renderResult = _templateEngine.RenderPage(shellDocument.Template, model); + if (renderResult.IsFailure) + return renderResult.Errors; + + return renderResult.Value.Content + renderResult.Value.Script; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + // The audio player bar is best effort: when the component template of the active theme cannot be loaded or rendered, the application Razor fallback is rendered instead. + return Error.NotFound(code: "Theme.Template.Unavailable", description: "The audio player theme template could not be loaded."); + } + } + + /// + /// Gets the raw template source of an audio player sub template, degrading to an empty string when the theme does not provide one. + /// + /// The manifest id of the active theme. + /// The raw template source of the component shell, used to detect the mirrored resolution falling back to the shell when a sub template is missing. + /// The page key of the sub template. + /// Cancellation token that can be used to stop the execution. + /// The raw template source, or an empty string when the theme does not provide the template. + private async Task GetSubTemplateAsync(string themeId, string shellTemplate, string pageKey, CancellationToken cancellationToken) + { + try + { + ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(pageKey, themeId, cancellationToken).ConfigureAwait(false); + // When the theme does not ship the sub template, the mirrored template resolution walks up the path scopes + // and returns the component shell template instead, which the client script must not render as dynamic content. + if (string.Equals(document.Template, shellTemplate, StringComparison.Ordinal)) + return string.Empty; + + return document.Template; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + // Each sub template is best effort: when the theme omits one, the client script renders that part with its built-in markup instead. + return string.Empty; + } + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs index ecb86226..119d6a21 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs @@ -22,6 +22,7 @@ public class ThemeLayoutRenderer private readonly ThemeTemplateEngine _templateEngine; private readonly RazorViewToStringRenderer _viewRenderer; private readonly ThemeNavBuilder _navBuilder; + private readonly ThemeAudioPlayerRenderer _audioPlayerRenderer; private readonly IHttpContextAccessor _httpContextAccessor; /// @@ -31,13 +32,15 @@ public class ThemeLayoutRenderer /// The template engine used to render the documents. /// The renderer used to produce the application chrome fragments. /// The builder used to produce the navigation menu model. + /// The renderer used to produce the themed audio player bar. /// Injected accessor for the current HTTP context. - public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, IHttpContextAccessor httpContextAccessor) + public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, ThemeAudioPlayerRenderer audioPlayerRenderer, IHttpContextAccessor httpContextAccessor) { _themeService = themeService; _templateEngine = templateEngine; _viewRenderer = viewRenderer; _navBuilder = navBuilder; + _audioPlayerRenderer = audioPlayerRenderer; _httpContextAccessor = httpContextAccessor; } @@ -58,7 +61,7 @@ public class ThemeLayoutRenderer string appHead = await _viewRenderer.RenderPartialAsync("_ThemeLayoutHead", cancellationToken); string nav = await RenderNavAsync(themeId, cancellationToken); - string audioPlayer = isAuthenticated ? await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken) : string.Empty; + string audioPlayer = isAuthenticated ? await RenderAudioPlayerAsync(themeId, cancellationToken) : string.Empty; string appScripts = await _viewRenderer.RenderPartialAsync("_ThemeLayoutScripts", cancellationToken); ThemeLayoutModelDto layoutModel = new( @@ -119,4 +122,21 @@ public class ThemeLayoutRenderer return await _viewRenderer.RenderPartialAsync("_NavMenu", cancellationToken); } + + /// + /// Renders the audio player bar with the theme the layout was resolved with, falling back to the application Razor markup when the theme does not provide a bar template. + /// + /// The manifest id of the theme the layout was rendered with, so that the bar always matches the shell, including a preview of another theme. + /// Cancellation token that can be used to stop the execution. + /// The rendered audio player bar HTML. + private async Task RenderAudioPlayerAsync(string themeId, CancellationToken cancellationToken) + { + // The audio player renderer already degrades to an error when the theme template is missing or cannot be + // rendered, so a failure here only means the application fallback markup is rendered instead. + Result audioPlayerResult = await _audioPlayerRenderer.RenderAsync(themeId, cancellationToken); + if (audioPlayerResult.IsSuccess) + return audioPlayerResult.Value; + + return await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken); + } } diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml index 61363d5b..29783fdf 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml @@ -9,9 +9,10 @@ @* APPLICATION FALLBACK AUDIO PLAYER BAR - READ BEFORE EDITING - This partial renders the audio player bar into the layout of the application and of every theme, for an - authenticated visitor. It is only the markup: the behavior lives in the global audio player script - (wwwroot/js/audio-player/), which binds to the hooks documented below. + This partial renders the audio player bar into the fallback layout of the application, for an authenticated visitor. + The themed layout renders the same bar from the 'shared/audio-player' template of the active theme instead, and only + calls this partial when the theme does not provide one. Either way, the markup is only the structure: the behavior + lives in the global audio player script (wwwroot/js/audio-player/), which binds to the hooks documented below. The bar is hidden by default. The 'hidden' attribute keeps it unrendered until the audio player script takes over, so a page load never shows the bar, not even for a frame while the stylesheets settle. The script then hands the bar @@ -26,6 +27,9 @@ binds and routes to the audio player. - The hook attributes the audio player binds: 'data-audio-player-play-pause', '-progress', '-progress-played', '-progress-downloaded', '-current-time', '-total-time', '-track-name', '-cover-thumbnail', '-cover-image' and '-queue'. + - The plain text script elements that carry the raw source of the 'shared/audio-player/queue-item' and + 'shared/audio-player/playlist-item' sub templates, with the ids 'audio-player-template-queue-item' and + 'audio-player-template-playlist-item'. The play affordances the pages hand to the player use the 'data-audio-player-play' trigger attribute. The 'The Audio Player Bar' section of docs/technical/theming/Theming.md documents this contract for theme authors. @@ -53,8 +57,8 @@
- @localizer["ToggleFullHeight"] - @localizer["ToggleVisibility"] + +
diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 89faf6c9..3b80ea66 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -45,6 +45,7 @@ + diff --git a/src/Lumina.Presentation.Web/wwwroot/css/site.css b/src/Lumina.Presentation.Web/wwwroot/css/site.css index a53b68e9..dfa4b18f 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/site.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/site.css @@ -1407,6 +1407,15 @@ html.audio-player-initializing .audio-player-container { gap: 10px; } +.audio-player-controls button { + background: none; + border: none; + padding: 0px; + color: inherit; + font: inherit; + cursor: pointer; +} + .audio-player-expanded { display: none; flex: 1 1 auto; diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js index 64b05f4e..cc1c5a23 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -27,7 +27,7 @@ * - on(event, handler): subscribes to a player event, returns an unsubscribe function. * - once(event, handler), off(event, handler): one shot subscribe, and unsubscribe. * - getState(), getDescriptor(), getQueue(), getCurrentTime(), getDuration(), - * getVolume(), isMuted(), getPreferences(), getCapabilities(), getLastError(). + * getVolume(), isMuted(), getPreferences(), getCapabilities(), getLastError(), getSubTemplates(). * - destroyAsync(): releases every resource of the player. It is only used for an explicit teardown, never * by a navigation, because the navigation manager never recreates the player. * - registerEngine(name, factory): registers an engine factory on this player, by name. @@ -264,6 +264,26 @@ return text === '' ? '' : text; } + /** + * Reads the raw source of a theme sub template element of the player bar, or null when the theme does not provide one. + * + * The theme inlines the sub template sources into plain text script elements of the bar, so that the browser never + * parses the theme markup into live elements and requests their resources before the player renders them. The raw + * source is recovered by reading the element text, exactly like the file system browser does it. + * @param {string} elementId - The id of the plain text template element. + * @returns {string|null} The raw template source, or null when the element or the template engine is missing. + */ + function readSubTemplate(elementId) { + const templateElement = document.getElementById(elementId); + if (!templateElement) + return null; + // The theme template engine may be absent on a partially loaded page, in which case the built-in markup is used. + if (typeof window.renderThemeTemplate !== 'function') + return null; + // An empty template element means the theme does not provide the template, in which case the built-in markup is used. + return templateElement.textContent || null; + } + /** * Reads a play descriptor from the data attributes of a play trigger element, per * {@link LuminaAudioPlayer.PLAY_DESCRIPTOR_DATA_KEYS}. @@ -335,6 +355,8 @@ this.container = null; this.main = null; this.dom = {}; + // The raw theme sub templates of the dynamic content, read once with the bar elements and null when the theme does not provide them. + this.subTemplates = { queueItem: null, playlistItem: null }; this.descriptorClickHandler = null; this.controlHandlers = []; this.isProgressRenderScheduled = false; @@ -392,6 +414,12 @@ this.dom.progressDownloaded = query('[data-audio-player-progress-downloaded]'); this.dom.playPause = query('[data-audio-player-play-pause]'); this.dom.queue = query('[data-audio-player-queue]'); + // The sub template sources are read once, with the bar elements, because the theme markup is part of the bar + // the player was bound to, and the player is never recreated by a navigation. + this.subTemplates = { + queueItem: readSubTemplate('audio-player-template-queue-item'), + playlistItem: readSubTemplate('audio-player-template-playlist-item') + }; } /** @@ -715,6 +743,14 @@ return [...this.queue]; } + /** + * Gets the raw theme sub templates the player renders its dynamic content from. + * @returns {Object} The sub templates, with a queueItem and a playlistItem source, each null when the theme provides none. + */ + getSubTemplates() { + return { ...this.subTemplates }; + } + /** * Gets the playhead of the current track. * @returns {number} The playhead, in seconds. @@ -1272,27 +1308,82 @@ /** * Renders the ordered queue in the expanded bar. The list is only shown when the play context * holds more than one track, so that a single track never renders a one item list. + * + * Each item is rendered from the 'shared/audio-player/queue-item' sub template of the active theme when it + * provides one, so that the theme owns the structure of a queue item, and the built-in markup is used otherwise. */ renderQueue() { if (!this.dom.queue) return; this.dom.queue.innerHTML = ''; const items = this.queue.length > 1 ? this.queue : []; - for (const item of items) { - const entry = document.createElement('li'); - entry.className = 'audio-player-queue-item'; - entry.dataset.trackId = item.trackId; - const title = document.createElement('span'); - title.className = 'audio-player-queue-item-title'; - title.textContent = item.title || ''; - const duration = document.createElement('span'); - duration.className = 'audio-player-queue-item-duration'; - duration.textContent = formatDuration(item.durationInSeconds); - entry.appendChild(title); - entry.appendChild(duration); - this.dom.queue.appendChild(entry); + for (let index = 0; index < items.length; index++) { + const entry = this.renderQueueItem(items[index], index, items.length); + if (entry) + this.dom.queue.appendChild(entry); } } + + /** + * Renders one queue item, from the theme sub template when the theme provides one and from the built-in markup + * otherwise. + * @param {Object} item - The play descriptor of the item. + * @param {number} index - The zero based position of the item in the queue. + * @param {number} totalItems - The number of items in the queue. + * @returns {HTMLElement|null} The rendered queue item, or null when the markup produced no element. + */ + renderQueueItem(item, index, totalItems) { + // The model exposes only what a queue item can show, so a theme template never reaches into the player internals. + const viewModel = { + index: index + 1, + trackId: item.trackId, + albumId: item.albumId, + artistId: item.artistId, + libraryId: item.libraryId, + title: item.title || '', + duration: formatDuration(item.durationInSeconds), + durationSeconds: item.durationInSeconds, + coverArtUrl: item.coverArtUrl || '', + isCurrent: index === this.currentIndex, + isPlayed: index < this.currentIndex, + isLast: index === totalItems - 1 + }; + if (this.subTemplates.queueItem) { + try { + const container = document.createElement('div'); + container.innerHTML = window.renderThemeTemplate(this.subTemplates.queueItem, viewModel); + const entry = container.firstElementChild; + if (entry) + return entry; + } catch (error) { + // A broken theme sub template falls through to the built-in markup, so the queue never disappears. + console.error('Audio player: the theme queue item template could not be rendered.', error); + } + } + return this.buildDefaultQueueItem(viewModel); + } + + /** + * Builds one queue item with the built-in markup, used when the theme provides no queue item sub template. + * @param {Object} viewModel - The queue item model, per {@link LuminaAudioPlayer.AudioPlayer#renderQueueItem}. + * @returns {HTMLElement} The built-in queue item. + */ + buildDefaultQueueItem(viewModel) { + const entry = document.createElement('li'); + entry.className = 'audio-player-queue-item'; + entry.dataset.trackId = viewModel.trackId; + if (viewModel.isCurrent) + entry.classList.add('is-current'); + const title = document.createElement('span'); + title.className = 'audio-player-queue-item-title'; + title.textContent = viewModel.title; + const duration = document.createElement('span'); + duration.className = 'audio-player-queue-item-duration'; + duration.textContent = viewModel.duration; + entry.appendChild(title); + entry.appendChild(duration); + return entry; + } } LuminaAudioPlayer.AudioPlayer = AudioPlayer; diff --git a/src/Lumina.Presentation.Web/wwwroot/js/theme-client-template-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/theme-client-template-engine.js index 64446976..e1d8c3d1 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/theme-client-template-engine.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/theme-client-template-engine.js @@ -1,6 +1,6 @@ // A small, non-executable Mustache-style renderer, mirroring the subset of the server side ThemeTemplateEngine that the -// file system browser uses. The theme sub templates rendered by this script can place values and test truthiness, but cannot execute JavaScript. -// It is loaded lazily together with the file system browser dialog script, and exposed globally so that components can share it. +// file system browser and the audio player use. The theme sub templates rendered by this script can place values and test truthiness, but cannot execute JavaScript. +// It is loaded globally by the layout scripts, and exposed globally so that every component shares a single instance. (function () { 'use strict'; diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs index 33616a08..7088d346 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs @@ -85,7 +85,9 @@ public class ThemeLayoutRendererTests RazorViewToStringRenderer viewRenderer = new(_mockViewEngine, _mockTempDataProvider, _mockServiceProvider, _mockHttpContextAccessor); ThemeNavBuilder navBuilder = new(_mockUrlService, _mockStringLocalizerFactory, _mockAuthorizationService, _mockHttpContextAccessor); ThemeService themeService = new(_mockApiHttpClient); - _sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, _mockHttpContextAccessor); + ThemeAudioPlayerBuilder audioPlayerBuilder = new(_mockStringLocalizerFactory, _mockHttpContextAccessor); + ThemeAudioPlayerRenderer audioPlayerRenderer = new(themeService, new ThemeTemplateEngine(), audioPlayerBuilder); + _sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, audioPlayerRenderer, _mockHttpContextAccessor); } [Fact] From 0c6de6b392028cc2b498a5e30aea20cfd2b28b0e Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 16 Oct 2026 15:26:55 +0300 Subject: [PATCH 15/77] Adds the audio player transport UI and its three state progress bar. --- docs/technical/theming/Theming.md | 23 +- .../Core/Themes/Bundled/editorial-paper.zip | Bin 374932 -> 375101 bytes .../Core/Themes/Bundled/lumina-default.zip | Bin 374395 -> 374564 bytes .../Resources/Views/Shared/_Layout.ar-SA.resx | 21 + .../Resources/Views/Shared/_Layout.de-DE.resx | 21 + .../Resources/Views/Shared/_Layout.en-US.resx | 21 + .../Resources/Views/Shared/_Layout.es-ES.resx | 21 + .../Resources/Views/Shared/_Layout.fr-FR.resx | 21 + .../Resources/Views/Shared/_Layout.it-IT.resx | 21 + .../Resources/Views/Shared/_Layout.ja-JP.resx | 21 + .../Core/Resources/Views/Shared/_Layout.resx | 21 + .../Resources/Views/Shared/_Layout.ro-RO.resx | 21 + .../Resources/Views/Shared/_Layout.uk-UA.resx | 21 + .../Resources/Views/Shared/_Layout.zh-CN.resx | 21 + .../Core/Views/Shared/_AudioPlayer.cshtml | 41 +- .../Views/Shared/_ThemeLayoutScripts.cshtml | 24 +- .../wwwroot/css/site.css | 123 +- .../js/audio-player/audio-player-engine.js | 9 +- .../js/audio-player/audio-player-events.js | 2 + .../wwwroot/js/audio-player/audio-player.js | 1047 ++++++++++++++++- 20 files changed, 1433 insertions(+), 67 deletions(-) diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index d774e536..54df94a4 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -237,6 +237,7 @@ The bar is fixed to the bottom of the viewport, so the theme owns the room reser | --- | --- | --- | | The bar container, with the `audio-player-container` class | `not-shown` class | The bar is hidden, and its height collapses. | | The bar container | `full-height` class | The bar is expanded to its full height form. | +| The bar container | `inert` attribute | Set while the bar is hidden and removed when it is shown, so a collapsed bar keeps none of its focusable controls in the tab order. | | The main content element | `audio-player-not-shown` class | The bar is hidden, so the content area uses the full height. | | The main content element | `audio-player-full-height` class | The bar is expanded, so the content area gives it the full height. | | The full height control | `id="audio-player-full-height-toggle"` | A focusable control, such as a `button`, that expands or collapses the bar. | @@ -250,7 +251,7 @@ The `shared/audio-player` template receives the following model: | `assetBase` | The base URL of the theme assets, used by the theme template to reference its own assets. | | `queueItemTemplate` | The raw source of the `shared/audio-player/queue-item` sub template, inlined by the application into a plain text script element. | | `playlistItemTemplate` | The raw source of the `shared/audio-player/playlist-item` sub template, inlined by the application into a plain text script element. | -| `strings` | The localized strings of the bar, keyed by their resource names. | +| `strings` | The localized strings of the bar, keyed by their resource names. A shell template uses `toggleFullHeight` and `toggleVisibility` for its two controls; the player reads the play, pause, mute, unmute, volume, seek and buffering labels from the global scripts configuration instead, so a themed shell does not need to render them. | A theme must reserve the space for the bar itself, as the bundled themes do: @@ -271,7 +272,25 @@ main.audio-player-full-height { The application fallback layout, which renders when the active theme cannot be loaded, reserves the room itself, because the application stylesheet does not position the content area of a theme. A theme that omits the rules above leaves the fixed bar overlapping the bottom of the page. -The markup inside the bar exposes the ten hook attributes the audio player script binds: `data-audio-player-play-pause`, `data-audio-player-progress`, `data-audio-player-progress-played`, `data-audio-player-progress-downloaded`, `data-audio-player-current-time`, `data-audio-player-total-time`, `data-audio-player-track-name`, `data-audio-player-cover-thumbnail`, `data-audio-player-cover-image` and `data-audio-player-queue`. A theme that replaces the bar markup must keep all of them; the part of the bar whose hook is missing stays inert. The play affordances of the pages use the `data-audio-player-play` trigger attribute. +The markup inside the bar exposes the hook attributes the audio player script binds. A theme that replaces the bar markup must keep all of them; the part of the bar whose hook is missing stays inert. The play affordances of the pages use the `data-audio-player-play` trigger attribute. + +| Hook attribute | Meaning | +| --- | --- | +| `data-audio-player-play-pause` | The play and pause control. The player adds the `is-playing` class to it while a track plays. | +| `data-audio-player-progress` | The progress bar, a `role="slider"` element with `tabindex="0"` that the player scrubs and whose ARIA value attributes it writes. It carries `data-audio-player-progress-state` (`idle`, `ready` or `buffering`) and the `is-buffering` class while it loads. | +| `data-audio-player-progress-played` | The played layer of the bar. The player publishes its start and width as the custom properties `--audio-player-progress-played-start` and `--audio-player-progress-played-width`. | +| `data-audio-player-progress-downloaded` | The downloaded but not played layer. `--audio-player-progress-downloaded-start` and `--audio-player-progress-downloaded-width`. | +| `data-audio-player-progress-undownloaded` | The not yet downloaded layer. `--audio-player-progress-undownloaded-start` and `--audio-player-progress-undownloaded-width`. | +| `data-audio-player-current-time` | The current position, written as `m:ss`. | +| `data-audio-player-total-time` | The duration, written as `m:ss`, or `--:--` while it is unknown. | +| `data-audio-player-track-name` | The track name. | +| `data-audio-player-cover-thumbnail`, `data-audio-player-cover-image` | The cover art of the condensed bar and of the expanded bar. | +| `data-audio-player-volume` | The volume slider, a `role="slider"` element with `tabindex="0"` that the player scrubs and whose ARIA value attributes it writes. The fill is published as `--audio-player-volume-start` and `--audio-player-volume-width`. | +| `data-audio-player-volume-level` | The volume fill. It carries no geometry of its own: the stylesheet drives it from the custom properties above. | +| `data-audio-player-mute` | The mute toggle. The player toggles the `is-muted` class and the `aria-pressed` state on it. | +| `data-audio-player-queue` | The queue list of the expanded bar. | + +Each progress layer also carries `data-audio-player-progress-layer` (`played`, `downloaded` or `undownloaded`) in the markup, so a theme can select a layer by its state as well as by its class. The player writes no inline geometry on any of the bar elements: it publishes the geometry of each state as the custom properties above, which the application stylesheet consumes, so a theme restyles or reorients either bar by consuming the same properties. #### The audio player sub templates diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index 8085208a85d9cd4f3f449750f4066d812f6d7774..28b833d95508816807bb119bff852568d01e5e4b 100644 GIT binary patch delta 5167 zcmZu#3p|xc8=rIDcRI;k91%Gbx}c~wZ6$V7TXu6Qq;!O(QX!EpLZV_xA;z6@FS%rO z3bnP{*OD$PvL#Y$yDgQ+rpPelzo*|NnWOnR#a3dC!rT!gH^L8e#{A z)dT>H1g*s#TGBt9(7Jp&w#9M_W_clnMw%+;EsdDM^z~0>H>ovDICo;7k&N#gLfP}X+kue zKyJcWm#;eS#gzB>E?^Bqg{{KRXKj)6HN>HNyKbM16aKI(^}e%%q^POC^}4~}kyI(g z^7yVRs}XM>EyppxL(*myKJZD&SGqv)OUmUVNIO__14GJt+OD+UTDM<=v@Oi<(YDGo zS1r=sVE;gqln$$>2}v2YML^s8qZiY%Iqd+&S63X+BmLb?QOZ7F!nq#O|kZ z$8D?w?aJE0#tX2jc=8^Wip-)}TT1cY$4(zb?ByR~)oB!`6J=3^C$n#<^Bw8z5+lq( zm+IL65^h~RTR(|Zc0OY3=?u&oV7(_3B-<3OHz1V}i(oD7`cVSK`ZTpr(np;?_yC+# zM50hQG2*1lH_0v2l+L}L5`Uw|?`%lB`teIUn=RFa8zhbMrf6A9AE-_CT~K^K#^uPu(8IdsEteI4O^bR|mgu~1*Zauk>W>rI z_pe$b%PYM+)LqJEgtmjW`O`F}cZuHXPZQ0VQPN_yYkfrXESsHeW1MHV>Bbc>*W!y* z6(3eCGP$JYGs-|Eac2P9?BnM6`xlkbn~yHMKDkd+)T(r(Ys+=v_zF9p?4nCspC@_M zxwA71D)aOfW`%tg?Ka2gB&hpNVbiZVJ)_OrN(4qf8CgBPINGzVRhS)jS#@)O(}qBg zSyum<@x67FMf<#n+(}*0r+*RMn&GxSS?}9~1d|>cJE8j4>#yw{dhHFW*IY?m`fQX( zrLe{^V>5sJK*-tE7HeUq(aT`r?25-h87{HG$HrPrvA^)7;OX5-tByXr`laF1)pPyc zCgnyJ2+G(hfmUV8=f{86$WzX}tl_7kooRHYd;bgD*?RgP%QWqOiO@=^w^G~G>%RQk zpF%@?&pucgF3oRGQ}r{c+%pl1v6KvYd>>|Nl~j- z{H>$Tzhb3&{jAoPhx9vNhF^RgRywP`D9Zg<)csQ)Q`>ve-b^~%tC951EaH~uuDzkw zEk_*Ho8S0Y2KRlsvT*F~)B_O{Uo_RnZ5N!_UD#D@{P|98!|ARKk2%pYh=3i}{Iq>!A z8#k`Im2P@-+u?lDHL3TjS5|>BulJ^0ITQaW_h#c4lb;@%{i!>)_>-Qy!EZqGXIsUH z1J)`xQ??xS80R+XakFK$!wRo$1(R%32l7gMGYSkoljv;BDNLH+k>Ia(SEots%DOa5 zJWbcQ=oAl;sdyfzLD<`jiMOMr>uRm}2{*~=Ae?$~Y+wtPf z3x1Z^-79NCvgb!I_%$GwI69;BFxZH<3i1wzx5<{ViGb1MI6{{aU=IPR4new0(d)yo zmjDkEp)=j2)<@tix_?zup%rfdkFN>j-<5Uv&1t{`U=%LppWqEXem)i(g97};4uf@Q zS{l^jcLS8028GBw4U%&iMH0}TPrxapeU-HT%OqPcdYk0+VoCBJ-Meq#{k>5Y0ChR1 zcNGBe3<~lI4w~wJ z0F`5gvNBcvaq?||pI3laz>fdt=5RyIgE`nm6^=}>uE=cYSPz;jtj@+pS_A+X%Nc zN~k=Gb5Ku=m84_b5-DbLm`*mvEGscKKKWq9NEP{6L0d?7?Nwq5Rc1p?Ix1=Jr0y$9 z0KCL0VIe=NcIq_aj>@n|7qJ^_7UM`0@Kl(~iJTu(QRO3L6p+J36_$hDK7CK!;@b|n z#Gu<4W13WW$SwztN4mLCpP;jIF&Z<0ha$6}A=-&shGdCq*Y>;EY6H+90>D(x+iWWt z_t#uVZWE}NSUA5}hMMJZs9hdLfAf-|^SpQh6q5&)sPPeA$>sX^K4y%KTgn-~zg;Gn zvz@1IEK^UGM*uRC-KzWz?8D~{zU4_yQCQ5=dSTgEti6p||sDkJC@XJlx$ zlqVRf;~m2c_#+Pm7C>WUe+-hl7g|fuicT4-(#caDs=GiKMz3THHlOn+$|uPqKz7B@ z1PKIuT@;?rEml0~Iibt-{F2YDRu2K)=WyWE0%%Axr_Hqe<|e#zI>rGoO>X9_oH%M~ z0T*Uv0oM2Ua^MnQ{;(+33o#)jnj<(D!m-rB^ySBP72_kI3UAGsat=fp95o`HuRbg} zrw7J8nSoEQAVUCV$jNl8IGIin)T184Tf|zQ)bNRlv&&YFn%79Evr$43)S}czyN8KW z@o2xtDKD0z4zzRBfOftP3M-MFE1)#pDj(;^I-DPla{P=w!k3Ws%PYpKbDUwgRsGb! zAC2@FMx9!r*(p{koR?z)zzJ+(k(`wZjln9v5q))Q?q4VH%g!;H51!m8eV`m zc=NDi?X#D09qk!~p~+)gimi36k}+&nF{4mIDVHZ%q)W%2;kIf=DHKviR+n>^UBa)Y zcs!x`r+gPyz!%GE+I${A(! zRg|?l5{ zN27WS(zO?))ryL-y-xg(XK>K7Vg*OdUCt^Xr7~`Abjz?2ya%X}@D=Q^gV>W0);M#7 zq%ugpnoubLBUW-?lMAbkdSv$gB0Y(#xSmc|R&iL$`+0x8c0GQzYv5O&Xi#_nta2kV z3*sR0BsTML4QFP_8g|$&>>`8?FOHyA&Yj6q%Q3il9S3@pb8EMYfK3}Y@I*PBKq=~w7m3^}p)tMls2Cnd)xaTz z;pxL$cF@D@WB z;JR|0SW*$6ZrhE$Psg_|dGEUpBT*F;(P5AHQ!tQ$S>1T(_{19Y985wURd5^`_MR#{ zGUp>Gr;1y=bENHdNzt5%LHd1u^MRJ-+~8voB9+c1K@WJ|GF_KJ^)lc$^_d7a9R@&bV$qq z|FJSY+p9AHu#po4Peh5|Lrv6G&+4K3)i`Jz{6|uDE+Rd)XwCPsbD1~l{rTtkOm0g6 zV4<9mbaz5^G9Xuoe?N@@Fp^{SAhrft(s&%5)9NB|=O_Fx|3cG>K+ZMLh8|Fsxxs=% zn4yaoL;mjbdjv#9VbB1z)NmKRz8W0y`8`PGG@M1lI2Ehamxi_aSUU@s|2_+lxfD)B z@u#_kEIW;rmWjwh3Qf_ILr{Ha4y#EqAt;Fu?8xKK8?^kb36&+0(jrN? zqVkuSX+p;GH!;bQ5Hi%vpdtLvIrj~{a{KhT=lp)(?{7QneRY589q88MdwDRd4nBHb_szw7mViGJ9yzqN2* z)9xPWcaQef#eI+IZ94dE=QmmpzXM~HNk4p>J9(eV*g@oz%XSRM`i7>h0>W$2A@87$ zG=h8m{sFcxyET}u!G>iAM$)AiA)Dq%Zykagm)vQSp}6rfnC`_S*^6~_1Y!B^rq#8v zBwR|j8{o#=YPwzpH#9HMg~M>8<}MveSayHX$;8DeWgbmfG6P<@F~&qp?$>sPS;ESB7gV691miDBD`>ggJm%o5p&cy>FXJ0`FmL?udO_b4M)fnWV2EgK8g1?yy5DGljb;gr$45sZ(tNO8LN&?+@+%nev; z+GJvBUby2xTibPKS84h|NkL`noC8KRGtJ+2y?tn*+P1eNqKcnawLI#_+Yha4-%gL6 zapBzCd)KB;SX*tA=JhC3IP~5PSEJ_cd!eGOhNorDM)Mu-1*g5M?&&JhuD8lcyks;d z#6Yl0Q+;0RUFW}Nl`Dnb^|DDn>*IT%qw+7G=Ph;ll2^f7Q-ii#`!Vjrh)GqCe$8Xzc5a-O6_(y;U930f{f>75 zImd)Pepc?v5At2d>#H@MTyc9=THwP?f?S(tn3S^^f5>HpI~@EchfnGiVAqAz>2m;cm2^|BhYV;j*FrHbD1 zVWH8Xb`fzgtETO%S;Yu7roBJdt8N;hd|BL@?;*C^X7g6N`i)7qR#S=T;*W2W+=shu z`Sr}Y^gC1YPh@EJB+v8T{e176J9DMco}hE2?k^wB;--76>rTkIoa*BKizwWCPONBg zgYE0N4O`m}sowq*DnCxUk*v*LogXTrLRSE>Y@zPb6VXJ*28l$Qt1 z)1m%7iM;$Dx||ZsLK*fj6lDsHGk^dsS(uao^x(7%Fw7XQT$qF&@{{s2fR-nI8`%DiB3k``3j#-Zkz=Fd-KqB8<*=!+FqNp*9t zlpF@aWjMe6jXT>WBHQIE{lg1Gg_4K2JUl2WX64tydv;&iXpXX5fM$uFLU=cZNUrPa zLz_&1PZ>BN6P3u;Kq9o$mADR5v+bYf-cc$`q{z_!(2i-QV8~L>S z?cgxLNQU9}=QB{)fx{`vR>8>9X_D9u6UpZ3{K1NzVQLn#=dy&T1O3$Dy(})^7g!#< z8q1-r6zGzgdV9t;(#S#ju>KA4bS#3h<#1-(lI@QsO11Or?Ji z-bax7)@4Ew9|1bVne2sC`z1a_b)#{&Q_SXfgfx|W*CH5Df*EYYX?GOiK2(BH3Zykp zpfDRu#L)y~BX>&gkr6YAb+0Nsna$;V2FaPH0$LIqD}?`K1AM$egB&D0X37bdpbi$U z$3h1!OA-`p=&NMg@bc}7D*#9ZuYe^D55$Pk%dA;pMo%S3_&RcOG*s2 z(AXPOl!F55Ljp#b!Lzx*fIy|&Dn~US=-&qYQw-n5`A*qQ4;W{MqbRrySsWlsN(-Rq zD3|qKq+yoHxLlH|Y2^V$J;+aRTZ)F<3{9%h3c;DwAIbyHICj#(}Xn}zvVRA z$G`|uhh~eG8Yt^xr(hE zttI&@G^cq-Hx!^HUv5NEV-#qUGhplwU~C!VR}8IE~q zmaIUt#8Uw;d-WNw4PSNf^a%-%&6Ywm6Mo?_kj_IBj`;t?Fq%X!#Ji;z|JdXs<`i`j zS)8F@v`MosYwmHB2QnCi-ptkUa#h)JphL{;YPI+-AFb-^17@&bnjEWo0^l1w6rMm9 zdVS^6&=UaPG~s3}9UIM%g<6M%#H?dOw)aoynAtO=|L$~a2M6sz7yABtkNrtx>oMd2 zF((23#(_Jru&x9Pbz$vEFqAk5%sv~}5=2ocyZax8hMgQ#tw=sx6;aVKt!O{@MJEs% zu|ALE9OzmE@D&QyTh4@xipc(?19_M(&pD1J1<`aJ){a@?_H0DlI!UcvqBr1 zMp7Fr+;K!=@d`e-{>HpP=(191Ls4j{^m&4}vH#w8;=M6Q_sgSM!#v~A>H_9IlBUC%ePos|miaH^NZWUkz&Ml|{g}+7u zMHRph_mALyR0gcA0JgaQ9QUhh;GjxCK1gjVQ7uYqStzyy_V8XEs{wacawDCNRnbr6 zs;mxH3-%xtS+Q-yBfC_rDJuF3MY$-%V)Nk(K?VAsk}o0V1Fu7Xw)DzOigH#Uh%KP_ z6qt>JyMGD=_ij4w>p;OwForlJ$Mik5hO*2?0Dr=#56!9SG@7~en+r&pDT48TW}Ns z7_=Xl9ohl_G>~yMw3H!D^**8*4@Gk6UMxM9N~Gp6UJNw*&%$nu=-4kujIEYmQBK=L zdKjX4I1}Aw6?ebi#Bg;rxBF#Pqbk}SfM=_@A%BYc408y;A_$Ci`ma9xNe1ty1HF+h b5cK&V^YQ>_HljN(`dey@er`xd%ai&)AC=nV diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip index a83ac6367b7e7444694db9ef87bb0133466d5cb1..7f88f07300b00c7bd4254e541359351d263b61c2 100644 GIT binary patch delta 4949 zcmZWs3p~`>7r!&}yD5(`-fxCN5_zQPK`)i`&|^^~*=!_Kqz6_-%2q1k4n`!Q@)%J= z+BRETsVM2GcWT>~MEY+ns{g%rW@|=2AD?^A_nhxJ=iYnnWBNL@3p=&dy*xRLCIDbC z@b&RpI?Z~p5bex>7762`H4KgZ_;lYtl<(o0=6&e>Z#k;_Y}3qzQ9X|v7ua8nzkB`$ zr|Ee8yG*C`1+y+%-%X#N`H%Xj?C7WWeH~_YW*XH+QBwOFsihL@8_tH_Wo9& zY3H`#%d@Ar)ijojzpUx>rL}9i@ItqL*I#zlXEbd2=XPhaSZrUPD#Y4OTVu`(NMvS6Kby2{<#QCjpi(}F z$kCc19MV44@uhla{rBobwzYXoWv-pC7Lh~TpJ|fTbBUccY2()@P&qltgSO3r9TZlpfir=fS>PRGU`||ns~?t)+)+cpTbhrAV{*1)uvB6VPaPO5Yn-&XO$R` z&b^1MwUp)A%}Synng_92lyyswUCAdlJI1kZ>XMG%LbjONXoj*&sKc{~>=cT4WU)Vz zF^Z>(*h$p5;WFD#jUX1S>>O%y{w(AkuN2!)THv6EE^&EXW$6xCP83 z0{AUthLgn=Z(qci5{cRFnU6H42r;wFunP6pGXJAxvA}pvSdbL}7tWw(=5RFHB7!{e)H-Ih74cB{f;mH{ zBeIWKF@hks&EZND(s6Z%r>Uyf4|*A?krG2`pY{G`15l;}fEjui3;7AQA<^Nh%e?2L zx7aEF+GD-@dV6?nOlyFyZjIx^jA?TwILCC&sLRd$^!D=H)}p1wIdGlF$cCFORYyXW zHcYhEauz@1jR>7q{B)=Hf$6dP^le%$D%}+%{#m;JhwYpDwl-IN9?tZ=yS24k6cniD zT{=3p72I*NQ+IsA?=!OFj~|^-(&DgrW%F3qO?PyEaJi$utB}*UyGT{(WyK7O3%p=O z6Yl;^k!W?W-@F%7L`ka;O>Y{}#V@+0eBjBNChegWlY?`MF0AWJ3#toXoC-zxhSP=d zW0L&Fo0WmOUxtL;)oa(Vxl^KGcHYe4RlUaYJGZoRcU@Fn9l0oEZQxjkKSoz4I49b+ zPRz4Cy?TDzb7tMK&$tHp<2UYlzAddYZ3l&P4N(C)Z z#<*jb)bmyHE~bZK&^E=@lAp;uYz@x%RYO`|_K2Mo!Q6C^#)v(|O~)GlN&9^!#C6M1_yqnX$LJ z_ZmIw{<*#<{^-~s~6=HoW$m^%7i-ulL=DmEbQacAt+m&coQg0uRcIFH#L zd+l@k#opC^HOulp{A6A5d*f-#6Q}S0sx&KQQ1GK0Zr5%(eVTph`t>HiqhTNJd7e#c z6t8&q&SCA&o^2UdYIc9gyV)>h#Ou8-U)oZNzZeFXJWl|cmnJFgaOU33SaT@Q*iZ3Q zvwfB4!l3nqR+BP6<(GtJ7n+P&s<-Okk+flfsS&&fdRKW@eiGQ5*Loz*Pbx3$@ldxs zeA2qCqkmtR;Y6JkL!9=Wf+1vseIp~n1215_ZwIs zK_*n@lg&GO9`D?2Z1(`$8GW@O9e;LuG0TK2?-+GwLPJ&?;vz^+3gm*IA-iD+@!x?==%PpgBnLK%#~AAq$`(Ky zA~q0{9-DMm8%xB^l9(7~VXVb2{h2@~-N{ZLg-P*E1h<)vakKPncV*-vln%4>$0G?Z zwE!?R24IxjFnNBcI}1)Ek?gWDd&*kEMr*R67M-B^^VVKw;rSOB05DRH>A9W8sYy~E zI7!clqs%OzNXlBCv7 z*fy;cvlc>q%AUcjI_ZH^OEm<*Mvgu86|qbg{i!lie*I)01OrKT`>6ZpLP&0Z^hpQ} zIkj9Csu#kc$SoHd5i}qdqcOuMYKjhGiJ)f)YUv(It6Mk2+U- zVws$!4?xKsdUTfiwLmq|D6>k8=y=I?C~KAARF7i2I18`W^XxwTtH%T(DxiDIMg zt3yzqW_fj(LQ^q*=$*xbcami#W z34i7hY_zlMJEOcKa2VaglRy3una2fS2riVFatRAKXnzSbldKvJs(}oPB&9#T2=BUF z^?~X%0^`I)q|JAcsJn_Fc{?M;VhlcZm*LEF=M4GobST=kZbT#WGyi z#hmXdrJh7kh>%#ZN+5Y9BE1p}mh2?pFyx0pI%wgW@%#7URXT)M$y#pErv${*g;1{% zYH9_MwKI=O&Lo4Q80&1O7@BufT3aVphetld4^ZDh0N_HA`8abKQu5m`6%hw| z^HI}LXi4i*L2#O1j2VycKQ2$1Z}LJ0?ODJW4BQcJ$FK|jBDC}vw4|e%v|?9BJHA4L zn1L>4{eTLONvfrZu)=*%$1!L}MrV8+%L$9ogyWDruu%w+XZWGy8r{nWGuQpuqKvE>bO*u#Czvx_lFZ$~H0v z)&oyh@o!dbjX3-iMF4cHz(=Rd7qSnzS3rIMxvzRn=3HyUE8&8}sLI#?5Szw;$zD^3yhLy|nbLzI%!+wQ zWP2p)V+N!Di6HrnjFc;}W_15o4G)D?N+x&{)^M^dAet|NqtGQR(aLMhQ1$h}yYn9( z0A|P}3;<_3wbekz{%|Bpb%#UH>=P1SOHN>4zxjXDk4ERPiVi^T2cn!qwauuq8lP-k zu}~Q)RYCIW9vN5RgvZB!)tI1&DoKzyqEY<$t40M~i-W4D0jp^s!5*)4H@rmaY5>4L zZe_j~lw^SnswFXOtFfn5sl<~dimHajls|6K=k89-;^V_)j0_tu-(F%mjat=mf-Q2f zc0H*aIjgLF5{DB`N^Te5lQ_zb{gQkq?1M_*owuSX#j|p-pJcpc<;&wyx`ftpQgZZl e5?|FB642xn-&0bzeb>J4rN*d4nVBdRH%z4sZBnVBlrYLz5~IC2Y169Gu5`1@ zj2R{jzR{qPgvJ-D&kPOGcg}h5m~NBb&wHN#^M96ep64vL>ZS6#=gLxi4=$rfQPeDI zyI6fojj zLJz6qfm0{lC4mQ1U3BdnJgDoZHxnz3|IvF%hzfBIO{}WbIjuUFY2*CrH z<%}Y(kigKJF~TK*UaOdX3|OpYOmHm)K3_7rSR+XGWn{_V&>H4PqFNQeRFc6&Ak&8% zLC_PzWDtK55lj$+k;_qx85xYnGDAewvxOmDA}B~;_7iiRM8<=tHYGFPiX*FOsgO>U1zqXh|Q3K-8bUQFfDfzN1r&mYn+^BEu zBI}}JyL9W4#QQsHl0p=VOvO~jBJ7S#?f~}D#)s@4Jbg4P-T0Y=dw}lR@|At3g1UC- z@ zizj+RGrx-AFP&TV`Nbbo=F1%RzO*>nA}1r-rtpJb@cU%?M=|U8@xh0u+!Am3bo}XQ zrKp^1+1yHXE!+?v_3-D>gB%})UxULJhlV(G)|v?FgL$S6CTS8I*77blYG!u~Co0JI zG}-km^>6V0<>s1I0SQ*B26|l6vgAXO1?3*y?&DqqFXzFi(t@O14TqGB<5~MMb=zdO zNGJa)?@fowRmIe~%%@-XRJ``i^;%b9{aewWZ}+r0$Tu5aDG%PNe@)NCs5UKcaPZb5 zmy&|~+?uvNuRQHDZbom$-aIm%J$QIHsza)>BP{0oyN}GyzFD$)>80~;9^CxGVQZ&( z4*zkHuG)j!F4{fg55o6oo)j!f(OzZyASCB)=fqfpLYHZA^3U2{q3XO?IhmDx{fqus z)+!d>&o?hP?c-1f@nzxU5o<&K8E(k~3O(jJ=J+qO&%c1>B9^m!P*H%)Uc$$mCE zmONYE&O*97bN%j{-^ah#a_V?|qmmncV25jQWWg1)MrE&eX>Wtes&xZQ-NhezSGm}$ zN?xgtxVtQ8-J_kna`R_9og}!4BWC6coFA)ycjsVCnAJeE$;Ov$sj?@WmyR2|Ul7~l z;pQ~>;pm>|yvodxs|`gd(@#&h^lNY(H6K*o1@7V|9NPu<;(ZMhGr$N2LNftrcUYYT zo?{?48>}YX{wx>VAsgXhKCq=_|2dNRL8%Mr(rkI7l%UfR85xg0#58@9Rb}X2&wo2` zUEEFOs{D;p$)gdCszc|s*Zocp--%5AsnF5ea43J|o{7iObd~FlV=)$L21(r+L2s5{ zdb8ZC-1Cu2Pjpt}5w838s216z#d$W@*Q@r&{;C;v(0|vaZTkM3VK)5gk$W(&Ia6z6Z@wr2f7{_(6}H+j+}q zikje3ls>vzru}6A6Doq9@|@BA(_n5=9-NbGLD{&1X7()gyPg2~d=l z8bzs#7|6p>2=Ji*)eC?IXJQt#F97%?fNQY)S`sD|09`B>V!4wCJB4yDmLnD6UqZh6 z5hUMM$-SVe3i(F>K80a0#w^rxWvrBPt>#F=Vj+GU<9e0|H-@7^>^;UfHn6+|sN{;x zRfnF1tP}r2qzH7y3ccLuB~lhMXV(x~o$^G9qI9(=%35T0&i<^`@&FlFaEx^)SA^Vc z{)$zkZkB-lMXVwcE4J@t73ur_9cTGdivlNQikhoEGtT7#Vg)(H0N;jCyBN7z-pqn) zi-8g;oAK}gS7#nYSt(GIiAbKmb+gotVu0@|cn#YJ-ov0if_ z0+h9JFNFQENC(POlrt)=rHE58SXKh?wFVy`OYZMH8V(i#U8q&c7TCEIq1F0AGzCeR zTY^!axk9wR6ey6~%R(E@52#X9F6v8Tkube(Q1&R8M_9@6o;OdSem(&~e^%IG|y_lsQETMV- zY7J|-6CJxGC@MgDW+MkvR0+2~ zve8)&O)(Ym?L@fO`h?tpep&{0mIEnbaIf9L<5Sd~0<=?YMGTzBg$A=LfI69Fw}JSL z8dS{lXr_xqxR=FXO9e23QRqKHy%H6i7N$c{2R=a!DMG!XhN;eYEypX+n(lDKvMIE$ z1X>vMt3=?6RV;Y4QrMimIzOFUgTnGrXNt~i)<%}96~&Q)5>>)8DF4;qen&K|OQ_VM z{1bavesC4Q4>-833dLJ^gat2D0sIJqy%?O|!h&9{93Hf;W}9MRHPW2Bf;C3)=2eac zED>tzu}1y=M~wn>>E)@;f7Cb%XiRIRH4))>vk=r8s{^iB=CS4S|)a}}aGOSlryzE)WKW8Z8s zdx>^?6>1jIuATG~8p!x_XaB2hrx(LaB;QXr!Hc!P9;frR76tw-jmz$8$2wty7Qa}K zorzAVa&$_Wi`YJaLT+9iz;AxoScg2EYa*x;yx7d;!IyRHVoqX}=7>;ba~vpMbB`k zQ;*1~Cl}QNW76I(VTYcNpertfnR#O+uZH{TfeCimjID}&;PrZ7gXJkKH~B%$27q6+ z(7gf4iT-dy1F$0Lcd15Cm7#mkLz1F&rX^2Na{?JC5ya?PiYCSnx|OTe&PVqwU!0=! zL`?o#&%ogjMxU%1ac_Hjb({f8`1!1v_i}nT1Ct^cEtuZGu5W51O6~WJu(T1(Clj_z zeQ~=2#W{vn)=(slVk~CqL6s(ee+NOcCS>~8X6V)g46z)C%z^gJ!VVQ&Fde#%!hSZJqEtk}YNawzYB%!mHR9qphnj%~ ztpjVD+4n#<5;-CJ;In3S&&+B;GR%ZVEdc-8gKkK6KAz1`>*M3Y6XLBCBEvU@TSdjs zT;NyIs$H^ZWqlja`$QyzDhMlEfCYAT3p*b>1xH(e9$BuHT3*p1rWEzV*_kKh@M$== z6?kH+lvZR_{TR!0;f+={&leaBefJTZ1;04KcC7yiv_w}80rZ|^tYIyZNLBCW%lP@C z4fWcWqLzvzXzNP23UD+KSirSQfCRK`V;5^d8}jus;2-@b(DQ`w==|pg)y$T1NrvSe zKmk5%V{@HCUN~JlSkR^&nB!RmwIeWV=SPqSi`v;|M<>=qea&iIP9jH>?QGA;oJ5+j zZ$D~m$s#(g{xJR$%}59B=ubsv)_?dTRS_0u0y+5eNp@m)ktbRkW}gHmP_u(Q%pE$A zcU~5264e1zi1(JyYL*qDExaG?9MQst=3pu*>@V2VF%Qd%0dWbI5pi2%!>l3`HpR^B s6a1X7LrEGSm#A5%{UzoD>hJD~i{*O&w1p^YE&8XWgG%-t+VIr>0q_`;3jhEB diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx index 6a9daef8..35d9de2a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx @@ -120,6 +120,27 @@ إيقاف + + جارٍ التخزين المؤقت + + + كتم الصوت + + + إيقاف مؤقت + + + تشغيل + + + موضع التشغيل + + + إلغاء كتم الصوت + + + مستوى الصوت + إلغاء diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx index e9ac8596..66d2225f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx @@ -120,6 +120,27 @@ Abbrechen + + Wird gepuffert + + + Stummschalten + + + Pause + + + Abspielen + + + Wiedergabeposition + + + Stummschaltung aufheben + + + Lautstärke + Abbrechen diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx index 6b99cf65..8af1c8e3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx @@ -120,6 +120,27 @@ Abort + + Buffering + + + Mute + + + Pause + + + Play + + + Playback position + + + Unmute + + + Volume + Cancel diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx index 4f09682d..aa48670f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx @@ -120,6 +120,27 @@ Anular + + Cargando + + + Silenciar + + + Pausa + + + Reproducir + + + Posición de reproducción + + + Activar sonido + + + Volumen + Cancelar diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx index 70581855..89f415cd 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx @@ -120,6 +120,27 @@ Abandonner + + Mise en mémoire tampon + + + Muet + + + Pause + + + Lecture + + + Position de lecture + + + Activer le son + + + Volume + Annuler diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx index 3e510bb1..96e4c685 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx @@ -120,6 +120,27 @@ Interrompi + + Caricamento in corso + + + Disattiva audio + + + Pausa + + + Riproduci + + + Posizione di riproduzione + + + Riattiva audio + + + Volume + Annulla diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx index 25aed7bb..498740a1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx @@ -120,6 +120,27 @@ 中止する + + バッファリング中 + + + ミュート + + + 一時停止 + + + 再生 + + + 再生位置 + + + ミュート解除 + + + 音量 + キャンセル diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx index 6b99cf65..8af1c8e3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx @@ -120,6 +120,27 @@ Abort + + Buffering + + + Mute + + + Pause + + + Play + + + Playback position + + + Unmute + + + Volume + Cancel diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx index 24855322..cc6f9de6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx @@ -120,6 +120,27 @@ Anulare + + Se încarcă + + + Fără sunet + + + Pauză + + + Redare + + + Poziția de redare + + + Activează sunetul + + + Volum + Anulare diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx index 40c86c8f..847d6304 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx @@ -120,6 +120,27 @@ Перервати + + Буферизація + + + Вимкнути звук + + + Пауза + + + Відтворити + + + Позиція відтворення + + + Увімкнути звук + + + Гучність + Скасувати diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx index 12bb510a..49547c28 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx @@ -120,6 +120,27 @@ 中止 + + 缓冲中 + + + 静音 + + + 暂停 + + + 播放 + + + 播放位置 + + + 取消静音 + + + 音量 + 取消 diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml index 29783fdf..3fb2d034 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml @@ -20,13 +20,29 @@ The DOM contract a theme must preserve is: - The container element with the 'audio-player-container' class, carrying 'not-shown' while the bar is hidden, - and 'full-height' while it is expanded. The audio player toggles both classes. + and 'full-height' while it is expanded. The audio player toggles both classes. While the bar is hidden the + player also sets the 'inert' attribute on it, and removes it when the bar is shown, so a collapsed bar keeps + none of its focusable controls in the tab order. - The main content element, carrying 'audio-player-not-shown' while the bar is hidden, and 'audio-player-full-height' while it is expanded. The audio player toggles both classes on it as well. - The elements with the ids 'audio-player-full-height-toggle' and 'audio-player-close', which the global site script binds and routes to the audio player. - The hook attributes the audio player binds: 'data-audio-player-play-pause', '-progress', '-progress-played', - '-progress-downloaded', '-current-time', '-total-time', '-track-name', '-cover-thumbnail', '-cover-image' and '-queue'. + '-progress-downloaded', '-progress-undownloaded', '-current-time', '-total-time', '-track-name', + '-cover-thumbnail', '-cover-image', '-volume', '-volume-level', '-mute' and '-queue'. The volume fill element + ('-volume-level') is a styling hook the stylesheet drives from the custom properties below, not one the script + writes to. + - The three state progress bar: the played part carries 'audio-player-progress-played', the downloaded but not + played part carries 'audio-player-progress-downloaded', and the not yet downloaded part carries + 'audio-player-progress-undownloaded'. Each layer also carries 'data-audio-player-progress-layer' ('played', + 'downloaded' or 'undownloaded') in the markup, so a theme can select a layer by state as well as by class. The + player publishes the start and the width of each state as the CSS custom properties + '--audio-player-progress-played-start', '-played-width', '-downloaded-start', '-downloaded-width', + '-undownloaded-start' and '-undownloaded-width' on the bar, and the volume fill as + '--audio-player-volume-start' and '--audio-player-volume-width' on the volume control, and writes no inline + geometry, so a theme consumes the properties to style each state and to give either bar its own shape and + orientation. The player marks the bar with 'is-buffering' while it is loading, and carries the state in + 'data-audio-player-progress-state' ('idle', 'ready' or 'buffering') together with the slider ARIA attributes. - The plain text script elements that carry the raw source of the 'shared/audio-player/queue-item' and 'shared/audio-player/playlist-item' sub templates, with the ids 'audio-player-template-queue-item' and 'audio-player-template-playlist-item'. @@ -41,21 +57,32 @@
    - +
    0:00 -
    -
    -
    +
    +
    +
    +
    --:--
    -
    +
    + +
    +
    +
    +
    diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 3b80ea66..1bd1dd28 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -33,13 +33,31 @@ error: '@localizer["Error"]', information: '@localizer["Information"]' }; - // The endpoints the audio player reads the stored playback preferences of the user from. The routes are the culture - // aware web routes, so the player never hardcodes a path, and it never reaches the API server directly. + // The endpoints the audio player reads the stored playback preferences of the user from, and writes the volume and + // mute state it changes back to. The routes are the culture aware web routes, so the player never hardcodes a path, + // and it never reaches the API server directly. var audioPlayerConfiguration = { getUserSettingsUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)', - getPlaybackStateUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_PLAYBACK_STATE)' + getPlaybackStateUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_PLAYBACK_STATE)', + updatePlaybackStateUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_PLAYBACK_STATE)', + strings: { + play: '@localizer["AudioPlayerPlay"]', + pause: '@localizer["AudioPlayerPause"]', + mute: '@localizer["AudioPlayerMute"]', + unmute: '@localizer["AudioPlayerUnmute"]', + volume: '@localizer["AudioPlayerVolume"]', + seek: '@localizer["AudioPlayerSeek"]', + buffering: '@localizer["AudioPlayerBuffering"]' + } }; +@if (User?.Identity?.IsAuthenticated == true) +{ + + @Html.AntiForgeryToken() +} diff --git a/src/Lumina.Presentation.Web/wwwroot/css/site.css b/src/Lumina.Presentation.Web/wwwroot/css/site.css index dfa4b18f..0d8fbe4a 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/site.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/site.css @@ -1340,27 +1340,76 @@ html.audio-player-initializing .audio-player-container { flex: 2 1 40%; min-width: 40px; height: 6px; - background-color: #333333; + background-color: transparent; cursor: pointer; + /* A touch drag is claimed by the control instead of the browser, which would otherwise cancel the gesture. */ + touch-action: none; } -/* The bar exposes three distinct states a theme can style: the not yet downloaded track, the downloaded - part ('audio-player-progress-downloaded'), and the played part ('audio-player-progress-played'). */ +/* The bar exposes three distinct states a theme can style independently: the not yet downloaded track + ('audio-player-progress-undownloaded'), the downloaded but not played part ('audio-player-progress-downloaded'), + and the played part ('audio-player-progress-played'). The player publishes the start and the width of each state as + the custom properties below, and this stylesheet consumes them; a theme overrides these rules, or consumes the same + properties itself, to give each state its own look and the bar its own shape or orientation. */ .audio-player-progress-played, -.audio-player-progress-downloaded { +.audio-player-progress-downloaded, +.audio-player-progress-undownloaded { position: absolute; top: 0px; - left: 0px; - width: 0%; height: 100%; } +.audio-player-progress-played { + left: var(--audio-player-progress-played-start, 0%); + width: var(--audio-player-progress-played-width, 0%); + background-color: #6DCBFE; +} + .audio-player-progress-downloaded { + left: var(--audio-player-progress-downloaded-start, 0%); + width: var(--audio-player-progress-downloaded-width, 0%); background-color: #5A6B78; } -.audio-player-progress-played { - background-color: #6DCBFE; +.audio-player-progress-undownloaded { + left: var(--audio-player-progress-undownloaded-start, 0%); + width: var(--audio-player-progress-undownloaded-width, 100%); + background-color: #333333; +} + +/* While a seek waits for the range of its target position the bar pulses, so the loading state is visible without a + separate element. A theme restyles it through the 'is-buffering' class. The pulse is a decoration, so it is dropped + when the visitor asked for reduced motion; the 'is-buffering' class and the state attribute still mark the state. */ +.audio-player-progress.is-buffering { + animation: audio-player-progress-buffering 1s ease-in-out infinite; +} + +@keyframes audio-player-progress-buffering { + 0% { + opacity: 1; + } + + 50% { + opacity: 0.45; + } + + 100% { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .audio-player-progress.is-buffering { + animation: none; + } +} + +.audio-player-progress.is-scrubbing { + cursor: grabbing; +} + +.audio-player-volume.is-scrubbing { + cursor: grabbing; } .audio-player-transport { @@ -1400,6 +1449,64 @@ html.audio-player-initializing .audio-player-container { border-left: 3px solid #E6E6E6; } +.audio-player-volume-control { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 6px; +} + +.audio-player-mute { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0px; + background-color: transparent; + border: 0px; + cursor: pointer; +} + +/* The speaker cone of the mute toggle is drawn with CSS, so that a theme restyles it without an image. */ +.audio-player-mute-icon { + display: block; + width: 0px; + height: 0px; + border-style: solid; + border-width: 5px 8px 5px 0px; + border-color: transparent #E6E6E6 transparent transparent; +} + +.audio-player-mute.is-muted .audio-player-mute-icon { + border-right-color: #8A8A8A; +} + +/* The volume fill is positioned from the custom properties the player publishes, exactly like the progress bar, so a + theme restyles or reorients it without any inline geometry. touch-action is disabled on both sliders so a touch drag + is claimed by the control instead of the browser, which would otherwise cancel the gesture mid-drag. */ +.audio-player-volume { + position: relative; + width: 80px; + height: 6px; + background-color: #333333; + cursor: pointer; + touch-action: none; +} + +.audio-player-volume-level { + position: absolute; + top: 0px; + left: var(--audio-player-volume-start, 0%); + width: var(--audio-player-volume-width, 100%); + height: 100%; + background-color: #6DCBFE; +} + +.audio-player-volume.is-muted .audio-player-volume-level { + background-color: #5A6B78; +} + .audio-player-controls { flex: 0 0 auto; display: flex; diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js index ea66d23c..f6458c0d 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js @@ -13,8 +13,12 @@ * - loadAsync(descriptor): prepares the resources of a track (opens its stream, configures a decoder). * - playAsync(): starts, or resumes, audible playback. * - pauseAsync(): suspends audible playback, keeping the current position. - * - seekAsync(seconds): moves the playhead to the given position, in seconds. + * - seekAsync(seconds): moves the playhead to the given position, in seconds, fetching the range of that position + * when it has not been downloaded yet. * - setVolumeAsync(volume): sets the output volume, as a value between 0 and 1, with 0 meaning silence. + * - getBufferedTimeRanges(): the time ranges, in seconds, the engine already downloaded, as a list of objects with + * a 'start' and an 'end'. It is optional: an engine that does not implement it makes the player unable to tell + * whether a seek target is buffered, in which case the player never shows a loading state for a seek. * - destroyAsync(): releases every resource the engine holds, including any audio context. * * The engine host @@ -27,6 +31,9 @@ * - host.reportTime(currentTime, duration): reports the playhead and the known duration. * - host.reportDuration(duration): reports a duration discovered after loading. * - host.reportProgress(downloadedFraction): reports how much of the track has been downloaded, between 0 and 1. + * - host.reportBuffering(isBuffering): reports that the engine is, or is no longer, waiting for data, so that the + * bar shows the same loading state for an engine's own range fetch as it does for a seek. The state it sets + * stays until the engine reports it is no longer buffering, and a playhead report never clears it. * - host.reportEnded(): reports that the current track reached its end. * - host.reportError(error): reports an engine failure, wrapped into a {@link LuminaAudioPlayer.PlayerError}. A download * engine must forward its downloader's onError here, because the downloader only reports to its own callback and diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js index 2804731d..39e8305b 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js @@ -29,6 +29,8 @@ MUTE_CHANGED: 'mutechange', // The downloaded fraction of the current track changed. Payload: { downloadedFraction }. PROGRESS: 'progress', + // A seek started waiting for the range of its target position, or such a wait ended. Payload: { isBuffering, pendingSeekTime }. + BUFFERING_CHANGED: 'bufferingchange', // The current track reached its end. ENDED: 'ended', // A {@link LuminaAudioPlayer.PlayerError} was raised. Payload: the player error. diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js index cc1c5a23..8fb6736c 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -5,8 +5,11 @@ * in-place navigation manager swaps. Because it is never torn down by a page swap, playback and its * UI survive navigation. It produces no audio itself: audio is delegated to a swappable engine that * fulfills the interface documented in audio-player-engine.js. This module only owns the state machine, the - * event bus, capability detection, the play descriptor, the bar and the public API; the download, - * decode and render pipeline is plugged in as an engine by the later stages. + * event bus, capability detection, the play descriptor, the bar, the transport controls it binds and renders, and the + * public API. The download, decode and render pipeline is plugged in as an engine by the later stages. The bar holds + * the three state progress bar (played, downloaded but not played, and not yet downloaded), the volume and mute + * controls, the keyboard shortcuts, and the loading state a seek into a not yet downloaded position shows; the volume + * and mute the controls change are persisted to the stored playback state of the user on their own. * * Public control API (window.LuminaAudioPlayer.instance) * ---------------------------------------- @@ -19,15 +22,16 @@ * - stopAsync(): stops playback. While the bar is condensed, it also hides the bar; while the bar is * expanded, it stays on screen. * - seekAsync(seconds): moves the playhead to an absolute position, in seconds. - * - setVolumeAsync(volume): sets the output volume, between 0 and 1. + * - setVolumeAsync(volume): sets the output volume, between 0 and 1. Volume and mute are persisted to the stored + * playback state of the user, so they survive a reload. * - setMutedAsync(muted): sets the mute state. Volume and mute are independent: unmuting restores the volume. * - toggleMuteAsync(): flips the mute state. * - toggleFullHeight(): expands or collapses the bar. * - toggleVisibility(): shows or hides the bar. * - on(event, handler): subscribes to a player event, returns an unsubscribe function. * - once(event, handler), off(event, handler): one shot subscribe, and unsubscribe. - * - getState(), getDescriptor(), getQueue(), getCurrentTime(), getDuration(), - * getVolume(), isMuted(), getPreferences(), getCapabilities(), getLastError(), getSubTemplates(). + * - getState(), getDescriptor(), getQueue(), getCurrentTime(), getDuration(), getVolume(), isMuted(), + * isBuffering(), getBufferedTimeRanges(), getPreferences(), getCapabilities(), getLastError(), getSubTemplates(). * - destroyAsync(): releases every resource of the player. It is only used for an explicit teardown, never * by a navigation, because the navigation manager never recreates the player. * - registerEngine(name, factory): registers an engine factory on this player, by name. @@ -86,6 +90,43 @@ */ const REDIRECTED = Object.freeze({ redirected: true }); + /** + * Follows a server redirect, but only when the target is an http or https URL on the same origin and protocol as + * the current page, and carries no credentials. + * + * An expired session is answered with a redirect to the sign in page, which is on this origin. A redirect to any + * other origin, which a misconfigured proxy that trusts a forwarded host header could produce, is not followed, so + * the player never turns a session expiry into an open redirect. The protocol is checked separately, so a target + * that only matches because an opaque document and a javascript:, data: or about: target all report the origin + * 'null' is not followed either. A target that embeds a user name or a password is dropped too, because the origin + * check ignores the userinfo, so such a target would otherwise put attacker-chosen credentials in the address bar. + * The target is resolved against the current page, so a relative target is handled, and a malformed one is dropped. + * @param {string} url - The redirect target the server answered with. + */ + function navigateToRedirect(url) { + if (!url) + return; + try { + const target = new URL(url, window.location.href); + // The target must stay on the origin of the page and use its protocol. The protocol is checked separately + // from the origin because an opaque document, such as about:blank, reports the origin 'null', which a + // javascript: or data: target also reports, so the origin alone would let such a target through. The scheme + // is also confined to http and https, so a redirect can never introduce one. A target that embeds a user + // name or a password is dropped too, because the origin check ignores the userinfo, so such a target would + // otherwise put attacker-chosen credentials in the address bar. + const isHttp = target.protocol === 'http:' || target.protocol === 'https:'; + const isSameOrigin = target.origin === window.location.origin + && target.protocol === window.location.protocol; + if (!isHttp || !isSameOrigin || target.username !== '' || target.password !== '') { + console.warn('Audio player: a redirect that is not to this page was not followed.'); + return; + } + window.location.href = target.href; + } catch (error) { + console.debug('Audio player: a redirect target could not be followed.', error); + } + } + /** * The attribute that marks an element as a play trigger the player handles by event delegation. * @readonly @@ -118,6 +159,38 @@ */ const UNKNOWN_TIME = '--:--'; + /** + * The number of seconds the left and right arrow keys move the playhead by, matching the seek step of the + * reference web player. + * @readonly + * @type {number} + */ + const SEEK_STEP_SECONDS = 5; + + /** + * The fraction of the full volume the up and down arrow keys change the volume by, matching the volume step of + * the reference web player. + * @readonly + * @type {number} + */ + const VOLUME_STEP = 0.05; + + /** + * The delay, in milliseconds, that coalesces the volume and mute writes a drag of the volume control produces + * into a single request, so that dragging across the control never sends one request per pixel. + * @readonly + * @type {number} + */ + const PLAYBACK_STATE_PERSIST_DELAY_MS = 500; + + /** + * The tolerance, in seconds, within which a playhead report counts as having reached a pending seek target, so + * that the loading state of the seek is cleared once playback resumes there. + * @readonly + * @type {number} + */ + const SEEK_SETTLE_TOLERANCE_SECONDS = 0.25; + /** * Formats a known, positive time in seconds as m:ss, or h:mm:ss when it is an hour or longer. * @param {number} totalSeconds - The time to format, in seconds. @@ -352,6 +425,54 @@ this.engine = null; this.isAvailable = false; this.isInitialized = false; + // True while the bar shows a loading state, which is either a seek waiting for the range of its target, or + // the engine reporting that it is itself waiting for data. Boolean state keeps its conventional is/has + // prefix, except where a public is*() accessor already owns that name: isBuffering() is that accessor here, + // so the backing field keeps the participle instead of shadowing the method. + this.buffering = false; + // The position a pending seek is waiting for, or null when no seek is pending. + this.pendingSeekTime = null; + // The pending seek time the last loading state event carried, so a second seek that only moves the target + // while the bar is already buffering still publishes the new target. + this.announcedPendingSeekTime = null; + // The position the pending seek started from, so a backward seek is only cleared once the playhead crosses + // down into the target instead of by the pre-seek position the engine reports first. + this.pendingSeekFromTime = null; + // True while the engine reports that it is waiting for data on its own, which is independent of a seek and + // is therefore never cleared by a playhead report. + this.engineBuffering = false; + // The ratio, between 0 and 1, the pointer currently scrubs the progress bar to, or null when no scrub is + // in progress. While it is set the bar shows the scrub position instead of the reported playhead. + this.scrubRatio = null; + this.isScrubbing = false; + // The pointer Id captured by the progress bar or the volume control, or null, so the capture is always + // released with the Id it was taken with, whatever ends the drag. + this.scrubPointerId = null; + this.volumePointerId = null; + this.isAdjustingVolume = false; + // The bounds of a control, measured once when a drag starts, so a pointer move never has to read the layout + // again, which would force a reflow per event. + this.progressBounds = null; + this.volumeBounds = null; + // The latest ratio of a volume drag and whether a render of it is already scheduled, so a burst of pointer + // moves is coalesced into one volume change per frame. + this.pendingVolumeRatio = null; + this.isVolumeApplyScheduled = false; + // The last values written to the bar, so a render skips the DOM writes whose value did not move; the clock + // and the accessible value only change once per second, while reports arrive far more often. + this.renderedProgress = null; + // True once the user changes the volume or the mute state, so a stored state that arrives after the change + // is not applied over the user's choice. + this.hasUserChangedVolume = false; + this.hasUserChangedMute = false; + // True once the stored playback state has been read successfully, i.e. once the player knows the values the + // server holds. A write is refused until then, so a flush on unload can never overwrite the stored volume + // and mute state with the local defaults of a player that has not loaded them yet. + this.isStoredPlaybackStateLoaded = false; + this.persistenceTimer = null; + this.lastPersistedPlaybackState = null; + this.keyboardHandler = null; + this.unloadHandler = null; this.container = null; this.main = null; this.dom = {}; @@ -386,11 +507,17 @@ this.collectDomReferences(); this.bindPlaybackControls(); + this.bindKeyboardShortcuts(); + this.bindUnloadFlush(); this.bindDescriptorDelegation(); // The bar is hidden until the user starts playback, so a refresh never flashes an empty player. this.suppressInitialTransitions(); this.applyHiddenState(); this.releaseInitialHiddenState(); + // The volume and mute controls are rendered from the state the player already holds, so the bar shows the + // default volume even before the stored state is read. + this.renderVolume(); + this.renderTransportState(); this.capabilitiesReady = this.detectCapabilitiesAsync(); // The stored preferences are read in the background; a slow or failing request never blocks the bar. @@ -412,7 +539,10 @@ this.dom.progress = query('[data-audio-player-progress]'); this.dom.progressPlayed = query('[data-audio-player-progress-played]'); this.dom.progressDownloaded = query('[data-audio-player-progress-downloaded]'); + this.dom.progressUndownloaded = query('[data-audio-player-progress-undownloaded]'); this.dom.playPause = query('[data-audio-player-play-pause]'); + this.dom.volume = query('[data-audio-player-volume]'); + this.dom.mute = query('[data-audio-player-mute]'); this.dom.queue = query('[data-audio-player-queue]'); // The sub template sources are read once, with the bar elements, because the theme markup is part of the bar // the player was bound to, and the player is never recreated by a navigation. @@ -423,15 +553,54 @@ } /** - * Binds the transport controls the player owns. The full height and close affordances are bound - * by the global site script, which delegates them to this player, so that a single click never - * toggles them twice. + * Binds the transport controls the player owns: the play and pause toggle, the scrub of the progress bar and + * of the volume control, and the mute toggle. The full height and close affordances are bound by the global + * site script, which delegates them to this player, so that a single click never toggles them twice. */ bindPlaybackControls() { if (this.dom.playPause) this.addControlHandler(this.dom.playPause, 'click', () => this.toggleAsync()); - if (this.dom.progress) - this.addControlHandler(this.dom.progress, 'click', (event) => this.handleProgressClick(event)); + if (this.dom.progress) { + // The progress bar is scrubbed with pointer events rather than clicks, so that a drag moves the + // playhead continuously; the pointer is captured, so a drag that leaves the bar keeps scrubbing. A + // released pointer commits the seek, while a cancelled one discards the preview. + this.addControlHandler(this.dom.progress, 'pointerdown', (event) => this.handleProgressPointerDown(event)); + this.addControlHandler(this.dom.progress, 'pointermove', (event) => this.handleProgressPointerMove(event)); + this.addControlHandler(this.dom.progress, 'pointerup', () => this.handleProgressPointerUp()); + this.addControlHandler(this.dom.progress, 'pointercancel', () => this.handleProgressPointerCancel()); + } + if (this.dom.volume) { + // A released pointer commits the last queued volume, while a cancelled one drops it. + this.addControlHandler(this.dom.volume, 'pointerdown', (event) => this.handleVolumePointerDown(event)); + this.addControlHandler(this.dom.volume, 'pointermove', (event) => this.handleVolumePointerMove(event)); + this.addControlHandler(this.dom.volume, 'pointerup', () => this.handleVolumePointerUp()); + this.addControlHandler(this.dom.volume, 'pointercancel', () => this.handleVolumePointerCancel()); + } + if (this.dom.mute) + this.addControlHandler(this.dom.mute, 'click', () => this.toggleMuteAsync()); + } + + /** + * Binds the keyboard shortcuts of the transport, matching the reference web player: the left and right arrows + * seek backward and forward on the track, and the up and down arrows change the volume. The listener is on the + * document rather than on the bar, so a shortcut works without the bar being focused, and it is bound once + * because the player is created once and never torn down by a navigation. + */ + bindKeyboardShortcuts() { + this.keyboardHandler = (event) => this.handleKeyboardShortcut(event); + document.addEventListener('keydown', this.keyboardHandler); + } + + /** + * Binds the page unload flush, so a volume or mute change that is still inside its debounce window is written + * before the page goes away. The write is sent with keepalive, so the browser finishes it after the page + * is gone instead of cancelling it with the page's other requests. + */ + bindUnloadFlush() { + this.unloadHandler = () => { + this.flushPlaybackStateAsync({ keepalive: true }); + }; + window.addEventListener('pagehide', this.unloadHandler); } /** @@ -494,6 +663,10 @@ this.duration = descriptor.durationInSeconds; this.currentTime = 0; this.downloadedFraction = 0; + this.scrubRatio = null; + this.endScrub(); + this.endVolumeAdjust(); + this.clearBuffering(); // An album or artist descriptor carries no track id of its own, so the queue starts at its first item in that case. this.queue = descriptor.queue && descriptor.queue.length > 0 ? [...descriptor.queue] : [descriptor]; this.currentIndex = Math.max(0, this.queue.findIndex(item => item.trackId === descriptor.trackId)); @@ -586,6 +759,10 @@ // The playhead and the progress are reset while the descriptor is kept, so the bar can still show what was stopped. this.currentTime = 0; this.downloadedFraction = 0; + this.scrubRatio = null; + this.endScrub(); + this.endVolumeAdjust(); + this.clearBuffering(); this.renderProgress(); this.setState(LuminaAudioPlayer.PlayerState.IDLE); this.renderTransportState(); @@ -596,6 +773,10 @@ /** * Moves the playhead to an absolute position. + * + * When the engine reports the ranges it already downloaded and the target position is not inside one of them, + * the seek needs the range of that position, so the bar shows a loading state until the engine reports the + * range arrived. The engine's seekAsync is what triggers that range fetch. * @param {number} seconds - The target position, in seconds. * @returns {Promise} A promise that completes when the seek was requested. */ @@ -609,11 +790,22 @@ const position = this.duration > 0 ? clamp(request, 0, this.duration) : Math.max(0, Number.isFinite(request) ? request : 0); + // The position the seek starts from is captured before the playhead moves, so a backward seek can be told + // apart from the pre-seek position the engine reports first. + const fromPosition = this.currentTime; this.currentTime = position; + // A track that is not loaded yet, or an engine that does not report its downloaded ranges, has no range to + // wait for, so no loading state is shown; only a known-to-be-missing range produces one. + const knowsBufferedRanges = this.engine !== null && typeof this.engine.getBufferedTimeRanges === 'function'; + if (knowsBufferedRanges && !this.isPositionBuffered(position)) + this.setSeekPending(true, position, fromPosition); + else + this.clearSeekPending(); if (this.engine) { try { await this.engine.seekAsync(position); } catch (error) { + this.clearSeekPending(); this.raiseError(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); } } @@ -622,27 +814,81 @@ } /** - * Sets the output volume. Mute is independent of the volume: a muted player remembers the volume. + * Seeks by a relative number of seconds, bounded by the duration of the current track. + * @param {number} deltaSeconds - The number of seconds to seek by, negative to seek backward. + */ + seekBy(deltaSeconds) { + if (!this.descriptor || this.duration <= 0) + return; + this.seekAsync(this.currentTime + deltaSeconds); + } + + /** + * Changes the volume by a relative amount, unmuting first when the volume changes out of a muted state. + * @param {number} delta - The amount to change the volume by, between -1 and 1. + * @returns {Promise} A promise that completes when the volume was applied. + */ + async changeVolumeByAsync(delta) { + const next = clamp(this.volume + delta, 0, 1); + // Changing the volume out of a muted state restores audible output, exactly like the reference web player; + // lowering the volume to zero still leaves the output audible at the new, lower volume. + if (this.muted && next > 0) + await this.setMutedAsync(false); + await this.setVolumeAsync(next); + } + + /** + * Sets the output volume, as a user change, and writes it to the stored playback state of the user. Mute is + * independent of the volume: a muted player remembers the volume. * @param {number} volume - The output volume, between 0 and 1. * @returns {Promise} The applied volume. */ async setVolumeAsync(volume) { - const value = clamp(Number(volume), 0, 1); - this.volume = value; - await this.applyVolumeAsync(); - this.events.emit(LuminaAudioPlayer.PlayerEvent.VOLUME_CHANGED, this.buildVolumePayload()); - return this.volume; + this.hasUserChangedVolume = true; + return this.applyVolumeValueAsync(volume, true); } /** - * Sets the mute state. + * Sets the mute state, as a user change, and writes it to the stored playback state of the user. * @param {boolean} muted - True to mute the output, false to unmute it. * @returns {Promise} A promise that completes when the mute was applied. */ async setMutedAsync(muted) { + this.hasUserChangedMute = true; + return this.applyMuteValueAsync(muted, true); + } + + /** + * Applies a volume value to the output. It is the shared body of the user-facing setter and the stored-state + * apply, so the stored state is applied without being marked as a user change or written back. + * @param {number} volume - The output volume, between 0 and 1. + * @param {boolean} shouldPersist - True to schedule a write of the new state. + * @returns {Promise} The applied volume. + */ + async applyVolumeValueAsync(volume, shouldPersist) { + const value = clamp(Number(volume), 0, 1); + this.volume = value; + await this.applyVolumeAsync(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.VOLUME_CHANGED, this.buildVolumePayload()); + // The volume is written to the stored playback state of the user, so it survives a reload and never has to + // be a field of the user settings page. + if (shouldPersist) + this.schedulePlaybackStatePersist(); + return this.volume; + } + + /** + * Applies a mute state to the output. It is the shared body of the user-facing setter and the stored-state apply. + * @param {boolean} muted - True to mute the output, false to unmute it. + * @param {boolean} shouldPersist - True to schedule a write of the new state. + * @returns {Promise} A promise that completes when the mute was applied. + */ + async applyMuteValueAsync(muted, shouldPersist) { this.muted = muted === true; await this.applyVolumeAsync(); this.events.emit(LuminaAudioPlayer.PlayerEvent.MUTE_CHANGED, this.buildVolumePayload()); + if (shouldPersist) + this.schedulePlaybackStatePersist(); } /** @@ -690,6 +936,8 @@ const wasHidden = this.container.classList.contains('not-shown'); this.container.removeAttribute('hidden'); this.container.classList.remove('not-shown'); + // A shown bar is interactive again, so its controls return to the tab order and to assistive technology. + this.setBarInert(false); if (this.main) this.main.classList.remove('audio-player-not-shown'); if (wasHidden) @@ -706,11 +954,27 @@ if (this.container.classList.contains('not-shown')) return; this.container.classList.add('not-shown'); + // A collapsed bar is only hidden by height and overflow, so its focusable controls would otherwise stay in + // the tab order while invisible; inert removes the whole bar from the tab order and from assistive technology. + this.setBarInert(true); if (this.main) this.main.classList.add('audio-player-not-shown'); this.events.emit(LuminaAudioPlayer.PlayerEvent.VISIBILITY_CHANGED, { isVisible: false }); } + /** + * Sets whether the bar is inert, so that a collapsed bar keeps no focusable control in the tab order. + * @param {boolean} isInert - True to remove the bar and its controls from the tab order and from assistive technology. + */ + setBarInert(isInert) { + if (!this.container) + return; + if (isInert) + this.container.setAttribute('inert', ''); + else + this.container.removeAttribute('inert'); + } + /** * Checks whether the bar is in its expanded form. * @returns {boolean} True when the bar is expanded. @@ -783,6 +1047,37 @@ return this.muted; } + /** + * Checks whether the bar is showing a loading state, which is the case both while a seek waits for the range of + * its target position and while the engine reports that it is waiting for data on its own. + * @returns {boolean} True when the player is buffering. + */ + isBuffering() { + return this.buffering; + } + + /** + * Gets the time ranges the engine has already downloaded, in seconds. An engine that does not report them + * yields an empty list, and the player then never shows a loading state for a seek, because it cannot know + * whether the target is buffered. + * @returns {Array<{ start: number, end: number }>} The buffered time ranges, in ascending order. + */ + getBufferedTimeRanges() { + if (!this.engine || typeof this.engine.getBufferedTimeRanges !== 'function') + return []; + try { + const ranges = this.engine.getBufferedTimeRanges(); + // A copy is returned, never the live array of the engine, so a consumer that reads or writes the list + // cannot reach into the download state of the engine, exactly like the other getters copy. + return Array.isArray(ranges) + ? ranges.map((range) => ({ start: range.start, end: range.end })) + : []; + } catch (error) { + console.debug('Audio player: the buffered ranges of the engine could not be read.', error); + return []; + } + } + /** * Gets the stored playback preferences loaded for the user. * @returns {Object} The preferences. @@ -847,6 +1142,19 @@ document.removeEventListener('click', this.descriptorClickHandler); this.descriptorClickHandler = null; } + if (this.keyboardHandler) { + document.removeEventListener('keydown', this.keyboardHandler); + this.keyboardHandler = null; + } + if (this.unloadHandler) { + window.removeEventListener('pagehide', this.unloadHandler); + this.unloadHandler = null; + } + // A change that is still inside its debounce window is flushed before the timer is dropped, so a teardown + // never loses the last volume or mute the user set. The flush clears the timer itself. + await this.flushPlaybackStateAsync(); + this.endScrub(); + this.endVolumeAdjust(); for (const control of this.controlHandlers) control.element.removeEventListener(control.event, control.handler); this.controlHandlers = []; @@ -906,6 +1214,7 @@ */ fail(error, code = LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) { const typed = this.raiseError(error, code); + this.clearBuffering(); this.setState(LuminaAudioPlayer.PlayerState.ERROR); return typed; } @@ -994,6 +1303,7 @@ reportTime: (currentTime, duration) => this.handleEngineTime(currentTime, duration), reportDuration: (duration) => this.handleEngineDuration(duration), reportProgress: (fraction) => this.handleEngineProgress(fraction), + reportBuffering: (isBuffering) => this.handleEngineBuffering(isBuffering), reportEnded: () => this.handleEngineEnded(), reportError: (error) => this.fail(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) }; @@ -1011,9 +1321,41 @@ this.handleEngineDuration(duration); const position = Number(currentTime); this.currentTime = Number.isFinite(position) && position > 0 ? position : 0; + // The playhead crossing from where the seek started into the target means its range arrived, so the loading + // state of the seek is cleared. The crossing is directional: a forward seek clears once the playhead + // reaches the target, while a backward seek clears once it falls to the target, so the pre-seek position + // the engine reports first never clears the state. Engine-originated buffering is not playhead driven and + // is left untouched here. + if (this.pendingSeekTime !== null && this.hasReachedPendingSeek()) + this.clearSeekPending(); this.scheduleProgressRender(); } + /** + * Checks whether the playhead has crossed from where a pending seek started into its target. + * @returns {boolean} True when the playhead reached the target, within the settle tolerance. + */ + hasReachedPendingSeek() { + const target = this.pendingSeekTime; + const from = this.pendingSeekFromTime; + // Without a start position there is no direction to check, so any report counts as having arrived. + if (from === null) + return true; + return target >= from + ? this.currentTime >= target - SEEK_SETTLE_TOLERANCE_SECONDS + : this.currentTime <= target + SEEK_SETTLE_TOLERANCE_SECONDS; + } + + /** + * Handles a buffering report from the engine, so an engine that fetches a range on its own can show the same + * loading state the player shows for its own seeks. The state is kept on its own flag, so a playhead report + * never clears a buffering state the engine reported. + * @param {boolean} isBuffering - True when the engine is waiting for data, false when it has enough to play. + */ + handleEngineBuffering(isBuffering) { + this.setEngineBuffering(isBuffering === true); + } + /** * Handles a duration report from the engine. * @param {number} duration - The known duration, in seconds. @@ -1037,6 +1379,10 @@ handleEngineProgress(fraction) { const value = clamp(Number(fraction), 0, 1); this.downloadedFraction = value; + // The range a pending seek waits for may have just arrived, so the seek is cleared as soon as the buffered + // ranges cover the target, whichever direction it was in. Engine-originated buffering is left untouched. + if (this.pendingSeekTime !== null && this.isPositionBuffered(this.pendingSeekTime)) + this.clearSeekPending(); this.scheduleProgressRender(); this.events.emit(LuminaAudioPlayer.PlayerEvent.PROGRESS, { downloadedFraction: value }); } @@ -1113,10 +1459,25 @@ this.events.emit(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, Object.freeze({ ...this.preferences })); } if (playbackState) { - if (Number.isFinite(Number(playbackState.volume))) - await this.setVolumeAsync(clamp(Number(playbackState.volume), 0, 1)); - if (typeof playbackState.isMuted === 'boolean') - await this.setMutedAsync(playbackState.isMuted); + // The state the server holds is recorded before it is applied, so a change the user makes while this + // request was in flight is still seen as a difference and written, instead of being recorded as already + // persisted and dropped. The stored state is applied through the internal appliers, which neither mark + // it as a user change nor write it back, and it is skipped for whichever control the user already + // changed, so the late answer never reverts the user's own choice. + this.lastPersistedPlaybackState = { + volume: Number.isFinite(Number(playbackState.volume)) ? clamp(Number(playbackState.volume), 0, 1) : this.volume, + isMuted: typeof playbackState.isMuted === 'boolean' ? playbackState.isMuted : this.muted + }; + if (Number.isFinite(Number(playbackState.volume)) && !this.hasUserChangedVolume) + await this.applyVolumeValueAsync(clamp(Number(playbackState.volume), 0, 1), false); + if (typeof playbackState.isMuted === 'boolean' && !this.hasUserChangedMute) + await this.applyMuteValueAsync(playbackState.isMuted, false); + // The stored state is now known, so a write is allowed from this point on. A change the user made while + // this request was in flight was refused a write until now, so it is scheduled here to be written with + // the stored state of the control the user did not change. + this.isStoredPlaybackStateLoaded = true; + if (this.hasUserChangedVolume || this.hasUserChangedMute) + this.schedulePlaybackStatePersist(); } } @@ -1152,7 +1513,7 @@ }); if (response.redirected) { // The session expired and the server answered with the login page; follow it, and report the redirect, not a failure. - window.location.href = response.url; + navigateToRedirect(response.url); return REDIRECTED; } if (!response.ok) @@ -1165,11 +1526,60 @@ } } + /** + * Writes a JSON payload to a web endpoint, with the anti-forgery token the page rendered, without surfacing a + * notification on failure, because the request is a background one that must never disturb the page. + * @param {string} url - The endpoint URL. Nothing is requested when it is empty. + * @param {Object} data - The payload to send as the JSON body. + * @param {Object} [options] - The request options. + * @param {boolean} [options.keepalive=false] - True to let the browser finish the request after the page is gone, used by the unload flush. + * @returns {Promise<*|null|undefined|Object>} The unwrapped data, null when the endpoint answered without data, undefined when the request failed, or the REDIRECTED marker when the session expired and the page is navigating away. + */ + async postJsonAsync(url, data, options = {}) { + if (!url) + return null; + try { + const headers = { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'X-Requested-With': 'XMLHttpRequest' + }; + // The state endpoint validates an anti-forgery token, which the global scripts partial renders into the + // page, so the header is set whenever the token is present. + const token = document.querySelector('input[name="__RequestVerificationToken"]'); + if (token && token.value) + headers['RequestVerificationToken'] = token.value; + const response = await fetch(url, { + method: 'POST', + headers: headers, + body: JSON.stringify(data ?? {}), + // A keepalive request is not cancelled when the page unloads, so the last volume or mute set before + // leaving the page is not lost to the navigation. + keepalive: options.keepalive === true + }); + if (response.redirected) { + // The session expired and the server answered with the login page; follow it, and report the redirect, not a failure. + navigateToRedirect(response.url); + return REDIRECTED; + } + if (!response.ok) + return undefined; + const payload = await response.json(); + return payload && payload.success === true ? payload.data : null; + } catch (error) { + console.error('Audio player: a playback state request failed.', error); + return undefined; + } + } + /** * Applies the effective volume to the engine. * @returns {Promise} A promise that completes when the engine received the volume. */ async applyVolumeAsync() { + // The volume control is rendered before the engine check, so the bar reflects the volume even before the first + // track creates an engine. + this.renderVolume(); // Before the first play there is no engine to receive the volume, so it is remembered and applied when the engine is // created, which keeps a volume set before playback from being lost. if (!this.engine) @@ -1200,19 +1610,452 @@ } /** - * Handles a click on the progress bar as a seek to the clicked ratio. - * @param {MouseEvent} event - The click event on the progress bar. + * Handles a pointer press on the progress bar: it captures the pointer so a drag that leaves the bar keeps + * scrubbing, and moves the preview to the pressed ratio. + * @param {PointerEvent} event - The pointer event on the progress bar. */ - handleProgressClick(event) { - // Without a track, without a known duration, without the bar, or with a zero width bar there is no position to - // map the click to, and dividing by the width would produce a NaN seek, so the click is ignored instead. + handleProgressPointerDown(event) { + // Scrubbing only makes sense with a track and a known duration, because the ratio is mapped through the + // duration; without the bar there is nothing to scrub either. A secondary mouse button is ignored. if (!this.descriptor || this.duration <= 0 || !this.dom.progress) return; - const bounds = this.dom.progress.getBoundingClientRect(); - if (bounds.width <= 0) + if (event.button !== undefined && event.button !== 0) return; - const ratio = clamp((event.clientX - bounds.left) / bounds.width, 0, 1); - this.seekAsync(ratio * this.duration); + event.preventDefault(); + // The pointer press is prevented so it never starts a text selection, which suppresses the default focus on + // a press, so the element is focused explicitly; a focusable slider is then reachable and operable by + // keyboard, and the shortcut handler routes to it. + if (typeof this.dom.progress.focus === 'function') + this.dom.progress.focus({ preventScroll: true }); + // The bounds are measured once, at the start of the drag, so a pointer move never reads the layout again. + this.progressBounds = this.dom.progress.getBoundingClientRect(); + this.isScrubbing = true; + this.scrubPointerId = event.pointerId; + this.dom.progress.classList.add('is-scrubbing'); + try { + this.dom.progress.setPointerCapture(event.pointerId); + } catch (error) { + console.debug('Audio player: the progress bar could not capture the pointer.', error); + } + this.updateScrubFromPointer(event); + } + + /** + * Handles a pointer move while scrubbing the progress bar, updating the preview position. + * @param {PointerEvent} event - The pointer event on the progress bar. + */ + handleProgressPointerMove(event) { + if (!this.isScrubbing) + return; + event.preventDefault(); + this.updateScrubFromPointer(event); + } + + /** + * Handles the release of the pointer that scrubbed the progress bar: the seek is committed once, at the + * scrubbed position, so that dragging across the bar never issues one range fetch per pixel. + */ + handleProgressPointerUp() { + if (!this.isScrubbing) + return; + const ratio = this.scrubRatio; + this.scrubRatio = null; + this.endScrub(); + // A scrub that never moved still commits the pressed ratio, so a plain click keeps seeking where it clicked. + if (ratio !== null) + this.seekAsync(ratio * this.duration); + else + this.scheduleProgressRender(); + } + + /** + * Handles the cancellation of the pointer that scrubbed the progress bar, which happens when the browser takes + * the gesture over. The scrub is abandoned without seeking, and the bar returns to the reported playhead. + */ + handleProgressPointerCancel() { + if (!this.isScrubbing) + return; + this.scrubRatio = null; + this.endScrub(); + this.scheduleProgressRender(); + } + + /** + * Ends a scrub of the progress bar, whatever ends it: the pointer being released, or the track stopping or + * another one starting while the drag is still in progress. It clears the scrubbing state, drops the dragging + * cursor and releases a captured pointer, so a stopped player is never left with a control that still reacts + * to pointer moves. It is idempotent, so calling it when no scrub is in progress is harmless. + */ + endScrub() { + const element = this.dom.progress; + if (element) { + element.classList.remove('is-scrubbing'); + if (this.scrubPointerId !== null) { + try { + element.releasePointerCapture(this.scrubPointerId); + } catch (error) { + console.debug('Audio player: the progress bar could not release the pointer.', error); + } + } + } + this.scrubPointerId = null; + this.progressBounds = null; + this.isScrubbing = false; + } + + /** + * Updates the preview position of a scrub from the horizontal position of the pointer. + * @param {PointerEvent} event - The pointer event on the progress bar. + */ + updateScrubFromPointer(event) { + const ratio = this.computeRatioFromPointer(event, this.dom.progress, this.progressBounds); + if (ratio === null) + return; + this.scrubRatio = ratio; + this.scheduleProgressRender(); + } + + /** + * Handles a pointer press on the volume control: it captures the pointer and starts adjusting the volume. + * @param {PointerEvent} event - The pointer event on the volume control. + */ + handleVolumePointerDown(event) { + if (!this.dom.volume) + return; + if (event.button !== undefined && event.button !== 0) + return; + event.preventDefault(); + // The pointer press is prevented so it never starts a text selection, which suppresses the default focus on + // a press, so the element is focused explicitly; a focusable slider is then reachable and operable by + // keyboard, and the shortcut handler routes to it. + if (typeof this.dom.volume.focus === 'function') + this.dom.volume.focus({ preventScroll: true }); + // The bounds are measured once, at the start of the drag, so a pointer move never reads the layout again. + this.volumeBounds = this.dom.volume.getBoundingClientRect(); + this.isAdjustingVolume = true; + this.volumePointerId = event.pointerId; + this.dom.volume.classList.add('is-scrubbing'); + try { + this.dom.volume.setPointerCapture(event.pointerId); + } catch (error) { + console.debug('Audio player: the volume control could not capture the pointer.', error); + } + this.updateVolumeFromPointer(event); + } + + /** + * Handles a pointer move while adjusting the volume, queuing the volume of the pointer position. + * @param {PointerEvent} event - The pointer event on the volume control. + */ + handleVolumePointerMove(event) { + if (!this.isAdjustingVolume) + return; + event.preventDefault(); + this.updateVolumeFromPointer(event); + } + + /** + * Handles the release of the pointer that adjusted the volume. The last queued volume is applied, because the + * frame it was queued for may not have run yet, so a fast click or the final delta of a drag is never lost. + */ + handleVolumePointerUp() { + if (!this.isAdjustingVolume) + return; + this.endVolumeAdjust(false); + } + + /** + * Handles the cancellation of the pointer that adjusted the volume, which happens when the browser takes the + * gesture over. The queued volume is dropped, so a cancelled gesture never changes the volume. + */ + handleVolumePointerCancel() { + if (!this.isAdjustingVolume) + return; + this.endVolumeAdjust(); + } + + /** + * Ends a volume adjustment, whatever ends it: the pointer being released, or the track stopping or another one + * starting while the drag is still in progress. It clears the adjusting state, drops the dragging cursor and + * releases a captured pointer, so a stopped player is never left with a volume control that still reacts to + * pointer moves. It is idempotent, so calling it when no adjustment is in progress is harmless. + * @param {boolean} [discardPending=true] - True to drop a volume change that is still queued for the next frame, which is what a stop or a track change wants; false to apply it, which is what a pointer release wants. + */ + endVolumeAdjust(discardPending = true) { + const element = this.dom.volume; + if (element) { + element.classList.remove('is-scrubbing'); + if (this.volumePointerId !== null) { + try { + element.releasePointerCapture(this.volumePointerId); + } catch (error) { + console.debug('Audio player: the volume control could not release the pointer.', error); + } + } + } + this.volumePointerId = null; + this.volumeBounds = null; + const pendingRatio = this.pendingVolumeRatio; + // The queued change is cleared either way, so the frame that was scheduled for it finds nothing to do; a + // release applies it here instead, while a stop or a track change drops it, so the control never applies one + // more volume after it was released. + this.pendingVolumeRatio = null; + this.isAdjustingVolume = false; + if (!discardPending && pendingRatio !== null) + this.applyVolumeRatioAsync(pendingRatio); + } + + /** + * Queues the volume of the horizontal position of the pointer, coalescing a burst of pointer moves into a + * single volume change per frame. + * @param {PointerEvent} event - The pointer event on the volume control. + */ + updateVolumeFromPointer(event) { + const ratio = this.computeRatioFromPointer(event, this.dom.volume, this.volumeBounds); + if (ratio === null) + return; + this.pendingVolumeRatio = ratio; + this.scheduleVolumeApply(); + } + + /** + * Schedules the queued volume change on the next frame, so a burst of pointer moves does not turn into a burst + * of volume changes and bar renders. + */ + scheduleVolumeApply() { + if (this.isVolumeApplyScheduled) + return; + this.isVolumeApplyScheduled = true; + const apply = () => { + this.isVolumeApplyScheduled = false; + const ratio = this.pendingVolumeRatio; + this.pendingVolumeRatio = null; + if (ratio !== null) + this.applyVolumeRatioAsync(ratio); + }; + if (typeof requestAnimationFrame === 'function') + requestAnimationFrame(apply); + else + apply(); + } + + /** + * Applies a volume ratio, unmuting a muted player first, exactly like the keyboard shortcut does. + * @param {number} ratio - The volume ratio to apply, between 0 and 1. + * @returns {Promise} A promise that completes when the volume was applied. + */ + async applyVolumeRatioAsync(ratio) { + if (this.muted && ratio > 0) + await this.setMutedAsync(false); + await this.setVolumeAsync(ratio); + } + + /** + * Computes the ratio, between 0 and 1, of the horizontal position of the pointer within an element. + * @param {PointerEvent} event - The pointer event whose position is measured. + * @param {HTMLElement} element - The element the ratio is measured on. + * @param {Object} [bounds] - The bounds of the element, measured when a drag started, so a move never reads the layout. They are measured here when omitted. + * @returns {number|null} The ratio, or null when the element has no measurable width. + */ + computeRatioFromPointer(event, element, bounds) { + if (!element) + return null; + const measured = bounds || element.getBoundingClientRect(); + if (measured.width <= 0) + return null; + return clamp((event.clientX - measured.left) / measured.width, 0, 1); + } + + /** + * Handles a keyboard shortcut of the transport. The listener is on the document, so the shortcuts work without + * the bar being focused, but they never run while a form control or an editable element has focus, and never + * while the bar is hidden, so they never steal a keystroke from the page. + * @param {KeyboardEvent} event - The keydown event. + */ + handleKeyboardShortcut(event) { + if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey) + return; + if (!this.isAvailable || !this.container || this.container.classList.contains('not-shown')) + return; + if (this.isTextEntryTarget(event.target)) + return; + switch (event.key) { + case 'ArrowRight': + this.seekBy(SEEK_STEP_SECONDS); + event.preventDefault(); + break; + case 'ArrowLeft': + this.seekBy(-SEEK_STEP_SECONDS); + event.preventDefault(); + break; + case 'ArrowUp': + this.changeVolumeByAsync(VOLUME_STEP); + event.preventDefault(); + break; + case 'ArrowDown': + this.changeVolumeByAsync(-VOLUME_STEP); + event.preventDefault(); + break; + default: + break; + } + } + + /** + * Checks whether a key event targets a control that consumes the keystroke itself, such as a text field. + * @param {EventTarget|null} target - The target of the key event. + * @returns {boolean} True when the target is a form control or an editable element. + */ + isTextEntryTarget(target) { + if (!(target instanceof Element)) + return false; + const tagName = target.tagName; + if (tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') + return true; + return target.isContentEditable === true; + } + + /** + * Marks whether a seek is waiting for the range of its target, and publishes the combined loading state. + * @param {boolean} isPending - True to mark a seek as pending. + * @param {number|null} targetTime - The position the pending seek waits for. + * @param {number|null} fromTime - The position the pending seek started from, or null. + */ + setSeekPending(isPending, targetTime, fromTime) { + const nextTarget = isPending ? targetTime : null; + const nextFrom = isPending ? fromTime : null; + if (this.pendingSeekTime === nextTarget && this.pendingSeekFromTime === nextFrom) + return; + this.pendingSeekTime = nextTarget; + this.pendingSeekFromTime = nextFrom; + this.updateBufferingState(); + } + + /** + * Clears a pending seek, when there is one, leaving an engine-originated buffering state in place. + */ + clearSeekPending() { + if (this.pendingSeekTime === null && this.pendingSeekFromTime === null) + return; + this.pendingSeekTime = null; + this.pendingSeekFromTime = null; + this.updateBufferingState(); + } + + /** + * Marks whether the engine reports that it is waiting for data on its own, and publishes the combined state. + * @param {boolean} isBuffering - True when the engine is waiting for data. + */ + setEngineBuffering(isBuffering) { + if (this.engineBuffering === isBuffering) + return; + this.engineBuffering = isBuffering; + this.updateBufferingState(); + } + + /** + * Recomputes the loading state from the pending seek and the engine buffering report, renders the bar, and + * publishes the change when it moved. The state is shown while either input is active, so a buffering engine + * stays visible even when no seek is pending, and a seek stays visible even when the engine reports no + * buffering. + */ + updateBufferingState() { + const isBuffering = this.pendingSeekTime !== null || this.engineBuffering; + // The event is published when either input changed, so a second seek that only moves the pending target + // while the bar is already buffering still carries the new target, exactly as the event documents. + const hasChanged = this.buffering !== isBuffering || this.announcedPendingSeekTime !== this.pendingSeekTime; + this.buffering = isBuffering; + this.scheduleProgressRender(); + if (!hasChanged) + return; + this.announcedPendingSeekTime = this.pendingSeekTime; + this.events.emit(LuminaAudioPlayer.PlayerEvent.BUFFERING_CHANGED, { + isBuffering: this.buffering, + pendingSeekTime: this.pendingSeekTime + }); + } + + /** + * Clears the whole loading state: a pending seek and an engine-originated buffering report. + */ + clearBuffering() { + const hadSeek = this.pendingSeekTime !== null || this.pendingSeekFromTime !== null; + const hadEngineBuffering = this.engineBuffering; + if (!hadSeek && !hadEngineBuffering) + return; + this.pendingSeekTime = null; + this.pendingSeekFromTime = null; + this.engineBuffering = false; + this.updateBufferingState(); + } + + /** + * Checks whether a position, in seconds, falls inside one of the ranges the engine downloaded. + * @param {number} seconds - The position to check. + * @returns {boolean} True when the position is covered by a buffered range. + */ + isPositionBuffered(seconds) { + const ranges = this.getBufferedTimeRanges(); + if (ranges.length === 0) + return false; + return ranges.some((range) => Number.isFinite(range.start) && Number.isFinite(range.end) && seconds >= range.start && seconds <= range.end); + } + + /** + * Schedules a write of the volume and mute state to the stored playback state of the user. + * + * A drag of the volume control changes the volume on every pointer move, so the writes are coalesced into one + * request. Only a user change schedules a write: the stored state is applied through the internal appliers, + * which never call this. + */ + schedulePlaybackStatePersist() { + if (this.persistenceTimer !== null) + clearTimeout(this.persistenceTimer); + this.persistenceTimer = setTimeout(() => { + this.persistenceTimer = null; + this.persistPlaybackStateAsync(); + }, PLAYBACK_STATE_PERSIST_DELAY_MS); + } + + /** + * Writes the volume and mute state right away, cancelling a scheduled debounce, so a change that is still + * waiting is not lost when the page goes away or the player is torn down. + * @param {Object} [options] - The request options, forwarded to the write. + * @returns {Promise} A promise that completes when the write was attempted. + */ + flushPlaybackStateAsync(options = {}) { + if (this.persistenceTimer !== null) { + clearTimeout(this.persistenceTimer); + this.persistenceTimer = null; + } + return this.persistPlaybackStateAsync(options); + } + + /** + * Writes the volume and mute state to the stored playback state of the user, unless it is already the stored + * state. The request is best effort: a failure is logged, and the player keeps working with the local values. + * + * The write is refused until the stored state has been read once. The endpoint takes the whole state, both the + * volume and the mute flag, and rejects a missing one, so writing the local defaults of a player that has not + * loaded the stored state yet, for example from the unload flush, would overwrite what the user had stored. + * @param {Object} [options] - The request options, forwarded to the write. + * @returns {Promise} A promise that completes when the write was attempted. + */ + async persistPlaybackStateAsync(options = {}) { + if (!this.isStoredPlaybackStateLoaded) + return; + const configuration = this.getConfiguration(); + const url = configuration.updatePlaybackStateUrl; + if (!url) + return; + const state = { volume: this.volume, isMuted: this.muted }; + const last = this.lastPersistedPlaybackState; + if (last && last.volume === state.volume && last.isMuted === state.isMuted) + return; + // The state is remembered as persisted before the request settles, so a failed background write is not + // retried on every later change of an unrelated value. + this.lastPersistedPlaybackState = state; + await this.postJsonAsync(url, state, options); } /** @@ -1220,6 +2063,7 @@ */ applyHiddenState() { this.container.classList.add('not-shown'); + this.setBarInert(true); if (this.main) this.main.classList.add('audio-player-not-shown'); } @@ -1279,30 +2123,141 @@ } /** - * Renders the three state progress bar: the played part, the downloaded part, and the remainder. + * Renders the three state progress bar: the played part, the downloaded but not played part, and the not yet + * downloaded part. + * + * The player publishes the geometry of each state, as a start and a width, through the CSS custom properties + * '--audio-player-progress--start' and '--audio-player-progress--width' on the bar, where the + * state is 'played', 'downloaded' or 'undownloaded'. It writes no inline geometry, so a theme consumes those + * properties to style each state, and to give the bar any shape or orientation; the fallback stylesheet + * consumes them too. The player never hardcodes a color or a shape here. While the bar is scrubbed the position + * shown is the scrub position, and while a seek waits for its range the bar is marked with the 'is-buffering' + * class and the 'buffering' state. */ renderProgress() { - // Only widths are written here, as percentages; the colors, shape and layering of the three states belong to the - // theme's CSS, which selects them through the classes on the bar elements, so the player never hardcodes a look. - if (this.dom.currentTime) - this.dom.currentTime.textContent = formatTime(this.currentTime); - if (this.dom.totalTime) - this.dom.totalTime.textContent = formatDuration(this.duration); - const playedRatio = this.duration > 0 ? clamp(this.currentTime / this.duration, 0, 1) : 0; + const isScrubbing = this.scrubRatio !== null; + const position = isScrubbing ? this.scrubRatio * this.duration : this.currentTime; + const playedRatio = this.duration > 0 ? clamp(position / this.duration, 0, 1) : 0; const downloadedRatio = clamp(this.downloadedFraction, 0, 1); - if (this.dom.progressPlayed) - this.dom.progressPlayed.style.width = `${playedRatio * 100}%`; - if (this.dom.progressDownloaded) - this.dom.progressDownloaded.style.width = `${downloadedRatio * 100}%`; + // The downloaded but not played state runs from the playhead to the downloaded frontier, and the not yet + // downloaded state runs from that frontier to the end. Scrubbing past the frontier keeps the three states + // contiguous by moving the frontier with the scrub position. + const frontier = Math.max(playedRatio, downloadedRatio); + const downloadedOnlyRatio = Math.max(downloadedRatio - playedRatio, 0); + const undownloadedRatio = clamp(1 - frontier, 0, 1); + const currentTimeText = formatTime(position); + const totalTimeText = formatDuration(this.duration); + // The bar is a slider: its value is the playhead in seconds, its maximum is the duration once it is known, + // and its readable value is the position within the track, replaced by the loading label while it buffers. + const maximum = this.duration > 0 ? Math.max(1, Math.round(this.duration)) : 1; + const value = Math.round(clamp(playedRatio, 0, 1) * maximum); + const strings = this.getStrings(); + const bufferingLabel = this.buffering ? (strings.buffering || '') : ''; + const valueText = bufferingLabel !== '' ? bufferingLabel : `${currentTimeText} / ${totalTimeText}`; + const state = this.descriptor ? (this.buffering ? 'buffering' : 'ready') : 'idle'; + // The values are compared to the previous render, so a report that arrives between two seconds skips the + // clock and the accessible value instead of rewriting them unchanged, while the geometry, which moves every + // frame during playback, is still written. + const next = { + currentTimeText, + totalTimeText, + playedStart: '0%', + playedWidth: `${playedRatio * 100}%`, + downloadedStart: `${playedRatio * 100}%`, + downloadedWidth: `${downloadedOnlyRatio * 100}%`, + undownloadedStart: `${frontier * 100}%`, + undownloadedWidth: `${undownloadedRatio * 100}%`, + buffering: this.buffering, + state, + seekLabel: strings.seek || null, + maximum: String(maximum), + value: String(value), + valueText, + ariaBusy: this.buffering ? 'true' : 'false' + }; + const previous = this.renderedProgress; + this.renderedProgress = next; + const changed = (key) => !previous || previous[key] !== next[key]; + if (this.dom.currentTime && changed('currentTimeText')) + this.dom.currentTime.textContent = currentTimeText; + if (this.dom.totalTime && changed('totalTimeText')) + this.dom.totalTime.textContent = totalTimeText; + if (this.dom.progress) { + // Each state gets the start and the width it occupies, so the name of a property and the value it + // carries always agree, and no theme has to subtract one state from another. + const style = this.dom.progress.style; + if (changed('playedStart')) style.setProperty('--audio-player-progress-played-start', next.playedStart); + if (changed('playedWidth')) style.setProperty('--audio-player-progress-played-width', next.playedWidth); + if (changed('downloadedStart')) style.setProperty('--audio-player-progress-downloaded-start', next.downloadedStart); + if (changed('downloadedWidth')) style.setProperty('--audio-player-progress-downloaded-width', next.downloadedWidth); + if (changed('undownloadedStart')) style.setProperty('--audio-player-progress-undownloaded-start', next.undownloadedStart); + if (changed('undownloadedWidth')) style.setProperty('--audio-player-progress-undownloaded-width', next.undownloadedWidth); + if (changed('buffering')) this.dom.progress.classList.toggle('is-buffering', next.buffering); + if (changed('state')) this.dom.progress.dataset.audioPlayerProgressState = next.state; + if (!previous) this.dom.progress.setAttribute('aria-valuemin', '0'); + if (changed('maximum')) this.dom.progress.setAttribute('aria-valuemax', next.maximum); + if (changed('value')) this.dom.progress.setAttribute('aria-valuenow', next.value); + if (changed('valueText')) this.dom.progress.setAttribute('aria-valuetext', next.valueText); + if (changed('ariaBusy')) this.dom.progress.setAttribute('aria-busy', next.ariaBusy); + // The seek label comes from the configuration, so a themed bar that renders no label of its own still + // gets one; the fallback markup already carries it, and setting an identical value is skipped. + if (next.seekLabel && changed('seekLabel')) + this.dom.progress.setAttribute('aria-label', next.seekLabel); + } } /** - * Renders the play or pause affordance of the transport control. + * Renders the play or pause affordance of the transport control, and its accessible label. */ renderTransportState() { const isPlaying = this.state === LuminaAudioPlayer.PlayerState.PLAYING; - if (this.dom.playPause) - this.dom.playPause.classList.toggle('is-playing', isPlaying); + if (!this.dom.playPause) + return; + this.dom.playPause.classList.toggle('is-playing', isPlaying); + const strings = this.getStrings(); + const label = isPlaying ? strings.pause : strings.play; + if (label) + this.dom.playPause.setAttribute('aria-label', label); + } + + /** + * Renders the volume control and the mute toggle: the fill of the volume bar, and the accessible value and + * label of both controls. The volume shown is the volume the user set, even while the output is muted, and the + * muted state is exposed both as the 'aria-pressed' state of the toggle and as the 'is-muted' class. + * + * The fill is published as the '--audio-player-volume-start' and '--audio-player-volume-width' custom properties + * on the control, which the stylesheet consumes, so a theme restyles or reorients the bar the same way it does + * the progress bar; no inline geometry is written. + */ + renderVolume() { + const strings = this.getStrings(); + const levelRatio = clamp(this.volume, 0, 1); + if (this.dom.volume) { + this.dom.volume.style.setProperty('--audio-player-volume-start', '0%'); + this.dom.volume.style.setProperty('--audio-player-volume-width', `${levelRatio * 100}%`); + this.dom.volume.setAttribute('aria-valuemin', '0'); + this.dom.volume.setAttribute('aria-valuemax', '100'); + this.dom.volume.setAttribute('aria-valuenow', String(Math.round(levelRatio * 100))); + if (strings.volume) + this.dom.volume.setAttribute('aria-label', strings.volume); + this.dom.volume.classList.toggle('is-muted', this.muted); + } + if (this.dom.mute) { + this.dom.mute.setAttribute('aria-pressed', this.muted ? 'true' : 'false'); + this.dom.mute.classList.toggle('is-muted', this.muted); + const label = this.muted ? strings.unmute : strings.mute; + if (label) + this.dom.mute.setAttribute('aria-label', label); + } + } + + /** + * Gets the localized strings of the bar, emitted with the global scripts configuration. + * @returns {Object} The strings, keyed by name, or an empty object. + */ + getStrings() { + const configuration = this.getConfiguration(); + return configuration && configuration.strings ? configuration.strings : {}; } /** From 4e06cc47d36a2036608b8ec785c3a9389b20be1e Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 16 Oct 2026 17:26:54 +0300 Subject: [PATCH 16/77] Adds the audio player Web Audio output and scheduler. --- .../Views/Shared/_ThemeLayoutScripts.cshtml | 1 + .../js/audio-player/audio-player-render.js | 1582 +++++++++++++++++ 2 files changed, 1583 insertions(+) create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 1bd1dd28..8698f4b9 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -68,6 +68,7 @@ + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js new file mode 100644 index 00000000..3528bce1 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js @@ -0,0 +1,1582 @@ +/** + * Web Audio output and scheduler of the audio player. + * + * The player never uses a native audio element, so the sound of a track is produced here. This module owns an + * AudioContext, a master GainNode that carries the output volume and the mute state, and a per-track GainNode that + * carries the ReplayGain normalization of the current track, and it schedules decoded audio for playback. It does not + * read files, decode anything or fetch bytes: the download engine of the player brings the bytes in, the decode pipeline + * turns them into decoded audio, and the scheduler of this module turns that decoded audio into sound. + * + * Signal chain + * ------------ + * Every scheduled source is connected to the per-track GainNode, which feeds the master GainNode, which feeds the + * destination, so: + * - the master gain is the output volume, and it is zero while the player is muted, which is how mute is honored; + * - the per-track gain is the ReplayGain linear gain of the current track, chosen by the user's ReplayGain mode among + * the values the playback manifest carries. + * Keeping the master gain and the ReplayGain gain on two separate nodes lets either change without disturbing the other. + * The engine of the player folds the mute state into the volume it passes, so it delivers a mute as setVolumeAsync(0) + * and never calls setMutedAsync; that setter exists for a caller that owns both the volume and the mute state itself. + * + * Scheduling model + * ---------------- + * A decoded AudioData is converted to an AudioBuffer, one channel at a time, and scheduled with start(when) on the + * context timeline. The scheduler keeps a media cursor, the media position of the next buffer, and a wall clock cursor, + * the context time at which the next buffer starts, and it lays every buffer directly after the one before it, so the + * decoded audio of a track plays back to back with no gap. It maintains the playhead as an anchor, a pair of a context + * time and the media position the audio had at that context time, so the current time is derived from the context clock + * rather than guessed, and it stays accurate while the context runs and frozen while the context is suspended. + * + * The playhead is the media position of the audio, not the position of the download: the scheduler reports the position + * of the samples that were actually handed to it, so a track that has only been partially decoded reports the position + * it reached, never the position the buffer has merely downloaded. + * + * End of stream + * ------------- + * A drained schedule is not the end of a track: a decode that is slower than real time, a garbage collection pause or a + * cold start can leave the schedule empty while more audio is still on its way. The renderer reports the end only once + * the schedule has drained and the decode pipeline has stated that it fed the last decoded frame, by calling + * markStreamComplete. Completion is never inferred from the duration of the manifest, because that duration is a whole + * number of seconds and a decode that is still on its way near the end would then have its last frames cut off. A drained + * schedule that is not complete is a gap: the renderer keeps playing, reports the playhead pinned to the frontier of the + * scheduled audio, and waits for more, which is what lets the later stages treat a gap as an underrun and recover from + * it instead of ending the track. The end is also detected from the end of the last source, so a tab that the browser + * hides, and whose animation frame loop it suspends, still reaches the end while the audio keeps playing. The end is + * reported through onEnded once per configured track: a buffer scheduled after an end resumes playback, but the callback + * is not fired a second time, so a consumer that advances a queue on it is never advanced twice for one track. + * + * Backpressure + * ------------ + * The scheduler accepts decoded audio as fast as it is handed to it and never drops a buffer, so a decoder that runs + * faster than real time would queue a large part of a track and hold its decoded audio in memory. It therefore exposes + * getScheduledAheadSeconds, the wall time between the audio clock and the end of the schedule, which a decode loop + * polls to pace itself, exactly as it uses the decode queue size of its decoder. A caller that cannot be trusted to pace + * itself can be contained with the maxScheduledAheadSeconds option, which refuses a buffer that would run the schedule + * too far ahead instead of letting it, and the decoded audio it retains, grow without bound. + * + * Seeking + * ------- + * The renderer owns the absolute media position of the track, not a position relative to whatever was decoded first, so + * seekTo moves the schedule to a media offset: it releases the scheduled audio, places the playhead there, and treats + * the next buffer that is scheduled as the audio at that position. It is only the scheduler half of a seek; the caller + * resets its decoder, fetches the byte range of the target and re-demuxes from there, after which the renderer keeps the + * reported time, the duration and the end check absolute across the seek. + * + * The caller must supply the first buffer that follows a seek starting exactly at the requested position. The renderer + * stamps that buffer as the audio at the target and has no way to correct an offset it is not told about, so a demuxer + * that lands on a packet boundary before the target must trim the leading samples to the target before it schedules + * them. Because a null schedule reports no end by itself, the renderer also never declares the end until at least one + * buffer has been scheduled since the last reset. + * + * Playing, pausing and the playback rate + * -------------------------------------- + * playAsync resumes the AudioContext, which is the call that needs a user gesture, and is meant to be invoked from the + * play affordance of the player. pauseAsync suspends the AudioContext, so the context clock freezes and the current + * time freezes with it, while the buffers that are already scheduled stay scheduled; resuming continues at the very + * position the pause froze. A playback rate other than one rescales how much media a unit of context time carries, so + * changing it re-times the buffers that have not finished yet, keeping the audio continuous. + * + * Sample rate + * ----------- + * A decoded AudioData may carry a sample rate that differs from the sample rate of the context. The buffer of such a + * decode is created at the decoded rate whenever the browser accepts it, which makes the Web Audio graph resample it on + * output; only a rate outside the range a buffer may carry falls back to a linear resample into the context rate, so the + * common case never pays for a resample in JavaScript. + * + * Decoded audio contract + * ---------------------- + * The scheduler copies each channel of an AudioData as planar 32 bit floats, so the decode pipeline must hand over planar + * float audio. The module cannot enforce the layout of a decoder, so a source in any other layout is refused with a + * typed error rather than reinterpreted. The scheduler takes ownership of every AudioData it receives: it closes it, + * releasing its native memory, before schedule returns or throws, so a caller must not use the object again and must not + * close it itself. A decode loop therefore hands each decoded frame to schedule exactly once. + * + * Reporting and failures + * ---------------------- + * The renderer is a sub component, like the download engine. It records the failures it cannot recover from, so that they + * are readable through getError: a context that refuses to suspend or to close, and a decode it refuses, all land there. + * A condition it recovers from, such as a gain automation the browser rejects and that falls back to a direct assignment, + * is only logged. The calls a pipeline drives, configure, playAsync, schedule and seekTo, throw the typed error, because + * the caller that triggered the failure is the one that can react to it; setPlaybackRate can also throw when the re-time + * of the schedule fails, while the other setters and the pause and teardown calls never throw. A caller observes the + * playhead and the end of the audio through the optional onTimeUpdate and onEnded callbacks, or by polling getCurrentTime + * and isPlaying: the renderer advances its own schedule for the whole duration of playback, so the end is reached and + * isPlaying turns false either way. destroyAsync releases every resource, including the AudioContext when the renderer + * owns it. + * + * Using it + * -------- + * const renderer = LuminaAudioPlayer.createTrackRenderer({ + * replayGainMode: host.getPreferences().replayGainMode, + * events: host.events, + * onTimeUpdate: (time, duration) => host.reportTime(time, duration), + * onEnded: () => host.reportEnded() + * }); + * renderer.configure(manifest); + * await renderer.playAsync(); // from a user gesture + * renderer.schedule(audioData); // from the decode output callback, once per decoded frame, + * // paced by renderer.getScheduledAheadSeconds() + * renderer.markStreamComplete(); // once the last decoded frame of the track was fed + * await renderer.pauseAsync(); + * await renderer.destroyAsync(); + * + * When the player event bus is provided, the renderer follows the ReplayGain mode of the player on its own. Volume and + * mute are deliberately not read from the bus: they are driven by the caller through setVolumeAsync and setMutedAsync, + * which is what the engine interface hands over, so the master gain has a single writer. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Clamps a number into an inclusive range, through the shared helper on the namespace. The reference is resolved on + * every call rather than captured at load time, so this module does not depend on the load order of the util. + * @param {number} value - The value to clamp. + * @param {number} minimum - The inclusive lower bound. + * @param {number} maximum - The inclusive upper bound. + * @returns {number} The clamped value. + */ + function clamp(value, minimum, maximum) { + return LuminaAudioPlayer.clamp(value, minimum, maximum); + } + + /** + * The user facing ways ReplayGain normalization is applied to a track. + * + * This list mirrors the ReplayGainMode enumeration of the server (Lumina.Domain.SharedKernel.Common.Enums.Playback). + * A mode added to the server must be added here too: a value the server sends that is not listed is reported by + * normalizeReplayGainMode and treated as no normalization, so the two lists cannot drift apart silently. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerReplayGainMode = Object.freeze({ + // ReplayGain is not applied, and the track plays at the loudness at which it was stored. + OFF: 'Off', + // Each track is normalized with its own ReplayGain track gain. + TRACK: 'Track', + // Each track is normalized with the ReplayGain album gain of its album. + ALBUM: 'Album' + }); + + /** + * The lowest playback rate the renderer accepts. A lower rate stretches the audio so far that it stops being useful, + * and a rate of zero or below would freeze or reverse the timeline of the scheduler. It is a module local, not a + * namespace value, so no other script can change the bound the renderer enforces. + * @readonly + * @type {number} + */ + const MIN_PLAYBACK_RATE = 0.25; + + /** + * The highest playback rate the renderer accepts. + * @readonly + * @type {number} + */ + const MAX_PLAYBACK_RATE = 4; + + /** + * The lowest sample rate an AudioBuffer may carry, per the Web Audio specification. A buffer created below it, or + * above MAX_AUDIO_BUFFER_SAMPLE_RATE, is rejected by the browser. + * @readonly + * @type {number} + */ + const MIN_AUDIO_BUFFER_SAMPLE_RATE = 3000; + + /** + * The highest sample rate an AudioBuffer may carry, per the Web Audio specification. + * @readonly + * @type {number} + */ + const MAX_AUDIO_BUFFER_SAMPLE_RATE = 768000; + + /** + * The largest number of frames a single decoded chunk may carry. It is a hard allocation ceiling, far above the size of + * a real decoded packet, which is a fraction of a second: it exists only to refuse a value so large that allocating a + * buffer for it would be the wrong thing to do. + * @readonly + * @type {number} + */ + const MAX_DECODED_FRAMES_PER_CHUNK = 1000000; + + /** + * The largest number of channels a single decoded chunk may carry. Web Audio refuses to create a buffer with more than + * 32 channels, so the bound matches that limit and a chunk beyond it is rejected here instead of failing later in createBuffer. + * @readonly + * @type {number} + */ + const MAX_DECODED_CHANNELS = 32; + + /** + * The largest number of samples, that is frames times channels, a single decoded chunk, or the resampled output of + * one, may carry. It is the bound that actually matters, because a buffer allocates its samples in one block, so the + * frame and channel bounds are checked together as a product through this one. At four bytes a sample it caps a + * single allocation at sixteen megabytes. + * @readonly + * @type {number} + */ + const MAX_DECODED_SAMPLES_PER_CHUNK = 4194304; + + /** + * The lead, in seconds, the very first buffer of a chain is scheduled ahead of the context clock. Without a lead, the + * scheduling could land in the past of the audio thread and drop the start, while a large lead would delay the first + * sound; this one is small enough to be inaudible and large enough to absorb the audio thread quantum. + * @readonly + * @type {number} + */ + const MIN_SCHEDULE_LEAD_SECONDS = 0.02; + + /** + * The time constant, in seconds, of a master gain change. It de-zippers a volume or mute change, so dragging the + * volume control never produces a click. + * @readonly + * @type {number} + */ + const MASTER_GAIN_RAMP_SECONDS = 0.02; + + /** + * The time constant, in seconds, of a per-track gain change, applied when a track starts or the ReplayGain mode + * changes. + * @readonly + * @type {number} + */ + const TRACK_GAIN_RAMP_SECONDS = 0.05; + + /** + * The interval, in milliseconds, the reporter falls back to when the page has no requestAnimationFrame. + * @readonly + * @type {number} + */ + const REPORTER_FALLBACK_INTERVAL_MS = 16; + + /** + * Coerces a value to a finite number, or null when it is absent or not finite. + * @param {*} value - The value to coerce. + * @returns {number|null} The finite number, or null. + */ + function toFiniteNumber(value) { + if (value === null || value === undefined || value === '') + return null; + const number = Number(value); + return Number.isFinite(number) ? number : null; + } + + /** + * Normalizes a ReplayGain mode into one of the {@link LuminaAudioPlayer.PlayerReplayGainMode} values, defaulting an + * absent or unrecognized value to no normalization. + * @param {string} value - The mode to normalize, as the user settings or the manifest spell it. + * @returns {string} One of the {@link LuminaAudioPlayer.PlayerReplayGainMode} values. + */ + function normalizeReplayGainMode(value) { + // An absent mode, or an empty string, is simply no normalization and is not reported. + if (value === null || value === undefined || value === '') + return LuminaAudioPlayer.PlayerReplayGainMode.OFF; + if (typeof value === 'string') { + const text = value.trim().toLowerCase(); + if (text === '' || text === 'off') + return LuminaAudioPlayer.PlayerReplayGainMode.OFF; + if (text === 'track') + return LuminaAudioPlayer.PlayerReplayGainMode.TRACK; + if (text === 'album') + return LuminaAudioPlayer.PlayerReplayGainMode.ALBUM; + } + // A value the renderer does not know is very likely a mode the server added and this list does not carry yet, so it + // is reported, whatever its type, instead of being dropped silently; the sync of the two lists is documented on the + // enum. + console.warn(`Audio player: the ReplayGain mode '${String(value)}' is not known to the renderer, so no normalization is applied.`); + return LuminaAudioPlayer.PlayerReplayGainMode.OFF; + } + + /** + * Converts a ReplayGain value in decibels into a linear gain, capped so it cannot clip the signal. + * + * ReplayGain carries a track, or album, gain to bring the loudness of the audio to the reference level, and a peak, + * the highest sample amplitude of the audio. A gain that would push the peak above the full scale would clip, so the + * gain is limited to the largest value that keeps the normalized peak at or below the full scale, exactly as the + * ReplayGain specification prescribes. A missing gain means no normalization, and a missing or non positive peak + * leaves the gain uncapped. + * @param {number|null} gainDb - The ReplayGain value, in decibels. + * @param {number|null} peak - The peak amplitude the gain is applied to. + * @returns {number} The linear gain, one when there is nothing to apply. + */ + function computeReplayGainLinearGain(gainDb, peak) { + const decibels = toFiniteNumber(gainDb); + if (decibels === null) + return 1; + let linear = Math.pow(10, decibels / 20); + const peakValue = toFiniteNumber(peak); + if (peakValue !== null && peakValue > 0) { + const ceiling = 1 / peakValue; + if (linear > ceiling) + linear = ceiling; + } + return Number.isFinite(linear) && linear >= 0 ? linear : 1; + } + + /** + * Resolves the ReplayGain values a mode selects out of a playback manifest. + * + * A gain and its peak belong together: the peak is the amplitude the gain is applied to, so a pair is always taken as + * a unit. The track mode uses the track pair and falls back to the album pair, the album mode does the opposite, and + * the off mode selects nothing. The fallback matters because a track whose album was not analyzed can carry only one + * of the two pairs, and normalizing with the pair that exists is better than not normalizing at all. A peak is never + * taken from one pair while the gain comes from the other, because the anti-clip ceiling would then be computed from a + * peak the applied gain does not belong to. + * @param {Object|null} manifest - The playback manifest of the track. + * @param {string} mode - One of the {@link LuminaAudioPlayer.PlayerReplayGainMode} values. + * @returns {{ gainDb: number|null, peak: number|null }} The selected pair, null when nothing is selected. + */ + function resolveReplayGain(manifest, mode) { + if (!manifest || mode === LuminaAudioPlayer.PlayerReplayGainMode.OFF) + return { gainDb: null, peak: null }; + const trackGain = toFiniteNumber(manifest.replayGainTrackGain); + const trackPeak = toFiniteNumber(manifest.replayGainTrackPeak); + const albumGain = toFiniteNumber(manifest.replayGainAlbumGain); + const albumPeak = toFiniteNumber(manifest.replayGainAlbumPeak); + // The gain decides which pair is used, and the peak of that same pair goes with it. + if (mode === LuminaAudioPlayer.PlayerReplayGainMode.ALBUM) { + if (albumGain !== null) + return { gainDb: albumGain, peak: albumPeak }; + return { gainDb: trackGain, peak: trackPeak }; + } + if (trackGain !== null) + return { gainDb: trackGain, peak: trackPeak }; + return { gainDb: albumGain, peak: albumPeak }; + } + + /** + * Creates an AudioContext through the browser constructors. + * @returns {AudioContext|null} The created context, or null when the browser exposes no constructor. + */ + function createDefaultAudioContext() { + const targetWindow = typeof window !== 'undefined' ? window : null; + if (!targetWindow) + return null; + const ContextConstructor = targetWindow.AudioContext || targetWindow.webkitAudioContext; + return typeof ContextConstructor === 'function' ? new ContextConstructor() : null; + } + + /** + * Produces sound through the Web Audio API and schedules the decoded audio of a track for playback. + */ + class TrackRenderer { + /** + * Creates an instance of TrackRenderer. + * @param {Object} [options] - The renderer options. + * @param {AudioContext} [options.audioContext] - An existing audio context to use. One is created through the context factory when omitted. + * @param {Function} [options.contextFactory] - A factory that returns an AudioContext. Defaults to the browser constructors. + * @param {boolean} [options.ownsContext] - True when the renderer owns the audio context and may close it on destroy. Defaults to true; pass false when the context is shared or owned by the caller and must outlive this renderer. + * @param {number} [options.volume] - The output volume, between 0 and 1. Defaults to 1. + * @param {boolean} [options.isMuted] - True to mute the output. Defaults to false. + * @param {string} [options.replayGainMode] - The user's ReplayGain mode, one of the {@link LuminaAudioPlayer.PlayerReplayGainMode} values. Defaults to no normalization. + * @param {number} [options.playbackRate] - The playback rate, within the accepted playback rate range. Defaults to 1. + * @param {number} [options.maxScheduledAheadSeconds] - An optional ceiling, in seconds, on how far ahead of the audio clock the schedule may run. Scheduling beyond it is refused with a typed error, so a caller that never paces itself cannot grow the schedule without bound. Leave the option out to disable the ceiling; a value of zero is a real ceiling that refuses every buffer, not a way to disable it. + * @param {Object} [options.events] - The player event bus. When provided, the renderer follows the player's ReplayGain mode changes. + * @param {Function} [options.onTimeUpdate] - Called with the current time and the duration, in seconds, while the audio plays. + * @param {Function} [options.onEnded] - Called once per configured track when its scheduled audio has been fully played. Audio scheduled after the end, without a configure or a seek, continues the same logical track and does not report the end again. + */ + constructor(options = {}) { + this.context = options.audioContext || null; + this.contextFactory = typeof options.contextFactory === 'function' ? options.contextFactory : createDefaultAudioContext; + // A context is a long lived resource that a browser counts, so the renderer closes it on destroy only when it + // owns it; a caller that shares or injects one passes ownsContext false. + this.ownsContext = options.ownsContext !== false; + // A ceiling of zero is meaningful, so a negative value is clamped to it rather than disabling the ceiling. + this.maxScheduledAheadSeconds = toFiniteNumber(options.maxScheduledAheadSeconds); + if (this.maxScheduledAheadSeconds !== null) + this.maxScheduledAheadSeconds = Math.max(0, this.maxScheduledAheadSeconds); + this.volume = clamp(toFiniteNumber(options.volume) === null ? 1 : Number(options.volume), 0, 1); + // Boolean state keeps its conventional is/has prefix, except where a public is*() accessor already owns that + // name: isMuted() and isDestroyed() are those accessors here, so the backing fields keep the participles. + this.muted = options.isMuted === true; + this.replayGainMode = normalizeReplayGainMode(options.replayGainMode); + // The default is assigned to the field before it is normalized, so an absent or invalid option falls back to + // it instead of to the still unset field, which would make every duration computation a NaN. + this.playbackRate = 1; + this.playbackRate = this.normalizePlaybackRate(options.playbackRate); + this.events = options.events || null; + this.onTimeUpdate = typeof options.onTimeUpdate === 'function' ? options.onTimeUpdate : null; + this.onEnded = typeof options.onEnded === 'function' ? options.onEnded : null; + + this.masterGain = null; + this.trackGain = null; + this.manifest = null; + this.duration = 0; + this.trackGainValue = 1; + this.error = null; + + // The scheduled sources, in media order, each one holding the audio buffer it plays so a playback rate change + // can re-time the part of the chain that has not finished yet. + this.scheduledSources = []; + // The index of the first entry of scheduledSources that has not finished yet. Cleanup advances it instead of + // shifting the array, so releasing a finished source never costs the size of the schedule behind it. + this.firstLiveIndex = 0; + // The media position of the next buffer to schedule, in seconds. + this.mediaCursor = 0; + // The context time at which the next buffer starts, in seconds. + this.nextStartTime = 0; + // The playhead anchor: the context time and the media position of the audio at that context time. + this.anchorContextTime = 0; + this.anchorMediaTime = 0; + // The media position the audio was frozen at by a pause, restored when playback resumes. + this.pausedMediaTime = 0; + + this.playing = false; + this.paused = false; + this.destroyed = false; + // True once a buffer has been scheduled since the last reset (configure, seekTo or destroy). It gates the end + // detection, so a schedule that was just reset to a media position does not report the end of the track + // before a single buffer has been scheduled at that position. + this.hasScheduledSinceReset = false; + // True once the decode pipeline has fed the last decoded frame of the track, which is what tells a drained + // schedule apart from the end of the track. + this.streamComplete = false; + // True once the current track has reached its end, that is once the schedule drained while the track was known + // to be complete. It drives whether a newly scheduled buffer resumes playback; a configure, a seek or a newly + // scheduled buffer clears it. + this.reachedEnd = false; + // True once the end of the current configured track has been reported through onEnded. It is a latch of its + // own, so the callback fires once per configured track even when audio is scheduled after the end; only a + // configure or a seek, which start a new logical track, clear it. + this.endReported = false; + this.reporterHandle = null; + this.unsubscribers = []; + this.subscribeToEvents(); + } + + //+======================================================================================+ + //| Lifecycle | + //+======================================================================================+ + + /** + * Prepares the renderer for a track: it makes sure the context and its gain nodes exist, resets the schedule and + * the playhead, and applies the ReplayGain normalization of the track. + * @param {Object} manifest - The playback manifest of the track, carrying its duration and ReplayGain values. + * @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining. + * @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed. + */ + configure(manifest) { + if (this.destroyed) + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The renderer was destroyed.')); + this.ensureContext(); + // A reconfigure starts a fresh track, so a failure of the previous one is not reported as a failure of this. + this.error = null; + this.stopAllSources(); + this.manifest = manifest || null; + this.duration = this.manifest && toFiniteNumber(this.manifest.durationInSeconds) !== null + ? Math.max(0, Number(this.manifest.durationInSeconds)) + : 0; + this.mediaCursor = 0; + this.nextStartTime = 0; + this.pausedMediaTime = 0; + this.playing = false; + this.paused = false; + this.streamComplete = false; + this.anchorContextTime = this.context.currentTime; + this.anchorMediaTime = 0; + this.applyTrackGain(0); + this.applyMasterGain(0); + return this; + } + + /** + * Releases every resource of the renderer: the schedule, the gain nodes, the event subscriptions and, when the + * renderer owns it, the audio context. + * @returns {Promise} A promise that completes when the context is closed. + */ + async destroyAsync() { + this.destroyed = true; + this.playing = false; + this.paused = false; + this.stopReporter(); + for (const unsubscribe of this.unsubscribers) { + try { + unsubscribe(); + } catch (error) { + console.debug('Audio player: a renderer event subscription could not be released.', error); + } + } + this.unsubscribers = []; + this.stopAllSources(); + if (this.trackGain) { + try { + this.trackGain.disconnect(); + } catch (error) { + console.debug('Audio player: the track gain node could not be disconnected.', error); + } + this.trackGain = null; + } + if (this.masterGain) { + try { + this.masterGain.disconnect(); + } catch (error) { + console.debug('Audio player: the master gain node could not be disconnected.', error); + } + this.masterGain = null; + } + if (!this.context) + return; + // A context the caller owns is left open, because it outlives this renderer. + if (!this.ownsContext) { + this.context = null; + return; + } + if (typeof this.context.close === 'function') { + try { + await this.context.close(); + } catch (error) { + // The context is still live. Its reference is kept rather than dropped, and the failure is recorded, so a + // caller can still reach the context through getContext() and close it itself; the renderer itself is + // destroyed and never uses it again. Dropping the only reference would lose a context that the browser + // counts until it is closed. + this.raise(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + console.error('Audio player: the audio context could not be closed.', error); + return; + } + } + this.context = null; + } + + //+======================================================================================+ + //| Playback control | + //+======================================================================================+ + + /** + * Resumes the audio context, which is the call that needs a user gesture, and starts the playhead. + * @returns {Promise} A promise that completes when the context is running. + * @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed, or the context could not be resumed. + */ + async playAsync() { + if (this.destroyed) + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The renderer was destroyed.')); + this.ensureContext(); + try { + if (this.context.state === 'suspended' && typeof this.context.resume === 'function') + await this.context.resume(); + } catch (error) { + throw this.raise(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + } + if (this.playing) + return; + this.reanchor(this.context.currentTime, this.pausedMediaTime); + this.paused = false; + this.playing = true; + this.startReporter(); + } + + /** + * Suspends the audio context, freezing the context clock and the current time, while the schedule is kept. + * @returns {Promise} A promise that completes when the context is suspended. + */ + async pauseAsync() { + if (!this.playing || this.destroyed) + return; + if (this.context && this.context.state === 'running' && typeof this.context.suspend === 'function') { + try { + await this.context.suspend(); + } catch (error) { + // A context that refuses to suspend keeps playing, so the player is not paused: nothing is changed, + // and the failure is recorded, so isPaused never claims a pause that did not happen. + this.raise(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + return; + } + } + // The context is suspended now, so the clock is frozen and the media position it reports is the position the + // pause holds; marking the state after the suspend is what keeps the two consistent. + this.pausedMediaTime = this.getCurrentTime(); + this.playing = false; + this.paused = true; + this.stopReporter(); + } + + /** + * Sets the playback rate, re-timing the part of the schedule that has not finished yet, so the audio stays + * continuous. Like the other setters, it does not throw on a destroyed renderer; it merely has nothing to apply. + * It can still throw when the re-time of the schedule itself fails, which is a failure of the audio pipeline, + * rather than of the state of the renderer. + * @param {number} rate - The playback rate, within the accepted playback rate range. + * @returns {number} The applied playback rate. + * @throws {LuminaAudioPlayer.PlayerError} When the schedule could not be re-timed. + */ + setPlaybackRate(rate) { + if (this.destroyed) + return this.playbackRate; + const next = this.normalizePlaybackRate(rate); + if (next === this.playbackRate) + return this.playbackRate; + if (this.context) { + const now = this.context.currentTime; + // The media position is captured under the old rate before the rate changes, so the anchor can be moved to + // the same position under the new rate, at the context time the rescheduled audio actually resumes. The + // re-time is applied only once it fully succeeded, so a failure leaves the rate and the anchor unchanged. + const mediaAtNow = this.getCurrentTime(); + const restartTime = this.retimeScheduledSources(now, mediaAtNow, next); + this.anchorContextTime = restartTime; + this.anchorMediaTime = mediaAtNow; + } + this.playbackRate = next; + return this.playbackRate; + } + + /** + * Sets the output volume, which is independent of the mute state. The engine of the player passes the effective + * volume here, which is zero while the player is muted, so driving the renderer through the engine honors mute + * without ever calling setMutedAsync. + * @param {number} volume - The output volume, between 0 and 1. + * @returns {Promise} The applied volume. + */ + async setVolumeAsync(volume) { + const value = clamp(toFiniteNumber(volume) === null ? this.volume : Number(volume), 0, 1); + this.volume = value; + this.applyMasterGain(MASTER_GAIN_RAMP_SECONDS); + return this.volume; + } + + /** + * Sets the mute state. Mute is a flag of its own: the volume is kept, and only the gain sent to the output is + * zeroed, so unmuting restores the volume the user had set. + * + * A caller that drives the renderer through the player engine does not need this: the engine delivers the mute as + * setVolumeAsync(0), because it folds the mute state into the effective volume. Use this setter only when a caller + * owns both the volume and the mute state itself and wants the volume kept across a mute. + * @param {boolean} muted - True to mute the output, false to unmute it. + * @returns {Promise} The applied mute state. + */ + async setMutedAsync(muted) { + this.muted = muted === true; + this.applyMasterGain(MASTER_GAIN_RAMP_SECONDS); + return this.muted; + } + + /** + * Sets the ReplayGain mode and applies the gain it selects out of the manifest of the current track. + * @param {string} mode - One of the {@link LuminaAudioPlayer.PlayerReplayGainMode} values. + * @returns {string} The applied mode. + */ + setReplayGainMode(mode) { + const next = normalizeReplayGainMode(mode); + if (next === this.replayGainMode) + return this.replayGainMode; + this.replayGainMode = next; + this.applyTrackGain(TRACK_GAIN_RAMP_SECONDS); + return this.replayGainMode; + } + + //+======================================================================================+ + //| Scheduling | + //+======================================================================================+ + + /** + * Converts a decoded AudioData into an AudioBuffer, schedules it to play directly after the audio that is already scheduled, and advances the playhead. + * + * The buffer is adopted as the audio at the current media position of the timeline, so a buffer that follows a + * seekTo is held to begin exactly at the position that was requested. The renderer takes ownership of the + * AudioData: it closes it, releasing its native memory, before this call returns or throws, so a caller must not + * use the object again and must not close it itself. Scheduling audio while the renderer had reached the end of + * the current track resumes the playback state, so the playhead and the callbacks continue to run. + * @param {AudioData} audioData - The decoded audio to schedule. Ownership transfers to the renderer, which closes it. + * @returns {number} The media position, in seconds, at the end of the scheduled audio. + * @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed, or the audio could not be converted or scheduled. + */ + schedule(audioData) { + // The decoded audio is consumed by this call whatever happens, so it is released even when the renderer refuses + // it, which is what keeps a decode loop from leaking native memory when a frame is rejected. + try { + if (this.destroyed) + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The renderer was destroyed.')); + this.ensureContext(); + const buffer = this.createBufferFromAudioData(audioData); + // A decode with no frame carries no media, so it contributes nothing to the timeline and is dropped. + if (!buffer || buffer.duration <= 0) + return this.mediaCursor; + // Scheduling after the current track already reached its end means the audio is playing on, so the playback + // state is resumed, which is what a gapless handoff or a recovered underrun relies on. + const wasEnded = this.reachedEnd; + const now = this.context.currentTime; + const rate = this.playbackRate; + const mediaDuration = buffer.duration; + const wallDuration = mediaDuration / rate; + const hasScheduled = this.hasLiveEntries(); + // The ceiling is checked against the frontier the schedule would reach once this buffer is added, not against + // the frontier it already has, so the schedule never settles a buffer beyond the ceiling. The start this + // buffer would take is the one the chain gives it, which is the existing frontier when it is still ahead of + // the clock and one lead ahead otherwise. + const prospectiveStart = hasScheduled && this.nextStartTime > now ? this.nextStartTime : now + MIN_SCHEDULE_LEAD_SECONDS; + if (this.maxScheduledAheadSeconds !== null && prospectiveStart + wallDuration - now > this.maxScheduledAheadSeconds) + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR, 'The schedule would run further ahead than the renderer allows.', { reason: 'scheduled-ahead-limit' })); + let when = this.nextStartTime; + // The chain is anchored on its first buffer, and re-anchored whenever it fell behind the context clock, which + // is an underrun: the buffer starts as soon as it can and the playhead follows the audio that actually plays. + // The first buffer of a chain, and any buffer whose start time has already passed (the chain fell behind the + // clock), starts one lead ahead and re-anchors the playhead. A buffer that still starts in the future is laid + // exactly on its start time, so a chain that is merely scheduled close to the clock is not turned into a gap. + if (!hasScheduled || when < now) { + when = now + MIN_SCHEDULE_LEAD_SECONDS; + this.reanchor(when, this.mediaCursor); + } + let source = null; + try { + source = this.context.createBufferSource(); + source.buffer = buffer; + if (source.playbackRate) + source.playbackRate.value = rate; + // The end of a source is an end-of-audio signal that is not tied to the animation frame loop, which a + // hidden tab suspends, so the end of the track is still detected while the tab is in the background. + source.onended = () => this.handleSourceEnded(); + source.connect(this.trackGain); + source.start(when); + } catch (error) { + if (source) { + try { + source.disconnect(); + } catch (disconnectError) { + console.debug('Audio player: the failed source could not be disconnected.', disconnectError); + } + } + throw this.raise(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + } + this.scheduledSources.push({ + source, + buffer, + // The media origin of the buffer, i.e. the media position of its first frame. It is kept so a later + // playback rate change can measure the resume offset against the buffer itself, never against a position + // the entry happened to start at. + bufferMediaStart: this.mediaCursor, + mediaDuration, + when, + rate + }); + this.hasScheduledSinceReset = true; + // Scheduling audio means the track is playing on, so a previous end of the current track no longer holds. + this.reachedEnd = false; + this.mediaCursor += mediaDuration; + this.nextStartTime = when + wallDuration; + this.cleanupFinishedSources(); + if (wasEnded && !this.playing && !this.paused) { + this.playing = true; + this.startReporter(); + } + return this.mediaCursor; + } finally { + this.closeAudioData(audioData); + } + } + + /** + * Releases the native memory of a decoded AudioData, which the renderer owns once schedule received it. + * @param {AudioData} audioData - The decoded audio to close. + */ + closeAudioData(audioData) { + if (!audioData || typeof audioData.close !== 'function') + return; + try { + audioData.close(); + } catch (error) { + console.debug('Audio player: the decoded audio could not be closed.', error); + } + } + + /** + * Moves the schedule to a media position: it stops and releases the scheduled audio, moves the playhead to that + * position, and treats the next buffer that is scheduled as the audio at that position. It is the scheduler half + * of a seek; the caller still resets its decoder, fetches the byte range of the position and re-demuxes from + * there before it feeds decoded audio again. Because the renderer owns the absolute position of the track, a seek + * keeps getCurrentTime, the reported time and the end check absolute instead of forcing every caller to translate + * them through an offset of its own. + * + * The first buffer scheduled after this call must begin exactly at that position. A caller whose demuxer instead + * lands on a packet boundary before the target must trim the leading samples to the target before scheduling + * them, because the renderer adopts the requested position as the media origin of that buffer and cannot correct + * an offset it is not told about. + * @param {number} seconds - The media position to move to, in seconds. + * @returns {number} The applied media position, in seconds. + * @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed. + */ + seekTo(seconds) { + if (this.destroyed) + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The renderer was destroyed.')); + const request = toFiniteNumber(seconds); + // A position that is not a number is not a seek: nothing is reset and the current media frontier is returned, + // so an accidental NaN never tears down the schedule and drops the audio that is already playing. + if (request === null) + return this.mediaCursor; + this.ensureContext(); + const position = Math.max(0, request); + const bounded = this.duration > 0 ? Math.min(position, this.duration) : position; + this.stopAllSources(); + this.mediaCursor = bounded; + this.nextStartTime = 0; + this.streamComplete = false; + this.pausedMediaTime = bounded; + this.anchorContextTime = this.context.currentTime; + this.anchorMediaTime = bounded; + return bounded; + } + + /** + * States that the decode pipeline has fed the last decoded frame of the track. A drained schedule is treated as + * the end of the track only after this call, so a gap caused by a decode that is slower than real time is not + * mistaken for the end. + * @returns {void} + */ + markStreamComplete() { + this.streamComplete = true; + } + + //+======================================================================================+ + //| Query surface | + //+======================================================================================+ + + /** + * Gets the current media position of the audio, in seconds. It is derived from the context clock through the + * playhead anchor, so it is precise while the context runs, and frozen while the context is suspended by a pause. + * @returns {number} The current time, in seconds. + */ + getCurrentTime() { + // The playhead can never run past the media that has actually been scheduled: before the first buffer is + // scheduled there is nothing to play, so the position is zero rather than the wall time that has elapsed + // since playAsync, and a schedule that drained holds the position at its frontier until more audio arrives. + const upperBound = this.mediaCursor; + if (this.paused) + return clamp(this.pausedMediaTime, 0, upperBound); + if (!this.playing || !this.context) + return clamp(this.anchorMediaTime, 0, upperBound); + const media = this.anchorMediaTime + (this.context.currentTime - this.anchorContextTime) * this.playbackRate; + return clamp(media, 0, upperBound); + } + + /** + * Gets the duration of the current track, from its playback manifest. + * @returns {number} The duration, in seconds, or zero when it is unknown. + */ + getDuration() { + return this.duration; + } + + /** + * Gets the output volume, which is independent of the mute state. + * @returns {number} The volume, between 0 and 1. + */ + getVolume() { + return this.volume; + } + + /** + * Gets the mute state. + * @returns {boolean} True when the output is muted. + */ + isMuted() { + return this.muted; + } + + /** + * Gets the playback rate. + * @returns {number} The playback rate. + */ + getPlaybackRate() { + return this.playbackRate; + } + + /** + * Gets the ReplayGain mode in effect. + * @returns {string} One of the {@link LuminaAudioPlayer.PlayerReplayGainMode} values. + */ + getReplayGainMode() { + return this.replayGainMode; + } + + /** + * Gets the linear gain currently applied to the current track for ReplayGain. + * @returns {number} The per-track gain. + */ + getTrackGainValue() { + return this.trackGainValue; + } + + /** + * Gets the gain currently applied to the output, which is the volume, or zero when the output is muted. + * @returns {number} The master gain. + */ + getMasterGainValue() { + return this.muted ? 0 : this.volume; + } + + /** + * Checks whether the renderer is playing. + * @returns {boolean} True when the audio context is running and the schedule produces sound. + */ + isPlaying() { + return this.playing; + } + + /** + * Checks whether playback is suspended by a pause. + * @returns {boolean} True when the renderer was paused. + */ + isPaused() { + return this.paused; + } + + /** + * Checks whether the renderer was destroyed. + * @returns {boolean} True when the renderer was destroyed. + */ + isDestroyed() { + return this.destroyed; + } + + /** + * Checks whether the schedule holds an entry that has not finished yet. + * @returns {boolean} True when a live entry is scheduled. + */ + hasLiveEntries() { + return this.firstLiveIndex < this.scheduledSources.length; + } + + /** + * Checks whether any audio is scheduled and has not finished playing yet. + * @returns {boolean} True when the schedule still holds audio. + */ + hasScheduledAudio() { + if (!this.hasLiveEntries()) + return false; + const now = this.context ? this.context.currentTime : 0; + // The entries are held in media order, so their finish times ascend and only the last one can still be ahead + // of the clock: testing that one is enough, and it costs nothing per call. + const last = this.scheduledSources[this.scheduledSources.length - 1]; + return last.when + last.mediaDuration / last.rate > now; + } + + /** + * Gets the media position, in seconds, of the next buffer to schedule, which is the frontier of the schedule. It + * is the total media scheduled from the start of the track, and after a seek it is the absolute position of the + * seek target plus the media scheduled since, because the renderer owns the absolute position of the track. + * @returns {number} The media position of the schedule frontier, in seconds. + */ + getScheduledMediaDuration() { + return this.mediaCursor; + } + + /** + * Gets how far ahead of the audio clock, in seconds, the scheduled audio currently extends. + * + * The scheduler accepts decoded audio as fast as it is handed to it and never drops a buffer, so a decoder that + * runs faster than real time would otherwise queue a large part of a track and hold its decoded audio in memory. + * A decode loop polls this value to pace itself, exactly as it uses the decode queue size of its decoder, and + * stops feeding while the schedule is already far enough ahead. It is zero when the schedule has drained. + * @returns {number} The scheduled ahead duration, in seconds. + */ + getScheduledAheadSeconds() { + if (!this.context || this.nextStartTime <= 0) + return 0; + return Math.max(0, this.nextStartTime - this.context.currentTime); + } + + /** + * Checks whether the decode pipeline has stated that it fed the last decoded frame of the track. + * @returns {boolean} True when the track is known to be complete. + */ + isStreamComplete() { + return this.streamComplete; + } + + /** + * Gets the last failure, or null when there was none. + * @returns {LuminaAudioPlayer.PlayerError|null} The last failure. + */ + getError() { + return this.error; + } + + /** + * Gets the audio context, or null when it has not been created yet, when the renderer does not own it, or once it + * was closed. When destroyAsync ran but the context refused to close, it returns the still open context even though + * isDestroyed() is true, so a caller can close it itself; the renderer never uses it again. + * @returns {AudioContext|null} The audio context, which may outlive a destroyed renderer only when closing it failed. + */ + getContext() { + return this.context; + } + + //+======================================================================================+ + //| Internal helpers | + //+======================================================================================+ + + /** + * Makes sure the audio context and its gain nodes exist, creating them on first use. + * @returns {AudioContext} The audio context. + * @throws {LuminaAudioPlayer.PlayerError} When the environment exposes no audio context, or it could not be created. + */ + ensureContext() { + if (this.context) { + if (!this.masterGain || !this.trackGain) + this.buildGainGraph(); + return this.context; + } + let context = null; + try { + context = this.contextFactory(); + } catch (error) { + throw this.raise(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED); + } + if (!context || typeof context.createGain !== 'function') + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'This environment provides no audio context for the player output.')); + this.context = context; + this.buildGainGraph(); + return context; + } + + /** + * Builds the two gain nodes of the output and connects them: the sources feed the per-track gain, which feeds the + * master gain, which feeds the destination. + */ + buildGainGraph() { + this.masterGain = this.context.createGain(); + this.trackGain = this.context.createGain(); + this.trackGain.connect(this.masterGain); + this.masterGain.connect(this.context.destination); + this.applyMasterGain(0); + this.applyTrackGain(0); + } + + /** + * Applies the output gain, which is the volume, or zero while muted, to the master gain node. + * @param {number} rampSeconds - The duration of the ramp to the new value, in seconds. Zero applies it at once. + */ + applyMasterGain(rampSeconds) { + if (!this.masterGain || !this.masterGain.gain) + return; + this.setAudioParamValue(this.masterGain.gain, this.muted ? 0 : this.volume, rampSeconds); + } + + /** + * Applies the ReplayGain normalization selected by the mode and the manifest to the per-track gain node. + * @param {number} rampSeconds - The duration of the ramp to the new value, in seconds. Zero applies it at once. + */ + applyTrackGain(rampSeconds) { + const values = resolveReplayGain(this.manifest, this.replayGainMode); + this.trackGainValue = computeReplayGainLinearGain(values.gainDb, values.peak); + if (!this.trackGain || !this.trackGain.gain) + return; + this.setAudioParamValue(this.trackGain.gain, this.trackGainValue, rampSeconds); + } + + /** + * Applies a value to an audio parameter, ramping to it so a change never clicks. + * @param {AudioParam} param - The audio parameter to change. + * @param {number} value - The value to apply. + * @param {number} rampSeconds - The duration of the ramp, in seconds. Zero, or a parameter that cannot be ramped, assigns the value directly. + */ + setAudioParamValue(param, value, rampSeconds) { + if (!param) + return; + const target = Number.isFinite(value) ? value : 0; + if (rampSeconds > 0 + && typeof param.cancelScheduledValues === 'function' + && typeof param.setValueAtTime === 'function' + && typeof param.linearRampToValueAtTime === 'function' + && this.context) { + try { + const now = this.context.currentTime; + const current = Number.isFinite(param.value) ? param.value : target; + param.cancelScheduledValues(now); + param.setValueAtTime(current, now); + param.linearRampToValueAtTime(target, now + rampSeconds); + return; + } catch (error) { + // A parameter that rejects automation falls through to the direct assignment below. + console.debug('Audio player: a gain ramp could not be scheduled.', error); + } + } + param.value = target; + } + + /** + * Converts a decoded AudioData into an AudioBuffer, one channel at a time, handling a sample rate that differs from the context rate. + * @param {AudioData} audioData - The decoded audio to convert. + * @returns {AudioBuffer|null} The audio buffer, or null when the decode carries no frame. + * @throws {LuminaAudioPlayer.PlayerError} When the decode carries nothing copyable. + */ + createBufferFromAudioData(audioData) { + if (!audioData || typeof audioData.copyTo !== 'function') + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR, 'The decoded audio could not be read.')); + const frames = Math.floor(toFiniteNumber(audioData.numberOfFrames) || 0); + const channels = Math.floor(toFiniteNumber(audioData.numberOfChannels) || 0); + const sampleRate = toFiniteNumber(audioData.sampleRate); + if (frames <= 0 || channels <= 0 || sampleRate === null || sampleRate <= 0) + return null; + if (!this.isWithinDecodeBudget(frames, channels)) + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR, 'The decoded audio carries an implausible frame count or channel count.')); + // A buffer created at the decoded rate is resampled to the context rate by the Web Audio graph itself, which is + // both cheaper and higher quality than a resample in JavaScript. Only a rate a buffer may not carry is resampled here. + const canUseDecodedRate = sampleRate >= MIN_AUDIO_BUFFER_SAMPLE_RATE && sampleRate <= MAX_AUDIO_BUFFER_SAMPLE_RATE; + try { + if (canUseDecodedRate) { + const buffer = this.context.createBuffer(channels, frames, sampleRate); + // The decoded samples are copied straight into the channel data of the buffer, so the pass-through path allocates no scratch array and copies the audio only once. + for (let channel = 0; channel < channels; channel++) + this.copyChannelData(audioData, channel, frames, buffer.getChannelData(channel)); + return buffer; + } + // A rate a buffer may not carry, outside the range createBuffer accepts, is the only case that reaches here, + // because any accepted rate is used directly above. A conforming decoder never reports such a rate, so this + // path, and the JavaScript resampler it uses, exist only as a safety net for a non-conforming decoder. + const targetRate = this.context.sampleRate; + const resampledFrames = Math.max(1, Math.round(frames / sampleRate * targetRate)); + // The resampled output is a fresh allocation whose size is derived from the decoded rate, so it is held to + // the same budget as the decoded chunk. The length is computed once here and handed to the resampler, so the + // budget check and the allocation can never disagree. + if (!this.isWithinDecodeBudget(resampledFrames, channels)) + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR, 'The resampled audio would be implausibly large.')); + const buffer = this.context.createBuffer(channels, resampledFrames, targetRate); + for (let channel = 0; channel < channels; channel++) { + const source = this.copyChannelData(audioData, channel, frames); + buffer.copyToChannel(this.resampleChannel(source, resampledFrames), channel); + } + return buffer; + } catch (error) { + throw this.raise(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + } + } + + /** + * Checks that a chunk size is within the decode budget, as a product: a buffer allocates all of its samples in + * one block, so the frame count and the channel count are only meaningful together. + * @param {number} frames - The number of frames of the chunk. + * @param {number} channels - The number of channels of the chunk. + * @returns {boolean} True when the chunk fits the budget. + */ + isWithinDecodeBudget(frames, channels) { + return frames <= MAX_DECODED_FRAMES_PER_CHUNK && channels <= MAX_DECODED_CHANNELS && frames * channels <= MAX_DECODED_SAMPLES_PER_CHUNK; + } + + /** + * Copies one channel of a decoded AudioData into a Float32Array, as planar 32 bit floats. + * + * The copy targets planar float samples, which is the layout the scheduler reads and writes into an AudioBuffer + * channel. The decode pipeline must therefore supply planar float audio; the module cannot enforce the layout of + * a decoder, so a source in any other layout is refused rather than reinterpreted, because copying an interleaved + * source into a single plane would silently write the wrong layout instead of failing. + * @param {AudioData} audioData - The decoded audio to copy from. + * @param {number} channel - The zero based channel to copy. + * @param {number} frames - The number of frames of the decode. + * @param {Float32Array} [destination] - The array to copy into, which must hold at least the frames of the channel. A new array is allocated when it is omitted, which is what the resample path passes; the pass-through path passes the channel data of the AudioBuffer, so the samples are copied once and no scratch array is allocated. + * @returns {Float32Array} The destination array, holding the channel samples. + * @throws {LuminaAudioPlayer.PlayerError} When the channel cannot be copied as planar float samples. + */ + copyChannelData(audioData, channel, frames, destination) { + const target = destination || new Float32Array(frames); + try { + audioData.copyTo(target, { planeIndex: channel, format: 'f32-planar' }); + return target; + } catch (error) { + // A browser that rejects the explicit planar float format is retried without one, which is safe only when + // the decode already carries planar float samples, so the native format is checked first. + if (audioData.format !== 'f32-planar') + throw this.raise(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + try { + audioData.copyTo(target, { planeIndex: channel, frameCount: frames }); + return target; + } catch (fallbackError) { + throw this.raise(fallbackError, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + } + } + } + + /** + * Resamples one channel of samples with linear interpolation, to an exact output length. It is a safety net for a + * decoder that reports a sample rate the Web Audio graph cannot itself resample, which a conforming decoder never + * does, so only a non-conforming one, and a test, reach it. + * @param {Float32Array} channelData - The samples to resample. + * @param {number} outputLength - The exact number of frames to produce, which the caller computed and budgeted. + * @returns {Float32Array} The resampled samples. + */ + resampleChannel(channelData, outputLength) { + if (outputLength <= 0 || channelData.length === 0) + return channelData; + const ratio = outputLength / channelData.length; + const output = new Float32Array(outputLength); + for (let index = 0; index < outputLength; index++) { + const position = index / ratio; + const lower = Math.floor(position); + const fraction = position - lower; + const first = lower < channelData.length ? channelData[lower] : 0; + const second = lower + 1 < channelData.length ? channelData[lower + 1] : first; + output[index] = first + (second - first) * fraction; + } + return output; + } + + /** + * Re-times the schedule for a playback rate change, so the audio stays continuous. + * + * The source that is already playing is not recreated: stopping and restarting it would put a gap into the audio + * that is being heard and churn a node for a change its rate can carry, so its rate is changed in place and its + * entry is re-based at the current instant. Only the buffers that have not started yet are recreated, laid + * contiguously after the playing source from their first frame, because the playhead cannot be past a buffer that + * starts in the future. A rate change therefore re-times the whole pending chain and closes any gap the original + * start times carried; the scheduler never lays a gap itself, so this is the only place one could appear. The whole + * mutation is applied only after every new source was created, so a failure leaves the schedule that is already + * playing exactly as it was and the caller keeps reporting the old rate. + * @param {number} now - The current context time. + * @param {number} mediaAtNow - The current media position, in seconds. + * @param {number} newRate - The playback rate to apply. + * @returns {number} The context time the audio resumes at, which the caller anchors the playhead to. + */ + retimeScheduledSources(now, mediaAtNow, newRate) { + // One linear pass over the live entries splits the schedule into the ones that have finished, the one that is + // playing, and the ones that have not started yet. The entries are in media order, so there is at most one + // playing entry, and the entries before the live cursor have already been released. + const finished = []; + const notStarted = []; + let running = null; + for (let index = this.firstLiveIndex; index < this.scheduledSources.length; index++) { + const entry = this.scheduledSources[index]; + const end = entry.when + entry.mediaDuration / entry.rate; + if (end <= now) + finished.push(entry); + else if (entry.when <= now) + running = entry; + else + notStarted.push(entry); + } + // The playing source is kept, so the chain continues from the media position it has already reached, at the new + // rate. A chain with nothing playing restarts one scheduling lead ahead, like a fresh chain. + let wall = now; + let restartTime = now; + let runningRemaining = 0; + if (running) { + const consumedMedia = clamp(mediaAtNow - running.bufferMediaStart, 0, running.buffer.duration); + runningRemaining = running.buffer.duration - consumedMedia; + wall = now + runningRemaining / newRate; + } else { + wall = now + MIN_SCHEDULE_LEAD_SECONDS; + restartTime = wall; + } + // The buffers that have not started are rebuilt first, without touching the live schedule, so a failure to + // create a source leaves everything that is already playing untouched. Each one is laid contiguously after the + // playing source from its first frame, because the playhead cannot be past a buffer that starts in the future. + const rebuilt = []; + for (const entry of notStarted) { + let source = null; + try { + source = this.context.createBufferSource(); + source.buffer = entry.buffer; + if (source.playbackRate) + source.playbackRate.value = newRate; + source.onended = () => this.handleSourceEnded(); + source.connect(this.trackGain); + source.start(wall); + } catch (error) { + this.releaseSources(rebuilt); + if (source) { + try { + source.disconnect(); + } catch (disconnectError) { + console.debug('Audio player: the re-timed source could not be disconnected.', disconnectError); + } + } + throw this.raise(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + } + rebuilt.push({ + source, + buffer: entry.buffer, + bufferMediaStart: entry.bufferMediaStart, + mediaDuration: entry.buffer.duration, + when: wall, + rate: newRate + }); + wall += entry.buffer.duration / newRate; + } + // Every new source exists, so the mutation is applied: the playing source takes the new rate in place, the + // finished and replaced sources are released, and the rebuilt entries replace the schedule. + if (running) { + if (running.source.playbackRate) + running.source.playbackRate.value = newRate; + running.when = now; + running.mediaDuration = runningRemaining; + running.rate = newRate; + } + for (const entry of finished) + this.releaseSource(entry.source); + for (const entry of notStarted) + this.releaseSource(entry.source); + this.scheduledSources = running ? [running, ...rebuilt] : rebuilt; + // The rebuilt array holds only live entries, so the cursor starts over at its beginning. + this.firstLiveIndex = 0; + // A schedule with nothing left leaves the schedule drained, which getScheduledAheadSeconds reports as zero. + this.nextStartTime = this.scheduledSources.length > 0 ? wall : 0; + return restartTime; + } + + /** + * Stops and disconnects one scheduled source. + * @param {AudioBufferSourceNode} source - The source to release. + * @param {number} [when] - The context time to stop at, or nothing to stop immediately. + */ + releaseSource(source, when) { + if (!source) + return; + // An intentional stop must not be read as the end of the track, so the end handler is detached before it. + try { + source.onended = null; + } catch (error) { + console.debug('Audio player: the source end handler could not be detached.', error); + } + try { + if (when === undefined) + source.stop(); + else + source.stop(when); + } catch (error) { + console.debug('Audio player: a scheduled source could not be stopped.', error); + } + try { + source.disconnect(); + } catch (error) { + console.debug('Audio player: a scheduled source could not be disconnected.', error); + } + } + + /** + * Releases every source of a list. + * @param {Array<{ source: AudioBufferSourceNode }>} entries - The entries whose sources are released. + */ + releaseSources(entries) { + for (const entry of entries) + this.releaseSource(entry.source); + } + + /** + * Stops and disconnects every scheduled source and resets the schedule cursors. + */ + stopAllSources() { + // Every source is released through the one helper that stops, detaches its end handler and disconnects it, so + // the teardown path here and the swap path of a rate change can never drift apart. + for (let index = this.firstLiveIndex; index < this.scheduledSources.length; index++) + this.releaseSource(this.scheduledSources[index].source); + this.scheduledSources = []; + this.firstLiveIndex = 0; + this.mediaCursor = 0; + this.nextStartTime = 0; + // Nothing is scheduled any more, so the end detection is suspended until a buffer is scheduled again, and the + // track is no longer considered to have reached its end. A reset starts a new logical track, so the reported + // end of the previous one is cleared as well. + this.hasScheduledSinceReset = false; + this.reachedEnd = false; + this.endReported = false; + } + + /** + * Releases the scheduled sources whose audio has finished playing. The entries are held in media order, so the + * finished ones are always a prefix; the cursor of the first live entry is advanced over that prefix instead of the + * array being shifted, so releasing a finished source never costs the size of the schedule behind it. + */ + cleanupFinishedSources() { + const now = this.context ? this.context.currentTime : 0; + while (this.firstLiveIndex < this.scheduledSources.length) { + const entry = this.scheduledSources[this.firstLiveIndex]; + if (entry.when + entry.mediaDuration / entry.rate > now) + break; + this.releaseSource(entry.source); + this.firstLiveIndex++; + } + // The dead prefix is dropped entirely once nothing is live, so a track that ended holds no buffer, and otherwise + // it is reclaimed in bulk only once it is at least as large as what remains, which keeps the array bounded and + // the reclaim amortized against the entries it discards. + if (!this.hasLiveEntries() || (this.firstLiveIndex > 64 && this.firstLiveIndex * 2 >= this.scheduledSources.length)) { + this.scheduledSources = this.scheduledSources.slice(this.firstLiveIndex); + this.firstLiveIndex = 0; + } + } + + /** + * Moves the playhead anchor to a context time and the media position the audio has at that context time. + * @param {number} contextTime - The context time of the anchor. + * @param {number} mediaTime - The media position at the anchor. + */ + reanchor(contextTime, mediaTime) { + this.anchorContextTime = contextTime; + this.anchorMediaTime = mediaTime; + } + + /** + * Normalizes a playback rate into the accepted range, keeping the current rate when the value is not a number. + * @param {number} rate - The playback rate to normalize. + * @returns {number} The normalized playback rate. + */ + normalizePlaybackRate(rate) { + const value = toFiniteNumber(rate); + if (value === null) + return this.playbackRate; + return clamp(value, MIN_PLAYBACK_RATE, MAX_PLAYBACK_RATE); + } + + /** + * Starts the reporter that reports the playhead and the end of the scheduled audio while it plays. + */ + startReporter() { + if (this.reporterHandle !== null || this.destroyed) + return; + // The reporter runs for the whole duration of playback, even without a consumer callback, so the end of the + // audio is detected and isPlaying turns false whether the caller observes it through a callback or by polling. + this.scheduleReporterFrame(); + } + + /** + * Stops the reporter. + */ + stopReporter() { + if (this.reporterHandle === null) + return; + const handle = this.reporterHandle; + this.reporterHandle = null; + try { + if (typeof cancelAnimationFrame === 'function' && handle.isFrame === true) + cancelAnimationFrame(handle.id); + else + clearTimeout(handle.id); + } catch (error) { + console.debug('Audio player: the renderer reporter could not be stopped.', error); + } + } + + /** + * Schedules the next reporter tick, on the next frame when the page has an animation frame and on a short timeout + * otherwise. + */ + scheduleReporterFrame() { + const tick = () => { + this.reporterHandle = null; + this.notifyTick(); + }; + // An animation frame is the smooth choice while the page is visible, but the browser suspends it while the tab + // is hidden, even though the audio graph keeps producing sound. A timer, which a hidden tab throttles but does + // not suspend, drives the report then, so the playhead and the end are still observed in the background. + const isVisible = typeof document === 'undefined' || document.hidden !== true; + if (isVisible && typeof requestAnimationFrame === 'function') + this.reporterHandle = { id: requestAnimationFrame(tick), isFrame: true }; + else + this.reporterHandle = { id: setTimeout(tick, REPORTER_FALLBACK_INTERVAL_MS), isFrame: false }; + } + + /** + * Checks whether the track has ended: the scheduled audio has drained and the track is known to be complete. A + * drained schedule that is not complete is a gap, not the end, however the gap came about, and an empty schedule + * right after a reset is never an end because nothing has been scheduled at that position yet. Completion is only + * ever stated by markStreamComplete: the duration of the manifest is not used as a completion signal, because the + * last frames of a decode that is still on its way would then be cut off. + * @returns {boolean} True when the track has ended. + */ + isEndOfTrack() { + if (!this.streamComplete || !this.hasScheduledSinceReset || this.mediaCursor <= 0) + return false; + const now = this.context ? this.context.currentTime : 0; + return this.nextStartTime <= now; + } + + /** + * Reports the playhead, and the end of the scheduled audio, to the consumer callbacks. + */ + notifyTick() { + if (!this.playing || this.destroyed) + return; + if (this.onTimeUpdate) { + try { + this.onTimeUpdate(this.getCurrentTime(), this.getDuration()); + } catch (error) { + console.error('Audio player: the renderer time callback threw.', error); + } + } + const now = this.context ? this.context.currentTime : 0; + // The finished sources are released as soon as the schedule drains, because no further buffer will arrive to trigger the sweep of schedule(). + if (this.hasScheduledSinceReset && this.mediaCursor > 0 && this.nextStartTime <= now) + this.cleanupFinishedSources(); + // The track ends only when the drained schedule is also known to be complete; a decode that fell behind keeps playing and waits for the audio that is still on its way. + if (this.isEndOfTrack()) { + this.completeEnd(); + return; + } + this.scheduleReporterFrame(); + } + + /** + * Handles the end of a scheduled source. It is the end-of-audio signal that survives a hidden tab, because it does + * not depend on the animation frame loop, which the browser suspends while the tab is in the background, while the + * audio graph keeps producing sound. + */ + handleSourceEnded() { + if (!this.playing || this.destroyed) + return; + if (this.isEndOfTrack()) + this.completeEnd(); + } + + /** + * Completes the current track: the playhead is pinned to the end of the media, playback stops, and the reporter + * stops. The end is reported through the onEnded callback once per configured track: scheduling audio after an end + * resumes the playback state, so completeEnd runs again for that audio, but the callback is not fired a second + * time, and only a configure or a seek, which start a new logical track, allow it to fire again. + */ + completeEnd() { + const now = this.context ? this.context.currentTime : 0; + // The playhead is pinned to the end of the media, so a report after the track ends shows its end instead of the anchor of the first buffer. + this.reanchor(now, this.mediaCursor); + this.pausedMediaTime = this.mediaCursor; + this.playing = false; + this.stopReporter(); + // The schedule has drained, so the finished sources are released here too, because the end can also be reached + // from the end of a source, which does not pass through the reporter tick that would otherwise sweep them. + this.cleanupFinishedSources(); + this.reachedEnd = true; + if (this.endReported) + return; + this.endReported = true; + if (!this.onEnded) + return; + try { + this.onEnded(); + } catch (error) { + console.error('Audio player: the renderer end callback threw.', error); + } + } + + /** + * Subscribes the renderer to the player event bus, so a ReplayGain mode change made on the player is applied to + * the per-track gain without the caller pushing it again. The volume and the mute state are deliberately not read + * here: they are driven by the caller through setVolumeAsync and setMutedAsync, which is exactly what the engine + * interface hands over, so the master gain has a single writer. + */ + subscribeToEvents() { + if (!this.events || !LuminaAudioPlayer.PlayerEvent || typeof this.events.on !== 'function') + return; + if (LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED) { + this.unsubscribers.push(this.events.on(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, (preferences) => { + if (preferences && typeof preferences.replayGainMode === 'string') + this.setReplayGainMode(preferences.replayGainMode); + })); + } + } + + /** + * Records and types a failure, so a caller or a poll of getError sees a consistent error. + * @param {*} error - The failure to record. + * @param {string} [code] - The code to use when the failure is not already a player error. + * @returns {LuminaAudioPlayer.PlayerError} The recorded typed error. + */ + raise(error, code = LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) { + const typed = LuminaAudioPlayer.PlayerError.from(error, code); + this.error = typed; + return typed; + } + } + + LuminaAudioPlayer.TrackRenderer = TrackRenderer; + + /** + * Creates a track renderer. See {@link LuminaAudioPlayer.TrackRenderer} for the options. + * @param {Object} options - The renderer options. + * @returns {LuminaAudioPlayer.TrackRenderer} The created renderer. + */ + LuminaAudioPlayer.createTrackRenderer = function (options) { + return new TrackRenderer(options); + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); From fbc67c81c3861e2632aecb14c5fcd3913055b3e1 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 16 Oct 2026 18:33:25 +0300 Subject: [PATCH 17/77] Adds the audio player WebCodecs decode pipeline. --- .../Views/Shared/_ThemeLayoutScripts.cshtml | 1 + .../js/audio-player/audio-player-decode.js | 1162 +++++++++++++++++ .../js/audio-player/audio-player-download.js | 5 +- .../js/audio-player/audio-player-engine.js | 7 +- .../js/audio-player/audio-player-errors.js | 26 + .../js/audio-player/audio-player-render.js | 19 +- 6 files changed, 1213 insertions(+), 7 deletions(-) create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 8698f4b9..02b961cb 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -69,6 +69,7 @@ + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js new file mode 100644 index 00000000..25f37265 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js @@ -0,0 +1,1162 @@ +/** + * WebCodecs decode pipeline of the audio player. + * + * The player never uses a native audio element, so the encoded audio of a track is turned into sound in three steps: the + * download engine brings the bytes in, the demuxers parse them into encoded packets, and this module decodes those packets + * with WebCodecs into decoded audio, which the scheduler of the render module turns into sound. This module is the middle + * step: it owns one WebCodecs.AudioDecoder, feeds it the packets a demuxer produces, and hands every decoded frame to the + * renderer's scheduler. + * + * WebCodecs, and why a decoder is not a file reader + * ------------------------------------------------- + * AudioDecoder does not read a file and does not know about containers. It consumes two things: a configuration, which + * names the codec, the sample rate and the channel count, plus the codec private data the container carries, and a stream + * of EncodedAudioChunk objects, each one a single encoded packet with its presentation timestamp and its duration, both + * in microseconds. Its output is a stream of AudioData objects. Nothing about a container, a byte offset or a file lives + * here: the demuxer (audio-player-demux/) has already done that work, and this module deliberately knows nothing about it, + * so one decoder serves every supported container. + * + * The demuxer contract + * -------------------- + * The demuxers of the player (audio-player-demux/) expose, per format, the configuration and the packets this module consumes: + * - a configuration, the shape of options.config below: { codec, sampleRate, numberOfChannels, description? }, where + * the codec is a WebCodecs codec string ('mp3', 'flac', 'opus', 'mp4a.40.2', 'vorbis', 'pcm-s16', ...) and the + * description is the codec private data the container carries (the AudioSpecificConfig of an ADTS stream, the + * identification header of an Ogg Opus or Ogg Vorbis stream, the EXTRADATA of an MP4, and so on), when the codec needs one; + * - a stream of encoded packets, each one { data, timestamp, duration, type? }, where data is the encoded bytes, the + * timestamp and the duration are integers (or numbers) of microseconds, and the type is 'key' or 'delta', defaulting + * to 'key', which is the type of every audio packet of the formats the player supports directly. + * A demuxer that already builds WebCodecs objects may hand over an EncodedAudioChunk directly instead of a plain packet, + * in which case it is fed as it is. Keeping the conversion here, rather than in each demuxer, is what makes the + * microsecond timestamps and the packet type uniform across the formats. + * + * The scheduled audio contract + * ---------------------------- + * The decoded AudioData does not go to a queue of this module: the output callback hands each frame to a scheduler, by + * default the TrackRenderer of audio-player-render.js, through scheduler.schedule(audioData). The scheduler takes + * ownership of every frame and closes it, releasing its native memory, so this module hands each frame over exactly once + * and never touches it again. The scheduler must accept decoded audio as fast as it is produced and lay it back to back, + * and it must expose getScheduledAheadSeconds, which is what keeps a decoder faster than real time from decoding, and + * retaining, a whole track: a scheduler that cannot report it is refused at construction rather than decoded against + * without a bound. When the scheduler also publishes its own scheduled ahead ceiling through getMaxScheduledAheadSeconds, + * the decoder stays a margin below it automatically, so the scheduler does not refuse frames and no frame is lost. + * + * Backpressure + * ------------ + * A decoder that is fed as fast as the demuxer produces would queue a large part of an encoded track and, through its + * output callback, a large part of a decoded one. Two ceilings bound that: + * - the decode queue size, decoder.decodeQueueSize, capped by maxQueueSize, which bounds how many encoded packets are + * in flight inside the decoder at once; + * - the scheduled ahead duration of the scheduler, capped by the decoder's own maxDecodeAheadSeconds and by the + * scheduler's published scheduled ahead ceiling, whichever is smaller, which bounds how much decoded audio is + * retained by the scheduler ahead of the playhead. It matters most while playback is paused or has not started, when + * the audio clock is frozen and the schedule would otherwise grow without bound. + * A caller paces itself with canAccept, or simply awaits decodeAsync, which waits for room itself. The wait is released + * when the decoder dequeues a chunk (the dequeue event) or, when only the scheduled ahead duration is holding it back, + * when a poll notices that the playhead has consumed enough of the schedule. + * + * The decoder stays a margin below the scheduler's published scheduled ahead ceiling, so the scheduler does not normally + * refuse a frame. It still can, when the scheduler does not publish its ceiling, or when a frame is longer than that + * margin. Such a refusal is backpressure, not corruption, so while the ceiling can still be satisfied it is not recorded + * as a failure: the decoder tightens the schedule ahead it feeds to, down to the point of the refusal minus the wall time + * of the refused frame, and resumes once the playhead has drained below it, which settles at the scheduler's ceiling + * instead of refusing one frame per decoded frame. A sustained mismatch is a configuration slip, so it is logged once per + * stream. A refusal is not free, however: the scheduler closes the refused frame before it throws, so that frame's audio is + * lost and the backoff can only keep the following frames from being refused too. The one refusal that is recorded as a + * failure is a refusal of an empty schedule, which can only come from a ceiling smaller than one frame plus the scheduling + * lead and so can never be satisfied. + * + * Seeking + * ------- + * A seek is two halves. The scheduler half is renderer.seekTo(seconds), which moves the playhead. The decoder half is + * resetAsync: it resets the decoder, dropping the chunks that are queued and the frames that have not been emitted, and + * reconfigures it with the configuration it was last given, because reset returns a decoder to the unconfigured state. A + * decode that was waiting for room when the seek arrived belongs to the stream before the seek, so it is released as a + * clean stop rather than resumed to submit a packet the new playhead must not play. The caller then fetches and demuxes the + * byte range of the target position and feeds the packets from there. Two separate things must line up, and they are not + * the same thing: the first decoded samples must begin exactly at the target, which the caller gets by trimming the + * demuxer's leading samples to that position, because the scheduler places the first buffer it receives after a seekTo at + * the exact target it was given and ignores that buffer's timestamp, so it cannot correct a leading offset it is not told + * about; and the chunk timestamps the decoder itself is fed must stay monotonic across the seek, which is the decoder's own + * ordering concern and does not re-base the scheduler's timeline. + * + * Failures + * -------- + * The decoder is a sub component, like the download engine: it does not throw strings and does not move the player state + * machine. A failure it cannot recover from, a decoder error, a chunk the decoder refuses, a configuration it rejects, or + * a scheduler failure other than a scheduled ahead refusal it can recover from, is recorded on the decoder for polling + * through getError, is reported to the onError callback as a {@link LuminaAudioPlayer.PlayerError}, and stops the decoder + * cleanly: no chunk is accepted, the queue is dropped and the native decoder is closed. The recorded error carries + * {@link LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED} when the failure is the decoder's own, and the code of the + * error when another component already typed it with {@link LuminaAudioPlayer.PlayerError} (for example the renderer's + * ENGINE_ERROR), because that code is more specific than the decoder's. The recorded error is always owned by this + * decoder: a PlayerError raised by another component is copied rather than adopted, so its details are never mutated and + * getError never returns an object the raising component still holds. An engine must forward the callback to + * host.reportError(error), exactly as the download engine's callback is forwarded, so the failure reaches the + * player and the event bus. + * + * The pipeline calls a caller drives, configure, decode, decodeAsync, flushAsync and resetAsync, also throw the typed + * error, because the caller that triggered the failure is the one that can react to it; the other calls never throw. A + * teardown is never a failure: an abort, a reset or a destroy that interrupts a pending flush is observed as a clean stop, + * not as a decode failure. + * + * Using it + * -------- + * const decoder = LuminaAudioPlayer.createTrackDecoder({ + * scheduler: renderer, + * maxQueueSize: 8, + * maxDecodeAheadSeconds: 5, + * onError: (error) => host.reportError(error) + * }); + * decoder.configure(demuxer.getConfiguration()); // codec, sampleRate, numberOfChannels, description + * renderer.configure(manifest); + * await renderer.playAsync(); // from a user gesture + * while (true) { + * const packet = await demuxer.readPacketAsync(); + * if (!packet) + * break; + * if (!await decoder.decodeAsync(packet)) // waits for room, false when the decoder stopped + * break; + * } + * await decoder.flushAsync(); // all frames emitted + * renderer.markStreamComplete(); // the scheduler may now detect the end of the track + * await decoder.resetAsync(); // the decoder half of a seek + * await decoder.destroyAsync(); + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The number of encoded chunks the decoder may hold before a caller is asked to wait. It bounds the encoded audio in + * flight inside the decoder and, indirectly, how far ahead of the playhead the decode runs. + * @readonly + * @type {number} + */ + const DEFAULT_MAX_QUEUE_SIZE = 8; + + /** + * The default ceiling, in seconds, on how far ahead of the audio clock the scheduler may run before the decoder is + * asked to wait. It bounds the decoded audio retained by the scheduler, which matters while playback is paused or has + * not started; it is deliberately larger than the queue bound so that a short decode hiccup never starves playback. + * @readonly + * @type {number} + */ + const DEFAULT_MAX_SCHEDULED_AHEAD_SECONDS = 5; + + /** + * The interval, in milliseconds, at which a wait for room is re-checked when only the scheduled ahead duration is + * holding it back. The scheduler reports no event when the playhead consumes its schedule, so a poll is the only way + * to notice it; the interval is short enough to be inaudible against the audio already scheduled ahead. + * @readonly + * @type {number} + */ + const CAPACITY_POLL_INTERVAL_MS = 200; + + /** + * The lowest value the scheduled ahead gate may take, in seconds. A refusal proves only that the scheduler's ceiling is + * smaller than the schedule ahead plus the refused frame, not that it is smaller than a single frame, so a gate of + * zero or below would be a false failure and would also block every future chunk. The gate is therefore floored here: + * any ceiling that can accept one frame is above this floor, so a satisfiable ceiling recovers while a genuinely + * unsatisfiable one is detected when it refuses an empty schedule. + * @readonly + * @type {number} + */ + const MINIMUM_SCHEDULE_BACKOFF_SECONDS = 0.01; + + /** + * The margin, in seconds, the decoder keeps between its own scheduled ahead ceiling and the scheduler's published one, + * so that a frame it feeds fits under the scheduler's ceiling instead of being refused and lost. It is approximately + * one frame's wall time: a frame is refused once the schedule ahead plus its wall length would exceed the scheduler's + * ceiling, so feeding up to the scheduler's ceiling minus this margin leaves room for a frame of that length. + * @readonly + * @type {number} + */ + const SCHEDULER_CEILING_MARGIN_SECONDS = 0.1; + + /** + * Coerces a value to a finite number, or null when it is absent or not finite. + * @param {*} value - The value to coerce. + * @returns {number|null} The finite number, or null. + */ + function toFiniteNumber(value) { + if (value === null || value === undefined || value === '') + return null; + const number = Number(value); + return Number.isFinite(number) ? number : null; + } + + /** + * Coerces a value to a positive integer, or null when it is absent, not finite or not positive. + * @param {*} value - The value to coerce. + * @returns {number|null} The positive integer, or null. + */ + function toPositiveInteger(value) { + const number = toFiniteNumber(value); + if (number === null || number <= 0) + return null; + const integer = Math.round(number); + return integer > 0 ? integer : null; + } + + /** + * Accepts the buffer source collections WebCodecs reads a codec description or an encoded packet from, and rejects + * everything else. + * @param {*} value - The value to check. + * @returns {ArrayBuffer|ArrayBufferView|null} The value when it is a buffer source, null otherwise. + */ + function toBufferSource(value) { + if (value === null || value === undefined) + return null; + if (typeof ArrayBuffer === 'undefined') + return null; + if (value instanceof ArrayBuffer) + return value; + if (ArrayBuffer.isView(value)) + return value; + return null; + } + + /** + * Checks whether a value is the AbortError a reset or a close rejects a pending flush with. An AbortError is tested + * by name rather than by type, because in a browser it is a DOMException, which is not an Error. + * @param {*} error - The value to check. + * @returns {boolean} True when the value is an AbortError. + */ + function isAbortError(error) { + return !!error && error.name === 'AbortError'; + } + + /** + * Checks whether a scheduler refused a frame because its own scheduled ahead ceiling is tighter than the decoder's. + * That is backpressure, not corruption: the scheduler refused the frame before scheduling it, so the pipeline can keep + * running, it must only wait for the schedule to drain. The classification rests on two properties the scheduler's + * schedule contract must keep, both documented on the renderer's schedule: the refusal is thrown without being recorded + * as the scheduler's own last error, and the refused frame is closed before the throw. + * @param {*} error - The value the scheduler threw. + * @returns {boolean} True when the refusal is a scheduled ahead limit. + */ + function isScheduledAheadRefusal(error) { + return !!error && !!error.details && error.details.reason === LuminaAudioPlayer.PlayerErrorReason.SCHEDULED_AHEAD_LIMIT; + } + + /** + * Reads the media duration of a decoded frame, in seconds. It must be read before the frame is handed to the + * scheduler, because the scheduler closes the frame before it returns or throws, and a closed frame no longer reports + * its duration. It is the media the frame would add to the schedule ahead, so it is the margin a scheduled ahead + * refusal is honored with. + * @param {AudioData} audioData - The decoded frame. + * @returns {number} The duration, in seconds, or zero when it cannot be read. + */ + function getAudioDataDurationSeconds(audioData) { + if (!audioData) + return 0; + const duration = toFiniteNumber(audioData.duration); + // WebCodecs reports the duration of a decoded frame in microseconds. + return duration === null ? 0 : Math.max(0, duration) / 1000000; + } + + /** + * Merges two error detail objects into a new one, so that a details object a component owns is never mutated in place. + * @param {Object|null} base - The existing details. + * @param {Object|null} extra - The details to add. + * @returns {Object|null} The merged details, or null when both are absent. + */ + function mergeErrorDetails(base, extra) { + const hasBase = base !== null && base !== undefined; + const hasExtra = extra !== null && extra !== undefined; + if (!hasBase && !hasExtra) + return null; + if (!hasExtra) + return Object.assign({}, base); + if (!hasBase) + return Object.assign({}, extra); + return Object.assign({}, base, extra); + } + + /** + * Builds an error this decoder owns. A PlayerError raised by another component is copied rather than adopted, so its + * details are never mutated and the decoder failure never aliases the error the raising component keeps for itself. + * @param {*} error - The failure to own. + * @param {string} fallbackCode - The code to use when the failure is not already a player error. + * @param {Object|null} details - Optional details to merge in. + * @returns {LuminaAudioPlayer.PlayerError} The owned typed error. + */ + function toOwnedError(error, fallbackCode, details) { + if (error instanceof LuminaAudioPlayer.PlayerError) + return new LuminaAudioPlayer.PlayerError(error.code, error.message, mergeErrorDetails(error.details, details)); + const typed = LuminaAudioPlayer.PlayerError.from(error, fallbackCode); + if (!details) + return typed; + return new LuminaAudioPlayer.PlayerError(typed.code, typed.message, mergeErrorDetails(typed.details, details)); + } + + /** + * Creates the WebCodecs audio decoder of the player through the browser constructor. + * @param {{ output: Function, error: Function }} handlers - The output and error callbacks the decoder is created with. + * @returns {AudioDecoder|null} The created decoder, or null when the browser exposes no constructor. + */ + function createDefaultAudioDecoder(handlers) { + const targetWindow = typeof window !== 'undefined' ? window : null; + if (!targetWindow || typeof targetWindow.AudioDecoder !== 'function') + return null; + return new targetWindow.AudioDecoder({ output: handlers.output, error: handlers.error }); + } + + /** + * Gets the WebCodecs EncodedAudioChunk constructor, or null when the browser exposes none. + * @returns {Function|null} The constructor, or null. + */ + function getEncodedAudioChunkConstructor() { + const targetWindow = typeof window !== 'undefined' ? window : null; + return targetWindow && typeof targetWindow.EncodedAudioChunk === 'function' ? targetWindow.EncodedAudioChunk : null; + } + + /** + * Decodes the encoded audio of one track with WebCodecs, feeding the frames it produces to a scheduler. + */ + class TrackDecoder { + /** + * Creates an instance of TrackDecoder. + * @param {Object} options - The decoder options. + * @param {Object} options.scheduler - The decoded audio sink, by default the TrackRenderer of audio-player-render.js. It must expose schedule(audioData), which takes ownership of the frame and closes it, and getScheduledAheadSeconds(), which the decoder uses to bound the decode-ahead. When it also publishes its own scheduled ahead ceiling through getMaxScheduledAheadSeconds(), the decoder stays a margin below it automatically, so the scheduler never refuses a frame. + * @param {Function} [options.decoderFactory] - A factory that receives { output, error } and returns an AudioDecoder. Defaults to the browser AudioDecoder constructor, and exists for injection in a test. + * @param {Object} [options.config] - The initial configuration, of the shape configure accepts; it may also be given to configure later. + * @param {number} [options.maxQueueSize] - The number of encoded chunks the decoder may hold before a caller is asked to wait. Defaults to eight. + * @param {number|null} [options.maxDecodeAheadSeconds] - The decoder's own ceiling, in seconds, on how far ahead of the audio clock it decodes and feeds, so that a fast decoder does not retain a whole decoded track. It is distinct from the scheduler's own ceiling, whose option has a different name and the opposite convention, absent meaning disabled there and a default here. Defaults to five seconds; pass null to disable the decoder's own ceiling, which leaves only the scheduler's, if any. An absent key, an explicit undefined, and a value of zero or below all keep the default, the last because a ceiling of zero could never be satisfied. When the scheduler publishes its own ceiling, the decoder uses the smaller of the two. + * @param {Function} [options.onError] - Called with a {@link LuminaAudioPlayer.PlayerError} when the decoder fails. An engine must forward it to host.reportError. + * @throws {TypeError} When no scheduler with a schedule method and a getScheduledAheadSeconds method is provided. + * @throws {LuminaAudioPlayer.PlayerError} When an initial options.config is given and it is invalid or the browser rejects it. + */ + constructor(options = {}) { + const settings = options || {}; + this.scheduler = settings.scheduler || null; + if (!this.scheduler || typeof this.scheduler.schedule !== 'function') + throw new TypeError('The audio decoder requires a scheduler with a schedule method.'); + // The decode-ahead bound is the only thing that keeps a fast decoder from retaining a whole decoded track, so a + // scheduler that cannot report its scheduled ahead duration is refused instead of silently decoding without a + // bound beyond the small encoded queue. + if (typeof this.scheduler.getScheduledAheadSeconds !== 'function') + throw new TypeError('The audio decoder requires a scheduler that reports its scheduled ahead duration.'); + this.decoderFactory = typeof settings.decoderFactory === 'function' ? settings.decoderFactory : createDefaultAudioDecoder; + this.maxQueueSize = toPositiveInteger(settings.maxQueueSize) || DEFAULT_MAX_QUEUE_SIZE; + // The ceiling must be strictly positive to be satisfiable: the scheduled ahead duration is never negative, so a + // ceiling of zero or below would block every chunk forever instead of refusing one buffer, and a wait for room + // would then never settle. An absent key, an explicit undefined and an invalid or non-positive value all keep + // the default, and an explicit null is the only way to disable the ceiling. + if (!Object.prototype.hasOwnProperty.call(settings, 'maxDecodeAheadSeconds')) { + this.maxDecodeAheadSeconds = DEFAULT_MAX_SCHEDULED_AHEAD_SECONDS; + } else if (settings.maxDecodeAheadSeconds === null) { + this.maxDecodeAheadSeconds = null; + } else { + const ceiling = toFiniteNumber(settings.maxDecodeAheadSeconds); + this.maxDecodeAheadSeconds = ceiling === null || ceiling <= 0 ? DEFAULT_MAX_SCHEDULED_AHEAD_SECONDS : ceiling; + } + this.onError = typeof settings.onError === 'function' ? settings.onError : null; + /** @type {AudioDecoder|null} */ + this.decoder = null; + /** @type {Object|null} */ + this.config = null; + /** @type {LuminaAudioPlayer.PlayerError|null} */ + this.error = null; + this.configured = false; + this.destroyed = false; + /** @type {Array} */ + this.capacityWaiters = []; + /** @type {number|null} */ + this.capacityTimer = null; + this.chunksFed = 0; + this.framesDecoded = 0; + // The scheduled ahead duration below which feeding reopens after the scheduler refused a frame, if any. It + // only ever tightens for the stream, so a scheduler whose own ceiling is tighter than this decoder's settles at + // that ceiling instead of refusing one frame per decoded frame. + /** @type {number|null} */ + this.scheduleBackoffSeconds = null; + // True once the scheduled ahead mismatch of the current stream was logged, so a sustained mismatch, which is a + // configuration slip, does not flood the console. + this.scheduleBackoffWarned = false; + // Incremented every time the stream the decoder is decoding changes, which is a configure or a reset. A decode + // that was waiting for room across such a change belongs to the previous stream and must not be submitted, + // so it is identified by the generation it started with and dropped when the generation moved on. + this.generation = 0; + + if (settings.config) + this.configure(settings.config); + } + + //+======================================================================================+ + //| Lifecycle | + //+======================================================================================+ + + /** + * Configures the decoder for a track, creating the native decoder on first use. The configuration is kept, so + * that a reset can reconfigure the decoder on a seek without the caller supplying it again. + * @param {Object} config - The decoder configuration. + * @param {string} config.codec - The WebCodecs codec string of the track, for example 'mp3', 'flac', 'opus', 'mp4a.40.2', 'vorbis' or 'pcm-s16'. + * @param {number} config.sampleRate - The sample rate of the encoded audio, in Hz. + * @param {number} config.numberOfChannels - The number of channels of the encoded audio. + * @param {ArrayBuffer|ArrayBufferView} [config.description] - The codec private data the container carries, for a codec that needs one. + * @returns {LuminaAudioPlayer.TrackDecoder} This decoder, for chaining. + * @throws {LuminaAudioPlayer.PlayerError} When the decoder was destroyed, already failed, or the configuration is missing a required value or is rejected by the browser. + */ + configure(config) { + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The audio decoder was destroyed.'); + if (this.error) + throw this.error; + // The configuration is validated before the native decoder is created, so an invalid configuration never + // allocates one and a decoder that already exists is left untouched. + const normalized = this.normalizeConfig(config); + this.ensureDecoder(); + // A reconfigure starts a new stream at the native boundary too. configure() resets an already configured + // decoder itself, but the reset is done explicitly here so that the module's stream boundary and the native one + // cannot drift apart, and so a track change drops the queued chunks and the pending frames deterministically + // instead of leaving it to configure(). A reset returns the decoder to the unconfigured state, so it is only + // done when a configuration is already in effect. + if (this.configured && typeof this.decoder.reset === 'function') { + try { + this.decoder.reset(); + } catch (error) { + throw this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: 'reset-failed' }); + } + } + this.applyConfiguration(normalized); + this.config = normalized; + this.configured = true; + // A reconfigure starts a new stream, so a decode that is waiting for room belongs to the previous one and is + // released as a clean stop instead of being submitted against the new configuration, and a backoff learned + // from the previous stream no longer applies. There is no pump after this: resolveWaiters already emptied the + // waiters, so a pump would return at once. + this.generation++; + this.scheduleBackoffSeconds = null; + this.scheduleBackoffWarned = false; + this.clearCapacityTimer(); + this.resolveWaiters(false); + return this; + } + + /** + * Releases the native decoder, and every wait that was resting on it. It is safe to call more than once. + * + * A direct call releases the pending capacity waiters and the poll timer exactly as fail and destroyAsync do, so a + * caller that closes the decoder itself cannot strand a wait or leave the 200 ms poll running. The decoder is left + * unconfigured but neither stopped nor destroyed, so a later configure creates a fresh one. + * @returns {void} + */ + closeDecoder() { + // The release happens before the decoder existence check, so a call on an already closed decoder still settles + // anything that is waiting, rather than relying on the decoder reference being non-null. + this.clearCapacityTimer(); + this.resolveWaiters(false); + if (!this.decoder) + return; + const decoder = this.decoder; + this.decoder = null; + this.configured = false; + if (typeof decoder.close !== 'function') + return; + try { + const closing = decoder.close(); + // close never rejects, but a decoder implementation that returns a rejected promise must not leave an + // unhandled rejection behind, so the outcome is deliberately discarded. + if (closing && typeof closing.catch === 'function') + closing.catch(() => {}); + } catch (error) { + console.debug('Audio player: the audio decoder could not be closed.', error); + } + } + + /** + * Releases every resource of the decoder: the pending capacity waiters, the poll timer and the native decoder. + * @returns {Promise} A promise that completes when the native decoder is closed. + */ + async destroyAsync() { + if (this.destroyed) + return; + this.destroyed = true; + this.configured = false; + this.clearCapacityTimer(); + this.resolveWaiters(false); + const decoder = this.decoder; + this.decoder = null; + if (!decoder || typeof decoder.close !== 'function') + return; + try { + await decoder.close(); + } catch (error) { + console.debug('Audio player: the audio decoder could not be closed.', error); + } + } + + //+======================================================================================+ + //| Decode surface | + //+======================================================================================+ + + /** + * Performs the decoder half of a seek: it resets the decoder, dropping the queued chunks and the frames that have + * not been emitted, and reconfigures it with the configuration it was last given. A decode that is waiting for + * room when the seek arrives is released as a clean stop, because its packet belongs to the stream before the + * seek. The scheduler half of the seek, renderer.seekTo, is the caller's to perform. + * @returns {Promise} A promise that resolves once the decoder is configured again. + * @throws {LuminaAudioPlayer.PlayerError} When the decoder was destroyed, already failed, or could not be reset. + */ + async resetAsync() { + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The audio decoder was destroyed.'); + if (this.error) + throw this.error; + if (!this.decoder) + return; + this.configured = false; + // The seek starts a new stream, so every decode that is waiting for room belongs to the stream before the + // seek and is released as a clean stop, instead of resuming to submit a stale pre-seek packet once the + // reset empties the queue. A backoff learned from the stream before the seek no longer applies either. + this.generation++; + this.scheduleBackoffSeconds = null; + this.scheduleBackoffWarned = false; + this.clearCapacityTimer(); + this.resolveWaiters(false); + try { + this.decoder.reset(); + } catch (error) { + throw this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: 'reset-failed' }); + } + // A reset returns the decoder to the unconfigured state, so the last configuration is applied again before + // any new packet is fed; without it the decoder would refuse the first packet of the seek. + if (this.config) { + this.applyConfiguration(this.config); + this.configured = true; + } + } + + /** + * Feeds one encoded packet to the decoder, submitting an EncodedAudioChunk with its microsecond timestamp and + * duration. The chunk is submitted, not decoded: the decoded frames arrive later, in the output callback. + * @param {Object|EncodedAudioChunk} packet - The encoded packet, or a prebuilt EncodedAudioChunk. See {@link LuminaAudioPlayer.TrackDecoder#buildEncodedChunk} for the packet shape. + * @returns {void} + * @throws {LuminaAudioPlayer.PlayerError} With {@link LuminaAudioPlayer.PlayerErrorCode.DECODER_BUSY} and details.reason === 'queue-full' when there is no room right now, which is a transient condition a caller resolves by waiting for {@link LuminaAudioPlayer.TrackDecoder#waitForCapacityAsync}. Otherwise, with {@link LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE} when the decoder is destroyed or not configured, or with a fatal recorded failure when it rejects the packet. + */ + decode(packet) { + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The audio decoder was destroyed.'); + if (this.error) + throw this.error; + if (!this.configured) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The audio decoder is not configured.'); + if (!this.canAccept()) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODER_BUSY, 'The audio decoder cannot accept another chunk yet.', { reason: 'queue-full' }); + const chunk = this.buildEncodedChunk(packet); + try { + this.decoder.decode(chunk); + } catch (error) { + throw this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: 'decode-rejected' }); + } + this.chunksFed++; + } + + /** + * Waits for room in the decoder, then feeds one encoded packet. This is the entry point a decode loop uses; a loop + * that paces itself with canAccept may call decode directly instead. + * @param {Object|EncodedAudioChunk} packet - The encoded packet, per {@link LuminaAudioPlayer.TrackDecoder#decode}. + * @returns {Promise} True when the packet was submitted, false when the decoder stopped or the stream + * changed before there was room, which the caller reads as a clean stop rather than a failure. + * @throws {LuminaAudioPlayer.PlayerError} When the decoder is in a state that can never accept the packet, or rejects it. + */ + async decodeAsync(packet) { + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The audio decoder was destroyed.'); + if (this.error) + throw this.error; + if (!this.configured) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The audio decoder is not configured.'); + const generation = this.generation; + // A single pump releases a batch of waiters at once, and their continuations run one after another, so another + // caller can take the last slot before this one reaches decode. The wait is therefore repeated until this + // caller actually has room, which keeps the race from surfacing as a queue-full throw in the decode loop. + while (true) { + const accepted = await this.waitForCapacityAsync(); + if (!accepted) + return false; + // The state may have changed while the wait was pending, so it is re-read before the packet is submitted. + // The generation is a configure or a reset that happened while this packet waited, which makes the packet + // stale: it belongs to the previous stream and must not be decoded against the new one. + if (this.destroyed || this.error || !this.configured || generation !== this.generation) + return false; + if (!this.canAccept()) + continue; + this.decode(packet); + return true; + } + } + + /** + * Emits every decoded frame of the chunks fed so far, and resolves once none is left pending. A caller invokes it + * after the last packet was fed and before it declares the stream complete to the scheduler, so that no frame is + * lost behind the end of the track. It is a no-op, resolving without touching the native decoder, when the decoder + * is not configured, so a caller that is unsure whether it ever configured one may call it unconditionally. + * @returns {Promise} A promise that resolves once the decoder has emitted every pending frame. + * @throws {LuminaAudioPlayer.PlayerError} When the decoder was destroyed, already failed, or refused to flush. + */ + async flushAsync() { + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The audio decoder was destroyed.'); + if (this.error) + throw this.error; + if (!this.decoder || !this.configured) + return; + try { + await this.decoder.flush(); + } catch (error) { + // A reset or a close interrupts a pending flush; that is a teardown of the decode pipeline, not a failure + // of the track, so it is observed as a clean stop. + if (this.destroyed || this.error || isAbortError(error)) + return; + throw this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: 'flush-failed' }); + } + } + + //+======================================================================================+ + //| Backpressure | + //+======================================================================================+ + + /** + * Checks whether the decoder can take another chunk right now, without waiting. + * @returns {boolean} True when there is room in the decode queue and the scheduler is not too far ahead. + */ + canAccept() { + return this.getAvailableSlots() > 0; + } + + /** + * Gets the number of chunks the decoder can take right now. It is zero when the decoder is stopped, unconfigured, + * its decode queue is full, the scheduler is at or beyond the effective scheduled ahead ceiling, or the scheduler + * refused a frame and the schedule has not yet drained below the refusal point. + * @returns {number} The number of available slots. + */ + getAvailableSlots() { + if (this.destroyed || this.error || !this.configured) + return 0; + const slots = this.maxQueueSize - this.getDecodeQueueSize(); + if (slots <= 0) + return 0; + const ahead = this.getScheduledAheadSeconds(); + const ceiling = this.getEffectiveCeiling(); + if (ceiling !== null && ahead >= ceiling) + return 0; + // A refused frame means the scheduler enforced a tighter ceiling than this decoder's, so feeding stays paused + // until the playhead has consumed the schedule below the point of the refusal. + if (this.scheduleBackoffSeconds !== null && ahead >= this.scheduleBackoffSeconds) + return 0; + return slots; + } + + /** + * Gets the scheduled ahead ceiling the decoder actually feeds to, in seconds, or null when it feeds without a + * bound. It is the smaller of the decoder's own ceiling and the scheduler's published one, the latter kept a margin + * below, so that a frame the decoder feeds fits under the scheduler's ceiling and is not refused and lost. Reading + * the scheduler's ceiling here is what enforces the lossless ordering instead of leaving it to the caller to keep + * the two options in the right relation. + * @returns {number|null} The effective ceiling, in seconds, or null when there is none. + */ + getEffectiveCeiling() { + const schedulerCeiling = this.getSchedulerCeiling(); + if (schedulerCeiling === null) + return this.maxDecodeAheadSeconds; + // The margin is one frame's wall time, and the floor keeps a scheduler ceiling smaller than a frame from + // closing the gate entirely, so the refusal handler can still detect an unsatisfiable ceiling. + const safe = Math.max(MINIMUM_SCHEDULE_BACKOFF_SECONDS, schedulerCeiling - SCHEDULER_CEILING_MARGIN_SECONDS); + if (this.maxDecodeAheadSeconds === null) + return safe; + return Math.min(this.maxDecodeAheadSeconds, safe); + } + + /** + * Gets the scheduled ahead ceiling the scheduler publishes, in seconds, or null when it publishes none or its + * accessor throws. + * @returns {number|null} The scheduler's ceiling, in seconds, or null. + */ + getSchedulerCeiling() { + if (!this.scheduler || typeof this.scheduler.getMaxScheduledAheadSeconds !== 'function') + return null; + try { + const ceiling = toFiniteNumber(this.scheduler.getMaxScheduledAheadSeconds()); + return ceiling === null || ceiling < 0 ? null : ceiling; + } catch (error) { + console.debug('Audio player: the scheduler could not report its scheduled ahead ceiling.', error); + return null; + } + } + + /** + * Resolves as soon as the decoder has room for another chunk. It resolves false when the decoder will never have + * room for the caller: when it is stopped or not configured, or when a configure, a reset, a failure or a destroy + * releases the pending wait, because the packet the caller holds belongs to the stream that just ended. A wait that + * finds room immediately resolves true without any generation check; decodeAsync is the entry point that drops a + * packet whose stream changed under it. + * @returns {Promise} True when there is room, false when the decoder stopped, is not configured, or the wait was released by a configure, reset, failure or destroy. + */ + waitForCapacityAsync() { + if (this.canAccept()) + return Promise.resolve(true); + if (this.destroyed || this.error || !this.configured) + return Promise.resolve(false); + return new Promise((resolve) => { + this.capacityWaiters.push(resolve); + // The decoder reports no event while the audio clock consumes the schedule, so the wait is also polled. + this.scheduleCapacityCheck(); + }); + } + + //+======================================================================================+ + //| Query surface | + //+======================================================================================+ + + /** + * Gets the number of encoded chunks the decoder holds right now. + * @returns {number} The decode queue size. + */ + getDecodeQueueSize() { + if (!this.decoder) + return 0; + const size = Number(this.decoder.decodeQueueSize); + return Number.isFinite(size) && size > 0 ? size : 0; + } + + /** + * Gets the decode queue ceiling the decoder enforces. + * @returns {number} The maximum decode queue size. + */ + getMaxQueueSize() { + return this.maxQueueSize; + } + + /** + * Gets how far ahead of the audio clock the scheduler currently runs, in seconds. The scheduler is required to + * expose the value, so this is what the scheduler reports; a scheduler whose accessor throws, for example once its + * audio context is closed, is treated as an empty schedule rather than failing the caller, because this is called + * from a polling timer and from the output callback, where an escaping exception could not be reported. + * @returns {number} The scheduled ahead duration, in seconds. + */ + getScheduledAheadSeconds() { + try { + const ahead = Number(this.scheduler.getScheduledAheadSeconds()); + return Number.isFinite(ahead) ? Math.max(0, ahead) : 0; + } catch (error) { + console.debug('Audio player: the scheduler could not report its scheduled ahead duration.', error); + return 0; + } + } + + /** + * Gets the playback rate the scheduler is running at. It converts a frame's media duration into the wall time the + * frame adds to the schedule ahead, which the scheduled ahead gate is measured in. The scheduler is not required to + * expose it, so a scheduler that does not, or one whose accessor throws, is assumed to run at rate one. + * @returns {number} The playback rate, or one when the scheduler does not report it. + */ + getPlaybackRate() { + if (!this.scheduler || typeof this.scheduler.getPlaybackRate !== 'function') + return 1; + try { + const rate = Number(this.scheduler.getPlaybackRate()); + return Number.isFinite(rate) && rate > 0 ? rate : 1; + } catch (error) { + console.debug('Audio player: the scheduler could not report its playback rate.', error); + return 1; + } + } + + /** + * Gets the configuration the decoder is running with. + * @returns {Object|null} A shallow copy of the configuration, or null when the decoder was never configured. The + * codec description buffer is shared with the decoder, not cloned. + */ + getConfig() { + return this.config ? Object.assign({}, this.config) : null; + } + + /** + * Gets the last failure the decoder recorded, or null when there was none. + * @returns {LuminaAudioPlayer.PlayerError|null} The recorded failure. + */ + getError() { + return this.error; + } + + /** + * Checks whether the decoder is configured and ready to take encoded packets. + * @returns {boolean} True when the decoder is configured. + */ + isConfigured() { + return this.configured && !this.destroyed && !this.error; + } + + /** + * Checks whether the decoder was destroyed. + * @returns {boolean} True when the decoder was destroyed. + */ + isDestroyed() { + return this.destroyed; + } + + /** + * Checks whether the decoder can no longer accept encoded packets, because it was destroyed or because it + * failed. + * @returns {boolean} True when the decoder has stopped. + */ + isStopped() { + return this.destroyed || this.error !== null; + } + + /** + * Gets a snapshot of the decoder counters, for diagnostics and tests. + * @returns {{ chunksFed: number, framesDecoded: number, decodeQueueSize: number }} The snapshot. + */ + getStatistics() { + return Object.freeze({ + chunksFed: this.chunksFed, + framesDecoded: this.framesDecoded, + decodeQueueSize: this.getDecodeQueueSize() + }); + } + + //+======================================================================================+ + //| Internal helpers | + //+======================================================================================+ + + /** + * Makes sure the native decoder exists, creating it on first use through the decoder factory. + * @returns {AudioDecoder} The native decoder. + * @throws {LuminaAudioPlayer.PlayerError} When the environment provides no decoder, or it could not be created. + */ + ensureDecoder() { + if (this.decoder) + return this.decoder; + let decoder = null; + try { + decoder = this.decoderFactory({ + output: (audioData) => this.handleOutput(audioData), + error: (error) => this.handleError(error) + }); + } catch (error) { + throw this.fail(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED); + } + if (!decoder || typeof decoder.configure !== 'function' || typeof decoder.decode !== 'function') { + // A factory that returns something unusable may still hold native resources, so the object is released + // before the failure is raised, exactly as a decoder that fails later is released by fail(). + if (decoder && typeof decoder.close === 'function') { + try { + const closing = decoder.close(); + if (closing && typeof closing.catch === 'function') + closing.catch(() => {}); + } catch (closeError) { + console.debug('Audio player: the unusable audio decoder could not be closed.', closeError); + } + } + throw this.fail(this.createError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'This environment provides no audio decoder for the player.')); + } + this.decoder = decoder; + if (typeof decoder.addEventListener === 'function') { + // One dequeue event fires per chunk that leaves the decoder, which is the moment a slot is freed and a + // waiting caller can be released without polling. + try { + decoder.addEventListener('dequeue', () => this.pump()); + } catch (error) { + console.debug('Audio player: the decoder dequeue event could not be observed.', error); + } + } + return decoder; + } + + /** + * Validates and normalizes a configuration into the exact shape the browser is given. + * @param {Object} config - The configuration to normalize. + * @returns {Object} The normalized configuration. + * @throws {LuminaAudioPlayer.PlayerError} When the configuration is missing a required value or carries an invalid one. + */ + normalizeConfig(config) { + if (!config || typeof config !== 'object') + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, 'The audio decoder configuration is missing.', { reason: 'invalid-config' }); + const codec = typeof config.codec === 'string' ? config.codec.trim() : ''; + if (codec === '') + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, 'The audio decoder configuration names no codec.', { reason: 'invalid-config' }); + const sampleRate = toPositiveInteger(config.sampleRate); + if (sampleRate === null) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, 'The audio decoder configuration carries no valid sample rate.', { reason: 'invalid-config' }); + const numberOfChannels = toPositiveInteger(config.numberOfChannels); + if (numberOfChannels === null) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, 'The audio decoder configuration carries no valid channel count.', { reason: 'invalid-config' }); + const normalized = { codec, sampleRate, numberOfChannels }; + if (config.description !== null && config.description !== undefined) { + const description = toBufferSource(config.description); + if (description === null) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, 'The audio decoder configuration carries an invalid codec description.', { reason: 'invalid-config' }); + normalized.description = description; + } + return normalized; + } + + /** + * Applies a normalized configuration to the native decoder. + * @param {Object} normalized - The configuration, per {@link LuminaAudioPlayer.TrackDecoder#normalizeConfig}. + * @returns {void} + * @throws {LuminaAudioPlayer.PlayerError} When the browser rejects the configuration, for example a codec it cannot decode. + */ + applyConfiguration(normalized) { + try { + this.decoder.configure(normalized); + } catch (error) { + throw this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: 'configure-failed' }); + } + } + + /** + * Builds a WebCodecs EncodedAudioChunk from the packet a demuxer produced, or accepts one that a demuxer built itself. + * + * The packet shape is { data, timestamp, duration, type? }: data is the encoded bytes, as a buffer source; the + * timestamp is the presentation timestamp of the first sample, in microseconds; the duration is the number of + * microseconds the packet covers; and the type is 'key' or 'delta', defaulting to 'key', which is the type of + * every audio packet of the formats the player supports directly. A missing or non finite timestamp is refused, + * because a decoder cannot place a packet without one; a missing duration is treated as zero. + * @param {Object|EncodedAudioChunk} packet - The packet to convert. + * @returns {EncodedAudioChunk} The chunk to feed the decoder. + * @throws {LuminaAudioPlayer.PlayerError} When the packet is not a usable encoded chunk. + */ + buildEncodedChunk(packet) { + const ChunkConstructor = getEncodedAudioChunkConstructor(); + if (ChunkConstructor && packet instanceof ChunkConstructor) + return packet; + if (!packet || typeof packet !== 'object') + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, 'The demuxer provided no encoded packet to decode.', { reason: 'invalid-packet' }); + const data = toBufferSource(packet.data); + if (data === null) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, 'The encoded packet carries no decodable data.', { reason: 'invalid-packet' }); + const timestamp = toFiniteNumber(packet.timestamp); + if (timestamp === null) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, 'The encoded packet carries no valid timestamp.', { reason: 'invalid-packet' }); + const duration = toFiniteNumber(packet.duration); + if (!ChunkConstructor) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'This environment provides no encoded audio chunk type for the player.'); + try { + return new ChunkConstructor({ + type: packet.type === 'delta' ? 'delta' : 'key', + timestamp: Math.round(timestamp), + duration: duration === null ? 0 : Math.round(duration), + data + }); + } catch (error) { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, 'The demuxer provided an encoded packet the decoder cannot use.', { reason: 'invalid-packet' }); + } + } + + /** + * Consumes one decoded frame out of the decoder and hands it to the scheduler. + * + * The scheduler takes ownership of the frame and closes it, so this callback never closes a frame it handed over. + * A frame that arrives after the decoder stopped or failed is closed here instead, so its native memory is always + * released. A refusal caused by the scheduler's own scheduled ahead ceiling is treated as backpressure rather than + * corruption, through handleScheduleRefusal. + * @param {AudioData} audioData - The decoded frame. + */ + handleOutput(audioData) { + if (this.destroyed || this.error) { + this.closeAudioData(audioData); + return; + } + // The wall time the frame would add to the schedule ahead, which is its media duration scaled by the playback + // rate. It is read before the frame is handed over, because the scheduler closes it before returning or throwing. + const frameWallSeconds = getAudioDataDurationSeconds(audioData) / this.getPlaybackRate(); + try { + this.scheduler.schedule(audioData); + } catch (error) { + if (isScheduledAheadRefusal(error)) { + // The scheduler closed the frame already, so it is not closed here. + this.handleScheduleRefusal(error, frameWallSeconds); + return; + } + // The scheduler closes the frame before it throws, so it must not be closed here as well. + this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: 'schedule-failed' }); + return; + } + this.framesDecoded++; + this.pump(); + } + + /** + * Handles a frame the scheduler refused because it ran beyond the scheduler's own scheduled ahead ceiling. For a + * ceiling that can still be satisfied that is backpressure, not corruption, so the decoder keeps running and only + * tightens when it feeds again; a refusal of an empty schedule, which can never be satisfied, is the one case that + * stops the decoder. + * + * A refusal is not free: the scheduler closes the refused frame before it throws, so that frame's audio is + * discarded and cannot be replayed, and this method can only keep the following frames from being refused too. The + * decoder normally avoids refusals by staying a margin below the scheduler's published ceiling, so reaching here + * means the scheduler does not publish its ceiling or a frame was longer than the margin. + * + * The scheduler refuses a frame once the schedule ahead plus that frame's wall length would exceed its ceiling. + * Feeding therefore reopens only after the playhead has drained the schedule below the point of the refusal by the + * frame's wall length, which is the most the refused frame could have added and so is enough for the next frame of + * a similar size to fit. The gate is floored, because a refusal only proves the ceiling is smaller than the + * schedule ahead plus the frame, not that it is smaller than one frame, so a satisfiable ceiling must not be turned + * into a failure. The gate only ever tightens for the stream, which is what makes a sustained mismatch settle at + * the scheduler's ceiling instead of refusing a frame per decoded frame, and the mismatch, a configuration slip, is + * logged once per stream. + * @param {*} error - The scheduled ahead refusal the scheduler threw. + * @param {number} frameWallSeconds - The wall time, in seconds, the refused frame would have added to the schedule. + */ + handleScheduleRefusal(error, frameWallSeconds) { + const ahead = this.getScheduledAheadSeconds(); + // Only a refusal of an empty schedule is genuinely unsatisfiable: it can only come from a ceiling smaller than + // one frame plus the scheduling lead, which can never accept anything, so it is a configuration failure. Any + // other refusal may still be a satisfiable ceiling that simply has to drain further, so it is recoverable. + if (ahead <= 0) { + this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: LuminaAudioPlayer.PlayerErrorReason.SCHEDULED_AHEAD_UNSATISFIABLE }); + return; + } + const duration = Number.isFinite(frameWallSeconds) ? Math.max(0, frameWallSeconds) : 0; + const margin = duration > 0 ? duration : ahead / 2; + const gate = Math.max(MINIMUM_SCHEDULE_BACKOFF_SECONDS, ahead - margin); + this.scheduleBackoffSeconds = this.scheduleBackoffSeconds === null ? gate : Math.min(this.scheduleBackoffSeconds, gate); + if (!this.scheduleBackoffWarned) { + this.scheduleBackoffWarned = true; + console.warn('Audio player: the scheduler refused a decoded frame it had no room for, so the decode-ahead is reduced for this track and the refused frame is lost. Keep the decoder scheduled ahead ceiling below the scheduler ceiling.'); + } + this.pump(); + } + + /** + * Handles a failure reported by the native decoder itself. It is a failure of the track, not of a caller, so it is + * recorded and stops the decoder cleanly. A failure that arrives after the decoder was torn down is not a failure + * of the track, so it is ignored, exactly as a frame that arrives after a teardown is dropped by handleOutput. + * @param {*} error - The failure the decoder reported. + */ + handleError(error) { + if (this.destroyed || this.error) + return; + this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: 'decoder-error' }); + } + + /** + * Releases the native memory of a decoded frame the scheduler will not take. + * @param {AudioData} audioData - The frame to close. + */ + closeAudioData(audioData) { + if (!audioData || typeof audioData.close !== 'function') + return; + try { + audioData.close(); + } catch (error) { + console.debug('Audio player: a decoded frame could not be released.', error); + } + } + + /** + * Records a fatal failure, stops the decoder cleanly and notifies the error callback. The first failure wins, so + * a burst of callbacks after the decoder stopped never overwrites the cause or reports twice. The error is copied + * into one this decoder owns, and a failure that another component already typed with a player error keeps that + * component's code, which is more specific than the code passed here. + * @param {*} error - The failure to record. + * @param {string} [code] - The code to use when the failure is not already a player error. + * @param {Object} [details] - Optional structured details about the failure. + * @returns {LuminaAudioPlayer.PlayerError} The recorded typed error. + */ + fail(error, code = LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, details = null) { + if (this.error) + return this.error; + // The error is owned by this decoder: a PlayerError raised elsewhere is copied rather than adopted, so its + // details are never mutated and getError never returns an object the raising component still holds. + const typed = toOwnedError(error, code, details); + this.error = typed; + this.clearCapacityTimer(); + this.closeDecoder(); + this.resolveWaiters(false); + if (this.onError) { + try { + this.onError(typed); + } catch (callbackError) { + console.error('Audio player: the decoder error callback threw.', callbackError); + } + } + return typed; + } + + /** + * Builds a typed error without recording it, for a caller error that does not stop the decoder, such as feeding a + * packet when the decoder is not configured. + * @param {string} code - One of the {@link LuminaAudioPlayer.PlayerErrorCode} values. + * @param {string} message - The developer facing description of the failure. + * @param {Object} [details] - Optional structured details about the failure. + * @returns {LuminaAudioPlayer.PlayerError} The typed error. + */ + createError(code, message, details = null) { + return new LuminaAudioPlayer.PlayerError(code, message, details); + } + + /** + * Resolves the waiters whose room is now available, and reschedules the poll while some are still waiting. + */ + pump() { + if (this.capacityWaiters.length === 0) + return; + if (this.destroyed || this.error) { + this.resolveWaiters(false); + return; + } + let slots = this.getAvailableSlots(); + while (slots > 0 && this.capacityWaiters.length > 0) { + const resolve = this.capacityWaiters.shift(); + resolve(true); + slots--; + } + if (this.capacityWaiters.length > 0) + this.scheduleCapacityCheck(); + else + this.clearCapacityTimer(); + } + + /** + * Schedules a poll that re-checks the room once, while at least one waiter is pending. It is the fallback for the + * wait that only the audio clock can release, because the scheduler emits no event when it consumes its schedule. + */ + scheduleCapacityCheck() { + if (this.destroyed || this.capacityTimer !== null || this.capacityWaiters.length === 0) + return; + this.capacityTimer = setTimeout(() => { + this.capacityTimer = null; + this.pump(); + }, CAPACITY_POLL_INTERVAL_MS); + } + + /** + * Clears the poll timer, when one is pending. + */ + clearCapacityTimer() { + if (this.capacityTimer === null) + return; + clearTimeout(this.capacityTimer); + this.capacityTimer = null; + } + + /** + * Resolves and clears every pending capacity waiter. + * @param {boolean} value - The value to resolve each waiter with. + */ + resolveWaiters(value) { + if (this.capacityWaiters.length === 0) + return; + const waiters = this.capacityWaiters; + this.capacityWaiters = []; + for (const resolve of waiters) + resolve(value); + } + } + + LuminaAudioPlayer.TrackDecoder = TrackDecoder; + + /** + * Creates a WebCodecs track decoder. See {@link LuminaAudioPlayer.TrackDecoder} for the options. + * @param {Object} options - The decoder options. + * @returns {LuminaAudioPlayer.TrackDecoder} The created decoder. + */ + LuminaAudioPlayer.createTrackDecoder = function (options) { + return new TrackDecoder(options); + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js index 7777203d..14d26630 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js @@ -131,12 +131,13 @@ } /** - * Checks whether a value is the AbortError a cancelled fetch or stream read rejects with. + * Checks whether a value is the AbortError a cancelled fetch or stream read rejects with. It is tested by name rather + * than by type, because in a browser an AbortError is a DOMException, which is not an Error. * @param {*} error - The value to check. * @returns {boolean} True when the value is an AbortError. */ function isAbortError(error) { - return error instanceof Error && error.name === 'AbortError'; + return !!error && error.name === 'AbortError'; } /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js index f6458c0d..673ff0bd 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js @@ -35,9 +35,10 @@ * bar shows the same loading state for an engine's own range fetch as it does for a seek. The state it sets * stays until the engine reports it is no longer buffering, and a playhead report never clears it. * - host.reportEnded(): reports that the current track reached its end. - * - host.reportError(error): reports an engine failure, wrapped into a {@link LuminaAudioPlayer.PlayerError}. A download - * engine must forward its downloader's onError here, because the downloader only reports to its own callback and - * never emits on the event bus, so a failure that is not forwarded stays unobserved. + * - host.reportError(error): reports an engine failure, wrapped into a {@link LuminaAudioPlayer.PlayerError}. Every sub + * component that reports through its own callback must be forwarded here, because such a component only reports to its + * own callback and never emits on the event bus, so a failure that is not forwarded stays unobserved. The download + * engine must forward its downloader's onError, and an engine that decodes must forward its decoder's onError as well. * * Registering and selecting an engine * ----------------------------------- diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js index ebc06ce6..9fc8d704 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -25,6 +25,11 @@ ENGINE_LOAD_FAILED: 'engine-load-failed', // The engine reported a failure while decoding, buffering or rendering audio. ENGINE_ERROR: 'engine-error', + // The WebCodecs decode pipeline could not be configured, refused a chunk, or failed to decode one. + DECODE_FAILED: 'decode-failed', + // The decoder has no room for another chunk right now, so a caller that paces itself should wait. Unlike + // DECODE_FAILED, which is fatal, this is a transient, recoverable pacing condition. + DECODER_BUSY: 'decoder-busy', // The download of a track failed, or was rejected by the stream. DOWNLOAD_FAILED: 'download-failed', // The download of a track was intentionally stopped, by an abort or a destroy, so a reader can tell a teardown apart from a stream failure. @@ -33,6 +38,27 @@ PREFERENCES_LOAD_FAILED: 'preferences-load-failed' }); + /** + * Enum-like object for the stable details.reason values that cross a module boundary of the player. + * + * A reason is a structured detail of a {@link LuminaAudioPlayer.PlayerError} that a consumer branches on, so its value + * is defined once here and shared, never written as a literal by the producer and the consumer separately: two copies + * of a literal drift apart silently, and a consumer that keys on a stale one reclassifies a recoverable condition as + * a fatal failure without anything failing to compile. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerErrorReason = Object.freeze({ + // A scheduler refused a decoded frame because its own scheduled ahead ceiling is tighter than the caller's, so the + // frame is backpressure rather than a failure. Published by the renderer's schedule and recognized by the decode + // pipeline, which pauses feeding instead of stopping. + SCHEDULED_AHEAD_LIMIT: 'scheduled-ahead-limit', + // A scheduler's scheduled ahead ceiling is smaller than one frame plus its scheduling lead, so it can never accept a + // frame at all. Unlike SCHEDULED_AHEAD_LIMIT, which is recoverable backpressure, this is terminal: the decode + // pipeline stops because it can never make progress. + SCHEDULED_AHEAD_UNSATISFIABLE: 'scheduled-ahead-unsatisfiable' + }); + /** * An error raised by the player, carrying a stable code and optional structured details. */ diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js index 3528bce1..594a3a36 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js @@ -674,7 +674,7 @@ * the current track resumes the playback state, so the playhead and the callbacks continue to run. * @param {AudioData} audioData - The decoded audio to schedule. Ownership transfers to the renderer, which closes it. * @returns {number} The media position, in seconds, at the end of the scheduled audio. - * @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed, or the audio could not be converted or scheduled. + * @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed, or the audio could not be converted or scheduled. A refusal caused by the renderer's own maxScheduledAheadSeconds ceiling carries details.reason === {@link LuminaAudioPlayer.PlayerErrorReason}.SCHEDULED_AHEAD_LIMIT and is backpressure rather than corruption: it is thrown without being recorded as the renderer's last error, so a caller can treat it as recoverable. The frame is closed before this call returns or throws, whichever happens, so a caller must never close it and a refusal never leaks. Both properties are load-bearing for a caller, such as the decode pipeline, that classifies the refusal from the thrown value. */ schedule(audioData) { // The decoded audio is consumed by this call whatever happens, so it is released even when the renderer refuses @@ -701,7 +701,10 @@ // the clock and one lead ahead otherwise. const prospectiveStart = hasScheduled && this.nextStartTime > now ? this.nextStartTime : now + MIN_SCHEDULE_LEAD_SECONDS; if (this.maxScheduledAheadSeconds !== null && prospectiveStart + wallDuration - now > this.maxScheduledAheadSeconds) - throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR, 'The schedule would run further ahead than the renderer allows.', { reason: 'scheduled-ahead-limit' })); + // The refusal is backpressure, not a failure: a caller that paces itself retries once the schedule has + // drained, so it is thrown without being recorded as the renderer's last error, which would mark a + // renderer that is still healthy as failed, contradicting the reason the shared enum publishes. + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR, 'The schedule would run further ahead than the renderer allows.', { reason: LuminaAudioPlayer.PlayerErrorReason.SCHEDULED_AHEAD_LIMIT }); let when = this.nextStartTime; // The chain is anchored on its first buffer, and re-anchored whenever it fell behind the context clock, which // is an underrun: the buffer starts as soon as it can and the playhead follows the audio that actually plays. @@ -970,6 +973,18 @@ return Math.max(0, this.nextStartTime - this.context.currentTime); } + /** + * Gets the scheduled ahead ceiling the renderer enforces, in seconds, or null when it enforces none. + * + * It is published so that a caller that paces itself, such as the decode pipeline, can keep its own ceiling + * strictly below it and never feed a frame the renderer would refuse. Keeping a decode ceiling above the renderer's + * is what makes the renderer refuse, and a refused frame is closed and lost. + * @returns {number|null} The ceiling, in seconds, or null when the renderer enforces none. + */ + getMaxScheduledAheadSeconds() { + return this.maxScheduledAheadSeconds; + } + /** * Checks whether the decode pipeline has stated that it fed the last decoded frame of the track. * @returns {boolean} True when the track is known to be complete. From c05978fac080957d5bd17e954b3cfa0516f59a44 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 16 Oct 2026 22:10:21 +0300 Subject: [PATCH 18/77] Adds the audio player container demuxers. --- .../Views/Shared/_ThemeLayoutScripts.cshtml | 7 + .../audio-player/audio-player-capabilities.js | 87 +- .../js/audio-player/audio-player-decode.js | 49 +- .../audio-player-demux-aac.js | 367 ++++++ .../audio-player-demux-capabilities.js | 363 ++++++ .../audio-player-demux-common.js | 1016 +++++++++++++++ .../audio-player-demux-flac.js | 1064 ++++++++++++++++ .../audio-player-demux-mp3.js | 443 +++++++ .../audio-player-demux-ogg.js | 1113 +++++++++++++++++ .../audio-player-demux-wav.js | 303 +++++ .../js/audio-player/audio-player-download.js | 26 +- .../js/audio-player/audio-player-errors.js | 19 +- .../js/audio-player/audio-player-events.js | 7 + .../js/audio-player/audio-player-utils.js | 53 +- 14 files changed, 4838 insertions(+), 79 deletions(-) create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-aac.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-common.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-flac.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-mp3.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-ogg.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-wav.js diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 02b961cb..67256666 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -71,5 +71,12 @@ + + + + + + + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js index 38e5b477..2614d8fe 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js @@ -22,19 +22,59 @@ }); /** - * The codec configurations probed with AudioDecoder.isConfigSupported, one per audio codec the demuxers of the player can recognize. - * Each entry is a representative configuration; the returned report says whether the browser can decode that codec at all. + * The representative decoder configuration of every audio codec the player supports, keyed by the canonical codec name + * a demuxer registers itself with. It is the single source of truth for those configurations: the capability report + * below probes them, and each demuxer registers its own descriptor with the entry for its codec, so the report and the + * per demuxer check can never silently disagree. + * @readonly + * @type {Object} + */ + LuminaAudioPlayer.AUDIO_CODEC_PROBES = Object.freeze({ + MP3: Object.freeze({ codec: 'mp3', sampleRate: 44100, numberOfChannels: 2 }), + FLAC: Object.freeze({ codec: 'flac', sampleRate: 44100, numberOfChannels: 2 }), + OPUS: Object.freeze({ codec: 'opus', sampleRate: 48000, numberOfChannels: 2 }), + AAC: Object.freeze({ codec: 'mp4a.40.2', sampleRate: 44100, numberOfChannels: 2 }), + VORBIS: Object.freeze({ codec: 'vorbis', sampleRate: 44100, numberOfChannels: 2 }), + PCM: Object.freeze({ codec: 'pcm-s16', sampleRate: 44100, numberOfChannels: 2 }) + }); + + /** + * The codec configurations probed with AudioDecoder.isConfigSupported, one per audio codec the demuxers of the player + * can recognize. It is derived from {@link LuminaAudioPlayer.AUDIO_CODEC_PROBES}, so the same configuration answers + * both this report and the per demuxer check. * @readonly * @type {ReadonlyArray<{ name: string, config: Object }>} */ - LuminaAudioPlayer.PROBED_AUDIO_CODECS = Object.freeze([ - Object.freeze({ name: 'mp3', config: Object.freeze({ codec: 'mp3', sampleRate: 44100, numberOfChannels: 2 }) }), - Object.freeze({ name: 'flac', config: Object.freeze({ codec: 'flac', sampleRate: 44100, numberOfChannels: 2 }) }), - Object.freeze({ name: 'opus', config: Object.freeze({ codec: 'opus', sampleRate: 48000, numberOfChannels: 2 }) }), - Object.freeze({ name: 'aac', config: Object.freeze({ codec: 'mp4a.40.2', sampleRate: 44100, numberOfChannels: 2 }) }), - Object.freeze({ name: 'vorbis', config: Object.freeze({ codec: 'vorbis', sampleRate: 44100, numberOfChannels: 2 }) }), - Object.freeze({ name: 'pcm', config: Object.freeze({ codec: 'pcm-s16', sampleRate: 44100, numberOfChannels: 2 }) }) - ]); + LuminaAudioPlayer.PROBED_AUDIO_CODECS = Object.freeze(Object.keys(LuminaAudioPlayer.AUDIO_CODEC_PROBES) + .map((name) => Object.freeze({ name: name.toLowerCase(), config: LuminaAudioPlayer.AUDIO_CODEC_PROBES[name] }))); + + /** + * Builds a stable fingerprint of the codec private data of a configuration, so that two configurations that differ + * only in their description bytes are never answered from the same cache entry. The decoder can depend on the + * description, because it overrides values of the configuration itself, for example the bit depth a FLAC STREAMINFO + * states or the channel count an OpusHead states, so the bytes matter and not merely whether they are present. + * @param {*} value - The description, as an ArrayBuffer, a view over one, or nothing. + * @returns {string} A fingerprint that combines the length and a 32 bit FNV-1a hash of the bytes. + */ + function fingerprintDescription(value) { + if (value === null || value === undefined) + return 'none'; + let bytes; + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) + bytes = new Uint8Array(value); + else if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value)) + bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + else + return 'unknown'; + let hash = 0x811c9dc5; + for (let index = 0; index < bytes.length; index++) { + hash ^= bytes[index]; + // 0x811c9dc5 is the FNV offset basis and 0x01000193 the FNV prime; the multiply is done modulo 2^32 by the + // unsigned shift, so the hash is a plain 32 bit value whatever the platform's number type. + hash = (hash * 0x01000193) >>> 0; + } + return `${bytes.length}:${hash.toString(16)}`; + } /** * Detects the browser capabilities the audio player relies on, and caches the result. @@ -50,6 +90,14 @@ this.report = null; /** @type {Promise|null} */ this.pendingReport = null; + /** + * The answers the browser already gave for a configuration, keyed by the shape of the configuration. The answer + * cannot change while the page lives, so it is memoized: enumerating many tracks, each with its own exact + * configuration, would otherwise be one browser round trip per track. The pending promise is cached rather than + * the settled value, so concurrent probes of the same configuration share one round trip. + * @type {Map>} + */ + this.configSupportCache = new Map(); } /** @@ -86,6 +134,25 @@ async supportsAudioConfigAsync(config) { if (!this.hasAudioDecoder()) return false; + // The key covers the whole configuration, including a fingerprint of the description bytes: the decoder can + // depend on them, so two configurations that differ only in their codec private data must not share an answer. + const key = config + ? `${config.codec}|${config.sampleRate}|${config.numberOfChannels}|${fingerprintDescription(config.description)}` + : String(config); + const cached = this.configSupportCache.get(key); + if (cached) + return await cached; + const probe = this.runAudioConfigProbeAsync(config); + this.configSupportCache.set(key, probe); + return await probe; + } + + /** + * Performs one configuration probe against the browser, without consulting the cache. + * @param {Object} config - An AudioDecoderConfig like value, with codec, sampleRate and numberOfChannels. + * @returns {Promise} True when the configuration is decodable, false otherwise or when it cannot be probed. + */ + async runAudioConfigProbeAsync(config) { try { const result = await this.window.AudioDecoder.isConfigSupported(config); // The isConfigSupported call resolves with a result object; a missing result and a false supported flag both diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js index 25f37265..cd6b41ff 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js @@ -216,16 +216,6 @@ return null; } - /** - * Checks whether a value is the AbortError a reset or a close rejects a pending flush with. An AbortError is tested - * by name rather than by type, because in a browser it is a DOMException, which is not an Error. - * @param {*} error - The value to check. - * @returns {boolean} True when the value is an AbortError. - */ - function isAbortError(error) { - return !!error && error.name === 'AbortError'; - } - /** * Checks whether a scheduler refused a frame because its own scheduled ahead ceiling is tighter than the decoder's. * That is backpressure, not corruption: the scheduler refused the frame before scheduling it, so the pipeline can keep @@ -255,41 +245,6 @@ return duration === null ? 0 : Math.max(0, duration) / 1000000; } - /** - * Merges two error detail objects into a new one, so that a details object a component owns is never mutated in place. - * @param {Object|null} base - The existing details. - * @param {Object|null} extra - The details to add. - * @returns {Object|null} The merged details, or null when both are absent. - */ - function mergeErrorDetails(base, extra) { - const hasBase = base !== null && base !== undefined; - const hasExtra = extra !== null && extra !== undefined; - if (!hasBase && !hasExtra) - return null; - if (!hasExtra) - return Object.assign({}, base); - if (!hasBase) - return Object.assign({}, extra); - return Object.assign({}, base, extra); - } - - /** - * Builds an error this decoder owns. A PlayerError raised by another component is copied rather than adopted, so its - * details are never mutated and the decoder failure never aliases the error the raising component keeps for itself. - * @param {*} error - The failure to own. - * @param {string} fallbackCode - The code to use when the failure is not already a player error. - * @param {Object|null} details - Optional details to merge in. - * @returns {LuminaAudioPlayer.PlayerError} The owned typed error. - */ - function toOwnedError(error, fallbackCode, details) { - if (error instanceof LuminaAudioPlayer.PlayerError) - return new LuminaAudioPlayer.PlayerError(error.code, error.message, mergeErrorDetails(error.details, details)); - const typed = LuminaAudioPlayer.PlayerError.from(error, fallbackCode); - if (!details) - return typed; - return new LuminaAudioPlayer.PlayerError(typed.code, typed.message, mergeErrorDetails(typed.details, details)); - } - /** * Creates the WebCodecs audio decoder of the player through the browser constructor. * @param {{ output: Function, error: Function }} handlers - The output and error callbacks the decoder is created with. @@ -608,7 +563,7 @@ } catch (error) { // A reset or a close interrupts a pending flush; that is a teardown of the decode pipeline, not a failure // of the track, so it is observed as a clean stop. - if (this.destroyed || this.error || isAbortError(error)) + if (this.destroyed || this.error || LuminaAudioPlayer.isAbortError(error)) return; throw this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: 'flush-failed' }); } @@ -1063,7 +1018,7 @@ return this.error; // The error is owned by this decoder: a PlayerError raised elsewhere is copied rather than adopted, so its // details are never mutated and getError never returns an object the raising component still holds. - const typed = toOwnedError(error, code, details); + const typed = LuminaAudioPlayer.toOwnedPlayerError(error, code, details); this.error = typed; this.clearCapacityTimer(); this.closeDecoder(); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-aac.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-aac.js new file mode 100644 index 00000000..e7828002 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-aac.js @@ -0,0 +1,367 @@ +/** + * AAC (ADTS) demuxer of the audio player. + * + * A raw AAC file is a stream of ADTS frames, each one a short header followed by one or more raw AAC data blocks. Unlike + * an MP3 frame the header does not state the bitrate: it states the length of the whole ADTS frame in bytes, which is + * what makes the frame directly addressable, together with the Audio Object Type, the sample rate index, the channel + * configuration and the number of raw data blocks the frame carries. This demuxer walks those frames and hands each one + * to the decoder as an encoded packet. + * + * Framing and the codec private data + * ---------------------------------- + * The WebCodecs AAC registration accepts either an ADTS streamed form, where each EncodedAudioChunk is a whole ADTS frame + * and no description is given, or a raw form, where each chunk is a raw AAC frame and the description is the + * AudioSpecificConfig. This demuxer uses the first, because the ADTS header is already the per frame configuration and + * carrying it in each frame means a frame can be decoded even after a seek that lands in the middle of the stream without + * re-deriving the AudioSpecificConfig. The configuration therefore carries the codec string, the sample rate and the + * channel count, and no description. + * + * Duration + * -------- + * An AAC frame decodes to 1024 samples per raw data block, and the number of raw data blocks is stated by the two bit + * field of the header, so the duration of a packet is 1024 times that count, divided by the sample rate. The total + * duration of the stream is not stated anywhere in an ADTS header, so it is estimated from the average byte rate of the + * frames read so far once the stream is past its beginning, and only once the end is reached is it exact. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The number of bytes of an ADTS header without the optional CRC. + * @readonly + * @type {number} + */ + const ADTS_HEADER_BYTES = 7; + + /** + * The number of bytes of an ADTS header with the optional CRC. + * @readonly + * @type {number} + */ + const ADTS_HEADER_CRC_BYTES = 9; + + /** + * The sample rates, in Hz, indexed by the four bit sample rate index of an AAC header. + * @readonly + * @type {Array} + */ + const SAMPLE_RATES = Object.freeze([96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]); + + /** + * The number of samples one raw AAC data block decodes to. + * @readonly + * @type {number} + */ + const SAMPLES_PER_BLOCK = 1024; + + /** + * The twelve bit ADTS frame sync, as the two byte prefix a scan matches on. The mask covers the top nibble of the + * second byte, so a scan rejects a byte pattern that is not a sync by a comparison instead of by an awaited header + * parse. + * @readonly + * @type {Array} + */ + const ADTS_SYNC_PREFIX = Object.freeze([0xFF, 0xF0]); + + /** + * The byte mask of {@link ADTS_SYNC_PREFIX}, matching the twelve bit sync exactly. + * @readonly + * @type {Array} + */ + const ADTS_SYNC_MASK = Object.freeze([0xFF, 0xF0]); + + /** + * The number of channels each channel configuration of an ADTS header names, indexed by its three bit value. Index 0 + * means the channels are described by a program configuration element, which this demuxer refuses, and index 7 is eight + * channels (7.1), not seven, so the raw value cannot be used as a channel count. + * @readonly + * @type {Array} + */ + const CHANNEL_CONFIGURATIONS = Object.freeze([0, 1, 2, 3, 4, 5, 6, 8]); + + /** + * Parses the header of an ADTS frame. + * @param {Uint8Array} bytes - The bytes to read the header from. + * @param {number} offset - The offset of the first header byte. + * @returns {Object|null} The parsed header, or null when the bytes are not a valid ADTS header. + */ + function parseAdtsHeader(bytes, offset) { + if (!bytes || offset < 0 || offset + ADTS_HEADER_BYTES > bytes.length) + return null; + // An ADTS header is a bit packed big endian structure. The fields this demuxer reads are laid out as: + // bytes 0-1: the twelve bit sync, then the MPEG version, two layer bits that are always zero, and the + // protection-absent flag that says whether a two byte CRC follows the header + // byte 2: the two bit Audio Object Type, the four bit sample rate index, and the top bit of the channel + // configuration + // byte 3: the low two bits of the channel configuration, then the top two bits of the frame length + // byte 4: the middle eight bits of the frame length + // byte 5: the low three bits of the frame length, then the buffer fullness + // byte 6: the two bit count of raw data blocks + // Every field below is extracted from that layout, which is why the shifts and masks cross byte boundaries. + if (bytes[offset] !== 0xFF || (bytes[offset + 1] & 0xF0) !== 0xF0) + return null; + // The layer field of an ADTS header is always zero; a non zero layer is a false sync. + if (((bytes[offset + 1] >> 1) & 0x03) !== 0) + return null; + const protectionAbsent = (bytes[offset + 1] & 0x01) === 1; + // The Audio Object Type is one more than the two bit field, and the raw data block count is one more than its + // two bit field, because both are stored biased by one. + const objectType = ((bytes[offset + 2] >> 6) & 0x03) + 1; + const sampleRateIndex = (bytes[offset + 2] >> 2) & 0x0F; + if (sampleRateIndex >= SAMPLE_RATES.length) + return null; + const channelConfiguration = ((bytes[offset + 2] & 0x01) << 2) | ((bytes[offset + 3] >> 6) & 0x03); + const frameLength = ((bytes[offset + 3] & 0x03) * 2048) + + (bytes[offset + 4] * 8) + + ((bytes[offset + 5] >> 5) & 0x07); + const headerBytes = protectionAbsent ? ADTS_HEADER_BYTES : ADTS_HEADER_CRC_BYTES; + if (frameLength < headerBytes) + return null; + const rawDataBlocks = (bytes[offset + 6] & 0x03) + 1; + return Object.freeze({ + objectType, + sampleRate: SAMPLE_RATES[sampleRateIndex], + sampleRateIndex, + channelConfiguration, + frameLength, + headerBytes, + rawDataBlocks + }); + } + + /** + * Demuxes an AAC stream that is framed as ADTS. + */ + class AacDemuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of AacDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.offset = 0; + this.dataStart = 0; + this.timelineMicros = 0; + /** @type {Object|null} */ + this.header = null; + this.durationSeconds = null; + this.reachedEnd = false; + // The first audio frame, the anchor the average byte rate is estimated from while the end of the stream is unknown. + this.firstFrameOffset = 0; + } + + //+======================================================================================+ + //| Initialization | + //+======================================================================================+ + + /** + * Skips an ID3v2 tag if the file carries one and positions the read cursor on the first ADTS frame. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not an ADTS stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + const dataStart = await this.skipId3v2Async(0); + const end = this.reader.getLength(); + const firstFrame = await LuminaAudioPlayer.scanForFrameAsync(this.reader, dataStart, end, ADTS_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: ADTS_SYNC_MASK }); + if (firstFrame < 0) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The bytes do not contain an ADTS frame.', { reason: 'no-adts-frame' }); + const header = await this.parseHeaderAtAsync(firstFrame); + if (!header) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The ADTS frame header could not be parsed.', { reason: 'no-adts-frame' }); + if (header.channelConfiguration === 0) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The AAC stream describes its channels in a program configuration this demuxer does not read.', { reason: 'unsupported-channel-config' }); + this.dataStart = firstFrame; + this.firstFrameOffset = firstFrame; + this.offset = firstFrame; + this.header = header; + this.durationSeconds = null; + this.timelineMicros = 0; + this.reachedEnd = false; + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.header) + return null; + return { + codec: `mp4a.40.${this.header.objectType}`, + sampleRate: this.header.sampleRate, + numberOfChannels: CHANNEL_CONFIGURATIONS[this.header.channelConfiguration] + }; + } + + /** + * Gets the best known duration of the stream, which is exact only once the last frame was read. + * @returns {number|null} The duration in seconds, or null when it is not known yet. + */ + getDuration() { + return this.durationSeconds; + } + + //+======================================================================================+ + //| Reading | + //+======================================================================================+ + + /** + * Reads the next ADTS frame as an encoded packet. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + if (this.reachedEnd) + return null; + try { + const header = await this.parseHeaderAtAsync(this.offset); + if (!header) + return await this.resyncAsync(); + const data = await this.reader.readAsync(this.offset, header.frameLength); + if (data.length < header.frameLength) { + this.reachedEnd = true; + this.updateEstimatedDuration(); + return null; + } + // The duration is kept unrounded while the timeline accumulates it, so that rounding it per packet does not + // make the timeline drift; only the packet the decoder receives carries a whole number of microseconds. + const duration = ((SAMPLES_PER_BLOCK * header.rawDataBlocks) / header.sampleRate) * 1000000; + const packet = LuminaAudioPlayer.createDemuxerPacket(data.slice(), this.timelineMicros, duration); + this.timelineMicros += duration; + this.offset += header.frameLength; + this.updateEstimatedDuration(); + return packet; + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Rescans for the next ADTS frame after a byte that is not the start of one. + * @returns {Promise} The next packet, or null when no further frame is found. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async resyncAsync() { + const end = this.reader.getLength(); + const next = await LuminaAudioPlayer.scanForFrameAsync(this.reader, this.offset + 1, end, ADTS_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: ADTS_SYNC_MASK }); + if (next < 0) { + this.reachedEnd = true; + this.updateEstimatedDuration(); + return null; + } + this.offset = next; + return await this.readPacketAsync(); + } + + /** + * Repositions the read cursor to the ADTS frame that covers a time. An ADTS stream has no seek table, so the + * byte position is estimated from the average byte rate of the frames read so far, and then scanned forward to + * the next real frame. A seek to the start is answered exactly even on a fresh demuxer, whose frames have not been + * walked yet, because the first frame is already known from initialization. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a frame gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const end = this.reader.getLength(); + if (end === null || !Number.isFinite(seconds) || seconds < 0) + return null; + if (seconds <= 0) { + this.offset = this.firstFrameOffset; + this.reachedEnd = false; + this.timelineMicros = 0; + return this.firstFrameOffset; + } + const elapsedBytes = this.offset - this.firstFrameOffset; + const elapsedMicros = this.timelineMicros; + if (elapsedBytes <= 0 || elapsedMicros <= 0) + return null; + const bytesPerSecond = elapsedBytes / (elapsedMicros / 1000000); + const estimate = this.firstFrameOffset + Math.floor(seconds * bytesPerSecond); + const start = Math.max(this.firstFrameOffset, Math.min(end - 1, estimate)); + const frame = await LuminaAudioPlayer.scanForFrameAsync(this.reader, start, end, ADTS_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: ADTS_SYNC_MASK }); + if (frame < 0) + return null; + this.offset = frame; + this.reachedEnd = false; + // The exact sample position of the frame is not known without walking the stream from its start, so the + // timeline is set to the requested time, which the seek stage uses as the target to trim the first packet to. + this.timelineMicros = Math.max(0, seconds) * 1000000; + return frame; + } + + //+======================================================================================+ + //| Internal helpers | + //+======================================================================================+ + + /** + * Reads the header of an ADTS frame at an offset. + * @param {number} offset - The offset of the frame. + * @returns {Promise} The parsed header, or null when the bytes are not a valid ADTS header. + */ + async parseHeaderAtAsync(offset) { + const bytes = await this.reader.readAsync(offset, ADTS_HEADER_BYTES); + if (bytes.length < ADTS_HEADER_BYTES) + return null; + return parseAdtsHeader(bytes, 0); + } + + /** + * Checks whether a candidate offset is the start of a real ADTS frame, by parsing its header and, when the next + * frame fits in the stream, by requiring it to parse with the same sample rate and channel configuration too. + * @param {number} offset - The candidate offset. + * @returns {Promise} True when the offset is the start of a real frame. + */ + async isValidFrameAtAsync(offset) { + const header = await this.parseHeaderAtAsync(offset); + if (!header) + return false; + const end = this.reader.getLength(); + const next = offset + header.frameLength; + if (end !== null && next + ADTS_HEADER_BYTES > end) + return true; + const nextHeader = await this.parseHeaderAtAsync(next); + if (!nextHeader) + return false; + return nextHeader.sampleRate === header.sampleRate + && nextHeader.channelConfiguration === header.channelConfiguration; + } + + /** + * Refreshes the estimated duration from the average byte rate of the frames read so far. It is exact only once + * the last frame was read, because an ADTS stream states no duration. + */ + updateEstimatedDuration() { + const bytes = this.offset - this.firstFrameOffset; + const micros = this.timelineMicros; + if (bytes <= 0 || micros <= 0) + return; + const end = this.reader.getLength(); + if (end === null) + return; + const remaining = end - this.firstFrameOffset; + const totalMicros = (remaining / bytes) * micros; + this.durationSeconds = totalMicros / 1000000; + } + } + + LuminaAudioPlayer.AacDemuxer = AacDemuxer; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.AAC, + codec: LuminaAudioPlayer.DemuxerCodec.AAC, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.AAC, + create: (options) => new AacDemuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js new file mode 100644 index 00000000..9b8f3321 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js @@ -0,0 +1,363 @@ +/** + * Demux capability module of the audio player. + * + * The server decides, before any audio is fetched, whether a track is a direct play or has to be normalized (remuxed or + * transcoded), from the container and the codec the player advertises. This module produces that advertisement from the + * demuxers that loaded and the codecs the browser can decode, and it resolves the two halves of the client side of the + * same decision: which demuxer handles the container and codec of a track, and whether the browser can decode the codec + * it produces. + * + * Matching a manifest to a demuxer + * -------------------------------- + * The manifest carries the container and the codec of the stored audio as free form descriptions taken from the probe + * result, so they are canonicalized here exactly as the server canonicalizes them, and matched against the demuxer + * registry. A pair no registered demuxer handles is a track the bundled player cannot play directly. + * + * Verifying with the browser + * -------------------------- + * A demuxer existing for a format is not proof that the browser can decode it: the codec may be missing from this + * browser, or the codec might be refused for the sample rate or channel count of the track. Two checks are therefore + * offered, in increasing cost and precision: + * - a cheap check against a representative configuration of the codec, which answers whether the browser can decode + * that codec at all, using the same probes the capability detector already runs; + * - a full check against the real configuration the demuxer extracted from the file, which is exact but requires the + * header of the track to have been read already. + * The convenience factories below use the full check when they initialize the demuxer, and fall back to a clear + * 'needs normalization' event whenever a demuxer is missing, the bytes cannot be parsed, or the browser refuses the + * configuration, so a consumer can ask the server to normalize the track instead of failing. + * + * Advertising capabilities + * ------------------------ + * The 'capabilities' query parameter of the manifest request is documented as the container and codec pairs the player can + * demux and decode, so the advertisement is filtered by the cheap browser check, and a codec this browser cannot decode is + * never advertised. Advertising it would make the server mark such a track a direct play, and the client would discover + * the gap only after fetching the manifest and would have to normalize in a second round trip. The unfiltered, demux only + * set is available for a caller with no detector, and it is what the server already assumes when it applies its default. + * + * The needs normalization event + * ----------------------------- + * It is published on the player event bus as {@link LuminaAudioPlayer.PlayerEvent.NEEDS_NORMALIZATION}, with the payload + * { container, codec, reason }, plus directPlay when the caller supplied it, where the reason is one of the + * {@link LuminaAudioPlayer.PlayerErrorReason} values NO_DEMUXER, CODEC_UNSUPPORTED or DEMUXER_FAILED. A consumer that + * asked for a normalized delivery uses it to request one. A normalized manifest, whose directPlay flag is false, is + * refused by {@link LuminaAudioPlayer.createDemuxerForManifest} without an event, because the server already normalized + * such a track on purpose and its stream is not in the stored container. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Resolves the demuxer descriptors, the browser capabilities and the event bus a capability module works with. Only + * the registry has a process wide default, because it is the one collaborator whose contents are the registry itself; + * the capability detector and the event bus are injected by the caller, like every other collaborator of the player, + * so that this module never reaches into a running player whose instance comes and goes. + * @param {Object} [options] - The options to resolve from. + * @returns {Object} The resolved registry, capabilities and events. + */ + function resolveDependencies(options = {}) { + const settings = options || {}; + return { + registry: settings.registry || LuminaAudioPlayer.demuxerRegistry, + capabilities: settings.capabilities || null, + events: settings.events || null + }; + } + + /** + * Requires an injected collaborator, failing loudly rather than silently degrading when it is missing. + * @param {*} value - The collaborator to check. + * @param {string} name - The name of the collaborator, for the message. + * @returns {*} The collaborator. + * @throws {TypeError} When the collaborator was not injected. + */ + function requireInjected(value, name) { + if (!value) + throw new TypeError(`The demux capability resolver requires an injected ${name}.`); + return value; + } + + /** + * Publishes the need for a normalized delivery on the event bus. + * @param {Object} events - The event bus. + * @param {string} container - The canonical container of the track. + * @param {string} codec - The canonical codec of the track. + * @param {string} reason - One of the {@link LuminaAudioPlayer.PlayerErrorReason} values. + * @param {boolean} [directPlay] - The direct play flag of the manifest, when the caller has one. + */ + function publishNeedsNormalization(events, container, codec, reason, directPlay) { + if (!events || !LuminaAudioPlayer.PlayerEvent || typeof events.emit !== 'function') + return; + const payload = { + container: LuminaAudioPlayer.canonicalizeDemuxerContainer(container), + codec: LuminaAudioPlayer.canonicalizeDemuxerCodec(codec), + reason + }; + // The direct play flag is carried only when the caller supplied it: an omitted flag means the caller does not + // know, which is not the same as a false flag, the documented signal that the server already normalized the + // track. Coercing an omitted flag to false would make every caller that has no manifest look like one whose + // track the server chose to normalize. + if (directPlay !== undefined) + payload.directPlay = directPlay === true; + events.emit(LuminaAudioPlayer.PlayerEvent.NEEDS_NORMALIZATION, Object.freeze(payload)); + } + + /** + * Detects the demuxers the bundled player loaded and the browser configurations it can decode, and answers whether a track can be played directly. + */ + class DemuxerCapabilities { + /** + * Creates an instance of DemuxerCapabilities. + * @param {Object} [options] - The options. + * @param {LuminaAudioPlayer.DemuxerRegistry} [options.registry] - The demuxer registry. Defaults to the process wide registry, the one collaborator that is not injected. + * @param {LuminaAudioPlayer.PlayerCapabilities} [options.capabilities] - The browser capability detector, injected by the caller. A method that probes without it fails loudly. + * @param {Object} [options.events] - The player event bus, injected by the caller. + */ + constructor(options = {}) { + const resolved = resolveDependencies(options); + this.registry = resolved.registry; + this.capabilities = resolved.capabilities; + this.events = resolved.events; + } + + /** + * Finds the demuxer descriptor of a container and codec pair. + * @param {string} container - The container of the track, in any casing or as a free form description. + * @param {string} codec - The codec of the track, in any casing or as a free form description. + * @returns {Object|null} The descriptor, or null when no demuxer handles the pair. + */ + match(container, codec) { + return this.registry ? this.registry.find(container, codec) : null; + } + + /** + * Finds the demuxer descriptor of the stored format of a playback manifest. + * @param {Object} manifest - The playback manifest. + * @returns {Object|null} The descriptor, or null when no demuxer handles the stored format. + */ + matchManifest(manifest) { + if (!manifest) + return null; + return this.match(manifest.sourceContainer, manifest.sourceCodec); + } + + /** + * Asks the browser whether it can decode a codec at all, through the representative probe the descriptor carries. + * It is the cheap check, usable before any byte of the track is read. The probe is read from the descriptor rather + * than looked up by name, so the check never depends on a demuxer being named in the registry. + * @param {Object} descriptor - A demuxer descriptor. + * @returns {Promise} True when the browser can decode the codec. + * @throws {TypeError} When no capability detector was injected. + */ + async isCodecSupportedAsync(descriptor) { + if (!descriptor) + return false; + const capabilities = requireInjected(this.capabilities, 'capability detector'); + return await capabilities.supportsAudioConfigAsync(descriptor.probe); + } + + /** + * Asks the browser whether it can decode the exact configuration a demuxer extracted from a track. It is the + * exact check, usable once the demuxer was initialized. + * @param {Object} configuration - A configuration, per {@link LuminaAudioPlayer.Demuxer#getConfiguration}. + * @returns {Promise} True when the browser can decode the configuration. + * @throws {TypeError} When no capability detector was injected. + */ + async isConfigurationSupportedAsync(configuration) { + if (!configuration) + return false; + const capabilities = requireInjected(this.capabilities, 'capability detector'); + return await capabilities.supportsAudioConfigAsync(configuration); + } + + /** + * Resolves whether a track can be played directly, using the cheap representative check. It publishes the needs + * normalization event and resolves false when no demuxer handles the format or the browser cannot decode it. The + * event carries the reason the caller acts on, so the event bus is required rather than optional: a missing bus + * would silently drop the only signal that says which delivery to request. + * @param {string} container - The container of the track. + * @param {string} codec - The codec of the track. + * @param {boolean} [directPlay] - The direct play flag of the manifest, carried into the event. + * @returns {Promise} True when a demuxer exists and the browser can decode the codec. + * @throws {TypeError} When no capability detector or no event bus was injected. It is a composition error, not a + * property of the track, so it rejects rather than classifying the track. + */ + async canPlayDirectlyAsync(container, codec, directPlay) { + const events = requireInjected(this.events, 'event bus'); + const descriptor = this.match(container, codec); + if (!descriptor) { + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, directPlay); + return false; + } + if (!await this.isCodecSupportedAsync(descriptor)) { + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, directPlay); + return false; + } + return true; + } + + /** + * Resolves whether the stored format of a manifest can be played directly. + * @param {Object} manifest - The playback manifest. + * @returns {Promise} True when a demuxer exists and the browser can decode the codec. + * @throws {TypeError} When no capability detector or no event bus was injected. + */ + async canPlayManifestDirectlyAsync(manifest) { + if (!manifest) + return false; + return await this.canPlayDirectlyAsync(manifest.sourceContainer, manifest.sourceCodec, manifest.directPlay); + } + + /** + * Builds the value of the 'capabilities' query parameter of the manifest request from the demuxers that loaded, + * without consulting the browser. It is the set the player can demux, which is what the server already assumes + * when it applies its own default; a caller that needs the set the player can also decode uses + * {@link LuminaAudioPlayer.DemuxerCapabilities#describeFormatsAsync}. + * @returns {string} A comma separated list of container/codec pairs. + */ + describeFormats() { + if (!this.registry) + return ''; + return this.registry.getDescriptors() + .map((descriptor) => `${descriptor.container.toLowerCase()}/${descriptor.codec.toLowerCase()}`) + .join(','); + } + + /** + * Builds the value of the 'capabilities' query parameter of the manifest request from the demuxers whose codec the + * browser can actually decode. The parameter is documented as the pairs the player can demux and decode, so a + * codec the browser cannot decode must not be promised to the server: otherwise the server marks such a track a + * direct play, and the client only discovers the gap after fetching the manifest and has to normalize in a second + * round trip. With the memoizing capability detector, this is one probe per codec, once. + * @returns {Promise} A promise resolving to a comma separated list of container/codec pairs. + * @throws {TypeError} When no capability detector was injected. + */ + async describeFormatsAsync() { + const capabilities = requireInjected(this.capabilities, 'capability detector'); + if (!this.registry) + return ''; + const pairs = []; + for (const descriptor of this.registry.getDescriptors()) { + if (await capabilities.supportsAudioConfigAsync(descriptor.probe)) + pairs.push(`${descriptor.container.toLowerCase()}/${descriptor.codec.toLowerCase()}`); + } + return pairs.join(','); + } + } + + LuminaAudioPlayer.DemuxerCapabilities = DemuxerCapabilities; + + /** + * Creates a demux capability resolver. See {@link LuminaAudioPlayer.DemuxerCapabilities} for the options. + * @param {Object} [options] - The options. + * @returns {LuminaAudioPlayer.DemuxerCapabilities} The resolver. + */ + LuminaAudioPlayer.createDemuxerCapabilities = function (options) { + return new DemuxerCapabilities(options); + }; + + /** + * Creates and verifies the demuxer of a container and codec pair. + * + * It resolves the demuxer, initializes it, and asks the browser whether it can decode the exact configuration the + * demuxer extracted. A failure to parse the bytes or to decode the codec is an expected negotiation outcome, not a + * playback failure, so the demuxer is created as a probe with the caller's error callback detached and that callback + * is attached only once the demuxer proved usable. Anything that makes the pair unplayable (no demuxer, unparseable + * bytes, or a codec the browser refuses) resolves to null and publishes a needs normalization event, so a caller can + * request a normalized delivery instead of failing, and never receives both a player failure and a normalization + * request for the same unplayable file. + * + * The one failure that resolves to null without publishing is an intentional download stop: a teardown that crossed + * the header probe is not a track the server has to normalize. A caller that must tell the two nulls apart therefore + * checks whether it received a needs normalization event, or its own teardown state, rather than the null itself. + * @param {string} container - The container of the track. + * @param {string} codec - The codec of the track. + * @param {Object} [options] - The demuxer options, plus the injected capabilities and events, per {@link LuminaAudioPlayer.DemuxerCapabilities}. + * @returns {Promise} The ready demuxer, or null when the pair must be normalized. + * @throws {TypeError} When no event bus was injected. It is a composition error, not a property of the track, so it + * rejects rather than resolving to a null the caller would have to classify without an event to classify it by. + */ + LuminaAudioPlayer.createDemuxerFor = async function (container, codec, options) { + const settings = options || {}; + const dependencies = resolveDependencies(settings); + // The event bus is required rather than optional, because a caller tells a track that must be normalized from an + // intentional teardown by whether a needs normalization event arrived, and a missing bus would silently drop that + // only signal and make the two nulls indistinguishable. + const events = requireInjected(dependencies.events, 'event bus'); + const descriptor = dependencies.registry ? dependencies.registry.find(container, codec) : null; + if (!descriptor) { + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, settings.directPlay); + return null; + } + let demuxer = null; + try { + demuxer = descriptor.create(Object.assign({}, settings, { onError: null })); + await demuxer.initializeAsync(); + } catch (error) { + console.debug('Audio player: the demuxer of the track failed to initialize.', error); + if (demuxer && typeof demuxer.destroyAsync === 'function') + await demuxer.destroyAsync(); + // An intentional download stop, a teardown that crossed the header probe, is not a track the server has to + // normalize, so it is not published as one; the demuxer already reports it as a normal stop everywhere else. + if (!LuminaAudioPlayer.isDownloadAbort(error)) + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.DEMUXER_FAILED, settings.directPlay); + return null; + } + const configuration = demuxer.getConfiguration(); + let isConfigurationSupported = false; + try { + const resolver = new DemuxerCapabilities(dependencies); + isConfigurationSupported = await resolver.isConfigurationSupportedAsync(configuration); + } catch (error) { + // A wiring failure (a missing injected capability detector) is not a property of the track, so the just built + // demuxer is released and the failure is propagated, never swallowed as a normalization request. + await demuxer.destroyAsync(); + throw error; + } + if (!isConfigurationSupported) { + await demuxer.destroyAsync(); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, settings.directPlay); + return null; + } + // The demuxer is usable, so the caller's error callback is attached from here on: a failure while reading is a + // playback failure and reaches it, while a failure during the probe above never did. + demuxer.onError = typeof settings.onError === 'function' ? settings.onError : null; + return demuxer; + }; + + /** + * Creates and verifies the demuxer of the stored format of a direct play manifest. It uses the source container and + * codec, because that is the format the capability negotiation is about. Only a direct play manifest has its stored + * format as its stream: a manifest whose direct play flag is false describes a delivery in a different container, so + * resolving its stored format would build a demuxer for the wrong bytes, and the failure to initialize it would + * publish a normalization request for a track the server already normalized, a normalization loop. Such a manifest + * therefore resolves to null here, silently, and a caller that has one runs the normalized pipeline instead. + * @param {Object} manifest - The playback manifest. + * @param {Object} [options] - The demuxer options, per {@link LuminaAudioPlayer.createDemuxerFor}. + * @returns {Promise} The ready demuxer, or null for a manifest that is not a direct play, or one that must be normalized. + */ + LuminaAudioPlayer.createDemuxerForManifest = function (manifest, options) { + if (!manifest || manifest.directPlay !== true) + return Promise.resolve(null); + return LuminaAudioPlayer.createDemuxerFor(manifest.sourceContainer, manifest.sourceCodec, Object.assign({}, options, { directPlay: true })); + }; + + /** + * Builds the value of the 'capabilities' query parameter of the manifest request from the process wide registry, + * without consulting the browser. See {@link LuminaAudioPlayer.describeDemuxerFormatsAsync} for the decode aware set. + * @returns {string} A comma separated list of container/codec pairs. + */ + LuminaAudioPlayer.describeDemuxerFormats = function () { + return new DemuxerCapabilities().describeFormats(); + }; + + /** + * Builds the value of the 'capabilities' query parameter of the manifest request from the process wide registry, + * keeping only the pairs whose codec the browser can decode, which is the set the parameter is documented to carry. + * @param {Object} [options] - The options, with the injected capability detector and event bus, per {@link LuminaAudioPlayer.DemuxerCapabilities}. + * @returns {Promise} A promise resolving to a comma separated list of container/codec pairs. + * @throws {TypeError} When no capability detector was injected. + */ + LuminaAudioPlayer.describeDemuxerFormatsAsync = function (options) { + return new DemuxerCapabilities(options).describeFormatsAsync(); + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-common.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-common.js new file mode 100644 index 00000000..abac5067 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-common.js @@ -0,0 +1,1016 @@ +/** + * Common foundation of the audio player demuxers. + * + * WebCodecs cannot decode a file: an AudioDecoder consumes a configuration (a codec, a sample rate, a channel count and + * the codec private data the container carries) and a stream of EncodedAudioChunk objects. Something must therefore parse + * the bytes the download engine brings in, recognize the container, extract that configuration and split the audio into + * packets, each with a presentation timestamp and a duration in microseconds. That is what a demuxer does, and this + * module holds everything the per format demuxers (MP3, AAC/ADTS, FLAC, OGG and WAV) share, so that each one only + * implements its own container grammar. + * + * What lives here + * --------------- + * - The canonical names of the containers and codecs the bundled player supports, and the canonicalizers that map the + * free form descriptions the probe stores to those names. Both canonicalizers mirror the server on the same values + * (containers by trimming and upper casing, as PlaybackFormatService.CanonicalizeContainer does; codecs by the + * distinctive token of the description, as CanonicalizeCodec does), so the two sides agree on what a track holds and + * on which tracks are a direct play. Neither adds an alias the server does not, because a container the server's + * direct-play gate would reject must not resolve a demuxer here. + * - A byte source adapter that turns the range downloading TrackDownloader of the download engine into a flat, + * random access byte source that answers a read at an absolute offset and reports end of file instead of rejecting. + * - A windowing reader over that source, which keeps one read ahead window so that a parser that walks byte by byte + * does not issue one request per byte. + * - A bit reader for the big endian bitstream headers of MPEG, FLAC and OGG. + * - The packet factory, so every demuxer emits the same frozen packet shape the decode pipeline consumes. + * - The base class of a demuxer, which owns the reader, the recorded failure and the error callback, and the demuxer + * registry the format modules register themselves into. + * + * The demuxer contract + * -------------------- + * Every demuxer (audio-player-demux-mp3.js and its siblings) exposes: + * - initializeAsync(): reads the header(s) of the stream and prepares getConfiguration(); resolves when the stream is + * ready to be read, and rejects with a typed error when the bytes are not a stream of this format. + * - getConfiguration(): the AudioDecoderConfig like value { codec, sampleRate, numberOfChannels, description? } after + * initializeAsync resolved, and null before that. + * - readPacketAsync(): the next encoded packet as { data, timestamp, duration, type }, where the timestamp and the + * duration are in microseconds, or null once the stream ended. It is incremental: it reads only the bytes of the + * packet it returns, never the whole file. + * - getDuration(): the duration of the whole stream in seconds, and null when no demuxer of the format can state one. A + * format whose duration only becomes exact once the whole stream is read (AAC, OGG) returns a progressive estimate in + * the meantime, so a caller must treat a non null value as an estimate that may still be refined, not as a final one. + * - seekToTimeAsync(seconds): repositions the read cursor to a packet boundary at or before the given time, so that the + * next readPacketAsync returns the packet that covers it. It returns the byte offset it repositioned to, or null when + * the format cannot be repositioned by time. How the first packet after a seek is trimmed to the exact target is the + * concern of the seek stage, not of the demuxer. + * - destroyAsync(): releases every resource, including the reader. + * + * A demuxer is a sub component, like the download engine and the decoder: it never moves the player state machine and + * never emits on the event bus itself. A failure it cannot recover from is recorded on the instance for polling through + * getError, is reported to the onError callback as a {@link LuminaAudioPlayer.PlayerError} with the DEMUX_FAILED code, and + * makes the awaited calls (initializeAsync, readPacketAsync, seekToTimeAsync) reject with that same error. An engine must + * forward onError to host.reportError, exactly as it forwards the download engine's and the decoder's, so the failure + * reaches the player. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The size, in bytes, of the read ahead window the reader keeps. It is large enough that a parser walking a frame + * header byte by byte issues one read per window rather than one per byte, and small enough to stay cheap to hold. + * @readonly + * @type {number} + */ + const WINDOW_SIZE_BYTES = 65536; + + /** + * The largest number of bytes a single read may ask for. It bounds the window a malformed stream can make the reader + * allocate, so a corrupt length field can never turn a read into an unbounded allocation. + * @readonly + * @type {number} + */ + const MAX_READ_BYTES = 16 * 1024 * 1024; + + /** + * The size, in bytes, of a scan chunk. A scan for the next frame of a format reads at most this many bytes at a time. + * @readonly + * @type {number} + */ + const SCAN_CHUNK_BYTES = 65536; + + /** + * Enum-like object for the canonical names of the containers the bundled player demuxes. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.DemuxerContainer = Object.freeze({ + MP3: 'MP3', + AAC: 'AAC', + OGG: 'OGG', + FLAC: 'FLAC', + WAV: 'WAV' + }); + + /** + * Enum-like object for the canonical names of the codecs the bundled player decodes. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.DemuxerCodec = Object.freeze({ + MP3: 'MP3', + AAC: 'AAC', + OPUS: 'OPUS', + VORBIS: 'VORBIS', + FLAC: 'FLAC', + PCM: 'PCM' + }); + + /** + * Canonicalizes the container of an audio file by trimming and upper casing it, exactly as the server canonicalizes + * the container of the same probe result. It deliberately adds no aliases: a container the server's direct-play gate + * would not match against the advertised set must not resolve a demuxer here either, so the two sides agree on which + * tracks are a direct play. Keeping the mapping identical to the server's is what makes a rename on either side a + * matching change rather than a client that plays a track the server decided to remux. + * @param {string|null|undefined} container - The container to canonicalize. + * @returns {string} The canonical container, or an empty string when there is none. + */ + function canonicalizeContainer(container) { + if (typeof container !== 'string') + return ''; + return container.trim().toUpperCase(); + } + + /** + * Canonicalizes the codec of an audio file, mapping the free form descriptions the probe reports to the canonical codec + * names the player advertises. It mirrors the mapping of the server, so that the demuxer the player selects for a track + * is the one the server expected when it decided the delivery. The most specific tokens are matched first, and the MPEG + * layer is matched by its layer number only, so 'MPEG-1 Layer 2' is not mistaken for an MP3. + * @param {string|null|undefined} codec - The codec to canonicalize. + * @returns {string} The canonical codec, or an empty string when there is none. + */ + function canonicalizeCodec(codec) { + if (typeof codec !== 'string') + return ''; + const normalized = codec.trim().toUpperCase(); + if (normalized === '') + return ''; + if (normalized.includes('VORBIS')) + return 'VORBIS'; + if (normalized.includes('OPUS')) + return 'OPUS'; + if (normalized.includes('FLAC')) + return 'FLAC'; + if (normalized.includes('ALAC') || normalized.includes('APPLE LOSSLESS')) + return 'ALAC'; + if (normalized.includes('AAC')) + return 'AAC'; + if (normalized.includes('MP3') || normalized.includes('LAYER 3') || normalized.includes('LAYER III')) + return 'MP3'; + if (normalized.includes('PCM') || normalized.includes('UNCOMPRESSED') || normalized.includes('LINEAR')) + return 'PCM'; + if (normalized.includes('WINDOWS MEDIA') || normalized.includes('WMA')) + return 'WMA'; + return normalized; + } + + LuminaAudioPlayer.canonicalizeDemuxerContainer = canonicalizeContainer; + LuminaAudioPlayer.canonicalizeDemuxerCodec = canonicalizeCodec; + + /** + * Converts a count of samples to microseconds at a sample rate, the unit of every packet timestamp of the player. + * @param {number} samples - The number of samples. + * @param {number} sampleRate - The sample rate, in Hz. + * @returns {number} The duration, in microseconds, rounded to the nearest microsecond. + */ + function samplesToMicroseconds(samples, sampleRate) { + if (!Number.isFinite(samples) || !Number.isFinite(sampleRate) || sampleRate <= 0 || samples <= 0) + return 0; + return Math.round((samples / sampleRate) * 1000000); + } + + LuminaAudioPlayer.samplesToMicroseconds = samplesToMicroseconds; + + /** + * Checks whether a run of bytes at an offset spells out an ASCII string. It is the check every magic number of a + * container is recognized by. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the run. + * @param {string} text - The expected ASCII text. + * @returns {boolean} True when the bytes spell out the text at the offset. + */ + function bytesEqualAscii(bytes, offset, text) { + if (!bytes || offset < 0 || offset + text.length > bytes.length) + return false; + for (let index = 0; index < text.length; index++) + if (bytes[offset + index] !== text.charCodeAt(index)) + return false; + return true; + } + + /** + * Reads an unsigned integer from a run of bytes in big endian order. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the integer. + * @param {number} length - The number of bytes of the integer, between 1 and 6. + * @returns {number|null} The value, or null when the run is truncated. + */ + function readUintBE(bytes, offset, length) { + if (!bytes || offset < 0 || offset + length > bytes.length || length < 1 || length > 6) + return null; + let value = 0; + for (let index = 0; index < length; index++) + value = value * 256 + bytes[offset + index]; + return value; + } + + /** + * Reads an unsigned integer from a run of bytes in little endian order. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the integer. + * @param {number} length - The number of bytes of the integer, between 1 and 6. + * @returns {number|null} The value, or null when the run is truncated. + */ + function readUintLE(bytes, offset, length) { + if (!bytes || offset < 0 || offset + length > bytes.length || length < 1 || length > 6) + return null; + let value = 0; + let factor = 1; + for (let index = 0; index < length; index++) { + value += bytes[offset + index] * factor; + factor *= 256; + } + return value; + } + + /** + * Reads a signed integer from a run of bytes in little endian order, two's complement. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the integer. + * @param {number} length - The number of bytes of the integer, between 1 and 4. + * @returns {number|null} The value, or null when the run is truncated. + */ + function readIntLE(bytes, offset, length) { + const value = readUintLE(bytes, offset, length); + if (value === null) + return null; + const limit = Math.pow(2, 8 * length); + return value >= limit / 2 ? value - limit : value; + } + + LuminaAudioPlayer.demuxReadUintBE = readUintBE; + LuminaAudioPlayer.demuxReadUintLE = readUintLE; + LuminaAudioPlayer.demuxReadIntLE = readIntLE; + LuminaAudioPlayer.demuxBytesEqualAscii = bytesEqualAscii; + + /** + * Reads a little endian signed 64 bit integer from a run of bytes, used by the granule position of an OGG page. The + * value is built from two 32 bit halves so that it stays exact for every granule a real stream can carry. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the integer. + * @returns {number|null} The value, or null when the run is truncated. + */ + function readInt64LE(bytes, offset) { + const low = readUintLE(bytes, offset, 4); + const high = readIntLE(bytes, offset + 4, 4); + if (low === null || high === null) + return null; + // A granule position is a signed 64 bit value; a page that has not completed a packet carries -1, and the two + // halves are combined without a bitwise shift, which would truncate to 32 bits. This is exact, because a granule + // is a sample count that never approaches the 2^53 range a double can represent. + return high * 4294967296 + low; + } + + LuminaAudioPlayer.demuxReadInt64LE = readInt64LE; + + /** + * Reads a big endian sync safe integer, the size encoding an ID3v2 tag uses, where the top bit of each of its four + * bytes is zero. It is shared by the MP3 and AAC demuxers, which may both carry a leading ID3v2 tag. + * @param {Uint8Array} bytes - The bytes to read from. + * @param {number} offset - The offset of the first size byte. + * @returns {number} The value. + */ + function readSyncSafe(bytes, offset) { + // Each byte contributes seven bits, so the multipliers are 128, 128 squared and 128 cubed, and the top bit of + // every byte is masked off. + return ((bytes[offset] & 0x7F) * 2097152) + + ((bytes[offset + 1] & 0x7F) * 16384) + + ((bytes[offset + 2] & 0x7F) * 128) + + (bytes[offset + 3] & 0x7F); + } + + LuminaAudioPlayer.demuxReadSyncSafe = readSyncSafe; + + /** + * Builds the byte-at-a-time lookup table of a non-reflected CRC, so that a checksum over a run of bytes costs one + * table lookup and one shift per byte instead of one iteration per bit. The checksum it produces is identical to the + * bit-by-bit form, because it is the same polynomial, initial value and bit order, only evaluated a byte at a time. + * @param {number} polynomial - The CRC polynomial, without its leading term (0x04C11DB7, 0x8005, 0x07, ...). + * @param {number} width - The width of the checksum in bits: 8, 16 or 32. + * @returns {Uint32Array} The 256 entry table, indexed by byte value. + */ + function buildCrcTable(polynomial, width) { + const table = new Uint32Array(256); + const mask = width === 32 ? 0xFFFFFFFF : (1 << width) - 1; + const topBit = 1 << (width - 1); + for (let index = 0; index < 256; index++) { + let crc = (index << (width - 8)) & mask; + for (let bit = 0; bit < 8; bit++) + crc = (crc & topBit) !== 0 ? ((crc << 1) ^ polynomial) & mask : (crc << 1) & mask; + table[index] = crc >>> 0; + } + return table; + } + + LuminaAudioPlayer.demuxBuildCrcTable = buildCrcTable; + + /** + * A bit reader over a run of big endian bytes, for the bit packed headers of MPEG, FLAC and OGG. + */ + class DemuxerBitReader { + /** + * Creates an instance of DemuxerBitReader. + * @param {Uint8Array} bytes - The bytes to read from. + */ + constructor(bytes) { + this.bytes = bytes instanceof Uint8Array ? bytes : new Uint8Array(0); + this.bitPosition = 0; + } + + /** + * Reads an unsigned integer of up to 53 bits. The accumulation is done in floating point, so the value is exact up + * to 2^53, which covers every field a container header holds, including the 36 bit total sample count of FLAC. + * @param {number} count - The number of bits to read, up to 53. + * @returns {number} The value. + * @throws {RangeError} When the bytes end before the requested bits are read. + */ + readBits(count) { + let value = 0; + for (let index = 0; index < count; index++) { + const byteIndex = this.bitPosition >> 3; + if (byteIndex >= this.bytes.length) + throw new RangeError('The demuxer bit reader ran past the end of its bytes.'); + const shift = 7 - (this.bitPosition & 7); + value = value * 2 + ((this.bytes[byteIndex] >> shift) & 1); + this.bitPosition++; + } + return value; + } + + /** + * Gets the number of whole bytes consumed so far. + * @returns {number} The byte position. + */ + getBytePosition() { + return this.bitPosition >> 3; + } + } + + LuminaAudioPlayer.DemuxerBitReader = DemuxerBitReader; + + /** + * A random access byte source that answers a read at an absolute offset and reports end of file as a short read + * instead of a failure. The demuxers read through this interface, so a test injects a plain in memory implementation + * and never a downloader. + */ + class DemuxerByteSource { + /** + * Creates an instance of DemuxerByteSource over a range downloading downloader. + * @param {Object} downloader - The TrackDownloader of the download engine, with readBytesAsync, getTotalBytes, getRanges, isComplete and getError. + */ + constructor(downloader) { + this.downloader = downloader; + } + + /** + * Gets the total size of the stream, when the download already discovered it. + * @returns {number|null} The length in bytes, or null when it is not known yet. + */ + getLength() { + const total = this.downloader && this.downloader.getTotalBytes ? this.downloader.getTotalBytes() : null; + return Number.isInteger(total) && total >= 0 ? total : null; + } + + /** + * Reads a window of bytes at an absolute offset, waiting for it when the download has not fetched it yet. A window + * that reaches past the end of the file is shortened, and a window entirely past it reads as empty, so a parser + * sees end of file as a short read. + * @param {number} offset - The first byte of the window. + * @param {number} length - The number of bytes of the window. + * @returns {Promise} The bytes, possibly fewer than requested at the end of the stream. + */ + async readAsync(offset, length) { + const start = Math.max(0, Math.floor(offset)); + let size = Math.max(0, Math.floor(length)); + if (size === 0) + return new Uint8Array(0); + const total = this.getLength(); + if (total !== null) { + if (start >= total) + return new Uint8Array(0); + size = Math.min(size, total - start); + } + try { + const bytes = await this.downloader.readBytesAsync(start, size); + return bytes && bytes.length > 0 ? bytes.subarray(0, size) : new Uint8Array(0); + } catch (error) { + // The read rejects when the window can no longer be filled. That is end of file when the window simply + // reaches past the last downloaded byte and the download has drained: the bytes that are there are still + // returned, and only the tail is shortened. + if (!isWindowUnavailableError(error)) + throw error; + const coveredEnd = this.getCoveredEnd(start); + if (coveredEnd > start) { + const available = Math.min(size, coveredEnd - start); + const bytes = await this.downloader.readBytesAsync(start, available); + return bytes && bytes.length > 0 ? bytes.subarray(0, available) : new Uint8Array(0); + } + return new Uint8Array(0); + } + } + + /** + * Gets the end of the contiguous run of downloaded bytes that covers an offset. + * @param {number} offset - The offset to look up. + * @returns {number} The exclusive end of the covering run, or the offset itself when it is not covered. + */ + getCoveredEnd(offset) { + if (!this.downloader || typeof this.downloader.getRanges !== 'function') + return offset; + const ranges = this.downloader.getRanges(); + for (const range of ranges) + if (offset >= range.start && offset < range.end) + return range.end; + return offset; + } + } + + /** + * Checks whether a value is the failure the downloader reports for a window it can never fill, which a byte source + * reads as end of file. + * @param {*} error - The value to check. + * @returns {boolean} True when it is a window unavailable failure. + */ + function isWindowUnavailableError(error) { + return !!error + && error.code === LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED + && !!error.details + && error.details.reason === LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE; + } + + /** + * Checks whether a value is the stop a download reports when it is intentionally aborted or destroyed. The download + * module treats such a stop as a normal teardown, not as a failure of the track, so a demuxer must not record it. + * @param {*} error - The value to check. + * @returns {boolean} True when the value is an intentional download stop. + */ + function isDownloadAbort(error) { + if (!error) + return false; + if (error.code === LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED) + return true; + // A raw fetch abort is also an intentional stop, so a DOMException named AbortError is treated the same way. + return LuminaAudioPlayer.isAbortError(error); + } + + LuminaAudioPlayer.isDownloadAbort = isDownloadAbort; + + /** + * Adapts a byte source for a demuxer: a caller passes the TrackDownloader of the download engine, an object that + * already implements readAsync and getLength, or nothing. + * @param {*} source - The source to adapt. + * @returns {Object} An object with getLength and readAsync. + */ + function toByteSource(source) { + if (source && typeof source.readAsync === 'function' && typeof source.getLength === 'function') + return source; + if (source && typeof source.readBytesAsync === 'function') + return new DemuxerByteSource(source); + return { + getLength: () => null, + readAsync: async () => new Uint8Array(0) + }; + } + + LuminaAudioPlayer.DemuxerByteSource = DemuxerByteSource; + LuminaAudioPlayer.createDemuxerByteSource = toByteSource; + + /** + * A windowing reader over a byte source. A parser walks the stream with absolute offsets, and the reader keeps the + * last window it loaded, so that a sequence of nearby small reads is served from memory and issues one request per + * window rather than one per read. + */ + class DemuxerReader { + /** + * Creates an instance of DemuxerReader. + * @param {Object} source - The byte source, per {@link LuminaAudioPlayer.createDemuxerByteSource}. + * @param {Object} [options] - The reader options. + * @param {number} [options.windowSize] - The number of bytes kept in the read ahead window. Defaults to 64 KiB. + */ + constructor(source, options = {}) { + this.source = toByteSource(source); + this.windowSize = Number.isInteger(options.windowSize) && options.windowSize > 0 ? options.windowSize : WINDOW_SIZE_BYTES; + this.windowStart = 0; + /** @type {Uint8Array} */ + this.windowBytes = new Uint8Array(0); + this.windowLength = 0; + // Set by destroy; a destroyed reader is never nulled out from under a caller, it only stops returning bytes. + this.destroyed = false; + } + + /** + * Releases the byte source of the reader, so that the downloader it holds is no longer referenced. The reader is + * deliberately left in place as a dead reader rather than being cleared by its owner: an operation that was in + * flight when the demuxer was destroyed keeps a reference to it and reads from it, so a freed object would turn + * that continuation into a TypeError, which the operation would record as a failure of a track that was in fact + * torn down. Every read after this returns an empty array and the length reads as unknown instead. + * @returns {void} + */ + destroy() { + this.destroyed = true; + this.source = null; + this.windowStart = 0; + this.windowBytes = new Uint8Array(0); + this.windowLength = 0; + } + + /** + * Gets the total size of the stream, when it is known. + * @returns {number|null} The length in bytes, or null. + */ + getLength() { + return this.source ? this.source.getLength() : null; + } + + /** + * Reads up to a number of bytes at an absolute offset. The returned view may be shorter than requested at the end + * of the stream, and is empty past it. It is a view over the read ahead window, so a caller must not mutate it and + * must not hold it across the end of the stream, though keeping it is safe while the reader is alive because a + * reload replaces the window rather than reusing its buffer. + * @param {number} offset - The first byte to read. + * @param {number} length - The number of bytes to read. + * @returns {Promise} The bytes, or an empty array when the offset is at or past the end of the stream. + * @throws {RangeError} When the length is past the limit of a single read. It is refused rather than truncated, + * because a caller treats a short read as the end of the stream, so a truncated read would be misread as EOF. + */ + async readAsync(offset, length) { + // A destroyed reader reads as an empty stream, so an operation still in flight ends at an end of stream rather + // than on a released reader. + if (this.destroyed) + return new Uint8Array(0); + const start = Math.max(0, Math.floor(offset)); + const requested = Math.max(0, Math.floor(length)); + if (requested > MAX_READ_BYTES) + throw new RangeError(`A single demuxer read cannot exceed ${MAX_READ_BYTES} bytes.`); + const size = requested; + if (size === 0) + return new Uint8Array(0); + if (start >= this.windowStart && start + size <= this.windowStart + this.windowLength) + return this.windowBytes.subarray(start - this.windowStart, start - this.windowStart + size); + const loadSize = Math.max(this.windowSize, size); + const bytes = await this.source.readAsync(start, loadSize); + this.windowStart = start; + this.windowBytes = bytes; + this.windowLength = bytes ? bytes.length : 0; + if (this.windowLength === 0) + return new Uint8Array(0); + return this.windowLength >= size ? this.windowBytes.subarray(0, size) : this.windowBytes; + } + + /** + * Reads a window of bytes and copies it, so that the caller owns bytes that do not alias the read ahead window. + * It is used for the codec private data a demuxer hands to the decoder. + * @param {number} offset - The first byte to read. + * @param {number} length - The number of bytes to read. + * @returns {Promise} A copy of the bytes, possibly shorter than requested at the end of the stream. + */ + async copyAsync(offset, length) { + const bytes = await this.readAsync(offset, length); + return bytes.length === 0 ? bytes : bytes.slice(); + } + + /** + * Reads the last bytes of the stream, when its length is known. It is how a demuxer reads a trailer, such as the + * last OGG page, without walking the whole stream. + * @param {number} maxLength - The maximum number of trailing bytes to read. + * @returns {Promise<{ bytes: Uint8Array, offset: number }|null>} The trailing bytes and their absolute offset, or null when the length is unknown or the stream is empty. + */ + async readTailAsync(maxLength) { + const total = this.getLength(); + if (total === null || total <= 0) + return null; + const size = Math.min(Math.max(1, Math.floor(maxLength)), total); + const offset = total - size; + const bytes = await this.copyAsync(offset, size); + return bytes.length > 0 ? { bytes, offset } : null; + } + } + + LuminaAudioPlayer.DemuxerReader = DemuxerReader; + + /** + * Coerces a value to a whole, non negative number of microseconds, so that a packet the decoder receives always + * carries a finite timestamp and duration. A non finite value becomes zero rather than passing through, because this + * is the last point before the decoder and a NaN or an Infinity there would corrupt the decode timeline silently. + * @param {number} value - The value to coerce. + * @returns {number} The whole, non negative microsecond value. + */ + function toMicroseconds(value) { + return Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0; + } + + /** + * Builds the frozen packet shape the decode pipeline consumes. + * @param {Uint8Array} data - The encoded bytes of the packet. + * @param {number} timestamp - The presentation timestamp of the first sample, in microseconds. + * @param {number} duration - The duration of the packet, in microseconds. + * @returns {Object} The frozen packet. + */ + function createPacket(data, timestamp, duration) { + return Object.freeze({ + data, + timestamp: toMicroseconds(timestamp), + duration: toMicroseconds(duration), + type: 'key' + }); + } + + LuminaAudioPlayer.createDemuxerPacket = createPacket; + + /** + * The number of candidate positions a single scan will validate before it gives up. A validator is an awaited read, so + * a stream whose body is filled with byte patterns that look like a sync, but are not, would otherwise make one scan + * do one awaited read per pattern. The cap is far above what any real stream needs, because a real frame or page is + * found within one frame or page length of the start, so it only ever refuses a crafted or badly corrupt region. + * @readonly + * @type {number} + */ + const SCAN_MAX_CANDIDATES = 65536; + + /** + * Scans a stream for the next offset whose bytes start with a prefix and pass a validator. It reads forward in + * chunks and only calls the validator on the offsets that match the prefix, so a byte that merely looks like a frame + * sync costs one comparison while a real header is validated in full. The validator reads the extra bytes it needs + * itself, so it is not limited by the size of a scan chunk. + * + * The prefix may carry a mask per byte, so a format whose sync is shorter than a whole byte can reject most false + * candidates with a comparison rather than with the awaited validator; and the number of candidates a scan validates + * is capped, so a crafted region cannot turn a scan into an unbounded number of awaited reads. A scan that reaches + * that cap throws rather than returning the same -1 it uses for end of stream, so a refused region is reported as a + * demux failure instead of ending playback silently. + * @param {LuminaAudioPlayer.DemuxerReader} reader - The reader to scan through. + * @param {number} start - The offset to start the scan at. + * @param {number|null} end - The exclusive end of the scan, or null to scan to the end of the stream. + * @param {Array} prefix - The bytes a candidate must start with. + * @param {Function} [validateAsync] - An async validator that receives the absolute offset of a candidate and returns whether it is a real frame header. When omitted, the prefix match alone accepts a candidate. + * @param {Object} [options] - The scan options. + * @param {Array} [options.prefixMask] - A mask per prefix byte; a candidate matches when each byte matches under its mask. Defaults to an exact comparison of every byte. + * @returns {Promise} The offset of the first accepted candidate, or -1 when the scan reaches the end of the stream without one. + * @throws {LuminaAudioPlayer.PlayerError} With {@link LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED} and details.reason === 'scan-budget-exhausted' when the scan evaluated its candidate budget without finding a frame, which is a corrupt or crafted region rather than an end of stream. + */ + async function scanForFrameAsync(reader, start, end, prefix, validateAsync, options = {}) { + const settings = options || {}; + const prefixMask = settings.prefixMask || null; + let remaining = SCAN_MAX_CANDIDATES; + const limit = end === null ? Number.POSITIVE_INFINITY : Math.floor(end); + const overlap = Math.max(0, prefix.length - 1); + let position = Math.max(0, Math.floor(start)); + // The outer loop walks the stream forward one chunk at a time: each iteration reads one chunk at `position`, + // examines its candidates, and then advances `position` past it (less the overlap), until the scan limit or the + // end of the stream is reached. + while (position < limit) { + const requested = Math.min(SCAN_CHUNK_BYTES, limit - position); + const bytes = await reader.readAsync(position, requested); + if (bytes.length === 0) + return -1; + // A candidate must fit entirely inside the chunk, so the last start offset is the one where a whole prefix still fits; the `<=` below includes it. + const lastCandidate = bytes.length - prefix.length; + // The middle loop tries every byte offset of the chunk as the start of a candidate frame. + for (let index = 0; index <= lastCandidate; index++) { + let matches = true; + // The inner loop matches the candidate against the prefix, byte by byte and under each byte's mask, + // stopping at the first mismatch. This is the cheap filter: only a candidate that matches the whole + // prefix is worth the awaited validator, which reads further bytes. + for (let prefixIndex = 0; prefixIndex < prefix.length; prefixIndex++) { + const mask = prefixMask ? prefixMask[prefixIndex] : 0xFF; + if ((bytes[index + prefixIndex] & mask) !== (prefix[prefixIndex] & mask)) { + matches = false; + break; + } + } + if (!matches) + continue; + // The prefix matched, so this offset is a full candidate: it costs one unit of the scan budget, and the validator, when there is one, decides whether it is a real frame header. + if (remaining <= 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The scan evaluated its candidate budget without finding a frame.', { reason: 'scan-budget-exhausted' }); + remaining--; + const offset = position + index; + if (!validateAsync || await validateAsync(offset)) + return offset; + } + // When the chunk came back short the stream ended, so there is nothing beyond it to scan. + if (bytes.length < requested) + return -1; + // The next chunk overlaps this one by one byte less than the prefix, so a candidate that straddles the boundary is still validated instead of being skipped. + position += Math.max(1, bytes.length - overlap); + } + return -1; + } + + LuminaAudioPlayer.scanForFrameAsync = scanForFrameAsync; + + /** + * Copies a run of bytes into a new array. It is used when a packet is assembled from more than one read, so that the + * bytes the decoder receives do not alias a read ahead window. + * @param {Array} parts - The runs to concatenate, in order. + * @returns {Uint8Array} The concatenated bytes. + */ + function concatBytes(parts) { + let total = 0; + for (const part of parts) + total += part.byteLength; + const result = new Uint8Array(total); + let offset = 0; + for (const part of parts) { + result.set(part, offset); + offset += part.byteLength; + } + return result; + } + + LuminaAudioPlayer.concatDemuxerBytes = concatBytes; + + /** + * The base class of a demuxer. It owns the byte reader, the recorded failure and the error callback, and it defines the interface every per format demuxer implements. + */ + class Demuxer { + /** + * Creates an instance of Demuxer. + * @param {Object} options - The demuxer options. + * @param {*} options.source - The byte source, per {@link LuminaAudioPlayer.createDemuxerByteSource}. + * @param {LuminaAudioPlayer.DemuxerReader} [options.reader] - An existing reader to use instead of building one from the source. + * @param {Function} [options.onError] - Called with a {@link LuminaAudioPlayer.PlayerError} when the demuxer fails. + * @param {number} [options.windowSize] - The size of the read ahead window of the reader. + */ + constructor(options = {}) { + const settings = options || {}; + this.reader = settings.reader instanceof DemuxerReader ? settings.reader : new DemuxerReader(settings.source, settings); + this.onError = typeof settings.onError === 'function' ? settings.onError : null; + /** @type {LuminaAudioPlayer.PlayerError|null} */ + this.error = null; + this.destroyed = false; + this.initialized = false; + } + + /** + * Checks whether the stream was initialized and can be read. + * @returns {boolean} True when the stream is initialized. + */ + isInitialized() { + return this.initialized && !this.destroyed && this.error === null; + } + + /** + * Checks whether the demuxer can no longer read, because it was destroyed or failed. + * @returns {boolean} True when the demuxer has stopped. + */ + isStopped() { + return this.destroyed || this.error !== null; + } + + /** + * Checks whether the demuxer was destroyed. + * @returns {boolean} True when the demuxer was destroyed. + */ + isDestroyed() { + return this.destroyed; + } + + /** + * Gets the last failure the demuxer recorded, or null. + * @returns {LuminaAudioPlayer.PlayerError|null} The recorded failure. + */ + getError() { + return this.error; + } + + /** + * Builds a typed error without recording it. + * @param {string} code - One of the {@link LuminaAudioPlayer.PlayerErrorCode} values. + * @param {string} message - The developer facing description of the failure. + * @param {Object} [details] - Optional structured details. + * @returns {LuminaAudioPlayer.PlayerError} The typed error. + */ + createError(code, message, details = null) { + return new LuminaAudioPlayer.PlayerError(code || LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, message, details || null); + } + + /** + * Records a fatal failure, stops the demuxer and notifies the error callback. The first failure wins, so a burst + * of failures after the demuxer stopped never overwrites the cause or reports twice. A failure that another + * component already typed with a player error keeps that component's code. + * @param {*} error - The failure to record. + * @param {string} [code] - The code to use when the failure is not already a player error. + * @param {Object} [details] - Optional structured details. + * @returns {LuminaAudioPlayer.PlayerError} The recorded typed error. + */ + fail(error, code = LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, details = null) { + if (this.error) + return this.error; + const typed = LuminaAudioPlayer.toOwnedPlayerError(error, code, details); + this.error = typed; + this.initialized = false; + if (this.onError) { + try { + this.onError(typed); + } catch (callbackError) { + console.error('Audio player: the demuxer error callback threw.', callbackError); + } + } + return typed; + } + + /** + * Skips an ID3v2 tag at an offset, when one is present. The MP3 and AAC demuxers both use it, because a stream of + * either may carry a leading ID3v2 tag before its first frame. + * @param {number} offset - The offset to look for the tag at. + * @returns {Promise} The offset just past the tag, or the given offset when there is none. + */ + async skipId3v2Async(offset) { + const bytes = await this.reader.readAsync(offset, 10); + if (bytes.length < 10 || !LuminaAudioPlayer.demuxBytesEqualAscii(bytes, 0, 'ID3')) + return offset; + const flags = bytes[5]; + const size = LuminaAudioPlayer.demuxReadSyncSafe(bytes, 6); + // A tag may carry a ten byte footer, which is not counted in the size. + return offset + 10 + size + ((flags & 0x10) !== 0 ? 10 : 0); + } + + /** + * Records a fatal failure through {@link LuminaAudioPlayer.Demuxer#fail}, with two exceptions: an intentional + * download stop, which is a normal teardown and not a failure of the track, is returned typed without being + * recorded or reported; and a failure that another component already typed with a structured reason keeps its + * own reason instead of the generic one of the caller. + * @param {*} error - The failure to record. + * @param {string} reason - The structured reason to attach when the failure carries none. + * @returns {LuminaAudioPlayer.PlayerError} The typed error, recorded unless it is an intentional stop. + */ + recordFailure(error, reason) { + // A failure observed after the demuxer was destroyed belongs to the teardown of the operation, not to the track, + // so it is returned typed as an abort and is neither recorded nor reported as a track failure. + if (this.destroyed) + return LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED); + // An intentional stop is returned typed but not recorded, and it is wrapped with the abort code rather than + // the demux code, so that a caller which classifies the failure again, as the capability module does, still + // sees it as an abort and not as a track that has to be normalized. + if (isDownloadAbort(error)) + return LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED); + if (error instanceof LuminaAudioPlayer.PlayerError && error.details && error.details.reason !== undefined) + return this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED); + return this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, { reason }); + } + + /** + * Reads the header(s) of the stream and prepares the configuration. It must be called before reading any packet. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not a stream of this format. + */ + async initializeAsync() { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This demuxer does not implement initializeAsync.'); + } + + /** + * Reads the next encoded packet of the stream. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This demuxer does not implement readPacketAsync.'); + } + + /** + * Gets the decoder configuration of the stream, available after initializeAsync resolved. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + return null; + } + + /** + * Gets the duration of the whole stream, when the header states it. + * @returns {number|null} The duration in seconds, or null when it is not known from the header. + */ + getDuration() { + return null; + } + + /** + * Repositions the read cursor to a packet boundary at or before a time. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the format cannot be repositioned by time. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a frame gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + return null; + } + + /** + * Releases every resource of the demuxer. It is safe to call more than once. It releases the reader, and through + * it the byte source that holds the download engine, without clearing the reader reference itself, because an + * operation that is still in flight holds that reference and reads through it; the released reader reads as an + * empty stream, so the operation ends at an end of stream instead of on a freed object. It also gives a subclass + * the chance to release its own queued state through onDestroy. + * @returns {Promise} A promise resolving when the demuxer is released. + */ + async destroyAsync() { + this.destroyed = true; + this.initialized = false; + if (typeof this.onDestroy === 'function') + this.onDestroy(); + if (this.reader && typeof this.reader.destroy === 'function') + this.reader.destroy(); + } + + /** + * Ensures the stream was initialized before it is read. + * @returns {void} + * @throws {LuminaAudioPlayer.PlayerError} When the demuxer was destroyed, failed, or was not initialized. + */ + ensureInitialized() { + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + if (this.error) + throw this.error; + if (!this.initialized) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer is not initialized.'); + } + } + + LuminaAudioPlayer.Demuxer = Demuxer; + + /** + * A registry of demuxer descriptors, keyed by the canonical container and codec pair a demuxer handles. + */ + class DemuxerRegistry { + /** + * Creates an instance of DemuxerRegistry. + */ + constructor() { + /** @type {Map} */ + this.descriptors = new Map(); + } + + /** + * Builds the key a container and codec pair is registered and looked up under. + * @param {string} container - The canonical container name. + * @param {string} codec - The canonical codec name. + * @returns {string} The registry key. + */ + static buildKey(container, codec) { + return `${container}/${codec}`; + } + + /** + * Registers a demuxer descriptor. + * @param {Object} descriptor - The descriptor, with a container, a codec, a representative decoder probe and a create function that receives the demuxer options and returns a demuxer. + * @returns {LuminaAudioPlayer.DemuxerRegistry} This registry, for chaining. + * @throws {TypeError} When the descriptor is incomplete, including when it carries no representative probe. The probe is required so that the browser check of the demux capability module never has to guess from a name, which would silently report a supported codec as unsupported. + */ + register(descriptor) { + if (!descriptor || typeof descriptor.create !== 'function') + throw new TypeError('A demuxer descriptor must carry a create function.'); + const container = canonicalizeContainer(descriptor.container); + const codec = canonicalizeCodec(descriptor.codec); + if (container === '' || codec === '') + throw new TypeError('A demuxer descriptor must name a container and a codec.'); + const probe = descriptor.probe; + if (!probe + || typeof probe.codec !== 'string' || probe.codec === '' + || !Number.isInteger(probe.sampleRate) || probe.sampleRate <= 0 + || !Number.isInteger(probe.numberOfChannels) || probe.numberOfChannels <= 0) + throw new TypeError('A demuxer descriptor must carry a representative decoder probe with a codec string, a sample rate and a channel count.'); + this.descriptors.set(DemuxerRegistry.buildKey(container, codec), Object.freeze({ + container, + codec, + probe: Object.freeze({ codec: probe.codec, sampleRate: probe.sampleRate, numberOfChannels: probe.numberOfChannels }), + create: descriptor.create + })); + return this; + } + + /** + * Finds the demuxer descriptor of a container and codec pair, matching canonicalized names. + * @param {string} container - The container name, in any casing. + * @param {string} codec - The codec name, in any casing or as a free form probe description. + * @returns {Object|null} The descriptor, or null when no demuxer handles the pair. + */ + find(container, codec) { + const key = DemuxerRegistry.buildKey(canonicalizeContainer(container), canonicalizeCodec(codec)); + return this.descriptors.get(key) || null; + } + + /** + * Lists the registered descriptors, in registration order. + * @returns {Array} The descriptors. + */ + getDescriptors() { + return [...this.descriptors.values()]; + } + } + + LuminaAudioPlayer.DemuxerRegistry = DemuxerRegistry; + + /** + * The process wide registry the per format modules register their demuxers into. It exists as soon as this module + * loads, so a format module loaded after it can always register, whatever the load order among the formats. + * @type {LuminaAudioPlayer.DemuxerRegistry} + */ + LuminaAudioPlayer.demuxerRegistry = new DemuxerRegistry(); + + /** + * Registers a demuxer descriptor into the process wide registry. + * @param {Object} descriptor - The descriptor, per {@link LuminaAudioPlayer.DemuxerRegistry#register}. + * @returns {LuminaAudioPlayer.DemuxerRegistry} The process wide registry, for chaining. + */ + LuminaAudioPlayer.registerDemuxer = function (descriptor) { + return LuminaAudioPlayer.demuxerRegistry.register(descriptor); + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-flac.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-flac.js new file mode 100644 index 00000000..974ba8e6 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-flac.js @@ -0,0 +1,1064 @@ +/** + * FLAC demuxer of the audio player. + * + * A FLAC file is the four byte magic 'fLaC', a sequence of metadata blocks whose first is the mandatory STREAMINFO + * block, and then a stream of audio frames. STREAMINFO states the sample rate, the channel count, the bit depth and the + * total number of samples of the whole stream, so the duration is known up front, which no other container here gives. + * Each frame header states its own block size, sample rate, channel assignment and sample size, plus a CRC-8 over the + * header, and the frame number or sample number it starts at. + * + * Finding the exact frame boundary + * -------------------------------- + * A FLAC frame does not state its own compressed length. This demuxer computes it the way the format defines it, by + * walking the frame's bitstream: the frame header, then one subframe per channel, then zero padding to the next byte + * boundary, then the 16 bit frame CRC. Each subframe is parsed to its exact end without decoding it, whatever it holds: + * - a constant subframe is one tail of bits-per-sample bits; + * - a verbatim subframe is a whole block of bits-per-sample bits; + * - a fixed or an LPC subframe is a run of warm-up samples, the LPC parameters when it is LPC, and then a coded + * residual; + * - a coded residual is one or more Rice partitions, each either Rice coded with a per-partition parameter, or, under + * the escape code, a run of raw bits. Walking a partition means walking every coded value of it, because a Rice code + * is not a fixed width, so the parser reads the unary prefix and the remainder of each value. + * The 16 bit frame CRC closes the frame, and it is verified against the bytes that were walked, so a frame that was + * framed wrongly, or that is corrupt, is reported rather than handed to the decoder. The frame header CRC-8 is verified + * too, so a byte pattern that merely looks like a sync cannot start a frame. + * + * The codec private data + * ---------------------- + * The WebCodecs FLAC registration requires a description that is the bytes of a FLAC bitstream up to the first frame, + * at least the 'fLaC' magic followed by the STREAMINFO metadata block. This demuxer builds exactly that: the magic and + * the STREAMINFO block, header included, without the other metadata blocks of the file, so the description stays small + * whatever a file carries. + * + * Seeking and resynchronization + * ----------------------------- + * A frame boundary is located from a distance by scanning for a frame header whose CRC-8 and stream parameters match, + * which is what a seek uses to land on a frame before parsing it exactly, and what a resynchronization uses after a + * corrupted region. A FLAC stream may carry a SEEKTABLE, but this demuxer does not need one: it estimates the byte + * position of a time from its proportion of the total samples and then scans to the next frame header, whose coded frame + * or sample number gives the position back exactly. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The four byte magic every FLAC stream starts with. + * @readonly + * @type {string} + */ + const FLAC_MAGIC = 'fLaC'; + + /** + * The number of bytes of the STREAMINFO metadata block body. + * @readonly + * @type {number} + */ + const STREAMINFO_BODY_BYTES = 34; + + /** + * The number of header bytes read to parse a frame header. A FLAC frame header is at most seventeen bytes long. + * @readonly + * @type {number} + */ + const FRAME_HEADER_WINDOW_BYTES = 20; + + /** + * The number of bytes held in the read ahead window of the frame bitstream reader. It is at least a whole FLAC + * subframe for the common configurations, so the parser issues one read per window rather than one per bit. + * @readonly + * @type {number} + */ + const FRAME_WINDOW_BYTES = 65536; + + /** + * The byte budget a frame is allowed to consume when neither the maximum frame size of STREAMINFO nor the length of + * the stream is known. It is above the largest frame the format can produce, so a parser never stops a valid frame, + * while a corrupt one cannot make it read without bound. + * @readonly + * @type {number} + */ + const DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024; + + /** + * The sample rates, in Hz, named directly by the sample rate codes of a FLAC frame header. + * @readonly + * @type {Object} + */ + const SAMPLE_RATE_CODES = Object.freeze({ + 1: 88200, + 2: 176400, + 3: 192000, + 4: 8000, + 5: 16000, + 6: 22050, + 7: 24000, + 8: 32000, + 9: 44100, + 10: 48000, + 11: 96000 + }); + + /** + * The bits-per-sample each sample size code names, with zero meaning 'from STREAMINFO'. + * @readonly + * @type {Array} + */ + const SAMPLE_SIZE_CODES = Object.freeze([0, 8, 12, 0, 16, 20, 24, 32]); + + /** + * The fourteen bit frame sync of a FLAC frame, as the two byte prefix a scan matches on. The mask covers the top six + * bits of the second byte, so a scan rejects a byte pattern that is not a sync by a comparison instead of by an + * awaited header parse. + * @readonly + * @type {Array} + */ + const FLAC_SYNC_PREFIX = Object.freeze([0xFF, 0xF8]); + + /** + * The byte mask of {@link FLAC_SYNC_PREFIX}, matching the fourteen bit sync exactly. + * @readonly + * @type {Array} + */ + const FLAC_SYNC_MASK = Object.freeze([0xFF, 0xFC]); + + /** + * The number of metadata blocks the demuxer will walk past STREAMINFO before it refuses the stream. Real files carry a + * handful, and the walk is bounded by this cap rather than by the length of the stream. + * @readonly + * @type {number} + */ + const MAX_METADATA_BLOCKS = 4096; + + /** + * The lookup table of the FLAC frame checksum, built once. It turns the checksum from eight bit iterations to one byte + * lookup per byte of a frame. + * @readonly + * @type {Uint32Array} + */ + const CRC16_TABLE = LuminaAudioPlayer.demuxBuildCrcTable(0x8005, 16); + + /** + * The lookup table of the FLAC frame header checksum, built once. + * @readonly + * @type {Uint32Array} + */ + const CRC8_TABLE = LuminaAudioPlayer.demuxBuildCrcTable(0x07, 8); + + /** + * Computes the CRC-16 of a run of bytes, with the polynomial 0x8005 and an initial value of zero, the checksum a + * FLAC frame ends with. + * @param {Uint8Array} bytes - The bytes to checksum. + * @returns {number} The checksum. + */ + function computeCrc16(bytes) { + let crc = 0; + for (let index = 0; index < bytes.length; index++) + crc = ((crc << 8) ^ CRC16_TABLE[((crc >> 8) ^ bytes[index]) & 0xFF]) & 0xFFFF; + return crc & 0xFFFF; + } + + /** + * Computes the CRC-8 of a run of bytes, with the polynomial 0x07 and an initial value of zero, the checksum a FLAC + * frame header ends with. + * @param {Uint8Array} bytes - The bytes to checksum. + * @returns {number} The checksum. + */ + function computeCrc8(bytes) { + let crc = 0; + for (let index = 0; index < bytes.length; index++) + crc = CRC8_TABLE[(crc ^ bytes[index]) & 0xFF]; + return crc; + } + + /** + * Reads the UTF-8 style coded number a FLAC frame header uses for the frame number or the sample number. + * @param {LuminaAudioPlayer.DemuxerBitReader} reader - The bit reader positioned on the first byte of the number. + * @returns {number} The decoded number. + * @throws {RangeError} When the coded number is malformed. + */ + function readCodedNumber(reader) { + const first = reader.readBits(8); + if ((first & 0x80) === 0) + return first; + // The number is coded the way UTF-8 codes a code point: the run of leading one bits in the first byte states how + // many bytes the number spans, and each following byte starts with a '10' prefix and contributes six more bits. + let leadingOnes = 0; + let mask = 0x80; + while (mask !== 0 && (first & mask) !== 0) { + leadingOnes++; + mask >>= 1; + } + if (leadingOnes < 2 || leadingOnes > 7) + throw new RangeError('The FLAC coded number is malformed.'); + let value = first & (0x7F >> leadingOnes); + for (let index = 1; index < leadingOnes; index++) { + const continuation = reader.readBits(8); + if ((continuation & 0xC0) !== 0x80) + throw new RangeError('The FLAC coded number is malformed.'); + value = value * 64 + (continuation & 0x3F); + } + return value; + } + + /** + * Resolves the block size a FLAC frame header names. + * @param {number} code - The four bit block size code. + * @param {LuminaAudioPlayer.DemuxerBitReader} reader - The bit reader, positioned after the coded number, from which the variable codes read their extra bytes. + * @returns {number|null} The block size in samples, or null when the code is invalid. + */ + function resolveBlockSize(code, reader) { + // Codes 2 to 5 are powers of two starting at 576 samples, codes 6 and 7 store the size minus one in the one or + // two bytes that follow, and codes 8 to 15 are powers of two starting at 256. + if (code === 0) + return null; + if (code === 1) + return 192; + if (code >= 2 && code <= 5) + return 576 * Math.pow(2, code - 2); + if (code === 6) + return reader.readBits(8) + 1; + if (code === 7) + return reader.readBits(16) + 1; + return 256 * Math.pow(2, code - 8); + } + + /** + * Resolves the sample rate a FLAC frame header names. It distinguishes the code that means "take it from STREAMINFO" + * from the reserved code, which a frame may never use: collapsing the two into null would accept a frame header that + * names a reserved sample rate code, leaving only the header checksum to reject a false sync. + * @param {number} code - The four bit sample rate code. + * @param {LuminaAudioPlayer.DemuxerBitReader} reader - The bit reader, positioned after the block size, from which the variable codes read their extra bytes. + * @returns {{ rate: number|null, isValid: boolean }} The sample rate in Hz, or null to mean 'from STREAMINFO', together with whether the code is one the format defines. + */ + function resolveFrameSampleRate(code, reader) { + if (code === 0) + return { rate: null, isValid: true }; + if (Object.prototype.hasOwnProperty.call(SAMPLE_RATE_CODES, code)) + return { rate: SAMPLE_RATE_CODES[code], isValid: true }; + if (code === 12) + return { rate: reader.readBits(8) * 1000, isValid: true }; + if (code === 13) + return { rate: reader.readBits(16), isValid: true }; + if (code === 14) + return { rate: reader.readBits(16) * 10, isValid: true }; + return { rate: null, isValid: false }; + } + + /** + * Parses the header of a FLAC frame. + * @param {Uint8Array} bytes - The bytes holding the header. + * @param {number} offset - The offset of the frame's first byte. + * @param {Object} streamInfo - The STREAMINFO fields of the stream. + * @returns {Object|null} The parsed header, or null when the bytes are not a valid frame header. + */ + function parseFrameHeader(bytes, offset, streamInfo) { + if (!bytes || offset < 0 || offset + 4 > bytes.length) + return null; + try { + const reader = new LuminaAudioPlayer.DemuxerBitReader(bytes.subarray(offset)); + // A frame header is bit packed: a fourteen bit sync (0x3FFE), a reserved bit that must be zero, a blocking + // strategy bit, a four bit block size code, a four bit sample rate code, a four bit channel assignment, a + // three bit sample size code, a second reserved bit, the coded frame or sample number, and finally the eight + // bit header checksum. The fields are validated against STREAMINFO so a byte pattern inside frame data is + // rejected as a header. + if (reader.readBits(14) !== 0x3FFE) + return null; + if (reader.readBits(1) !== 0) + return null; + const blockingStrategy = reader.readBits(1); + const blockSizeCode = reader.readBits(4); + const sampleRateCode = reader.readBits(4); + const channelAssignment = reader.readBits(4); + const sampleSizeCode = reader.readBits(3); + if (reader.readBits(1) !== 0) + return null; + const codedNumber = readCodedNumber(reader); + const blockSize = resolveBlockSize(blockSizeCode, reader); + if (blockSize === null) + return null; + const frameSampleRate = resolveFrameSampleRate(sampleRateCode, reader); + if (!frameSampleRate.isValid) + return null; + const sampleRate = frameSampleRate.rate === null ? streamInfo.sampleRate : frameSampleRate.rate; + if (sampleRate !== streamInfo.sampleRate) + return null; + const channels = channelAssignment <= 7 ? channelAssignment + 1 : channelAssignment <= 10 ? 2 : null; + if (channels === null || channels !== streamInfo.channels) + return null; + // Assignments 0 to 7 mean that many independent channels minus one, and 8, 9 and 10 are the three stereo + // decorrelation modes (left/side, right/side and mid/side), which still carry two channels. + if (sampleSizeCode === 3) + return null; + const bitsPerSample = sampleSizeCode === 0 ? streamInfo.bitsPerSample : SAMPLE_SIZE_CODES[sampleSizeCode]; + if (bitsPerSample !== streamInfo.bitsPerSample) + return null; + const crcPosition = reader.getBytePosition(); + const expectedCrc = reader.readBits(8); + const computedCrc = computeCrc8(bytes.subarray(offset, offset + crcPosition)); + if (expectedCrc !== computedCrc) + return null; + return Object.freeze({ + blockSize, + sampleRate, + channels, + channelAssignment, + bitsPerSample, + blockingStrategy, + codedNumber, + headerBytes: reader.getBytePosition() + }); + } catch (error) { + // A header that runs past the bytes read so far, or a malformed coded number, is not a frame header. + return null; + } + } + + /** + * A bit reader over the byte source, used to walk a whole FLAC frame without holding it in memory. It reads through a + * window that it reloads as the walk crosses it, and it enforces a bit budget, so a corrupt bitstream cannot make it + * read without bound. + * + * The reader has an awaited surface (readBitsAsync, readUnaryAsync, skipBitsAsync) and a synchronous one + * (tryReadBits, walkRiceSamples) that runs over the resident window without a promise. The synchronous surface is the + * hot path of a lossless frame: a coded residual holds thousands of values, and awaiting one promise per value, each + * resolving from bytes already in the window, is pure overhead on a realtime path. A caller therefore reloads the + * window with refillAsync and then walks as many values as fit, which costs one reload per window instead of one + * promise per value; the awaited surface remains for the fields that span a window, which are rare and tiny. + */ + class FlacBitstreamReader { + /** + * Creates an instance of FlacBitstreamReader. + * @param {LuminaAudioPlayer.DemuxerReader} reader - The windowing reader over the track. + * @param {Object} options - The options. + * @param {number} options.startOffset - The absolute byte offset the bitstream starts at. + * @param {number} options.maxBitOffset - The number of bits the walk may consume before the frame is refused. + */ + constructor(reader, options) { + this.reader = reader; + this.base = options.startOffset; + this.maxBitOffset = options.maxBitOffset; + this.bitOffset = 0; + /** @type {Uint8Array} */ + this.windowBytes = new Uint8Array(0); + this.windowStart = 0; + this.windowLength = 0; + } + + /** + * Gets the absolute byte offset the walk reached. It is meaningful while the walk is byte aligned. + * @returns {number} The absolute byte offset. + */ + getBytePosition() { + return this.base + (this.bitOffset >> 3); + } + + /** + * Gets the number of bits the walk consumed. + * @returns {number} The bit offset relative to the start of the bitstream. + */ + getBitOffset() { + return this.bitOffset; + } + + /** + * Makes sure a run of bytes is available in the window, reloading it when it is not. It throws when the run + * reaches past the end of the stream, which means the frame is truncated, and when the walk exceeded its budget. + * @param {number} relativeStart - The first byte of the run, relative to the start offset. + * @param {number} byteCount - The number of bytes of the run. + * @returns {Promise} A promise resolving when the run is available. + * @throws {RangeError} With an isEof or an isBound flag when the walk cannot continue. + */ + async ensureRangeAsync(relativeStart, byteCount) { + const absoluteStart = this.base + relativeStart; + const absoluteEnd = absoluteStart + byteCount - 1; + if (absoluteStart >= this.windowStart && absoluteEnd < this.windowStart + this.windowLength) + return; + const bytes = await this.reader.readAsync(absoluteStart, Math.max(FRAME_WINDOW_BYTES, byteCount)); + this.windowStart = absoluteStart; + this.windowBytes = bytes; + this.windowLength = bytes ? bytes.length : 0; + if (this.windowLength === 0 || absoluteEnd >= this.windowStart + this.windowLength) { + const error = new RangeError('The FLAC frame bitstream ended before the frame did.'); + error.isEof = true; + throw error; + } + } + + /** + * Refuses to read past the frame's bit budget. + * @param {number} extraBits - The number of bits about to be consumed. + * @throws {RangeError} With an isBound flag when the budget is exceeded. + */ + checkBudget(extraBits) { + if (this.maxBitOffset !== null && this.bitOffset + extraBits > this.maxBitOffset) { + const error = new RangeError('The FLAC frame exceeded the size it may occupy.'); + error.isBound = true; + throw error; + } + } + + /** + * Reads an unsigned integer of up to 32 bits. + * @param {number} count - The number of bits to read. + * @returns {Promise} The value. + * @throws {RangeError} When the walk cannot continue. + */ + async readBitsAsync(count) { + if (count <= 0) + return 0; + this.checkBudget(count); + const firstByte = this.bitOffset >> 3; + const lastByte = (this.bitOffset + count - 1) >> 3; + await this.ensureRangeAsync(firstByte, lastByte - firstByte + 1); + let value = 0; + for (let index = 0; index < count; index++) { + const local = this.base + (this.bitOffset >> 3) - this.windowStart; + const bit = 7 - (this.bitOffset & 7); + value = value * 2 + ((this.windowBytes[local] >> bit) & 1); + this.bitOffset++; + } + return value; + } + + /** + * Reads a unary coded value: the number of zero bits before the terminating one. + * @returns {Promise} The number of zero bits read. + * @throws {RangeError} When the walk cannot continue. + */ + async readUnaryAsync() { + let zeros = 0; + for (;;) { + this.checkBudget(1); + const byteIndex = this.bitOffset >> 3; + await this.ensureRangeAsync(byteIndex, 1); + const local = this.base + byteIndex - this.windowStart; + const startBit = 7 - (this.bitOffset & 7); + const byte = this.windowBytes[local]; + for (let bit = startBit; bit >= 0; bit--) { + if (((byte >> bit) & 1) !== 0) { + zeros += startBit - bit; + this.bitOffset += startBit - bit + 1; + return zeros; + } + } + // The rest of the byte is zeros, so it is consumed and the scan continues on the next byte. + zeros += startBit + 1; + this.bitOffset += startBit + 1; + } + } + + /** + * Skips a number of bits, verifying that the last skipped byte exists so that a truncated frame is detected. + * @param {number} count - The number of bits to skip. + * @returns {Promise} A promise resolving when the bits were skipped. + * @throws {RangeError} When the walk cannot continue. + */ + async skipBitsAsync(count) { + if (count <= 0) + return; + this.checkBudget(count); + const newOffset = this.bitOffset + count; + await this.ensureRangeAsync((newOffset - 1) >> 3, 1); + this.bitOffset = newOffset; + } + + //+=======================================================================================+ + //| Synchronous fast path | + //+=======================================================================================+ + + /** + * Checks whether the byte the walk is on is already resident in the window, so that a caller can tell whether a + * read would need to await a reload before it awaits one. + * @returns {boolean} True when the current byte is in the window. + */ + isResident() { + const absolute = this.base + (this.bitOffset >> 3); + return absolute >= this.windowStart && absolute < this.windowStart + this.windowLength; + } + + /** + * Loads the window so that it starts at the current byte, when it does not already cover it, or always when it is + * forced. It is the single awaited step of the residual fast path: the walk below it runs synchronously until the + * window runs out, so a frame costs one reload per window rather than one promise per coded value. + * @param {boolean} [force] - True to reload even when the current byte is already resident. + * @returns {Promise} A promise resolving when the window covers the current byte. + * @throws {RangeError} When the bitstream ended. + */ + async refillAsync(force) { + const absolute = this.base + (this.bitOffset >> 3); + if (!force && absolute >= this.windowStart && absolute < this.windowStart + this.windowLength) + return; + const bytes = await this.reader.readAsync(absolute, FRAME_WINDOW_BYTES); + this.windowStart = absolute; + this.windowBytes = bytes; + this.windowLength = bytes ? bytes.length : 0; + if (this.windowLength === 0) { + const error = new RangeError('The FLAC frame bitstream ended before the frame did.'); + error.isEof = true; + throw error; + } + this.checkBudget(0); + } + + /** + * Reads an unsigned integer of up to 32 bits without awaiting, when the bits are already resident. It never + * advances the walk when it returns null, so a caller can reload the window and try again. + * @param {number} count - The number of bits to read. + * @returns {number|null} The value, or null when the bits are not all resident yet. + */ + tryReadBits(count) { + if (count <= 0) + return 0; + if (this.base + ((this.bitOffset + count - 1) >> 3) >= this.windowStart + this.windowLength) + return null; + let value = 0; + for (let index = 0; index < count; index++) { + const local = this.base + (this.bitOffset >> 3) - this.windowStart; + const bit = 7 - (this.bitOffset & 7); + value = value * 2 + ((this.windowBytes[local] >> bit) & 1); + this.bitOffset++; + } + // The synchronous path advances the walk itself, so it enforces the budget itself, exactly, rather than + // leaving the overshoot to the next awaited read. + this.checkBudget(0); + return value; + } + + /** + * Walks a run of Rice coded residual values synchronously over the resident window. This is the hot path of a + * lossless frame: the unary prefix is scanned byte by byte and the remainder is stepped over in one move, with no + * promise per value. It returns the number of values it completed, and leaves a value whose bits reach past the + * window untouched, so the walk resumes exactly on that value's first bit once the window is reloaded. + * @param {number} parameter - The Rice parameter of the partition. + * @param {number} maxSamples - The number of values still to walk in the partition. + * @returns {number} The number of values completed, between zero and maxSamples. + */ + walkRiceSamples(parameter, maxSamples) { + this.checkBudget(0); + const windowEndBit = (this.windowStart + this.windowLength - this.base) * 8; + let completed = 0; + // One iteration per residual value of the partition, until the partition is walked or a value turns out not to fit the resident window. + while (completed < maxSamples) { + const valueStart = this.bitOffset; + let found = false; + // Walk the unary prefix of this value: every zero bit is skipped and the first one bit ends the prefix. + // The window bytes are scanned directly, so the prefix costs no promise per bit. + while (this.bitOffset < windowEndBit) { + const local = this.base + (this.bitOffset >> 3) - this.windowStart; + const startBit = 7 - (this.bitOffset & 7); + const byte = this.windowBytes[local]; + let hit = false; + // Within this byte, the bits are examined from the current bit down to bit 0, looking for the one bit. that ends the unary prefix. + for (let bit = startBit; bit >= 0; bit--) { + if (((byte >> bit) & 1) !== 0) { + this.bitOffset += startBit - bit + 1; + hit = true; + break; + } + } + if (hit) { + found = true; + break; + } + this.bitOffset += startBit + 1; + // The synchronous walk enforces the budget after every advance, so a corrupt value cannot overshoot it. + this.checkBudget(0); + } + if (!found || (parameter > 0 && this.bitOffset + parameter > windowEndBit)) { + // The value does not fit the window; it is left untouched for a reload or the spanning reader. + this.bitOffset = valueStart; + break; + } + this.bitOffset += parameter; + completed++; + this.checkBudget(0); + } + return completed; + } + } + + /** + * Demuxes a FLAC stream. + */ + class FlacDemuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of FlacDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.offset = 0; + this.dataStart = 0; + this.timelineMicros = 0; + /** @type {Object|null} */ + this.streamInfo = null; + /** @type {Uint8Array|null} */ + this.description = null; + this.totalSamples = 0; + this.maxFrameSize = 0; + this.durationSeconds = null; + this.reachedEnd = false; + } + + //+=======================================================================================+ + //| Initialization | + //+=======================================================================================+ + + /** + * Reads the STREAMINFO block and the metadata blocks that follow it, builds the codec private data, and positions the read cursor on the first audio frame. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not a FLAC stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + const magic = await this.reader.readAsync(0, 4); + if (!LuminaAudioPlayer.demuxBytesEqualAscii(magic, 0, FLAC_MAGIC)) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The bytes are not a native FLAC stream.', { reason: 'no-flac-magic' }); + const streamInfo = await this.readStreamInfoAsync(); + if (!streamInfo) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The FLAC stream carries no STREAMINFO block.', { reason: 'no-streaminfo' }); + this.streamInfo = streamInfo; + this.dataStart = streamInfo.dataStart; + this.description = streamInfo.description; + this.totalSamples = streamInfo.totalSamples; + this.maxFrameSize = streamInfo.maxFrameSize; + this.durationSeconds = streamInfo.sampleRate > 0 && streamInfo.totalSamples > 0 + ? streamInfo.totalSamples / streamInfo.sampleRate + : null; + this.offset = this.dataStart; + this.timelineMicros = 0; + this.reachedEnd = false; + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream, including the required FLAC description. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.streamInfo) + return null; + return { + codec: 'flac', + sampleRate: this.streamInfo.sampleRate, + numberOfChannels: this.streamInfo.channels, + description: this.description + }; + } + + /** + * Gets the duration of the stream, from the total sample count STREAMINFO states. + * @returns {number|null} The duration in seconds, or null when it is not stated. + */ + getDuration() { + return this.durationSeconds; + } + + //+=======================================================================================+ + //| Reading | + //+=======================================================================================+ + + /** + * Reads the next FLAC frame as an encoded packet, by walking its bitstream to its exact end. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + if (this.reachedEnd) + return null; + try { + let header = await this.parseHeaderAtAsync(this.offset); + if (!header) { + const resynced = await this.resyncAsync(); + if (resynced < 0) { + this.reachedEnd = true; + return null; + } + header = await this.parseHeaderAtAsync(this.offset); + if (!header) { + this.reachedEnd = true; + return null; + } + } + const frameEnd = await this.measureFrameEndAsync(this.offset, header); + const length = frameEnd - this.offset; + const data = await this.reader.copyAsync(this.offset, length); + if (data.length < length) { + // The bytes of the frame are not all there, which is the end of a truncated stream. + this.reachedEnd = true; + return null; + } + this.verifyFrameCrc16(data); + // The duration is kept unrounded while the timeline accumulates it, so that rounding it per packet does not + // make the timeline drift; only the packet the decoder receives carries a whole number of microseconds. + const duration = (header.blockSize / header.sampleRate) * 1000000; + const packet = LuminaAudioPlayer.createDemuxerPacket(data, this.timelineMicros, duration); + this.timelineMicros += duration; + this.offset = frameEnd; + return packet; + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Repositions the read cursor to the frame that covers a time, using the sample proportion as a byte estimate and + * then scanning to the next frame header, whose coded number states the exact sample it starts at. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a frame gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const end = this.reader.getLength(); + const streamInfo = this.streamInfo; + if (end === null || !streamInfo || !Number.isFinite(seconds) || seconds < 0 || streamInfo.sampleRate <= 0) + return null; + const targetSample = Math.floor(seconds * streamInfo.sampleRate); + let estimate; + if (this.totalSamples > 0) { + const fraction = LuminaAudioPlayer.clamp(targetSample / this.totalSamples, 0, 1); + estimate = this.dataStart + Math.floor(fraction * (end - this.dataStart)); + } else + estimate = this.dataStart + Math.floor((seconds / (this.durationSeconds || 1)) * (end - this.dataStart)); + const start = Math.max(this.dataStart, Math.min(end - 1, estimate)); + const frame = await this.findNextFrameAsync(start, end); + if (frame < 0) + return null; + const header = await this.parseHeaderAtAsync(frame); + this.offset = frame; + this.reachedEnd = false; + // The coded number is the frame number on a fixed blocking stream and the sample number on a variable one, so + // the sample the frame starts at is exact in both cases once the block size of the frame is known. + if (header) { + const sample = header.blockingStrategy === 1 ? header.codedNumber : header.codedNumber * header.blockSize; + // The exact time of the sample the frame starts at, kept unrounded so the timeline it seeds does not drift. + this.timelineMicros = Math.max(0, (sample / streamInfo.sampleRate) * 1000000); + } else + this.timelineMicros = Math.max(0, seconds) * 1000000; + return frame; + } + + //+=======================================================================================+ + //| Frame measurement | + //+=======================================================================================+ + + /** + * Walks a frame from its header to its footer and returns the offset just past it. The walk reads the subframes + * of every channel and the coded residuals they hold, then steps over the zero padding to the byte boundary and + * the 16 bit frame CRC. + * @param {number} frameStart - The absolute offset of the frame's first byte. + * @param {Object} header - The parsed header of the frame. + * @returns {Promise} The absolute offset just past the frame. + * @throws {RangeError} When the frame is malformed, truncated, or longer than its budget. + */ + async measureFrameEndAsync(frameStart, header) { + const base = frameStart + header.headerBytes; + const end = this.reader.getLength(); + const budget = this.maxFrameSize > 0 + ? this.maxFrameSize + FRAME_HEADER_WINDOW_BYTES + : (end !== null ? Math.max(1, end - base) : DEFAULT_MAX_FRAME_BYTES); + const reader = new FlacBitstreamReader(this.reader, { startOffset: base, maxBitOffset: budget * 8 }); + await this.walkSubframesAsync(reader, header); + const misaligned = reader.getBitOffset() % 8; + if (misaligned !== 0) + await reader.skipBitsAsync(8 - misaligned); + await reader.readBitsAsync(16); + return reader.getBytePosition(); + } + + /** + * Walks the subframes of a frame, one per channel, using the bit width each channel's subframe carries under the channel assignment of the frame. + * @param {LuminaAudioPlayer.FlacBitstreamReader} reader - The frame bitstream reader. + * @param {Object} header - The parsed header of the frame. + * @returns {Promise} A promise resolving when every subframe was walked. + */ + async walkSubframesAsync(reader, header) { + const assignment = header.channelAssignment; + const subframes = assignment <= 7 ? assignment + 1 : 2; + for (let index = 0; index < subframes; index++) { + let bitsPerSample = header.bitsPerSample; + // The side channel of a decorrelated stereo pair carries one bit more than the stream's bit depth. + if ((assignment === 8 && index === 1) || (assignment === 9 && index === 0) || (assignment === 10 && index === 1)) + bitsPerSample += 1; + await this.walkSubframeAsync(reader, header.blockSize, bitsPerSample); + } + } + + /** + * Walks one subframe to its end. + * @param {LuminaAudioPlayer.FlacBitstreamReader} reader - The frame bitstream reader. + * @param {number} blockSize - The number of samples of the frame. + * @param {number} sampleBits - The bit width of the subframe, before its wasted bits. + * @returns {Promise} A promise resolving when the subframe was walked. + * @throws {RangeError} When the subframe type is reserved or its parameters are invalid. + */ + async walkSubframeAsync(reader, blockSize, sampleBits) { + const padding = await reader.readBitsAsync(1); + if (padding !== 0) + throw new RangeError('The FLAC subframe does not begin with a zero padding bit.'); + const type = await reader.readBitsAsync(6); + const hasWastedBits = await reader.readBitsAsync(1); + let wastedBits = 0; + if (hasWastedBits !== 0) + wastedBits = (await reader.readUnaryAsync()) + 1; + const bitsPerSample = sampleBits - wastedBits; + if (bitsPerSample <= 0) + throw new RangeError('The FLAC subframe has no bits per sample left.'); + if (type === 0) { + // Constant: one sample value. + await reader.readBitsAsync(bitsPerSample); + return; + } + if (type === 1) { + // Verbatim: every sample, unencoded. + await reader.skipBitsAsync(blockSize * bitsPerSample); + return; + } + if (type >= 8 && type <= 12) { + // Fixed predictor: the order is the low three bits, and it is followed by a coded residual. + const order = type - 8; + await reader.skipBitsAsync(order * bitsPerSample); + await this.walkResidualAsync(reader, blockSize, order); + return; + } + if (type >= 32) { + // LPC: the order is the low five bits plus one, with a precision, a shift and the coefficients before the residual. + const order = (type & 0x1F) + 1; + await reader.skipBitsAsync(order * bitsPerSample); + const precision = (await reader.readBitsAsync(4)) + 1; + if (precision === 16) + throw new RangeError('The FLAC LPC subframe names an invalid coefficient precision.'); + await reader.readBitsAsync(5); + await reader.skipBitsAsync(order * precision); + await this.walkResidualAsync(reader, blockSize, order); + return; + } + throw new RangeError('The FLAC subframe names a reserved type.'); + } + + /** + * Walks the coded residual of a fixed or LPC subframe, partition by partition. Each partition is walked by the + * synchronous fast path of the reader, so the per value awaits that a naive walk would pay are replaced by one + * reload per window; only a value longer than a whole window falls back to the awaited readers. + * @param {LuminaAudioPlayer.FlacBitstreamReader} reader - The frame bitstream reader. + * @param {number} blockSize - The number of samples of the frame. + * @param {number} predictorOrder - The order of the predictor that produced the residual. + * @returns {Promise} A promise resolving when the residual was walked. + * @throws {RangeError} When the residual coding method or its partition sizes are invalid. + */ + async walkResidualAsync(reader, blockSize, predictorOrder) { + const method = await reader.readBitsAsync(2); + if (method > 1) + throw new RangeError('The FLAC residual names a reserved coding method.'); + const parameterBits = method === 0 ? 4 : 5; + const escape = method === 0 ? 15 : 31; + const partitionOrder = await reader.readBitsAsync(4); + const partitions = 1 << partitionOrder; + if (blockSize % partitions !== 0) + throw new RangeError('The FLAC residual partitions do not divide the block evenly.'); + const partitionSamples = blockSize / partitions; + for (let partition = 0; partition < partitions; partition++) { + // Walk each partition in turn; the first one also holds the warm-up samples of the predictor, which are + // not coded as residual values and are therefore skipped from its count. + const count = partition === 0 ? partitionSamples - predictorOrder : partitionSamples; + if (count < 0) + throw new RangeError('The FLAC residual partition is shorter than the predictor order.'); + let parameter = reader.tryReadBits(parameterBits); + if (parameter === null) { + await reader.refillAsync(false); + parameter = reader.tryReadBits(parameterBits); + if (parameter === null) + parameter = await reader.readBitsAsync(parameterBits); + } + if (parameter === escape) { + let rawBits = reader.tryReadBits(5); + if (rawBits === null) { + await reader.refillAsync(false); + rawBits = reader.tryReadBits(5); + if (rawBits === null) + rawBits = await reader.readBitsAsync(5); + } + await reader.skipBitsAsync(count * rawBits); + continue; + } + let remaining = count; + while (remaining > 0) { + if (!reader.isResident()) + await reader.refillAsync(false); + let completed = reader.walkRiceSamples(parameter, remaining); + if (completed === 0) { + // The value was left untouched by a window boundary, so it is retried against a fresh window. + await reader.refillAsync(true); + completed = reader.walkRiceSamples(parameter, remaining); + } + if (completed === 0) { + // A single value longer than a whole window, which only a pathological stream produces: it is walked with the awaited readers, which span windows. + await reader.readUnaryAsync(); + if (parameter > 0) + await reader.readBitsAsync(parameter); + completed = 1; + } + remaining -= completed; + } + } + } + + /** + * Verifies the 16 bit frame CRC against the bytes that were walked. + * @param {Uint8Array} frameBytes - The bytes of the whole frame, ending with the CRC. + * @returns {void} + * @throws {LuminaAudioPlayer.PlayerError} When the checksum does not match. + */ + verifyFrameCrc16(frameBytes) { + if (frameBytes.length < 3) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The FLAC frame is too short to carry a checksum.', { reason: 'frame-crc-mismatch' }); + const length = frameBytes.length; + const expected = LuminaAudioPlayer.demuxReadUintBE(frameBytes, length - 2, 2); + const computed = computeCrc16(frameBytes.subarray(0, length - 2)); + if (expected !== computed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The FLAC frame checksum does not match.', { reason: 'frame-crc-mismatch' }); + } + + //+=======================================================================================+ + //| Internal helpers | + //+=======================================================================================+ + + /** + * Reads the STREAMINFO block and walks the remaining metadata blocks to find where the audio frames begin. + * @returns {Promise} The stream information, or null when STREAMINFO is missing. + */ + async readStreamInfoAsync() { + const blockHeader = await this.reader.readAsync(4, 4); + if (blockHeader.length < 4) + return null; + // The first byte of a metadata block header is the last-block flag in its top bit and the seven bit block type + // below it; the next three bytes are the big endian length of the block body. + const isLast = (blockHeader[0] & 0x80) !== 0; + const blockType = blockHeader[0] & 0x7F; + const length = LuminaAudioPlayer.demuxReadUintBE(blockHeader, 1, 3); + if (blockType !== 0 || length !== STREAMINFO_BODY_BYTES) + return null; + const body = await this.reader.readAsync(8, STREAMINFO_BODY_BYTES); + if (body.length < STREAMINFO_BODY_BYTES) + return null; + const reader = new LuminaAudioPlayer.DemuxerBitReader(body); + const minBlockSize = reader.readBits(16); + const maxBlockSize = reader.readBits(16); + reader.readBits(24); + const maxFrameSize = reader.readBits(24); + const sampleRate = reader.readBits(20); + const channels = reader.readBits(3) + 1; + const bitsPerSample = reader.readBits(5) + 1; + const totalSamples = reader.readBits(36); + if (sampleRate <= 0 || channels <= 0 || minBlockSize < 16 || maxBlockSize < minBlockSize) + return null; + const description = LuminaAudioPlayer.concatDemuxerBytes([ + await this.reader.copyAsync(0, 4), + blockHeader.slice(), + body.slice() + ]); + const dataStart = await this.walkMetadataBlocksAsync(isLast, 4 + 4 + length); + return { + sampleRate, + channels, + bitsPerSample, + totalSamples: totalSamples > 0 ? totalSamples : 0, + maxFrameSize, + description, + dataStart + }; + } + + /** + * Walks the metadata blocks that follow STREAMINFO, to find where the audio frames begin. Like the equivalent walk + * of the WAV demuxer, the number of blocks it will consider is capped, so a stream of zero length blocks that never + * sets the last block flag cannot make the walk do one read per four bytes of the file. + * @param {boolean} isStreamInfoLast - True when STREAMINFO is the last metadata block. + * @param {number} offset - The offset just past the STREAMINFO block. + * @returns {Promise} The offset of the first audio frame. + * @throws {LuminaAudioPlayer.PlayerError} When the stream has more metadata blocks than the player accepts. + */ + async walkMetadataBlocksAsync(isStreamInfoLast, offset) { + let cursor = offset; + let isLast = isStreamInfoLast; + const end = this.reader.getLength(); + let blocks = 0; + while (!isLast && blocks < MAX_METADATA_BLOCKS) { + if (end !== null && cursor >= end) + return cursor; + const header = await this.reader.readAsync(cursor, 4); + if (header.length < 4) + return cursor; + // The same metadata block header as STREAMINFO: the last-block flag is the top bit of the first byte, and the next three bytes are the big endian body length. + isLast = (header[0] & 0x80) !== 0; + const length = LuminaAudioPlayer.demuxReadUintBE(header, 1, 3); + cursor += 4 + length; + blocks++; + } + if (!isLast) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The FLAC stream has more metadata blocks than the player accepts.', { reason: 'metadata-too-many' }); + return cursor; + } + + /** + * Reads the header of a frame at an offset. + * @param {number} offset - The offset of the frame. + * @returns {Promise} The parsed header, or null when the bytes are not a valid frame header. + */ + async parseHeaderAtAsync(offset) { + if (!this.streamInfo) + return null; + const bytes = await this.reader.readAsync(offset, FRAME_HEADER_WINDOW_BYTES); + if (bytes.length < 6) + return null; + return parseFrameHeader(bytes, 0, this.streamInfo); + } + + /** + * Scans for the next frame header consistent with the stream, starting at an offset. It is used from a distance, + * by a seek or a resynchronization, before the frame is walked exactly. + * @param {number} start - The offset to start the scan at. + * @param {number|null} end - The exclusive end of the scan, or null to scan to the end of the stream. + * @returns {Promise} The offset of the next frame header, or -1 when there is none. + * @throws {LuminaAudioPlayer.PlayerError} When the scan gives up on a corrupt or crafted region. + */ + async findNextFrameAsync(start, end) { + return await LuminaAudioPlayer.scanForFrameAsync(this.reader, start, end, FLAC_SYNC_PREFIX, async (offset) => { + const header = await this.parseHeaderAtAsync(offset); + return header !== null; + }, { prefixMask: FLAC_SYNC_MASK }); + } + + /** + * Rescans for the next frame after the current offset deviated from a frame boundary, so that a corrupted or + * partially downloaded region does not stop the stream. + * @returns {Promise} The offset of the next frame header, or -1 when there is none. + * @throws {LuminaAudioPlayer.PlayerError} When the scan gives up on a corrupt or crafted region. + */ + async resyncAsync() { + const end = this.reader.getLength(); + const next = await this.findNextFrameAsync(this.offset + 1, end); + if (next >= 0) + this.offset = next; + return next; + } + } + + LuminaAudioPlayer.FlacDemuxer = FlacDemuxer; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.FLAC, + codec: LuminaAudioPlayer.DemuxerCodec.FLAC, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.FLAC, + create: (options) => new FlacDemuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-mp3.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-mp3.js new file mode 100644 index 00000000..b5b7cd11 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-mp3.js @@ -0,0 +1,443 @@ +/** + * MP3 demuxer of the audio player. + * + * An MP3 file is a stream of MPEG audio frames, each one a self contained frame whose four byte header fully describes + * it: the MPEG version, the layer, the bitrate and the sample rate of the frame, so its length can be computed without + * reading it, and the number of samples it decodes to is fixed by the version and the layer. This demuxer walks those + * frames, hands each one to the decoder as an encoded packet, and derives the sample rate, the channel count and the + * duration from the headers themselves. + * + * The header, and what is read from it + * ------------------------------------ + * The header of a frame gives the MPEG version (MPEG-1, MPEG-2 or MPEG-2.5), the layer (I, II or III), the bitrate, the + * sample rate, whether the frame is padded, and the channel mode. From the version and the layer come the samples per + * frame (1152 for MPEG-1 Layer III, 576 for MPEG-2 or MPEG-2.5 Layer III, and so on), and from those, the bitrate and the + * sample rate comes the length of the frame, which is what makes the next frame directly addressable. Only Layer III is a + * stream the WebCodecs 'mp3' codec decodes, so a file that names another layer is refused as unsupported rather than + * handed to a decoder that cannot decode it, which routes it to server normalization. + * + * Encoder padding and seeking + * --------------------------- + * VBR MP3 files carry an extra, silent MPEG frame at the very start (the Xing/Info header) that holds the frame count, + * the byte count and a 100 entry table of percentage positions, or a VBRI header at a fixed offset instead. The Xing + * frame is not audio: the first real frame follows it, so this demuxer reads it for the duration and the seek table and + * skips it. Without a Xing or VBRI table the stream is assumed to be CBR and the duration is estimated from the file size + * and the bitrate of the first frame. Seeking without a table maps a time to a byte position through that same estimate, + * which is exact for CBR and approximate for a VBR file that lost its table; either way the demuxer then scans forward to + * the next real frame, so the byte it lands on is always a frame boundary. + * + * The codec private data + * ---------------------- + * The WebCodecs 'mp3' codec takes no description: each packet is a whole MPEG frame, header included, and the decoder + * reads the frame header itself. The configuration therefore carries only the codec string, the sample rate and the + * channel count. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The number of header bytes every MPEG frame starts with. + * @readonly + * @type {number} + */ + const MPEG_HEADER_BYTES = 4; + + /** + * The bitrates, in kbps, of the MPEG-1 and MPEG-2/MPEG-2.5 layers, indexed by the four bit bitrate index of the frame + * header. Index 0 is the free format, which this demuxer refuses, and index 15 is invalid and is never looked up. + * @readonly + * @type {Object>>} + */ + const BITRATES = Object.freeze({ + // MPEG-1, indexed by layer (1 = Layer III, 2 = Layer II, 3 = Layer I). + mpeg1: Object.freeze({ + 1: Object.freeze([0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]), + 2: Object.freeze([0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384]), + 3: Object.freeze([0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448]) + }), + // MPEG-2 and MPEG-2.5. + mpeg2: Object.freeze({ + 1: Object.freeze([0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]), + 2: Object.freeze([0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]), + 3: Object.freeze([0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256]) + }) + }); + + /** + * The sample rates, in Hz, indexed by the two bit sample rate index of the frame header, per MPEG version. + * @readonly + * @type {Object>} + */ + const SAMPLE_RATES = Object.freeze({ + mpeg1: Object.freeze([44100, 48000, 32000]), + mpeg2: Object.freeze([22050, 24000, 16000]), + mpeg25: Object.freeze([11025, 12000, 8000]) + }); + + /** + * The eleven bit frame sync of an MPEG audio frame, as the two byte prefix a scan matches on. The mask covers the + * three sync bits of the second byte, so a scan rejects a byte pattern that is not a sync by a comparison instead of + * by an awaited header parse, which matters because a scan's prefix is what decides how many candidates it validates. + * @readonly + * @type {Array} + */ + const MP3_SYNC_PREFIX = Object.freeze([0xFF, 0xE0]); + + /** + * The byte mask of {@link MP3_SYNC_PREFIX}, matching the eleven bit sync exactly. + * @readonly + * @type {Array} + */ + const MP3_SYNC_MASK = Object.freeze([0xFF, 0xE0]); + + /** + * Parses the four byte header of an MPEG audio frame. + * @param {Uint8Array} bytes - The bytes to read the header from. + * @param {number} offset - The offset of the first header byte. + * @returns {Object|null} The parsed header, or null when the bytes are not a valid frame header this demuxer supports. + */ + function parseMpegHeader(bytes, offset) { + if (!bytes || offset < 0 || offset + MPEG_HEADER_BYTES > bytes.length) + return null; + const first = bytes[offset]; + const second = bytes[offset + 1]; + const third = bytes[offset + 2]; + const fourth = bytes[offset + 3]; + // The header is a bit packed big endian structure: eleven sync bits (all ones), two version bits, two layer bits, + // a protection bit that is zero when a CRC follows, the four bit bitrate index and the two bit sample rate index + // in the third byte, a padding bit and a private bit, the two bit channel mode in the top of the fourth byte, and + // then the mode extension, the copyright and original bits and the emphasis. The fields this demuxer needs are + // extracted below, which is why the shifts and masks split the second, third and fourth bytes. + // The eleven bit frame sync is all ones; the two following bits are the version and the next two the layer. + if (first !== 0xFF || (second & 0xE0) !== 0xE0) + return null; + const versionBits = (second >> 3) & 0x03; + const layerBits = (second >> 1) & 0x03; + const bitrateIndex = (third >> 4) & 0x0F; + const sampleRateIndex = (third >> 2) & 0x03; + if (versionBits === 1 || layerBits === 0 || bitrateIndex === 0 || bitrateIndex === 15 || sampleRateIndex === 3) + return null; + const isMpeg1 = versionBits === 3; + const versionKey = isMpeg1 ? 'mpeg1' : 'mpeg2'; + const sampleRateKey = isMpeg1 ? 'mpeg1' : versionBits === 2 ? 'mpeg2' : 'mpeg25'; + const bitrate = BITRATES[versionKey][layerBits][bitrateIndex]; + const sampleRate = SAMPLE_RATES[sampleRateKey][sampleRateIndex]; + if (!bitrate || !sampleRate) + return null; + // Layer III decodes to 1152 samples on MPEG-1 and 576 on MPEG-2 and MPEG-2.5; Layer II always to 1152 and Layer I to 384. + let samplesPerFrame; + if (layerBits === 1) + samplesPerFrame = isMpeg1 ? 1152 : 576; + else if (layerBits === 2) + samplesPerFrame = 1152; + else + samplesPerFrame = 384; + const padding = (third >> 1) & 0x01; + // Layer I pads in four byte slots; the other layers pad in single byte slots. + const frameLength = layerBits === 3 + ? Math.floor((12 * bitrate * 1000) / sampleRate) * 4 + padding * 4 + : Math.floor(((samplesPerFrame / 8) * bitrate * 1000) / sampleRate) + padding; + if (!Number.isFinite(frameLength) || frameLength < MPEG_HEADER_BYTES) + return null; + const channelMode = (fourth >> 6) & 0x03; + const channels = channelMode === 3 ? 1 : 2; + return Object.freeze({ + version: versionBits, + layer: layerBits, + isMpeg1, + samplesPerFrame, + sampleRate, + bitrate, + channels, + frameLength, + crcProtected: (second & 0x01) === 0 + }); + } + + /** + * Demuxes an MP3 (MPEG Layer III) stream. + */ + class Mp3Demuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of Mp3Demuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.offset = 0; + this.dataStart = 0; + this.timelineMicros = 0; + /** @type {Object|null} */ + this.header = null; + this.durationSeconds = null; + this.reachedEnd = false; + /** @type {Uint8Array|null} */ + this.xingToc = null; + } + + //+=======================================================================================+ + //| Initialization | + //+=======================================================================================+ + + /** + * Reads the ID3v2 tag, the first MPEG frame with its Xing or VBRI metadata, and the duration they state, and + * positions the read cursor on the first real audio frame. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not an MP3 stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + const dataStart = await this.skipId3v2Async(0); + const end = this.reader.getLength(); + const firstFrame = await LuminaAudioPlayer.scanForFrameAsync(this.reader, dataStart, end, MP3_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: MP3_SYNC_MASK }); + if (firstFrame < 0) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The bytes do not contain an MPEG audio frame.', { reason: 'no-mpeg-frame' }); + const header = await this.parseHeaderAtAsync(firstFrame); + if (!header) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The MPEG frame header could not be parsed.', { reason: 'no-mpeg-frame' }); + if (header.layer !== 1) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The MPEG stream uses a layer the player does not decode.', { reason: 'unsupported-layer' }); + const metadata = await this.readVariableRateMetadataAsync(firstFrame, header); + this.dataStart = metadata ? firstFrame + header.frameLength : firstFrame; + this.offset = this.dataStart; + this.header = header; + this.durationSeconds = this.resolveDuration(header, metadata, end); + this.xingToc = metadata && metadata.toc ? metadata.toc : null; + this.timelineMicros = 0; + this.reachedEnd = false; + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.header) + return null; + return { + codec: 'mp3', + sampleRate: this.header.sampleRate, + numberOfChannels: this.header.channels + }; + } + + /** + * Gets the duration of the stream, from the Xing or VBRI frame count when there is one and from the file size + * otherwise. + * @returns {number|null} The duration in seconds, or null when it cannot be derived. + */ + getDuration() { + return this.durationSeconds; + } + + //+=======================================================================================+ + //| Reading | + //+=======================================================================================+ + + /** + * Reads the next MPEG frame as an encoded packet. A byte that is not the start of a valid frame is skipped by + * rescanning for the next frame sync, so a corrupted or partially downloaded region does not stop the stream. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + if (this.reachedEnd) + return null; + try { + const header = await this.parseHeaderAtAsync(this.offset); + if (!header) { + return await this.resyncAsync(); + } + const data = await this.reader.readAsync(this.offset, header.frameLength); + if (data.length < header.frameLength) { + // The last frame is incomplete, which is the end of a partially downloaded or truncated stream. + this.reachedEnd = true; + return null; + } + // The duration is kept unrounded while the timeline accumulates it, so that rounding it per packet does not + // make the timeline drift; only the packet the decoder receives carries a whole number of microseconds. + const duration = (header.samplesPerFrame / header.sampleRate) * 1000000; + const packet = LuminaAudioPlayer.createDemuxerPacket(data.slice(), this.timelineMicros, duration); + this.timelineMicros += duration; + this.offset += header.frameLength; + return packet; + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Rescans for the next valid frame after a byte that is not the start of one. + * @returns {Promise} The next packet, or null when no further frame is found. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async resyncAsync() { + const end = this.reader.getLength(); + const next = await LuminaAudioPlayer.scanForFrameAsync(this.reader, this.offset + 1, end, MP3_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: MP3_SYNC_MASK }); + if (next < 0) { + this.reachedEnd = true; + return null; + } + this.offset = next; + return await this.readPacketAsync(); + } + + /** + * Repositions the read cursor to the frame that covers a time, using the Xing table when the stream has one and + * the constant bitrate estimate otherwise, and then scanning to the next real frame. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a frame gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const end = this.reader.getLength(); + if (end === null || !Number.isFinite(seconds) || this.durationSeconds === null || this.durationSeconds <= 0) + return null; + const fraction = LuminaAudioPlayer.clamp(seconds / this.durationSeconds, 0, 1); + let estimate; + if (this.xingToc) { + const index = Math.min(99, Math.floor(fraction * 100)); + const byteFraction = this.xingToc[index] / 256; + estimate = this.dataStart + Math.floor(byteFraction * (end - this.dataStart)); + } else { + const bitrate = this.header ? this.header.bitrate * 1000 : 128000; + estimate = this.dataStart + Math.floor((seconds * bitrate) / 8); + } + const start = Math.max(this.dataStart, Math.min(end - 1, estimate)); + const frame = await LuminaAudioPlayer.scanForFrameAsync(this.reader, start, end, MP3_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: MP3_SYNC_MASK }); + if (frame < 0) + return null; + this.offset = frame; + this.reachedEnd = false; + // The exact sample position of the frame is not known without walking the stream from the start, so the + // timeline is seeded with the requested time, kept unrounded so the timeline it starts does not drift, and the + // seek stage uses it as the target to trim the first packet to. + this.timelineMicros = Math.max(0, seconds) * 1000000; + return frame; + } + + //+=======================================================================================+ + //| Internal helpers | + //+=======================================================================================+ + + /** + * Reads the header of a frame at an offset. + * @param {number} offset - The offset of the frame. + * @returns {Promise} The parsed header, or null when the bytes are not a valid frame header. + */ + async parseHeaderAtAsync(offset) { + const bytes = await this.reader.readAsync(offset, MPEG_HEADER_BYTES); + if (bytes.length < MPEG_HEADER_BYTES) + return null; + return parseMpegHeader(bytes, 0); + } + + /** + * Checks whether a candidate offset is the start of a real frame, by parsing its header and, unless it is the + * last frame of a known length stream, by requiring the frame that follows it to parse as well with the same + * version, layer and sample rate. That second frame is what rejects a byte pattern inside frame data. + * @param {number} offset - The candidate offset. + * @returns {Promise} True when the offset is the start of a real frame. + */ + async isValidFrameAtAsync(offset) { + const header = await this.parseHeaderAtAsync(offset); + if (!header || header.layer !== 1) + return false; + const end = this.reader.getLength(); + const next = offset + header.frameLength; + if (end !== null && next + MPEG_HEADER_BYTES > end) + return true; + const nextHeader = await this.parseHeaderAtAsync(next); + if (!nextHeader) + return false; + return nextHeader.version === header.version + && nextHeader.layer === header.layer + && nextHeader.sampleRate === header.sampleRate; + } + + /** + * Reads the Xing, Info or VBRI metadata of the first frame, when that frame is a metadata frame rather than audio. + * @param {number} frameStart - The offset of the first frame. + * @param {Object} header - The parsed header of the first frame. + * @returns {Promise} The metadata, with the frame count and the seek table, or null when the first frame is real audio. + */ + async readVariableRateMetadataAsync(frameStart, header) { + const crcBytes = header.crcProtected ? 2 : 0; + const sideInfoBytes = header.isMpeg1 ? (header.channels === 1 ? 17 : 32) : (header.channels === 1 ? 9 : 17); + // The Xing or Info tag sits right after the header and the side info; the VBRI tag sits at a fixed offset from + // the frame start. Both are read from one window so neither field is fetched twice. + const window = await this.reader.readAsync(frameStart, header.frameLength); + if (window.length < MPEG_HEADER_BYTES) + return null; + const xingOffset = MPEG_HEADER_BYTES + crcBytes + sideInfoBytes; + const isXing = LuminaAudioPlayer.demuxBytesEqualAscii(window, xingOffset, 'Xing') + || LuminaAudioPlayer.demuxBytesEqualAscii(window, xingOffset, 'Info'); + let cursor = -1; + if (isXing) + cursor = xingOffset + 4; + else if (LuminaAudioPlayer.demuxBytesEqualAscii(window, MPEG_HEADER_BYTES + 32, 'VBRI')) + cursor = MPEG_HEADER_BYTES + 32 + 4 + 2 + 2 + 2; + if (cursor < 0) + return null; + const isVbri = !isXing; + let frameCount = null; + let toc = null; + if (isVbri) // VBRI: bytes (4), frames (4), then a two entry-per-percent table this demuxer does not use. + frameCount = LuminaAudioPlayer.demuxReadUintBE(window, cursor + 4, 4); + else { + const flags = LuminaAudioPlayer.demuxReadUintBE(window, cursor, 4) || 0; + cursor += 4; + if ((flags & 0x01) !== 0) { + frameCount = LuminaAudioPlayer.demuxReadUintBE(window, cursor, 4); + cursor += 4; + } + if ((flags & 0x02) !== 0) // The byte count the tag may carry is not needed, but its four bytes still shift the seek table. + cursor += 4; + if ((flags & 0x04) !== 0) { + const raw = await this.reader.copyAsync(frameStart + cursor, 100); + if (raw.length === 100) + toc = raw; + } + } + return { frameCount, toc }; + } + + /** + * Resolves the duration of the stream from the metadata of its first frame, or from the file size and the first frame's bitrate when the stream carries no metadata. + * @param {Object} header - The parsed header of the first real frame. + * @param {Object|null} metadata - The Xing or VBRI metadata, or null. + * @param {number|null} end - The length of the stream, or null when it is unknown. + * @returns {number|null} The duration in seconds, or null when it cannot be derived. + */ + resolveDuration(header, metadata, end) { + if (metadata && Number.isFinite(metadata.frameCount) && metadata.frameCount > 0) + return (metadata.frameCount * header.samplesPerFrame) / header.sampleRate; + if (end === null) + return null; + const bytes = end - this.dataStart; + const bitrate = header.bitrate * 1000; + if (bitrate <= 0 || bytes <= 0) + return null; + return (bytes * 8) / bitrate; + } + } + + LuminaAudioPlayer.Mp3Demuxer = Mp3Demuxer; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.MP3, + codec: LuminaAudioPlayer.DemuxerCodec.MP3, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.MP3, + create: (options) => new Mp3Demuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-ogg.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-ogg.js new file mode 100644 index 00000000..00552480 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-ogg.js @@ -0,0 +1,1113 @@ +/** + * OGG demuxer of the audio player, for the Opus and Vorbis codecs. + * + * An OGG file is a sequence of pages, each one a header followed by a segment table and the page's data. The segmented + * data is not framed by bytes but by lacing: a run of lacing values of 255 means the packet continues, and a value below + * 255 ends a packet, so a packet may span several pages and a page may hold several packets. A page also carries a + * granule position, which is the position, in the codec's own sample unit, of the last packet that completed on the page, + * a serial number, so that several logical streams can be multiplexed into one physical stream, and a CRC-32 over the + * whole page, which this demuxer verifies so that a corrupt page, or a byte pattern that merely looks like a page + * capture, is never read as data. + * + * This module owns the page and packet assembly once, in the OggDemuxer base, and the two codec specific demuxers only + * describe their identification headers, the codec private data WebCodecs needs, and how a packet's duration is measured. + * The registry maps both the OGG/OPUS and the OGG/VORBIS pair to their demuxer. + * + * Telling the two apart + * --------------------- + * The first packet of the logical stream identifies the codec: it begins with 'OpusHead' for Opus and, for Vorbis, with + * a packet type byte of 0x01 followed by 'vorbis'. Everything after the identification header is a codec header packet + * (OpusTags for Opus, the comment and setup headers for Vorbis) that is not audio, and this demuxer consumes those during + * initialization, so the first packet readPacketAsync returns is audio. + * + * Timestamps and the granule position + * ----------------------------------- + * A granule is a count of samples for Vorbis and a count of 48 kHz samples, including the pre-skip the encoder inserted, + * for Opus. The page granule gives the end position of its last completed packet exactly, so this demuxer anchors the + * timeline to it at every page boundary and derives the packets that precede it, on the same page, by summing their own + * durations from the packed packet header (the table of contents byte of an Opus packet, the block size bit of a Vorbis + * packet). The pre-skip of an Opus stream is subtracted, because the WebCodecs decoder discards those priming samples + * itself when the description carries the OpusHead, so the first decoded sample is reported at time zero. + * + * Seeking + * ------- + * Page granule positions are non decreasing, so seeking is a bisection over the byte offsets of the stream: it reads the + * page at the middle of the search interval and narrows the interval by its granule, which converges to the first page + * whose granule is at or after the target in a logarithmic number of page reads, and never walks the stream. When that + * page carries the continuation flag, its first packet began on the previous page, so the seek steps back one page, whose + * exact end was verified, so that the packet is assembled from its true start. A seek never lands on a page of codec + * headers either: the cursor is brought forward to the first page that holds audio, and a page that still carries a header + * packet, which can happen when a setup header shares a page with audio, has that packet filtered out as well. + * + * The codec private data + * ---------------------- + * - Opus: the description is the OpusHead identification header, which also tells the decoder the pre-skip to discard. + * - Vorbis: the description is the Xiph extradata format the WebCodecs registration requires: a byte with the count of + * lacing values, the lacing values themselves, and then the identification, comment and setup header packets. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The four byte capture pattern every OGG page starts with. + * @readonly + * @type {Array} + */ + const OGG_CAPTURE_PATTERN = Object.freeze([0x4F, 0x67, 0x67, 0x53]); + + /** + * The number of bytes of an OGG page header, before the segment table. + * @readonly + * @type {number} + */ + const OGG_PAGE_HEADER_BYTES = 27; + + /** + * The offset of the CRC field of an OGG page header, which is zeroed while the checksum is computed. + * @readonly + * @type {number} + */ + const OGG_CRC_OFFSET = 22; + + /** + * The largest size a single OGG page can have: the fixed header, the largest segment table, and the largest payload + * the lacing values can describe. A candidate that claims more is not a page, and the bound is what keeps a crafted + * length field from making a scan read and checksum an arbitrarily large span. + * @readonly + * @type {number} + */ + const OGG_MAX_PAGE_BYTES = OGG_PAGE_HEADER_BYTES + 255 + 255 * 255; + + /** + * The number of candidate pages a single scan may read in full and checksum before it gives up. A stream whose body is + * filled with the capture pattern, with header fields crafted to pass the cheap structural checks, can surround a real + * page with thousands of false candidates; the cheap checks reject most of them, and this budget bounds the rest, so a + * scan can never be turned into unbounded checksum and allocation work. + * @readonly + * @type {number} + */ + const OGG_MAX_SCAN_VALIDATIONS = 1024; + + /** + * The number of pages a single seek may step back over when the page it landed on is a continuation of a packet that + * began earlier. A packet that spans this many pages is far past anything a real stream produces, so the bound only + * stops a pathological one; the shared validation budget of the seek bounds the work underneath it. + * @readonly + * @type {number} + */ + const OGG_MAX_CONTINUED_STEPS = 255; + + /** + * The number of bytes a single page lookup scans before it gives up. A valid stream has no gaps between pages, so the + * page at or after any offset starts within one page length of it; the bound keeps a stream whose middle is filled + * with the capture pattern from making one lookup walk an arbitrarily long region. + * @readonly + * @type {number} + */ + const OGG_SCAN_SPAN_BYTES = OGG_MAX_PAGE_BYTES * 2; + + /** + * The largest packet this demuxer will assemble. A packet may span any number of pages, and the parts of one are held + * until it is complete, so without a cap a crafted stream could make a single packet hold the whole stream in memory. + * The cap is far past any real audio packet of the supported codecs, so it only ever refuses a crafted one. + * @readonly + * @type {number} + */ + const OGG_MAX_PACKET_BYTES = 16 * 1024 * 1024; + + /** + * Draws one unit from a shared scan budget, reporting whether a unit was available. Every unit of work a seek does + * that is proportional to the bytes or the page patterns of the stream draws from the same budget: the window read + * that precedes a scan, each cheap header probe, and each full page validation. That is what keeps a crafted stream + * from multiplying the work of a seek by the number of its steps. + * @param {{ remaining: number }} budget - The shared budget. + * @returns {boolean} True when a unit was available and was consumed. + */ + function consumeBudget(budget) { + if (budget.remaining <= 0) + return false; + budget.remaining--; + return true; + } + + /** + * The number of bytes of the tail read to find the last page of a stream. + * @readonly + * @type {number} + */ + const OGG_TAIL_BYTES = 65536; + + /** + * The number of bytes read before a page to find the page that precedes it when a seek lands on a continued page. + * @readonly + * @type {number} + */ + const OGG_PREVIOUS_WINDOW_BYTES = 131072; + + /** + * The number of samples per second a granule of an Opus stream counts at, fixed by the Opus format. + * @readonly + * @type {number} + */ + const OPUS_GRANULE_RATE = 48000; + + /** + * The duration, in milliseconds, of one Opus frame per configuration number, indexed by the five bit configuration + * of the packet's table of contents byte (RFC 6716, table 2). + * @readonly + * @type {Array} + */ + const OPUS_FRAME_DURATION_MS = Object.freeze([ + 10, 20, 40, 60, 10, 20, 40, 60, 10, 20, 40, 60, + 10, 20, 10, 20, + 2.5, 5, 10, 20, 2.5, 5, 10, 20, 2.5, 5, 10, 20, 2.5, 5, 10, 20 + ]); + + /** + * The header type flag of an OGG page that marks a continued packet. + * @readonly + * @type {number} + */ + const OGG_CONTINUED_FLAG = 0x01; + + /** + * The lookup table of the OGG page checksum, built once for the life of the page. It turns the checksum from eight + * bit iterations to one byte lookup per byte of a page. + * @readonly + * @type {Uint32Array} + */ + const OGG_CRC_TABLE = LuminaAudioPlayer.demuxBuildCrcTable(0x04C11DB7, 32); + + /** + * Computes the CRC-32 of an OGG page, with the polynomial 0x04C11DB7 and an initial value of zero, over the page + * with its CRC field read as zero, as the framing specification defines it. The zeroed field is passed as a range + * rather than applied to a copy, so a page is never duplicated just to compute its checksum. + * @param {Uint8Array} bytes - The page bytes. + * @param {number} [zeroStart] - The first byte of the field to read as zero, or -1 for none. + * @param {number} [zeroLength] - The number of bytes of the field to read as zero. + * @returns {number} The checksum. + */ + function computeOggCrc(bytes, zeroStart = -1, zeroLength = 0) { + const zeroEnd = zeroStart + zeroLength; + let crc = 0; + for (let index = 0; index < bytes.length; index++) { + const byte = index >= zeroStart && index < zeroEnd ? 0 : bytes[index]; + crc = ((crc << 8) ^ OGG_CRC_TABLE[((crc >>> 24) ^ byte) & 0xFF]) >>> 0; + } + return crc >>> 0; + } + + /** + * Demuxes an OGG logical stream, owning the page and packet assembly and leaving the codec specifics to a subclass. + */ + class OggDemuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of OggDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.pageOffset = 0; + this.currentSerial = null; + // The offset of the last page read from the logical stream, and the offset of the first page that holds audio. + this.lastPageOffset = null; + this.audioStartOffset = null; + /** @type {Array} */ + this.pendingParts = []; + // The number of bytes the parts of the packet being assembled hold, so the assembled packet size is bounded without having to concatenate them first. + this.pendingLength = 0; + /** @type {Array<{ data: Uint8Array, granule: number|null }>} */ + this.pendingPackets = []; + this.lastGranule = null; + this.durationSeconds = null; + // True once the duration was taken from the last page, so that the granule of an intermediate page, which is + // the position reached and not the length of the stream, never overwrites it. + this.durationIsFinal = false; + this.reachedEnd = false; + this.seekResync = false; + this.timelineMicros = 0; + } + + //+=======================================================================================+ + //| Reading | + //+=======================================================================================+ + + /** + * Reads the next packet of the logical stream, assembling it across pages when it spans them. + * @returns {Promise<{ data: Uint8Array, granule: number|null }|null>} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the page structure is corrupt. + */ + async readRawPacketAsync() { + while (this.pendingPackets.length === 0) { + if (this.reachedEnd) + return null; + await this.readNextPageAsync(); + } + return this.pendingPackets.shift(); + } + + /** + * Reads the next audio packet of the logical stream as a demuxer packet, skipping any codec header packet it + * meets. Initialization consumes the header packets of a stream once, but a seek may reposition the read cursor + * onto a page that also carries them, so they are filtered here as well rather than only during initialization. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the page structure is corrupt. + */ + async readNextAudioPacketAsync() { + let packet = await this.readRawPacketAsync(); + while (packet && this.isHeaderPacket(packet.data)) + packet = await this.readRawPacketAsync(); + if (!packet) + return null; + const duration = this.computePacketDurationMicros(packet.data); + const timestamp = packet.granule !== null + ? Math.max(0, this.granuleToMicros(packet.granule) - duration) + : this.timelineMicros; + this.timelineMicros = timestamp + duration; + return LuminaAudioPlayer.createDemuxerPacket(packet.data, timestamp, duration); + } + + /** + * Reads the next page and turns its lacing values into queued packets, carrying a packet that spans pages over to the next one. + * @returns {Promise} A promise resolving when the page was consumed. + * @throws {LuminaAudioPlayer.PlayerError} When the page structure is corrupt. + */ + async readNextPageAsync() { + const page = await this.readPageAsync(this.pageOffset); + if (!page) { + this.reachedEnd = true; + return; + } + this.pageOffset = page.nextOffset; + if (this.currentSerial === null) + this.currentSerial = page.serial; + // A physical stream can multiplex several logical streams; only the one this demuxer locked onto is read. + if (page.serial !== this.currentSerial) + return; + this.lastPageOffset = page.offset; + if (page.granule !== null) { + this.lastGranule = page.granule; + // Only an unknown length is tracked from page to page; when the last page was already probed, the granule + // of an intermediate page would replace the total with the position reached so far. + if (!this.durationIsFinal) + this.refreshDuration(); + } + const isContinued = (page.headerType & OGG_CONTINUED_FLAG) !== 0; + if (isContinued !== (this.pendingParts.length > 0)) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG page continuation flags do not line up.', { reason: 'invalid-continuation' }); + const completions = []; + let dataOffset = 0; + // The segment table is a list of lacing values. A value of 255 means the packet continues into the next + // segment, and possibly the next page, while any value below 255 ends the packet it belongs to, so a packet + // completes exactly when such a value is reached. + for (const lace of page.segments) { + const slice = page.data.subarray(dataOffset, dataOffset + lace); + dataOffset += lace; + this.pendingParts.push(slice); + this.pendingLength += lace; + if (lace < 255) { + completions.push(LuminaAudioPlayer.concatDemuxerBytes(this.pendingParts)); + this.pendingParts = []; + this.pendingLength = 0; + } + } + // A packet can span any number of pages, and its parts are held until it completes, so its size is bounded here + // rather than left to whatever the stream claims. + if (this.pendingLength > OGG_MAX_PACKET_BYTES) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG packet being assembled exceeds the size the player accepts.', { reason: 'packet-too-large' }); + const lastCompletion = completions.length - 1; + for (let index = 0; index < completions.length; index++) + this.pendingPackets.push({ data: completions[index], granule: index === lastCompletion ? page.granule : null }); + } + + /** + * Reads and validates the fixed part of a page header, without reading the segment table or the payload. It is the + * cheap structural gate a scan runs on every capture pattern: the version and the reserved header type bits reject + * a false capture before any page sized buffer is allocated or any checksum computed. The page size bound depends + * on the lacing values, so it can only be enforced once the segment table is read, in {@link LuminaAudioPlayer.OggDemuxer#finishPageAsync}. + * @param {number} offset - The offset of the candidate capture pattern. + * @returns {Promise} An object with a kind of 'page', 'not-a-page' or 'unsupported-version', and, for a page, the parsed header fields. + */ + async readPageHeaderAsync(offset) { + if (offset < 0) + return { kind: 'not-a-page' }; + const header = await this.reader.readAsync(offset, OGG_PAGE_HEADER_BYTES); + if (header.length < OGG_PAGE_HEADER_BYTES || !LuminaAudioPlayer.demuxBytesEqualAscii(header, 0, 'OggS')) + return { kind: 'not-a-page' }; + if (header[4] !== 0) + return { kind: 'unsupported-version' }; + // Only the three defined header type flags may be set; any other bit is reserved, which marks a false capture. + if ((header[5] & 0xF8) !== 0) + return { kind: 'not-a-page' }; + // The fixed part of a page header is the four byte capture pattern, one byte version, one byte header type + // flags, the eight byte granule position, the four byte serial, the four byte sequence number, the four byte + // checksum and one byte segment count; the segment table and the payload follow it. + return { + kind: 'page', + headerType: header[5], + granule: LuminaAudioPlayer.demuxReadInt64LE(header, 6), + serial: LuminaAudioPlayer.demuxReadUintLE(header, 14, 4), + storedCrc: LuminaAudioPlayer.demuxReadUintLE(header, OGG_CRC_OFFSET, 4), + pageSegments: header[26] + }; + } + + /** + * Reads and validates one OGG page, including its CRC-32. + * @param {number} offset - The offset of the page's capture pattern. + * @param {Object} [options] - The options. + * @param {boolean} [options.strict] - True to treat a checksum mismatch or an unsupported version as a failure; false to report it as 'not a page'. Defaults to true, and a probe or a scan uses false. + * @param {number|null} [options.serial] - The serial a page must carry to be accepted, or null to accept any. A scan passes the serial of its logical stream. + * @returns {Promise} The page, or null at the end of the stream, at a truncated page, or at a page a non strict read refused. + * @throws {LuminaAudioPlayer.PlayerError} When a strict read finds an unsupported version or a checksum mismatch. + */ + async readPageAsync(offset, options = {}) { + const strict = options.strict !== false; + const probe = await this.readPageHeaderAsync(offset); + if (probe.kind === 'not-a-page') + return null; + if (probe.kind === 'unsupported-version') { + if (!strict) + return null; + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG page uses an unsupported version.', { reason: 'unsupported-ogg-version' }); + } + if (options.serial !== undefined && options.serial !== null && probe.serial !== options.serial) + return null; + return await this.finishPageAsync(offset, probe, strict); + } + + /** + * Reads the segment table and the payload of a page whose header a caller already validated, computes the + * checksum over the page with its own CRC field read as zero, and returns the page. The data a page carries is + * exposed as a view of the one buffer that was read, so validating a page allocates a single page sized buffer. + * @param {number} offset - The offset of the page's capture pattern. + * @param {Object} probe - The parsed header, per {@link LuminaAudioPlayer.OggDemuxer#readPageHeaderAsync}. + * @param {boolean} strict - True to treat a checksum mismatch as a failure, false to report it as 'not a page'. + * @returns {Promise} The page, or null when it is truncated or refused. + * @throws {LuminaAudioPlayer.PlayerError} When a strict read finds a checksum mismatch. + */ + async finishPageAsync(offset, probe, strict) { + const segmentTable = await this.reader.readAsync(offset + OGG_PAGE_HEADER_BYTES, probe.pageSegments); + if (segmentTable.length < probe.pageSegments) + return null; + let dataLength = 0; + for (let index = 0; index < probe.pageSegments; index++) + dataLength += segmentTable[index]; + // The length is bounded by the page structure itself: at most 255 lacing values of at most 255 bytes each, so it can never exceed OGG_MAX_PAGE_BYTES and needs no separate check. + const totalLength = OGG_PAGE_HEADER_BYTES + probe.pageSegments + dataLength; + const pageBytes = await this.reader.copyAsync(offset, totalLength); + if (pageBytes.length < totalLength) + return null; + if (computeOggCrc(pageBytes, OGG_CRC_OFFSET, 4) !== (probe.storedCrc >>> 0)) { + if (!strict) + return null; + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG page checksum does not match.', { reason: 'page-crc-mismatch' }); + } + return Object.freeze({ + offset, + headerType: probe.headerType, + granule: probe.granule !== null && probe.granule >= 0 ? probe.granule : null, + serial: probe.serial, + segments: segmentTable.slice(), + data: pageBytes.subarray(OGG_PAGE_HEADER_BYTES + probe.pageSegments), + nextOffset: offset + totalLength + }); + } + + /** + * Finds the first page whose capture pattern is at or after an offset and before a limit, skipping a pattern that + * is not a valid page. A candidate is filtered by the cheap structural gate first, and only a candidate that + * passes it is read in full and checksummed, drawing from the caller's budget, so that a whole seek shares one + * bound instead of giving each of its steps a fresh one. + * @param {number} offset - The offset to start the search at. + * @param {number|null} [limit] - The exclusive end of the search, or null to search to the end of the stream. + * @param {{ remaining: number }} [budget] - The shared validation budget, or null for a fresh one. + * @returns {Promise} The page, or null when there is none before the limit. + * @throws {LuminaAudioPlayer.PlayerError} When the scan gives up on a corrupt or crafted region. + */ + async findPageAtOrAfterAsync(offset, limit, budget) { + const end = this.reader.getLength(); + let scanLimit; + if (limit === null || limit === undefined) + scanLimit = end; + else + scanLimit = end === null ? limit : Math.min(limit, end); + const shared = budget || { remaining: OGG_MAX_SCAN_VALIDATIONS }; + // The scan itself reads a window, so it draws a unit before it does anything. + if (!consumeBudget(shared)) + return null; + let cursor = Math.max(0, Math.floor(offset)); + // A capture pattern that turns out not to be a valid page is skipped and the search resumes just past it, so + // the loop repeats until a page is accepted or the cursor reaches the end of the search limit. + while (scanLimit === null || cursor < scanLimit) { + const found = await LuminaAudioPlayer.scanForFrameAsync(this.reader, cursor, scanLimit, OGG_CAPTURE_PATTERN, async (candidate) => { + // A cheap header probe is a unit of work too, so a stream whose body is tiled with capture patterns + // that fail the gate cannot make a seek do an unbounded number of probes. + if (!consumeBudget(shared)) + return false; + const probe = await this.readPageHeaderAsync(candidate); + return probe.kind === 'page' && (this.currentSerial === null || probe.serial === this.currentSerial); + }); + if (found < 0) + return null; + if (!consumeBudget(shared)) + return null; + const page = await this.readPageAsync(found, { strict: false, serial: this.currentSerial }); + if (page) + return page; + cursor = found + 1; + } + return null; + } + + /** + * Finds the page that ends exactly at an offset, used to step back over a continued packet. Each candidate is + * filtered by the cheap structural gate, and the full reads draw from the caller's shared budget. + * @param {number} offset - The offset a page ends at. + * @param {{ remaining: number }} [budget] - The shared validation budget, or null for a fresh one. + * @returns {Promise} The preceding page, or null when it cannot be found. + */ + async findPreviousPageAsync(offset, budget) { + const start = Math.max(0, offset - OGG_PREVIOUS_WINDOW_BYTES); + if (offset <= start) + return null; + const shared = budget || { remaining: OGG_MAX_SCAN_VALIDATIONS }; + // The window read is a unit of work, so it draws one before it is done. + if (!consumeBudget(shared)) + return null; + const bytes = await this.reader.copyAsync(start, offset - start); + for (let index = bytes.length - OGG_CAPTURE_PATTERN.length; index >= 0; index--) { + if (!LuminaAudioPlayer.demuxBytesEqualAscii(bytes, index, 'OggS')) + continue; + const candidateOffset = start + index; + if (!consumeBudget(shared)) + return null; + const probe = await this.readPageHeaderAsync(candidateOffset); + if (probe.kind !== 'page' || (this.currentSerial !== null && probe.serial !== this.currentSerial)) + continue; + if (!consumeBudget(shared)) + return null; + const candidate = await this.finishPageAsync(candidateOffset, probe, false); + if (candidate && candidate.nextOffset === offset) + return candidate; + } + return null; + } + + //+=======================================================================================+ + //| Duration | + //+=======================================================================================+ + + /** + * Gets the duration of the logical stream. When the total length of the stream is known, it is the exact duration, + * taken from the granule of the last page. When the length is unknown, it is a progressive estimate from the granule + * of the last page read so far, so it grows as more of the stream is read and is only final once the last page has + * been seen; durationIsFinal reports which of the two it is. + * @returns {number|null} The duration in seconds, or null when no page with a granule has been read yet. + */ + getDuration() { + return this.durationSeconds; + } + + /** + * Refreshes the known duration from the last granule read. + */ + refreshDuration() { + if (this.lastGranule === null) + return; + const micros = this.granuleToMicros(this.lastGranule); + if (Number.isFinite(micros) && micros >= 0) + this.durationSeconds = micros / 1000000; + } + + /** + * Reads the granule position of the last page of the stream, when the length of the stream is known. It is what + * gives the duration before the end of the stream is reached. A candidate is filtered by the cheap structural gate + * first, and only a candidate that passes it is read in full and checksummed; the tail is bounded, and the cheap + * probes and the full validations both draw from one budget, so a tail filled with the capture pattern cannot turn + * this into unbounded work. + * @returns {Promise} The last granule, or null when it cannot be read. + */ + async probeLastGranuleAsync() { + const tail = await this.reader.readTailAsync(OGG_TAIL_BYTES); + if (!tail) + return null; + const bytes = tail.bytes; + const budget = { remaining: OGG_MAX_SCAN_VALIDATIONS }; + for (let index = bytes.length - OGG_CAPTURE_PATTERN.length; index >= 0; index--) { + if (!LuminaAudioPlayer.demuxBytesEqualAscii(bytes, index, 'OggS')) + continue; + const offset = tail.offset + index; + if (!consumeBudget(budget)) + return null; + const probe = await this.readPageHeaderAsync(offset); + if (probe.kind !== 'page' || (this.currentSerial !== null && probe.serial !== this.currentSerial)) + continue; + if (!consumeBudget(budget)) + return null; + const candidate = await this.finishPageAsync(offset, probe, false); + if (candidate && candidate.granule !== null) { + this.currentSerial = candidate.serial; + return candidate.granule; + } + } + return null; + } + + //+=======================================================================================+ + //| Seeking | + //+=======================================================================================+ + + /** + * Repositions the read cursor to the page that holds a time. Page granule positions are non decreasing, so the + * offset of the first page that ends at or after the target is found by a lower bound binary search over byte + * offsets: each step reads the page at or after the middle of the search interval and narrows it by whether that + * page already reaches the target. Every step shares one validation budget, and each page lookup only scans a + * bounded span, so the whole seek is bounded even against a stream whose middle is filled with the capture pattern. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a page gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const end = this.reader.getLength(); + if (end === null || !Number.isFinite(seconds) || seconds < 0) + return null; + // The target is clamped to the duration only when that duration is final. While the total length of the stream + // is unknown, the duration is a progressive estimate from the pages read so far, and clamping to it would land + // the seek short of the requested time; without a clamp the binary search positions on the granules themselves. + const targetMicros = this.durationIsFinal && this.durationSeconds > 0 + ? Math.min(seconds, this.durationSeconds) * 1000000 + : seconds * 1000000; + // One budget for the whole seek, shared by the binary search and the step back over a continued packet. + const budget = { remaining: OGG_MAX_SCAN_VALIDATIONS }; + let low = 0; + let high = end - 1; + let iterations = 0; + while (low < high && iterations < 64 && budget.remaining > 0) { + iterations++; + const middle = Math.floor((low + high) / 2); + const page = await this.findPageAtOrAfterAsync(middle, Math.min(end, middle + OGG_SCAN_SPAN_BYTES), budget); + // A page that is missing past the last page start means the interval is past the end, which counts as + // reaching the target, so the lower bound narrows onto the last page rather than running past it. + const reachesTarget = page === null || (page.granule !== null && this.granuleToMicros(page.granule) >= targetMicros); + if (reachesTarget) + high = middle; + else + low = middle + 1; + } + let result = await this.findPageAtOrAfterAsync(low, Math.min(end, low + OGG_SCAN_SPAN_BYTES), budget); + if (!result) + result = await this.findPageAtOrAfterAsync(0, Math.min(end, OGG_SCAN_SPAN_BYTES), budget); + if (!result) + return null; + // A seek must never land on a page of codec headers: the identification, comment and setup packets are not + // audio, so the cursor is brought forward to the first page that holds audio. + if (this.audioStartOffset !== null && result.offset < this.audioStartOffset) { + const firstAudioPage = await this.findPageAtOrAfterAsync(this.audioStartOffset, Math.min(end, this.audioStartOffset + OGG_SCAN_SPAN_BYTES), budget); + if (firstAudioPage) + result = firstAudioPage; + } + // A continued page starts in the middle of a packet, so the walk steps back over every continued page until it + // reaches the page that actually starts the packet, so a packet that spans more than two pages is assembled + // from its true start. The walk is allowed to cross the first page that holds audio, because a large setup + // header can continue into that page, and the codec header packets it would then read there are filtered out + // on the read path by isHeaderPacket, so crossing can never re-emit a header as audio. + let steps = 0; + while ((result.headerType & OGG_CONTINUED_FLAG) !== 0 && steps < OGG_MAX_CONTINUED_STEPS) { + const previous = await this.findPreviousPageAsync(result.offset, budget); + if (!previous) + break; + result = previous; + steps++; + } + this.pageOffset = result.offset; + this.pendingPackets = []; + this.pendingParts = []; + this.pendingLength = 0; + this.reachedEnd = false; + // The page granule gives the end of its last completed packet; the packets before it on the page are placed by + // the seek resync, once the page was read, so they are all emitted with an absolute, correct timeline. + this.seekResync = true; + return result.offset; + } + + /** + * Prepares the first page read after a seek, so that every packet of that page is emitted with an absolute + * timestamp derived from the page granule rather than from the requested time. It reads the page when the queue is + * empty and sets the timeline so that the page's last audio packet ends at its granule. The page duration is + * measured without touching any per packet state, so the packets are then emitted with the very same durations + * they were measured with. + * @returns {Promise} A promise resolving when the timeline is set. + */ + async prepareAfterSeekAsync() { + this.seekResync = false; + if (this.pendingPackets.length === 0) + await this.readNextPageAsync(); + const packets = this.pendingPackets; + if (packets.length === 0) + return; + const total = this.measurePacketsDurationMicros(packets); + // The granule of the last audio packet of the page is the page's granule; a header packet that shares the page does not carry it. + let granule = null; + for (let index = packets.length - 1; index >= 0; index--) { + if (!this.isHeaderPacket(packets[index].data)) { + granule = packets[index].granule; + break; + } + } + this.timelineMicros = granule !== null + ? Math.max(0, this.granuleToMicros(granule) - total) + : Math.max(0, this.timelineMicros); + } + + //+=======================================================================================+ + //| Abstract surface | + //+=======================================================================================+ + + /** + * Gets the duration, in microseconds, of one packet of this codec. A codec must implement it: the base throws, + * because a default of zero would freeze the timeline of the codec that forgot to override it, and the failure + * would be silent. + * @param {Uint8Array} data - The packet bytes. + * @returns {number} The duration in microseconds. + * @throws {LuminaAudioPlayer.PlayerError} When the codec does not implement it. + */ + computePacketDurationMicros(data) { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This OGG demuxer does not implement computePacketDurationMicros.'); + } + + /** + * Converts a granule position to a media time, in microseconds. A codec must implement it: the base throws, + * because the raw granule is in the codec's own sample unit and is not a media time, so a default that returned it + * unchanged would report a wrong timeline for the codec that forgot to override it. + * @param {number} granule - The granule position. + * @returns {number} The media time in microseconds. + * @throws {LuminaAudioPlayer.PlayerError} When the codec does not implement it. + */ + granuleToMicros(granule) { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This OGG demuxer does not implement granuleToMicros.'); + } + + /** + * Records the offset of the first page that holds audio, once every codec header packet was consumed. It is what + * keeps a seek from landing on a page of identification or comment headers and emitting them as audio. + * @returns {void} + */ + beginAudio() { + this.audioStartOffset = this.pendingPackets.length > 0 ? this.lastPageOffset : this.pageOffset; + } + + /** + * Releases the queued packet state of the demuxer when it is destroyed, so a torn down stream does not keep the pages it had already read alive. + * @returns {void} + */ + onDestroy() { + this.pendingPackets = []; + this.pendingParts = []; + this.pendingLength = 0; + } + + /** + * Checks whether a packet is a codec header packet rather than audio, so that a page that carries headers, which + * a seek can land on, does not emit them. The default is that every packet is audio. + * @param {Uint8Array} data - The packet bytes. + * @returns {boolean} True when the packet is a codec header. + */ + isHeaderPacket(data) { + return false; + } + + /** + * Measures the total duration, in microseconds, of a list of packets, without advancing any per packet state, so + * that measuring a page never disturbs the state the packets are then emitted with. A codec must implement it + * together with computePacketDurationMicros, because the base throws rather than defaulting to a loop that calls + * computePacketDurationMicros directly: for a codec whose packet duration depends on the packet before it, that + * loop mutates the state, so the first page after a seek would then be emitted with the durations the measurement + * left behind rather than the ones it measured. + * @param {Array<{ data: Uint8Array, granule: number|null }>} packets - The packets to measure. + * @returns {number} The total duration in microseconds. + * @throws {LuminaAudioPlayer.PlayerError} When the codec does not implement it. + */ + measurePacketsDurationMicros(packets) { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This OGG demuxer does not implement measurePacketsDurationMicros.'); + } + } + + /** + * Computes the number of samples one Opus packet decodes to, from its table of contents byte. + * @param {Uint8Array} data - The Opus packet. + * @returns {number} The number of samples at 48 kHz. + */ + function getOpusPacketSamples(data) { + if (!data || data.length < 1) + return 0; + const toc = data[0]; + // The table of contents byte is a five bit configuration, which selects the frame duration, and a two bit code, which states how many frames the packet holds. + const config = toc >> 3; + const code = toc & 0x03; + let frameCount; + if (code === 0) + frameCount = 1; + else if (code === 1 || code === 2) + frameCount = 2; + else { + if (data.length < 2) + return 0; + frameCount = data[1] & 0x3F; + if (frameCount <= 0) + return 0; + } + const frameMilliseconds = OPUS_FRAME_DURATION_MS[config]; + if (!Number.isFinite(frameMilliseconds)) + return 0; + return Math.round(frameMilliseconds * OPUS_GRANULE_RATE / 1000) * frameCount; + } + + /** + * Builds the Xiph extradata of a Vorbis stream: the count of lacing values, the lacing values, and the three header packets, in order. + * @param {Array} packets - The identification, comment and setup header packets. + * @returns {Uint8Array|null} The extradata, or null when the headers are too large to be laced into a single byte count. + */ + function buildXiphExtradata(packets) { + const lacing = []; + for (const packet of packets) { + let length = packet.length; + while (length >= 255) { + lacing.push(255); + length -= 255; + } + lacing.push(length); + } + if (lacing.length > 255) + return null; + const total = 1 + lacing.length; + let payload = 0; + for (const packet of packets) + payload += packet.length; + const result = new Uint8Array(total + payload); + result[0] = lacing.length; + for (let index = 0; index < lacing.length; index++) + result[1 + index] = lacing[index]; + let offset = total; + for (const packet of packets) { + result.set(packet, offset); + offset += packet.length; + } + return result; + } + + /** + * Demuxes an OGG Opus stream. + */ + class OggOpusDemuxer extends OggDemuxer { + /** + * Creates an instance of OggOpusDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + /** @type {Uint8Array|null} */ + this.description = null; + this.preSkip = 0; + this.channels = 0; + } + + /** + * Reads the OpusHead and the OpusTags packets and positions the read cursor on the first audio packet. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not an OGG Opus stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + this.pageOffset = 0; + this.pendingParts = []; + this.pendingLength = 0; + this.pendingPackets = []; + this.currentSerial = null; + const head = await this.readRawPacketAsync(); + if (!head || !LuminaAudioPlayer.demuxBytesEqualAscii(head.data, 0, 'OpusHead')) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG stream is not an Opus stream.', { reason: 'no-opus-head' }); + if (head.data.length < 19) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OpusHead packet is too short.', { reason: 'invalid-opus-head' }); + this.channels = head.data[9]; + this.preSkip = LuminaAudioPlayer.demuxReadIntLE(head.data, 10, 2) || 0; + if (this.channels <= 0) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OpusHead packet names no channels.', { reason: 'invalid-opus-head' }); + this.description = head.data.slice(); + // The mapping requires the OpusTags comment packet after the identification header; any further packet is audio. + const tags = await this.readRawPacketAsync(); + if (tags && !LuminaAudioPlayer.demuxBytesEqualAscii(tags.data, 0, 'OpusTags')) + // A stream that skips its comment packet is malformed, but the packet is kept so it is not lost. + this.pendingPackets.unshift(tags); + const lastGranule = await this.probeLastGranuleAsync(); + if (lastGranule !== null) { + this.lastGranule = lastGranule; + this.durationIsFinal = true; + this.refreshDuration(); + } + this.beginAudio(); + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.description) + return null; + return { + codec: 'opus', + sampleRate: OPUS_GRANULE_RATE, + numberOfChannels: this.channels, + description: this.description + }; + } + + /** + * Checks whether a packet is one of the Opus header packets, which are not audio. + * @param {Uint8Array} data - The packet bytes. + * @returns {boolean} True when the packet is the identification or the comment header. + */ + isHeaderPacket(data) { + return LuminaAudioPlayer.demuxBytesEqualAscii(data, 0, 'OpusHead') + || LuminaAudioPlayer.demuxBytesEqualAscii(data, 0, 'OpusTags'); + } + + /** + * Reads the next Opus audio packet. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + try { + if (this.seekResync) + await this.prepareAfterSeekAsync(); + return await this.readNextAudioPacketAsync(); + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Gets the duration, in microseconds, of one Opus packet. + * @param {Uint8Array} data - The packet bytes. + * @returns {number} The duration in microseconds. + */ + computePacketDurationMicros(data) { + return LuminaAudioPlayer.samplesToMicroseconds(getOpusPacketSamples(data), OPUS_GRANULE_RATE); + } + + /** + * Measures the total duration of a list of Opus packets. An Opus packet's duration is self contained, so summing + * the per packet durations touches no state and is exact. + * @param {Array<{ data: Uint8Array, granule: number|null }>} packets - The packets to measure. + * @returns {number} The total duration in microseconds. + */ + measurePacketsDurationMicros(packets) { + let total = 0; + for (const packet of packets) { + if (this.isHeaderPacket(packet.data)) + continue; + total += this.computePacketDurationMicros(packet.data); + } + return total; + } + + /** + * Converts an Opus granule position to a media time, subtracting the pre-skip the decoder discards. + * @param {number} granule - The granule position. + * @returns {number} The media time in microseconds. + */ + granuleToMicros(granule) { + return LuminaAudioPlayer.samplesToMicroseconds(Math.max(0, granule - this.preSkip), OPUS_GRANULE_RATE); + } + } + + /** + * Demuxes an OGG Vorbis stream. + */ + class OggVorbisDemuxer extends OggDemuxer { + /** + * Creates an instance of OggVorbisDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + /** @type {Uint8Array|null} */ + this.description = null; + this.channels = 0; + this.sampleRate = 0; + this.blockSizes = [0, 0]; + this.lastBlockSize = null; + } + + /** + * Reads the identification, comment and setup header packets and positions the read cursor on the first audio packet. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not an OGG Vorbis stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + this.pageOffset = 0; + this.pendingParts = []; + this.pendingLength = 0; + this.pendingPackets = []; + this.currentSerial = null; + const identification = await this.readRawPacketAsync(); + if (!identification || identification.data.length < 30 + || identification.data[0] !== 0x01 + || !LuminaAudioPlayer.demuxBytesEqualAscii(identification.data, 1, 'vorbis')) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG stream is not a Vorbis stream.', { reason: 'no-vorbis-identification' }); + this.channels = identification.data[11]; + this.sampleRate = LuminaAudioPlayer.demuxReadUintLE(identification.data, 12, 4) || 0; + // The block size byte of the identification header holds the two base-two exponents of the short and the long block size, one per nibble, so the sizes themselves are powers of two. + const blockSizeByte = identification.data[28]; + this.blockSizes = [1 << (blockSizeByte & 0x0F), 1 << ((blockSizeByte >> 4) & 0x0F)]; + if (this.channels <= 0 || this.sampleRate <= 0 || this.blockSizes[0] < 16 || this.blockSizes[1] < this.blockSizes[0]) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The Vorbis identification header is invalid.', { reason: 'invalid-vorbis-identification' }); + const comment = await this.readRawPacketAsync(); + const setup = await this.readRawPacketAsync(); + if (!comment || !setup) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The Vorbis stream is missing its header packets.', { reason: 'missing-vorbis-headers' }); + const description = buildXiphExtradata([identification.data, comment.data, setup.data]); + if (!description) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The Vorbis header packets are too large for the codec private data format.', { reason: 'vorbis-headers-too-large' }); + this.description = description; + const lastGranule = await this.probeLastGranuleAsync(); + if (lastGranule !== null) { + this.lastGranule = lastGranule; + this.durationIsFinal = true; + this.refreshDuration(); + } + this.lastBlockSize = null; + this.beginAudio(); + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream, including the required Vorbis description. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.description) + return null; + return { + codec: 'vorbis', + sampleRate: this.sampleRate, + numberOfChannels: this.channels, + description: this.description + }; + } + + /** + * Checks whether a packet is one of the three Vorbis header packets, which are not audio. + * @param {Uint8Array} data - The packet bytes. + * @returns {boolean} True when the packet is the identification, comment or setup header. + */ + isHeaderPacket(data) { + if (!data || data.length < 7) + return false; + const type = data[0]; + return (type === 0x01 || type === 0x03 || type === 0x05) && LuminaAudioPlayer.demuxBytesEqualAscii(data, 1, 'vorbis'); + } + + /** + * Measures the total duration of a list of Vorbis packets without touching the block size state, so that the + * durations the packets are then emitted with are exactly the ones they were measured with. + * @param {Array<{ data: Uint8Array, granule: number|null }>} packets - The packets to measure. + * @returns {number} The total duration in microseconds. + */ + measurePacketsDurationMicros(packets) { + let total = 0; + let previous = this.lastBlockSize; + for (const packet of packets) { + if (this.isHeaderPacket(packet.data) || !packet.data || packet.data.length < 1) + continue; + const blockSize = this.blockSizes[(packet.data[0] >> 7) & 0x01]; + const prior = previous === null ? blockSize : previous; + total += LuminaAudioPlayer.samplesToMicroseconds(Math.floor((prior + blockSize) / 4), this.sampleRate); + previous = blockSize; + } + return total; + } + + /** + * Reads the next Vorbis audio packet. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + try { + if (this.seekResync) + await this.prepareAfterSeekAsync(); + return await this.readNextAudioPacketAsync(); + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Gets the duration, in microseconds, of one Vorbis packet. The first bit of an audio packet selects one of the + * two block sizes of the stream, and a packet produces the average of its own block size and the previous one, + * which is the amount of audio the overlap of two windows covers. + * @param {Uint8Array} data - The packet bytes. + * @returns {number} The duration in microseconds. + */ + computePacketDurationMicros(data) { + if (!data || data.length < 1) + return 0; + const blockFlag = (data[0] >> 7) & 0x01; + const blockSize = this.blockSizes[blockFlag]; + const previous = this.lastBlockSize === null ? blockSize : this.lastBlockSize; + this.lastBlockSize = blockSize; + const samples = Math.floor((previous + blockSize) / 4); + return LuminaAudioPlayer.samplesToMicroseconds(samples, this.sampleRate); + } + + /** + * Converts a Vorbis granule position to a media time. A Vorbis granule counts decoded samples. + * @param {number} granule - The granule position. + * @returns {number} The media time in microseconds. + */ + granuleToMicros(granule) { + return LuminaAudioPlayer.samplesToMicroseconds(Math.max(0, granule), this.sampleRate); + } + } + + LuminaAudioPlayer.OggDemuxer = OggDemuxer; + LuminaAudioPlayer.OggOpusDemuxer = OggOpusDemuxer; + LuminaAudioPlayer.OggVorbisDemuxer = OggVorbisDemuxer; + LuminaAudioPlayer.computeOggCrc = computeOggCrc; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.OGG, + codec: LuminaAudioPlayer.DemuxerCodec.OPUS, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.OPUS, + create: (options) => new OggOpusDemuxer(options) + }); + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.OGG, + codec: LuminaAudioPlayer.DemuxerCodec.VORBIS, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.VORBIS, + create: (options) => new OggVorbisDemuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-wav.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-wav.js new file mode 100644 index 00000000..20090143 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-wav.js @@ -0,0 +1,303 @@ +/** + * WAV (RIFF) demuxer of the audio player. + * + * A WAV file is a RIFF container: the four byte magic 'RIFF', a size, the four byte form 'WAVE', and then a sequence of + * tagged chunks, of which the 'fmt ' chunk describes the audio and the 'data' chunk holds it. The audio is uncompressed, + * so the payload of the data chunk is the samples themselves, interleaved by channel. There is no framing inside the + * payload at all: this demuxer invents packets by cutting the payload into fixed size blocks of whole frames, which is + * what makes the stream seekable to an exact byte and therefore to an exact sample. + * + * The codec private data and the codec string + * ------------------------------------------- + * WebCodecs decodes uncompressed audio under the PCM codec strings, one per sample format ('pcm-u8', 'pcm-s16', + * 'pcm-s24', 'pcm-s32', 'pcm-f32'), each packet being raw interleaved samples and no description. This demuxer maps the + * sample format and the bits per sample of the fmt chunk to the matching codec string: a 8 bit PCM stream is unsigned + * (as RIFF defines 8 bit samples), an integer stream of 16, 24 or 32 bits is signed, and a 32 bit IEEE float stream is + * 'pcm-f32'. A format or a bit depth the player has no codec string for is refused as unsupported. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The number of frames a WAV packet holds. The payload is uncompressed, so the block only has to be small enough to + * keep a packet light and large enough to keep the call overhead low. + * @readonly + * @type {number} + */ + const FRAMES_PER_PACKET = 4096; + + /** + * The format tag RIFF uses for integer PCM. + * @readonly + * @type {number} + */ + const FORMAT_PCM = 1; + + /** + * The format tag RIFF uses for IEEE float PCM. + * @readonly + * @type {number} + */ + const FORMAT_FLOAT = 3; + + /** + * The format tag RIFF uses for an extensible format, whose real format is in a subformat GUID. + * @readonly + * @type {number} + */ + const FORMAT_EXTENSIBLE = 0xFFFE; + + /** + * Resolves the WebCodecs PCM codec string of a WAV sample format. + * @param {number} audioFormat - The format tag of the fmt chunk, after resolving an extensible format. + * @param {number} bitsPerSample - The bits per sample of the fmt chunk. + * @returns {string|null} The codec string, or null when the player has no codec string for the format. + */ + function resolvePcmCodec(audioFormat, bitsPerSample) { + if (audioFormat === FORMAT_FLOAT) + return bitsPerSample === 32 ? 'pcm-f32' : null; + if (audioFormat !== FORMAT_PCM) + return null; + if (bitsPerSample === 8) + return 'pcm-u8'; + if (bitsPerSample === 16) + return 'pcm-s16'; + if (bitsPerSample === 24) + return 'pcm-s24'; + if (bitsPerSample === 32) + return 'pcm-s32'; + return null; + } + + /** + * Demuxes a WAV (RIFF) stream. + */ + class WavDemuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of WavDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.offset = 0; + this.dataStart = 0; + this.dataEnd = 0; + this.timelineMicros = 0; + /** @type {Object|null} */ + this.format = null; + this.durationSeconds = null; + this.reachedEnd = false; + } + + //+=======================================================================================+ + //| Initialization | + //+=======================================================================================+ + + /** + * Reads the RIFF header and walks the chunks to find the fmt chunk and the data chunk. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not a WAV stream the player decodes. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + const riff = await this.reader.readAsync(0, 12); + if (!LuminaAudioPlayer.demuxBytesEqualAscii(riff, 0, 'RIFF') || !LuminaAudioPlayer.demuxBytesEqualAscii(riff, 8, 'WAVE')) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The bytes are not a WAV stream.', { reason: 'no-riff-magic' }); + const result = await this.readChunksAsync(); + if (result.formatResult === null) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The WAV stream carries no format chunk.', { reason: 'no-format-chunk' }); + if (result.formatResult.status === 'invalid') + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The WAV format chunk is too short or malformed to describe the audio.', { reason: 'invalid-format-chunk' }); + if (result.formatResult.status === 'unsupported') + // The chunk is present and well formed, but it names a format or a bit depth the player decodes no PCM + // codec string for, which is a different outcome from a chunk that is missing, and is reported as such. + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The WAV stream holds an audio format the player does not decode.', { + reason: 'unsupported-format', + audioFormat: result.formatResult.audioFormat, + bitsPerSample: result.formatResult.bitsPerSample + }); + if (result.dataStart === null) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The WAV stream carries no data chunk.', { reason: 'no-data-chunk' }); + const format = result.formatResult.format; + this.format = format; + this.dataStart = result.dataStart; + this.dataEnd = result.dataEnd; + this.durationSeconds = format.byteRate > 0 ? (this.dataEnd - this.dataStart) / format.byteRate : null; + this.offset = this.dataStart; + this.timelineMicros = 0; + this.reachedEnd = false; + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.format) + return null; + return { + codec: this.format.codec, + sampleRate: this.format.sampleRate, + numberOfChannels: this.format.channels + }; + } + + /** + * Gets the duration of the stream, computed from the size of the data chunk and the byte rate of the format. + * @returns {number|null} The duration in seconds, or null when it cannot be derived. + */ + getDuration() { + return this.durationSeconds; + } + + //+=======================================================================================+ + //| Reading | + //+=======================================================================================+ + + /** + * Reads the next block of whole frames from the data chunk as an encoded packet. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + if (this.reachedEnd) + return null; + try { + const format = this.format; + const remaining = this.dataEnd - this.offset; + if (remaining < format.blockAlign) { + this.reachedEnd = true; + return null; + } + const frames = Math.min(FRAMES_PER_PACKET, Math.floor(remaining / format.blockAlign)); + const length = frames * format.blockAlign; + const data = await this.reader.copyAsync(this.offset, length); + if (data.length < length) { // A short read means the stream was truncated below the data chunk size it declared. + this.reachedEnd = true; + return null; + } + // The duration is kept unrounded while the timeline accumulates it, so that rounding it per packet does not + // make the timeline drift; only the packet the decoder receives carries a whole number of microseconds. + const duration = (frames / format.sampleRate) * 1000000; + const packet = LuminaAudioPlayer.createDemuxerPacket(data, this.timelineMicros, duration); + this.timelineMicros += duration; + this.offset += length; + if (this.offset + format.blockAlign > this.dataEnd) + this.reachedEnd = true; + return packet; + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Repositions the read cursor to the exact frame that covers a time. The payload is uncompressed and frame aligned, so the position is computed rather than scanned. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const format = this.format; + if (!format || !Number.isFinite(seconds) || seconds < 0) + return null; + const frame = Math.floor(seconds * format.sampleRate); + const offset = Math.min(this.dataEnd, this.dataStart + frame * format.blockAlign); + const aligned = this.dataStart + Math.floor((offset - this.dataStart) / format.blockAlign) * format.blockAlign; + this.offset = aligned; + this.reachedEnd = this.offset >= this.dataEnd; + // The exact time of the requested frame, kept unrounded so the timeline it seeds does not drift. + this.timelineMicros = ((aligned - this.dataStart) / format.blockAlign / format.sampleRate) * 1000000; + return aligned; + } + + //+=======================================================================================+ + //| Internal helpers | + //+=======================================================================================+ + + /** + * Walks the RIFF chunks, parsing the format chunk and locating the data chunk. + * @returns {Promise} The result of the format chunk, and the offset and end of the data chunk. The format result distinguishes an absent chunk from an unsupported one. + */ + async readChunksAsync() { + const end = this.reader.getLength(); + let cursor = 12; + /** @type {Object|null} */ + let formatResult = null; + let dataStart = null; + let dataEnd = null; + // The chunk list is bounded so a malformed size field cannot make this walk forever. + for (let count = 0; count < 4096; count++) { + if (end !== null && cursor + 8 > end) + break; + const header = await this.reader.readAsync(cursor, 8); + if (header.length < 8) + break; + const id = String.fromCharCode(header[0], header[1], header[2], header[3]); + const size = LuminaAudioPlayer.demuxReadUintLE(header, 4, 4) || 0; + const bodyStart = cursor + 8; + if (id === 'fmt ') + formatResult = await this.parseFormatChunkAsync(bodyStart, size); + else if (id === 'data') { + dataStart = bodyStart; + dataEnd = end === null ? bodyStart + size : Math.min(bodyStart + size, end); + } + // A RIFF chunk body is padded to an even length, and the pad byte is not counted in the size. + cursor = bodyStart + size + (size % 2); + } + return { formatResult, dataStart, dataEnd }; + } + + /** + * Parses the fmt chunk of a WAV stream. + * @param {number} offset - The offset of the chunk body. + * @param {number} size - The number of bytes of the chunk body. + * @returns {Promise} A result whose status is 'ok' with the parsed format, 'unsupported' with the format tag and bit depth the player decodes no PCM codec string for, or 'invalid' when the chunk is too short or malformed. The three are distinguished so that a present but unsupported format is not reported as a missing chunk. + */ + async parseFormatChunkAsync(offset, size) { + if (size < 16) + return { status: 'invalid' }; + const bytes = await this.reader.readAsync(offset, Math.min(size, 40)); + if (bytes.length < 16) + return { status: 'invalid' }; + // The first sixteen bytes of a fmt chunk are the format tag, the channel count, the sample rate, the byte rate, + // the block alignment and the bits per sample, in that order, every one little endian. + let audioFormat = LuminaAudioPlayer.demuxReadUintLE(bytes, 0, 2); + const channels = LuminaAudioPlayer.demuxReadUintLE(bytes, 2, 2); + const sampleRate = LuminaAudioPlayer.demuxReadUintLE(bytes, 4, 4); + const byteRate = LuminaAudioPlayer.demuxReadUintLE(bytes, 8, 4); + let blockAlign = LuminaAudioPlayer.demuxReadUintLE(bytes, 12, 2); + const bitsPerSample = LuminaAudioPlayer.demuxReadUintLE(bytes, 14, 2); + // An extensible format names its real format in the first two bytes of the subformat GUID. + if (audioFormat === FORMAT_EXTENSIBLE && size >= 40 && bytes.length >= 40) + audioFormat = LuminaAudioPlayer.demuxReadUintLE(bytes, 24, 2); + if (!channels || channels <= 0 || !sampleRate || sampleRate <= 0 || !bitsPerSample) + return { status: 'invalid' }; + const codec = resolvePcmCodec(audioFormat, bitsPerSample); + if (!codec) + return { status: 'unsupported', audioFormat, bitsPerSample }; + const sampleBytes = bitsPerSample / 8; + // A stream whose block alignment disagrees with its channels and bit depth cannot be sliced into frames, so the computed alignment is used and the declared one is only a fallback. + if (!blockAlign || blockAlign <= 0 || blockAlign % sampleBytes !== 0 || blockAlign % channels !== 0) + blockAlign = channels * sampleBytes; + return { status: 'ok', format: Object.freeze({ codec, channels, sampleRate, byteRate: byteRate || sampleRate * blockAlign, blockAlign, bitsPerSample }) }; + } + } + + LuminaAudioPlayer.WavDemuxer = WavDemuxer; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.WAV, + codec: LuminaAudioPlayer.DemuxerCodec.PCM, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.PCM, + create: (options) => new WavDemuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js index 14d26630..1642eb2a 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js @@ -69,7 +69,7 @@ * the reads that are waiting for a window, with {@link LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED}, so a seek * teardown is never mistaken for a stream failure. A read therefore resolves once the buffer covers its window, and is * rejected when the window can no longer be filled: on a destroy or an abort (DOWNLOAD_ABORTED), with the recorded failure - * when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason === 'window-unavailable' when + * when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE} when * the file completed or the loop ended with no gap left to fill. A read that is waiting while the download is merely * paused, or before it has started, is left pending, because a resume or a start can still fill it. The loop callbacks and * getError only ever see DOWNLOAD_FAILED. @@ -130,16 +130,6 @@ return { start, end, total }; } - /** - * Checks whether a value is the AbortError a cancelled fetch or stream read rejects with. It is tested by name rather - * than by type, because in a browser an AbortError is a DOMException, which is not an Error. - * @param {*} error - The value to check. - * @returns {boolean} True when the value is an AbortError. - */ - function isAbortError(error) { - return !!error && error.name === 'AbortError'; - } - /** * Checks whether a Content-Type is one the track stream may answer with: an audio type, or the generic binary type * the stream endpoint falls back to for a container it cannot name. Any other type, in particular the text/html of a @@ -777,7 +767,7 @@ * @param {number} offset - The first byte of the window. * @param {number} length - The length of the window, in bytes. * @returns {Promise} A copy of the requested bytes. - * @throws {LuminaAudioPlayer.PlayerError} The rejection of {@link LuminaAudioPlayer.TrackDownloader#whenRangeAvailableAsync}, which a read propagates, or DOWNLOAD_FAILED with details.reason === 'window-unavailable' if the window was released without ever arriving. + * @throws {LuminaAudioPlayer.PlayerError} The rejection of {@link LuminaAudioPlayer.TrackDownloader#whenRangeAvailableAsync}, which a read propagates, or DOWNLOAD_FAILED with details.reason {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE} if the window was released without ever arriving. */ async readBytesAsync(offset, length) { const direct = this.buffer.read(offset, length); @@ -794,8 +784,8 @@ * Resolves once a window of bytes has been downloaded. * @param {number} offset - The first byte of the window. * @param {number} length - The length of the window, in bytes. - * @returns {Promise} A promise that resolves once the buffer covers the window. It is rejected when the window can no longer be filled: on a destroy or an abort, with the recorded failure when the loop stopped after a failure, or with the window-unavailable error when the file completed or the loop ended with no gap left to fill. A read issued while the download is merely paused, or before it has started, stays pending, because a resume or a start can still fill it. - * @throws {LuminaAudioPlayer.PlayerError} With DOWNLOAD_ABORTED when the downloader is destroyed or was aborted, with the recorded failure when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason === 'window-unavailable' when the file completed or the loop ended with no gap left to fill. + * @returns {Promise} A promise that resolves once the buffer covers the window. It is rejected when the window can no longer be filled: on a destroy or an abort, with the recorded failure when the loop stopped after a failure, or with the {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE} error when the file completed or the loop ended with no gap left to fill. A read issued while the download is merely paused, or before it has started, stays pending, because a resume or a start can still fill it. + * @throws {LuminaAudioPlayer.PlayerError} With DOWNLOAD_ABORTED when the downloader is destroyed or was aborted, with the recorded failure when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE} when the file completed or the loop ended with no gap left to fill. */ whenRangeAvailableAsync(offset, length) { if (this.buffer.covers(offset, length)) @@ -1034,7 +1024,7 @@ this.noteTotal(resolved.total); return await this.readResponseIntoBufferAsync(response, resolved, controller, spec.stopOnPause === true, spec.openEnded === true); } catch (error) { - if (isAbortError(error)) + if (LuminaAudioPlayer.isAbortError(error)) return { isAborted: true, isFailed: false, isDestroyed: this.destroyed }; // The failure left the response body unread, so it is discarded and the request is aborted to release the // connection instead of waiting for the browser to drop the stream. @@ -1156,7 +1146,7 @@ try { result = await reader.read(); } catch (error) { - if (isAbortError(error)) { + if (LuminaAudioPlayer.isAbortError(error)) { isStopped = true; break; } @@ -1359,10 +1349,10 @@ * Builds the single error used whenever a byte window can no longer be filled: a completed file, a loop that * drained with nothing left to fetch, or a window that was released without ever arriving. Every path that reports * this outcome uses it, so a consumer sees one consistent code and reason. - * @returns {LuminaAudioPlayer.PlayerError} The window unavailable error, with details.reason === 'window-unavailable'. + * @returns {LuminaAudioPlayer.PlayerError} The window unavailable error, with details.reason === {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE}. */ createWindowUnavailableError() { - return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The requested byte window can no longer be filled.', { reason: 'window-unavailable' }); + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The requested byte window can no longer be filled.', { reason: LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE }); } } diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js index 9fc8d704..c40509cd 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -34,6 +34,8 @@ DOWNLOAD_FAILED: 'download-failed', // The download of a track was intentionally stopped, by an abort or a destroy, so a reader can tell a teardown apart from a stream failure. DOWNLOAD_ABORTED: 'download-aborted', + // The container of a track could not be parsed into encoded packets, or the bytes it holds do not describe a stream the demuxer supports. + DEMUX_FAILED: 'demux-failed', // The stored playback preferences of the user could not be read. PREFERENCES_LOAD_FAILED: 'preferences-load-failed' }); @@ -56,7 +58,22 @@ // A scheduler's scheduled ahead ceiling is smaller than one frame plus its scheduling lead, so it can never accept a // frame at all. Unlike SCHEDULED_AHEAD_LIMIT, which is recoverable backpressure, this is terminal: the decode // pipeline stops because it can never make progress. - SCHEDULED_AHEAD_UNSATISFIABLE: 'scheduled-ahead-unsatisfiable' + SCHEDULED_AHEAD_UNSATISFIABLE: 'scheduled-ahead-unsatisfiable', + // The bundled demuxers have no demuxer for the container of a track, so the server must change the container or the + // codec of the track before the player can play it. Published by the demux capability module, which a consumer reads + // to ask for a normalized delivery instead of failing. + NO_DEMUXER: 'no-demuxer', + // A demuxer exists for the container of a track, but the browser cannot decode the codec of the track, so the server + // must re-encode it. Published by the demux capability module alongside NO_DEMUXER. + CODEC_UNSUPPORTED: 'codec-unsupported', + // A demuxer exists for the container of a track, but the bytes of the track could not be parsed, so the file is + // treated as one the bundled player cannot play directly rather than as a fatal player failure. + DEMUXER_FAILED: 'demuxer-failed', + // A read asked the download engine for a byte window it can never fill, because the file completed or the loop + // stopped with no gap left to fill. Published by the download engine and recognized by the demuxer byte source, + // which reads it as end of file rather than as a failure, so a rename on either side cannot silently turn a + // drained window into a fatal read error. + WINDOW_UNAVAILABLE: 'window-unavailable' }); /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js index 39e8305b..ac8b61b8 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js @@ -39,6 +39,13 @@ CAPABILITIES_CHANGED: 'capabilitieschange', // The stored playback preferences of the user were loaded. Payload: the preferences object. PREFERENCES_CHANGED: 'preferenceschange', + // A track cannot be demuxed and decoded directly by the bundled player, so the server has to normalize it (remux or + // transcode) before it can play. Payload: { container, codec, reason }, where reason is one of the + // {@link LuminaAudioPlayer.PlayerErrorReason} values NO_DEMUXER, CODEC_UNSUPPORTED or DEMUXER_FAILED, and, when the + // caller supplied one, directPlay, the direct play flag of the manifest it asked about, so a consumer can tell a + // client-side capability gap from a track the server already decided to normalize. The flag is absent, not false, + // when the caller had no manifest. + NEEDS_NORMALIZATION: 'needsnormalization', // The player bar became visible or hidden. Payload: { isVisible }. The value is deliberately not 'visibilitychange', // which is the name of the DOM page visibility event, so that the two can never be confused. VISIBILITY_CHANGED: 'barvisibilitychange' diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js index d77a2463..c85efe06 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js @@ -2,9 +2,10 @@ * Shared helpers of the audio player. * * This module has no dependency on any other player module, and it is loaded before them, so it is the home of the small - * numeric helpers several modules need. Keeping one implementation here avoids the copies that otherwise drift apart, and - * because this file is a dedicated, dependency free util, no consumer depends on the load order of a feature module such - * as the event bus or the download engine. + * numeric and error helpers several modules need. Keeping one implementation here avoids the copies that otherwise drift + * apart, and because this file is a dedicated, dependency free util, no consumer depends on the load order of a feature + * module such as the event bus or the download engine. The error helpers read {@link LuminaAudioPlayer.PlayerError} at + * call time rather than at load time, so they do not depend on the error module being loaded first either. */ (function (LuminaAudioPlayer) { 'use strict'; @@ -21,4 +22,50 @@ return minimum; return Math.min(maximum, Math.max(minimum, value)); }; + + /** + * Checks whether a value is the AbortError a reset, a close or an aborted fetch rejects with. An AbortError is tested + * by name rather than by type, because in a browser it is a DOMException, which is not an Error. + * @param {*} error - The value to check. + * @returns {boolean} True when the value is an AbortError. + */ + LuminaAudioPlayer.isAbortError = function isAbortError(error) { + return !!error && error.name === 'AbortError'; + }; + + /** + * Merges two error detail objects into a new one, so that a details object a component owns is never mutated in place. + * @param {Object|null} base - The existing details. + * @param {Object|null} extra - The details to add. + * @returns {Object|null} The merged details, or null when both are absent. + */ + LuminaAudioPlayer.mergeErrorDetails = function mergeErrorDetails(base, extra) { + const hasBase = base !== null && base !== undefined; + const hasExtra = extra !== null && extra !== undefined; + if (!hasBase && !hasExtra) + return null; + if (!hasExtra) + return Object.assign({}, base); + if (!hasBase) + return Object.assign({}, extra); + return Object.assign({}, base, extra); + }; + + /** + * Copies a failure into a {@link LuminaAudioPlayer.PlayerError} that the caller owns, so that a player error raised by + * another component is never aliased and its details are never mutated. A failure that is already a player error keeps + * its own code, which is more specific than the fallback the caller would give it. + * @param {*} error - The failure to own. + * @param {string} [fallbackCode] - The code to use when the failure is not already a player error. + * @param {Object|null} [details] - Optional details to merge in. + * @returns {LuminaAudioPlayer.PlayerError} The owned typed error. + */ + LuminaAudioPlayer.toOwnedPlayerError = function toOwnedPlayerError(error, fallbackCode, details) { + if (error instanceof LuminaAudioPlayer.PlayerError) + return new LuminaAudioPlayer.PlayerError(error.code, error.message, LuminaAudioPlayer.mergeErrorDetails(error.details, details || null)); + const typed = LuminaAudioPlayer.PlayerError.from(error, fallbackCode); + if (!details) + return typed; + return new LuminaAudioPlayer.PlayerError(typed.code, typed.message, LuminaAudioPlayer.mergeErrorDetails(typed.details, details)); + }; })(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); From e6fa85f7c60e8350d00e4f1e07b1f25a3ec182ae Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 17 Oct 2026 15:08:52 +0300 Subject: [PATCH 19/77] Adds audio player seeking, resync, underrun recovery and gapless transitions. - Adds the media pipeline engine, seek-aware byte source, schedulers and manifest client. - Implements seeking, resync, underrun recovery, bounded gapless prefetch and clean failure handling. - Pins manifest, stream and configuration requests to validated page-origin routes. - Adds why comments to the complex pipeline and download paths. --- .../Common/Services/IUrlService.cs | 11 +- .../Common/Services/UrlService.cs | 22 +- .../Views/Shared/_ThemeLayoutScripts.cshtml | 19 +- .../audio-player-demux-capabilities.js | 20 +- .../js/audio-player/audio-player-download.js | 293 ++- .../js/audio-player/audio-player-engine.js | 45 +- .../js/audio-player/audio-player-errors.js | 15 +- .../js/audio-player/audio-player-manifest.js | 321 +++ .../audio-player-pipeline-byte-source.js | 352 +++ .../audio-player-pipeline-engine.js | 1938 +++++++++++++++++ .../audio-player-pipeline-schedulers.js | 390 ++++ .../js/audio-player/audio-player-render.js | 223 +- .../js/audio-player/audio-player-utils.js | 22 + .../wwwroot/js/audio-player/audio-player.js | 372 +++- 14 files changed, 3958 insertions(+), 85 deletions(-) create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js diff --git a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs index 93663e4d..dda5ac04 100644 --- a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs @@ -1,7 +1,7 @@ namespace Lumina.Presentation.Web.Common.Services; /// -/// Interface for the service for generating absolute URLs from the application route templates, with URL localization. +/// Interface for the service for generating URLs from the application route templates, with URL localization. /// public interface IUrlService { @@ -12,4 +12,13 @@ public interface IUrlService /// Optional additional route values, like route parameters. /// An absolute URL to the specified route. string? GetAbsoluteUrl(string routeTemplate, object? additionalRouteValues = null); + + /// + /// Generates a root relative URL for the specified route template, including the path base and the culture, but not the scheme or the host. + /// A browser resolves it against the origin of the page, so it does not depend on how the server sees its own host behind a proxy. + /// + /// The route template of the target page or endpoint, taken from the constants. + /// Optional additional route values, like route parameters. + /// A root relative URL to the specified route. + string? GetRelativeUrl(string routeTemplate, object? additionalRouteValues = null); } diff --git a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs index acc29775..2c6ac95a 100644 --- a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs @@ -38,7 +38,20 @@ public class UrlService : IUrlService /// Thrown when is not one of the route templates defined in the constants. public string? GetAbsoluteUrl(string routeTemplate, object? additionalRouteValues = null) { - // fail fast when the route template is not one of the ones defined in the WebRoutes constants, instead of silently generating a broken URL + string? path = GetRelativeUrl(routeTemplate, additionalRouteValues); + if (path is null) + return null; + HttpContext? httpContext = _httpContextAccessor.HttpContext; + if (httpContext is null) + return null; + // Build the absolute URL from the request's scheme, host and the already localized path base. + return $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{path}"; + } + + /// + public string? GetRelativeUrl(string routeTemplate, object? additionalRouteValues = null) + { + // Fail fast when the route template is not one of the ones defined in the WebRoutes constants, instead of silently generating a broken URL. if (!s_knownRouteTemplates.Contains(routeTemplate)) throw new ArgumentException($"The route template '{routeTemplate}' is not defined in the WebRoutes constants.", nameof(routeTemplate)); @@ -50,11 +63,12 @@ public class UrlService : IUrlService if (additionalRouteValues is not null) foreach (PropertyInfo property in additionalRouteValues.GetType().GetProperties()) path = path.Replace($"{{{property.Name}}}", property.GetValue(additionalRouteValues)?.ToString(), StringComparison.OrdinalIgnoreCase); - // ensure the path starts with a slash, so that it is relative to the server root when concatenated with the host and the path base + // Ensure the path starts with a slash, so that it is relative to the server root when concatenated with the path base. if (!path.StartsWith('/')) path = "/" + path; - // build the absolute URL from the request's scheme, host and path base - return $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.PathBase}{path}"; + // The scheme and host are deliberately omitted. A browser resolves this against its own origin, so the value stays + // correct behind a reverse proxy even when the request headers do not describe the origin the browser used. + return $"{httpContext.Request.PathBase}{path}"; } /// diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 67256666..5485eb9b 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -33,13 +33,16 @@ error: '@localizer["Error"]', information: '@localizer["Information"]' }; - // The endpoints the audio player reads the stored playback preferences of the user from, and writes the volume and - // mute state it changes back to. The routes are the culture aware web routes, so the player never hardcodes a path, - // and it never reaches the API server directly. + // The endpoints the audio player reads the stored playback preferences of the user from, writes the volume and mute + // state it changes back to, and fetches the playback manifest of a track from, together with the stream route + // template the manifest path must match. The routes are the culture aware web routes, so the player never hardcodes + // a path, and it never reaches the API server directly. var audioPlayerConfiguration = { - getUserSettingsUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)', - getPlaybackStateUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_PLAYBACK_STATE)', - updatePlaybackStateUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_PLAYBACK_STATE)', + getUserSettingsUrl: '@_urlService.GetRelativeUrl(WebRoutes.Settings.GET_USER_SETTINGS)', + getPlaybackStateUrl: '@_urlService.GetRelativeUrl(WebRoutes.Settings.GET_PLAYBACK_STATE)', + updatePlaybackStateUrl: '@_urlService.GetRelativeUrl(WebRoutes.Settings.UPDATE_PLAYBACK_STATE)', + getPlaybackManifestUrl: '@_urlService.GetRelativeUrl(WebRoutes.Music.GET_PLAYBACK_MANIFEST)', + streamTrackRouteTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Music.STREAM_TRACK)', strings: { play: '@localizer["AudioPlayerPlay"]', pause: '@localizer["AudioPlayerPause"]', @@ -80,3 +83,7 @@ + + + + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js index 9b8f3321..25da12a3 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js @@ -266,15 +266,18 @@ * request a normalized delivery instead of failing, and never receives both a player failure and a normalization * request for the same unplayable file. * - * The one failure that resolves to null without publishing is an intentional download stop: a teardown that crossed - * the header probe is not a track the server has to normalize. A caller that must tell the two nulls apart therefore - * checks whether it received a needs normalization event, or its own teardown state, rather than the null itself. + * The failures that resolve to null without publishing are the ones that say nothing about the format: an intentional + * download stop, a teardown that crossed the header probe, and a transport failure. A transport failure is propagated + * instead of being turned into a normalization request, because the server cannot make a track it could not fetch + * playable. A caller distinguishes the nulls by its own teardown state and by whether it received a needs + * normalization event, rather than by the null itself. * @param {string} container - The container of the track. * @param {string} codec - The codec of the track. * @param {Object} [options] - The demuxer options, plus the injected capabilities and events, per {@link LuminaAudioPlayer.DemuxerCapabilities}. - * @returns {Promise} The ready demuxer, or null when the pair must be normalized. + * @returns {Promise} The ready demuxer, or null when the pair must be normalized or the probe was stopped intentionally. * @throws {TypeError} When no event bus was injected. It is a composition error, not a property of the track, so it * rejects rather than resolving to a null the caller would have to classify without an event to classify it by. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes could not be fetched because of a transport failure, which is not a format the server could normalize. */ LuminaAudioPlayer.createDemuxerFor = async function (container, codec, options) { const settings = options || {}; @@ -298,8 +301,13 @@ await demuxer.destroyAsync(); // An intentional download stop, a teardown that crossed the header probe, is not a track the server has to // normalize, so it is not published as one; the demuxer already reports it as a normal stop everywhere else. - if (!LuminaAudioPlayer.isDownloadAbort(error)) - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.DEMUXER_FAILED, settings.directPlay); + if (LuminaAudioPlayer.isDownloadAbort(error)) + return null; + // A transport failure says nothing about the format of the track either: the server must not normalize a file + // whose bytes could not be fetched, so the failure is propagated and reported as the download failure it is. + if (error instanceof LuminaAudioPlayer.PlayerError && error.code === LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED) + throw error; + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.DEMUXER_FAILED, settings.directPlay); return null; } const configuration = demuxer.getConfiguration(); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js index 1642eb2a..dbe093fd 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js @@ -41,7 +41,7 @@ * durationInSeconds: manifest.durationInSeconds, * shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, * events: host.events, - * onProgress: (progress) => host.reportProgress(progress.downloadedFraction), + * onProgress: (downloadedFraction) => host.reportProgress(downloadedFraction), * onError: (error) => host.reportError(error) * }); * // Fire and forget: the promise settles only when the loop stops, which is when the whole file is downloaded, the region @@ -86,6 +86,24 @@ (function (LuminaAudioPlayer) { 'use strict'; + /** + * The timeout, in milliseconds, of an explicit one shot range request. The loop request is deliberately not bounded by + * a total timeout, because it is an open ended transfer; a one shot read is a small, bounded window, so a server that + * never answers it is a failure rather than a reason to hold a seek open forever. + * @readonly + * @type {number} + */ + const ONE_SHOT_REQUEST_TIMEOUT_MS = 15000; + + /** + * The lookahead, in bytes, within which a read is considered covered by the active loop request even though the loop + * has not received those bytes yet. It lets the first read of the loop wait for the bytes it is about to deliver, + * without making a seek at a distant offset wait for the sequential download to reach it. + * @readonly + * @type {number} + */ + const LOOP_IN_FLIGHT_LOOKAHEAD_BYTES = 256 * 1024; + /** * Clamps a number into an inclusive range, through the shared helper on the namespace. The reference is resolved on * every call rather than captured at load time, so this module does not depend on the load order of the util. @@ -98,6 +116,15 @@ return LuminaAudioPlayer.clamp(value, minimum, maximum); } + /** + * Builds the failure of a one shot range request that exceeded its timeout. It is a failed request, not an intentional + * abort, so the seek recovery does not retry it with another full timeout. + * @returns {LuminaAudioPlayer.PlayerError} The timeout failure. + */ + function createRangeTimeoutError() { + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The range request timed out.', { reason: LuminaAudioPlayer.PlayerErrorReason.REQUEST_TIMEOUT }); + } + /** * Parses the total byte count of a Content-Length header. * @param {string|null} value - The header value. @@ -306,6 +333,8 @@ const size = Math.max(0, Math.floor(length)); if (size === 0) return new Uint8Array(0); + // Touching segments are merged on append, so a requested window is always contained by exactly one segment. + // Finding that segment is enough; a window that crosses a boundary means the buffer has a real gap. let segmentIndex = -1; for (let index = 0; index < this.segments.length; index++) { const candidate = this.segments[index]; @@ -321,6 +350,8 @@ if (segmentIndex === -1) return null; const segment = this.segments[segmentIndex]; + // local is the offset of the requested window inside the segment. position is the segment offset of the chunk + // the loop is looking at, and filled is how many requested bytes were already copied. const local = start - segment.start; const result = new Uint8Array(size); let filled = 0; @@ -338,6 +369,8 @@ position += chunk.byteLength; continue; } + // Clip the chunk to the part that intersects the requested window: from is the first byte to copy out of + // this chunk, take is how many bytes still fit in the result. const from = Math.max(0, local - position); const take = Math.min(chunk.byteLength - from, size - filled); result.set(chunk.subarray(from, from + take), filled); @@ -348,6 +381,8 @@ } position += chunk.byteLength; } + // The segment promised the window by its length, but its chunks did not cover it. Treat it as a gap instead of + // returning a partially filled buffer the caller could play as if it were complete. return null; } @@ -389,6 +424,8 @@ const segmentEnd = segment.start + segment.length; if (segmentEnd <= position) continue; + // The first segment that starts after the position is the gap that ends the run. Touching segments were + // merged on append, so no adjacency check is needed here. if (segment.start > position) break; position = Math.max(position, segmentEnd); @@ -431,7 +468,7 @@ * @param {string} [options.credentials] - The credentials mode of the request. Defaults to 'same-origin', so the session cookie is sent. * @param {Object} [options.events] - The player event bus. When provided, the 'keep downloading while paused' preference is kept current from it. * @param {boolean} [options.shouldKeepDownloadingWhilePaused] - The value of the 'keep downloading while paused' setting, seeded by the engine from host.getPreferences(). It is the initial value; later PREFERENCES_CHANGED events and setKeepDownloadingWhilePaused override it. - * @param {Function} [options.onProgress] - Called with the progress snapshot every time the buffer grows. + * @param {Function} [options.onProgress] - Called with the downloaded fraction every time the buffer grows. The full snapshot is only produced once, by the completion callback. * @param {Function} [options.onComplete] - Called once when every byte of the file has been downloaded. * @param {Function} [options.onError] - Called with a {@link LuminaAudioPlayer.PlayerError} when the download fails. */ @@ -471,8 +508,15 @@ this.isUnusable = false; this.error = null; // A downloader may have one loop request and, at most, an explicit one shot range request in flight at the same - // time, so every controller is tracked and an abort or a destroy cancels all of them, not just the newest. + // time. They are tracked apart: a pause or a pivot only cancels the loop request, while an abort or a destroy + // cancels every request, including an explicit range read such as the one a demuxer seek performs. this.abortControllers = new Set(); + this.oneShotControllers = new Set(); + // The byte range of the loop request that is currently being read, so a seek aware source can tell whether a + // window it needs is already being fetched and does not need a duplicate one shot request. The cursor is the + // exclusive end of the bytes the loop has actually received, so a far window is not mistaken for in flight. + this.activeLoopRange = null; + this.activeLoopCursor = null; this.loopPromise = null; this.waiters = []; this.unsubscribePreferences = null; @@ -605,7 +649,7 @@ */ abort() { this.isAborted = true; - this.cancelActiveRequest(); + this.abortAllRequests(); // The download is stopping and no byte will append until it is started again, so a reader that is waiting for a // byte window is released with the aborted code instead of waiting forever. this.rejectWaiters(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The track download was aborted.')); @@ -619,7 +663,7 @@ async destroyAsync() { this.destroyed = true; this.isAborted = true; - this.cancelActiveRequest(); + this.abortAllRequests(); if (this.unsubscribePreferences) { this.unsubscribePreferences(); this.unsubscribePreferences = null; @@ -648,6 +692,69 @@ return this.buffer.getRanges(); } + /** + * Checks whether the download buffer already holds a byte window, without allocating a range list. It is the + * allocation-free equivalent of searching getRanges and is safe to call on every demuxer read. + * @param {number} offset - The first byte of the window. + * @param {number} length - The length of the window, in bytes. + * @returns {boolean} True when the window is fully buffered. + */ + isRangeCovered(offset, length) { + const start = Math.max(0, Math.floor(offset)); + const size = Math.max(0, Math.floor(length)); + return this.buffer.covers(start, size); + } + + /** + * Gets the byte position the download loop fetches from, or will fetch from once it is allowed to run. + * @returns {number} The loop target byte. + */ + getTargetByte() { + return this.targetByte; + } + + /** + * Gets the exclusive end of the contiguous run of downloaded bytes that starts at or after an offset. A seek aware + * source uses it to start a range request after the bytes it already has instead of re-requesting a whole block. + * @param {number} offset - The byte to start from. + * @returns {number} The exclusive end of the contiguous run. + */ + getContiguousEnd(offset) { + return this.buffer.getContiguousEnd(offset); + } + + /** + * Gets the progress of the active loop request, so a seek aware source can tell a slow loop from a stalled one. + * The range start and the received cursor are both reported, because a new request can start at the same cursor a previous one was abandoned at. + * @returns {{ start: number, cursor: number }|null} The request start and its received cursor, or null when no loop request is active. + */ + getLoopProgress() { + if (!this.activeLoopRange || this.activeLoopCursor === null) + return null; + return { start: this.activeLoopRange.start, cursor: this.activeLoopCursor }; + } + + /** + * Checks whether the loop request that is currently in flight is reading a range that covers a byte window. A seek + * aware source uses it to wait for the bytes that are already on their way instead of issuing a duplicate request. + * @param {number} offset - The first byte of the window. + * @param {number} length - The length of the window, in bytes. + * @returns {boolean} True when the active loop request covers the window. + */ + isRangeBeingFetched(offset, length) { + if (!this.activeLoopRange || this.activeLoopCursor === null || this.destroyed || this.isAborted) + return false; + const start = Math.max(0, Math.floor(offset)); + const end = start + Math.max(0, Math.floor(length)); + // The loop covers a window only when it starts at or before the window, the window has been reached by the + // received cursor or lies within the first fetch block of the loop, and the window is inside the response. A + // window far ahead of the cursor is fetched as a one-shot instead of waiting for the sequential download. + const reachable = Math.max(this.activeLoopCursor, this.activeLoopRange.start + LOOP_IN_FLIGHT_LOOKAHEAD_BYTES); + return this.activeLoopRange.start <= start + && start <= reachable + && end <= this.activeLoopRange.end; + } + /** * Gets the downloaded time ranges, mapped through either the known total size and the duration or, when the size * is not known yet, through the bytes themselves once the whole file is in the buffer. @@ -666,6 +773,28 @@ })); } + /** + * Checks whether a time position is already downloaded, without allocating a time range list. It maps the position + * to a byte through the same total size and duration proportion the time ranges use, and it matches the inclusive + * end of those ranges instead of testing one isolated byte. + * @param {number} seconds - The position to check, in seconds. + * @returns {boolean} True when the position is inside a stored run or at the inclusive end of one. + */ + coversTime(seconds) { + const value = Number(seconds); + const total = this.resolveTotalForMapping(); + if (!Number.isFinite(value) || total === null || total <= 0 || this.duration <= 0) + return false; + const fraction = clamp(value / this.duration, 0, 1); + const byte = Math.floor(fraction * total); + if (this.buffer.covers(byte, 1)) + return true; + // getTimeRanges maps the exclusive end of a byte range to an inclusive time end, so the player treats a + // position exactly at the end of a buffered run as buffered. Checking the end of the run that covers the + // previous byte reproduces that inclusive end without allocating the range list. + return byte > 0 && this.buffer.getContiguousEnd(byte - 1) >= byte; + } + /** * Gets the fraction of the track that has been downloaded, between 0 and 1. * @@ -820,7 +949,7 @@ * @returns {Promise} The outcome, per {@link LuminaAudioPlayer.TrackDownloader#performFetchAsync}. */ downloadRangeAsync(start, end) { - return this.performFetchAsync({ start, end }); + return this.performFetchAsync({ start, end, isOneShot: true }); } /** @@ -830,7 +959,7 @@ * @returns {Promise} The outcome, per {@link LuminaAudioPlayer.TrackDownloader#performFetchAsync}. */ downloadOpenEndedAsync(start) { - return this.performFetchAsync({ start, openEnded: true }); + return this.performFetchAsync({ start, openEnded: true, isOneShot: true }); } /** @@ -840,7 +969,7 @@ * @returns {Promise} The outcome, per {@link LuminaAudioPlayer.TrackDownloader#performFetchAsync}. */ downloadSuffixAsync(length) { - return this.performFetchAsync({ suffix: length }); + return this.performFetchAsync({ suffix: length, isOneShot: true }); } //+======================================================================================+ @@ -888,13 +1017,33 @@ } /** - * Cancels every in flight request through its AbortController. A pause, a pivot, an abort and a destroy all route - * here, so no request, and no connection, is left open behind one that another controller replaced. + * Cancels the in flight requests of the download loop through their AbortControllers. A pause, a resume and a + * pivot route here, and they deliberately leave explicit one shot range requests alone: a demuxer that is scanning + * for a seek target must not be interrupted by a pause that happens while the scan is running. */ cancelActiveRequest() { - if (this.abortControllers.size === 0) + this.abortRequests(this.abortControllers); + } + + /** + * Cancels every in flight request, including explicit one shot range requests. An intentional abort, a destroy and + * the start of a new seek route here, so no stale read and no connection is left behind. + */ + abortAllRequests() { + this.activeLoopRange = null; + this.activeLoopCursor = null; + this.abortRequests(this.abortControllers); + this.abortRequests(this.oneShotControllers); + } + + /** + * Aborts every controller in one of the request sets. + * @param {Set} controllers - The controllers to abort. + */ + abortRequests(controllers) { + if (controllers.size === 0) return; - for (const controller of [...this.abortControllers]) { + for (const controller of [...controllers]) { try { controller.abort(); } catch (error) { @@ -995,17 +1144,37 @@ * @param {number} [spec.suffix] - The number of trailing bytes to request. * @param {boolean} [spec.openEnded] - True to request an open ended range, from start to the end of the file. * @param {boolean} [spec.stopOnPause] - True when a paused player must stop this request at the next chunk. The download loop sets it; a one shot range request does not, so an explicit request always completes. + * @param {boolean} [spec.isOneShot] - True for an explicit range request. Such a request is tracked apart from the + * loop request and is not cancelled by a pause or a pivot, only by abort() or destroyAsync(). * @returns {Promise} The outcome, one of: { isFailed: true, error } when the request failed, { isAborted: true } when it was aborted, { isDestroyed: true } when the downloader was destroyed, { isSatisfied: true } when the range was already satisfied, or { isAborted, isFailed: false, isDestroyed, isStopped } for a read that ended. It never rejects. */ async performFetchAsync(spec = {}) { if (this.destroyed) return { isDestroyed: true, isAborted: false, isFailed: false }; + // An explicit range request must not reopen a request after an intentional abort. startAsync clears the aborted + // state before it starts the loop again, so a request issued for a live timeline still runs. + if (this.isAborted) + return { isAborted: true, isFailed: false, isDestroyed: false }; if (this.fetchImpl === null || this.url === '') { this.isUnusable = true; return { isFailed: true, error: new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The download request could not be built.') }; } const controller = new AbortController(); - this.abortControllers.add(controller); + // An explicit range request is not cancelled by a pause or a pivot, because a seek scan must be able to read + // its windows while playback is paused. Only abort(), destroyAsync() or its own timeout cancel it. + const controllers = spec.isOneShot === true ? this.oneShotControllers : this.abortControllers; + controllers.add(controller); + let didTimeout = false; + const timeoutTimer = spec.isOneShot === true + ? setTimeout(() => { + didTimeout = true; + try { + controller.abort(); + } catch (error) { + console.debug('Audio player: the timed out range request could not be aborted.', error); + } + }, ONE_SHOT_REQUEST_TIMEOUT_MS) + : null; let response = null; try { response = await this.fetchImpl(this.url, { @@ -1022,8 +1191,44 @@ return { isAborted: false, isFailed: false, isDestroyed: this.destroyed, isSatisfied: true }; } this.noteTotal(resolved.total); - return await this.readResponseIntoBufferAsync(response, resolved, controller, spec.stopOnPause === true, spec.openEnded === true); + if (spec.isOneShot !== true) { + // The loop request is open ended in practice, and this is the range it is actually reading. A window + // inside it is already being fetched, so a seek aware source can simply wait for it. + this.activeLoopRange = { + start: resolved.start, + end: resolved.endInclusive === null ? Number.POSITIVE_INFINITY : resolved.endInclusive + }; + this.activeLoopCursor = resolved.start; + } + // A bounded one shot request keeps the exact window it asked for, so a server or proxy that ignores Range + // and answers with a 200 cannot make the read store the whole resource. The window is only used for a 200 + // response; a 206 already carries its own range. + let readWindow = null; + if (spec.isOneShot === true && Number.isFinite(Number(spec.start)) && Number.isFinite(Number(spec.end))) { + const windowStart = Math.max(0, Math.floor(Number(spec.start))); + const windowEnd = Math.max(windowStart, Math.floor(Number(spec.end))); + readWindow = { start: windowStart, length: windowEnd - windowStart + 1 }; + } else if (spec.isOneShot === true && Number.isFinite(Number(spec.suffix)) && resolved.total !== null) { + const windowLength = Math.min(resolved.total, Math.max(1, Math.floor(Number(spec.suffix)))); + readWindow = { start: resolved.total - windowLength, length: windowLength }; + } + const outcome = await this.readResponseIntoBufferAsync(response, resolved, controller, spec.stopOnPause === true, spec.openEnded === true, readWindow, spec.isOneShot !== true); + // A timeout that fires during the body read is caught inside the read and reported as an abort. It is still + // a failed request, so it is mapped to the same timeout failure as a timeout before the body started, and + // a seek does not retry it with another full deadline. + if (didTimeout && outcome.isAborted) { + this.discardResponseBody(response); + return { isFailed: true, isAborted: false, isDestroyed: this.destroyed, error: createRangeTimeoutError() }; + } + return outcome; } catch (error) { + // A timeout is not an intentional stop: it is a failed request, so a seek does not retry it with another + // full timeout and the bar does not stay in its loading state for double the deadline. The check comes + // first because an abort can surface as an AbortError or as a body read error, depending on the browser. + if (didTimeout) { + this.discardResponseBody(response); + return { isFailed: true, isAborted: false, isDestroyed: this.destroyed, error: createRangeTimeoutError() }; + } if (LuminaAudioPlayer.isAbortError(error)) return { isAborted: true, isFailed: false, isDestroyed: this.destroyed }; // The failure left the response body unread, so it is discarded and the request is aborted to release the @@ -1037,7 +1242,13 @@ } return { isFailed: true, error: LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED) }; } finally { - this.abortControllers.delete(controller); + if (timeoutTimer !== null) + clearTimeout(timeoutTimer); + if (spec.isOneShot !== true) { + this.activeLoopRange = null; + this.activeLoopCursor = null; + } + controllers.delete(controller); } } @@ -1122,16 +1333,24 @@ * @param {AbortController} controller - The controller of the request, aborted when the loop must stop. * @param {boolean} stopOnPause - True when a paused player must stop the read at the next chunk boundary. * @param {boolean} openEnded - True when the request asked for a range that runs to the end of the file. Such a read is driven to the end of the body, and that end proves the end of the file, rather than the range the response happens to declare. + * @param {{ start: number, length: number }|null} [readWindow] - The bounded window a one shot request asked for. When the server answered with a 200 instead of a range, the body is read up to the end of this window, only the bytes of the window are stored, and the rest of the body is discarded. + * @param {boolean} [isLoopRequest=false] - True when this read belongs to the download loop. The received cursor of the loop is advanced per chunk so a seek aware source only waits for windows the loop is actually reaching. * @returns {Promise} The outcome of the read. * @throws {LuminaAudioPlayer.PlayerError} When the response carries no readable body. */ - async readResponseIntoBufferAsync(response, range, controller, stopOnPause, openEnded) { + async readResponseIntoBufferAsync(response, range, controller, stopOnPause, openEnded, readWindow = null, isLoopRequest = false) { if (!response.body || typeof response.body.getReader !== 'function') throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The stream response carried no readable body.'); const reader = response.body.getReader(); let offset = range.start; + if (isLoopRequest) + this.activeLoopCursor = offset; let isStopped = false; let hasReachedEnd = false; + // A 200 response means the server ignored the range. A bounded one shot request then stores only its own window + // and can stop reading as soon as that window is complete, instead of pulling the whole resource into memory. + const isFullResourceWindow = readWindow !== null && range.endInclusive === null; + const readWindowEnd = readWindow !== null ? readWindow.start + readWindow.length : null; // True when a bounded request read its whole declared range and stopped before the body ended, so any remaining // bytes are discarded. An open ended request instead reads the body to its end, because that end, and not the // range the response happens to declare, is the only signal that proves the end of the file. @@ -1159,15 +1378,35 @@ const value = result.value; if (!value || value.byteLength === 0) continue; - this.buffer.append(offset, value); - offset += value.byteLength; - this.notifyProgress(); - this.resolveWaiters(); - // A bounded request stops once it has read the range it asked for, while an open ended request reads on - // to the end of the body, so a capped response is not mistaken for the end of the file. - if (!openEnded && range.endInclusive !== null && offset > range.endInclusive) { - isStoppedAtRangeEnd = true; - break; + if (isFullResourceWindow) { + // The body starts at the beginning of the resource, so the bytes before the requested window are + // consumed and dropped, and only the requested window is stored, at its absolute offset. + const chunkStart = offset; + const from = Math.max(chunkStart, readWindow.start); + const to = Math.min(chunkStart + value.byteLength, readWindowEnd); + if (to > from) { + this.buffer.append(from, value.subarray(from - chunkStart, to - chunkStart)); + this.notifyProgress(); + this.resolveWaiters(); + } + offset += value.byteLength; + if (offset >= readWindowEnd) { + isStoppedAtRangeEnd = true; + break; + } + } else { + this.buffer.append(offset, value); + offset += value.byteLength; + if (isLoopRequest) + this.activeLoopCursor = offset; + this.notifyProgress(); + this.resolveWaiters(); + // A bounded request stops once it has read the range it asked for, while an open ended request reads + // on to the end of the body, so a capped response is not mistaken for the end of the file. + if (!openEnded && range.endInclusive !== null && offset > range.endInclusive) { + isStoppedAtRangeEnd = true; + break; + } } } } finally { @@ -1264,7 +1503,9 @@ if (!this.onProgress) return; try { - this.onProgress(this.getProgress()); + // Only the fraction is built per chunk: the full snapshot allocates range lists and is reserved for the + // completion callback, where it is produced once per track. + this.onProgress(this.getDownloadedFraction()); } catch (error) { console.error('Audio player: the download progress callback threw.', error); } diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js index 673ff0bd..8fe463fe 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js @@ -10,7 +10,9 @@ * -------------------- * An engine is created by a factory that receives the engine host (see below) and returns an object * with these methods, all of them returning a Promise: - * - loadAsync(descriptor): prepares the resources of a track (opens its stream, configures a decoder). + * - loadAsync(descriptor, options): prepares the resources of a track (opens its stream, configures a decoder). + * options.keepBuffering keeps a loading state the player handed to the load, used by an automatic continuation so the + * teardown of the previous track does not clear it during the end gap. * - playAsync(): starts, or resumes, audible playback. * - pauseAsync(): suspends audible playback, keeping the current position. * - seekAsync(seconds): moves the playhead to the given position, in seconds, fetching the range of that position @@ -19,15 +21,38 @@ * - getBufferedTimeRanges(): the time ranges, in seconds, the engine already downloaded, as a list of objects with * a 'start' and an 'end'. It is optional: an engine that does not implement it makes the player unable to tell * whether a seek target is buffered, in which case the player never shows a loading state for a seek. + * - discardCurrentAsync() (optional): releases the currently prepared track without destroying the engine, so a stop + * during an automatic continuation does not leave the track it started loaded behind an idle player. * - destroyAsync(): releases every resource the engine holds, including any audio context. * * The engine host * --------------- * The factory also receives a host object that the engine uses to talk back to the controller, so * that the controller stays the single source of truth: - * - host.events: the player event bus, for {@link LuminaAudioPlayer.PlayerEvent} values the engine emits itself. + * - host.events: the player event bus, for {@link LuminaAudioPlayer.PlayerEvent} values the engine emits itself. It is + * also the inbound channel: an engine and the renderer subscribe to PREFERENCES_CHANGED to follow a gapless or + * ReplayGain preference that changes while a track is playing. * - host.getPreferences(): the playback preferences of the user the player currently holds, for example the * 'keep downloading while paused' setting an engine's downloader honors. + * - host.getConfiguration(): the endpoint configuration of the player, so an engine never keeps a second copy of it. + * - host.fetchJsonAsync(url, signal, label): the player's JSON transport. The optional signal cancels the request, the + * label describes it in the failure log, and an expired session redirect is followed to the sign in page and reported + * through the player's REDIRECTED marker, so an engine request behaves like the player's other background requests. + * - host.getCapabilityDetector(): the browser capability detector of the player, so an engine does not run a second + * capability detection. + * - host.getNextDescriptor(): { entryId, descriptor } of the queue entry that follows the current one, or null at the + * end of the queue. It is the player's own queue cursor, so an engine never re-implements queue traversal or picks + * the wrong repeated track. + * - host.advanceQueueTo(entryId): moves the player queue cursor to the entry with that identity without starting + * playback, which an engine uses for a gapless transition whose audio is already scheduled immediately after the current + * track. The advance is refused when the identity is no longer part of the queue, so the bar never describes a track + * that is not playing. A linear advance, a wrap and a reordered queue all use this same commit. + * - host.requestNextTrackAsync(reason): asks the player to start the next queue entry through its own play path, which + * owns the player state, the pause intent and the capability gate. An engine uses it when a gapless handoff could not + * be prepared, instead of starting a playback session itself. The returned Promise resolves true when the + * player took ownership of the transition, including a load it will report as failed, and false when it declined the + * request because the player is paused, stopped, or has no next entry. An engine must not report an end for a + * transition the player owns, and keeps the end it just reported when the promise resolves false. * - host.reportTime(currentTime, duration): reports the playhead and the known duration. * - host.reportDuration(duration): reports a duration discovered after loading. * - host.reportProgress(downloadedFraction): reports how much of the track has been downloaded, between 0 and 1. @@ -42,9 +67,10 @@ * * Registering and selecting an engine * ----------------------------------- - * Engines are registered on a registry by name, and the player runs the engine selected by name. The silent engine - * is registered under NULL_ENGINE_NAME and is the default, so the player is usable before the real pipeline exists. - * The singleton is created automatically when the module loads, so the way to plug a real engine into the running + * Engines are registered on a registry by name, and the player runs the engine selected by name. The silent engine is + * registered under NULL_ENGINE_NAME and is the default of a bare player, but the shipped composition installs the media + * pipeline engine when that module loads and selects it, so the running application plays through the pipeline. The + * singleton is created automatically when the core module loads, so the way to plug a different engine into the running * application is the instance seam: * - window.LuminaAudioPlayer.instance.registerEngine(name, factory) registers a factory of the shape (host) => engine. * - window.LuminaAudioPlayer.instance.useEngine(name) selects a registered engine; it takes effect on the next load, @@ -66,10 +92,11 @@ /** * An engine that fulfills the engine interface without producing any audio. * - * It is the default engine of the core module, so that the control API, the state machine, the - * lifecycle and the bar are fully callable before the download, decode and render pipeline is - * wired up. It tracks a playhead so that a seek, a pause and a resume report the position the - * player expects, but it never loads, decodes or plays a byte. + * It is the default engine of a bare player, so that the control API, the state machine, the + * lifecycle and the bar are fully callable before, or without, the media pipeline. The shipped + * composition selects the pipeline when that module loads. This engine tracks a playhead so that + * a seek, a pause and a resume report the position the player expects, but it never loads, + * decodes or plays a byte. */ class NullPlayerEngine { /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js index c40509cd..b513f41d 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -73,7 +73,20 @@ // stopped with no gap left to fill. Published by the download engine and recognized by the demuxer byte source, // which reads it as end of file rather than as a failure, so a rename on either side cannot silently turn a // drained window into a fatal read error. - WINDOW_UNAVAILABLE: 'window-unavailable' + WINDOW_UNAVAILABLE: 'window-unavailable', + // A range request exceeded its timeout. Unlike an intentional abort, this is a failed request and is not retried + // by the seek recovery. + REQUEST_TIMEOUT: 'request-timeout', + // The playback manifest says the track is not a direct play, so the server has to normalize its container or its + // codec before the bundled player can play it. Published by the media pipeline engine while the normalized + // delivery pipeline does not exist yet, instead of playing the stored bytes. + NORMALIZED_DELIVERY_REQUIRED: 'normalized-delivery-required', + // A load was overtaken by a newer play request before it finished. The player ignores it, because the newer + // request owns the player state and the queue. + LOAD_SUPERSEDED: 'load-superseded', + // The session expired while a manifest was requested, and the player is already navigating to the sign in page. + // The player ignores it, because it is an expected outcome of an expired session, not a playback failure. + SESSION_EXPIRED: 'session-expired' }); /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js new file mode 100644 index 00000000..e3d37771 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js @@ -0,0 +1,321 @@ +/** + * Playback manifest client of the audio player. + * + * It owns the transport concerns of a playback manifest: expanding the manifest route template with the Ids of a play + * descriptor, appending the capability query, applying the request timeout, following the player's redirect policy, and + * validating the stream path before a request that sends the session cookie is made. The playback engine and the later + * normalized delivery pipeline both consume it, so the route, capability and same-origin rules are defined once. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The timeout, in milliseconds, of a playback manifest request. + * @readonly + * @type {number} + */ + const MANIFEST_REQUEST_TIMEOUT_MS = 20000; + + /** + * Checks whether a value is a Guid, the only form the manifest route accepts for its Ids. + * @param {*} value - The value to check. + * @returns {boolean} True when the value is a Guid string. + */ + function isGuid(value) { + return typeof value === 'string' + && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value); + } + + /** + * Gets the origin this module resolves relative URLs against. The page origin is used in a browser; a fixed local + * origin keeps the route and origin checks testable in a host without a DOM. + * @returns {string} The base origin. + */ + function getBaseOrigin() { + return typeof window !== 'undefined' && window.location && window.location.origin + ? window.location.origin + : 'http://localhost'; + } + + /** + * Checks whether the module can compare a URL against the page origin. + * @returns {boolean} True when a page origin is available. + */ + function hasWindowOrigin() { + return typeof window !== 'undefined' && !!window.location && !!window.location.origin; + } + + /** + * Resolves and validates a path that a request carrying the session cookie will fetch. + * + * The value is built by the server, but it is validated again here as defense in depth: it must be a root relative + * path on this origin, with no backslash, control character, fragment, userinfo, dot segment, or encoded path + * separator that a browser could normalize into another location. The resolved absolute URL is returned, pinned to + * this origin by construction, so a base element can never redirect the fetch to another origin. + * @param {*} value - The path to validate. + * @returns {{ href: string, url: URL }} The validated resolved path and its parsed URL. + * @throws {LuminaAudioPlayer.PlayerError} When the path is not a safe same-origin root relative path. + */ + function resolveSameOriginUrl(value) { + if (typeof value !== 'string' || value.length === 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The request carries no path.'); + if (!value.startsWith('/') || value.startsWith('//')) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path is not a root relative path.'); + if (/[\u0000-\u001f\u007f\\#]/.test(value)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path carries a forbidden character.'); + const queryIndex = value.indexOf('?'); + const path = queryIndex >= 0 ? value.slice(0, queryIndex) : value; + // Decode every segment before judging it. The browser normalizes %2e%2e, %2f and %5c after the string is accepted, + // so checking only the raw text would let an encoded separator or dot segment through. + for (const segment of path.split('/')) { + if (segment === '') + continue; + let decoded; + try { + decoded = decodeURIComponent(segment); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path carries an invalid escape.', { cause: error }); + } + if (decoded === '.' || decoded === '..' || decoded.includes('/') || decoded.includes('\\') + || /[\u0000-\u001f\u007f]/.test(decoded)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path carries a traversal segment.'); + } + // Resolve last, so the returned href is absolute and a base element cannot change where the fetch goes. A host + // without a DOM uses the synthetic base only for parsing and keeps the raw path. + let resolved; + try { + resolved = new URL(value, getBaseOrigin()); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path is not a valid URL.', { cause: error }); + } + // A request with credentials or a non-http scheme is not one this player is allowed to make, and an origin other + // than the page origin would send the session cookie somewhere it must never go. + if ((resolved.protocol !== 'http:' && resolved.protocol !== 'https:') + || (hasWindowOrigin() && resolved.origin !== window.location.origin) + || resolved.username !== '' + || resolved.password !== '') + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path is not on this origin.'); + return { href: hasWindowOrigin() ? resolved.href : value, url: resolved }; + } + + /** + * Checks that a resolved stream path matches the stream route template this application emitted and belongs to the + * expected track and library. The template is the single source of truth for the route's static segments, their order + * and its placeholders, so a server route rename or an inserted segment does not need a matching client edit. The + * same-origin check alone is not enough: the session cookie and the Range header are sent before the response is + * inspected, so a state changing GET route on this origin must never be reachable as a stream. + * @param {URL} url - The resolved stream URL. + * @param {Object} descriptor - The play descriptor the manifest belongs to. + * @param {Object} configuration - The endpoints configuration of the player. + * @throws {LuminaAudioPlayer.PlayerError} When the route template is missing, is on another origin, or the path does not match the route or the expected track and library Ids. + */ + function validateStreamRoute(url, descriptor, configuration) { + const templateValue = configuration && configuration.streamTrackRouteTemplate; + if (typeof templateValue !== 'string' || templateValue.length === 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream route template is not configured.'); + let template; + try { + template = new URL(templateValue, getBaseOrigin()); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream route template is not a valid URL.', { cause: error }); + } + if ((template.protocol !== 'http:' && template.protocol !== 'https:') + || (hasWindowOrigin() && template.origin !== window.location.origin) + || template.origin !== url.origin + || template.username !== '' + || template.password !== '') + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream route template is not on this origin.'); + const expectedIds = { + artistId: descriptor && descriptor.artistId, + albumId: descriptor && descriptor.albumId, + trackId: descriptor && descriptor.trackId + }; + const templateSegments = template.pathname.split('/'); + const streamSegments = url.pathname.split('/'); + if (templateSegments.length !== streamSegments.length) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream path does not match the stream route.'); + for (let index = 0; index < templateSegments.length; index++) { + let templateSegment; + try { + // The URL parser percent-encodes braces, so a template segment has to be decoded before it can be recognized as a placeholder. + templateSegment = decodeURIComponent(templateSegments[index]); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream route template carries an invalid escape.', { cause: error }); + } + const placeholder = /^\{([A-Za-z0-9_]+)\}$/.exec(templateSegment); + if (placeholder) { + const name = placeholder[1]; + if (!Object.prototype.hasOwnProperty.call(expectedIds, name)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream route template carries an unknown placeholder.'); + const expected = expectedIds[name]; + if (!isGuid(expected)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, `The play descriptor carries no valid ${name}.`, { field: name }); + const actual = streamSegments[index]; + // The path must describe the track of this descriptor, not merely another track of the same library. + if (!isGuid(actual) || actual.toLowerCase() !== expected.toLowerCase()) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream path does not belong to the expected track.'); + continue; + } + let actualSegment; + try { + // Decode the actual segment too, so a path base or a static segment that contains an encoded character still compares equal to the template it came from. + actualSegment = decodeURIComponent(streamSegments[index]); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream path carries an invalid escape.', { cause: error }); + } + if (templateSegment !== actualSegment) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream path does not match the stream route.'); + } + const libraryId = descriptor && descriptor.libraryId; + if (!isGuid(libraryId)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, 'The play descriptor carries no valid library Id.', { field: 'libraryId' }); + const requestedLibraryIds = url.searchParams.getAll('libraryId'); + if (requestedLibraryIds.length !== 1 || requestedLibraryIds[0].toLowerCase() !== libraryId.toLowerCase()) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream path does not belong to the expected library.'); + } + + /** + * Resolves the stream path of a playback manifest into the URL the player fetches, after checking that it points at + * the stream route of the expected track and library. + * @param {Object} manifest - The playback manifest. + * @param {Object} descriptor - The play descriptor the manifest belongs to. + * @param {Object} configuration - The endpoints configuration of the player. + * @returns {string} The validated resolved stream URL. + * @throws {LuminaAudioPlayer.PlayerError} When the manifest carries no safe stream path or the path is not the + * stream route of the expected track and library. + */ + function resolveStreamUrl(manifest, descriptor, configuration) { + const resolved = resolveSameOriginUrl(manifest && manifest.streamPath); + validateStreamRoute(resolved.url, descriptor, configuration); + return resolved.href; + } + + /** + * Builds the URL of the playback manifest endpoint for a descriptor, including the capability list. + * @param {Object} configuration - The endpoints configuration of the player. + * @param {Object} descriptor - The play descriptor of the track. + * @param {string} capabilities - The comma separated container and codec capability list, or an empty string. + * @returns {string} The absolute manifest URL, pinned to this origin. + * @throws {LuminaAudioPlayer.PlayerError} When the descriptor or the configuration is incomplete, or the endpoint is not on this origin. + */ + function buildManifestUrl(configuration, descriptor, capabilities) { + const template = configuration && configuration.getPlaybackManifestUrl; + if (!template) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest endpoint is not configured.'); + const ids = { + artistId: descriptor.artistId, + albumId: descriptor.albumId, + trackId: descriptor.trackId, + libraryId: descriptor.libraryId + }; + for (const name of Object.keys(ids)) { + if (!ids[name]) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, `The play descriptor carries no ${name}.`, { field: name }); + // The manifest route only accepts Guids, and a value that is not a Guid must never be interpolated into a path the browser resolves against this origin. + if (!isGuid(ids[name])) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, `The play descriptor carries an invalid ${name}.`, { field: name }); + } + let url = String(template) + .split('{artistId}').join(encodeURIComponent(ids.artistId)) + .split('{albumId}').join(encodeURIComponent(ids.albumId)) + .split('{trackId}').join(encodeURIComponent(ids.trackId)); + const separator = url.includes('?') ? '&' : '?'; + url = `${url}${separator}libraryId=${encodeURIComponent(ids.libraryId)}`; + if (capabilities) + url = `${url}&capabilities=${encodeURIComponent(capabilities)}`; + // The manifest template is request derived, and the manifest is the response that controls the next fetches, so + // it is resolved against this origin and a different origin is refused instead of being requested. + let resolved; + try { + resolved = new URL(url, getBaseOrigin()); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest endpoint is not a valid URL.', { cause: error }); + } + if ((resolved.protocol !== 'http:' && resolved.protocol !== 'https:') + || (hasWindowOrigin() && resolved.origin !== window.location.origin) + || resolved.username !== '' + || resolved.password !== '') + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest endpoint is not on this origin.'); + return resolved.href; + } + + /** + * Creates an AbortSignal for a manifest request that aborts on the external signal or after the manifest timeout. + * @param {AbortSignal} [externalSignal] - The signal of the caller, for example the load or prefetch signal. + * @returns {{ signal: AbortSignal|undefined, dispose: Function }} The signal to use, and the cleanup that clears the timeout and the external listener. + */ + function createTimedRequestSignal(externalSignal) { + // A host without AbortController cannot combine a timeout with the caller's signal, so it passes that signal through. Cancellation still belongs to the caller in that case. + if (typeof AbortController !== 'function') + return { signal: externalSignal, dispose: () => {} }; + const controller = new AbortController(); + const abort = () => { + try { + controller.abort(); + } catch (error) { + console.debug('Audio player: the manifest request could not be aborted.', error); + } + }; + const onExternalAbort = () => abort(); + if (externalSignal) { + if (externalSignal.aborted) + abort(); + else + // A cancelled load or prefetch must cancel the manifest request too, otherwise a superseded prefetch keeps + // a connection and its timeout alive. + externalSignal.addEventListener('abort', onExternalAbort, { once: true }); + } + // A manifest that never answers must not hold a load forever. The deadline is independent of the caller's signal, so a stalled server cannot leave the player loading indefinitely. + const timer = setTimeout(abort, MANIFEST_REQUEST_TIMEOUT_MS); + return { + signal: controller.signal, + dispose: () => { + clearTimeout(timer); + // Remove the listener on both success and failure, so a long lived external signal does not retain this request after it settled. + if (externalSignal) + externalSignal.removeEventListener('abort', onExternalAbort); + } + }; + } + + /** + * Fetches the playback manifest of a track from the web application. + * @param {Object} options - The request options. + * @param {Object} options.configuration - The endpoints configuration of the player. + * @param {Object} options.descriptor - The play descriptor of the track. + * @param {string} options.capabilities - The comma separated capability list, or an empty string. + * @param {Function} options.transport - The JSON transport, in the shape of the player's fetchJsonAsync. It receives the + * URL, an optional signal, a label and a request options object with redirect: 'manual', so a redirect target is validated before the browser follows it. + * @param {AbortSignal} [options.signal] - An optional signal that cancels the request, used by a cancelled prefetch. + * @returns {Promise} The playback manifest. + * @throws {LuminaAudioPlayer.PlayerError} When the descriptor is incomplete, the session expired, or the manifest could not be read. + */ + async function fetchPlaybackManifestAsync(options) { + const settings = options || {}; + const transport = settings.transport; + if (typeof transport !== 'function') + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest transport is not configured.'); + const url = buildManifestUrl(settings.configuration, settings.descriptor, settings.capabilities || ''); + const request = createTimedRequestSignal(settings.signal); + try { + let data; + try { + data = await transport(url, request.signal, 'a playback manifest request', { redirect: 'manual' }); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest of the track could not be requested.', { cause: error }); + } + if (data === LuminaAudioPlayer.REDIRECTED) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The session expired while the playback manifest was requested.', { reason: LuminaAudioPlayer.PlayerErrorReason.SESSION_EXPIRED }); + if (data === undefined) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest of the track could not be requested.'); + if (!data || typeof data !== 'object') + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest of the track carried no data.'); + return data; + } finally { + request.dispose(); + } + } + + LuminaAudioPlayer.resolveStreamUrl = resolveStreamUrl; + LuminaAudioPlayer.fetchPlaybackManifestAsync = fetchPlaybackManifestAsync; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js new file mode 100644 index 00000000..1a7691fc --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js @@ -0,0 +1,352 @@ +/** + * Seek-aware byte source of the audio player pipeline. + * + * It fetches an uncovered demuxer window on demand, coalesced into an aligned block, while a seek or a gapless prefetch + * needs bytes the regular download loop is not fetching, and it never issues a duplicate request for a window the running loop is already reading. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The block size, in bytes, of an on-demand range fetch. A demuxer seek reads small windows one after another, so a + * request per window would pay a network round trip for each read; the windows are coalesced into aligned blocks of + * this size, which are still bounded and are stored in the same buffer the demuxer reads from. + * @readonly + * @type {number} + */ + const SEEK_FETCH_BLOCK_BYTES = 256 * 1024; + + /** + * How long the received cursor of the download loop may stay unchanged before a read that is waiting for that loop + * falls back to a one-shot range request, in milliseconds. A loop response that sends headers and then stalls has no + * deadline of its own, so without this bound a seek near the loop frontier would wait until the user resumes or aborts. + * @readonly + * @type {number} + */ + const LOOP_STALL_FALLBACK_MS = 3000; + + /** + * How often the progress of the download loop is checked while a read waits for it, in milliseconds. + * @readonly + * @type {number} + */ + const LOOP_STALL_POLL_MS = 100; + + /** + * A byte source for a demuxer that fetches an uncovered window on demand instead of waiting for a download loop. + * + * It serves two situations. A demuxer seek is not a sequential read: OGG binary-searches the byte range, and MP3 and + * AAC scan forward from an estimate that may lie below the target. Those reads can fall into a gap below the byte + * target the download loop is fetching, and a plain downloader read would then wait for a window the loop never + * fetches, in practice for the rest of the file. A gapless prefetch has no download loop at all, by design, so that it + * never runs a second open-ended download next to the current one. In both cases an uncovered window is fetched as a + * one-shot bounded range, coalesced with its neighbours into an aligned block of a few hundred kilobytes, and stored + * in the download buffer, so the demuxer can continue immediately and a later sequential read finds the same bytes in + * the buffer instead of fetching them again. A window that the running download loop is already fetching is awaited + * instead of being requested twice. The on-demand mode is switched off when a seek has scheduled its first frame, or + * when a prefetch is handed over and its download loop starts. + */ + class SeekAwareByteSource { + /** + * Creates an instance of SeekAwareByteSource. + * @param {LuminaAudioPlayer.TrackDownloader} downloader - The downloader of the track. + */ + constructor(downloader) { + this.downloader = downloader; + // The regular byte source owns the end-of-stream behavior of a downloader read: a window that reaches past the + // end is shortened, and a window that can no longer be filled reads as the end of the file. Delegating to it + // keeps that behavior identical whether the window came from a one-shot seek fetch or from the download loop. + this.standard = new LuminaAudioPlayer.DemuxerByteSource(downloader); + this.isSeeking = false; + this.destroyed = false; + // Incremented by every new seek, so a read that is still waiting for a previous seek can tell that a newer seek + // owns the timeline and release the demuxer operation instead of fetching a window for the outdated one. + this.seekGeneration = 0; + } + + /** + * Sets whether the demuxer is currently resolving a seek, which enables the on-demand range fetch. Every new seek + * starts a new generation, which invalidates the reads of the seek it replaced. + * @param {boolean} value - True while a seek is being resolved. + */ + setSeeking(value) { + const next = value === true; + if (next) + this.seekGeneration += 1; + this.isSeeking = next; + } + + /** + * Gets the total size of the stream, when the downloader knows it. + * @returns {number|null} The length in bytes, or null. + */ + getLength() { + return this.standard.getLength(); + } + + /** + * Reads a window of bytes, fetching it with a one-shot range request when a seek needs a window below the byte + * target of the download loop. + * @param {number} offset - The first byte to read. + * @param {number} length - The number of bytes to read. + * @returns {Promise} The bytes, possibly shorter at the end of the stream. + * @throws {LuminaAudioPlayer.PlayerError} When the seek range cannot be fetched, or the read was aborted. + */ + async readAsync(offset, length) { + if (this.destroyed) + return new Uint8Array(0); + const seekGeneration = this.seekGeneration; + if (this.isDownloaderAborted()) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.'); + const start = Math.max(0, Math.floor(offset)); + let size = Math.max(0, Math.floor(length)); + if (size === 0) + return new Uint8Array(0); + const total = this.downloader.getTotalBytes(); + if (total !== null) { + if (start >= total) + return new Uint8Array(0); + size = Math.min(size, total - start); + } + const targetByte = typeof this.downloader.getTargetByte === 'function' + ? this.downloader.getTargetByte() + : (Number.isInteger(this.downloader.targetByte) ? this.downloader.targetByte : null); + // The read offset alone never ends the on-demand mode: a demuxer seek can probe far ahead of the seek target, and + // the loop will not reach such a window for a long time. The engine clears the mode once the target's first frame + // is scheduled; until then isWindowCovered and isRangeBeingFetched decide whether a one-shot is needed, and reads + // behind the loop frontier stay on demand through isBelowLoopTarget. + const isBelowLoopTarget = targetByte !== null && start < targetByte; + // Serve the read from the cheapest source that can complete it: the buffer, the download loop that is already + // reading the same region, or a bounded one-shot. The order matters: a covered read must not touch the network, + // and a loop-covered read must not be requested twice. + if ((this.isSeeking || isBelowLoopTarget) && !this.isWindowCovered(start, size)) { + if (this.isLoopFetching(start, size)) { + // The regular read registers an event driven waiter that resolves the moment the loop stores the window, + // so a normal delivery adds no polling delay. A watchdog races it only to bound a loop that stalls or is replaced by a newer seek. + if (typeof this.downloader.getLoopProgress === 'function') + return this.readWhileLoopAsync(start, size, seekGeneration, total); + return this.standard.readAsync(start, size); + } + return this.fetchOnDemandAsync(start, size, total, seekGeneration); + } + return this.standard.readAsync(start, size); + } + + /** + * Reads a window the download loop is already fetching, racing the regular event driven read against a watchdog + * for a stalled, aborted or superseded loop. The read wins immediately when the loop delivers the window. + * @param {number} start - The first byte of the window. + * @param {number} size - The number of bytes of the window. + * @param {number} seekGeneration - The seek generation the read belongs to. + * @param {number|null} total - The total size of the stream, or null when it is unknown. + * @returns {Promise} The bytes, possibly shorter at the end of the stream. + */ + async readWhileLoopAsync(start, size, seekGeneration, total) { + const readPromise = this.standard.readAsync(start, size); + const readOutcome = readPromise.then( + (bytes) => ({ isRead: true, bytes }), + (error) => ({ isRead: false, error }) + ); + const watchdog = this.createLoopStallWatchdog(start, size, seekGeneration); + let result; + try { + result = await Promise.race([ + readOutcome, + watchdog.promise.then((reason) => ({ isWatchdog: true, reason })) + ]); + } finally { + watchdog.dispose(); + } + if (result.isRead) + return result.bytes; + if (!result.isWatchdog) { + // A read that the loop can no longer fill falls back to a one-shot, exactly like a watchdog that saw the + // loop stop fetching. Any other failure, including an abort, propagates. + if (!result.error) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The seek range request failed.'); + if (LuminaAudioPlayer.isDownloadAbort(result.error) + || !result.error.details + || result.error.details.reason !== LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE) + throw result.error; + if (this.isDownloaderAborted() || this.seekGeneration !== seekGeneration) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.'); + if (this.isWindowCovered(start, size)) + return this.standard.readAsync(start, size); + return this.fetchOnDemandAsync(start, size, total, seekGeneration); + } + // The regular read stays pending until the fallback one-shot stores the same window, or until the downloader is + // torn down and rejects it. It must not become an unhandled rejection in either case. + readPromise.catch(() => {}); + if (result.reason === 'aborted' || result.reason === 'superseded' + || this.isDownloaderAborted() || this.seekGeneration !== seekGeneration) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.'); + if (this.isWindowCovered(start, size)) + return this.standard.readAsync(start, size); + return this.fetchOnDemandAsync(start, size, total, seekGeneration); + } + + /** + * Checks whether the download buffer already holds the whole requested window, without allocating a range list. + * @param {number} start - The first byte of the window. + * @param {number} size - The number of bytes of the window. + * @returns {boolean} True when the window is fully buffered. + */ + isWindowCovered(start, size) { + if (typeof this.downloader.isRangeCovered === 'function') + return this.downloader.isRangeCovered(start, size); + const end = start + size; + return this.downloader.getRanges().some((range) => range.start <= start && range.end >= end); + } + + /** + * Checks whether the download loop is already reading a range that covers the window, in which case the read waits for those bytes instead of issuing a duplicate request. + * @param {number} start - The first byte of the window. + * @param {number} size - The number of bytes of the window. + * @returns {boolean} True when the active loop request covers the window. + */ + isLoopFetching(start, size) { + return typeof this.downloader.isRangeBeingFetched === 'function' + && this.downloader.isRangeBeingFetched(start, size); + } + + /** + * Checks whether the downloader was intentionally aborted or torn down, so an on-demand read must not start a request for a timeline nobody owns anymore. + * @returns {boolean} True when the downloader is aborted or destroyed. + */ + isDownloaderAborted() { + return this.destroyed + || this.downloader.destroyed === true + || this.downloader.isAborted === true; + } + + /** + * Creates a watchdog for a read that waits for the download loop. It resolves with the reason the wait must end + * when the downloader is aborted, a newer seek took the timeline, the loop stopped fetching the window, or its + * received cursor has not advanced for the stall bound. It stays pending while the loop is making progress, and the + * caller disposes it as soon as the regular read resolves. + * @param {number} start - The first byte of the window. + * @param {number} size - The number of bytes of the window. + * @param {number} seekGeneration - The seek generation the read belongs to. + * @returns {{ promise: Promise, dispose: Function }} The watchdog promise and its cleanup. + */ + createLoopStallWatchdog(start, size, seekGeneration) { + let disposed = false; + let timer = null; + let lastMarker = null; + let lastProgressAt = Date.now(); + const promise = new Promise((resolve) => { + const check = () => { + if (disposed) + return; + if (this.isDownloaderAborted()) { + resolve('aborted'); + return; + } + if (this.seekGeneration !== seekGeneration) { + resolve('superseded'); + return; + } + if (!this.isLoopFetching(start, size)) { + resolve('not-fetching'); + return; + } + const progress = this.downloader.getLoopProgress(); + const now = Date.now(); + if (progress) { + const marker = `${progress.start}:${progress.cursor}`; + if (lastMarker === null || marker !== lastMarker) { + lastMarker = marker; + lastProgressAt = now; + } + } + if (now - lastProgressAt >= LOOP_STALL_FALLBACK_MS) { + resolve('stalled'); + return; + } + timer = setTimeout(check, LOOP_STALL_POLL_MS); + }; + check(); + }); + return { + promise, + dispose: () => { + disposed = true; + if (timer !== null) + clearTimeout(timer); + } + }; + } + + /** + * Fetches an uncovered window as a bounded one-shot range request and then reads it through the regular source. + * @param {number} start - The first byte of the window. + * @param {number} size - The number of bytes of the window. + * @param {number|null} total - The total size of the stream, or null when it is unknown. + * @param {number} seekGeneration - The seek generation the read belongs to. + * @returns {Promise} The bytes, possibly shorter at the end of the stream. + */ + async fetchOnDemandAsync(start, size, total, seekGeneration) { + if (this.isDownloaderAborted() || this.seekGeneration !== seekGeneration) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.'); + const window = this.getFetchWindow(start, size, total); + if (window === null) + return new Uint8Array(0); + // A probe far ahead of the loop frontier can duplicate bytes that the loop's open ended response will also + // deliver. That duplication is accepted: without the one-shot an OGG binary search can wait for the rest of + // the file, while the byte buffer merges the overlapping ranges. + const outcome = await this.downloader.downloadRangeAsync(window.start, window.end); + if (outcome.isAborted || outcome.isDestroyed) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.'); + if (outcome.isFailed) + throw outcome.error || new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The seek range request failed.'); + // Every one-shot fetch is validated, not only a satisfied response: a short body or a changed file must not fall + // through to a read that waits for a loop window below its target that will never be fetched. + if (!this.isWindowCovered(start, size) && total !== null) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The seek range did not cover the requested window.'); + return this.standard.readAsync(start, size); + } + + /** + * Expands a small demuxer read into an aligned block, so a seek that scans the stream does not pay one network round + * trip per small window. The block never extends past the end of the file and is bounded to one aligned block around the requested window. + * @param {number} start - The first byte of the requested window. + * @param {number} size - The number of bytes of the requested window. + * @param {number|null} total - The total size of the stream, or null when it is unknown. + * @returns {{ start: number, end: number }|null} The inclusive byte range to fetch, or null when it is empty. + */ + getFetchWindow(start, size, total) { + if (size <= 0) + return null; + const blockStart = Math.floor(start / SEEK_FETCH_BLOCK_BYTES) * SEEK_FETCH_BLOCK_BYTES; + let blockEndExclusive = Math.ceil((start + size) / SEEK_FETCH_BLOCK_BYTES) * SEEK_FETCH_BLOCK_BYTES; + if (!Number.isFinite(blockEndExclusive) || blockEndExclusive <= blockStart) + blockEndExclusive = blockStart + SEEK_FETCH_BLOCK_BYTES; + if (total !== null) + blockEndExclusive = Math.min(total, blockEndExclusive); + if (blockEndExclusive <= blockStart) + return null; + // Start after the contiguous buffered run that covers the block start, so a seek into a partially buffered + // block does not request a whole block of bytes the buffer already holds. + let fetchStart = blockStart; + if (typeof this.downloader.getContiguousEnd === 'function') + fetchStart = Math.max(blockStart, this.downloader.getContiguousEnd(blockStart)); + // A run that already reaches the end of the requested window would have made isWindowCovered true; the clamp is + // only a guard against asking for an empty or reversed range in an inconsistent buffer state. + if (fetchStart >= start + size) + fetchStart = start; + if (fetchStart >= blockEndExclusive) + fetchStart = blockStart; + return { start: fetchStart, end: blockEndExclusive - 1 }; + } + + /** + * Releases the source, so a late read of a released track returns an end of stream instead of touching the + * downloader. + */ + destroy() { + this.destroyed = true; + } + } + + LuminaAudioPlayer.SeekAwareByteSource = SeekAwareByteSource; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js new file mode 100644 index 00000000..e80cc0b9 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js @@ -0,0 +1,1938 @@ +/** + * Media pipeline engine of the audio player: the engine that actually plays a track. + * + * The controller of the player owns the state machine, the play descriptor, the queue and the bar, but it produces no + * audio. This module is the engine the player runs with: it composes the download engine, the container demuxers, the + * WebCodecs decode pipeline and the Web Audio scheduler into one pipeline, and implements the engine interface documented + * in audio-player-engine.js. It is registered under {@link LuminaAudioPlayer.PIPELINE_ENGINE_NAME} and installed on the + * application singleton when this module loads, so the bar drives a real pipeline instead of the silent engine. + * + * What it owns + * ------------ + * A track is represented by a pipeline item: the playback manifest of the track, the downloader that fetches its bytes, + * the demuxer that turns the bytes into encoded packets, the decoder that turns the packets into decoded audio, and the + * scheduler that hands the decoded audio to the renderer. The renderer itself is shared by every track, because it owns + * the AudioContext, the master gain and the ReplayGain gain, and because a gapless transition is produced by appending + * the next track to the schedule of the current one instead of resetting it. + * + * Seeking + * ------- + * A seek is a coordinated reset of every stage. The in flight download request is aborted so the demuxer read that is + * waiting on it is released, the decode loop is stopped, the decoder is reset, the scheduler is moved to the new media + * position, the demuxer is repositioned to the packet boundary that covers that position, and the decode loop is started + * again from there. The renderer adopts the requested position as the media origin of the first buffer it receives, so the + * first decoded frame after a seek is trimmed to the requested position when the demuxer reported a timeline that starts + * before it. A container that seeds the packet timeline with the requested time, such as MP3 or AAC, needs no trim; a + * container that reports the real frame time, such as FLAC, OGG or WAV, is trimmed. A demuxer seek is not sequential: OGG + * binary-searches the byte range, and the MP3 and AAC estimates can land below the target, so the demuxer may read a gap + * below the byte position the download loop fetches. The seek aware byte source serves such a window with a one-shot + * bounded range request, so the demuxer scan never waits for a download that would only reach the gap at the end of the + * file. Seeks into bytes that are already downloaded do not fetch them again: the downloader keeps every byte it already + * has, as the download engine documents. + * + * Underrun + * -------- + * A decoder that catches the download frontier leaves the schedule empty while the track is still playing. The engine + * watches the scheduled ahead duration of the renderer: when it reaches zero before the stream is complete, the engine + * suspends the renderer and reports buffering through the host, then resumes the renderer as soon as enough audio has been + * scheduled again. A draining schedule at the very end of the track is not an underrun, because the renderer reports the + * end on its own once the decode pipeline declared the stream complete. + * + * Gapless transitions + * ------------------- + * When the user enabled gapless playback and the player queue holds another item, the engine prefetches the next item as + * soon as the current one is loaded: it fetches the next manifest, opens its demuxer, and pre-decodes the first seconds of + * its audio into memory. The prefetch does not run an open-ended download next to the current one: it fetches only the + * windows its pre-decode needs, as bounded range requests, and leaves the sequential download of the next track stopped + * until the handoff. Once the current decoder has scheduled its last frame, the pre-decoded audio is appended to the + * renderer schedule, exactly after the audio of the current track, the download of the next track resumes from its first + * missing byte, and the rest of the track is decoded into the same schedule. The engine then switches the current item at the exact media position where the next + * audio starts, reports the new duration and asks the player to advance its queue, so the bar shows the new track while + * the audio never stops. Only the last track of a continuous chain declares the stream complete, which is what keeps the + * renderer from reporting an end between two gapless items. + * + * Failures + * -------- + * A download, demux or decode failure that happens mid-stream is reported once, through host.reportError, and stops the + * pipeline cleanly; it never escapes as an unhandled rejection and never leaves the renderer or the downloader running. + * A failure of a prefetch is dropped instead, because it must not interrupt the track that is playing. A track whose + * manifest is not a direct play needs the normalized delivery pipeline, which this engine does not implement yet, so it + * is reported as an engine load failure with the {@link LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED} + * reason. A play descriptor must name a track, not an album or an artist, because the manifest endpoint is addressed by the + * track and its album and artist; expanding an album or an artist context into its tracks is the queue engine's job. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The name the media pipeline engine is registered and selected under. + * @readonly + * @type {string} + */ + LuminaAudioPlayer.PIPELINE_ENGINE_NAME = 'pipeline'; + + /** + * The scheduled ahead duration, in seconds, below which a playing renderer is treated as having underrun. + * @readonly + * @type {number} + */ + const UNDERRUN_THRESHOLD_SECONDS = 0.05; + + /** + * The scheduled ahead duration, in seconds, that must be reached again before an underrun pause is resumed. + * @readonly + * @type {number} + */ + const UNDERRUN_RESUME_SECONDS = 0.25; + + /** + * The interval, in milliseconds, of the monitor that detects underruns and gapless track boundaries. + * @readonly + * @type {number} + */ + const MONITOR_INTERVAL_MS = 150; + + /** + * The margin, in seconds, that is kept between the end of the scheduled audio and the deadline for a gapless prefetch. + * The handoff must be appended before the current audio drains, so the wait never runs to the very end of the schedule. + * @readonly + * @type {number} + */ + const PREFETCH_HANDOFF_MARGIN_SECONDS = 0.15; + + /** + * The longest, in seconds, that the end of a decode waits for a gapless prefetch. A prefetch that is not ready by this + * deadline is abandoned and the track ends normally, so a stalled next track can never hold the current one open. + * @readonly + * @type {number} + */ + const PREFETCH_HANDOFF_MAX_WAIT_SECONDS = 5; + + /** + * Coerces a value to a finite number, or null when it is absent or not finite. + * @param {*} value - The value to coerce. + * @returns {number|null} The finite number, or null. + */ + function toFiniteNumber(value) { + return LuminaAudioPlayer.toFiniteNumber(value); + } + + /** + * The media pipeline engine. See the module documentation for its behavior. It fulfills the engine interface + * documented in audio-player-engine.js. + */ + class MediaPipelineEngine { + /** + * Creates an instance of MediaPipelineEngine. + * @param {Object} host - The engine host provided by the player controller. + * @param {Object} [options] - The engine options, for injection in a test. + * @param {LuminaAudioPlayer.TrackRenderer} [options.renderer] - The renderer to use instead of creating one. + * @param {LuminaAudioPlayer.PlayerCapabilities} [options.capabilities] - The capability detector to use. + * @param {Object} [options.configuration] - The endpoints configuration. It overrides the host configuration and exists as an injection seam for a test or a composition that provides its own transport. + * @param {Function} [options.fetchJsonAsync] - The JSON transport to use instead of the host transport, as an injection seam. It has the signature of the host method. + */ + constructor(host, options = {}) { + this.host = host; + this.options = options || {}; + this.events = host.events; + // The player's detector is reused when the host exposes it, so the engine never runs a second, independent capability detection or keeps a second memoization cache. + this.capabilities = this.options.capabilities + || (typeof host.getCapabilityDetector === 'function' ? host.getCapabilityDetector() : null) + || new LuminaAudioPlayer.PlayerCapabilities(); + this.renderer = this.options.renderer || new LuminaAudioPlayer.TrackRenderer({ + events: this.events, + replayGainMode: host.getPreferences().replayGainMode, + onTimeUpdate: (currentTime) => this.handleTimeUpdate(currentTime), + onEnded: () => this.handleEnded() + }); + // The current track of the pipeline. The renderer is shared by every track. + this.current = null; + // The next item whose audio was already appended to the renderer schedule but whose media position has not started yet. It becomes current at the exact position its audio begins. + this.nextItem = null; + this.monitorTimer = null; + this.isMonitoring = false; + this.isUserPaused = false; + this.isUnderrunPaused = false; + this.destroyed = false; + // The token of the load that owns the pipeline, so a second load that overtakes the first one stops it. + this.loadToken = null; + // True while a load is between the start of its teardown and the installation of its item. The old gapless timeline must not advance its queue or end under a load that is about to replace it. + this.isLoadingTrack = false; + this.unsubscribePreferences = null; + this.subscribeToPreferences(); + } + + //+======================================================================================+ + //| Engine interface | + //+======================================================================================+ + + /** + * Loads a track: fetches its playback manifest, prepares its download, demux and decode stages, and starts decoding + * ahead. Playback itself is started by playAsync, so the caller can keep the preparation and the audio separate. + * @param {Object} descriptor - The play descriptor of the track, per {@link LuminaAudioPlayer.createPlayDescriptor}. + * @param {Object} [options] - The load options. + * @param {boolean} [options.keepBuffering] - True to keep a loading state that was handed to the load by the player, used by an automatic continuation so the teardown of the previous track does not clear it. + * @returns {Promise} A promise that completes when the track is ready to play. + * @throws {LuminaAudioPlayer.PlayerError} When the manifest cannot be read, the track cannot be played directly, or a stage of the pipeline cannot be created. + */ + async loadAsync(descriptor, options = {}) { + if (this.destroyed) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The media pipeline engine was destroyed.'); + // The manifest request of the load that is being replaced is aborted, so a slow session never keeps a stale request alive behind the track that the newer load owns. + this.abortLoad(this.loadToken); + const token = { + abortController: typeof AbortController === 'function' ? new AbortController() : null + }; + this.loadToken = token; + this.isLoadingTrack = true; + try { + await this.teardownPlaybackAsync(null, token, options.keepBuffering === true); + if (!this.isLoadCurrent(token)) + throw this.createSupersededLoadError(); + this.isUserPaused = false; + this.isUnderrunPaused = false; + const signal = token.abortController ? token.abortController.signal : undefined; + const manifest = await this.fetchManifestAsync(descriptor, signal); + if (!this.isLoadCurrent(token)) + throw this.createSupersededLoadError(); + if (manifest.directPlay !== true) { + // The normalized delivery pipeline is a later stage; until it exists, the track is reported instead of being played as its stored bytes, which would produce noise or a decoder error. + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The track needs a normalized delivery the player does not support yet.', { reason: LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED }); + } + this.renderer.configure(manifest); + const item = await this.buildItemAsync(descriptor, manifest, false); + if (!this.isLoadCurrent(token) || this.destroyed) { + await this.disposeItemAsync(item); + throw this.createSupersededLoadError(); + } + item.base = 0; + this.current = item; + this.isLoadingTrack = false; + if (item.duration > 0) + this.renderer.setTimelineDuration(item.duration); + this.host.reportDuration(item.duration); + this.startDecodeLoop(item); + this.startGaplessPrefetch(item); + } catch (error) { + // A failure of a load that was overtaken by a newer one belongs to a playback the user already replaced, so it is reported as a superseded load, which the player ignores, + // instead of surfacing an error over the track that the newer load owns. The rejection also stops the stale playAsync continuation before it can set READY or PLAYING over + // the newer request.A stale load leaves the loading flag to the newer load. + if (!this.isLoadCurrent(token)) + throw this.createSupersededLoadError(); + this.isLoadingTrack = false; + throw error; + } + } + + /** + * Creates the typed error that tells the player a load was overtaken by a newer play request. + * @returns {LuminaAudioPlayer.PlayerError} The superseded load error. + */ + createSupersededLoadError() { + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The load was superseded by a newer play request.', { reason: LuminaAudioPlayer.PlayerErrorReason.LOAD_SUPERSEDED }); + } + + /** + * Aborts the manifest request of a load, so a teardown or a newer load never leaves a stale request running. + * @param {Object|null} token - The load token whose request is aborted. + */ + abortLoad(token) { + if (!token || !token.abortController) + return; + try { + token.abortController.abort(); + } catch (error) { + console.debug('Audio player: the manifest request of the replaced load could not be aborted.', error); + } + } + + /** + * Checks whether a load is still the one that owns the pipeline. + * @param {Object} token - The token of the load. + * @returns {boolean} True when this load is still current and the engine was not destroyed. + */ + isLoadCurrent(token) { + return !this.destroyed && this.loadToken === token; + } + + /** + * Releases the currently prepared track without destroying the engine, which keeps its renderer and audio context for a later play. + * The player calls it when a stop arrives while an automatic continuation is loading: the stopped player should not keep a track loaded that it started only to continue a queue. + * @returns {Promise} A promise that completes when the prepared track was released. + */ + async discardCurrentAsync() { + if (this.destroyed) + return; + await this.teardownPlaybackAsync(null, null, false); + } + + /** + * Starts, or resumes, audible playback. + * @returns {Promise} A promise that completes when the renderer is running. + */ + async playAsync() { + this.isUserPaused = false; + this.isUnderrunPaused = false; + this.host.reportBuffering(false); + if (this.current) + this.current.downloader.setPlaybackPaused(false); + // An attached next item is about to own the playhead, so its sequential download resumes with playback. The detached prefetch stays stopped until the handoff and is never started by a resume. + if (this.nextItem && this.nextItem.downloader) { + this.nextItem.downloader.setPlaybackPaused(false); + this.nextItem.downloader.startAsync(); + if (!this.nextItem.isDecodeComplete) + this.resumeDecodeAfterSettledLoopAsync(this.nextItem); + } + await this.renderer.playAsync(); + this.startMonitor(); + } + + /** + * Suspends audible playback, keeping the position. The downloader stops with the pause only when the stored 'keep downloading while paused' preference is off, which the download engine enforces itself. + * @returns {Promise} A promise that completes when playback was suspended. + */ + async pauseAsync() { + this.isUserPaused = true; + this.isUnderrunPaused = false; + this.stopMonitor(); + this.host.reportBuffering(false); + if (this.current) + this.current.downloader.setPlaybackPaused(true); + // The attached next item started its sequential download at the handoff preparation, so it follows the same + // pause policy as the current item. The detached prefetch is deliberately not touched: it has no sequential + // download, and forwarding the paused state to it would start one when keep-downloading-while-paused is enabled. + if (this.nextItem && this.nextItem.downloader) + this.nextItem.downloader.setPlaybackPaused(true); + await this.renderer.pauseAsync(); + } + + /** + * Moves the playhead to a position of the current track. A position that is already downloaded is not fetched + * again; a position that is not downloaded triggers the range fetch of the download engine. + * @param {number} seconds - The target position of the current track, in seconds. + * @param {boolean} [isRetry=false] - True when this is the one automatic retry after an interrupted seek. + * @returns {Promise} A promise that completes when the decode pipeline resumed at the target. + */ + async seekAsync(seconds, isRetry = false) { + const item = this.current; + if (!item || this.destroyed) + return; + // The order is deliberate: stop the old timeline, reset the decoder, reposition the demuxer, and only then let + // the decode loop schedule frames at the target. Every await is followed by an isSeekCurrent check, so a newer + // seek can abandon this one without touching the pipeline the newer seek already owns. + // Every seek owns a token, so a seek that is overtaken by a newer one returns at its next await instead of + // resetting the demuxer, the decoder or the shared renderer that the newer seek is already using. + const token = {}; + item.seekToken = token; + // A decode completion that is parked while it waits for a prefetch is released at once, so the seek never waits for a stalled next track that is kept across the seek. + this.cancelPrefetchWait(item); + // A seek is a resume when the audio was playing or when an underrun had paused it. A seek requested by a user + // pause stays paused, and a seek in the ended state is refused by the player. The state is captured before the seek resets it. + const wasPlaying = this.renderer.isPlaying(); + const shouldResume = !this.isUserPaused && (wasPlaying || this.isUnderrunPaused); + const requested = Math.max(0, toFiniteNumber(seconds) === null ? 0 : Number(seconds)); + const position = item.duration > 0 ? Math.min(requested, item.duration) : requested; + const nextEntry = this.getNextQueueEntry(); + // From here until the target is scheduled, the seek owns the timeline: the monitor does not pause it and a boundary crossing of the old timeline does not advance the queue under it. + item.isSeeking = true; + item.isDecodeComplete = false; + item.continueToEntry = null; + item.skipUntilSeconds = null; + item.hasScheduledAudio = false; + item.scheduler.setSuppressed(true); + // A seek into bytes that are already downloaded needs no loading state: the player's own buffered range check already knows the target is available, so only an uncovered target reports engine buffering. + if (!this.isSeekTargetBuffered(item, position)) + this.host.reportBuffering(true); + + // The old sources are stopped and the playhead is moved before any teardown is awaited, so the seek is heard immediately and the prefetch teardown cannot extend the latency of the reposition. + item.loopToken = null; + item.downloader.abort(); + let decoderReset = null; + let decoderResetError = null; + try { + decoderReset = item.decoder.resetAsync(); + } catch (error) { + decoderResetError = error; + } + try { + this.renderer.seekTo(item.base + position); + } catch (error) { + this.failItem(item, error); + return; + } + + // An attached next item had its audio in the schedule that the reset above stopped, so it is released and a fresh prefetch is started after the seek. + // A detached prefetch does not touch the renderer, and it still describes the same successor, so it is kept without being torn down and rebuilt. + if (this.nextItem) { + const detached = this.nextItem; + this.nextItem = null; + this.renderer.cancelTrackGainChange(); + await this.disposeItemAsync(detached); + if (!this.isSeekCurrent(item, token)) + return; + } + if (item.prefetch && !this.canKeepPrefetch(item.prefetch, nextEntry)) { + await this.cancelPrefetchAsync(item); + if (!this.isSeekCurrent(item, token)) + return; + } + if (decoderResetError) { + if (LuminaAudioPlayer.isDownloadAbort(decoderResetError)) + return this.recoverInterruptedSeekAsync(item, token, position, isRetry); + this.failItem(item, decoderResetError); + return; + } + if (decoderReset) { + try { + await decoderReset; + } catch (error) { + if (LuminaAudioPlayer.isDownloadAbort(error)) + return this.recoverInterruptedSeekAsync(item, token, position, isRetry); + this.failItem(item, error); + return; + } + } + if (!this.isSeekCurrent(item, token)) + return; + await this.waitForDecodeLoopAsync(item); + if (!this.isSeekCurrent(item, token)) + return; + // The old loop may have reached the end of the stream while it was being stopped, after the seek already cleared + // the flag. It is cleared again here, so the new loop is not mistaken for one whose decode already finished. + item.isDecodeComplete = false; + // The loading state belongs to the frames of the seek target only, so the first frame notification is re-armed + // once the old decode loop has definitively stopped, and the frames of that loop are no longer dropped. + item.scheduler.rearm(); + item.scheduler.setSeekTarget(position); + item.scheduler.setSuppressed(false); + if (item.source) + item.source.setSeeking(true); + item.downloader.seek(position); + // startAsync clears the aborted state that the abort above set. The sequential loop only runs when playback is + // active and the keep-downloading-while-paused preference allows it, but the seek itself does not depend on it: + // the seek aware source fetches every window the demuxer needs for the target with bounded range requests. + item.downloader.startAsync(); + const seekOutcome = await this.runDemuxerOperationAsync(item, token, () => item.demuxer.seekToTimeAsync(position)); + if (seekOutcome.skipped) + return; + if (seekOutcome.error) { + if (!this.isSeekCurrent(item, token)) + return; + if (LuminaAudioPlayer.isDownloadAbort(seekOutcome.error)) + return this.recoverInterruptedSeekAsync(item, token, position, isRetry); + this.failItem(item, seekOutcome.error); + return; + } + if (!this.isSeekCurrent(item, token)) + return; + if (seekOutcome.value === null) { + // A stream the demuxer cannot reposition, for example one whose length is not known, is re-read from its + // start and the packets that end before the target are dropped, which still lands on the requested audio. + const rebuildOutcome = await this.runDemuxerOperationAsync(item, token, () => this.rebuildDemuxerAsync(item)); + if (rebuildOutcome.skipped) + return; + if (rebuildOutcome.error) { + if (!this.isSeekCurrent(item, token)) + return; + if (LuminaAudioPlayer.isDownloadAbort(rebuildOutcome.error)) + return this.recoverInterruptedSeekAsync(item, token, position, isRetry); + this.failItem(item, rebuildOutcome.error); + return; + } + item.skipUntilSeconds = position; + } + if (!this.isSeekCurrent(item, token)) + return; + // A resume requested while the seek was running also counts, which is why the renderer is consulted again: a + // paused track that the user resumed during the seek is playing even though the seek started without playback. + const shouldResumeNow = !this.isUserPaused && (shouldResume || this.renderer.isPlaying()); + if (shouldResumeNow) { + // A seek requested while the audio was playing, or while an underrun had paused it, resumes the renderer, + // so the schedule of the new position actually advances the playhead and reports its end. A pause that the user requested while the seek was being resolved still wins. + this.isUnderrunPaused = false; + try { + await this.renderer.playAsync(); + } catch (error) { + this.failItem(item, error); + return; + } + if (!this.isSeekCurrent(item, token)) + return; + this.startMonitor(); + } + this.startDecodeLoop(item); + // The decode of the seek may already have reached the end of the track, in which case the completion has + // already made its end decision and a prefetch started now would never be appended. + if (!item.isDecodeComplete) + this.startGaplessPrefetch(item); + } + + /** + * Runs an operation that mutates the demuxer of an item under a gate, so two seeks of the same track can never + * reposition or rebuild the same demuxer at the same time. A seek that is overtaken while it waits for the gate returns without running its operation. + * @param {Object} item - The item whose demuxer is operated on. + * @param {Object} token - The token of the seek that requests the operation. + * @param {Function} operation - The operation to run, returning a value or a promise of one. + * @returns {Promise} The outcome, with a value, an error, or the skipped flag when a newer seek owns the item. + */ + async runDemuxerOperationAsync(item, token, operation) { + // A demuxer is not safe to reposition or rebuild concurrently. A previous seek may still be operating on it, so + // the new operation waits for that gate before it reads the current seek token and takes the gate itself. + if (item.demuxerOperation) { + try { + await item.demuxerOperation; + } catch (error) { + // The gate never rejects, so this is only a teardown of the operation that held it. + } + } + if (!this.isSeekCurrent(item, token)) + return { skipped: true }; + let release = null; + // The gate resolves rather than rejects. One seek's failure must not become the next seek's failure just + // because the next seek was waiting behind it. + const gate = new Promise((resolve) => { + release = resolve; + }); + item.demuxerOperation = gate; + try { + return { value: await operation() }; + } catch (error) { + return { error }; + } finally { + // Clear the handle only if it is still ours. A newer seek may already have replaced it, and clearing that + // newer gate would let a third operation run concurrently with it. + if (item.demuxerOperation === gate) + item.demuxerOperation = null; + // Release in every outcome, including a failed operation, or the next seek waits forever. + release(); + } + } + + /** + * Checks whether a seek is still the one that owns the current track, so a seek that was overtaken by a newer one stops before it touches shared state. + * @param {Object} item - The item the seek was requested on. + * @param {Object} token - The token of the seek. + * @returns {boolean} True when this seek is still the current one. + */ + isSeekCurrent(item, token) { + return !this.destroyed && this.current === item && item.seekToken === token + && !item.failed && !item.stopped && !item.disposed; + } + + /** + * Checks whether a position of an item is already covered by its downloaded time ranges, so a seek into it does not need to report engine buffering. + * @param {Object} item - The item whose downloaded ranges are checked. + * @param {number} seconds - The position to check. + * @returns {boolean} True when the position is already downloaded. + */ + isSeekTargetBuffered(item, seconds) { + if (!item || !item.downloader) + return false; + const value = Number(seconds); + if (!Number.isFinite(value)) + return false; + // The fraction check answers from the byte buffer without allocating a time range list, which matters because this runs on a seek rather than on a network chunk. + if (typeof item.downloader.coversTime === 'function') { + try { + return item.downloader.coversTime(value); + } catch (error) { + console.debug('Audio player: the buffered state of the seek target could not be read.', error); + return false; + } + } + if (typeof item.downloader.getTimeRanges !== 'function') + return false; + try { + return item.downloader.getTimeRanges().some((range) => + Number.isFinite(range.start) && Number.isFinite(range.end) + && value >= range.start && value <= range.end); + } catch (error) { + console.debug('Audio player: the downloaded ranges of the seek target could not be read.', error); + return false; + } + } + + /** + * Recovers an interrupted seek. The seek is retried once, which succeeds when the interruption was a transient + * request abort such as a pause that reached the downloader; if the retry is interrupted too, the seek is reported + * as a clean download failure instead of leaving the item in a silent, permanently buffering state. + * @param {Object} item - The item whose seek was interrupted. + * @param {Object} token - The token of the interrupted seek. + * @param {number} position - The seek target, in seconds. + * @param {boolean} isRetry - True when the interrupted seek was already the automatic retry. + * @returns {Promise} A promise that completes when the seek was retried or failed. + */ + async recoverInterruptedSeekAsync(item, token, position, isRetry) { + if (!this.isSeekCurrent(item, token)) + return; + this.clearSeekState(item); + if (!isRetry) { + await this.seekAsync(position, true); + return; + } + this.failItem(item, new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The seek was interrupted before its target could be read.')); + } + + /** + * Clears the state a seek owns, so a seek that cannot continue leaves a pipeline that can be resumed or retried instead of an item whose monitor, boundary and end checks all return early. + * @param {Object} item - The item whose seek state is cleared. + */ + clearSeekState(item) { + this.cancelPrefetchWait(item); + item.isSeeking = false; + if (item.scheduler) { + item.scheduler.setSuppressed(false); + item.scheduler.rearm(); + } + if (item.source) + item.source.setSeeking(false); + } + + /** + * Sets the output volume. The player folds the mute state into the volume it sends, so the renderer receives zero while the player is muted. + * @param {number} volume - The output volume, between 0 and 1. + * @returns {Promise} A promise that completes when the renderer applied the volume. + */ + async setVolumeAsync(volume) { + await this.renderer.setVolumeAsync(volume); + } + + /** + * Gets the time ranges of the current track that were already downloaded, so the player can tell whether a seek + * target is buffered and can show the streamed part of the progress bar. + * @returns {Array<{ start: number, end: number }>} The downloaded time ranges, in seconds. + */ + getBufferedTimeRanges() { + if (!this.current) + return []; + try { + return this.current.downloader.getTimeRanges(); + } catch (error) { + console.debug('Audio player: the downloaded ranges of the current track could not be read.', error); + return []; + } + } + + /** + * Checks whether the engine was destroyed. + * @returns {boolean} True when the engine was destroyed. + */ + isDestroyed() { + return this.destroyed; + } + + /** + * Reports the downloaded fraction of an item to the player once, used at a gapless handoff where the prefetched downloader has nothing left to emit. + * @param {Object} item - The item whose progress is reported. + */ + reportItemProgress(item) { + if (!item || !item.downloader) + return; + try { + const fraction = Number(item.downloader.getDownloadedFraction()); + if (Number.isFinite(fraction)) + this.host.reportProgress(Math.min(1, Math.max(0, fraction))); + } catch (error) { + console.debug('Audio player: the downloaded fraction of the next track could not be read.', error); + } + } + + /** + * Releases every resource of the engine, including the audio context of the renderer. + * @returns {Promise} A promise that completes when every resource was released. + */ + async destroyAsync() { + if (this.destroyed) + return; + this.destroyed = true; + this.isLoadingTrack = false; + this.stopMonitor(); + if (this.unsubscribePreferences) { + this.unsubscribePreferences(); + this.unsubscribePreferences = null; + } + await this.teardownPlaybackAsync(this.loadToken, null); + try { + await this.renderer.destroyAsync(); + } catch (error) { + console.error('Audio player: the media pipeline renderer could not be destroyed.', error); + } + } + + //+======================================================================================+ + //| Pipeline setup | + //+======================================================================================+ + + /** + * Builds the pipeline item of a track: its downloader, its demuxer, its decoder and its scheduler. + * @param {Object} descriptor - The play descriptor of the track. + * @param {Object} manifest - The playback manifest of the track. + * @param {boolean} isPrefetch - True to build the item for a gapless prefetch, which buffers instead of scheduling. + * @param {Function} [onItemCreated] - Called with the item as soon as its downloader exists, so a cancellation can + * stop the prefetch before the rest of its stages were built. + * @returns {Promise} The prepared item. + */ + async buildItemAsync(descriptor, manifest, isPrefetch, onItemCreated) { + // Build in dependency order: downloader and byte source first, then demuxer, scheduler and decoder. The catch + // below disposes the partial item if a later stage fails, so a failed load never leaves a half-built pipeline. + const preferences = this.host.getPreferences(); + const duration = this.resolveDuration(manifest, descriptor, null); + const item = { + descriptor, + // The identity of the queue entry this item represents, when it came from a gapless prefetch. + entryId: null, + manifest, + downloader: null, + source: null, + demuxer: null, + decoder: null, + scheduler: null, + base: 0, + duration: duration, + isDecodeComplete: false, + isPreloading: isPrefetch, + isGainScheduled: false, + isSeeking: false, + seekToken: null, + demuxerOperation: null, + // The next queue entry to start normally when a gapless handoff could not be prepared before the track ended, so a slow or failed prefetch never strands the queue. + continueToEntry: null, + skipUntilSeconds: null, + loopToken: null, + loopPromise: null, + prefetch: null, + prefetchWaitCancel: null, + disposed: false, + failed: false, + stopped: false, + hasScheduledAudio: false + }; + const streamPath = LuminaAudioPlayer.resolveStreamUrl(manifest, descriptor, this.getConfiguration()); + item.downloader = LuminaAudioPlayer.createTrackDownloader({ + url: streamPath, + durationInSeconds: duration, + shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, + events: this.events, + onProgress: (downloadedFraction) => { + if (item === this.current) + this.host.reportProgress(downloadedFraction); + }, + onError: (error) => this.handleDownloadFailure(item, error) + }); + if (typeof onItemCreated === 'function') + onItemCreated(item); + // The demuxer reads through the seek aware source, so a seek can fetch a window below the byte target of the download loop instead of waiting for bytes the loop never fetches. + item.source = new LuminaAudioPlayer.SeekAwareByteSource(item.downloader); + if (isPrefetch) { + // A prefetch fetches only the windows its pre-decode needs, through one-shot range requests, instead of + // running a second open-ended download from the moment the current track starts. Its sequential download is + // started at the handoff, from the first byte that is still missing. + item.source.setSeeking(true); + } else { + item.downloader.startAsync(); + } + try { + const demuxer = await LuminaAudioPlayer.createDemuxerForManifest(manifest, { + source: item.source, + capabilities: this.capabilities, + events: this.events, + onError: (error) => this.failItem(item, error) + }); + if (!demuxer) { + // A cancelled or aborted header probe and a transport failure are not properties of the track, so + // they are reported as themselves. Only a probe that actually concluded the bundled player cannot + // handle the bytes is reported as a track the server has to normalize. + if (item.downloader.isAborted || item.stopped || item.disposed) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The header probe of the track was aborted.'); + const downloadError = item.downloader.getError(); + if (downloadError) + throw downloadError; + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The track cannot be demuxed and decoded by the bundled player.', { reason: LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED }); + } + item.demuxer = demuxer; + const configuration = demuxer.getConfiguration(); + if (!configuration) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The demuxer of the track reported no decoder configuration.'); + const schedulerTarget = isPrefetch ? new LuminaAudioPlayer.BufferingScheduler() : this.renderer; + item.scheduler = new LuminaAudioPlayer.SeekableScheduler(schedulerTarget, () => { + item.hasScheduledAudio = true; + // The first frame of a seek is what ends its loading state, not the moment the seek was requested. The same point ends the on-demand range fetch mode of the source: + // from here the demuxer reads forward from the seek target, which the regular download loop fetches. A prefetch keeps its on-demand mode until + // the handoff, because its download loop does not run while it pre-decodes. + if (item.source && item === this.current) + item.source.setSeeking(false); + if (item.isSeeking) { + item.isSeeking = false; + if (item === this.current) + this.host.reportBuffering(false); + } + }); + item.decoder = LuminaAudioPlayer.createTrackDecoder({ + scheduler: item.scheduler, + config: configuration, + onError: (error) => this.failItem(item, error) + }); + item.duration = this.resolveDuration(manifest, descriptor, demuxer); + return item; + } catch (error) { + await this.disposeItemAsync(item); + throw error; + } + } + + /** + * Resolves the duration of a track: the exact duration the demuxer stated, then the manifest duration, then the duration of the play descriptor. + * @param {Object} manifest - The playback manifest of the track. + * @param {Object} descriptor - The play descriptor of the track. + * @param {LuminaAudioPlayer.Demuxer|null} demuxer - The demuxer of the track, or null before it exists. + * @returns {number} The duration in seconds, or zero when no source knows it. + */ + resolveDuration(manifest, descriptor, demuxer) { + const candidates = [ + demuxer ? demuxer.getDuration() : null, + manifest && manifest.durationInSeconds, + descriptor && descriptor.durationInSeconds + ]; + for (const candidate of candidates) { + const value = toFiniteNumber(candidate); + if (value !== null && value > 0) + return value; + } + return 0; + } + + /** + * Starts the decode loop of an item when one is not already running. + * @param {Object} item - The item to decode. + * @returns {Promise|null} The loop promise, or null when the loop was already running or the item stopped. + */ + startDecodeLoop(item) { + if (!item || item.stopped || item.disposed || this.destroyed) + return null; + if (item.loopPromise) + return item.loopPromise; + const token = {}; + item.loopToken = token; + const loop = this.runDecodeLoopAsync(item, token); + item.loopPromise = loop; + loop.finally(() => { + if (item.loopToken === token) + item.loopToken = null; + if (item.loopPromise === loop) + item.loopPromise = null; + }).catch(() => { + // The loop reports its own failures through the engine, so a rejection is only a teardown and is swallowed + // here, so the bookkeeping promise can never surface as an unhandled rejection. + }); + return loop; + } + + /** + * Resumes the decode of an attached next item after its previous loop settles. A pause may have cancelled the loop + * request, and the loop is still finishing when the user resumes; starting a second loop immediately would return the dying one and never decode the track. + * @param {Object} item - The next item whose decode is resumed. + */ + resumeDecodeAfterSettledLoopAsync(item) { + if (!item || item.isDecodeComplete || item.stopped || item.failed || this.destroyed) + return; + const pending = item.loopPromise; + if (!pending) { + this.startDecodeLoop(item); + return; + } + Promise.resolve(pending).catch(() => {}).finally(() => { + // The item may have advanced to the playhead while its old loop was settling, so it is resumed when it is either still the attached next item or the current one. + if ((this.nextItem === item || this.current === item) && !item.isDecodeComplete && !item.stopped + && !item.failed && !this.destroyed && !this.isUserPaused) + this.startDecodeLoop(item); + }).catch(() => { + console.debug('Audio player: the resumed next track decode could not be started.'); + }); + } + + /** + * Runs the decode loop of an item: it reads encoded packets from the demuxer, feeds them to the decoder, and stops + * when the stream ends, the preload of a gapless prefetch is satisfied, or the item is stopped. + * @param {Object} item - The item to decode. + * @param {Object} token - The token that identifies this loop, so a seek can retire it. + * @returns {Promise} A promise that completes when the loop stops. + */ + async runDecodeLoopAsync(item, token) { + try { + while (!this.destroyed && !item.stopped && !item.failed && item.loopToken === token) { + if (item.isPreloading && item.scheduler.getScheduledAheadSeconds() >= LuminaAudioPlayer.GAPLESS_PRELOAD_SECONDS) + return; + if (item.isDecodeComplete) + return; + const packet = await item.demuxer.readPacketAsync(); + if (item.loopToken !== token || item.stopped || item.failed || this.destroyed) + return; + if (packet === null) { + await item.decoder.flushAsync(); + // A seek can retire the loop while the final flush is pending, and the decoder reset makes that + // flush resolve normally instead of rejecting. The completion must not be recorded for a loop that + // no longer owns the item, or the fresh seek loop would exit immediately at the completed flag. + if (item.loopToken !== token || item.stopped || item.failed || this.destroyed) + return; + item.isDecodeComplete = true; + await this.handleDecodeCompleteAsync(item, token); + return; + } + if (this.shouldSkipPacket(item, packet)) + continue; + const accepted = await item.decoder.decodeAsync(packet); + if (!accepted) { + if (item.decoder.isStopped() && item.decoder.getError()) + this.failItem(item, item.decoder.getError()); + return; + } + } + } catch (error) { + if (this.destroyed || item.stopped || LuminaAudioPlayer.isDownloadAbort(error)) + return; + this.failItem(item, error); + } + } + + /** + * Checks whether a packet of a demuxer that was restarted from the beginning ends before the seek target, in which + * case it is dropped. The packet that covers the target arms the trim of the scheduler. + * @param {Object} item - The item the packet belongs to. + * @param {Object} packet - The encoded packet. + * @returns {boolean} True when the packet must be skipped. + */ + shouldSkipPacket(item, packet) { + if (item.skipUntilSeconds === null) + return false; + const target = item.skipUntilSeconds; + const start = toFiniteNumber(packet.timestamp) === null ? 0 : Number(packet.timestamp) / 1000000; + const duration = toFiniteNumber(packet.duration) === null ? 0 : Number(packet.duration) / 1000000; + if (start + duration <= target + LuminaAudioPlayer.SEEK_TRIM_EPSILON_SECONDS) + return true; + item.skipUntilSeconds = null; + item.scheduler.setSeekTarget(target); + return false; + } + + /** + * Handles the end of the decode of an item. A prefetched item only records it; the current item either hands over + * to the prefetched next track or declares the stream complete, which is what lets the renderer report the end. + * @param {Object} item - The item whose decode ended. + * @param {Object} [loopToken] - The token of the decode loop that reached the end, when the completion was observed + * by that loop. It is omitted when the completion is re-evaluated for an item that already became current. + * @returns {Promise} A promise that completes when the completion was handled or abandoned as stale. + */ + async handleDecodeCompleteAsync(item, loopToken) { + // The state of the item at the moment the completion was observed, so a seek that overtakes the possibly long wait for a gapless prefetch is detected before it is acted on. + const seekToken = item.seekToken; + if (item !== this.current) { + // A prefetched item records its own completion; the handoff that consumes it decides when that matters. + item.isDecodeComplete = true; + item.isPreloading = false; + return; + } + if (!this.isCompletionCurrent(item, loopToken, seekToken)) + return; + item.isDecodeComplete = true; + item.isPreloading = false; + if (item.isSeeking) { + // A seek whose decode produced no frame, for example one to the very end of the track, has nothing left to + // schedule, so its loading state is cleared and the track is reported as ended instead of spinning. + item.isSeeking = false; + if (item.source) + item.source.setSeeking(false); + this.host.reportBuffering(false); + if (!item.hasScheduledAudio) { + item.downloader.abort(); + this.stopMonitor(); + this.renderer.markStreamComplete(); + this.renderer.pauseAsync().catch((error) => { + console.debug('Audio player: the renderer could not be paused after an empty seek.', error); + }); + // The track ended and a finished pipeline is not retained: its decoder, demuxer, downloader and byte + // buffer are released. The disposal is scheduled after this callback because the decode loop that is calling it is the loop the disposal waits for. + this.current = null; + this.host.reportEnded(); + Promise.resolve().then(() => this.disposeItemAsync(item)).catch((error) => { + console.debug('Audio player: the track that ended at an empty seek could not be released.', error); + }); + return; + } + } + if (this.nextItem) + return; + const preferences = this.host.getPreferences(); + if (preferences.isGaplessPlaybackEnabled) { + // The fallback and the completion are recorded before the wait, so a stalled prefetch can never hold the + // track open: the renderer ends at the end of the scheduled audio and the player starts the fallback track + // non-gaplessly. The wait only tries to improve that into a seamless handoff. + if (!this.nextItem) + item.continueToEntry = this.getNextQueueEntry(); + this.renderer.markStreamComplete(); + const token = item.prefetch; + if (token && !token.cancelled && !token.consumed) { + const prefetched = await this.waitForPrefetchAsync(item, token, loopToken, seekToken); + if (!this.isCompletionCurrent(item, loopToken, seekToken)) + return; + if (prefetched && this.isPrefetchUsable(prefetched) && !this.nextItem) + this.attachNextItem(item, prefetched); + } + return; + } + if (!this.isCompletionCurrent(item, loopToken, seekToken)) + return; + this.renderer.markStreamComplete(); + } + + /** + * Checks whether a decode completion still belongs to the current item and to the decode loop and seek that + * observed it, so a completion that was overtaken while it waited is abandoned instead of acted on. + * @param {Object} item - The item whose completion is checked. + * @param {Object} [loopToken] - The token of the decode loop that observed the completion, when there is one. + * @param {Object|null} seekToken - The seek token the item carried when the completion was observed. + * @returns {boolean} True when the completion is still current. + */ + isCompletionCurrent(item, loopToken, seekToken) { + return !this.destroyed && this.current === item && !item.stopped && !item.failed && !item.disposed + && item.seekToken === seekToken + && (loopToken === undefined || item.loopToken === loopToken); + } + + /** + * Waits for a gapless prefetch, bounded by the remaining scheduled audio and by a short maximum. A seek cancels the + * wait immediately through {@link LuminaAudioPlayer.MediaPipelineEngine#cancelPrefetchWait}, so a seek never waits for a stalled next track that is kept across it. + * @param {Object} item - The current item whose decode completion is waiting. + * @param {Object} token - The prefetch token of the current item. + * @param {Object} [loopToken] - The token of the decode loop that observed the completion. + * @param {Object|null} seekToken - The seek token the item carried when the completion was observed. + * @returns {Promise} The ready prefetched item, or null when it is not ready in time. + */ + waitForPrefetchAsync(item, token, loopToken, seekToken) { + if (!token || token.cancelled || token.consumed) + return Promise.resolve(null); + if (token.ready) + return Promise.resolve(token.item); + if (!token.promise) + return Promise.resolve(null); + const deadline = this.getPrefetchWaitSeconds(); + if (deadline <= 0) + return Promise.resolve(null); + return new Promise((resolve) => { + let hasSettled = false; + let timer = null; + const finish = (value) => { + if (hasSettled) + return; + hasSettled = true; + clearTimeout(timer); + if (item.prefetchWaitCancel === cancel) + item.prefetchWaitCancel = null; + resolve(value && token.ready && !token.cancelled && !token.consumed ? value : null); + }; + const cancel = () => finish(null); + item.prefetchWaitCancel = cancel; + timer = setTimeout(() => finish(null), deadline * 1000); + token.promise.then((prefetched) => { + // A completion that a seek already overtook is not handed over, even if the prefetch finished in time. + if (item.seekToken !== seekToken || (loopToken !== undefined && item.loopToken !== loopToken)) + finish(null); + else + finish(prefetched || null); + }, () => finish(null)); + }); + } + + /** + * Gets how long the end of a decode may wait for a gapless prefetch: the remaining scheduled audio minus the handoff margin, capped by the maximum wait. + * @returns {number} The wait, in seconds, never below zero. + */ + getPrefetchWaitSeconds() { + const ahead = Number(this.renderer.getScheduledAheadSeconds()); + const remaining = Number.isFinite(ahead) && ahead > 0 ? ahead : 0; + return Math.max(0, Math.min(PREFETCH_HANDOFF_MAX_WAIT_SECONDS, remaining - PREFETCH_HANDOFF_MARGIN_SECONDS)); + } + + /** + * Releases a decode completion that is waiting for a gapless prefetch, used when a seek takes over the timeline. + * @param {Object} item - The item whose prefetch wait is cancelled. + */ + cancelPrefetchWait(item) { + if (!item || !item.prefetchWaitCancel) + return; + const cancel = item.prefetchWaitCancel; + item.prefetchWaitCancel = null; + cancel(); + } + + /** + * Checks whether a prefetched item can be appended to the current schedule: it is ready, still alive, and holds + * decoded audio that can be handed to the renderer. + * @param {Object} prefetched - The prefetched item. + * @returns {boolean} True when the item can be handed over. + */ + isPrefetchUsable(prefetched) { + return Boolean(prefetched) && !prefetched.failed && !prefetched.stopped && !prefetched.disposed + && prefetched.scheduler + && prefetched.scheduler.getScheduledAheadSeconds() > 0; + } + + //+======================================================================================+ + //| Gapless transitions | + //+======================================================================================+ + + /** + * Starts prefetching the next item of the player queue for a gapless transition, when the stored preference is on. + * The prefetch is dropped silently when it fails, because it must never interrupt the track that is playing. + * @param {Object} item - The item whose next queue entry is prefetched. + */ + startGaplessPrefetch(item) { + // Only the item that owns the playhead can have a successor to prefetch. The item that is merely attached as + // the next handoff starts its own prefetch when it becomes current, so the queue is never traversed by hand. + if (this.destroyed || !item || item !== this.current || item.stopped || item.disposed || item.prefetch) + return; + // A completed decode is not rejected here. A short track, or a short remainder after a seek, can finish its decode before its prefetch is started, and the handoff re-evaluation still consumes a prefetch for it. + // The paths where completion really makes a handoff impossible, the seek completion and a preference change, check completion before calling this method. + const preferences = this.host.getPreferences(); + if (!preferences.isGaplessPlaybackEnabled) + return; + const nextEntry = this.getNextQueueEntry(); + if (!nextEntry) + return; + const nextDescriptor = nextEntry.descriptor; + const token = { + cancelled: false, + consumed: false, + ready: false, + entryId: nextEntry.entryId, + descriptor: nextDescriptor, + item: null, + promise: null, + abortController: typeof AbortController === 'function' ? new AbortController() : null + }; + item.prefetch = token; + const phase = (async () => { + try { + const signal = token.abortController ? token.abortController.signal : undefined; + const manifest = await this.fetchManifestAsync(nextDescriptor, signal); + if (token.cancelled || this.destroyed || item.stopped || manifest.directPlay !== true) + return null; + const prefetched = await this.buildItemAsync(nextDescriptor, manifest, true, (created) => { + token.item = created; + }); + prefetched.entryId = token.entryId; + token.item = prefetched; + // The prefetch downloader is deliberately not started here, even when the player is paused with keep + // downloading enabled: its pre-decode was fetched on demand, and its sequential download starts only at the handoff. + if (token.cancelled || this.destroyed || item.stopped) { + await this.disposeItemAsync(prefetched); + return null; + } + await this.startDecodeLoop(prefetched); + if (token.cancelled || prefetched.failed || prefetched.stopped) + return null; + // The pre-decode window is buffered, so no more bytes are fetched until the handoff. The downloader + // never ran for a prefetch, and the abort clears any range request that was still completing, while + // keeping the bytes that were fetched. The sequential download starts at the handoff. + if (prefetched.source) + prefetched.source.setSeeking(false); + try { + prefetched.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the prefetch download could not be stopped after pre-decoding.', abortError); + } + // Ready means the preload loop has stopped and the buffered audio can be appended to the shared schedule without two decode loops feeding the same item. + token.ready = true; + return prefetched; + } catch (error) { + if (!token.cancelled && !this.destroyed && !LuminaAudioPlayer.isDownloadAbort(error)) + console.debug('Audio player: the gapless prefetch of the next track failed.', error); + return null; + } + })(); + token.promise = phase.then((prefetched) => { + // A prefetch that settled without a usable item is forgotten, so a later preference change or a later decode completion can try again after a transient manifest or network failure. + if (!prefetched && item.prefetch === token) + item.prefetch = null; + return prefetched; + }); + } + + /** + * Appends the pre-decoded audio of the next item to the renderer schedule, exactly after the audio of the current + * track, and lets its decode continue into the same schedule. The current item stays current until the media position of the next item begins. + * @param {Object} current - The item that is finishing. + * @param {Object} next - The prefetched item that hands over. + */ + attachNextItem(current, next) { + const token = current.prefetch; + if (token) { + token.consumed = true; + next.entryId = token.entryId; + } + current.prefetch = null; + current.continueToEntry = null; + next.isPreloading = false; + // The prefetch fetched only the windows its pre-decode needed, so the sequential download of the next track starts now: the decode loop that continues after the buffered frames needs those bytes. + if (next.source) + next.source.setSeeking(false); + // The sequential download of the next track starts only when the player is not paused. While paused it stays stopped, keeping its bytes, and is started by the next resume or by the handoff. + if (!this.isUserPaused) { + next.downloader.setPlaybackPaused(false); + next.downloader.startAsync(); + } + // The end of the scheduled audio of the current track is the exact media position the next track starts at. + next.base = this.renderer.getScheduledMediaDuration(); + this.nextItem = next; + // The current decode completion marked the stream complete before it waited for the prefetch. The handoff + // appends more audio after the current track, so completion must be cleared: a drained schedule from here on + // is an underrun that the monitor pauses and resumes, not the end of the next track. + this.renderer.clearStreamComplete(); + if (next.duration > 0) + this.renderer.setTimelineDuration(next.base + next.duration); + // The ReplayGain change is scheduled at the context time the next track starts, so it is not applied a reporter tick late after the boundary was detected. + next.isGainScheduled = false; + try { + next.isGainScheduled = this.renderer.scheduleManifestGain(next.manifest, this.getContextTimeForMediaPosition(next.base)); + } catch (error) { + console.debug('Audio player: the ReplayGain change of the next track could not be scheduled.', error); + } + next.scheduler.attach(this.renderer); + this.startDecodeLoop(next); + } + + /** + * Switches the current item to the next one at the media position its audio already started at. It reports the new + * descriptor to the player queue and applies the ReplayGain values of the new track. + */ + advanceToNextItem() { + if (this.isLoadingTrack) + return; + const previous = this.current; + const next = this.nextItem; + if (!next) + return; + // The audio of the next track is already scheduled, so the handoff is bookkeeping: move the engine cursor, move + // the player cursor by identity, release the previous item and adopt the renderer manifest. The audio cannot be + // rolled back, so a failure is handled on the new item rather than by undoing the transition. + this.nextItem = null; + if (next.failed || next.disposed || next.stopped) { + // A next track that failed after it was attached can no longer be switched to, so the chain ends with the + // audio that is already in the schedule instead of advancing the player to a dead item. + this.disposeItemAsync(next).catch((error) => { + console.debug('Audio player: the failed handoff track could not be released.', error); + }); + this.renderer.cancelTrackGainChange(); + this.renderer.markStreamComplete(); + return; + } + this.current = next; + // A loading state that belonged to the previous track does not follow the gapless handoff, unless the next track is itself waiting for a seek target to arrive. + if (!next.isSeeking) + this.host.reportBuffering(false); + // The audio of the previous track is already in the schedule of the renderer, so its pipeline can be released + // without affecting the transition, and it is released before anything that can fail below can leak it. + if (previous) + this.disposeItemAsync(previous).catch((error) => { + console.debug('Audio player: the finished track of the pipeline could not be released.', error); + }); + // The handoff is committed against the queue entry identity that was actually scheduled. If the player queue + // changed under it, the bar is moved to that entry instead of describing a different track. + const scheduledEntryId = next.entryId; + // The gapless handoff and a normal continuation use the same identity based commit, so a failed advance can never succeed through a second adoption call. + const advanced = this.host.advanceQueueTo + ? this.host.advanceQueueTo(scheduledEntryId) + : null; + if (advanced) + next.descriptor = advanced; + // If the item was attached while the player was paused, a resume that happened before the handoff still left its downloader aborted. It is started now that the item owns the playhead. + if (!this.isUserPaused && next.downloader) + next.downloader.startAsync(); + try { + this.renderer.adoptManifest(next.manifest, next.isGainScheduled === true); + } catch (error) { + this.failItem(next, error); + return; + } + next.isGainScheduled = false; + if (next.duration > 0) + this.renderer.setTimelineDuration(next.base + next.duration); + this.host.reportDuration(next.duration); + // The prefetched downloader fetched its pre-decode window before the handoff, and it may already have all of + // it, so it will emit no further progress after the player reset the streamed indicator for the new track. The + // fraction is reported once here so the three-state bar starts at the real streamed state of the new item. + this.reportItemProgress(next); + const absolute = this.renderer.getCurrentTime(); + const local = Math.max(0, absolute - next.base); + this.host.reportTime(next.duration > 0 ? Math.min(local, next.duration) : local, next.duration); + // The item now owns the engine's playhead, but its successor can only be prefetched when the player queue + // actually moved to it. If the commit was refused, the player cursor still points at the previous entry, so + // resolving its next entry would prefetch the track that just started as its own successor. + if (advanced) + this.startGaplessPrefetch(next); + if (next.isDecodeComplete) { + this.handleDecodeCompleteAsync(next).catch((error) => { + console.debug('Audio player: the completion of the handed off track could not be handled.', error); + }); + } else { + this.startDecodeLoop(next); + } + } + + /** + * Gets the queue entry that follows the current item, from the player's own queue cursor. The entry carries its + * identity and its descriptor, so two occurrences of the same track are never confused. + * @returns {{ entryId: string, descriptor: Object }|null} The following entry, or null at the end of the queue. + */ + getNextQueueEntry() { + if (typeof this.host.getNextDescriptor !== 'function') + return null; + try { + return this.host.getNextDescriptor() || null; + } catch (error) { + console.debug('Audio player: the next queue entry could not be read.', error); + return null; + } + } + + /** + * Checks whether a prefetch can survive a seek. A detached prefetch never touched the renderer schedule, so a seek + * can keep it as long as it still describes the same queue entry identity. + * @param {Object} token - The prefetch token of the current item. + * @param {{ entryId: string, descriptor: Object }|null} nextEntry - The successor of the current track after the seek. + * @returns {boolean} True when the prefetch is still valid and must not be cancelled. + */ + canKeepPrefetch(token, nextEntry) { + if (!token || token.cancelled || token.consumed || !token.entryId || !nextEntry) + return false; + const prefetched = token.item; + if (prefetched && (prefetched.failed || prefetched.stopped || prefetched.disposed)) + return false; + return token.entryId === nextEntry.entryId; + } + + /** + * Converts an absolute media position of the shared renderer into the context time at which it will play, so a + * change can be scheduled to happen exactly at a track boundary rather than when the boundary is noticed. + * @param {number} mediaTime - The absolute media position, in seconds. + * @returns {number} The context time, in seconds. Zero when the renderer has no context yet. + */ + getContextTimeForMediaPosition(mediaTime) { + // The renderer owns the anchor, the rate and the schedule lead, so the conversion is delegated to it instead of + // being derived a second time with values that can drift from the audio clock. + return typeof this.renderer.getContextTimeForMediaPosition === 'function' + ? this.renderer.getContextTimeForMediaPosition(mediaTime) + : 0; + } + + /** + * Checks whether the media position that the next item starts at was reached, and switches to it when it was. + * @param {number} absoluteTime - The absolute media position of the shared renderer, in seconds. + */ + checkForTrackBoundary(absoluteTime) { + // A seek owns the timeline until it has repositioned every stage, so a boundary that the old timeline crosses + // during the seek must not invalidate it. A load in progress owns the queue and the player state, so the old timeline must not advance under it either. + if (!this.nextItem || this.isLoadingTrack || (this.current && this.current.isSeeking)) + return; + const value = toFiniteNumber(absoluteTime); + if (value === null || value < this.nextItem.base) + return; + this.advanceToNextItem(); + } + + /** + * Cancels and releases the prefetch of an item, including a prefetched item that was never attached. + * @param {Object} item - The item whose prefetch is cancelled. + * @returns {Promise} A promise that completes when the prefetch was released. + */ + async cancelPrefetchAsync(item) { + const token = item ? item.prefetch : null; + if (!token) + return; + item.prefetch = null; + token.cancelled = true; + if (token.abortController) { + try { + token.abortController.abort(); + } catch (abortError) { + console.debug('Audio player: the manifest request of the cancelled prefetch could not be aborted.', abortError); + } + } + let prefetched = token.item; + // A prefetch that is already built is stopped before its promise is awaited, so a decode that is waiting for + // bytes of a track nobody wants anymore is released instead of holding the teardown open. + if (prefetched && !prefetched.disposed && !token.consumed) { + prefetched.stopped = true; + if (prefetched.scheduler) + prefetched.scheduler.stop(); + try { + prefetched.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the prefetched download could not be aborted.', abortError); + } + // Destroying the decoder releases a decode that is waiting for room, which a prefetch whose buffer is full + // would otherwise wait for forever, because its schedule is never consumed while it is detached. + if (prefetched.decoder) { + try { + await prefetched.decoder.destroyAsync(); + } catch (decodeError) { + console.debug('Audio player: the prefetched decoder could not be destroyed.', decodeError); + } + } + } + try { + prefetched = (await token.promise) || prefetched; + } catch (error) { + // The prefetch reports its own failures and resolves null, so a rejection is only a teardown. + } + if (token.consumed || !prefetched) + return; + await this.disposeItemAsync(prefetched); + } + + //+======================================================================================+ + //| Playback monitoring | + //+======================================================================================+ + + /** + * Starts the monitor that detects underruns and gapless track boundaries. It is idempotent. + */ + startMonitor() { + if (this.monitorTimer !== null || this.destroyed) + return; + this.monitorTimer = setInterval(() => { + this.monitorPlayback(); + }, MONITOR_INTERVAL_MS); + } + + /** + * Stops the playback monitor. + */ + stopMonitor() { + if (this.monitorTimer === null) + return; + clearInterval(this.monitorTimer); + this.monitorTimer = null; + } + + /** + * Inspects the schedule and the shared timeline: it switches to the next track at its media position and it pauses + * and resumes the renderer around an underrun. It never runs while the user paused the player. + * @returns {Promise} A promise that completes when the monitor pass is done. + */ + async monitorPlayback() { + if (this.isMonitoring || this.destroyed || this.isUserPaused || !this.current) + return; + // A seek owns the timeline until its first frame is scheduled, and a load in progress owns the player state, so + // the monitor neither pauses the renderer nor advances a boundary of the timeline that is being replaced. + if (this.current.isSeeking || this.isLoadingTrack) + return; + this.isMonitoring = true; + try { + const absolute = this.renderer.getCurrentTime(); + this.checkForTrackBoundary(absolute); + if (this.isUnderrunPaused) { + if (this.renderer.getScheduledAheadSeconds() >= UNDERRUN_RESUME_SECONDS) { + this.isUnderrunPaused = false; + this.host.reportBuffering(false); + await this.renderer.playAsync(); + } + return; + } + if (!this.renderer.isPlaying()) + return; + if (this.renderer.getScheduledAheadSeconds() > UNDERRUN_THRESHOLD_SECONDS) + return; + // A drained schedule that is also declared complete is the end of the track, not an underrun. + if (this.renderer.isStreamComplete() && this.current.isDecodeComplete) + return; + // Before the first frame of a freshly loaded or seeked track there is nothing to play yet. Pausing that + // state would only flap the renderer between paused and playing, so the pause waits for audio to have been scheduled at least once. + if (!this.current.hasScheduledAudio) + return; + // A seek that started while this pass was running owns the timeline, so the pass does not pause it. + if (this.current.isSeeking) + return; + this.isUnderrunPaused = true; + this.host.reportBuffering(true); + await this.renderer.pauseAsync(); + } catch (error) { + if (!this.destroyed) + this.failItem(this.current, error); + } finally { + this.isMonitoring = false; + } + } + + /** + * Handles a playhead report from the renderer. The report is on the shared timeline, so it is translated to the + * position of the current track and the boundary of the next track is checked first. + * @param {number} absoluteTime - The absolute media position of the shared renderer, in seconds. + */ + handleTimeUpdate(absoluteTime) { + if (this.destroyed) + return; + this.checkForTrackBoundary(absoluteTime); + const item = this.current; + if (!item) + return; + const local = Math.max(0, Number(absoluteTime) - item.base); + const bounded = item.duration > 0 ? Math.min(local, item.duration) : local; + this.host.reportTime(bounded, item.duration); + } + + /** + * Handles the end of the scheduled audio reported by the renderer. + */ + handleEnded() { + if (this.destroyed) + return; + // An end of the timeline that a new load is replacing is not reported: the load owns the player state now. + if (this.isLoadingTrack) + return; + // An end that the old timeline reports while a seek is repositioning the pipeline belongs to the timeline the seek is replacing, not to the target it is moving to. + if (this.current && this.current.isSeeking) + return; + this.stopMonitor(); + this.isUnderrunPaused = false; + const current = this.current; + // The next entry is re-resolved at the end, not taken from the value cached at decode completion: a queue that + // changed in between may no longer offer a successor, in which case the track simply ends. + const nextEntry = this.getNextQueueEntry(); + if (current && current.continueToEntry && nextEntry && !this.isUserPaused + && typeof this.host.requestNextTrackAsync === 'function') { + // The engine reports the structural fact and lets the player's own play path start the next entry, so the + // controller keeps ownership of the state, the pause and stop intent, and the capability gate. The loading + // state spans the end gap: the continuation load keeps it across the teardown of the finished track. + current.continueToEntry = null; + this.host.reportBuffering(true); + Promise.resolve(this.host.requestNextTrackAsync('gapless-prefetch-failed')) + .then((hasTakenOwnership) => { + if (!hasTakenOwnership) + this.finishEndedTrack(current); + }) + .catch((error) => { + console.debug('Audio player: the player could not start the next track after a gapless fallback.', error); + this.finishEndedTrack(current); + }); + return; + } + this.host.reportBuffering(false); + if (current) + this.finishEndedTrack(current); + else + this.host.reportEnded(); + } + + /** + * Releases a finished item and reports the end to the player, unless a newer load already took ownership of the pipeline in the meantime. + * @param {Object} item - The item that ended. + */ + finishEndedTrack(item) { + if (this.current !== item) + return; + this.current = null; + this.host.reportBuffering(false); + this.host.reportEnded(); + this.disposeItemAsync(item).catch((error) => { + console.debug('Audio player: the ended track of the pipeline could not be released.', error); + }); + } + + /** + * Follows the stored playback preferences. Gapless playback is honored from the moment it is turned on, and a + * prefetch that becomes unwanted is released before its audio is appended to the schedule. + * @param {Object} preferences - The preferences payload of the player. + */ + handlePreferencesChanged(preferences) { + if (this.destroyed || !preferences || typeof preferences.isGaplessPlaybackEnabled !== 'boolean') + return; + const item = this.current; + if (!item) + return; + if (preferences.isGaplessPlaybackEnabled === false) { + this.cancelPrefetchAsync(item).catch((error) => { + console.debug('Audio player: the disabled gapless prefetch could not be released.', error); + }); + // A next item that was already appended to the schedule is cancelled too: the appended audio is removed, the + // current track is allowed to end at the boundary, and the player then starts the next entry non-gaplessly. + // The boundary may already be behind the playhead, in which case the next track is already audible and + // truncating it would rewind the timeline and replay audio that has played. That transition is left alone. + const next = this.nextItem; + if (next && typeof this.renderer.truncateScheduleAt === 'function' + && next.base > this.renderer.getCurrentTime()) { + this.nextItem = null; + this.renderer.cancelTrackGainChange(); + this.renderer.truncateScheduleAt(next.base); + item.continueToEntry = this.getNextQueueEntry(); + this.renderer.markStreamComplete(); + this.disposeItemAsync(next).catch((error) => { + console.debug('Audio player: the disabled gapless handoff could not be released.', error); + }); + } + return; + } + // A decode that has already completed made its end decision before gapless was enabled, so a prefetch started now could never be appended to the schedule. + if (!this.nextItem && !item.isDecodeComplete) + this.startGaplessPrefetch(item); + } + + /** + * Subscribes the engine to the stored preference changes of the player. + */ + subscribeToPreferences() { + if (!this.events || !LuminaAudioPlayer.PlayerEvent || typeof this.events.on !== 'function') + return; + this.unsubscribePreferences = this.events.on(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, (preferences) => { + this.handlePreferencesChanged(preferences); + }); + } + + //+======================================================================================+ + //| Failures and teardown | + //+======================================================================================+ + + /** + * Handles a download failure of an item. A prefetch failure is dropped; the failure of the current track is + * reported to the player, which moves to its error state without the pipeline leaving anything running. + * @param {Object} item - The item that failed. + * @param {*} error - The failure. + */ + handleDownloadFailure(item, error) { + if (LuminaAudioPlayer.isDownloadAbort(error)) + return; + this.failItem(item, error); + } + + /** + * Records a failure of an item once and reports it to the player when the item is the current one. + * @param {Object} item - The item that failed. + * @param {*} error - The failure. + */ + failItem(item, error) { + if (!item || item.failed || item.stopped || item.disposed || this.destroyed) + return; + if (LuminaAudioPlayer.isDownloadAbort(error)) + return; + item.failed = true; + item.stopped = true; + try { + item.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the failed download could not be aborted.', abortError); + } + if (item === this.nextItem) { + // The next track was already appended to the schedule but has not started yet, so the chain ends with the + // audio that is already scheduled and the player is not advanced to an item that can no longer play. + this.nextItem = null; + this.renderer.cancelTrackGainChange(); + this.renderer.markStreamComplete(); + this.host.reportBuffering(false); + this.disposeItemAsync(item).catch((disposeError) => { + console.debug('Audio player: the failed handoff track could not be released.', disposeError); + }); + return; + } + if (item !== this.current) { + console.debug('Audio player: a prefetched track of the pipeline failed.', error); + // A failed prefetch is released here instead of waiting for the next load or for the teardown, so its + // decoder, demuxer, downloader and buffered frames never outlive the failure. + this.disposeItemAsync(item).catch((disposeError) => { + console.debug('Audio player: the failed prefetch could not be released.', disposeError); + }); + return; + } + this.stopMonitor(); + this.isUnderrunPaused = false; + item.isSeeking = false; + if (item.scheduler) + item.scheduler.stop(); + if (item.source) + item.source.setSeeking(false); + this.host.reportBuffering(false); + // The audio that is already scheduled is suspended before the failure is reported, so a failed track never keeps playing while the player shows its error state. + this.renderer.pauseAsync().catch((pauseError) => { + console.debug('Audio player: the renderer could not be paused after a failure.', pauseError); + }); + this.host.reportError(LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR)); + // The failed item is not retained in the error state: its decoder, demuxer, downloader, prefetch and scheduled + // sources are released now. The player refuses seeks and resumes in the error state anyway, and a replay starts + // a fresh load. + if (this.current === item) + this.current = null; + this.disposeItemAsync(item).catch((disposeError) => { + console.debug('Audio player: the failed track could not be released.', disposeError); + }); + } + + /** + * Waits for the decode loop of an item to stop. + * @param {Object} item - The item whose loop is awaited. + * @returns {Promise} A promise that completes when the loop stopped. + */ + async waitForDecodeLoopAsync(item) { + const loop = item.loopPromise; + if (!loop) + return; + try { + await loop; + } catch (error) { + // The loop reports its own failures, so a teardown never surfaces them. + } + } + + /** + * Rebuilds the demuxer of an item from the beginning of its stream, used when a seek cannot be performed by time. + * @param {Object} item - The item whose demuxer is rebuilt. + * @returns {Promise} A promise that completes when the new demuxer is ready. + */ + async rebuildDemuxerAsync(item) { + const previous = item.demuxer; + item.demuxer = null; + if (previous) + await previous.destroyAsync(); + if (item.stopped || item.disposed) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The track was released while its demuxer was rebuilt.'); + const demuxer = await LuminaAudioPlayer.createDemuxerForManifest(item.manifest, { + source: item.source || item.downloader, + capabilities: this.capabilities, + events: this.events, + onError: (error) => this.failItem(item, error) + }); + if (!demuxer) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The track cannot be demuxed again after a seek.'); + if (item.stopped || item.disposed) { + // The item was released while the demuxer probed its header, so the new demuxer must not be installed after the disposal already walked past a null demuxer. + await demuxer.destroyAsync(); + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The track was released while its demuxer was rebuilt.'); + } + item.demuxer = demuxer; + const configuration = demuxer.getConfiguration(); + if (configuration) + item.decoder.configure(configuration); + } + + /** + * Releases every resource of a pipeline item. It is idempotent. + * @param {Object} item - The item to release. + * @returns {Promise} A promise that completes when the item was released. + */ + async disposeItemAsync(item) { + if (!item || item.disposed) + return; + item.disposed = true; + item.stopped = true; + item.loopToken = null; + this.cancelPrefetchWait(item); + if (item.scheduler) + item.scheduler.stop(); + // The item may itself have prefetched the track after it, which must not keep downloading or decoding once the + // item is released, for example when a seek drops a whole gapless chain. + if (item.prefetch) { + try { + await this.cancelPrefetchAsync(item); + } catch (error) { + console.debug('Audio player: the prefetch of a released track could not be released.', error); + } + } + if (item.downloader) { + try { + item.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the download of a released track could not be aborted.', abortError); + } + } + // The decoder is destroyed before the decode loop is awaited, because destroying it releases a decode that is + // waiting for room, which is the only thing that can keep the loop from noticing the item stopped. + if (item.decoder) { + try { + await item.decoder.destroyAsync(); + } catch (error) { + console.debug('Audio player: the decoder of a released track could not be destroyed.', error); + } + } + await this.waitForDecodeLoopAsync(item); + if (item.scheduler) { + try { + item.scheduler.dispose(); + } catch (error) { + console.debug('Audio player: the scheduler of a released track could not be released.', error); + } + } + if (item.demuxer) { + try { + await item.demuxer.destroyAsync(); + } catch (error) { + console.debug('Audio player: the demuxer of a released track could not be destroyed.', error); + } + } + if (item.source) + item.source.destroy(); + if (item.downloader) { + try { + await item.downloader.destroyAsync(); + } catch (error) { + console.debug('Audio player: the downloader of a released track could not be destroyed.', error); + } + } + } + + /** + * Releases the item that is playing, the prefetch that feeds it and the item that was already attached to the renderer schedule, without touching the renderer itself. + * @param {Object|null} [loadTokenToAbort] - A load token whose manifest request must be aborted, used by the + * destroy path. A load never aborts its own token here, because the request it is about to make belongs to it. + * @param {Object|null} [loadToken] - The token of the load that owns this teardown. Shared state is only touched + * after the awaited disposals when this is still the current token. + * @param {boolean} [keepBuffering=false] - True to keep a loading state that was handed to the load by the player, + * used by an automatic continuation so the end gap keeps showing that the next track is being prepared. + * @returns {Promise} A promise that completes when the playback resources were released. + */ + async teardownPlaybackAsync(loadTokenToAbort = null, loadToken = null, keepBuffering = false) { + // The items are captured and detached synchronously, so a teardown that is overtaken while it awaits can only + // release the pipeline it captured and can never null or dispose the item a newer load installed. + const current = this.current; + const next = this.nextItem; + this.current = null; + this.nextItem = null; + const prefetchedInFlight = current && current.prefetch ? current.prefetch.item : null; + this.abortLoad(loadTokenToAbort); + this.stopMonitor(); + this.isUnderrunPaused = false; + // Every stage is stopped before the renderer is reset: the schedulers drop the frames that are still in flight, + // the downloaders release the reads that are waiting, and only then does the shared renderer stop its schedule, + // so a decoder cannot append a frame of the replaced track after the reset. + for (const item of [current, next, prefetchedInFlight]) { + if (!item) + continue; + item.stopped = true; + item.loopToken = null; + if (item.scheduler) + item.scheduler.stop(); + if (item.downloader) { + try { + item.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the download of the replaced track could not be aborted.', abortError); + } + } + } + try { + this.renderer.cancelTrackGainChange(); + } catch (error) { + console.debug('Audio player: the scheduled ReplayGain change of the replaced track could not be cleared.', error); + } + try { + this.renderer.seekTo(0); + } catch (error) { + console.debug('Audio player: the schedule of the replaced track could not be stopped.', error); + } + // The captured items are released even when this teardown was overtaken, because the newer teardown already saw + // a null current and would otherwise leak them. No shared state is read or written after these awaits. + if (next) + await this.disposeItemAsync(next); + if (current) + await this.disposeItemAsync(current); + if (!keepBuffering && (!loadToken || this.loadToken === loadToken)) + this.host.reportBuffering(false); + } + + //+======================================================================================+ + //| Manifest access | + //+======================================================================================+ + + /** + * Fetches the playback manifest of a track from the web application. + * @param {Object} descriptor - The play descriptor of the track. + * @param {AbortSignal} [signal] - An optional signal that cancels the request, used by a cancelled prefetch. + * @returns {Promise} The playback manifest. + * @throws {LuminaAudioPlayer.PlayerError} When the descriptor is incomplete, the session expired, or the manifest + * could not be read. + */ + async fetchManifestAsync(descriptor, signal) { + // The injected transport wins over the host, exactly like the injected configuration does. + const transport = (typeof this.options.fetchJsonAsync === 'function') + ? this.options.fetchJsonAsync + : ((this.host && typeof this.host.fetchJsonAsync === 'function') + ? (requestUrl, requestSignal, label, requestOptions) => this.host.fetchJsonAsync(requestUrl, requestSignal, label, requestOptions) + : null); + return LuminaAudioPlayer.fetchPlaybackManifestAsync({ + configuration: this.getConfiguration(), + descriptor: descriptor, + capabilities: await this.describeCapabilitiesAsync(), + transport: transport, + signal: signal + }); + } + + /** + * Describes the container and codec pairs the browser can play directly, which the playback format service uses to decide between direct play, remux and transcode. + * @returns {Promise} The comma separated capability list, or an empty string when it cannot be built. + */ + async describeCapabilitiesAsync() { + if (typeof LuminaAudioPlayer.describeDemuxerFormatsAsync !== 'function') + return ''; + try { + return await LuminaAudioPlayer.describeDemuxerFormatsAsync({ + capabilities: this.capabilities, + events: this.events + }); + } catch (error) { + // The list is an optimization of the delivery decision, so a failed probe falls back to the static registry rather than making the track unplayable. + console.debug('Audio player: the decode aware capability list could not be built.', error); + return typeof LuminaAudioPlayer.describeDemuxerFormats === 'function' ? LuminaAudioPlayer.describeDemuxerFormats() : ''; + } + } + + /** + * Gets the endpoints configuration of the player. + * @returns {Object} The endpoints configuration. + */ + getConfiguration() { + if (this.options.configuration) + return this.options.configuration; + return this.host && typeof this.host.getConfiguration === 'function' ? this.host.getConfiguration() : {}; + } + + } + + LuminaAudioPlayer.MediaPipelineEngine = MediaPipelineEngine; + + /** + * Creates a media pipeline engine. See {@link LuminaAudioPlayer.MediaPipelineEngine} for the options. + * @param {Object} host - The engine host provided by the player controller. + * @param {Object} [options] - The engine options. + * @returns {LuminaAudioPlayer.MediaPipelineEngine} The created engine. + */ + LuminaAudioPlayer.createMediaPipelineEngine = function (host, options) { + return new MediaPipelineEngine(host, options); + }; + + /** + * Registers the media pipeline engine on a player and makes it the selected engine. The player is the singleton of + * the application, so this is what turns the control API and the bar into an actually audible player. + * @param {LuminaAudioPlayer.AudioPlayer} player - The player to install the engine on. + * @returns {LuminaAudioPlayer.AudioPlayer} The same player, for chaining. + */ + LuminaAudioPlayer.installMediaPipelineEngine = function (player) { + if (!player) + return player; + player.registerEngine(LuminaAudioPlayer.PIPELINE_ENGINE_NAME, (host) => new MediaPipelineEngine(host)); + return player.useEngine(LuminaAudioPlayer.PIPELINE_ENGINE_NAME); + }; + + /** + * Creates the singleton player when it does not exist yet and installs the media pipeline engine on it. It is the one + * composition point of the engine, and it requires the player module to be loaded first, which is the order the layout + * uses. When the player module is absent the install is skipped instead of throwing, so loading this module early is harmless; the engine is then simply not selected. + */ + function installOnDefaultPlayer() { + if (typeof LuminaAudioPlayer.createDefaultPlayer !== 'function') + return; + const player = LuminaAudioPlayer.createDefaultPlayer(); + LuminaAudioPlayer.installMediaPipelineEngine(player); + } + + if (document.readyState === 'loading') + document.addEventListener('DOMContentLoaded', installOnDefaultPlayer); + else + installOnDefaultPlayer(); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js new file mode 100644 index 00000000..9f269757 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js @@ -0,0 +1,390 @@ +/** + * Schedulers of the audio player pipeline. + * + * The seekable scheduler trims the first decoded frame after a seek to the requested position before it reaches the + * renderer. The buffering scheduler holds the decoded audio of a gapless prefetch until the handoff appends it to the + * shared schedule. They are the only pipeline stages that know how decoded AudioData is shaped and laid on the timeline. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The duration, in seconds, of the next track that is pre-decoded for a gapless transition. + * @readonly + * @type {number} + */ + const GAPLESS_PRELOAD_SECONDS = 2; + + /** + * The scheduled ahead ceiling, in seconds, of the scheduler that receives the pre-decoded audio of the next track. It + * bounds how much decoded audio is retained before the handoff, and it is lifted when the pre-decoded audio is appended to the renderer. + * @readonly + * @type {number} + */ + const GAPLESS_BUFFER_CEILING_SECONDS = GAPLESS_PRELOAD_SECONDS + 1; + + /** + * The tolerance, in seconds, within which the first frame after a seek counts as beginning at the seek target, so that a frame is not trimmed for a rounding error. + * @readonly + * @type {number} + */ + const SEEK_TRIM_EPSILON_SECONDS = 0.001; + + /** + * Coerces a value to a finite number, or null when it is absent or not finite. + * @param {*} value - The value to coerce. + * @returns {number|null} The finite number, or null. + */ + function toFiniteNumber(value) { + return LuminaAudioPlayer.toFiniteNumber(value); + } + + /** + * Reads the media duration of a decoded frame, in seconds. + * @param {AudioData} audioData - The decoded frame. + * @returns {number} The duration, in seconds, or zero when it cannot be read. + */ + function getAudioDataDurationSeconds(audioData) { + const frames = toFiniteNumber(audioData && audioData.numberOfFrames); + const sampleRate = toFiniteNumber(audioData && audioData.sampleRate); + if (frames === null || sampleRate === null || frames <= 0 || sampleRate <= 0) + return 0; + return frames / sampleRate; + } + + /** + * Releases the native memory of a decoded frame. It is safe to call on a frame that was already closed. + * @param {AudioData} audioData - The frame to close. + */ + function closeAudioData(audioData) { + if (!audioData || typeof audioData.close !== 'function') + return; + try { + audioData.close(); + } catch (error) { + console.debug('Audio player: a decoded frame could not be released.', error); + } + } + + /** + * Trims the leading frames of a decoded frame, so that the audio it carries starts exactly at a target position. + * + * The decoded frame is a planar 32 bit float frame, because that is what the decode pipeline copies and what the + * renderer consumes. The trimmed frame is a new AudioData whose timestamp is the target position, so the renderer + * adopts the requested seek position as the origin of the audio. The original frame is closed by this function when a trimmed frame is produced. + * @param {AudioData} audioData - The decoded frame to trim. + * @param {number} offsetSeconds - The number of seconds to remove from the start of the frame. + * @returns {AudioData|null} The trimmed frame, or null when the frame cannot be rebuilt. + */ + function trimAudioData(audioData, offsetSeconds) { + // Read the WebCodecs constructor at call time, so a host without AudioData (or a test) can fall back to scheduling + // the untrimmed frame instead of failing at module load. + const AudioDataConstructor = typeof window !== 'undefined' && typeof window.AudioData === 'function' + ? window.AudioData + : null; + if (!AudioDataConstructor || !audioData || typeof audioData.copyTo !== 'function') + return null; + // AudioData exposes readonly typed properties. Read them through the shared helper so a missing or non numeric + // value rejects the trim instead of producing a frame with NaN dimensions. + const frames = toFiniteNumber(audioData.numberOfFrames); + const channels = toFiniteNumber(audioData.numberOfChannels); + const sampleRate = toFiniteNumber(audioData.sampleRate); + const timestamp = toFiniteNumber(audioData.timestamp); + if (frames === null || channels === null || sampleRate === null || timestamp === null) + return null; + if (frames <= 0 || channels <= 0 || sampleRate <= 0) + return null; + // Round to the nearest sample. The offset is a time difference, so flooring it could leave a fraction of a sample + // of audio from before the seek target audible. + const framesToTrim = Math.round(offsetSeconds * sampleRate); + // AudioData can only hold whole frames. Drop any partial trailing sample from the source count. + const keptFrames = Math.floor(frames) - framesToTrim; + // Nothing to remove, or nothing left to play. The caller keeps the original frame, which is the safer fallback for + // a frame that starts at the target or ends exactly at it. + if (framesToTrim <= 0 || keptFrames <= 0) + return null; + // One planar block holds every channel back to back. The subarray per channel is exactly the layout AudioData + // expects for f32-planar, and it avoids one allocation per channel. + const samples = new Float32Array(keptFrames * Math.floor(channels)); + try { + for (let channel = 0; channel < channels; channel++) { + const destination = samples.subarray(channel * keptFrames, (channel + 1) * keptFrames); + // Skip the pre-target frames and copy only the kept tail. copyTo is the only way to read the native + // AudioData memory without holding on to the original frame. + audioData.copyTo(destination, { + planeIndex: channel, + frameOffset: framesToTrim, + frameCount: keptFrames, + format: 'f32-planar' + }); + } + // The trimmed frame starts at the seek target, and WebCodecs timestamps are integer microseconds. Keeping the + // original timestamp plus the removed audio keeps the frame on the same absolute timeline. + const trimmed = new AudioDataConstructor({ + format: 'f32-planar', + sampleRate: sampleRate, + numberOfFrames: keptFrames, + numberOfChannels: Math.floor(channels), + timestamp: Math.round(timestamp + offsetSeconds * 1000000), + data: samples + }); + // The original is released only after the replacement exists. If the constructor above throws, ownership stays + // with the caller, which then schedules the original frame. + closeAudioData(audioData); + return trimmed; + } catch (error) { + // Returning null rather than throwing lets the scheduler play the original frame. A seek may then be a packet + // early, but a browser that refuses to construct an AudioData never turns the seek into silence. + console.debug('Audio player: the first decoded frame after a seek could not be trimmed.', error); + return null; + } + } + + /** + * A scheduler proxy over the renderer that trims the first decoded frame after a seek to the requested position. + * + * A demuxer repositions to a packet boundary at or before the seek target, so the first decoded frame may carry audio + * from before the target. The renderer adopts the requested position as the origin of the first buffer it receives and + * cannot correct an offset it is not told about, so the offset is removed here, before the frame reaches the renderer. + */ + class SeekableScheduler { + /** + * Creates an instance of SeekableScheduler. + * @param {Object} target - The scheduler the frames are handed to, normally the renderer. + * @param {Function} [onScheduled] - Called once, when the first frame is handed to the target after a seek or a load. + */ + constructor(target, onScheduled) { + this.target = target; + this.onScheduled = typeof onScheduled === 'function' ? onScheduled : null; + this.hasScheduled = false; + // The absolute media position the first frame after a seek must start at, or null when no trim is pending. + this.trimTargetSeconds = null; + // A scheduler of a released item drops every frame that is still emitted, so a decoder that was destroyed with + // frames in flight can never schedule audio for a track that is no longer playing. + this.stopped = false; + // While a seek owns the timeline, frames that the old decode loop still emits are dropped instead of being laid + // at the new position before the decoder reset takes effect. + this.suppressed = false; + } + + /** + * Sets whether frames are dropped instead of scheduled, which a seek uses until every stage is repositioned. + * @param {boolean} value - True to drop frames, false to schedule them again. + */ + setSuppressed(value) { + this.suppressed = value === true; + } + + /** + * Marks the position the next decoded frame must begin at, removing any audio that a demuxer landed before it. + * @param {number} seconds - The absolute media position of the seek target, in seconds. + */ + setSeekTarget(seconds) { + const value = toFiniteNumber(seconds); + this.trimTargetSeconds = value === null ? null : Math.max(0, value); + } + + /** + * Re-arms the first frame notification, so the state of a fresh seek or a fresh track is observed again. + */ + rearm() { + this.hasScheduled = false; + } + + /** + * Stops the scheduler, so every later frame is dropped instead of being handed to the target. It is used when the item that owns the scheduler is released or fails. + */ + stop() { + this.stopped = true; + } + + /** + * Hands a decoded frame to the target, trimming it when it carries audio from before the pending seek target. + * @param {AudioData} audioData - The decoded frame. Ownership transfers to this scheduler, which always closes it. + * @returns {number} The media position at the end of the frame, or the target position when the frame was dropped. + */ + schedule(audioData) { + if (this.stopped || this.suppressed) { + closeAudioData(audioData); + return 0; + } + let frame = audioData; + const target = this.trimTargetSeconds; + if (target !== null) { + const frameStart = toFiniteNumber(frame.timestamp); + const frameDuration = getAudioDataDurationSeconds(frame); + if (frameStart !== null && frameDuration > 0) { + // WebCodecs reports the frame timestamp in microseconds, while the scheduler and the renderer work in + // seconds. + const secondsStart = frameStart / 1000000; + const secondsEnd = secondsStart + frameDuration; + if (secondsEnd <= target + SEEK_TRIM_EPSILON_SECONDS) { + // The whole frame is before the target, so it is dropped instead of played early. + closeAudioData(frame); + return target; + } + if (secondsStart < target - SEEK_TRIM_EPSILON_SECONDS) { + const trimmed = trimAudioData(frame, target - secondsStart); + if (trimmed) { + frame = trimmed; + } else { + // A frame that cannot be rebuilt is scheduled from its own start rather than dropped, so a + // browser that refuses to construct an AudioData never turns a seek into a gap. The offset is at most one packet long. + this.trimTargetSeconds = null; + } + } + } + // Only the first frame after a seek can straddle the target. Later frames already start after it, so a + // pending trim must not leak into the next seek. + this.trimTargetSeconds = null; + } + if (!this.hasScheduled) { + this.hasScheduled = true; + if (this.onScheduled) + this.onScheduled(); + } + return this.target.schedule(frame); + } + + /** + * Attaches the scheduler to the target it was buffering for, which is how a prefetch becomes the audio that plays. + * @param {Object} target - The scheduler the frames are handed to from now on. + */ + attach(target) { + const previous = this.target; + this.target = target; + // A buffering target flushes the audio it pre-decoded into the new target, which is the renderer. A renderer target has no attach method and is simply replaced. + if (previous && typeof previous.attach === 'function') + previous.attach(target); + } + + /** + * Gets the scheduled ahead duration the current target reports. + * @returns {number} The scheduled ahead duration, in seconds. + */ + getScheduledAheadSeconds() { + return typeof this.target.getScheduledAheadSeconds === 'function' ? this.target.getScheduledAheadSeconds() : 0; + } + + /** + * Gets the scheduled ahead ceiling the current target publishes, or null when it publishes none. + * @returns {number|null} The ceiling, in seconds. + */ + getMaxScheduledAheadSeconds() { + return typeof this.target.getMaxScheduledAheadSeconds === 'function' ? this.target.getMaxScheduledAheadSeconds() : null; + } + + /** + * Gets the playback rate of the current target, which is one when the target does not report it. + * @returns {number} The playback rate. + */ + getPlaybackRate() { + return typeof this.target.getPlaybackRate === 'function' ? this.target.getPlaybackRate() : 1; + } + + /** + * Releases the audio a buffering target still holds. A renderer target is left untouched, because it is shared. + */ + dispose() { + if (this.target && typeof this.target.close === 'function') + this.target.close(); + } + } + + /** + * A scheduler that holds the decoded audio of a prefetched track until the current track hands over to it. + * + * While it is detached it reports the duration it holds as its scheduled ahead duration, so the decoder paces itself + * against the buffer instead of decoding the whole next track, and it publishes a ceiling that bounds that buffer. + * Once attached, it flushes the buffered frames into the target in order and delegates every later frame to it. + */ + class BufferingScheduler { + /** + * Creates an instance of BufferingScheduler. + */ + constructor() { + this.target = null; + this.buffer = []; + this.bufferedSeconds = 0; + } + + /** + * Stores a decoded frame until the scheduler is attached, or hands it to the target once it is. + * @param {AudioData} audioData - The decoded frame. Ownership transfers to this scheduler. + * @returns {number} The buffered duration in seconds while detached, or the target position after attaching. + */ + schedule(audioData) { + if (this.target) + return this.target.schedule(audioData); + const duration = getAudioDataDurationSeconds(audioData); + this.buffer.push(audioData); + this.bufferedSeconds += duration; + return this.bufferedSeconds; + } + + /** + * Attaches the scheduler to the target it buffered for: the buffered frames are appended to the target in order, + * so the next track starts exactly at the end of the audio of the current one. + * @param {Object} target - The scheduler to hand the buffered and later frames to. + */ + attach(target) { + this.target = target; + const pending = this.buffer; + let index = 0; + try { + for (; index < pending.length; index++) + target.schedule(pending[index]); + } catch (error) { + // The target owns and closes the frame it refused; every frame after it is still buffered and must be + // released here, or up to the whole pre-decode window is retained as native audio until garbage collection. + console.debug('Audio player: a pre-decoded frame could not be scheduled.', error); + for (let remaining = index + 1; remaining < pending.length; remaining++) + closeAudioData(pending[remaining]); + } finally { + this.buffer = []; + this.bufferedSeconds = 0; + } + } + + /** + * Gets the buffered duration while detached, or the scheduled ahead duration of the target once attached. + * @returns {number} The scheduled ahead duration, in seconds. + */ + getScheduledAheadSeconds() { + return this.target ? this.target.getScheduledAheadSeconds() : this.bufferedSeconds; + } + + /** + * Gets the ceiling the decoder paces itself against. While detached it bounds the prefetch buffer, and once attached it is the ceiling of the target. + * @returns {number|null} The ceiling, in seconds. + */ + getMaxScheduledAheadSeconds() { + if (this.target) + return typeof this.target.getMaxScheduledAheadSeconds === 'function' ? this.target.getMaxScheduledAheadSeconds() : null; + return GAPLESS_BUFFER_CEILING_SECONDS; + } + + /** + * Gets the playback rate of the target, or one while detached. + * @returns {number} The playback rate. + */ + getPlaybackRate() { + return this.target && typeof this.target.getPlaybackRate === 'function' ? this.target.getPlaybackRate() : 1; + } + + /** + * Releases every frame that was buffered and never scheduled. + */ + close() { + for (const audioData of this.buffer) + closeAudioData(audioData); + this.buffer = []; + this.bufferedSeconds = 0; + } + } + + LuminaAudioPlayer.GAPLESS_PRELOAD_SECONDS = GAPLESS_PRELOAD_SECONDS; + LuminaAudioPlayer.SEEK_TRIM_EPSILON_SECONDS = SEEK_TRIM_EPSILON_SECONDS; + LuminaAudioPlayer.SeekableScheduler = SeekableScheduler; + LuminaAudioPlayer.BufferingScheduler = BufferingScheduler; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js index 594a3a36..2ae0156e 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js @@ -109,7 +109,7 @@ * const renderer = LuminaAudioPlayer.createTrackRenderer({ * replayGainMode: host.getPreferences().replayGainMode, * events: host.events, - * onTimeUpdate: (time, duration) => host.reportTime(time, duration), + * onTimeUpdate: (time, trackDuration, timelineDuration) => host.reportTime(time, trackDuration), * onEnded: () => host.reportEnded() * }); * renderer.configure(manifest); @@ -240,6 +240,14 @@ */ const TRACK_GAIN_RAMP_SECONDS = 0.05; + /** + * The ramp, in seconds, of the ReplayGain change at a gapless boundary. It is scheduled at the context time the next + * track starts, so it is short enough to be inaudible as a blend and long enough not to click. + * @readonly + * @type {number} + */ + const TRACK_GAIN_HANDOFF_RAMP_SECONDS = 0.01; + /** * The interval, in milliseconds, the reporter falls back to when the page has no requestAnimationFrame. * @readonly @@ -370,7 +378,9 @@ * @param {number} [options.playbackRate] - The playback rate, within the accepted playback rate range. Defaults to 1. * @param {number} [options.maxScheduledAheadSeconds] - An optional ceiling, in seconds, on how far ahead of the audio clock the schedule may run. Scheduling beyond it is refused with a typed error, so a caller that never paces itself cannot grow the schedule without bound. Leave the option out to disable the ceiling; a value of zero is a real ceiling that refuses every buffer, not a way to disable it. * @param {Object} [options.events] - The player event bus. When provided, the renderer follows the player's ReplayGain mode changes. - * @param {Function} [options.onTimeUpdate] - Called with the current time and the duration, in seconds, while the audio plays. + * @param {Function} [options.onTimeUpdate] - Called while the audio plays with the absolute timeline position, the + * duration of the current track, and the duration of the whole shared timeline, in seconds. The position is always + * on the timeline, so the timeline duration is the value that bounds a seek; the track duration is the one the bar shows for the current item. * @param {Function} [options.onEnded] - Called once per configured track when its scheduled audio has been fully played. Audio scheduled after the end, without a configure or a seek, continues the same logical track and does not report the end again. */ constructor(options = {}) { @@ -400,7 +410,12 @@ this.trackGain = null; this.manifest = null; this.duration = 0; + // The media duration of the whole shared timeline. It equals the duration of the current track until a gapless + // handoff appends another track, which is why it is kept apart from the duration of the current track. + this.timelineDuration = 0; this.trackGainValue = 1; + // The ReplayGain change of a gapless handoff, scheduled at the context time the next track starts, or null. + this.pendingGainChange = null; this.error = null; // The scheduled sources, in media order, each one holding the audio buffer it plays so a playback rate change @@ -464,6 +479,7 @@ this.duration = this.manifest && toFiniteNumber(this.manifest.durationInSeconds) !== null ? Math.max(0, Number(this.manifest.durationInSeconds)) : 0; + this.timelineDuration = this.duration; this.mediaCursor = 0; this.nextStartTime = 0; this.pausedMediaTime = 0; @@ -472,11 +488,117 @@ this.streamComplete = false; this.anchorContextTime = this.context.currentTime; this.anchorMediaTime = 0; + // A new track replaces any scheduled handoff gain of the previous one. + this.pendingGainChange = null; this.applyTrackGain(0); this.applyMasterGain(0); return this; } + /** + * Adopts the manifest of a track that continues the current schedule without resetting it, which is how a gapless + * transition applies the ReplayGain values of the next track. The schedule, the playhead and the completion state + * are left untouched, because the audio of the next track is already appended after the current one. + * @param {Object} manifest - The playback manifest of the continuing track. + * @param {boolean} [isGainAlreadyScheduled=false] - True when scheduleManifestGain already scheduled the ReplayGain + * change at the boundary, so applying it again with a late ramp is skipped. + * @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining. + * @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed. + */ + adoptManifest(manifest, isGainAlreadyScheduled = false) { + if (this.destroyed) + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The renderer was destroyed.')); + this.manifest = manifest || null; + this.duration = this.manifest && toFiniteNumber(this.manifest.durationInSeconds) !== null + ? Math.max(0, Number(this.manifest.durationInSeconds)) + : this.duration; + this.pendingGainChange = null; + // The gapless handoff schedules the gain automation at the exact boundary context time, so the manifest is + // adopted without applying a second, late ramp when that automation was accepted. + if (isGainAlreadyScheduled) { + this.trackGainValue = this.computeTrackGain(this.manifest); + } else { + this.applyTrackGain(TRACK_GAIN_RAMP_SECONDS); + } + return this; + } + + /** + * Schedules the ReplayGain change of the next track at the context time that track starts, instead of applying it + * when the boundary is detected up to a reporter tick later. The schedule is stored, so a ReplayGain mode change + * before the boundary can reschedule it, and it is cleared when the handoff is abandoned. + * @param {Object} manifest - The playback manifest of the next track. + * @param {number} whenContextTime - The context time, in seconds, at which the next track starts. + * @returns {boolean} True when the automation was scheduled, false when the parameter cannot automate. + * @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed. + */ + scheduleManifestGain(manifest, whenContextTime) { + if (this.destroyed) + throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The renderer was destroyed.')); + this.ensureContext(); + // A call that cannot schedule anything must not leave a previous handoff change pending. + this.pendingGainChange = null; + const when = toFiniteNumber(whenContextTime); + if (when === null || !this.trackGain || !this.trackGain.gain) + return false; + const param = this.trackGain.gain; + if (typeof param.setValueAtTime !== 'function' || typeof param.linearRampToValueAtTime !== 'function') + return false; + const start = Math.max(this.context.currentTime, when); + const gain = this.computeTrackGain(manifest); + try { + if (typeof param.cancelAndHoldAtTime === 'function') { + // Holding at the boundary samples the value the automation actually has at that time, including a ramp + // that is still in progress because the ReplayGain mode changed after the handoff was scheduled. + param.cancelAndHoldAtTime(start); + } else { + const current = Number.isFinite(param.value) ? param.value : 1; + param.setValueAtTime(current, start); + } + param.linearRampToValueAtTime(gain, start + TRACK_GAIN_HANDOFF_RAMP_SECONDS); + this.pendingGainChange = { manifest: manifest || null, when: start }; + return true; + } catch (error) { + this.pendingGainChange = null; + console.debug('Audio player: the ReplayGain change of the next track could not be scheduled.', error); + return false; + } + } + + /** + * Cancels a scheduled gapless ReplayGain change and restores the gain of the current manifest. It is used when the + * handoff is abandoned before the next track starts. + * @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining. + */ + cancelTrackGainChange() { + this.pendingGainChange = null; + if (this.trackGain && this.trackGain.gain && this.context + && typeof this.trackGain.gain.cancelScheduledValues === 'function') { + try { + this.trackGain.gain.cancelScheduledValues(this.context.currentTime); + } catch (error) { + console.debug('Audio player: the scheduled ReplayGain change could not be cancelled.', error); + } + } + if (!this.destroyed) + this.applyTrackGain(0); + return this; + } + + /** + * Extends the media duration of the shared timeline, so that a seek into a gapless chain is bounded by the audio + * that is actually scheduled rather than by the duration of the first track of the chain. The duration is only + * used to bound a seek and to report the timeline length; the end of the audio is detected from the schedule. + * @param {number} duration - The media duration of the whole timeline, in seconds. + * @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining. + */ + setTimelineDuration(duration) { + const value = toFiniteNumber(duration); + if (value !== null && value >= 0) + this.timelineDuration = value; + return this; + } + /** * Releases every resource of the renderer: the schedule, the gain nodes, the event subscriptions and, when the * renderer owns it, the audio context. @@ -486,6 +608,7 @@ this.destroyed = true; this.playing = false; this.paused = false; + this.pendingGainChange = null; this.stopReporter(); for (const unsubscribe of this.unsubscribers) { try { @@ -656,7 +779,11 @@ if (next === this.replayGainMode) return this.replayGainMode; this.replayGainMode = next; + // The current gain is applied first, which cancels the scheduled handoff change, so a scheduled change is put back with the values of the new mode. + const pending = this.pendingGainChange; this.applyTrackGain(TRACK_GAIN_RAMP_SECONDS); + if (pending) + this.scheduleManifestGain(pending.manifest, pending.when); return this.replayGainMode; } @@ -803,7 +930,10 @@ return this.mediaCursor; this.ensureContext(); const position = Math.max(0, request); - const bounded = this.duration > 0 ? Math.min(position, this.duration) : position; + // A track whose duration is not known has no timeline bound to clamp against; clamping to the end of the + // previous track would silently restart it at its base position. + const limit = this.duration > 0 ? (this.timelineDuration > 0 ? this.timelineDuration : this.duration) : 0; + const bounded = limit > 0 ? Math.min(position, limit) : position; this.stopAllSources(); this.mediaCursor = bounded; this.nextStartTime = 0; @@ -824,6 +954,17 @@ this.streamComplete = true; } + /** + * Clears the stream-complete state, so a drained schedule is treated as an underrun gap again instead of the end + * of the track. It is used when a gapless handoff appends the next track after the end of the current decode was + * already recorded: the schedule then carries more audio, and a slow download of that audio must pause and resume rather than end the second track early. + * @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining. + */ + clearStreamComplete() { + this.streamComplete = false; + return this; + } + //+======================================================================================+ //| Query surface | //+======================================================================================+ @@ -846,6 +987,21 @@ return clamp(media, 0, upperBound); } + /** + * Converts an absolute media position of the shared timeline into the context time at which it will play. The + * renderer owns the anchor, the playback rate and the lead time of the schedule, so a caller that needs to schedule + * something at a media position must use this conversion instead of repeating the anchor math. + * @param {number} mediaSeconds - The absolute media position, in seconds. + * @returns {number} The context time, in seconds, or zero when the renderer has no context. + */ + getContextTimeForMediaPosition(mediaSeconds) { + const target = toFiniteNumber(mediaSeconds); + if (target === null || !this.context) + return 0; + const rate = this.playbackRate > 0 ? this.playbackRate : 1; + return this.context.currentTime + Math.max(0, (target - this.getCurrentTime()) / rate); + } + /** * Gets the duration of the current track, from its playback manifest. * @returns {number} The duration, in seconds, or zero when it is unknown. @@ -854,6 +1010,15 @@ return this.duration; } + /** + * Gets the duration of the whole shared timeline, which is longer than the current track when a gapless handoff + * has appended another track. It is the value a seek is bounded by. + * @returns {number} The timeline duration, in seconds, or zero when it is unknown. + */ + getTimelineDuration() { + return this.timelineDuration; + } + /** * Gets the output volume, which is independent of the mute state. * @returns {number} The volume, between 0 and 1. @@ -1067,13 +1232,22 @@ * @param {number} rampSeconds - The duration of the ramp to the new value, in seconds. Zero applies it at once. */ applyTrackGain(rampSeconds) { - const values = resolveReplayGain(this.manifest, this.replayGainMode); - this.trackGainValue = computeReplayGainLinearGain(values.gainDb, values.peak); + this.trackGainValue = this.computeTrackGain(this.manifest); if (!this.trackGain || !this.trackGain.gain) return; this.setAudioParamValue(this.trackGain.gain, this.trackGainValue, rampSeconds); } + /** + * Computes the linear ReplayGain value a manifest and the current mode select. + * @param {Object|null} manifest - The playback manifest. + * @returns {number} The linear gain, one when nothing is selected. + */ + computeTrackGain(manifest) { + const values = resolveReplayGain(manifest, this.replayGainMode); + return computeReplayGainLinearGain(values.gainDb, values.peak); + } + /** * Applies a value to an audio parameter, ramping to it so a change never clicks. * @param {AudioParam} param - The audio parameter to change. @@ -1210,6 +1384,8 @@ const ratio = outputLength / channelData.length; const output = new Float32Array(outputLength); for (let index = 0; index < outputLength; index++) { + // Map each output sample back to its fractional position in the input. The neighbours are clamped at the + // end of the source, so the last sample repeats instead of reading past the array or turning into zero. const position = index / ratio; const lower = Math.floor(position); const fraction = position - lower; @@ -1380,6 +1556,41 @@ this.endReported = false; } + /** + * Removes every scheduled source whose audio begins at or after a media position, keeping the audio before it. It is + * used when a gapless handoff is abandoned after the next track was already appended: the appended audio is stopped + * and released, the media frontier is moved back to the boundary, and the current track can end normally there + * instead of being followed by a transition the user disabled. + * + * Call it while the boundary is still ahead of getCurrentTime(), after the gain change of the next track was + * cancelled and before markStreamComplete(). Truncating behind the playhead would move the media cursor backwards + * and replay audio that already played, so the caller checks getCurrentTime() first and leaves a handoff that has already begun alone. + * @param {number} mediaPosition - The absolute media position from which scheduled audio is removed. + * @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining. + */ + truncateScheduleAt(mediaPosition) { + const target = toFiniteNumber(mediaPosition); + if (this.destroyed || target === null) + return this; + const kept = []; + for (let index = 0; index < this.scheduledSources.length; index++) { + const entry = this.scheduledSources[index]; + if (index >= this.firstLiveIndex && entry.bufferMediaStart >= target) + this.releaseSource(entry.source); + else + kept.push(entry); + } + this.scheduledSources = kept; + if (this.firstLiveIndex > kept.length) + this.firstLiveIndex = kept.length; + this.mediaCursor = Math.max(0, target); + const last = kept[kept.length - 1]; + this.nextStartTime = last ? last.when + last.mediaDuration / last.rate : 0; + if (this.pausedMediaTime > this.mediaCursor) + this.pausedMediaTime = this.mediaCursor; + return this; + } + /** * Releases the scheduled sources whose audio has finished playing. The entries are held in media order, so the * finished ones are always a prefix; the cursor of the first live entry is advanced over that prefix instead of the @@ -1496,7 +1707,7 @@ return; if (this.onTimeUpdate) { try { - this.onTimeUpdate(this.getCurrentTime(), this.getDuration()); + this.onTimeUpdate(this.getCurrentTime(), this.getDuration(), this.getTimelineDuration()); } catch (error) { console.error('Audio player: the renderer time callback threw.', error); } diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js index c85efe06..07d38275 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js @@ -23,6 +23,18 @@ return Math.min(maximum, Math.max(minimum, value)); }; + /** + * Coerces a value to a finite number, or null when it is absent or not finite. + * @param {*} value - The value to coerce. + * @returns {number|null} The finite number, or null. + */ + LuminaAudioPlayer.toFiniteNumber = function toFiniteNumber(value) { + if (value === null || value === undefined || value === '') + return null; + const number = Number(value); + return Number.isFinite(number) ? number : null; + }; + /** * Checks whether a value is the AbortError a reset, a close or an aborted fetch rejects with. An AbortError is tested * by name rather than by type, because in a browser it is a DOMException, which is not an Error. @@ -68,4 +80,14 @@ return typed; return new LuminaAudioPlayer.PlayerError(typed.code, typed.message, LuminaAudioPlayer.mergeErrorDetails(typed.details, details)); }; + + /** + * The result of a background request whose answer was a redirect, which means the session expired and the page is + * being sent to the sign in page. It is distinct from a missing value, which is a failure, so that a caller does not + * report an error for a redirect it is already handling. It lives in this dependency free module, which is loaded + * before every feature module, so a consumer can recognize it even when the controller is not loaded. + * @readonly + * @type {Object} + */ + LuminaAudioPlayer.REDIRECTED = Object.freeze({ redirected: true }); })(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js index 8fb6736c..9d13c62a 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -30,8 +30,15 @@ * - toggleVisibility(): shows or hides the bar. * - on(event, handler): subscribes to a player event, returns an unsubscribe function. * - once(event, handler), off(event, handler): one shot subscribe, and unsubscribe. - * - getState(), getDescriptor(), getQueue(), getCurrentTime(), getDuration(), getVolume(), isMuted(), - * isBuffering(), getBufferedTimeRanges(), getPreferences(), getCapabilities(), getLastError(), getSubTemplates(). + * - getState(), getDescriptor(), getQueue(), getCurrentTime(), getDuration(), getVolume(), + * isMuted(), isBuffering(), getBufferedTimeRanges(), getPreferences(), getCapabilities(), getLastError(), + * getSubTemplates(). + * - getNextDescriptor(): the identity and descriptor of the next queue entry, or null. + * - advanceQueueTo(entryId): moves the queue cursor to the entry with that identity without starting playback, so a + * linear advance, a wrap, a reordered queue and a gapless handoff share one commit. The advance + * is refused when the identity is no longer part of the queue. + * - requestNextTrackAsync(reason): starts the next queue entry through the player's own play path, used by the engine + * when a gapless handoff could not be prepared. * - destroyAsync(): releases every resource of the player. It is only used for an explicit teardown, never * by a navigation, because the navigation manager never recreates the player. * - registerEngine(name, factory): registers an engine factory on this player, by name. @@ -81,14 +88,9 @@ error: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR] }); - /** - * The result of a background request whose answer was a redirect, which means the session expired and the page is - * being sent to the sign in page. It is distinct from a missing value, which is a failure, so that a caller does not - * report an error for a redirect it is already handling. - * @readonly - * @type {Object} - */ - const REDIRECTED = Object.freeze({ redirected: true }); + // The redirect sentinel belongs to the dependency free utils module, so a consumer that is loaded without this + // controller, such as the manifest client, can still recognize it. The local name keeps the references readable. + const REDIRECTED = LuminaAudioPlayer.REDIRECTED; /** * Follows a server redirect, but only when the target is an http or https URL on the same origin and protocol as @@ -127,6 +129,42 @@ } } + /** + * Checks whether a response is a redirect that was not followed because the request asked for manual redirects. + * @param {Response} response - The response to check. + * @returns {boolean} True when the response is a redirect. + */ + function isRedirectResponse(response) { + if (!response) + return false; + if (response.type === 'opaqueredirect') + return true; + const status = Number(response.status); + return status === 301 || status === 302 || status === 303 || status === 307 || status === 308; + } + + /** + * Resolves a configured endpoint URL against the origin of the page, so a root relative configuration value is always + * requested from the page's own origin and not from whatever the server saw as its host or a base element points at. + * @param {string} url - The configured URL. + * @returns {string|null} The resolved absolute URL, or null when it is missing or not on this origin. + */ + function resolveConfiguredUrl(url) { + if (typeof url !== 'string' || url.length === 0) + return null; + try { + const resolved = new URL(url, window.location.origin); + if ((resolved.protocol !== 'http:' && resolved.protocol !== 'https:') + || resolved.origin !== window.location.origin + || resolved.username !== '' + || resolved.password !== '') + return null; + return resolved.href; + } catch (error) { + return null; + } + } + /** * The attribute that marks an element as a play trigger the player handles by event delegation. * @readonly @@ -403,8 +441,15 @@ this.state = LuminaAudioPlayer.PlayerState.IDLE; this.descriptor = null; - this.queue = []; + // The queue entries are the single queue: each entry carries an identity per occurrence, so a repeated track is + // distinguishable from another occurrence of the same track, and the descriptor the public API exposes. Every + // traversal, advance and render derives from this array, so the cursor can never disagree with the queue. + this.queueEntries = []; + this.entrySequence = 0; this.currentIndex = 0; + // The order the queue list was last rendered in, so a future shuffle or reorder that changes queueEntries + // without rendering the list is detected instead of updating the wrong items in place. + this.renderedQueueOrder = []; this.currentTime = 0; this.duration = 0; this.downloadedFraction = 0; @@ -666,10 +711,12 @@ this.scrubRatio = null; this.endScrub(); this.endVolumeAdjust(); + // clearBuffering also clears any pending seek of the previous timeline. this.clearBuffering(); // An album or artist descriptor carries no track id of its own, so the queue starts at its first item in that case. - this.queue = descriptor.queue && descriptor.queue.length > 0 ? [...descriptor.queue] : [descriptor]; - this.currentIndex = Math.max(0, this.queue.findIndex(item => item.trackId === descriptor.trackId)); + const descriptors = descriptor.queue && descriptor.queue.length > 0 ? [...descriptor.queue] : [descriptor]; + this.queueEntries = descriptors.map((entry) => ({ entryId: this.createQueueEntryId(), descriptor: entry })); + this.currentIndex = Math.max(0, this.queueEntries.findIndex((entry) => entry.descriptor.trackId === descriptor.trackId)); // The bar is shown and the state moves to loading before the engine is touched, so a slow engine still gives the user // immediate feedback that the request was accepted. @@ -679,17 +726,50 @@ this.showBar(); this.setState(LuminaAudioPlayer.PlayerState.LOADING); this.events.emit(LuminaAudioPlayer.PlayerEvent.DESCRIPTOR_CHANGED, descriptor); - this.events.emit(LuminaAudioPlayer.PlayerEvent.QUEUE_CHANGED, this.queue); + this.events.emit(LuminaAudioPlayer.PlayerEvent.QUEUE_CHANGED, this.getQueue()); + return this.startLoadedDescriptorAsync(descriptor); + } + + /** + * Starts the engine load and playback of a descriptor the player has already made current and set to its loading + * state. The player state is checked again after each await, so a stop that happens while a load is running keeps + * its intent instead of being overwritten by the load or by the engine. + * @param {Object} descriptor - The descriptor that is already current on the player. + * @param {Object} [options] - The load options. + * @param {boolean} [options.keepBuffering] - True to keep a loading state that was handed to the load, used by an + * automatic continuation so the gap before the manifest and header probe shows a loading state. + * @returns {Promise} True when playback started, false when it was stopped or failed. + */ + async startLoadedDescriptorAsync(descriptor, options = {}) { + let engine = null; try { // The state follows the engine step by step, so a consumer can tell preparation apart from actual playback. - const engine = await this.ensureEngineAsync(); - await engine.loadAsync(descriptor); + engine = await this.ensureEngineAsync(); + await engine.loadAsync(descriptor, options); + if (this.state !== LuminaAudioPlayer.PlayerState.LOADING) { + // A stop during the load already paused the engine; a newer request owns the player state and must not be touched by this stale continuation. + if (this.state === LuminaAudioPlayer.PlayerState.IDLE) + await this.pauseEngineQuietlyAsync(engine); + return false; + } this.setState(LuminaAudioPlayer.PlayerState.READY); await engine.playAsync(); + if (this.state !== LuminaAudioPlayer.PlayerState.READY) { + if (this.state === LuminaAudioPlayer.PlayerState.IDLE) + await this.pauseEngineQuietlyAsync(engine); + return false; + } this.setState(LuminaAudioPlayer.PlayerState.PLAYING); this.renderTransportState(); } catch (error) { + // A load that a newer play request overtook, and a session that expired and is already navigating to the + // sign in page, are expected outcomes. They must not move the player to its error state, and they must not + // let this stale continuation set READY or PLAYING over the request that now owns the player. + const reason = error && error.details ? error.details.reason : null; + if (reason === LuminaAudioPlayer.PlayerErrorReason.LOAD_SUPERSEDED + || reason === LuminaAudioPlayer.PlayerErrorReason.SESSION_EXPIRED) + return false; // A failure before playback starts is a load failure; later failures are reported by the engine through its host. this.fail(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED); return false; @@ -697,6 +777,66 @@ return true; } + /** + * Pauses an engine after a load that the user stopped, without letting a pause failure disturb the player state. + * @param {Object} engine - The engine to pause. + * @returns {Promise} A promise that completes when the pause was attempted. + */ + async pauseEngineQuietlyAsync(engine) { + if (!engine || typeof engine.pauseAsync !== 'function') + return; + try { + await engine.pauseAsync(); + } catch (error) { + console.debug('Audio player: the engine could not be paused after a stopped load.', error); + } + } + + /** + * Requests the next queue entry as a new playback, with the player's own state machine owning the transition. It is + * the seam the engine uses for the end of a track when a gapless handoff could not be prepared. + * @param {string} [reason] - A developer facing reason for the request, for diagnostics. + * @returns {Promise} True when the player took ownership of the request, false when it declined it because the player is paused, stopped, or has no next entry. + */ + async requestNextTrackAsync(reason) { + // A paused or stopped player has made an explicit choice that the end of a track must not override. + if (this.state !== LuminaAudioPlayer.PlayerState.PLAYING) + return false; + const next = this.getNextDescriptor(); + if (!next) + return false; + // The capability gate is part of the player's play path, so an auto advance never starts a track the browser + // cannot decode. + const report = await this.capabilitiesReady; + if (this.state !== LuminaAudioPlayer.PlayerState.PLAYING) + return false; + if (report && !report.isSupported) { + this.fail(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'The browser is missing a capability the player requires.', + { missing: report.missing }), LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING); + return true; + } + const advanced = this.advanceQueueTo(next.entryId); + if (!advanced) + return false; + this.setState(LuminaAudioPlayer.PlayerState.LOADING); + this.renderTransportState(); + // The player owns the outcome from here, including a load that fails: returning true keeps the engine from + // reporting an end over a state the player has already set. The loading state is kept across the engine + // teardown, so the end gap shows that the next track is being prepared. + const hasStarted = await this.startLoadedDescriptorAsync(advanced, { keepBuffering: true }); + if (!hasStarted && this.state === LuminaAudioPlayer.PlayerState.IDLE + && this.engine && typeof this.engine.discardCurrentAsync === 'function') { + // A stop during the continuation load owns the outcome. The prepared track is released, so a stopped + // player does not keep a track loaded that was started only to continue a queue. + try { + await this.engine.discardCurrentAsync(); + } catch (error) { + console.debug('Audio player: the stopped continuation track could not be released.', error); + } + } + return true; + } + /** * Suspends playback, keeping the current position. * @returns {Promise} A promise that completes when the engine paused. @@ -781,9 +921,17 @@ * @returns {Promise} A promise that completes when the seek was requested. */ async seekAsync(seconds) { - // Without a descriptor there is no timeline to seek in. - if (!this.descriptor) + // Without a descriptor there is no timeline to seek in. A finished, failed or still loading track is not + // seekable either: its pipeline is either released or not yet the one the seek would address. Seeking a + // finished track is deliberately a no-op rather than a replay, and no resume is reported for it; a new play starts the next timeline. + if (!this.descriptor + || this.state === LuminaAudioPlayer.PlayerState.IDLE + || this.state === LuminaAudioPlayer.PlayerState.ENDED + || this.state === LuminaAudioPlayer.PlayerState.ERROR + || this.state === LuminaAudioPlayer.PlayerState.LOADING) { + this.clearSeekPending(); return; + } // A known duration bounds the target, while without one the position is only kept non negative, so a seek is never // silently snapped to zero just because the duration has not been reported yet. const request = Number(seconds); @@ -1004,7 +1152,84 @@ * @returns {Array} The ordered play descriptors. */ getQueue() { - return [...this.queue]; + return this.queueEntries.map((entry) => entry.descriptor); + } + + /** + * Creates the identity of a new queue entry. Every occurrence in the queue gets its own identity, so two entries + * that repeat the same track are never confused. + * @returns {string} The new entry Id. + */ + createQueueEntryId() { + this.entrySequence += 1; + return `queue-entry-${this.entrySequence}`; + } + + /** + * Gets the queue entry that follows the current one. + * @returns {{ entryId: string, descriptor: Object }|null} The identity and descriptor of the next entry, or null at the end of the queue. + */ + getNextDescriptor() { + if (this.currentIndex + 1 >= this.queueEntries.length) + return null; + const entry = this.queueEntries[this.currentIndex + 1]; + return { entryId: entry.entryId, descriptor: entry.descriptor }; + } + + /** + * Advances the queue to the entry with the given identity, without starting a new playback. It is the single commit + * of a queue transition: a gapless handoff passes the identity the engine already scheduled, and a non-gapless + * continuation passes the identity the player selected. The entry is found by identity rather than by position, so + * a linear advance, a wrap to the first entry and a reordered queue all share one path. + * @param {string} entryId - The identity of the queue entry to make current. + * @returns {Object|null} The descriptor the player advanced to, or null when the player is not playing or the entry is not part of the queue. + */ + advanceQueueTo(entryId) { + // A gapless boundary or a continuation only exists while the player is playing. In another state, for example + // while a new play request is loading, the queue cursor belongs to that request and must not be moved by the old timeline. + if (!entryId || this.state !== LuminaAudioPlayer.PlayerState.PLAYING) + return null; + const index = this.queueEntries.findIndex((entry) => entry.entryId === entryId); + // An entry that is no longer part of the queue is not a track this player can describe. + if (index < 0) + return null; + // Moving to the entry that is already current is not a transition. Applying its descriptor again would reset the + // playhead, the streamed fraction and the scrubbing state while the audio keeps playing. + if (index === this.currentIndex) + return this.queueEntries[index].descriptor; + // Navigation history, repeat and shuffle belong to the queue model of step 18. This commit only moves the cursor. + const previousIndex = this.currentIndex; + this.currentIndex = index; + return this.applyTrackDescriptor(this.queueEntries[index].descriptor, previousIndex); + } + + /** + * Applies a descriptor as the playing track without changing the queue cursor. It is the shared body of the + * validated queue advance and the scheduled-track adoption. + * @param {Object} descriptor - The descriptor to show as the playing track. + * @param {number|null} [previousIndex] - The queue position that was current before the cursor moved, when the + * commit knows it. It lets the queue update only the items whose current or played state changed. + * @returns {Object} The applied descriptor. + */ + applyTrackDescriptor(descriptor, previousIndex = null) { + this.descriptor = descriptor; + this.currentTime = 0; + this.downloadedFraction = 0; + this.scrubRatio = null; + this.endScrub(); + this.endVolumeAdjust(); + this.clearBuffering(); + // The duration of the next track is reported by its manifest as soon as the engine plays it, so the descriptor value is used here only until that report arrives. + this.duration = Number.isFinite(descriptor.durationInSeconds) && descriptor.durationInSeconds > 0 ? descriptor.durationInSeconds : 0; + this.renderDescriptor(); + this.renderProgress(); + if (Number.isInteger(previousIndex)) + this.updateQueueSelection(previousIndex); + else + this.renderQueue(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.DESCRIPTOR_CHANGED, descriptor); + this.events.emit(LuminaAudioPlayer.PlayerEvent.QUEUE_CHANGED, this.getQueue()); + return descriptor; } /** @@ -1300,6 +1525,17 @@ events: this.events, // A shallow frozen copy, so an engine or a test cannot mutate the controller state through the host. getPreferences: () => Object.freeze({ ...this.preferences }), + // The engine shares the player's endpoint configuration, JSON transport and capability detector, so an + // expired session redirect is followed by the same code that follows it for every other background + // request, and the engine never keeps a second copy of the configuration. + getConfiguration: () => this.getConfiguration(), + fetchJsonAsync: (url, signal, label, options) => this.fetchJsonAsync(url, signal, label, options), + getCapabilityDetector: () => this.capabilities, + // The queue cursor is read from the player for the gapless handoff, so the engine never re-implements the + // traversal and can never pick the wrong occurrence of a repeated track. + getNextDescriptor: () => this.getNextDescriptor(), + advanceQueueTo: (entryId) => this.advanceQueueTo(entryId), + requestNextTrackAsync: (reason) => this.requestNextTrackAsync(reason), reportTime: (currentTime, duration) => this.handleEngineTime(currentTime, duration), reportDuration: (duration) => this.handleEngineDuration(duration), reportProgress: (fraction) => this.handleEngineProgress(fraction), @@ -1410,6 +1646,11 @@ * Handles the end of the current track reported by the engine. */ handleEngineEnded() { + // A player that the user stopped, that already failed, or that is preparing a new track is not moved to ended by a late end report of the previous timeline. + if (this.state === LuminaAudioPlayer.PlayerState.IDLE + || this.state === LuminaAudioPlayer.PlayerState.ERROR + || this.state === LuminaAudioPlayer.PlayerState.LOADING) + return; this.setState(LuminaAudioPlayer.PlayerState.ENDED); this.renderTransportState(); this.events.emit(LuminaAudioPlayer.PlayerEvent.ENDED); @@ -1499,18 +1740,52 @@ * An expired session is answered by the server with a redirect to the login page, so the redirect is followed * here, exactly like the application API helper does it, instead of being mistaken for a failed request. * @param {string} url - The endpoint URL. Nothing is requested when it is empty. + * @param {AbortSignal} [signal] - An optional signal that cancels the request, used by an engine's prefetch. + * @param {string} [label] - The description used in the failure log, so a caller such as the engine reports its own request rather than a preferences request. + * @param {Object} [options] - The request options. + * @param {string} [options.redirect='follow'] - 'manual' to keep the browser from following a redirect before its target is validated. * @returns {Promise<*|null|undefined|Object>} The unwrapped data, null when the endpoint answered without data, undefined when the request failed, or the REDIRECTED marker when the session expired and the page is navigating away. */ - async fetchJsonAsync(url) { + async fetchJsonAsync(url, signal, label = 'a preferences request', options = {}) { if (!url) return null; + const requestUrl = resolveConfiguredUrl(url); + if (!requestUrl) { + console.error(`Audio player: ${label} has an endpoint that is not on this origin.`); + return undefined; + } try { - const response = await fetch(url, { + const request = { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' + }, + signal: signal + }; + if (options.redirect === 'manual') + request.redirect = 'manual'; + const response = await fetch(requestUrl, request); + if (options.redirect === 'manual' && isRedirectResponse(response)) { + // The browser did not follow the redirect, so the request cannot reach a target that was not validated. + // When the environment exposes the target, it goes through the same origin policy as a followed + // redirect; otherwise the request is reported as a session redirect without requesting the unknown target. + let location = null; + try { + location = response.headers && typeof response.headers.get === 'function' + ? response.headers.get('location') + : null; + } catch (error) { + console.debug('Audio player: the redirect target of the request could not be read.', error); } - }); + if (location) { + try { + navigateToRedirect(new URL(location, requestUrl).href); + } catch (error) { + console.debug('Audio player: the redirect target of the request could not be resolved.', error); + } + } + return REDIRECTED; + } if (response.redirected) { // The session expired and the server answered with the login page; follow it, and report the redirect, not a failure. navigateToRedirect(response.url); @@ -1521,7 +1796,11 @@ const payload = await response.json(); return payload && payload.success === true ? payload.data : null; } catch (error) { - console.error('Audio player: a preferences request failed.', error); + // A request that a cancelled prefetch, a superseded load or a timeout aborted is an expected stop, not a + // failed request, so it is reported with the same undefined result but without a console error. + if (LuminaAudioPlayer.isAbortError(error)) + return undefined; + console.error(`Audio player: ${label} failed.`, error); return undefined; } } @@ -1538,6 +1817,11 @@ async postJsonAsync(url, data, options = {}) { if (!url) return null; + const requestUrl = resolveConfiguredUrl(url); + if (!requestUrl) { + console.error('Audio player: the playback state endpoint is not on this origin.'); + return undefined; + } try { const headers = { 'Content-Type': 'application/json', @@ -1549,7 +1833,7 @@ const token = document.querySelector('input[name="__RequestVerificationToken"]'); if (token && token.value) headers['RequestVerificationToken'] = token.value; - const response = await fetch(url, { + const response = await fetch(requestUrl, { method: 'POST', headers: headers, body: JSON.stringify(data ?? {}), @@ -2271,12 +2555,48 @@ if (!this.dom.queue) return; this.dom.queue.innerHTML = ''; - const items = this.queue.length > 1 ? this.queue : []; + const items = this.queueEntries.length > 1 ? this.queueEntries : []; for (let index = 0; index < items.length; index++) { - const entry = this.renderQueueItem(items[index], index, items.length); + const entry = this.renderQueueItem(items[index].descriptor, index, items.length); if (entry) this.dom.queue.appendChild(entry); } + this.renderedQueueOrder = items.map((entry) => entry.entryId); + } + + /** + * Updates only the queue items whose current or played state changed after the cursor moved, so a gapless handoff + * of a large play context does not rebuild the whole list at the transition. It falls back to a full render when + * the DOM does not match the queue, for example before the first render or in a host that cannot replace a child. + * @param {number} previousIndex - The zero based queue position that was current before the advance. + */ + updateQueueSelection(previousIndex) { + if (!this.dom.queue) + return; + const total = this.queueEntries.length; + const children = this.dom.queue.children; + // A changed order means the rendered child at an index no longer describes the entry at that index, so the + // list is rebuilt instead of updating the wrong items. The same fallback covers a list that was never rendered. + const hasSameOrder = this.renderedQueueOrder.length === total + && this.renderedQueueOrder.every((entryId, index) => entryId === this.queueEntries[index].entryId); + if (total <= 1 || !children || children.length !== total || !hasSameOrder + || typeof this.dom.queue.replaceChild !== 'function') { + this.renderQueue(); + return; + } + const from = Math.min(previousIndex, this.currentIndex); + const to = Math.max(previousIndex, this.currentIndex); + if (!Number.isInteger(from) || from < 0 || to >= total) { + this.renderQueue(); + return; + } + // isPlayed flips for every position between the old and the new cursor, inclusive, and isCurrent flips at + // both ends, so that inclusive range is exactly the set of items whose state changed. + for (let index = from; index <= to; index++) { + const item = this.renderQueueItem(this.queueEntries[index].descriptor, index, total); + if (item) + this.dom.queue.replaceChild(item, children[index]); + } } /** From 6991640710c5b058fc3dc03652aa77f0c51de674 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 17 Oct 2026 20:51:47 +0300 Subject: [PATCH 20/77] Standardizes cancellation token parameter documentation --- src/Lumina.Application/Common/CQRS/ICommandHandler.cs | 2 +- src/Lumina.Application/Common/CQRS/IQueryHandler.cs | 2 +- .../Common/Telemetry/TelemetryCommandHandlerDecorator.cs | 2 +- .../Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs | 2 +- .../Common/Telemetry/TelemetryQueryHandlerDecorator.cs | 2 +- src/Lumina.Domain/Common/Events/IDomainEventHandler.cs | 2 +- src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs | 2 +- .../Common/DomainEvents/DomainEventPublisher.cs | 4 ++-- src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs | 2 +- .../Core/Scheduling/Execution/IScheduledJobCycleTicker.cs | 2 +- .../Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs | 2 +- .../Core/Plugins/IPluginSettingsStore.cs | 2 +- .../Common/HealthChecks/DatabaseHealthCheck.cs | 2 +- .../Common/HealthChecks/ApiReachabilityHealthCheck.cs | 2 +- .../Common/Setup/StubHttpMessageHandler.cs | 2 +- 15 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Lumina.Application/Common/CQRS/ICommandHandler.cs b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs index 19e0018d..04842335 100644 --- a/src/Lumina.Application/Common/CQRS/ICommandHandler.cs +++ b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs @@ -17,7 +17,7 @@ public interface ICommandHandler where TCommand : ICommand /// Handles the specified command and returns a result. /// /// The command to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the result of the command execution. Task HandleAsync(TCommand command, CancellationToken cancellationToken = default); } diff --git a/src/Lumina.Application/Common/CQRS/IQueryHandler.cs b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs index 8b5fadde..9f33322e 100644 --- a/src/Lumina.Application/Common/CQRS/IQueryHandler.cs +++ b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs @@ -17,7 +17,7 @@ public interface IQueryHandler where TQuery : IQuery /// Handles the specified query and returns a result. /// /// The query to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the result of the query execution. Task HandleAsync(TQuery query, CancellationToken cancellationToken = default); } diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs index 29123465..d71c82a1 100644 --- a/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs +++ b/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs @@ -36,7 +36,7 @@ public class TelemetryCommandHandlerDecorator : ICommandHandl /// Handles the specified command, emitting telemetry around the execution of the wrapped handler. /// /// The command to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the result of the command execution. public async Task HandleAsync(TCommand command, CancellationToken cancellationToken) { diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs index 02e96c1f..99171558 100644 --- a/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs +++ b/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs @@ -35,7 +35,7 @@ public class TelemetryDomainEventHandlerDecorator : IDomainEventHa /// Handles the specified domain event, emitting telemetry around the execution of the wrapped handler. /// /// The domain event to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. public async ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken) { diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs index f5529bb6..5712d6f2 100644 --- a/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs +++ b/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs @@ -36,7 +36,7 @@ public class TelemetryQueryHandlerDecorator : IQueryHandler /// The query to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the result of the query execution. public async Task HandleAsync(TQuery query, CancellationToken cancellationToken) { diff --git a/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs b/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs index 9209e99d..14354c5d 100644 --- a/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs +++ b/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs @@ -15,7 +15,7 @@ public interface IDomainEventHandler where TDomainEvent : IDomainE /// Handles the specified . /// /// The domain event to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken); } diff --git a/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs b/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs index df8b69fa..1529fd61 100644 --- a/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs +++ b/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs @@ -14,7 +14,7 @@ public interface IDomainEventPublisher /// Publishes the specified to all its registered handlers, in registration order. /// /// The domain event to publish. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default); } diff --git a/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs b/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs index 3c472e9b..15b3cf34 100644 --- a/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs +++ b/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs @@ -32,7 +32,7 @@ public class DomainEventPublisher : IDomainEventPublisher /// Publishes the specified to all its registered handlers, in registration order. /// /// The domain event to publish. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. public ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default) { @@ -54,7 +54,7 @@ public class DomainEventPublisher : IDomainEventPublisher /// The type of the domain event being dispatched. /// The domain event to dispatch. /// The provider used to resolve the domain event handlers. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. private static async Task DispatchAsync(IDomainEvent domainEvent, IServiceProvider serviceProvider, CancellationToken cancellationToken) where TDomainEvent : IDomainEvent diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs index 75aa4ff8..b4413224 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs @@ -37,7 +37,7 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore /// Gets the settings persisted by the host for the plugin identified by . /// /// The unique identifier of the plugin whose settings are read. - /// Cancellation token that can be used to cancel the operation. + /// Cancellation token that can be used to stop the execution. /// The persisted settings keyed by setting key, or when no settings were persisted for the plugin. public async Task?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken) { diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs index b25a91a3..5278f302 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs @@ -26,7 +26,7 @@ internal interface IScheduledJobCycleTicker : IDisposable /// /// Waits until the next tick of the ticker, or until the ticker is disposed or is cancelled. /// - /// Cancellation token that can be used to stop the wait. + /// Cancellation token that can be used to stop the execution. /// when a tick occurred; when the ticker was disposed before the next tick. ValueTask WaitForNextTickAsync(CancellationToken cancellationToken); } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs index b7c788ff..7ea258a1 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs @@ -36,7 +36,7 @@ internal sealed class PeriodicScheduledJobCycleTicker : IScheduledJobCycleTicker /// /// Waits until the next tick of the ticker, or until the ticker is disposed or is cancelled. /// - /// Cancellation token that can be used to stop the wait. + /// Cancellation token that can be used to stop the execution. /// when a tick occurred; when the ticker was disposed before the next tick. public ValueTask WaitForNextTickAsync(CancellationToken cancellationToken) { diff --git a/src/Lumina.Plugins.Contracts/Core/Plugins/IPluginSettingsStore.cs b/src/Lumina.Plugins.Contracts/Core/Plugins/IPluginSettingsStore.cs index e3b6dac2..dc6e9213 100644 --- a/src/Lumina.Plugins.Contracts/Core/Plugins/IPluginSettingsStore.cs +++ b/src/Lumina.Plugins.Contracts/Core/Plugins/IPluginSettingsStore.cs @@ -16,7 +16,7 @@ public interface IPluginSettingsStore /// Gets the settings persisted by the host for the plugin identified by . /// /// The unique identifier of the plugin whose settings are read. - /// Cancellation token that can be used to cancel the operation. + /// Cancellation token that can be used to stop the execution. /// The persisted settings keyed by setting key, or when no settings were persisted for the plugin. Task?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs b/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs index 9ff53c7d..8f2c1a6a 100644 --- a/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs +++ b/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs @@ -29,7 +29,7 @@ public class DatabaseHealthCheck : IHealthCheck /// Checks whether the database can be reached. /// /// The health check context. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the health check result. public virtual async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken) { diff --git a/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs b/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs index 496e1493..a9d8ca7a 100644 --- a/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs +++ b/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs @@ -33,7 +33,7 @@ public class ApiReachabilityHealthCheck : IHealthCheck /// Checks whether the remote API is reachable by probing its readiness endpoint. /// /// The health check context. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the health check result. public virtual async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken) { diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs index fc701d23..564e0679 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs @@ -43,7 +43,7 @@ internal sealed class StubHttpMessageHandler : HttpMessageHandler /// Returns a response with the configured status code and body. /// /// The request, which is ignored. - /// Cancellation token that can be used to cancel the operation. + /// Cancellation token that can be used to stop the execution. /// The configured response. protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { From 4e13b23f16819bd211ff7347ed34695c362ee648 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 17 Oct 2026 20:52:08 +0300 Subject: [PATCH 21/77] Adds normalized audio playback pipeline --- docs/manual/installation/index.md | 20 +- docs/manual/using-lumina/index.md | 2 +- .../architecture-decision-record-0016.md | 2 +- .../Playback/NormalizedTrackDto.cs | 34 + .../Playback/NormalizedTrackRequestDto.cs | 46 + .../Playback/NormalizedTrackSegmentDto.cs | 20 + .../Playback/ITrackNormalizationService.cs | 62 + .../Playback/PlaybackStreamingQuality.cs | 11 +- .../Common/Errors/Errors.Playback.cs | 9 + .../Common/Caching/TranscodingCachePaths.cs | 275 ++++ .../InfrastructureLayerServices.cs | 12 + .../SharedConfiguration.cs | 5 + .../Common/Errors/Errors.Configuration.cs | 13 + .../Configuration/TranscodingSettingsDto.cs | 45 + .../Playback/NormalizedAudioFormatDto.cs | 24 + .../Playback/NormalizedTrackIndexDto.cs | 37 + .../NormalizedTrackSegmentIndexDto.cs | 25 + .../Playback/TranscodingCacheEntryDto.cs | 21 + .../TranscodingSettingsDtoValidator.cs | 291 ++++ .../Playback/PlaybackFormatCatalog.cs | 102 ++ .../Playback/PlaybackFormatService.cs | 21 +- .../Playback/TrackNormalizationService.cs | 1389 +++++++++++++++++ .../Playback/TranscodingCacheCoordinator.cs | 591 +++++++ .../Playback/TranscodingCacheLeaseStream.cs | 220 +++ .../Playback/TranscodingCacheReaderLease.cs | 39 + .../Playback/TranscodingCacheReservation.cs | 84 + .../Playback/TranscodingOutputSizeTracker.cs | 125 ++ .../Playback/TranscodingStartupInitializer.cs | 228 +++ .../Playback/TranscodingToolchainStatus.cs | 73 + .../Lumina.Infrastructure.csproj | 1 + .../appsettings.shared.json | 8 + src/Lumina.Presentation.Api/Dockerfile | 8 +- src/Lumina.Presentation.Api/Program.cs | 2 +- .../AudioLibrary/PlaybackStreamingQuality.cs | 11 +- .../wwwroot/js/audio-player/audio-player.js | 2 +- 35 files changed, 3817 insertions(+), 41 deletions(-) create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs create mode 100644 src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs create mode 100644 src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs create mode 100644 src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs create mode 100644 src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs create mode 100644 src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs create mode 100644 src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs create mode 100644 src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs diff --git a/docs/manual/installation/index.md b/docs/manual/installation/index.md index dc41f332..4054ee27 100644 --- a/docs/manual/installation/index.md +++ b/docs/manual/installation/index.md @@ -21,16 +21,17 @@ Lumina ships as two applications that talk to each other over the network: the * > **Not production ready yet.** Lumina is pre-alpha software. Updates are one way and can lose Lumina's data, so read [Updating](#updating) before you install or upgrade. -There are **two ways to install Lumina**. Pick one: +There are **two ways to run Lumina**. Pick one: - **[Option A: run with Docker Compose](#option-a-run-with-docker-compose)**, the recommended route, where a single command brings up the whole system. -- **[Option B: build and run manually](#option-b-build-and-run-manually)**, if you would rather run the applications directly, without containers. +- **[Option B: run the applications directly](#option-b-run-the-applications-directly)**, whether you install a release package or build from source, if you would rather run them without containers. Everything from Configuration onward applies to whichever route you chose. ## Before you start -- **Docker**, if you want the container route, or the **.NET 10 SDK** if you want to build and run from source. +- **Docker**, if you want the container route. For a non-container install, you need the Lumina application files, from a release package or installer, or from your own build, plus the **.NET 10 runtime** unless that package is self-contained. The **.NET 10 SDK** is only needed if you build from source. +- **ffmpeg**, for any non-container install, however you obtained the application files. The API server uses it to remux or transcode audio that the browser cannot play as stored. The Docker API container image already includes it. - By default the **web client listens on port `5012`** and the **API on port `5214`**. You can change either, as long as the two agree on where the API is (see [Configuration](#configuration)). - For anything reachable beyond your own machine, put a **reverse proxy** in front to terminate TLS and forward to the web client. - Lumina needs **no external database server**. It keeps its data in a local SQLite file that is created automatically. @@ -77,15 +78,15 @@ The development configuration embeds throwaway keys so the container route works Set them as environment variables on the `lumina-api` and `lumina-web` services in your own compose file or orchestration. -## Option B: build and run manually +## Option B: run the applications directly -With the .NET 10 SDK installed, build the solution from the `src` directory: +Use a release package or installer when one is available, or, with the .NET 10 SDK installed, build the solution from the `src` directory: ```bash dotnet build Lumina.sln ``` -Run the API and the web client. In development, their addresses come from each project's `launchSettings.json` (`http://localhost:5214` and `http://localhost:5012`). When you run a published build directly on a host, set the addresses yourself, either with `ASPNETCORE_URLS` or with `ASPNETCORE_HTTP_PORTS`: +Run the API and the web client from the installed release package or from the published build. In development, their addresses come from each project's `launchSettings.json` (`http://localhost:5214` and `http://localhost:5012`). When you run a published build directly on a host, set the addresses yourself, either with `ASPNETCORE_URLS` or with `ASPNETCORE_HTTP_PORTS`: ```bash ASPNETCORE_HTTP_PORTS=5012 dotnet Lumina.Presentation.Web.dll @@ -93,6 +94,8 @@ ASPNETCORE_HTTP_PORTS=5012 dotnet Lumina.Presentation.Web.dll The API creates its SQLite database (`Lumina.db`) next to its own binary and applies any pending migrations at startup, so the first launch sets up the schema on its own. +The API server needs **ffmpeg** on its `PATH` to normalize audio that a player cannot play as stored. Install it with your platform's package manager, or point `TranscodingSettings:FfmpegPath` at the binary if it is somewhere else. + ## Configuration Each application reads its own `appsettings.json` and an optional environment specific `appsettings.development.json`, and environment variables override both. The API also loads the `appsettings.shared.json` file (and its development variant), which holds the server side settings that are not specific to a single layer, such as the media, plugins and theme options. @@ -112,10 +115,15 @@ The settings that matter most when installing: | `PluginsSettings:Directory` | API server | Folder holding installed plugin assemblies, `plugins` by default. | | `ThemeEngine:StoragePath`, `ThemeEngine:BundledThemesPath`, `ThemeEngine:DefaultThemeId` | API server | Where installed and bundled themes live, and which theme is activated by default. | | `ThemeEngine:MaxArchiveBytes`, `MaxExpandedBytes`, `MaxSingleFileBytes`, `MaxEntries` | API server | Limits enforced on uploaded theme packs. | +| `TranscodingSettings:FfmpegPath`, `MaxConcurrentJobs`, `MaxCacheBytes`, `JobTimeoutSeconds`, `EvictionGraceSeconds`, `CacheDirectory` | API server | Where the ffmpeg binary is, how many audio normalization jobs may run at once, the maximum size of the normalized audio cache in bytes, how long a single job may take in seconds, how long a freshly produced or served cache entry is protected from eviction, and where the cache is stored. When `CacheDirectory` is absent, a private directory under the API account's temporary directory is used. | | `Telemetry:Enabled`, `Telemetry:Otlp:Endpoint`, `Telemetry:TraceSampleRatio`, `Telemetry:ConsoleExporterEnabled` | API server and web client | Telemetry behavior. The OTLP endpoint also falls back to the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable. Again, while telemetry is enabled as a feature, nothing is sent anywhere. | The `LOG_PATH` environment variable selects where the rolling log files are written. +The normalized audio cache must not be placed inside `MediaSettings:RootDirectory`, because that directory is served at the `/media` route, and it must not contain that directory either, because cleaning the cache would remove the media. The startup configuration also rejects a cache directory that is a filesystem root, the application directory or one of its parents, or that overlaps the logs or plugins directories. The default uses a private directory under the API account's temporary directory and avoids all of these. The cache holds transcoded or remuxed audio only while it is useful: at API startup only the entries the cache itself owns are removed, and a directory is cleaned only when it carries Lumina's cache marker file (`.lumina-transcoding-cache`) or is empty, so a directory that belongs to something else is left untouched. Its total footprint is capped by `TranscodingSettings:MaxCacheBytes`, but an entry that is still being read, or that was just produced when the cache was already at the limit, is kept until it can be removed, so the cache can exceed the cap temporarily. The cache is not part of the media library. + +The default cache directory is scoped to the API account, but the coordinator, the running jobs and the startup cleanup are per process. Run a single API process per account and host, or configure a distinct `CacheDirectory` for each instance. On a multi-user Unix host the directory is created with private permissions, and a pre-existing directory owned by another account is treated as unavailable rather than reused or deleted. + ### Keeping the two applications in step The web client and the API must agree on two addresses, and getting them wrong is the usual cause of a client that loads but never updates live: diff --git a/docs/manual/using-lumina/index.md b/docs/manual/using-lumina/index.md index a5496021..21555490 100644 --- a/docs/manual/using-lumina/index.md +++ b/docs/manual/using-lumina/index.md @@ -87,6 +87,6 @@ Wherever Lumina needs a folder or a file from the server, it opens the file syst The tools section holds your settings and the language picker. -Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. A final group of options shapes playback: whether the player keeps downloading while it is paused, whether it continues automatically at the end of an album or artist, whether consecutive tracks play without a gap, how ReplayGain normalizes loudness, and the quality cap used when the server has to normalize a track. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md). +Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. A final group of options shapes playback: whether the player keeps downloading while it is paused, whether it continues automatically at the end of an album or artist, whether consecutive tracks play without a gap, how ReplayGain normalizes loudness, and the quality cap used when the server has to normalize a track. That cap applies only when the server re-encodes a track into a lossy format; a remux only repackages the stored audio, and a lossless delivery is not reduced. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md). The **language** picker switches the interface between the languages Lumina ships with, and remembers your choice. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md index d7a638a7..41252610 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md @@ -38,7 +38,7 @@ GET /api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{tr - A pair must name both a container and a codec, with neither empty (for example `flac`, `a/b/c` and `a//b` are ignored). - At most 32 pairs are read from one request, so the parsing work stays bounded regardless of the input length. - When the parameter is absent, empty, or lists no valid pair, the server applies the default capabilities of the bundled player, so a request that advertises nothing still gets a playable decision: - `mp3/mp3`, `flac/flac`, `ogg/opus`, `ogg/vorbis`, `wav/pcm`, `aac/aac`. The default set is the bundled player's demuxer set (MP3, AAC/ADTS, FLAC, OGG and WAV, from work order 14), so it deliberately contains no `mp4/aac` pair: a track stored in MP4 is remuxed to raw AAC for a request that advertises nothing, rather than being marked direct play for a container the bundled player cannot demux. + `mp3/mp3`, `flac/flac`, `ogg/opus`, `ogg/vorbis`, `wav/pcm`, `aac/aac`. The default set is the bundled player's demuxer set (MP3, AAC/ADTS, FLAC, OGG and WAV), so it deliberately contains no `mp4/aac` pair: a track stored in MP4 is remuxed to raw AAC for a request that advertises nothing, rather than being marked direct play for a container the bundled player cannot demux. - The convention is a query parameter rather than a request header, so that it is part of the request's own contract, is trivially testable, and is forwarded by the web app's manifest proxy without depending on header forwarding. ### Delivery shape diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs new file mode 100644 index 00000000..16efa3e8 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the normalized audio of a track, produced and cached as a sequence of fixed duration segments. +/// +/// The Id of the track whose audio the cached entry holds, so the caller can verify that the entry is the one it authorized. +/// The opaque identifier of the cached entry that holds the normalized audio. +/// The way the audio is delivered, which is a remux or a transcode. +/// The container of the delivered audio. +/// The codec of the delivered audio. +/// The duration of each segment of the delivered audio, in seconds. +/// +/// The duration of the produced and cached audio, in seconds, rounded up to the next second. It is the produced end rather than the probed duration, so +/// it always covers every produced segment. +/// +/// The segments that make up the delivered audio, in playback order. +[DebuggerDisplay("TrackId: {TrackId} CacheId: {CacheId} Container: {Container} Codec: {Codec}")] +public sealed record NormalizedTrackDto( + Guid TrackId, + string CacheId, + PlaybackDeliveryMode Mode, + string Container, + string Codec, + int SegmentDurationSeconds, + int DurationInSeconds, + IReadOnlyList Segments +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs new file mode 100644 index 00000000..4e28eb18 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the request to produce the normalized audio of a track, as the delivery decision of a playback manifest describes it. +/// +/// The Id of the track whose audio is normalized. It binds the produced cache entry to the track the caller authorized. +/// The file system path of the stored audio file of the track. +/// +/// The content locations the source path is allowed to be inside. The service validates the path against them and re-checks it after opening, so a +/// caller that forgets to enforce containment cannot hand an arbitrary path to the transcoder. +/// +/// The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer. Optional. +/// The way the audio is delivered, which is a remux or a transcode. +/// The container of the delivered audio, as chosen by the delivery decision. +/// The codec of the delivered audio, as chosen by the delivery decision. +/// The duration of each segment of the delivered audio, in seconds. +/// The duration of the audio of the track, in seconds. +/// The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec. Optional. +/// The sample rate of the stored audio of the track, in Hz, used to estimate the size of a lossless delivery. +/// The number of audio channels of the track, used to estimate the size of a lossless delivery. +/// The bit depth of the stored audio of the track, if applicable, used to estimate the size of a lossless delivery. +/// The quality cap applied to the delivered audio when it has to be re-encoded. +[DebuggerDisplay("TrackId: {TrackId} Mode: {Mode} Container: {Container} Codec: {Codec}")] +public sealed record NormalizedTrackRequestDto( + Guid TrackId, + string SourcePath, + IReadOnlyList AllowedRoots, + string? SourceContainer, + PlaybackDeliveryMode Mode, + string Container, + string Codec, + int SegmentDurationSeconds, + int DurationInSeconds, + int? Bitrate, + int SampleRate, + int Channels, + int? BitDepth, + PlaybackStreamingQuality Quality +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs new file mode 100644 index 00000000..00c3cb1a --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for a single fixed duration segment of the normalized audio of a track. +/// +/// The zero based position of the segment in the delivered audio. +/// The time, in seconds from the start of the track, at which the segment starts. +/// The duration of the segment, in seconds. +/// The length of the segment, in bytes. +[DebuggerDisplay("Index: {Index} StartSeconds: {StartSeconds} DurationSeconds: {DurationSeconds}")] +public sealed record NormalizedTrackSegmentDto( + int Index, + decimal StartSeconds, + decimal DurationSeconds, + long Length +); diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs new file mode 100644 index 00000000..45c2f418 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Primitives; +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Interface for the service that produces, caches and serves the normalized audio of a track, when the player cannot play the stored audio directly. +/// +/// +/// The caller is responsible for authorizing the request. The service re-validates the source path against the allowed roots carried by the request and +/// re-checks it after opening, as defense in depth, so a caller that forgets containment cannot hand an arbitrary path to the transcoder. The service +/// itself only handles the media pipeline: it never reads or writes a database row, and it never emits a domain event. Every entry is bound to the track +/// it was produced for, so a cache handle can never be used to read the audio of another track. +/// A production is atomic: the cache entry is published only after ffmpeg has finished the whole track, so the first request waits for a complete +/// production. Streaming in this contract means serving the produced segments from the cache without buffering them into memory, not publishing a partial +/// track. Incremental publication of segment 0 while the rest is produced would be a different contract. Admission is bounded: when every normalization job +/// slot is in use, a request for an entry that is not cached yet is reported as unavailable instead of being queued behind the running jobs. A production +/// that was admitted outlives the request that started it, so repeated aborts converge to a cached entry. A production that needs a toolchain the startup +/// probe found unusable reports as well, while an entry that is already +/// cached is still served. The playback stream surface that exposes the produced segments is the intended consumer of this contract; no API request path +/// calls it yet. +/// +public interface ITrackNormalizationService +{ + /// + /// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet. + /// + /// The track, the delivery decision, the source file and the quality cap the normalized audio is produced with. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the cached normalized audio of the track, or an error message. + /// + /// + /// Thrown when is canceled while the caller is waiting. The production continues in the background, so this is a + /// disconnect signal and must not be treated as a production failure. + /// + Task> GetOrCreateNormalizedTrackAsync(NormalizedTrackRequestDto request, CancellationToken cancellationToken); + + /// + /// Opens a read stream over a single segment of a cached normalized track, after verifying that the entry belongs to the provided track. + /// + /// + /// A missing or evicted cache entry, a segment that is no longer present, an entry that cannot be read, or a value that is not a well formed handle is + /// reported with . That is the caller's signal to request the + /// playback manifest again, or to trigger a new production, instead of treating the result as a broken transcode. A genuine production failure keeps + /// its own error. A service that has already been disposed reports + /// . + /// + /// The opaque identifier of the cached entry that holds the normalized audio. + /// The Id of the track the caller authorized and whose segment is opened. + /// The zero based position of the segment in the delivered audio. + /// + /// An containing either a read stream over the segment, or an error message. The caller owns the returned stream. + /// + Result OpenNormalizedSegment(string cacheId, Guid trackId, int segmentIndex); +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs index 6350f42b..0e3ecd72 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs @@ -4,27 +4,28 @@ namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; /// Enumeration for the quality cap applied to the audio the server normalizes (remuxes or transcodes) for a user. /// /// -/// The caps apply only to audio the server has to change; a track that is played directly is always delivered as it was stored. +/// The caps apply only to audio the server re-encodes into a lossy codec. A track that is played directly is delivered as it was stored, a remux only +/// repackages the stored codec without re-encoding it, and a lossless transcode is not reduced, so none of those deliveries is capped. /// public enum PlaybackStreamingQuality { /// - /// The server chooses the quality, with no explicit cap. + /// The server chooses the quality, with a default cap of 192 kbps for a lossy re-encode. /// Auto, /// - /// Normalized audio is capped at 96 kbps. + /// A lossy normalized audio stream is capped at 96 kbps. /// Low, /// - /// Normalized audio is capped at 160 kbps. + /// A lossy normalized audio stream is capped at 160 kbps. /// Medium, /// - /// Normalized audio is capped at 320 kbps. + /// A lossy normalized audio stream is capped at 320 kbps. /// High, } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs index 8e4662fc..16292916 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs @@ -12,5 +12,14 @@ public static partial class Errors public static class Playback { public static Error NoSupportedPlaybackFormat => Error.Forbidden(description: nameof(NoSupportedPlaybackFormat)); + public static Error PlaybackFormatNotImplemented => Error.Internal(description: nameof(PlaybackFormatNotImplemented)); + public static Error NormalizedTrackCacheEntryNotFound => Error.NotFound(description: nameof(NormalizedTrackCacheEntryNotFound)); + public static Error NormalizationFailed => Error.Failure(description: nameof(NormalizationFailed)); + public static Error NormalizationCacheLimitExceeded => Error.Failure(description: nameof(NormalizationCacheLimitExceeded)); + public static Error NormalizationTimedOut => Error.Timeout(description: nameof(NormalizationTimedOut)); + public static Error NormalizationUnavailable => Error.ResourceUnavailable(description: nameof(NormalizationUnavailable)); + public static Error NormalizationIsNotRequiredForDirectPlay => Error.InvalidOperation(description: nameof(NormalizationIsNotRequiredForDirectPlay)); + public static Error SegmentDurationMustBePositive => Error.Validation(description: nameof(SegmentDurationMustBePositive)); + public static Error TrackDurationMustBePositive => Error.Validation(description: nameof(TrackDurationMustBePositive)); } } diff --git a/src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs b/src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs new file mode 100644 index 00000000..29877a13 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs @@ -0,0 +1,275 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Common.Caching; + +/// +/// Provides the location, the ownership marker and the permissions of the temporary directory into which the audio normalization pipeline writes the normalized audio. +/// +internal static class TranscodingCachePaths +{ + /// + /// The name of the temporary directory that is used when no cache directory is configured. + /// + public const string DEFAULT_DIRECTORY_NAME = "lumina-transcoding-cache"; + + /// + /// The name of the file that marks a directory as a normalized audio cache created and owned by this application. + /// + public const string CACHE_MARKER_FILE_NAME = ".lumina-transcoding-cache"; + + /// + /// The prefix of the temporary directories of the normalization jobs that have not been published to the cache yet. + /// + public const string TEMPORARY_DIRECTORY_PREFIX = "tmp-"; + + /// + /// The prefix of the tombstone directories that were detached from the cache and are waiting to be deleted. + /// + public const string DELETION_DIRECTORY_PREFIX = "del-"; + + private const int CACHE_ID_HEX_LENGTH = 64; + private const UnixFileMode PRIVATE_DIRECTORY_MODE = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + private const UnixFileMode PRIVATE_FILE_MODE = UnixFileMode.UserRead | UnixFileMode.UserWrite; + private const int USER_SUFFIX_LENGTH = 16; + + /// + /// Gets the absolute path of the directory into which the audio normalization pipeline writes the normalized audio of the tracks. + /// + /// + /// The configured cache directory, relative to the application base directory when not rooted, or to use a private directory + /// under the system temporary directory. The default directory is scoped to the operating system account that runs the process. + /// + /// The absolute path of the transcoding cache directory. + public static string GetRootDirectory(string? configuredDirectory) + { + if (!string.IsNullOrWhiteSpace(configuredDirectory)) + { + string trimmedDirectory = configuredDirectory.Trim(); + string absoluteDirectory = Path.IsPathRooted(trimmedDirectory) + ? trimmedDirectory + : Path.Combine(AppContext.BaseDirectory, trimmedDirectory); + return Path.GetFullPath(absoluteDirectory); + } + return Path.Combine(Path.GetTempPath(), DEFAULT_DIRECTORY_NAME + "-" + GetUserSuffix()); + } + + /// + /// Checks whether a directory carries the marker of a normalized audio cache created by this application. + /// + /// The absolute path of the directory to check. + /// when the directory carries the cache marker, otherwise . + public static bool HasCacheMarker(string directoryPath) + { + return File.Exists(Path.Combine(directoryPath, CACHE_MARKER_FILE_NAME)); + } + + /// + /// Writes the marker that records the directory as a normalized audio cache created and owned by this application. + /// + /// The absolute path of the directory to mark. + /// + /// The marker is an ownership signal, not a lock: it is written once, and its presence is what allows a later startup to clean the directory. A directory + /// without the marker is never cleaned, so a cache directory that was configured by mistake can never lose data that does not belong to this application. + /// + public static void WriteCacheMarker(string directoryPath) + { + if (HasCacheMarker(directoryPath)) + return; + File.WriteAllText(Path.Combine(directoryPath, CACHE_MARKER_FILE_NAME), "Lumina normalized audio cache." + Environment.NewLine); + } + + /// + /// Checks whether an entry name belongs to the namespace of the normalized audio cache. + /// + /// The name of the entry, without its directory. + /// when the name is a cache identifier, a temporary directory name or a deletion tombstone name, otherwise . + public static bool IsCacheEntryName(string entryName) + { + if (string.IsNullOrEmpty(entryName)) + return false; + return IsValidCacheId(entryName) || + entryName.StartsWith(TEMPORARY_DIRECTORY_PREFIX, StringComparison.Ordinal) || + entryName.StartsWith(DELETION_DIRECTORY_PREFIX, StringComparison.Ordinal); + } + + /// + /// Checks whether a value is a well formed opaque cache identifier. + /// + /// The value to check. + /// when the value is a well formed cache identifier, otherwise . + public static bool IsValidCacheId(string cacheId) + { + if (string.IsNullOrEmpty(cacheId) || cacheId.Length != CACHE_ID_HEX_LENGTH) + return false; + foreach (char character in cacheId) + if (!char.IsAsciiHexDigitLower(character)) + return false; + return true; + } + + /// + /// Removes the entries of a directory that belong to the namespace of the normalized audio cache, and leaves every other entry untouched. + /// + /// The absolute path of the cache directory. + /// Cancellation token that can be used to stop the execution. + /// + /// The cache directory itself is never deleted, and entries that do not carry a cache identifier, a temporary directory name or a deletion tombstone + /// name are never inspected. This makes the startup cleanup safe even when the configured directory is not one this application created. + /// + /// The cleanup was canceled. + /// An entry could not be deleted. + /// An entry could not be deleted because access was denied. + public static void ClearCacheEntries(string directoryPath, CancellationToken cancellationToken) + { + foreach (string entryPath in Directory.GetDirectories(directoryPath)) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!IsCacheEntryName(Path.GetFileName(entryPath))) + continue; + DirectoryInfo entryDirectory = new(entryPath); + // A cache entry is never a link. A link left under a cache like name is deleted as a link, so the deletion can never be redirected outside the cache. + if (entryDirectory.LinkTarget is not null) + entryDirectory.Delete(); + else + DeleteDirectoryRecursive(entryPath, cancellationToken); + } + } + + /// + /// Deletes a directory and everything it contains. + /// + /// The directory to delete. + /// Cancellation token that can be used to stop the execution. + /// The deletion was canceled. + /// A file or directory could not be deleted. + /// A file or directory could not be deleted because access was denied. + private static void DeleteDirectoryRecursive(string directoryPath, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + foreach (string filePath in Directory.EnumerateFiles(directoryPath)) + { + cancellationToken.ThrowIfCancellationRequested(); + File.Delete(filePath); + } + foreach (string childDirectoryPath in Directory.EnumerateDirectories(directoryPath)) + { + cancellationToken.ThrowIfCancellationRequested(); + DirectoryInfo childDirectory = new(childDirectoryPath); + // A link is deleted as a link, so a tampered entry can never make the cleanup follow it outside the cache. + if (childDirectory.LinkTarget is not null) + childDirectory.Delete(); + else + DeleteDirectoryRecursive(childDirectoryPath, cancellationToken); + } + cancellationToken.ThrowIfCancellationRequested(); + Directory.Delete(directoryPath); + } + + /// + /// Verifies that an existing cache directory is not a symbolic link and tightens its permissions to the private mode on Unix. + /// + /// The absolute path of the cache directory. + /// The path is a symbolic link or cannot be inspected. + /// The directory is owned by another user or cannot be changed. + public static void RestrictPermissions(string directoryPath) + { + DirectoryInfo directoryInformation = new(directoryPath); + // A symbolic link is rejected even when its target does not exist, so CreateDirectory can never be redirected outside the intended path. + if (directoryInformation.LinkTarget is not null) + throw new IOException("The normalized audio cache directory is a symbolic link."); + + // On Unix a directory that already exists is not changed by CreateDirectory, and a directory planted by another user under a predictable name in + // the shared temporary directory would otherwise be reused with its own mode. Tightening it fails when the directory is not owned by this + // account, which makes the caller treat the cache as unavailable instead of using a directory it does not control. + if (!OperatingSystem.IsWindows() && directoryInformation.Exists) + File.SetUnixFileMode(directoryPath, PRIVATE_DIRECTORY_MODE); + } + + /// + /// Tightens the permissions of a file the cache created to owner read and write on Unix. + /// + /// The absolute path of the file. + /// The file permissions could not be changed. + /// The file is owned by another user or cannot be changed. + public static void RestrictFilePermissions(string filePath) + { + // Windows inherits the ACL of the private cache directory, so only the Unix mode bits need to be tightened here. + if (!OperatingSystem.IsWindows()) + File.SetUnixFileMode(filePath, PRIVATE_FILE_MODE); + } + + /// + /// Creates a directory with private permissions on the platforms that support them. + /// + /// The absolute path of the directory to create. + /// The directory could not be created. + /// The directory could not be created because access was denied. + public static void CreatePrivateDirectory(string directoryPath) + { + if (OperatingSystem.IsWindows()) + { + Directory.CreateDirectory(directoryPath); + return; + } + Directory.CreateDirectory(directoryPath, PRIVATE_DIRECTORY_MODE); + // CreateDirectory does not change an existing directory, so the mode is applied again after the directory is known to exist. + File.SetUnixFileMode(directoryPath, PRIVATE_DIRECTORY_MODE); + } + + /// + /// Creates the cache directory when it does not exist, or tightens an existing one, with private permissions on the platforms that support them. + /// + /// The absolute path of the cache directory. + /// + /// A directory created by this method is marked as owned by this application. An existing directory is never marked, so an operator supplied directory + /// is adopted only by the startup component, and only when it is empty. + /// + /// The directory could not be created, or the path is a symbolic link. + /// The directory could not be created or changed because access was denied. + public static void EnsureDirectoryExists(string directoryPath) + { + RestrictPermissions(directoryPath); + bool isCreated = !Directory.Exists(directoryPath); + CreatePrivateDirectory(directoryPath); + if (isCreated) + WriteCacheMarker(directoryPath); + } + + /// + /// Deletes a directory, and reports whether it was deleted. + /// + /// The directory to delete. + /// when the directory no longer exists, otherwise . + public static bool TryDeleteDirectory(string directoryPath) + { + try + { + if (Directory.Exists(directoryPath)) + Directory.Delete(directoryPath, recursive: true); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + } + + /// + /// Gets a short, file name safe suffix of the operating system account that runs the process, so the default directory is not shared between users. + /// + /// The account suffix used in the default cache directory name. + private static string GetUserSuffix() + { + string userIdentity = Environment.UserName; + if (string.IsNullOrWhiteSpace(userIdentity)) + userIdentity = "default"; + byte[] identityHash = SHA256.HashData(Encoding.UTF8.GetBytes(userIdentity)); + return Convert.ToHexString(identityHash).ToLowerInvariant()[..USER_SUFFIX_LENGTH]; + } +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 4154b4a9..b36d8d58 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -152,6 +152,18 @@ public static class InfrastructureLayerServices // repackaged into another container, or re-encoded into another codec. services.AddSingleton(); + // Music playback: records the outcome of the ffmpeg probe, so a missing binary or encoder is reported as unavailable for the affected formats. + services.AddSingleton(); + + // Music playback: produces the normalized (remuxed or transcoded) audio of a track with ffmpeg, caches it as fixed duration + // segments and serves it from the cache, bounded in concurrency, cancellable and capped in disk usage. The playback stream surface + // is its intended consumer; no API request path calls it yet. + services.AddSingleton(); + + // Music playback: owns the normalized audio cache lifecycle and verifies the ffmpeg encoders at startup, so a missing or changed toolchain + // is recorded and reported as unavailable for the affected formats instead of surfacing as a per track playback failure. + services.AddHostedService(); + // Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents. // The enablement cache lets the reading service skip the per-request database read of the reader configurations. services.AddSingleton(); diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index afd1c2c7..ce2327d0 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -70,6 +70,11 @@ public static class SharedConfiguration .ValidateFluently() .ValidateOnStart(); + services.AddOptions() + .Bind(configuration.GetRequiredSection(TranscodingSettingsDto.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + return services; } } diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index d5aa5e0e..b13262b8 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -33,5 +33,18 @@ public static partial class Errors public static Error ThemeMaxExpandedBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxExpandedBytesMustBePositive)); public static Error ThemeMaxSingleFileBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxSingleFileBytesMustBePositive)); public static Error ThemeMaxEntriesMustBePositive => Error.Validation(description: nameof(ThemeMaxEntriesMustBePositive)); + public static Error TranscodingFfmpegPathCannotBeEmpty => Error.Validation(description: nameof(TranscodingFfmpegPathCannotBeEmpty)); + public static Error TranscodingMaxConcurrentJobsMustBePositive => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsMustBePositive)); + public static Error TranscodingMaxConcurrentJobsIsTooLarge => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsIsTooLarge)); + public static Error TranscodingMaxCacheBytesMustBePositive => Error.Validation(description: nameof(TranscodingMaxCacheBytesMustBePositive)); + public static Error TranscodingJobTimeoutMustBePositive => Error.Validation(description: nameof(TranscodingJobTimeoutMustBePositive)); + public static Error TranscodingJobTimeoutIsTooLong => Error.Validation(description: nameof(TranscodingJobTimeoutIsTooLong)); + public static Error TranscodingEvictionGraceSecondsMustBePositive => Error.Validation(description: nameof(TranscodingEvictionGraceSecondsMustBePositive)); + public static Error TranscodingEvictionGraceSecondsIsTooLong => Error.Validation(description: nameof(TranscodingEvictionGraceSecondsIsTooLong)); + public static Error TranscodingCacheDirectoryIsInvalid => Error.Validation(description: nameof(TranscodingCacheDirectoryIsInvalid)); + public static Error TranscodingCacheDirectoryIsInsideMediaRoot => Error.Validation(description: nameof(TranscodingCacheDirectoryIsInsideMediaRoot)); + public static Error TranscodingCacheDirectoryContainsMediaRoot => Error.Validation(description: nameof(TranscodingCacheDirectoryContainsMediaRoot)); + public static Error TranscodingCacheDirectoryIsUnsafeLocation => Error.Validation(description: nameof(TranscodingCacheDirectoryIsUnsafeLocation)); + public static Error TranscodingDefaultCacheDirectoryIsInsideMediaRoot => Error.Validation(description: nameof(TranscodingDefaultCacheDirectoryIsInsideMediaRoot)); } } diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs new file mode 100644 index 00000000..a533f8e5 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.Configuration; + +/// +/// Data transfer object for deserializing the settings of the audio normalization pipeline. +/// +[DebuggerDisplay("Section name: {SECTION_NAME}")] +public sealed class TranscodingSettingsDto +{ + public const string SECTION_NAME = "TranscodingSettings"; + + /// + /// Gets or sets the file name or path of the ffmpeg binary, relative to the process search path when not rooted. + /// + public string FfmpegPath { get; set; } = "ffmpeg"; + + /// + /// Gets or sets the maximum number of normalization jobs that may run at the same time. + /// + public int MaxConcurrentJobs { get; set; } = 2; + + /// + /// Gets or sets the maximum total size of the normalized audio cache, in bytes. + /// + public long MaxCacheBytes { get; set; } = 2L * 1024 * 1024 * 1024; + + /// + /// Gets or sets the maximum duration of a single normalization job, in seconds, after which the job is stopped. + /// + public int JobTimeoutSeconds { get; set; } = 900; + + /// + /// Gets or sets the period, in seconds, during which a cache entry that was just produced or served is protected from eviction. + /// + public int EvictionGraceSeconds { get; set; } = 120; + + /// + /// Gets or sets the directory where normalized audio is cached, relative to the API base directory when not rooted. When absent or empty, a + /// private directory under the system temporary directory is used. + /// + public string? CacheDirectory { get; set; } +} diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs new file mode 100644 index 00000000..996b3262 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Describes how a single container and codec combination of the audio normalization pipeline is muxed and, when it has to be re-encoded, encoded. +/// +/// The canonical container of the delivered audio. +/// The canonical codec of the delivered audio. +/// The name of the ffmpeg muxer that writes the container. +/// The file extension of a single segment, including the leading dot. +/// The name of the ffmpeg encoder used when the audio is transcoded. +/// Whether the codec is lossless, in which case an encoder bitrate cap does not apply. +[DebuggerDisplay("Container: {Container} Codec: {Codec} Muxer: {MuxerName}")] +internal sealed record NormalizedAudioFormatDto( + string Container, + string Codec, + string MuxerName, + string FileExtension, + string EncoderName, + bool IsLossless +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs new file mode 100644 index 00000000..0190f027 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents the persisted description of a cached normalized track, which lets the cache be read without parsing the ffmpeg output again. +/// +/// The version of the index layout, so an index written by an older version is treated as a cache miss. +/// The Id of the track the cached audio belongs to, so a cache handle can be authorized against the track of the route. +/// The way the audio is delivered, which is a remux or a transcode. +/// The container of the delivered audio. +/// The codec of the delivered audio. +/// The duration of each segment of the delivered audio, in seconds. +/// +/// The duration of the produced and cached audio, in seconds, rounded up to the next second. It is the produced end rather than the probed duration, so +/// it always covers every produced segment. +/// +/// The segments that make up the delivered audio, in playback order. +[DebuggerDisplay("TrackId: {TrackId} Container: {Container} Codec: {Codec} Segments: {Segments.Count}")] +// The record is internal, so its primary constructor is not public. Marking it tells System.Text.Json to use it for the on disk index anyway. +[method: JsonConstructor] +internal sealed record NormalizedTrackIndexDto( + int Version, + Guid TrackId, + PlaybackDeliveryMode Mode, + string Container, + string Codec, + int SegmentDurationSeconds, + int DurationInSeconds, + IReadOnlyList Segments +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs new file mode 100644 index 00000000..d9ae324c --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents the persisted description of a single segment of a cached normalized track. +/// +/// The zero based position of the segment in the delivered audio. +/// The time, in seconds from the start of the track, at which the segment starts. +/// The duration of the segment, in seconds. +/// The file name of the segment inside the cache entry. +/// The length of the segment, in bytes. +[DebuggerDisplay("Index: {Index} StartSeconds: {StartSeconds} FileName: {FileName}")] +// The record is internal, so its primary constructor is not public. Marking it tells System.Text.Json to use it for the on disk index anyway. +[method: JsonConstructor] +internal sealed record NormalizedTrackSegmentIndexDto( + int Index, + decimal StartSeconds, + decimal DurationSeconds, + string FileName, + long Length +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs new file mode 100644 index 00000000..588a6c79 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents a single entry of the normalized audio cache, used to enforce the cache size limit. +/// +/// The absolute path of the directory that holds the entry. +/// The total size of the entry, in bytes. +/// The date and time, in UTC, when the entry was last produced or served. +/// The date and time, in UTC, when the entry was produced or, for an entry found on disk, the earliest representable time. +[DebuggerDisplay("Path: {Path} Size: {Size}")] +internal sealed record TranscodingCacheEntryDto( + string Path, + long Size, + DateTime LastUsedUtc, + DateTime ProducedAtUtc +); diff --git a/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs new file mode 100644 index 00000000..4d4d5213 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs @@ -0,0 +1,291 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Common.Validators; + +/// +/// Validates the needed validation rules for the TranscodingSettings application configuration settings section. +/// +public class TranscodingSettingsDtoValidator : AbstractValidator +{ + private const int MAX_CONCURRENT_JOBS = 64; + private const int MAX_JOB_TIMEOUT_SECONDS = 86400; + private const int MAX_EVICTION_GRACE_SECONDS = 86400; + + private static readonly StringComparison s_pathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + private readonly IPathService _pathService; + private readonly string _mediaRootDirectory; + private readonly string[] _conflictingDirectories; + + /// + /// Initializes a new instance of the class. + /// + /// The media settings, used to reject a cache directory that would be served by the media route. + /// The plugin settings, used to reject a cache directory that would overlap the plugins directory. + /// The service used to check whether two directories overlap. + public TranscodingSettingsDtoValidator(IOptions mediaSettings, IOptions pluginsSettings, IPathService pathService) + { + _pathService = pathService; + _mediaRootDirectory = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, mediaSettings.Value.RootDirectory)); + _conflictingDirectories = BuildConflictingDirectories(pluginsSettings.Value); + + RuleFor(settings => settings.FfmpegPath) + .NotEmpty() + .WithError(Errors.Errors.Configuration.TranscodingFfmpegPathCannotBeEmpty); + + RuleFor(settings => settings.MaxConcurrentJobs) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive); + + RuleFor(settings => settings.MaxConcurrentJobs) + .Must(maxConcurrentJobs => maxConcurrentJobs <= MAX_CONCURRENT_JOBS) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge); + + RuleFor(settings => settings.MaxCacheBytes) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingMaxCacheBytesMustBePositive); + + RuleFor(settings => settings.JobTimeoutSeconds) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingJobTimeoutMustBePositive); + + // CancellationTokenSource(TimeSpan) cannot represent an arbitrarily large delay, and a job that may run for days is a configuration error. + RuleFor(settings => settings.JobTimeoutSeconds) + .Must(jobTimeoutSeconds => jobTimeoutSeconds <= MAX_JOB_TIMEOUT_SECONDS) + .WithError(Errors.Errors.Configuration.TranscodingJobTimeoutIsTooLong); + + RuleFor(settings => settings.EvictionGraceSeconds) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive); + + RuleFor(settings => settings.EvictionGraceSeconds) + .Must(evictionGraceSeconds => evictionGraceSeconds <= MAX_EVICTION_GRACE_SECONDS) + .WithError(Errors.Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong); + + RuleFor(settings => settings.CacheDirectory) + .Must(BeAValidDirectoryPath) + .WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsInvalid) + .When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory)); + + // A malformed path is reported by the rule above, so the rules below must not try to resolve it: Path.GetFullPath would throw and abort + // startup with a raw exception instead of a configuration error. + RuleFor(settings => settings.CacheDirectory) + .Must(BeConfiguredDirectoryOutsideMediaRoot) + .WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot) + .When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory)); + + // The reverse containment is just as destructive: a cache directory that contains the media root would delete the media when it is cleaned. + RuleFor(settings => settings.CacheDirectory) + .Must(BeConfiguredDirectoryNotContainingMediaRoot) + .WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot) + .When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory)); + + // The cache directory is cleaned at startup, so it must never resolve to a location whose cleanup would damage the application or the host. + RuleFor(settings => settings.CacheDirectory) + .Must(BeInSafeLocation) + .WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation) + .When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory)); + + // When no directory is configured the service uses a per-user directory under the system temporary directory. A failure of that default is a + // different configuration problem from a CacheDirectory the operator chose, so it is reported with its own error and never names CacheDirectory. + RuleFor(settings => settings.CacheDirectory) + .Must(_ => BeDefaultDirectoryOutsideMediaRoot()) + .WithError(Errors.Errors.Configuration.TranscodingDefaultCacheDirectoryIsInsideMediaRoot) + .When(settings => string.IsNullOrWhiteSpace(settings.CacheDirectory)); + } + + /// + /// Checks whether the provided cache directory is a path the file system accepts. + /// + /// The configured cache directory, or when the default is used. + /// when the path is valid, otherwise . + private static bool BeAValidDirectoryPath(string? cacheDirectory) + { + if (string.IsNullOrWhiteSpace(cacheDirectory)) + return true; + try + { + Path.GetFullPath(cacheDirectory); + return true; + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + } + + /// + /// Checks whether the configured cache directory is outside the media root, which is served without authentication at the media route. + /// + /// The configured cache directory. It is already known to be a valid path. + /// when the cache is outside the media root, otherwise . + private bool BeConfiguredDirectoryOutsideMediaRoot(string? cacheDirectory) + { + try + { + return !IsSameOrWithin(TranscodingCachePaths.GetRootDirectory(cacheDirectory), _mediaRootDirectory); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception. + return true; + } + } + + /// + /// Checks whether the configured cache directory does not contain the media root. + /// + /// The configured cache directory. It is already known to be a valid path. + /// when the cache does not contain the media root, otherwise . + private bool BeConfiguredDirectoryNotContainingMediaRoot(string? cacheDirectory) + { + try + { + return !IsSameOrWithin(_mediaRootDirectory, TranscodingCachePaths.GetRootDirectory(cacheDirectory)); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception. + return true; + } + } + + /// + /// Checks whether the configured cache directory is a location whose cleanup cannot damage the application or the host. + /// + /// The configured cache directory. It is already known to be a valid path. + /// when the location is safe, otherwise . + private bool BeInSafeLocation(string? cacheDirectory) + { + try + { + string resolvedCacheDirectory = TranscodingCachePaths.GetRootDirectory(cacheDirectory); + if (IsFileSystemRoot(resolvedCacheDirectory)) + return false; + // The cache must never be the application base directory or one of its ancestors, because cleaning it would remove the application itself. + if (IsSameOrWithin(AppContext.BaseDirectory, resolvedCacheDirectory)) + return false; + // The logs and plugins directories are managed by the application, so the cache must not overlap them in either direction. + foreach (string conflictingDirectory in _conflictingDirectories) + if (IsSameOrWithin(resolvedCacheDirectory, conflictingDirectory) || IsSameOrWithin(conflictingDirectory, resolvedCacheDirectory)) + return false; + return true; + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception. + return true; + } + } + + /// + /// Checks whether the default cache directory, used when none is configured, is outside the media root. + /// + /// when the default cache is outside the media root, otherwise . + private bool BeDefaultDirectoryOutsideMediaRoot() + { + try + { + return !IsSameOrWithin(TranscodingCachePaths.GetRootDirectory(configuredDirectory: null), _mediaRootDirectory); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // A temporary directory that cannot be resolved is reported by the startup initializer; it is not a media root containment error. + return true; + } + } + + /// + /// Checks whether a path is equal to, or is located inside, another path. + /// + /// The path to check. + /// The path that must contain, or be equal to, the checked path. + /// when the path is equal to or inside the parent path, otherwise . + private bool IsSameOrWithin(string path, string parentPath) + { + string normalizedPath = NormalizePath(path); + string normalizedParentPath = NormalizePath(parentPath); + if (string.Equals(normalizedPath, normalizedParentPath, s_pathComparison)) + return true; + return _pathService.IsPathWithin(normalizedPath, normalizedParentPath); + } + + /// + /// Checks whether a path is the root of a file system, or of a volume, instead of a directory inside it. + /// + /// The absolute path to check. + /// when the path is a file system root, otherwise . + private static bool IsFileSystemRoot(string path) + { + string normalizedPath = NormalizePath(path); + string? rootPath = Path.GetPathRoot(normalizedPath); + return rootPath is not null && string.Equals(normalizedPath, rootPath, s_pathComparison); + } + + /// + /// Gets the full form of a path, without a trailing separator unless the path itself is the root of a file system or volume. + /// + /// The path to normalize. + /// The normalized absolute path. + private static string NormalizePath(string path) + { + string fullPath = Path.GetFullPath(path); + string? rootPath = Path.GetPathRoot(fullPath); + // The root must keep its trailing separator, otherwise a drive root such as "C:\" degenerates into the drive relative path "C:". + if (rootPath is null || fullPath.Length <= rootPath.Length) + return fullPath; + return fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + } + + /// + /// Gets the directories that the cache directory must never overlap: the logs directory and the plugins directory. + /// + /// The plugin settings, whose directory is resolved against the application base directory. + /// The absolute paths of the directories the cache must not overlap. + private static string[] BuildConflictingDirectories(PluginsSettingsDto pluginsSettings) + { + List conflictingDirectories = []; + if (!string.IsNullOrWhiteSpace(pluginsSettings.Directory)) + AddConflictingDirectory(conflictingDirectories, Path.Combine(AppContext.BaseDirectory, pluginsSettings.Directory)); + // The local log path is always the logs directory of the application base directory; the environment variable and the container path cover + // the other two ways the log path is selected at startup. + AddConflictingDirectory(conflictingDirectories, Path.Combine(AppContext.BaseDirectory, "logs")); + AddConflictingDirectory(conflictingDirectories, Environment.GetEnvironmentVariable("LOG_PATH")); + if (string.Equals(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase)) + AddConflictingDirectory(conflictingDirectories, "/logs"); + return [.. conflictingDirectories]; + } + + /// + /// Adds the full form of a directory to the list of conflicting directories, when it can be resolved and is not already listed. + /// + /// The list of conflicting directories to add to. + /// The directory to add, or when it is not configured. + private static void AddConflictingDirectory(List conflictingDirectories, string? directory) + { + if (string.IsNullOrWhiteSpace(directory)) + return; + try + { + string resolvedDirectory = NormalizePath(directory); + if (!conflictingDirectories.Contains(resolvedDirectory, StringComparer.FromComparison(s_pathComparison))) + conflictingDirectories.Add(resolvedDirectory); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // A malformed log path is reported by the logging configuration, not by the cache validation. + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs new file mode 100644 index 00000000..8a1fe34f --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// The single catalog of the audio formats the server can produce, shared by the playback delivery decision and the audio normalization pipeline. +/// +/// +/// The order of is significant: the first appearance of a codec is its transcode preference, and the order of the containers of a +/// codec is the order in which the server prefers to produce it. Both the delivery decision and the normalization pipeline derive their tables from this +/// catalog, so a format can never be promised in a manifest without also being implementable by the pipeline. +/// +internal static class PlaybackFormatCatalog +{ + /// + /// Gets the formats the server can produce, in the order of the transcode codec preference and, within a codec, of the container preference. + /// + public static IReadOnlyList Formats { get; } = + [ + new("MP4", "AAC", "mp4", ".m4a", "aac", false), + new("AAC", "AAC", "adts", ".aac", "aac", false), + new("OGG", "OPUS", "ogg", ".ogg", "libopus", false), + new("MP3", "MP3", "mp3", ".mp3", "libmp3lame", false), + new("OGG", "VORBIS", "ogg", ".ogg", "libvorbis", false), + new("FLAC", "FLAC", "flac", ".flac", "flac", true), + new("WAV", "PCM", "wav", ".wav", "pcm_s16le", true) + ]; + + /// + /// Gets the formats the server can produce, keyed by their canonical container and codec pair. + /// + public static FrozenDictionary FormatsByPair { get; } = BuildFormatsByPair(); + + /// + /// Gets the containers the server can produce each codec in, in order of preference. + /// + public static FrozenDictionary> ProducibleContainersByCodec { get; } = BuildProducibleContainersByCodec(); + + /// + /// Gets the codecs the server can produce, in order of preference. + /// + public static IReadOnlyList TranscodeCodecPreference { get; } = BuildTranscodeCodecPreference(); + + /// + /// Builds the key of a canonical container and codec pair. + /// + /// The container of the audio. + /// The codec of the audio. + /// The canonical key of the pair. + public static string BuildPairKey(string container, string codec) + { + return (container ?? string.Empty).Trim().ToUpperInvariant() + "/" + (codec ?? string.Empty).Trim().ToUpperInvariant(); + } + + /// + /// Builds the map of the producible formats, keyed by their canonical container and codec pair. + /// + /// The producible formats, keyed by their canonical pair. + private static FrozenDictionary BuildFormatsByPair() + { + return Formats.ToFrozenDictionary(format => BuildPairKey(format.Container, format.Codec), StringComparer.OrdinalIgnoreCase); + } + + /// + /// Builds the map of the containers the server can produce each codec in, preserving the order of the catalog. + /// + /// The containers of each producible codec, in order of preference. + private static FrozenDictionary> BuildProducibleContainersByCodec() + { + Dictionary> containersByCodec = new(StringComparer.OrdinalIgnoreCase); + foreach (NormalizedAudioFormatDto format in Formats) + { + if (!containersByCodec.TryGetValue(format.Codec, out List? containers)) + { + containers = []; + containersByCodec[format.Codec] = containers; + } + if (!containers.Contains(format.Container, StringComparer.OrdinalIgnoreCase)) + containers.Add(format.Container); + } + return containersByCodec.ToFrozenDictionary(entry => entry.Key, entry => (IReadOnlyList)entry.Value, StringComparer.OrdinalIgnoreCase); + } + + /// + /// Builds the codecs the server can produce, preserving the order in which they first appear in the catalog. + /// + /// The producible codecs, in order of preference. + private static IReadOnlyList BuildTranscodeCodecPreference() + { + List codecs = []; + foreach (NormalizedAudioFormatDto format in Formats) + if (!codecs.Contains(format.Codec, StringComparer.OrdinalIgnoreCase)) + codecs.Add(format.Codec); + return codecs; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs index 3afe9bf2..61df12f3 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs @@ -5,7 +5,6 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; -using System.Collections.Frozen; using System.Collections.Generic; using System.Linq; #endregion @@ -25,22 +24,6 @@ internal sealed class PlaybackFormatService : IPlaybackFormatService // The duration of each segment of a normalized (remuxed or transcoded) delivery, in seconds: short enough to seek quickly, long enough to keep the request overhead low. private const int SEGMENT_DURATION_SECONDS = 6; - // The order in which the codecs the server can produce are tried when a transcode is needed, most preferred first: the - // efficient lossy codecs come before the lossless ones, so a transcode stays small unless the player only supports lossless. - private static readonly IReadOnlyList s_transcodeCodecPreference = ["AAC", "OPUS", "MP3", "VORBIS", "FLAC", "PCM"]; - - // The containers the server can produce each codec in, in order of preference. The delivered container is always chosen from - // this list, so a container the player named is only ever matched against it and never becomes the delivered container itself. - private static readonly FrozenDictionary> s_producibleContainersByCodec = new Dictionary>(StringComparer.OrdinalIgnoreCase) - { - { "AAC", ["MP4", "AAC"] }, - { "OPUS", ["OGG"] }, - { "VORBIS", ["OGG"] }, - { "MP3", ["MP3"] }, - { "FLAC", ["FLAC"] }, - { "PCM", ["WAV"] } - }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); - /// /// Decides how the audio of a track, described by , is delivered to a player that advertises . /// @@ -101,7 +84,7 @@ internal sealed class PlaybackFormatService : IPlaybackFormatService /// private static PlaybackCapabilityDto? SelectFormatForCodec(IReadOnlyList capabilities, string codec) { - if (codec.Length == 0 || !s_producibleContainersByCodec.TryGetValue(codec, out IReadOnlyList? producibleContainers)) + if (codec.Length == 0 || !PlaybackFormatCatalog.ProducibleContainersByCodec.TryGetValue(codec, out IReadOnlyList? producibleContainers)) return null; IReadOnlyList advertisedContainers = [.. capabilities @@ -124,7 +107,7 @@ internal sealed class PlaybackFormatService : IPlaybackFormatService /// The preferred producible container and codec, or when the player supports no producible codec. private static PlaybackCapabilityDto? SelectTranscodeFormat(IReadOnlyList capabilities) { - foreach (string preferredCodec in s_transcodeCodecPreference) + foreach (string preferredCodec in PlaybackFormatCatalog.TranscodeCodecPreference) { PlaybackCapabilityDto? format = SelectFormatForCodec(capabilities, preferredCodec); if (format is not null) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs new file mode 100644 index 00000000..0fb9cfec --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs @@ -0,0 +1,1389 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Service that produces the normalized audio of a track with ffmpeg, caches it as fixed duration segments and serves it from the cache. +/// +/// +/// The normalized audio is written to a temporary directory that is wiped when the application starts. The number of jobs that run at the same time is +/// bounded, and a request that finds every slot occupied is reported as busy instead of being queued, so client requests cannot accumulate behind the +/// running jobs. Every child process is stopped when the application exits, and every job has a bounded duration. A production is shared by every request +/// for the same track and delivery: a request that disconnects stops waiting but does not stop the production, so repeated aborts converge to a cached entry. +/// A production is atomic: the entry is published only after ffmpeg finishes the whole track, so the first request waits for a complete production; the +/// produced segments are then served from the cache without buffering them into memory. The total size of the cache, including the output of the jobs that +/// are still running, is accounted for by a process wide coordinator, which evicts the least recently used entries that are neither freshly produced nor +/// being read. The command line is always built as a list of arguments, with the input protocol restricted to the file protocol, so a file path is never +/// interpolated into a command string and a probed file can never fetch a remote URL. Every component of a source path below a content location is checked +/// for reparse points, and ffmpeg consumes a private snapshot copied from the opened handle, so a path that is swapped after the open cannot redirect the +/// bytes that are transcoded. +/// +internal sealed class TrackNormalizationService : ITrackNormalizationService, IDisposable +{ + private const string CACHE_INDEX_FILE_NAME = "index.json"; + private const string SEGMENT_LIST_FILE_NAME = "segments.csv"; + private const string SOURCE_SNAPSHOT_FILE_NAME = "source"; + private const string SEGMENT_FILE_PREFIX = "segment-"; + private const string SEGMENT_FILE_NAME_PATTERN = SEGMENT_FILE_PREFIX + "%06d"; + private const string AUDIO_STREAM_MAP = "0:a:0"; + private const string NO_METADATA_MAP = "-1"; + private const string COPY_CODEC = "copy"; + private const string FILE_PROTOCOL = "file"; + private const long MAX_CACHE_INDEX_BYTES = 4 * 1024 * 1024; + private const long MAX_SEGMENT_LIST_BYTES = 4 * 1024 * 1024; + private const int CACHE_INDEX_VERSION = 2; + private const int MAX_SEGMENT_COUNT = 1_000_000; + private const int CACHE_SIZE_MONITOR_INTERVAL_MILLISECONDS = 500; + private const int PROCESS_EXIT_TIMEOUT_SECONDS = 5; + private const int PRODUCTION_DRAIN_TIMEOUT_SECONDS = 15; + private const int MAX_STANDARD_ERROR_CHARACTERS = 16 * 1024; + private const int AUTO_TRANSCODE_BITRATE_KBPS = 192; + private const int DEFAULT_SOURCE_BITRATE_KBPS = 320; + private const int DEFAULT_SAMPLE_RATE = 44100; + private const int DEFAULT_CHANNEL_COUNT = 2; + private const int DEFAULT_BIT_DEPTH = 16; + private const decimal FLAC_COMPRESSION_RATIO = 0.7m; + private const decimal REMUX_SIZE_MARGIN = 1.1m; + private const decimal SEGMENT_TIME_TOLERANCE_SECONDS = 0.001m; + private const decimal DURATION_TOLERANCE_MIN_SECONDS = 1m; + private const decimal DURATION_TOLERANCE_RATIO = 0.02m; + + // The demuxer of each container the probe can report. Pinning the demuxer stops ffmpeg from probing the content of the file and selecting a + // demuxer that can open a playlist or another indirection; the file protocol whitelist is the backstop for a container that is not listed here. + private static readonly FrozenDictionary s_sourceDemuxers = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["MP3"] = "mp3", + ["FLAC"] = "flac", + ["MP4"] = "mov", + ["M4A"] = "mov", + ["AAC"] = "aac", + ["ADTS"] = "aac", + ["OGG"] = "ogg", + ["OPUS"] = "ogg", + ["VORBIS"] = "ogg", + ["WAV"] = "wav", + ["WAVE"] = "wav", + ["AIFF"] = "aiff", + ["APE"] = "ape", + ["WAVPACK"] = "wv", + ["WV"] = "wv", + ["WMA"] = "asf", + ["ASF"] = "asf", + ["DSF"] = "dsf", + ["MATROSKA"] = "matroska", + ["MKA"] = "matroska", + ["WEBM"] = "matroska", + ["MPC"] = "mpc", + ["AA"] = "aa" + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + + // The index is server written, but a tampered file is still parsed defensively: MaxDepth bounds the recursion of the deserializer. + private static readonly JsonSerializerOptions s_indexJsonOptions = new(JsonSerializerDefaults.Web) + { + PropertyNameCaseInsensitive = true, + MaxDepth = 8 + }; + + // The productions are shared by every request of the process for the same cache entry, so a request that disconnects never cancels the work that + // another request, or a later retry, is waiting for. The key includes the cache root, because two service instances configured with different cache + // directories must never join each other's production. A completed production is removed from the registry; a later request reads the cache instead. + private static readonly ConcurrentDictionary<(string CacheRoot, string CacheId), Lazy>>> s_normalizationJobs = new(); + + private readonly TranscodingSettingsDto _settings; + private readonly ILogger _logger; + private readonly IPathService _pathService; + private readonly TranscodingCacheCoordinator _cache; + private readonly TranscodingToolchainStatus _toolchainStatus; + private readonly TimeSpan _evictionGracePeriod; + private readonly TimeSpan _touchThrottleInterval; + private readonly SemaphoreSlim _jobSlots; + private readonly ConcurrentDictionary _runningProcesses = new(); + private readonly CancellationTokenSource _shutdownCancellation = new(); + private readonly Lock _lifecycleSync = new(); + private readonly ManualResetEventSlim _productionsDrained = new(initialState: true); + private readonly string _cacheRoot; + private int _activeProductionCount; + // Written under _lifecycleSync by Dispose and read without the lock by the request paths through Volatile.Read, so the write is observed promptly. + private bool _isDisposed; + + /// + /// Initializes a new instance of the class. + /// + /// The audio normalization configuration options. + /// The logger for this service. + /// The service used to validate that a cached segment is inside its cache entry. + /// The status that records whether the ffmpeg toolchain found at startup can produce a format. + public TrackNormalizationService(IOptions options, ILogger logger, IPathService pathService, TranscodingToolchainStatus toolchainStatus) + { + _settings = options.Value; + _logger = logger; + _pathService = pathService; + _toolchainStatus = toolchainStatus; + _jobSlots = new SemaphoreSlim(_settings.MaxConcurrentJobs, _settings.MaxConcurrentJobs); + _evictionGracePeriod = TimeSpan.FromSeconds(_settings.EvictionGraceSeconds); + // A touch is written at most every quarter of the eviction grace period, so a stream that opens many segments does not rewrite the cache + // entry for every request while an actively used entry stays protected from eviction. + _touchThrottleInterval = TimeSpan.FromSeconds(Math.Clamp(_settings.EvictionGraceSeconds / 4.0, 0.25, 30)); + _cacheRoot = TranscodingCachePaths.GetRootDirectory(_settings.CacheDirectory); + _cache = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot); + // A killed process must never outlive the application, so every child process that is still running is stopped when the process exits. The + // subscription is removed when the service is disposed, so a host that is shut down in the same process does not keep this instance rooted. + AppDomain.CurrentDomain.ProcessExit += OnApplicationStopping; + } + + /// + /// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet. + /// + /// The track, the delivery decision, the source file and the quality cap the normalized audio is produced with. + /// Cancellation token that can be used to stop the execution. + /// An containing either the cached normalized audio of the track, or an error message. + /// + /// Thrown when is canceled while the caller is waiting. The production continues in the background, so this is a + /// disconnect signal and must not be treated as a production failure. + /// + public async Task> GetOrCreateNormalizedTrackAsync(NormalizedTrackRequestDto request, CancellationToken cancellationToken) + { + // Dispose sets _isDisposed under _lifecycleSync, but taking that lock on every request would serialize this hot path. The flag is therefore read + // without the lock. Volatile.Read keeps the read from being cached in a register, so a request observes the disposal flag once it is set and + // fails fast instead of using resources that Dispose has already released. + if (Volatile.Read(ref _isDisposed)) + return Errors.Playback.NormalizationUnavailable; + if (request.TrackId == Guid.Empty) + return Errors.Playback.NormalizationFailed; + if (string.IsNullOrWhiteSpace(request.SourcePath)) + return Errors.Music.TrackPathCannotBeEmpty; + // The caller authorizes the request, and the service re-validates the source path against the content locations carried by the request. A path + // that is outside every allowed root is reported as not found, never as a path error, so no file system detail is disclosed. + if (request.AllowedRoots is null || request.AllowedRoots.Count == 0 || !IsPathAllowed(request.SourcePath, request.AllowedRoots)) + return Errors.Music.TrackFileNotFound; + // Normalization only exists for audio the player cannot play as stored, so a direct play never reaches the pipeline. + if (request.Mode == PlaybackDeliveryMode.DirectPlay) + return Errors.Playback.NormalizationIsNotRequiredForDirectPlay; + if (request.SegmentDurationSeconds <= 0) + return Errors.Playback.SegmentDurationMustBePositive; + if (request.DurationInSeconds <= 0) + return Errors.Playback.TrackDurationMustBePositive; + // A delivery decision that names a pair the catalog does not implement is a disagreement between two server side tables. It must never be + // reported as a limitation of the player, which is what the forbidden NoSupportedPlaybackFormat means. + if (!PlaybackFormatCatalog.FormatsByPair.TryGetValue(PlaybackFormatCatalog.BuildPairKey(request.Container, request.Codec), out NormalizedAudioFormatDto? format)) + return Errors.Playback.PlaybackFormatNotImplemented; + + FileInfo sourceFile; + long sourceLength; + DateTime sourceLastModifiedUtc; + try + { + sourceFile = new FileInfo(request.SourcePath); + if (!sourceFile.Exists) + return Errors.Music.TrackFileNotFound; + // The length and the modification time of the source are read once, while the file is known to exist, and are used both for the cache + // identity and for the size estimate, so a file that disappears between two reads can never surface as an unhandled exception. + sourceLength = sourceFile.Length; + sourceLastModifiedUtc = sourceFile.LastWriteTimeUtc; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + return Errors.Music.TrackFileNotFound; // A file that cannot be read is indistinguishable, to the caller, from a file that does not exist. + } + + string cacheId = BuildCacheId(request, sourceFile.FullName, sourceLength, sourceLastModifiedUtc, format); + // The entry is touched before its index is read, so that a cache hit can never race an eviction that is deciding on the entry at the same time: + // an eviction that runs after the touch sees the entry as recently used, and one that ran before the touch makes the read miss and produce anew. + _cache.Touch(cacheId, _touchThrottleInterval); + if (TryReadCachedTrack(cacheId, out NormalizedTrackDto? cachedTrack) && cachedTrack is not null && cachedTrack.TrackId == request.TrackId) + return cachedTrack; + + // The production is shared by every request for this cache entry and is not tied to this request's token. This request only waits for it, so a + // disconnect stops this caller from waiting without destroying the work, and the next request either joins the same production or reads its result. + (string CacheRoot, string CacheId) normalizationJobKey = (_cacheRoot, cacheId); + // ExecutionAndPublication makes the factory run exactly once when several requests race to create the same job. + Lazy>> normalizationJob = s_normalizationJobs.GetOrAdd( + normalizationJobKey, + createdJobKey => new Lazy>>( + () => ProduceAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc), + LazyThreadSafetyMode.ExecutionAndPublication)); + Task> normalizationTask = normalizationJob.Value; + // Remove the job from the static registry when it finishes, so a completed result is not kept in memory forever. + _ = normalizationTask.ContinueWith( + completedTask => RemoveNormalizationJob(normalizationJobKey, normalizationJob), + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + + return await normalizationTask.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Opens a read stream over a single segment of a cached normalized track, after verifying that the entry belongs to the provided track. + /// + /// The opaque identifier of the cached entry that holds the normalized audio. + /// The Id of the track the caller authorized and whose segment is opened. + /// The zero based position of the segment in the delivered audio. + /// + /// An containing either a read stream over the segment, or an error message. The caller owns the returned stream. + /// + public Result OpenNormalizedSegment(string cacheId, Guid trackId, int segmentIndex) + { + // This runs for every segment request and must not take _lifecycleSync. Dispose writes _isDisposed under that lock, and Volatile.Read makes this + // lock free check observe the write instead of a value cached in a register, so segments stop being served as soon as the service is disposed. + if (Volatile.Read(ref _isDisposed)) + return Errors.Playback.NormalizationUnavailable; + if (trackId == Guid.Empty || !TranscodingCacheCoordinator.IsValidCacheId(cacheId) || segmentIndex < 0) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + // The lease is acquired before the index is read, so that an eviction that runs concurrently can never delete the entry between the read and + // the moment the segment stream starts. The lease is handed over to the stream and released when the caller disposes it. + TranscodingCacheReaderLease lease = _cache.AcquireReaderLease(cacheId); + bool isLeaseTransferred = false; + try + { + if (!TryReadIndex(cacheId, out NormalizedTrackIndexDto? index) || index is null) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + // The cache handle is not a capability: it is derived from the track and can be computed by anyone who knows the track. The entry is bound + // to the track it was produced for, so a handle can only ever serve the track the caller authorized against the route. + if (index.TrackId != trackId) + return Errors.Music.TrackNotFound; + + NormalizedTrackSegmentIndexDto? segment = index.Segments.FirstOrDefault(candidate => candidate.Index == segmentIndex); + if (segment is null) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + string cachePath = Path.Combine(_cacheRoot, cacheId); + string segmentPath = Path.Combine(cachePath, segment.FileName); + // The file name comes from the cache index, which only the server writes, but the resolved path is still confined to the cache entry so that a + // tampered index can never be used to read a file outside it. + if (!_pathService.IsPathWithin(segmentPath, cachePath)) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + // A cache entry is never reached through a reparse point. The index is only written by this application, but a tampered cache entry must not be + // able to redirect a segment outside the cache root. + if (HasReparsePointBelow(_cacheRoot, segmentPath)) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + FileInfo segmentFile = new(segmentPath); + if (!segmentFile.Exists || segmentFile.Length != segment.Length) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + _cache.Touch(cacheId, _touchThrottleInterval); + // A published entry is immutable, so every reader can share the file. Delete sharing is not granted: replacement is coordinated through the + // lease and the publication lock, never by deleting a file under a reader. + FileStream fileStream = new(segmentPath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true); + try + { + // The handle is checked against the length from the index and against the reparse points again, so a file or an ancestor swapped between + // the check and the open is never handed to the caller. + if (fileStream.Length != segment.Length || HasReparsePointBelow(_cacheRoot, segmentPath)) + { + fileStream.Dispose(); + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + } + } + catch + { + fileStream.Dispose(); + throw; + } + TranscodingCacheLeaseStream leaseStream = new(fileStream, lease); + isLeaseTransferred = true; + return Result.Success(leaseStream); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + } + finally + { + if (!isLeaseTransferred) + lease.Dispose(); + } + } + + /// + /// Opens the stored audio file of a track after re-validating that it is inside an allowed root, and re-checks the opened handle. + /// + /// + /// The caller has already authorized the request, but the path is still validated here as defense in depth. Every component between an allowed root and + /// the leaf is rejected when it is a reparse point, so a symbolic link inside a content location can never redirect the file outside it. The file is then + /// opened, and the opened handle is checked against the allowed roots and against the length and modification time the cache identity was built from. + /// The caller copies the opened handle into a private snapshot before the transcoder runs, so the transcoder reads exactly the bytes that were validated, + /// even when the path is replaced afterwards. The length is read from the handle; the modification time is a path based, best effort comparison. + /// + /// The request whose source path and allowed roots are validated. + /// The length of the stored audio file of the track, in bytes, read when the cache identity was built. + /// The date and time, in UTC, when the stored audio file of the track was last modified, read when the cache identity was built. + /// An containing either an open read stream over the authorized source file, or an error message. The caller owns the stream. + private Result OpenAuthorizedSource(NormalizedTrackRequestDto request, long sourceLength, DateTime sourceLastModifiedUtc) + { + try + { + FileInfo sourceFile = new(request.SourcePath); + if (!sourceFile.Exists || !IsPathAllowed(sourceFile.FullName, request.AllowedRoots)) + return Errors.Music.TrackFileNotFound; + + string resolvedPath = sourceFile.FullName; + FileStream sourceStream = new(resolvedPath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true); + try + { + // The file is checked again after it has been opened, so a path that was swapped between the FileInfo read and the open is never handed + // to the transcoder. The length is read from the handle itself; the modification time must also still match the value the cache identity was built from. + FileInfo openedFile = new(resolvedPath); + if (!openedFile.Exists || + !IsPathAllowed(openedFile.FullName, request.AllowedRoots) || + sourceStream.Length != sourceLength || + openedFile.LastWriteTimeUtc != sourceLastModifiedUtc) + { + sourceStream.Dispose(); + return Errors.Music.TrackFileNotFound; + } + + return sourceStream; + } + catch + { + sourceStream.Dispose(); + throw; + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + return Errors.Music.TrackFileNotFound; + } + } + + /// + /// Checks whether a path is inside at least one of the allowed roots, without crossing a reparse point below that root. + /// + /// The path to check. + /// The roots the path is allowed to be inside. + /// when the path is inside an allowed root and no component below that root is a reparse point, otherwise . + private bool IsPathAllowed(string path, IReadOnlyList allowedRoots) + { + foreach (string allowedRoot in allowedRoots) + { + if (string.IsNullOrWhiteSpace(allowedRoot) || !_pathService.IsPathWithin(path, allowedRoot)) + continue; + // A reparse point inside the content location fails closed instead of being resolved, because its target is outside the root the caller authorized. + return !HasReparsePointBelow(allowedRoot, path); + } + return false; + } + + /// + /// Checks whether any component of a path below a root is a reparse point. + /// + /// The root below which the components are checked. + /// The path inside the root whose components are checked. + /// when a component below the root is a reparse point, otherwise . + private static bool HasReparsePointBelow(string rootPath, string path) + { + string normalizedRootPath = Path.GetFullPath(rootPath); + string normalizedPath = Path.GetFullPath(path); + string relativePath = Path.GetRelativePath(normalizedRootPath, normalizedPath); + if (relativePath == ".") + return false; + string currentPath = normalizedRootPath; + foreach (string segment in relativePath.Split([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries)) + { + // The lexical containment check already succeeded, so a relative escape means the two paths disagree; the file is rejected rather than trusted. + if (segment == "..") + return true; + if (segment == ".") + continue; + currentPath = Path.Combine(currentPath, segment); + if ((File.GetAttributes(currentPath) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) + return true; + } + return false; + } + + /// + /// Admits a production to the service lifetime, so that shutdown cancels it and disposes the process lifetime resources only after it has left. + /// + /// The opaque identifier of the cache entry. + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// An containing either the normalized audio of the track, or an error message. + private async Task> ProduceAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc) + { + lock (_lifecycleSync) + { + // A production that arrives after shutdown has started must not touch the cancellation source, the job slots or the coordinator, because shutdown may already have disposed them. + if (_isDisposed) + return Errors.Playback.NormalizationUnavailable; + // Dispose waits on _productionsDrained before it releases the coordinator and job slots. Counting the production here closes the race + // between the disposal check above and the resources being released while the production is still using them. + _activeProductionCount++; + if (_activeProductionCount == 1) + _productionsDrained.Reset(); + } + + try + { + return await ProduceCoreAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc).ConfigureAwait(false); + } + finally + { + lock (_lifecycleSync) + { + _activeProductionCount--; + if (_activeProductionCount == 0) + _productionsDrained.Set(); + } + } + } + + /// + /// Produces the normalized audio of a track in the background, independent of any request that waits for it. + /// + /// The opaque identifier of the cache entry. + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// An containing either the normalized audio of the track, or an error message. + private async Task> ProduceCoreAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc) + { + CancellationToken cancellationToken = _shutdownCancellation.Token; + + // The startup initializer owns the cache directory, but the service re-ensures it before every production so a directory removed at runtime or a + // failed startup wipe cannot turn into an unhandled exception or a partial write. + try + { + TranscodingCachePaths.EnsureDirectoryExists(_cacheRoot); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + _logger.LogError(exception, "The normalized audio cache directory '{CacheDirectory}' is not available for track {TrackId} in cache entry {CacheId}.", _cacheRoot, request.TrackId, cacheId); + return Errors.Playback.NormalizationUnavailable; + } + + try + { + // A production is admitted immediately or reported as busy. Queueing a task per distinct request would let a client saturate the pipeline + // and outlive its own timeout, while a started production is still allowed to outlive every disconnected waiter. + if (!_jobSlots.Wait(0)) + return Errors.Playback.NormalizationUnavailable; + try + { + // Another production for the same entry may have finished while this one was created, so the cache is checked again before spendingan admitted slot on work that is already done. + if (TryReadCachedTrack(cacheId, out NormalizedTrackDto? cachedTrack) && cachedTrack is not null && cachedTrack.TrackId == request.TrackId) + { + _cache.Touch(cacheId, _touchThrottleInterval); + return cachedTrack; + } + + // A cached entry is served even when the toolchain is broken, but a new production needs a usable ffmpeg and, for a transcode, the + // encoder of the delivery format. The startup probe recorded what is missing, so this is reported as unavailable instead of failing per track. + if (!_toolchainStatus.IsTranscoderAvailable || (request.Mode == PlaybackDeliveryMode.Transcode && !_toolchainStatus.IsEncoderAvailable(format.EncoderName))) + return Errors.Playback.NormalizationUnavailable; + + long estimatedSize = EstimateOutputSize(request, format); + if (!_cache.TryReserve(estimatedSize, _settings.MaxCacheBytes, _evictionGracePeriod, out TranscodingCacheReservation? reservation) || reservation is null) + return Errors.Playback.NormalizationCacheLimitExceeded; + + using (reservation) + return await NormalizeAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc, reservation, cancellationToken).ConfigureAwait(false); + } + finally + { + _jobSlots.Release(); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return Errors.Playback.NormalizationUnavailable; // The application is stopping, so the production cannot finish; it is reported instead of being left as an unobserved cancellation. + } + catch (Exception exception) + { + // The production is shared by requests that are no longer necessarily waiting, so every failure is turned into a result and observed here. + _logger.LogError(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be produced.", request.TrackId, cacheId); + return Errors.Playback.NormalizationFailed; + } + } + + /// + /// Produces the normalized audio of a track into a temporary directory, persists its index and asks the coordinator to publish it into the cache. + /// + /// The opaque identifier of the cache entry. + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// The capacity the job reserved in the cache. + /// Cancellation token that can be used to stop the execution. + /// An containing either the normalized audio of the track, or an error message. + private async Task> NormalizeAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc, TranscodingCacheReservation reservation, CancellationToken cancellationToken) + { + string temporaryPath = Path.Combine(_cacheRoot, TranscodingCachePaths.TEMPORARY_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N")); + string segmentListPath = Path.Combine(temporaryPath, SEGMENT_LIST_FILE_NAME); + + // The source is opened and re-validated here, immediately before the transcoder runs, and copied into a private snapshot that the transcoder reads. + // The snapshot is written from the validated handle, so the transcoder consumes exactly the bytes that were validated even when the path is replaced. + Result openResult = OpenAuthorizedSource(request, sourceLength, sourceLastModifiedUtc); + if (openResult.IsFailure) + return openResult.Errors; + + using (FileStream sourceStream = openResult.Value) + { + try + { + TranscodingCachePaths.CreatePrivateDirectory(temporaryPath); + string snapshotPath = Path.Combine(temporaryPath, SOURCE_SNAPSHOT_FILE_NAME); + bool isSnapshotComplete; + // The copy is bounded by the job timeout as well, so a source that never finishes reading cannot hold a job slot indefinitely. + using (CancellationTokenSource snapshotTimeoutCancellationTokenSource = new(TimeSpan.FromSeconds(_settings.JobTimeoutSeconds))) + { + using (CancellationTokenSource snapshotCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, snapshotTimeoutCancellationTokenSource.Token)) + { + try + { + isSnapshotComplete = await CopySourceSnapshotAsync(sourceStream, snapshotPath, sourceLength, snapshotCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return Errors.Playback.NormalizationTimedOut; + } + } + } + if (!isSnapshotComplete) + return Errors.Music.TrackFileNotFound; + + Result runResult; + try + { + runResult = await RunFfmpegAsync(cacheId, request, snapshotPath, format, temporaryPath, segmentListPath, reservation, cancellationToken).ConfigureAwait(false); + } + finally + { + // The snapshot is not part of the cache entry; it is removed before the entry is moved or the temporary directory is cleaned. + TryDeleteFile(snapshotPath); + } + if (runResult.IsFailure) + return runResult.Errors; + NormalizedTrackIndexDto index = runResult.Value; + // The csv is only an intermediate of the production; it is not part of the published entry and is never read again. + TryDeleteFile(segmentListPath); + // The entries are created under a private root, but each produced file is tightened as well instead of relying on the directory mode alone. + foreach (NormalizedTrackSegmentIndexDto segment in index.Segments) + TranscodingCachePaths.RestrictFilePermissions(Path.Combine(temporaryPath, segment.FileName)); + + // The index is written before the entry is published, so a cache hit never has to parse the ffmpeg output or probe the segments again. + string indexJson = JsonSerializer.Serialize(index, s_indexJsonOptions); + string temporaryIndexPath = Path.Combine(temporaryPath, CACHE_INDEX_FILE_NAME); + await File.WriteAllTextAsync(temporaryIndexPath, indexJson, cancellationToken).ConfigureAwait(false); + TranscodingCachePaths.RestrictFilePermissions(temporaryIndexPath); + // The segments were stat'ed by the index parser, so the size is the parsed lengths plus the index file instead of another walk of the entry. + long entrySize = index.Segments.Sum(segment => segment.Length) + Encoding.UTF8.GetByteCount(indexJson); + FileInfo remainingSegmentList = new(segmentListPath); + if (remainingSegmentList.Exists) + entrySize += remainingSegmentList.Length; + // The coordinator replaces the previous directory, moves this one into place and registers its index under one lock, so a concurrent + // eviction can never delete the freshly published entry and a reader is never served a mix of two productions. + if (!reservation.TryComplete(cacheId, temporaryPath, entrySize, index, _settings.MaxCacheBytes, _evictionGracePeriod, out bool isKeptOverCapacity, out bool isEntryInUse)) + { + if (isEntryInUse) + return Errors.Playback.NormalizationUnavailable; + return Errors.Playback.NormalizationFailed; + } + if (isKeptOverCapacity) + _logger.LogWarning("The normalized audio of track {TrackId} in cache entry {CacheId} was produced successfully but exceeds the configured normalized audio cache limit. It is kept readable and will be evicted when it is no longer in use.", request.TrackId, cacheId); + + return CreateNormalizedTrackDto(cacheId, index); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) + { + _logger.LogWarning(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be cached.", request.TrackId, cacheId); + return Errors.Playback.NormalizationFailed; + } + finally + { + if (Directory.Exists(temporaryPath)) + TranscodingCachePaths.TryDeleteDirectory(temporaryPath); + } + } + } + + /// + /// Copies the validated source stream into a private snapshot file, so the transcoder reads exactly the bytes that were validated. + /// + /// The open, validated stream over the stored audio file of the track. + /// The path of the snapshot file to create. + /// The expected length of the source file, in bytes. + /// Cancellation token that can be used to stop the execution. + /// when the whole source was copied, otherwise . + private static async Task CopySourceSnapshotAsync(FileStream sourceStream, string snapshotPath, long expectedLength, CancellationToken cancellationToken) + { + using (FileStream snapshotStream = new(snapshotPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true)) + await sourceStream.CopyToAsync(snapshotStream, cancellationToken).ConfigureAwait(false); + // The snapshot is read from the open handle, so the comparison detects a source that was truncated or grew after the handle was validated. + return new FileInfo(snapshotPath).Length == expectedLength; + } + + /// + /// Runs ffmpeg to write the normalized audio of a track into a temporary directory, and builds the index of the produced segments. + /// + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The path of the private snapshot of the stored audio file, which was copied from the validated handle. + /// The container and codec combination the normalized audio is produced in. + /// The temporary directory the normalized audio is written into. + /// The file into which ffmpeg writes the list of produced segments. + /// The capacity the job reserved in the cache. + /// Cancellation token that can be used to stop the execution. + /// An containing either the index of the produced segments, or an error message. + private async Task> RunFfmpegAsync(string cacheId, NormalizedTrackRequestDto request, string inputPath, NormalizedAudioFormatDto format, string temporaryPath, string segmentListPath, TranscodingCacheReservation reservation, CancellationToken cancellationToken) + { + using Process process = new(); + process.StartInfo = new ProcessStartInfo + { + FileName = _settings.FfmpegPath, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardError = true, + RedirectStandardOutput = false + }; + foreach (string argument in BuildArguments(request, inputPath, format, temporaryPath, segmentListPath)) + process.StartInfo.ArgumentList.Add(argument); + + try + { + if (!process.Start()) + return Errors.Playback.NormalizationFailed; + } + catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException) + { + _logger.LogError(exception, "The audio transcoder for track {TrackId} in cache entry {CacheId} could not be started.", request.TrackId, cacheId); + return Errors.Playback.NormalizationUnavailable; + } + + // The process is registered so the application exit handler can kill it even if the host stops without reaching this method's finally. + _runningProcesses[process.Id] = process; + try + { + // Start draining stderr before waiting. A child that fills the pipe buffer blocks until it is read, so waiting for the exit first could deadlock. + Task standardErrorTask = ReadBoundedStandardErrorAsync(process.StandardError); + using CancellationTokenSource timeoutCancellationTokenSource = new(TimeSpan.FromSeconds(_settings.JobTimeoutSeconds)); + using CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token); + // The callback kills ffmpeg as soon as the token fires, so a cancellation or timeout stops the child even while this thread is awaiting its + // exit. The catch below only observes the exit that the callback caused. + using CancellationTokenRegistration cancellationRegistration = linkedCancellationTokenSource.Token.Register(() => KillProcess(process)); + using CancellationTokenSource monitorCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(linkedCancellationTokenSource.Token); + TranscodingOutputSizeTracker outputSizeTracker = new(temporaryPath, SEGMENT_FILE_PREFIX, format.FileExtension, SEGMENT_LIST_FILE_NAME); + Task monitorTask = MonitorOutputSizeAsync(cacheId, request.TrackId, outputSizeTracker, reservation, process, monitorCancellationTokenSource.Token); + try + { + await process.WaitForExitAsync(linkedCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + KillProcess(process); + // The cancellation callback fired the kill without waiting. The exit is observed asynchronously here, so the temporary directory is + // cleaned up after the child has actually stopped, without pinning the thread that triggered the cancellation. + using CancellationTokenSource exitCancellationTokenSource = new(TimeSpan.FromSeconds(PROCESS_EXIT_TIMEOUT_SECONDS)); + try + { + await process.WaitForExitAsync(exitCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + _logger.LogDebug("The audio transcoder did not exit within the process exit timeout."); + } + } + finally + { + // The monitor loops until it is canceled. Stop it before awaiting it, or a job that finished normally would wait forever. + monitorCancellationTokenSource.Cancel(); + } + + bool isCacheLimitExceeded = await monitorTask.ConfigureAwait(false); + // The read is bounded: a process that was killed but did not exit would otherwise keep the pipe open and park the job slot. + string standardError = await AwaitStandardErrorAsync(standardErrorTask).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + if (isCacheLimitExceeded) + return Errors.Playback.NormalizationCacheLimitExceeded; + if (timeoutCancellationTokenSource.IsCancellationRequested) + return Errors.Playback.NormalizationTimedOut; + if (process.ExitCode != 0) + { + _logger.LogWarning("The audio transcoder for track {TrackId} in cache entry {CacheId} exited with code {ExitCode}.", request.TrackId, cacheId, process.ExitCode); + if (!string.IsNullOrWhiteSpace(standardError)) + { + // The bounded stderr can contain the source path and media metadata. It is only written at Debug and never returned to a client. + string diagnostic = RedactPath(RedactPath(standardError, inputPath), request.SourcePath); + _logger.LogDebug("The audio transcoder for track {TrackId} in cache entry {CacheId} reported: {StandardError}", request.TrackId, cacheId, diagnostic); + } + return Errors.Playback.NormalizationFailed; + } + + return ParseSegmentIndex(cacheId, segmentListPath, temporaryPath, request, format); + } + finally + { + _runningProcesses.TryRemove(process.Id, out _); + KillProcess(process); + } + } + + /// + /// Builds the argument list of a single ffmpeg invocation, with one argument per list entry, so a path is never interpolated into a command line. + /// + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The path of the private snapshot of the stored audio file, which was copied from the validated handle. + /// The container and codec combination the normalized audio is produced in. + /// The temporary directory the normalized audio is written into. + /// The file into which ffmpeg writes the list of produced segments. + /// The argument list of the ffmpeg invocation. + private static IReadOnlyList BuildArguments(NormalizedTrackRequestDto request, string inputPath, NormalizedAudioFormatDto format, string temporaryPath, string segmentListPath) + { + List arguments = + [ + "-hide_banner", + "-loglevel", "error", + "-nostdin", + "-y", + "-protocol_whitelist", FILE_PROTOCOL + ]; + + // The demuxer is pinned to the container the probe stored, so ffmpeg never probes the content of the file and never selects a demuxer that + // can follow a playlist or another indirection. A container that is not known is still limited to the file protocol by the whitelist above. + if (TryResolveSourceDemuxer(request.SourceContainer, out string sourceDemuxer)) + { + arguments.Add("-f"); + arguments.Add(sourceDemuxer); + } + + arguments.AddRange( + [ + "-i", inputPath, + "-map", AUDIO_STREAM_MAP, + "-vn", + "-sn", + "-dn", + "-map_metadata", NO_METADATA_MAP + ]); + + // A remux only repackages the stored codec, while a transcode re-encodes it and applies the streaming quality cap when the codec is lossy. + arguments.Add("-c:a"); + if (request.Mode == PlaybackDeliveryMode.Remux) + arguments.Add(COPY_CODEC); + else + { + arguments.Add(format.EncoderName); + // A lossy transcode always carries an explicit bitrate, including Auto, so the emitted stream and the cache size estimate use the same number. + if (!format.IsLossless) + { + arguments.Add("-b:a"); + arguments.Add(GetTargetBitrateKbps(request.Quality).ToString(CultureInfo.InvariantCulture) + "k"); + } + } + + arguments.AddRange( + [ + "-f", "segment", + "-segment_time", request.SegmentDurationSeconds.ToString(CultureInfo.InvariantCulture), + "-segment_format", format.MuxerName + ]); + + // MP4 writes the moov atom at the end by default, so a client that starts reading a segment before it is fully fetched would stall. The segments + // are written as files, so the muxer can move the atom to the front of each one. + if (string.Equals(format.MuxerName, "mp4", StringComparison.OrdinalIgnoreCase)) + { + arguments.Add("-segment_format_options"); + arguments.Add("movflags=+faststart"); + } + + arguments.AddRange( + [ + "-segment_start_number", "0", + "-reset_timestamps", "1", + "-segment_list", segmentListPath, + "-segment_list_type", "csv", + Path.Combine(temporaryPath, SEGMENT_FILE_NAME_PATTERN + format.FileExtension) + ]); + return arguments; + } + + /// + /// Parses the segment list ffmpeg wrote and turns it into the persisted index of the normalized audio. + /// + /// + /// Every line must describe a complete, readable segment. A malformed line is a hard failure instead of a skipped segment, because skipping a line + /// would produce an index over audio that has a hole in it. The index of a segment is taken from the number in its generated file name, and the + /// numbers must form a contiguous sequence starting at zero, so a missing segment can never be silently renumbered. A trailing segment with an empty + /// time range, which ffmpeg can emit when the last frame ends exactly on a segment boundary, is discarded instead of being indexed. The produced + /// duration is compared with the probed duration only for a shortfall, which is the truncation case; a production that is longer than the probe is + /// kept and logged, because a probe that estimates a duration from the bitrate can underestimate a variable bitrate file. The duration recorded in the + /// index is the produced end, rounded up to the next second, so the seek map of the cache entry always covers every produced segment. + /// + /// The opaque identifier of the cache entry. + /// The file into which ffmpeg wrote the list of produced segments. + /// The temporary directory the normalized audio was written into. + /// The track, the delivery decision and the quality cap the normalized audio was produced with. + /// The container and codec combination the normalized audio was produced in. + /// + /// An containing either the index of the produced segments, or an error message. + /// + private Result ParseSegmentIndex(string cacheId, string segmentListPath, string temporaryPath, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format) + { + if (!File.Exists(segmentListPath)) + return Errors.Playback.NormalizationFailed; + if (new FileInfo(segmentListPath).Length > MAX_SEGMENT_LIST_BYTES) + return Errors.Playback.NormalizationFailed; + + List segments = []; + try + { + foreach (string line in File.ReadLines(segmentListPath)) + { + if (string.IsNullOrWhiteSpace(line)) + continue; + + // A csv entry is "file,start,end". The file name is generated by this application and never contains a comma, so the last two commas always delimit the two times. + int endSeparatorIndex = line.LastIndexOf(','); + if (endSeparatorIndex <= 0) + return Errors.Playback.NormalizationFailed; + int startSeparatorIndex = line.LastIndexOf(',', endSeparatorIndex - 1); + if (startSeparatorIndex <= 0) + return Errors.Playback.NormalizationFailed; + + string fileName = Path.GetFileName(line[..startSeparatorIndex].Trim()); + if (!TryGetSegmentNumber(fileName, format.FileExtension, out int segmentNumber)) + return Errors.Playback.NormalizationFailed; + + string startText = line[(startSeparatorIndex + 1)..endSeparatorIndex].Trim(); + string endText = line[(endSeparatorIndex + 1)..].Trim(); + if (!decimal.TryParse(startText, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal startSeconds)) + return Errors.Playback.NormalizationFailed; + if (!decimal.TryParse(endText, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal endSeconds)) + return Errors.Playback.NormalizationFailed; + if (startSeconds < 0 || endSeconds < startSeconds) + return Errors.Playback.NormalizationFailed; + + FileInfo segmentFile = new(Path.Combine(temporaryPath, fileName)); + decimal durationSeconds = endSeconds - startSeconds; + // ffmpeg can append a final segment whose time range is empty when the last frame ends exactly on a segment boundary. That segment is + // discarded after the list is sorted, but a zero duration anywhere else, or a missing or empty segment that is supposed to carry audio, is a malformed production. + if (durationSeconds == 0) + { + segments.Add(new NormalizedTrackSegmentIndexDto(segmentNumber, startSeconds, 0, fileName, segmentFile.Exists ? segmentFile.Length : 0)); + continue; + } + if (!segmentFile.Exists || segmentFile.Length <= 0) + return Errors.Playback.NormalizationFailed; + + segments.Add(new NormalizedTrackSegmentIndexDto(segmentNumber, startSeconds, durationSeconds, fileName, segmentFile.Length)); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return Errors.Playback.NormalizationFailed; + } + + if (segments.Count == 0 || segments.Count > MAX_SEGMENT_COUNT) + return Errors.Playback.NormalizationFailed; + + // The number in the file name is the index, not the position of the line, and the numbers must be exactly the sequence from zero to count - 1. + // A gap, a duplicate or an out of order line would otherwise produce an index over audio that the player would map to the wrong time. + segments.Sort((left, right) => left.Index.CompareTo(right.Index)); + // The trailing segment with an empty time range carries no audio, so it is removed from the index and from the cache entry instead of being + // exposed as a segment that the player would seek to and find empty. + while (segments.Count > 0 && segments[^1].DurationSeconds == 0) + { + string trailingSegmentPath = Path.Combine(temporaryPath, segments[^1].FileName); + segments.RemoveAt(segments.Count - 1); + TryDeleteFile(trailingSegmentPath); + } + if (segments.Count == 0) + return Errors.Playback.NormalizationFailed; + + decimal previousEndSeconds = 0; + for (int position = 0; position < segments.Count; position++) + { + // A segment must start where the previous one ended, within the small tolerance of the csv times. Checking only that it does not start + // before the previous end would accept a leading gap or a gap in the middle of the track as long as the final end still matched. + decimal startDifferenceSeconds = segments[position].StartSeconds - previousEndSeconds; + if (segments[position].Index != position || + segments[position].DurationSeconds <= 0 || + startDifferenceSeconds < -SEGMENT_TIME_TOLERANCE_SECONDS || + startDifferenceSeconds > SEGMENT_TIME_TOLERANCE_SECONDS) + return Errors.Playback.NormalizationFailed; + previousEndSeconds = segments[position].StartSeconds + segments[position].DurationSeconds; + } + + // A shortfall is the truncation case this check exists for. A probe that estimates the duration from the bitrate can underestimate a variable + // bitrate file, so a production that is longer than the probe is accepted and logged instead of being rejected forever. + decimal expectedDurationSeconds = request.DurationInSeconds; + decimal durationToleranceSeconds = Math.Max(DURATION_TOLERANCE_MIN_SECONDS, expectedDurationSeconds * DURATION_TOLERANCE_RATIO); + if (previousEndSeconds < expectedDurationSeconds - durationToleranceSeconds) + return Errors.Playback.NormalizationFailed; + if (previousEndSeconds > expectedDurationSeconds + durationToleranceSeconds) + _logger.LogInformation("The normalized audio of track {TrackId} in cache entry {CacheId} is longer than the probed duration: produced {ProducedSeconds} seconds, probed {ExpectedSeconds} seconds. The production is kept because only a shortfall is treated as truncation.", request.TrackId, cacheId, previousEndSeconds, expectedDurationSeconds); + + // The index advertises the produced end, rounded up to the next second, instead of the probed duration. A probe can underestimate a variable + // bitrate file, and a seek map that is shorter than the audio would hide the tail of every segment after the underestimated end. + int producedDurationSeconds = previousEndSeconds >= int.MaxValue + ? int.MaxValue + : (int)Math.Ceiling(previousEndSeconds); + return new NormalizedTrackIndexDto(CACHE_INDEX_VERSION, request.TrackId, request.Mode, format.Container, format.Codec, request.SegmentDurationSeconds, producedDurationSeconds, segments); + } + + /// + /// Reads the persisted index of a cached normalized track, and validates that it is complete and that every segment it names still exists. + /// + /// The opaque identifier of the cache entry. + /// The index of the cached normalized track, when it could be read. + /// when a complete and consistent cache entry could be read, otherwise . + private bool TryReadIndex(string cacheId, out NormalizedTrackIndexDto? index) + { + index = null; + if (!TranscodingCacheCoordinator.IsValidCacheId(cacheId)) + return false; + + if (_cache.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex) && cachedIndex is not null) + { + index = cachedIndex; + return true; + } + + string cachePath = Path.Combine(_cacheRoot, cacheId); + string indexPath = Path.Combine(cachePath, CACHE_INDEX_FILE_NAME); + try + { + if (!File.Exists(indexPath)) + return false; + if (new FileInfo(indexPath).Length > MAX_CACHE_INDEX_BYTES) + return false; + + string indexJson = File.ReadAllText(indexPath); + NormalizedTrackIndexDto? storedIndex = JsonSerializer.Deserialize(indexJson, s_indexJsonOptions); + if (storedIndex is null || + storedIndex.Version != CACHE_INDEX_VERSION || + storedIndex.TrackId == Guid.Empty || + storedIndex.Mode is not (PlaybackDeliveryMode.Remux or PlaybackDeliveryMode.Transcode) || + storedIndex.SegmentDurationSeconds <= 0 || + storedIndex.DurationInSeconds <= 0 || + storedIndex.Segments is null || + storedIndex.Segments.Count == 0 || + storedIndex.Segments.Count > MAX_SEGMENT_COUNT || + !PlaybackFormatCatalog.FormatsByPair.TryGetValue(PlaybackFormatCatalog.BuildPairKey(storedIndex.Container, storedIndex.Codec), out NormalizedAudioFormatDto? format)) + return false; + + decimal previousEndSeconds = 0; + for (int position = 0; position < storedIndex.Segments.Count; position++) + { + NormalizedTrackSegmentIndexDto? segment = storedIndex.Segments[position]; + // The index must already be in playback order, name a supported generated file, describe a real segment and cover the track without a hole. + decimal startDifferenceSeconds = segment is null ? 0 : segment.StartSeconds - previousEndSeconds; + if (segment is null || + segment.Index != position || + !IsValidSegmentFileName(segment.FileName) || + !TryGetSegmentNumber(segment.FileName, format.FileExtension, out int segmentNumber) || + segmentNumber != position || + segment.StartSeconds < 0 || + segment.DurationSeconds <= 0 || + segment.Length <= 0 || + startDifferenceSeconds < -SEGMENT_TIME_TOLERANCE_SECONDS || + startDifferenceSeconds > SEGMENT_TIME_TOLERANCE_SECONDS || + !File.Exists(Path.Combine(cachePath, segment.FileName))) + return false; + previousEndSeconds = segment.StartSeconds + segment.DurationSeconds; + } + + // The advertised duration must cover the produced segments, otherwise a seek map built from the index would end before the audio does. New + // indexes are written with the produced end rounded up; an index that claims less is treated as a corrupt cache entry. + if (storedIndex.DurationInSeconds < previousEndSeconds) + return false; + + index = storedIndex; + _cache.SetIndex(cacheId, storedIndex); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) + { + return false; + } + } + + /// + /// Reads a cached normalized track, when a complete cache entry for it exists. + /// + /// The opaque identifier of the cache entry. + /// The cached normalized track, when it could be read. + /// when a complete cache entry could be read, otherwise . + private bool TryReadCachedTrack(string cacheId, out NormalizedTrackDto? normalizedTrack) + { + normalizedTrack = null; + if (!TryReadIndex(cacheId, out NormalizedTrackIndexDto? index) || index is null) + return false; + + normalizedTrack = CreateNormalizedTrackDto(cacheId, index); + return true; + } + + /// + /// Projects a validated cache index into the normalized track the caller receives. + /// + /// The opaque identifier of the cache entry that holds the normalized audio. + /// The validated index of the cache entry. + /// The normalized track described by the index. + private static NormalizedTrackDto CreateNormalizedTrackDto(string cacheId, NormalizedTrackIndexDto index) + { + return new NormalizedTrackDto( + index.TrackId, + cacheId, + index.Mode, + index.Container, + index.Codec, + index.SegmentDurationSeconds, + index.DurationInSeconds, + [.. index.Segments.Select(segment => new NormalizedTrackSegmentDto(segment.Index, segment.StartSeconds, segment.DurationSeconds, segment.Length))]); + } + + /// + /// Builds the opaque cache identifier of a normalized track, so that a replaced or changed source file, or another track, never reuses a stale entry. + /// + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The full path of the stored audio file of the track. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// The container and codec combination the normalized audio is produced in. + /// The opaque cache identifier. + private static string BuildCacheId(NormalizedTrackRequestDto request, string sourcePath, long sourceLength, DateTime sourceLastModifiedUtc, NormalizedAudioFormatDto format) + { + string identity = string.Join('\n', + [ + request.TrackId.ToString(), + sourcePath, + sourceLength.ToString(CultureInfo.InvariantCulture), + sourceLastModifiedUtc.Ticks.ToString(CultureInfo.InvariantCulture), + request.Mode.ToString(), + format.Container, + format.Codec, + request.SegmentDurationSeconds.ToString(CultureInfo.InvariantCulture), + request.DurationInSeconds.ToString(CultureInfo.InvariantCulture), + // The quality cap only changes the output of a lossy transcode. A remux only repackages the stored codec, and a lossless transcode is not + // capped, so including the quality for them would only create byte-identical entries that compete for the same cache budget. + request.Mode == PlaybackDeliveryMode.Transcode && !format.IsLossless ? request.Quality.ToString() : string.Empty + ]); + // The identity is hashed so the cache entry name is a fixed length file name even when the source path is long, and so the source path is not + // exposed by the directory listing of the cache. + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity))).ToLowerInvariant(); + } + + /// + /// Resolves the ffmpeg demuxer of a stored container, so that the input is never probed by content. + /// + /// The container of the stored audio file, as captured by the probe. + /// The ffmpeg demuxer of the container, when it is known. + /// when the container maps to a known demuxer, otherwise . + private static bool TryResolveSourceDemuxer(string? sourceContainer, out string sourceDemuxer) + { + sourceDemuxer = string.Empty; + if (string.IsNullOrWhiteSpace(sourceContainer)) + return false; + if (!s_sourceDemuxers.TryGetValue(sourceContainer.Trim(), out string? demuxer) || string.IsNullOrEmpty(demuxer)) + return false; + sourceDemuxer = demuxer; + return true; + } + + /// + /// Gets the bitrate cap, in kbps, of a streaming quality setting. + /// + /// The streaming quality cap of the current user. + /// The bitrate cap in kbps. uses the server default cap. + private static int GetTargetBitrateKbps(PlaybackStreamingQuality quality) + { + return quality switch + { + PlaybackStreamingQuality.Low => 96, + PlaybackStreamingQuality.Medium => 160, + PlaybackStreamingQuality.High => 320, + _ => AUTO_TRANSCODE_BITRATE_KBPS + }; + } + + /// + /// Estimates the size of the normalized audio, so that the cache is trimmed before a job starts instead of only after it finished. + /// + /// + /// A lossless delivery is estimated from the sample rate, the channel count and the bit depth of the stored audio, because a hi-res track can be + /// several times larger than the uncompressed stereo audio at 44.1 kHz and 16 bits. A FLAC stream is compressed, so its initial estimate is a fraction + /// of the uncompressed size. A remux of a lossy codec is estimated from the stored audio bitrate, not from the length of the source container, so a + /// large video file with a small audio stream is not rejected as too big for the cache. The cache monitor grows the reservation when the actual output needs more room. + /// + /// The delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The estimated size of the normalized audio, in bytes. + private static long EstimateOutputSize(NormalizedTrackRequestDto request, NormalizedAudioFormatDto format) + { + if (format.IsLossless) + { + int sampleRate = request.SampleRate > 0 ? request.SampleRate : DEFAULT_SAMPLE_RATE; + int channelCount = request.Channels > 0 ? request.Channels : DEFAULT_CHANNEL_COUNT; + // The PCM encoder of the pipeline writes 16 bit samples, while the FLAC encoder keeps the sample format of the source, so the delivered + // bit depth is used instead of the stored one for PCM. The FLAC estimate is a fraction of the uncompressed size, because the stream is compressed. + int bitDepth = string.Equals(format.Container, "WAV", StringComparison.OrdinalIgnoreCase) + ? DEFAULT_BIT_DEPTH + : request.BitDepth is > 0 ? request.BitDepth.Value : DEFAULT_BIT_DEPTH; + long uncompressedBytesPerSecond = (long)sampleRate * channelCount * bitDepth / 8; + decimal compressionRatio = string.Equals(format.Container, "FLAC", StringComparison.OrdinalIgnoreCase) ? FLAC_COMPRESSION_RATIO : 1m; + return Math.Max((long)(uncompressedBytesPerSecond * request.DurationInSeconds * compressionRatio), 1); + } + + if (request.Mode == PlaybackDeliveryMode.Remux) + { + int sourceBitrateKbps = request.Bitrate is > 0 ? request.Bitrate.Value : DEFAULT_SOURCE_BITRATE_KBPS; + decimal estimatedBytes = request.DurationInSeconds * sourceBitrateKbps * 1000m / 8m * REMUX_SIZE_MARGIN; + return Math.Max((long)estimatedBytes, 1); + } + + int bitrateKbps = GetTargetBitrateKbps(request.Quality); + return Math.Max((long)request.DurationInSeconds * bitrateKbps * 1000 / 8, 1); + } + + /// + /// Checks whether a generated segment file name has the expected prefix and extension, and extracts the segment number from it. + /// + /// The file name of the segment. + /// The expected file extension of the segment, including the leading dot. + /// The number encoded in the file name, when the name is valid. + /// when the file name is a valid generated segment name, otherwise . + private static bool TryGetSegmentNumber(string fileName, string fileExtension, out int segmentNumber) + { + segmentNumber = -1; + if (string.IsNullOrEmpty(fileName) || + !fileName.StartsWith(SEGMENT_FILE_PREFIX, StringComparison.Ordinal) || + !fileName.EndsWith(fileExtension, StringComparison.Ordinal)) + return false; + + string numberText = fileName[SEGMENT_FILE_PREFIX.Length..^fileExtension.Length]; + return numberText.Length > 0 && + int.TryParse(numberText, NumberStyles.None, CultureInfo.InvariantCulture, out segmentNumber) && + segmentNumber >= 0; + } + + /// + /// Checks whether a value is a plain file name of a produced segment. + /// + /// The value to check. + /// when the value is a plain segment file name, otherwise . + private static bool IsValidSegmentFileName(string fileName) + { + return !string.IsNullOrWhiteSpace(fileName) && + string.Equals(fileName, Path.GetFileName(fileName), StringComparison.Ordinal) && + !fileName.Contains(Path.DirectorySeparatorChar) && + !fileName.Contains(Path.AltDirectorySeparatorChar); + } + + /// + /// Monitors the size of the temporary directory of a running job and keeps its cache reservation in step with the bytes it has actually written. + /// + /// The opaque identifier of the cache entry. + /// The Id of the track whose audio is normalized. + /// The tracker of the output size of the job. + /// The capacity the job reserved in the cache. + /// The ffmpeg process of the job. + /// Cancellation token that can be used to stop the execution. + /// when the job was stopped because it could not reserve enough cache capacity, otherwise . + private async Task MonitorOutputSizeAsync(string cacheId, Guid trackId, TranscodingOutputSizeTracker outputSizeTracker, TranscodingCacheReservation reservation, Process process, CancellationToken cancellationToken) + { + try + { + while (true) + { + await Task.Delay(CACHE_SIZE_MONITOR_INTERVAL_MILLISECONDS, cancellationToken).ConfigureAwait(false); + long actualBytes = outputSizeTracker.GetCurrentSize(); + if (!reservation.TryUpdate(actualBytes, _settings.MaxCacheBytes, _evictionGracePeriod)) + { + _logger.LogWarning("A normalization job for track {TrackId} in cache entry {CacheId} could not reserve enough space in the normalized audio cache and was stopped.", trackId, cacheId); + KillProcess(process); + return true; + } + } + } + catch (OperationCanceledException) + { + return false; + } + } + + /// + /// Waits for the bounded standard error of a finished process, without pinning the job when the pipe never closes. + /// + /// The task that reads the bounded standard error of the process. + /// The bounded standard error, or an empty string when the pipe did not close within the bounded wait. + private static async Task AwaitStandardErrorAsync(Task standardErrorTask) + { + try + { + return await standardErrorTask.WaitAsync(TimeSpan.FromSeconds(PROCESS_EXIT_TIMEOUT_SECONDS)).ConfigureAwait(false); + } + catch (TimeoutException) + { + // A kill that did not take effect leaves the pipe open. The job is finished without a diagnostic instead of holding a job slot forever; the + // read task ends when the process is disposed and its standard error stream is closed. + return string.Empty; + } + } + + /// + /// Reads the standard error of a running process while keeping only its last few kilobytes, so a crafted input cannot make the server buffer an unbounded diagnostic string over the whole job timeout. + /// + /// The standard error stream of the process. + /// The bounded tail of the standard error of the process. + private static async Task ReadBoundedStandardErrorAsync(StreamReader standardError) + { + char[] buffer = new char[4096]; + StringBuilder boundedStandardError = new(); + try + { + int read; + while ((read = await standardError.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) + { + boundedStandardError.Append(buffer, 0, read); + if (boundedStandardError.Length > MAX_STANDARD_ERROR_CHARACTERS * 2) + boundedStandardError.Remove(0, boundedStandardError.Length - MAX_STANDARD_ERROR_CHARACTERS); + } + } + catch (Exception exception) when (exception is IOException or ObjectDisposedException) + { + // The pipe is closed when the process is killed; the bytes read so far are still the useful diagnostic tail. + } + + if (boundedStandardError.Length > MAX_STANDARD_ERROR_CHARACTERS) + boundedStandardError.Remove(0, boundedStandardError.Length - MAX_STANDARD_ERROR_CHARACTERS); + return boundedStandardError.ToString(); + } + + /// + /// Replaces an absolute source path in a diagnostic message with a placeholder, so the path is not written to the application log. + /// + /// The diagnostic message. + /// The path to redact, or when there is none. + /// The diagnostic message with the path replaced. + private static string RedactPath(string diagnostic, string? path) + { + if (string.IsNullOrWhiteSpace(path)) + return diagnostic; + return diagnostic.Replace(path, "[source]", StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes a completed production from the shared registry, unless a newer production replaced it. + /// + /// The cache root and cache entry the production belongs to. + /// The production that completed. + private static void RemoveNormalizationJob((string CacheRoot, string CacheId) normalizationJobKey, Lazy>> normalizationJob) + { + if (s_normalizationJobs.TryGetValue(normalizationJobKey, out Lazy>>? currentJob) && ReferenceEquals(currentJob, normalizationJob)) + s_normalizationJobs.TryRemove(normalizationJobKey, out _); + } + + /// + /// Deletes a file, ignoring a file that is already gone or cannot be deleted. + /// + /// The file to delete. + private static void TryDeleteFile(string filePath) + { + try + { + if (File.Exists(filePath)) + File.Delete(filePath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // The trailing empty segment is not indexed, so a failed deletion only leaves a small unreferenced file in the cache entry. + } + } + + /// + /// Stops a child process and its descendants without waiting for it, so a cancellation callback is never blocked; the caller that awaits the process observes its exit. + /// + /// The process to stop. + private void KillProcess(Process process) + { + try + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + } + catch (Exception exception) when (exception is InvalidOperationException or NotSupportedException or Win32Exception) + { + _logger.LogDebug(exception, "The audio transcoder process could not be stopped."); + } + } + + /// + /// Stops every child process that is still running when the application exits, and cancels the productions that are still waiting for a job slot. + /// + /// The source of the event. + /// The event data. + private void OnApplicationStopping(object? sender, EventArgs eventArguments) + { + _shutdownCancellation.Cancel(); + foreach (Process process in _runningProcesses.Values) + KillProcess(process); + } + + /// + /// Releases the resources of the service when its host is disposed, including the process exit subscription that would otherwise keep it alive. + /// + /// + /// The cancellation source, the job slots and the cache coordinator are process lifetime resources that a production uses until it leaves. Shutdown + /// cancels and kills first, then waits a bounded time for every admitted production to leave before disposing them, so a production that is finishing + /// during shutdown still reports its Result instead of faulting on a disposed primitive or re-registering into a released coordinator. If the drain + /// times out the resources are intentionally left undisposed: the process is exiting and faulting the in-flight task would be worse. + /// + public void Dispose() + { + lock (_lifecycleSync) + { + if (_isDisposed) + return; + _isDisposed = true; + } + AppDomain.CurrentDomain.ProcessExit -= OnApplicationStopping; + OnApplicationStopping(this, EventArgs.Empty); + if (!_productionsDrained.Wait(TimeSpan.FromSeconds(PRODUCTION_DRAIN_TIMEOUT_SECONDS))) + { + _logger.LogWarning("The normalized audio productions did not drain within {DrainTimeoutSeconds} seconds during shutdown. The process lifetime resources are left undisposed.", PRODUCTION_DRAIN_TIMEOUT_SECONDS); + return; + } + _cache.Release(); + _jobSlots.Dispose(); + _shutdownCancellation.Dispose(); + _productionsDrained.Dispose(); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs new file mode 100644 index 00000000..7eff1ad3 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs @@ -0,0 +1,591 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Coordinates the process wide size accounting, eviction and reader protection of the normalized audio cache. +/// +/// +/// Every cached entry and every running normalization job of a cache root is accounted for under one lock, so the cache size limit is a global limit +/// instead of a per job limit. An entry is protected from eviction while a reader holds a lease on it, and for a grace period after it was produced or +/// last served, so an entry that a request is about to read is never deleted by another job. Replacing and registering a produced entry is atomic under +/// the same lock, so an eviction can never delete a freshly published entry. Directories are never deleted under the lock: an entry that is evicted or +/// replaced is renamed to a unique tombstone under the lock and deleted by a background sweeper, so serving a segment or opening a manifest never waits +/// for a recursive delete. The size limit is enforced against live entries: a tombstone occupies disk until the sweeper removes it. The coordinator is +/// shared by every service instance of the process that uses the same cache root. +/// +internal sealed class TranscodingCacheCoordinator +{ + private static readonly ConcurrentDictionary s_coordinators = new(StringComparer.Ordinal); + private static readonly Lock s_registrySync = new(); + + private readonly Lock _sync = new(); + private readonly string _cacheRoot; + private readonly Dictionary _entries = new(StringComparer.Ordinal); + private readonly Dictionary _reservations = new(StringComparer.Ordinal); + private readonly Dictionary _readerLeaseCounts = new(StringComparer.Ordinal); + // Read and written by request threads without _sync, so the index cache is a concurrent dictionary while the accounting dictionaries are guarded by _sync. + private readonly ConcurrentDictionary _indexCache = new(StringComparer.Ordinal); + // Entries that were over capacity but still leased. The last lease release hands them to the sweeper. + private readonly HashSet _pendingEvictions = new(StringComparer.Ordinal); + // Tombstones are consumed by one background reader, so a recursive delete never runs under _sync. + private readonly Channel _deletionQueue = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); + // The value is unused. Lazy is the once-only gate: the first caller runs the cache walk outside _sync and every other caller waits for it. + private readonly Lazy _initialization; + private int _referenceCount; + + /// + /// Initializes a new instance of the class. + /// + /// The absolute path of the cache root the coordinator accounts for. + private TranscodingCacheCoordinator(string cacheRoot) + { + _cacheRoot = cacheRoot; + _initialization = new Lazy(InitializeCore, LazyThreadSafetyMode.ExecutionAndPublication); + _ = Task.Run(ProcessDeletionQueueAsync); + } + + /// + /// Acquires the coordinator of a cache root, which is shared by every service instance of the process that uses the same root. + /// + /// The absolute path of the cache root. + /// The coordinator of the cache root. The caller must call when it no longer uses it. + public static TranscodingCacheCoordinator AcquireForRoot(string cacheRoot) + { + string normalizedRoot = Path.GetFullPath(cacheRoot); + lock (s_registrySync) + { + // The registry is process wide because two service instances that use the same cache root must share the same size and lease accounting. + // The reference count keeps the coordinator alive until the last service instance is disposed. + if (!s_coordinators.TryGetValue(normalizedRoot, out TranscodingCacheCoordinator? coordinator)) + { + coordinator = new TranscodingCacheCoordinator(normalizedRoot); + s_coordinators[normalizedRoot] = coordinator; + } + coordinator._referenceCount++; + return coordinator; + } + } + + /// + /// Releases the caller's use of the coordinator, removing it from the process registry when the last caller releases it. + /// + public void Release() + { + bool isUnused; + lock (s_registrySync) + { + if (_referenceCount > 0) + _referenceCount--; + isUnused = _referenceCount == 0; + if (isUnused) + s_coordinators.Remove(_cacheRoot, out _); + } + + if (!isUnused) + return; + lock (_sync) + { + _entries.Clear(); + _reservations.Clear(); + _readerLeaseCounts.Clear(); + _pendingEvictions.Clear(); + _indexCache.Clear(); + } + // The sweeper drains the tombstones it already owns and then stops. A deletion that is still in flight is finished, and a tombstone left by a + // deletion that cannot complete is removed by the startup cleanup. + _deletionQueue.Writer.TryComplete(); + } + + /// + /// Checks whether a value is a well formed opaque cache identifier. + /// + /// The value to check. + /// when the value is a well formed cache identifier, otherwise . + public static bool IsValidCacheId(string cacheId) + { + return TranscodingCachePaths.IsValidCacheId(cacheId); + } + + /// + /// Reserves capacity for the output of a normalization job, after evicting the entries that may be evicted to make room for it. + /// + /// The estimated size of the output of the job, in bytes. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// The reservation of the job, when capacity could be reserved. + /// when capacity could be reserved, otherwise . + public bool TryReserve(long requestedBytes, long maxCacheBytes, TimeSpan gracePeriod, out TranscodingCacheReservation? reservation) + { + reservation = null; + if (requestedBytes <= 0 || maxCacheBytes <= 0) + return false; + EnsureInitialized(); + lock (_sync) + { + long currentSize = GetTotalSize(); + if (requestedBytes > maxCacheBytes || !TryMakeRoom(requestedBytes, currentSize, excludedCacheId: null, maxCacheBytes, gracePeriod)) + return false; + + string reservationId = Guid.NewGuid().ToString("N"); + _reservations[reservationId] = requestedBytes; + reservation = new TranscodingCacheReservation(this, reservationId); + return true; + } + } + + /// + /// Grows the reservation of a running job to the number of bytes it has actually written, after evicting entries when it has to grow. + /// + /// The identifier of the reservation. + /// The number of bytes the job has actually written, in bytes. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the reservation covers the actual size, otherwise . + public bool TryGrow(string reservationId, long actualBytes, long maxCacheBytes, TimeSpan gracePeriod) + { + if (actualBytes < 0) + return false; + EnsureInitialized(); + lock (_sync) + { + if (!_reservations.TryGetValue(reservationId, out long reservedBytes)) + return false; + // A reservation is never shrunk while the job runs: a size of zero read before the first byte is written, or a size that fluctuates + // while a file is being appended, must not hand the reserved capacity to another job that the running job then cannot reclaim. + if (actualBytes <= reservedBytes) + return true; + if (actualBytes > maxCacheBytes) + return false; + + long currentSize = GetTotalSize(); + long requiredAdditionalBytes = actualBytes - reservedBytes; + if (!TryMakeRoom(requiredAdditionalBytes, currentSize, excludedCacheId: null, maxCacheBytes, gracePeriod)) + return false; + + _reservations[reservationId] = actualBytes; + return true; + } + } + + /// + /// Publishes the cache entry a finished job produced, replacing any previous entry for the same identifier, and enforces the cache size limit. + /// + /// The identifier of the reservation. + /// The identifier of the produced cache entry. + /// The temporary directory that holds the complete produced entry. + /// The total size of the produced cache entry, in bytes. + /// The validated index of the produced cache entry. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// + /// when the produced entry still exceeds the cache limit after every unprotected entry was detached, so it is kept readable and + /// becomes eligible for eviction later. The caller should report the production as successful and log the over-budget state. + /// + /// + /// when a reader still holds the previous entry of the same cache identifier, so the replacement was not attempted and the + /// caller should report a retryable failure instead of a production failure. + /// + /// + /// when the produced entry is readable and may be served, otherwise when it was not published. + /// + public bool TryPublish(string reservationId, string cacheId, string temporaryPath, long size, NormalizedTrackIndexDto index, long maxCacheBytes, TimeSpan gracePeriod, out bool isKeptOverCapacity, out bool isEntryInUse) + { + isKeptOverCapacity = false; + isEntryInUse = false; + EnsureInitialized(); + lock (_sync) + { + // The reservation is consumed whether or not the entry is published, because the caller never releases it after this call. + _reservations.Remove(reservationId); + + // The previous directory cannot be replaced while a reader holds it on every platform, so the production is reported as retryable and the + // previous entry stays intact. The next request retries the production after the reader is gone. + if (IsLeased(cacheId)) + { + isEntryInUse = true; + return false; + } + + string cachePath = Path.Combine(_cacheRoot, cacheId); + if (_entries.TryGetValue(cacheId, out TranscodingCacheEntryDto? existingEntry)) + { + if (!TryDetachEntryForDeletion(cacheId, existingEntry)) + return false; + } + else if (!TryMoveToDeletion(cachePath)) + return false; + + _indexCache.TryRemove(cacheId, out _); + _pendingEvictions.Remove(cacheId); + try + { + Directory.Move(temporaryPath, cachePath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + // Defense in depth against a directory that an external actor removed between the move and the registration. + if (!Directory.Exists(cachePath)) + return false; + + _entries[cacheId] = new TranscodingCacheEntryDto(cachePath, size, DateTime.UtcNow, DateTime.UtcNow); + _indexCache[cacheId] = index; + + long currentSize = GetTotalSize(); + if (currentSize <= maxCacheBytes) + return true; + if (TryMakeRoom(0, currentSize, cacheId, maxCacheBytes, gracePeriod)) + return true; + + // The entry does not fit even after every other unprotected entry was detached. It is kept readable and becomes eligible for eviction once + // its grace period ends, so a production that already consumed a full job is not discarded because the estimate was exceeded. + isKeptOverCapacity = true; + return true; + } + } + + /// + /// Releases the reservation of a job that did not produce a cache entry. + /// + /// The identifier of the reservation. + public void ReleaseReservation(string reservationId) + { + lock (_sync) + _reservations.Remove(reservationId); + } + + /// + /// Records that a cache entry was served, so that the least recently used eviction and the eviction grace period keep it for longer. + /// + /// The identifier of the cache entry. + /// + /// The minimum interval between two writes of the last use time. A value smaller than the eviction grace period keeps an actively used entry protected. + /// + public void Touch(string cacheId, TimeSpan throttleInterval) + { + EnsureInitialized(); + lock (_sync) + { + if (!_entries.TryGetValue(cacheId, out TranscodingCacheEntryDto? entry)) + return; + + DateTime nowUtc = DateTime.UtcNow; + // A stream opens a segment every few seconds, so writing the last use time on every request would needlessly serialize the coordinator. + if (nowUtc - entry.LastUsedUtc < throttleInterval) + return; + _entries[cacheId] = entry with { LastUsedUtc = nowUtc }; + } + } + + /// + /// Acquires a lease that prevents a cache entry from being evicted while a reader holds it. + /// + /// The identifier of the cache entry. + /// The lease, which must be disposed when the reader is done with the entry. + public TranscodingCacheReaderLease AcquireReaderLease(string cacheId) + { + EnsureInitialized(); + lock (_sync) + _readerLeaseCounts[cacheId] = _readerLeaseCounts.TryGetValue(cacheId, out int leaseCount) ? leaseCount + 1 : 1; + return new TranscodingCacheReaderLease(this, cacheId); + } + + /// + /// Gets the validated index of a cache entry, when it was already read and validated by this process. + /// + /// The identifier of the cache entry. + /// The validated index of the cache entry, when it is cached. + /// when the validated index is cached, otherwise . + public bool TryGetIndex(string cacheId, out NormalizedTrackIndexDto? index) + { + return _indexCache.TryGetValue(cacheId, out index); + } + + /// + /// Caches the validated index of a cache entry, so serving its segments does not re-read and re-validate the whole index on every request. + /// + /// The identifier of the cache entry. + /// The validated index of the cache entry. + public void SetIndex(string cacheId, NormalizedTrackIndexDto index) + { + _indexCache[cacheId] = index; + } + + /// + /// Releases a lease that a reader held on a cache entry. + /// + /// The identifier of the cache entry. + internal void ReleaseReaderLease(string cacheId) + { + lock (_sync) + { + if (!_readerLeaseCounts.TryGetValue(cacheId, out int leaseCount)) + return; + if (leaseCount > 1) + { + _readerLeaseCounts[cacheId] = leaseCount - 1; + return; + } + + _readerLeaseCounts.Remove(cacheId); + // An entry that could not be evicted while a reader was using it is detached only after the last reader is gone. The actual deletion is + // performed by the sweeper, outside this lock, so releasing a segment stream never waits for a recursive delete. + if (_pendingEvictions.Contains(cacheId) && _entries.TryGetValue(cacheId, out TranscodingCacheEntryDto? entry)) + { + _pendingEvictions.Remove(cacheId); + if (!TryDetachEntryForDeletion(cacheId, entry)) + _pendingEvictions.Add(cacheId); + } + } + } + + /// + /// Gets the total size of a directory, in bytes, without letting a file that disappears mid-walk discard the rest of the measurement. + /// + /// The directory whose size is computed. + /// The total size of the directory, in bytes. + internal static long GetDirectorySize(string directoryPath) + { + long size = 0; + Stack pendingDirectories = new(); + pendingDirectories.Push(directoryPath); + while (pendingDirectories.Count > 0) + { + string currentDirectory = pendingDirectories.Pop(); + try + { + using (IEnumerator fileEnumerator = Directory.EnumerateFiles(currentDirectory).GetEnumerator()) + { + while (true) + { + bool hasNextFile; + try + { + hasNextFile = fileEnumerator.MoveNext(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + break; + } + if (!hasNextFile) + break; + + try + { + size += new FileInfo(fileEnumerator.Current).Length; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A file that disappears between enumeration and its size read is not counted; the walk continues with the next one. + } + } + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A directory that cannot be opened is skipped; the rest of the cache is still measured. + } + + try + { + using (IEnumerator directoryEnumerator = Directory.EnumerateDirectories(currentDirectory).GetEnumerator()) + { + while (true) + { + bool hasNextDirectory; + try + { + hasNextDirectory = directoryEnumerator.MoveNext(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + break; + } + if (!hasNextDirectory) + break; + pendingDirectories.Push(directoryEnumerator.Current); + } + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A directory that cannot be enumerated is skipped; the rest of the cache is still measured. + } + } + return size; + } + + /// + /// Runs the once-only initialization of the entries that already exist in the cache root, outside the coordinator lock. + /// + private void EnsureInitialized() + { + _ = _initialization.Value; + } + + /// + /// Reads the entries that already exist in the cache root, so a cache that survived a restart is still accounted for. + /// + /// when the accounting was populated. + /// + /// The walk of the cache root happens outside the coordinator lock, because it stats every file of every entry. The result is published under the lock, + /// so a request never blocks a manifest or a segment open behind the walk. + /// + private bool InitializeCore() + { + Dictionary entries = new(StringComparer.Ordinal); + List tombstones = []; + if (Directory.Exists(_cacheRoot)) + { + try + { + foreach (string directoryPath in Directory.EnumerateDirectories(_cacheRoot)) + { + string cacheId = Path.GetFileName(directoryPath); + if (cacheId.StartsWith(TranscodingCachePaths.DELETION_DIRECTORY_PREFIX, StringComparison.Ordinal)) + { + // A tombstone left by a previous coordinator of the same process is handed to the sweeper instead of being accounted for. + tombstones.Add(directoryPath); + continue; + } + if (!IsValidCacheId(cacheId)) + continue; + entries[cacheId] = new TranscodingCacheEntryDto(directoryPath, GetDirectorySize(directoryPath), Directory.GetLastWriteTimeUtc(directoryPath), DateTime.MinValue); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A cache that cannot be enumerated is treated as empty for this run instead of being retried on every request. + } + } + + lock (_sync) + foreach (KeyValuePair entry in entries) + _entries[entry.Key] = entry.Value; + foreach (string tombstonePath in tombstones) + _deletionQueue.Writer.TryWrite(tombstonePath); + return true; + } + + /// + /// Gets the combined size of the cached entries and the reservations of the running jobs, in bytes. + /// + /// The combined size of the cached entries and the reservations, in bytes. + private long GetTotalSize() + { + long entriesSize = _entries.Values.Sum(entry => entry.Size); + long reservationsSize = _reservations.Values.Sum(); + return entriesSize + reservationsSize; + } + + /// + /// Detaches the least recently used unprotected entries until the required number of bytes fits under the cache size limit. + /// + /// The number of additional bytes that must fit. + /// The current combined size of the entries and reservations, in bytes. + /// The cache entry that must never be evicted by this pass, or when none is excluded. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the required number of bytes fits, otherwise . + private bool TryMakeRoom(long requiredBytes, long currentSize, string? excludedCacheId, long maxCacheBytes, TimeSpan gracePeriod) + { + if (currentSize + requiredBytes <= maxCacheBytes) + return true; + + DateTime nowUtc = DateTime.UtcNow; + foreach (TranscodingCacheEntryDto entry in _entries.Values.OrderBy(entry => entry.LastUsedUtc).ToList()) + { + string cacheId = Path.GetFileName(entry.Path); + if (string.Equals(cacheId, excludedCacheId, StringComparison.Ordinal)) + continue; + + DateTime lastActivityUtc = entry.LastUsedUtc > entry.ProducedAtUtc ? entry.LastUsedUtc : entry.ProducedAtUtc; + if (nowUtc - lastActivityUtc < gracePeriod) + continue; + if (IsLeased(cacheId)) + { + // A reader holds the entry, so it is detached when the last lease is released instead of failing the deletion under the lock. + _pendingEvictions.Add(cacheId); + continue; + } + if (!TryDetachEntryForDeletion(cacheId, entry)) + continue; + currentSize -= entry.Size; + if (currentSize + requiredBytes <= maxCacheBytes) + return true; + } + return currentSize + requiredBytes <= maxCacheBytes; + } + + /// + /// Checks whether a reader currently holds a cache entry. + /// + /// The identifier of the cache entry. + /// when at least one reader holds the entry, otherwise . + private bool IsLeased(string cacheId) + { + return _readerLeaseCounts.TryGetValue(cacheId, out int leaseCount) && leaseCount > 0; + } + + /// + /// Removes an entry from the cache accounting and schedules its directory for deletion. + /// + /// The identifier of the cache entry. + /// The entry to detach. + /// when the entry was detached, otherwise when its directory could not be renamed. + private bool TryDetachEntryForDeletion(string cacheId, TranscodingCacheEntryDto entry) + { + if (!TryMoveToDeletion(entry.Path)) + return false; + _entries.Remove(cacheId); + _pendingEvictions.Remove(cacheId); + _indexCache.TryRemove(cacheId, out _); + return true; + } + + /// + /// Moves a directory out of the live cache and schedules it for deletion. + /// + /// The directory to detach. + /// when the directory was detached or no longer exists, otherwise . + private bool TryMoveToDeletion(string directoryPath) + { + if (!Directory.Exists(directoryPath)) + return true; + string deletionPath = Path.Combine(_cacheRoot, TranscodingCachePaths.DELETION_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N")); + try + { + // A rename is a metadata operation, so it stays fast under the lock even for an entry with thousands of segments. + Directory.Move(directoryPath, deletionPath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + // A tombstone that cannot be enqueued because the coordinator was released is removed by the startup cleanup. + _deletionQueue.Writer.TryWrite(deletionPath); + return true; + } + + /// + /// Deletes the directories that were detached from the cache. + /// + private async Task ProcessDeletionQueueAsync() + { + await foreach (string directoryPath in _deletionQueue.Reader.ReadAllAsync().ConfigureAwait(false)) + TranscodingCachePaths.TryDeleteDirectory(directoryPath); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs new file mode 100644 index 00000000..a840329e --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs @@ -0,0 +1,220 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// A read stream over a cached segment that keeps the reader lease of its cache entry until the stream is disposed. +/// +internal sealed class TranscodingCacheLeaseStream : Stream +{ + private readonly Stream _innerStream; + private readonly TranscodingCacheReaderLease _lease; + private bool _isDisposed; + + /// + /// Gets whether the stream supports reading. + /// + public override bool CanRead => _innerStream.CanRead; + + /// + /// Gets whether the stream supports seeking. + /// + public override bool CanSeek => _innerStream.CanSeek; + + /// + /// Gets whether the stream supports writing. + /// + public override bool CanWrite => _innerStream.CanWrite; + + /// + /// Gets the length of the stream, in bytes. + /// + public override long Length => _innerStream.Length; + + /// + /// Gets or sets the position within the stream. + /// + public override long Position + { + get { return _innerStream.Position; } + set { _innerStream.Position = value; } + } + + /// + /// Initializes a new instance of the class. + /// + /// The stream over the cached segment. + /// The reader lease that protects the cache entry of the segment. + internal TranscodingCacheLeaseStream(Stream innerStream, TranscodingCacheReaderLease lease) + { + _innerStream = innerStream; + _lease = lease; + } + + /// + /// Clears the buffers of the stream. + /// + public override void Flush() + { + _innerStream.Flush(); + } + + /// + /// Reads a block of bytes from the stream. + /// + /// The buffer to read into. + /// The offset in the buffer at which to start writing. + /// The maximum number of bytes to read. + /// The number of bytes read. + public override int Read(byte[] buffer, int offset, int count) + { + return _innerStream.Read(buffer, offset, count); + } + + /// + /// Reads a block of bytes from the stream. + /// + /// The buffer to read into. + /// The number of bytes read. + public override int Read(Span buffer) + { + return _innerStream.Read(buffer); + } + + /// + /// Reads a block of bytes from the stream asynchronously. + /// + /// The buffer to read into. + /// The offset in the buffer at which to start writing. + /// The maximum number of bytes to read. + /// Cancellation token that can be used to stop the execution. + /// The number of bytes read. + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return _innerStream.ReadAsync(buffer, offset, count, cancellationToken); + } + + /// + /// Reads a block of bytes from the stream asynchronously. + /// + /// The buffer to read into. + /// Cancellation token that can be used to stop the execution. + /// The number of bytes read. + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + return _innerStream.ReadAsync(buffer, cancellationToken); + } + + /// + /// Sets the position within the stream. + /// + /// The offset relative to . + /// The reference point used to obtain the new position. + /// The new position within the stream. + public override long Seek(long offset, SeekOrigin origin) + { + return _innerStream.Seek(offset, origin); + } + + /// + /// Sets the length of the stream. + /// + /// The new length of the stream, in bytes. + public override void SetLength(long value) + { + _innerStream.SetLength(value); + } + + /// + /// Writes a block of bytes to the stream. + /// + /// The buffer to write from. + /// The offset in the buffer at which to start reading. + /// The number of bytes to write. + public override void Write(byte[] buffer, int offset, int count) + { + _innerStream.Write(buffer, offset, count); + } + + /// + /// Writes a block of bytes to the stream. + /// + /// The buffer to write from. + public override void Write(ReadOnlySpan buffer) + { + _innerStream.Write(buffer); + } + + /// + /// Writes a block of bytes to the stream asynchronously. + /// + /// The buffer to write from. + /// The offset in the buffer at which to start reading. + /// The number of bytes to write. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous write operation. + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return _innerStream.WriteAsync(buffer, offset, count, cancellationToken); + } + + /// + /// Writes a block of bytes to the stream asynchronously. + /// + /// The buffer to write from. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous write operation. + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + return _innerStream.WriteAsync(buffer, cancellationToken); + } + + /// + /// Releases the inner stream and the reader lease. + /// + /// Whether the method is called from the method. + protected override void Dispose(bool disposing) + { + if (disposing && !_isDisposed) + { + _isDisposed = true; + try + { + _innerStream.Dispose(); + } + finally + { + // The lease must be released even when disposing the stream throws, otherwise the entry stays protected from eviction forever. + _lease.Dispose(); + } + } + base.Dispose(disposing); + } + + /// + /// Releases the inner stream and the reader lease asynchronously. + /// + /// A task that represents the asynchronous dispose operation. + public override async ValueTask DisposeAsync() + { + if (!_isDisposed) + { + _isDisposed = true; + try + { + await _innerStream.DisposeAsync().ConfigureAwait(false); + } + finally + { + // The lease must be released even when disposing the stream throws, otherwise the entry stays protected from eviction forever. + _lease.Dispose(); + } + } + await base.DisposeAsync().ConfigureAwait(false); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs new file mode 100644 index 00000000..070246f6 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents a reader's lease on a cache entry, which keeps the entry from being evicted until the lease is released. +/// +[DebuggerDisplay("CacheId: {_cacheId}")] +internal sealed class TranscodingCacheReaderLease : IDisposable +{ + private readonly TranscodingCacheCoordinator _coordinator; + private readonly string _cacheId; + private bool _isDisposed; + + /// + /// Initializes a new instance of the class. + /// + /// The coordinator that accounts for the lease. + /// The identifier of the cache entry the lease holds. + internal TranscodingCacheReaderLease(TranscodingCacheCoordinator coordinator, string cacheId) + { + _coordinator = coordinator; + _cacheId = cacheId; + } + + /// + /// Releases the lease, so the cache entry may be evicted again. + /// + public void Dispose() + { + if (_isDisposed) + return; + _isDisposed = true; + _coordinator.ReleaseReaderLease(_cacheId); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs new file mode 100644 index 00000000..6e7114f1 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents the capacity a running normalization job reserved in the normalized audio cache, until it either produces an entry or is aborted. +/// +[DebuggerDisplay("Id: {Id}")] +internal sealed class TranscodingCacheReservation : IDisposable +{ + private readonly TranscodingCacheCoordinator _coordinator; + private bool _isCompleted; + private bool _isDisposed; + + /// + /// Gets the identifier of the reservation. + /// + internal string Id { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The coordinator that accounts for the reservation. + /// The identifier of the reservation. + internal TranscodingCacheReservation(TranscodingCacheCoordinator coordinator, string id) + { + _coordinator = coordinator; + Id = id; + } + + /// + /// Updates the reservation to the number of bytes the job has actually written, growing it when the output is larger than the estimate. + /// + /// The number of bytes the job has actually written, in bytes. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the reservation covers the actual size, otherwise . + public bool TryUpdate(long actualBytes, long maxCacheBytes, TimeSpan gracePeriod) + { + if (_isCompleted || _isDisposed) + return false; + return _coordinator.TryGrow(Id, actualBytes, maxCacheBytes, gracePeriod); + } + + /// + /// Replaces the reservation with the produced cache entry. + /// + /// The identifier of the produced cache entry. + /// The temporary directory that holds the complete produced entry. + /// The total size of the produced cache entry, in bytes. + /// The validated index of the produced cache entry. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the produced entry remains readable even though it exceeds the cache limit, otherwise . + /// when a reader still holds the previous entry of the same cache identifier, so the replacement was not attempted. + /// when the produced entry is readable and may be served, otherwise when it was not published. + public bool TryComplete(string cacheId, string temporaryPath, long size, NormalizedTrackIndexDto index, long maxCacheBytes, TimeSpan gracePeriod, out bool isKeptOverCapacity, out bool isEntryInUse) + { + isKeptOverCapacity = false; + isEntryInUse = false; + if (_isCompleted || _isDisposed) + return false; + bool isCompleted = _coordinator.TryPublish(Id, cacheId, temporaryPath, size, index, maxCacheBytes, gracePeriod, out isKeptOverCapacity, out isEntryInUse); + // The reservation is consumed even when the produced entry had to be removed, so it is never released a second time. + _isCompleted = true; + return isCompleted; + } + + /// + /// Releases the reservation when the job did not produce a cache entry. + /// + public void Dispose() + { + if (_isDisposed) + return; + _isDisposed = true; + if (!_isCompleted) + _coordinator.ReleaseReservation(Id); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs new file mode 100644 index 00000000..1e5870ba --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.IO; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Tracks the size of the temporary output of a running normalization job without walking the growing directory on every monitor tick. +/// +/// +/// Segment files are written in sequence and only the last one grows. The tracker discovers each new segment once, keeps the size of the completed +/// segments, and only re-stats the current segment and the segment list on every tick, so the monitor stays O(1) per tick instead of O(n). +/// +internal sealed class TranscodingOutputSizeTracker +{ + private readonly string _directoryPath; + private readonly string _segmentFilePrefix; + private readonly string _segmentFileExtension; + private readonly string _segmentListPath; + private long _totalBytes; + private long _segmentListLength; + private long _lastSegmentLength; + private int _nextSegmentIndex; + private string? _lastSegmentPath; + + /// + /// Initializes a new instance of the class. + /// + /// The temporary directory the job writes into. + /// The prefix of the generated segment file names. + /// The file extension of a segment, including the leading dot. + /// The file name of the segment list written by ffmpeg. + internal TranscodingOutputSizeTracker(string directoryPath, string segmentFilePrefix, string segmentFileExtension, string segmentListFileName) + { + _directoryPath = directoryPath; + _segmentFilePrefix = segmentFilePrefix; + _segmentFileExtension = segmentFileExtension; + _segmentListPath = Path.Combine(directoryPath, segmentListFileName); + } + + /// + /// Gets the current total size of the produced output, in bytes. + /// + /// The current total size of the produced output, in bytes. + public long GetCurrentSize() + { + // The previous tick's last segment may have grown before a new segment was started, so it is measured before new files are discovered. + RecalculateLastSegment(); + RecalculateSegmentList(); + DiscoverNewSegments(); + RecalculateLastSegment(); + return _totalBytes; + } + + /// + /// Updates the total with the growth of the segment that is currently being written, when there is one. + /// + private void RecalculateLastSegment() + { + if (_lastSegmentPath is null) + return; + long currentLength = GetFileLength(_lastSegmentPath, _lastSegmentLength); + _totalBytes += currentLength - _lastSegmentLength; + _lastSegmentLength = currentLength; + } + + /// + /// Updates the total with the growth of the segment list. + /// + private void RecalculateSegmentList() + { + long currentLength = GetFileLength(_segmentListPath, _segmentListLength); + _totalBytes += currentLength - _segmentListLength; + _segmentListLength = currentLength; + } + + /// + /// Adds every segment that has appeared since the previous tick, in sequence, and leaves the last one as the growing segment. + /// + private void DiscoverNewSegments() + { + while (true) + { + string segmentPath = Path.Combine(_directoryPath, $"{_segmentFilePrefix}{_nextSegmentIndex:D6}{_segmentFileExtension}"); + FileInfo segmentFile = new(segmentPath); + if (!segmentFile.Exists) + return; + + long segmentLength; + try + { + segmentLength = segmentFile.Length; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return; // A file that cannot be measured yet is retried on the next tick. + } + + _totalBytes += segmentLength; + _lastSegmentPath = segmentPath; + _lastSegmentLength = segmentLength; + _nextSegmentIndex++; + } + } + + /// + /// Gets the length of a file, falling back to its last known length when it cannot currently be measured. + /// + /// The file to measure. + /// The length to use when the file cannot be measured. + /// The current or fallback length of the file, in bytes. + private static long GetFileLength(string filePath, long fallbackLength) + { + try + { + FileInfo file = new(filePath); + return file.Exists ? file.Length : fallbackLength; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return fallbackLength; + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs new file mode 100644 index 00000000..93b69bc7 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs @@ -0,0 +1,228 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Startup component that owns the normalized audio cache lifecycle and verifies the ffmpeg toolchain before any playback request is served. +/// +/// +/// The cache is cleaned and recreated with private permissions at startup, and the configured ffmpeg binary is probed for the encoders the catalog uses. The +/// cleanup only removes the entries the cache itself owns, and only from a directory that carries the cache marker or was empty, so a configured directory +/// that belongs to something else is never wiped. The cleanup is bounded, so a slow or network backed cache directory cannot delay host readiness without +/// limit. The probe outcome is recorded in , so normalized playback reports that it is unavailable for the affected +/// formats instead of failing per track. A failure of either step is logged and does not abort the host, so direct playback of the rest of the application +/// keeps working. +/// +internal sealed class TranscodingStartupInitializer : IHostedService +{ + private const int CACHE_CLEANUP_TIMEOUT_SECONDS = 30; + private const int FFMPEG_PROBE_TIMEOUT_SECONDS = 10; + + private readonly TranscodingSettingsDto _settings; + private readonly TranscodingToolchainStatus _toolchainStatus; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The audio normalization configuration options. + /// The status that records the outcome of the ffmpeg probe for the normalization service. + /// The logger for this startup component. + public TranscodingStartupInitializer(IOptions options, TranscodingToolchainStatus toolchainStatus, ILogger logger) + { + _settings = options.Value; + _toolchainStatus = toolchainStatus; + _logger = logger; + } + + /// + /// Cleans and recreates the cache directory, then probes the ffmpeg binary for the encoders the pipeline uses. + /// + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous startup operation. + public async Task StartAsync(CancellationToken cancellationToken) + { + try + { + string cacheDirectory = TranscodingCachePaths.GetRootDirectory(_settings.CacheDirectory); + if (Directory.Exists(cacheDirectory)) + { + // The permissions are verified before the directory is inspected, so a directory planted by another account is never used or cleaned. + TranscodingCachePaths.RestrictPermissions(cacheDirectory); + if (TranscodingCachePaths.HasCacheMarker(cacheDirectory)) + { + // Only the entries the cache itself owns are removed, so a directory that was configured by mistake can never lose unrelated data. + // The cleanup is bounded and cancellable, because a network backed cache directory must not delay host readiness forever. + using (CancellationTokenSource cleanupTimeoutCancellationTokenSource = new(TimeSpan.FromSeconds(CACHE_CLEANUP_TIMEOUT_SECONDS))) + { + using (CancellationTokenSource linkedCleanupCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cleanupTimeoutCancellationTokenSource.Token)) + { + try + { + TranscodingCachePaths.ClearCacheEntries(cacheDirectory, linkedCleanupCancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + if (!cancellationToken.IsCancellationRequested) + _logger.LogWarning("The normalized audio cache cleanup did not finish within {CleanupTimeoutSeconds} seconds. Whatever remains is accounted for by the coordinator and is removed by the next cleanup.", CACHE_CLEANUP_TIMEOUT_SECONDS); + } + } + } + } + else if (!Directory.EnumerateFileSystemEntries(cacheDirectory).Any()) + TranscodingCachePaths.WriteCacheMarker(cacheDirectory); // An empty directory is adopted, so a cache directory created ahead of the first run works without manual preparation. + else // A non-empty directory without the marker was not created by this application. It is never wiped, because only the operator can tell whether its entries are safe to remove. + throw new IOException("The configured normalized audio cache directory exists, is not empty and does not carry the Lumina cache marker, so it was not wiped."); + } + else + TranscodingCachePaths.EnsureDirectoryExists(cacheDirectory); + _logger.LogInformation("The normalized audio cache uses the directory '{CacheDirectory}'.", cacheDirectory); + } + catch (Exception exception) + { + // A locked file, a read-only volume or a directory owned by another account must not stop the whole application; the coordinator accounts + // for whatever remains and the service reports normalized playback as unavailable when the directory still cannot be used. + _logger.LogError(exception, "The normalized audio cache could not be initialized (configured directory: '{CacheDirectory}'). Normalized playback may be unavailable.", _settings.CacheDirectory ?? "(default)"); + } + + try + { + await ProbeFfmpegAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) + { + // The startup component promises never to abort the host, so an unexpected probe failure is contained and reported here. + _toolchainStatus.RecordUnavailable(); + _logger.LogError(exception, "The ffmpeg startup probe failed unexpectedly. Normalized playback may be unavailable."); + } + } + + /// + /// Stops the startup component, which has no resources of its own to release. + /// + /// Cancellation token that can be used to stop the execution. + /// A completed task. + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + /// + /// Probes the ffmpeg binary for the encoders the catalog can produce, without failing the host when it is missing or incomplete. + /// + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous probe. + private async Task ProbeFfmpegAsync(CancellationToken cancellationToken) + { + try + { + using Process process = new(); + process.StartInfo = new ProcessStartInfo + { + FileName = _settings.FfmpegPath, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + process.StartInfo.ArgumentList.Add("-hide_banner"); + process.StartInfo.ArgumentList.Add("-encoders"); + + if (!process.Start()) + { + _toolchainStatus.RecordUnavailable(); + _logger.LogWarning("The ffmpeg binary '{FfmpegPath}' could not be started. Normalized playback will be unavailable.", _settings.FfmpegPath); + return; + } + + using CancellationTokenSource timeoutCancellationTokenSource = new(TimeSpan.FromSeconds(FFMPEG_PROBE_TIMEOUT_SECONDS)); + // The probe has two cancellation reasons: the host startup token and the probe timeout. Linking them gives the process wait and the pipe reads + // one token that means "this probe is over" for either reason. The parameter alone could not stop the reads on a timeout, and the timeout alone would ignore host shutdown. + using CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token); + // Drain both pipes while the process runs. A child that fills a pipe buffer blocks until it is read, so waiting for exit first could deadlock. + // The linked token stops the reads as well, so a probe timeout or host shutdown does not leave them running against a killed child. + Task standardOutputTask = process.StandardOutput.ReadToEndAsync(linkedCancellationTokenSource.Token); + Task standardErrorTask = process.StandardError.ReadToEndAsync(linkedCancellationTokenSource.Token); + try + { + await process.WaitForExitAsync(linkedCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + try + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + } + catch (Exception killException) when (killException is Win32Exception or InvalidOperationException or NotSupportedException) + { + _logger.LogDebug(killException, "The ffmpeg startup probe process could not be stopped."); + } + if (!cancellationToken.IsCancellationRequested) + _logger.LogWarning("The ffmpeg binary '{FfmpegPath}' did not respond to the startup probe.", _settings.FfmpegPath); + _toolchainStatus.RecordUnavailable(); + return; + } + + string encoderListing = await standardOutputTask.ConfigureAwait(false); + await standardErrorTask.ConfigureAwait(false); + if (process.ExitCode != 0) + { + _toolchainStatus.RecordUnavailable(); + _logger.LogWarning("The ffmpeg binary '{FfmpegPath}' exited with code {ExitCode} during the startup probe. Normalized playback may be unavailable.", _settings.FfmpegPath, process.ExitCode); + return; + } + + IReadOnlyList requiredEncoders = [.. PlaybackFormatCatalog.Formats + .Select(format => format.EncoderName) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + List missingEncoders = [.. requiredEncoders.Where(encoder => !ContainsEncoder(encoderListing, encoder))]; + if (missingEncoders.Count > 0) + { + // An unpinned distribution package can change the encoder set without changing the application build, so this is reported at startup instead of surfacing as a per track playback failure. + _toolchainStatus.RecordMissingEncoders(missingEncoders); + _logger.LogError("The ffmpeg binary '{FfmpegPath}' is missing the encoders {MissingEncoders}. Normalized playback for those formats will be unavailable.", _settings.FfmpegPath, string.Join(", ", missingEncoders)); + return; + } + _toolchainStatus.RecordAvailable(); + _logger.LogInformation("The ffmpeg binary '{FfmpegPath}' provides every encoder the normalized audio pipeline uses.", _settings.FfmpegPath); + } + catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException or UnauthorizedAccessException or NotSupportedException) + { + _toolchainStatus.RecordUnavailable(); + _logger.LogWarning(exception, "The ffmpeg binary '{FfmpegPath}' could not be probed. Normalized playback will be unavailable.", _settings.FfmpegPath); + } + } + + /// + /// Checks whether the encoder listing of ffmpeg contains the provided encoder name. + /// + /// The output of the ffmpeg encoder listing. + /// The encoder name to look for. + /// when the encoder is listed, otherwise . + private static bool ContainsEncoder(string encoderListing, string encoderName) + { + foreach (string line in encoderListing.Split('\n')) + { + string[] tokens = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); + // An encoder line is " "; the encoder name is always the second token. + if (tokens.Length >= 2 && string.Equals(tokens[1], encoderName, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs new file mode 100644 index 00000000..d6e0e717 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Records the outcome of the ffmpeg startup probe, so a missing toolchain or encoder is reported as a retryable unavailability instead of a production failure. +/// +/// +/// The status starts as available, because a request that arrives before the probe completes is better served by attempting the work than by rejecting it. The +/// probe replaces the status with its outcome, and every later production consults it before it spends a job slot. +/// +internal sealed class TranscodingToolchainStatus +{ + // The startup probe writes these fields and request threads read them without a lock, so volatile makes each write visible to the readers. + private volatile bool _isTranscoderAvailable = true; + private volatile FrozenSet _missingEncoders = []; + + /// + /// Initializes a new instance of the class, which starts as available until the startup probe records its outcome. + /// + public TranscodingToolchainStatus() + { + } + + /// + /// Gets a value indicating whether the ffmpeg binary can run at all. + /// + public bool IsTranscoderAvailable => _isTranscoderAvailable; + + /// + /// Records that the probe found a usable ffmpeg binary with every encoder the catalog needs. + /// + public void RecordAvailable() + { + // The set is cleared before the availability flag, so a reader never observes a missing encoder together with a fresh successful probe. + _missingEncoders = []; + _isTranscoderAvailable = true; + } + + /// + /// Records that the ffmpeg binary could not be started or did not answer the probe. + /// + public void RecordUnavailable() + { + _isTranscoderAvailable = false; + _missingEncoders = []; + } + + /// + /// Records that ffmpeg runs, but that some of the encoders the catalog needs are missing. + /// + /// The names of the encoders the startup probe did not find. + public void RecordMissingEncoders(IEnumerable missingEncoders) + { + _missingEncoders = missingEncoders.ToFrozenSet(StringComparer.OrdinalIgnoreCase); + _isTranscoderAvailable = true; + } + + /// + /// Checks whether an encoder can be used for a lossy or lossless transcode. + /// + /// The name of the ffmpeg encoder the delivery format needs. + /// when ffmpeg runs and the encoder was found, otherwise . + public bool IsEncoderAvailable(string encoderName) + { + return _isTranscoderAvailable && !_missingEncoders.Contains(encoderName); + } +} diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 1ffd9bd4..68c0bb03 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -26,6 +26,7 @@ + diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index dfeb872c..b984fd84 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -17,6 +17,14 @@ "MaxSingleFileBytes": 6291456, "MaxEntries": 250 }, + "TranscodingSettings": { + "FfmpegPath": "ffmpeg", + "MaxConcurrentJobs": 2, + "MaxCacheBytes": 2147483648, + "JobTimeoutSeconds": 900, + "EvictionGraceSeconds": 120, + "CacheDirectory": null + }, "ConnectionStrings": { "DefaultConnection": "Server=;Database=;User Id=;Password=;" }, diff --git a/src/Lumina.Presentation.Api/Dockerfile b/src/Lumina.Presentation.Api/Dockerfile index 297fdfe6..65811f8c 100644 --- a/src/Lumina.Presentation.Api/Dockerfile +++ b/src/Lumina.Presentation.Api/Dockerfile @@ -1,10 +1,14 @@ # This stage is used when running from VS in fast mode (Default for Debug configuration) FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base # curl is used by the container healthcheck to probe the /health endpoints +# ffmpeg is used by the API server to remux or transcode audio the browser cannot play directly. +# The package comes from the base image distribution and is not version-pinned, so the encoder set can change with a base image rebuild. +# The API startup probe verifies the encoders the normalization catalog uses and reports a missing one at startup. Pin the base image digest +# or the package version when a fully reproducible toolchain is required. RUN apt-get update \ - && apt-get install -y --no-install-recommends curl \ + && apt-get install -y --no-install-recommends curl ffmpeg \ && rm -rf /var/lib/apt/lists/* \ - && mkdir /logs && chown -R app:app /logs + && mkdir -p /app /logs && chown -R app:app /app /logs USER app WORKDIR /app EXPOSE 5214 diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 73d8fe89..ef9ecbbc 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -8,8 +8,8 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Infrastructure.Common.DependencyInjection; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; -using Lumina.Infrastructure.Core.Scheduling.Notifications; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Infrastructure.Core.Scheduling.Notifications; using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Middlewares; using Lumina.Presentation.Api.Common.Utilities; diff --git a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs index 283aabfe..345f01fa 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs @@ -8,28 +8,29 @@ namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary; /// Enumeration for the quality cap applied to the audio the server normalizes (remuxes or transcodes) for a user. /// /// -/// The caps apply only to audio the server has to change; a track that is played directly is always delivered as it was stored. +/// The caps apply only to audio the server re-encodes into a lossy codec. A track that is played directly is delivered as it was stored, a remux only +/// repackages the stored codec without re-encoding it, and a lossless transcode is not reduced, so none of those deliveries is capped. /// [DebuggerDisplay("{ToString()}")] public enum PlaybackStreamingQuality { /// - /// The server chooses the quality, with no explicit cap. + /// The server chooses the quality, with a default cap of 192 kbps for a lossy re-encode. /// Auto, /// - /// Normalized audio is capped at 96 kbps. + /// A lossy normalized audio stream is capped at 96 kbps. /// Low, /// - /// Normalized audio is capped at 160 kbps. + /// A lossy normalized audio stream is capped at 160 kbps. /// Medium, /// - /// Normalized audio is capped at 320 kbps. + /// A lossy normalized audio stream is capped at 320 kbps. /// High, } diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js index 9d13c62a..a6428985 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -1197,7 +1197,7 @@ // playhead, the streamed fraction and the scrubbing state while the audio keeps playing. if (index === this.currentIndex) return this.queueEntries[index].descriptor; - // Navigation history, repeat and shuffle belong to the queue model of step 18. This commit only moves the cursor. + // Navigation history, repeat and shuffle belong to the queue model, which is not part of this cursor movement. const previousIndex = this.currentIndex; this.currentIndex = index; return this.applyTrackDescriptor(this.queueEntries[index].descriptor, previousIndex); From 45f9aa3bd59b4b5a0ec89e79a5b7b2cbdbad5d49 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sun, 18 Oct 2026 14:55:56 +0300 Subject: [PATCH 22/77] Adds seekable normalized audio track delivery --- docs/manual/installation/index.md | 4 +- docs/manual/using-lumina/index.md | 2 +- .../audio-library/music-library/Api.Tracks.md | 56 +- .../architecture-decision-record-0016.md | 17 +- .../tracks/StreamTrackSegment.http | 2 + .../Playback/NormalizedTrackRequestDto.cs | 12 +- .../Playback/NormalizedTrackSegmentDataDto.cs | 29 + .../Playback/PlaybackDeliveryHandleDto.cs | 25 + .../Tracks/TrackPlaybackManifestDto.cs | 78 +- .../MusicLibrary/Tracks/TrackStreamDto.cs | 76 +- .../IPlaybackDeliveryHandleService.cs | 39 + .../Playback/ITrackNormalizationService.cs | 18 +- .../Playback/PlaybackDeliveryId.cs | 31 + .../GetPlaybackManifestQuery.cs | 4 +- .../GetPlaybackManifestQueryHandler.cs | 91 +- .../GetTrackSegment/GetTrackSegmentQuery.cs | 25 + .../GetTrackSegmentQueryHandler.cs | 130 ++ .../GetTrackSegmentQueryValidator.cs | 81 ++ .../Playback/PlaybackManifestResponse.cs | 24 +- .../MusicLibrary/TrackRepository.cs | 51 +- .../Common/Errors/Errors.Playback.cs | 9 +- .../InfrastructureLayerServices.cs | 8 +- .../Common/Errors/Errors.Configuration.cs | 3 + .../Configuration/TranscodingSettingsDto.cs | 6 + .../TranscodingSettingsDtoValidator.cs | 13 + .../Playback/PlaybackDeliveryHandleService.cs | 251 ++++ .../Playback/TrackNormalizationService.cs | 123 +- .../appsettings.shared.json | 1 + .../Common/MimeTypes/MusicMimeTypes.cs | 27 + .../MusicLibrary/ApiRoutes.Tracks.cs | 1 + .../Core/Endpoints/Common/BaseEndpoint.cs | 28 +- .../Endpoints/Common/DisposingStreamResult.cs | 48 + .../GetPlaybackManifestEndpoint.cs | 19 +- .../GetPlaybackManifestEndpointSummary.cs | 14 +- .../GetTrackSegmentEndpoint.cs | 93 ++ .../GetTrackSegmentEndpointSummary.cs | 145 ++ .../Common/Api/ApiStreamResult.cs | 50 + .../MusicLibrary/PlaybackManifestDto.cs | 19 +- .../Common/Http/ApiStreamProxy.cs | 75 + .../Common/Playback/PlaybackDeliveryId.cs | 31 + .../Tracks/StreamMusicTrackSegmentRequest.cs | 25 + .../Common/Routes/ApiRoutes.Music.cs | 1 + .../Common/Routes/WebRoutes.Music.cs | 1 + .../GetPlaybackManifestEndpoint.cs | 55 +- .../GetPlaybackManifestEndpointSummary.cs | 2 +- .../StreamMusicTrackEndpoint.cs | 62 +- .../StreamMusicTrackSegmentEndpoint.cs | 99 ++ .../StreamMusicTrackSegmentEndpointSummary.cs | 39 + .../Views/Shared/_ThemeLayoutScripts.cshtml | 2 + .../audio-player-demux-capabilities.js | 36 +- .../js/audio-player/audio-player-errors.js | 19 +- .../js/audio-player/audio-player-events.js | 2 +- .../js/audio-player/audio-player-manifest.js | 114 ++ .../audio-player-pipeline-engine.js | 367 ++++- .../audio-player-pipeline-normalized.js | 1204 +++++++++++++++++ src/Lumina.sln | 1 + .../GetPlaybackManifestEndpointTests.cs | 8 +- 57 files changed, 3452 insertions(+), 344 deletions(-) create mode 100644 docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Common/DisposingStreamResult.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs create mode 100644 src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-normalized.js diff --git a/docs/manual/installation/index.md b/docs/manual/installation/index.md index 4054ee27..f2a933f3 100644 --- a/docs/manual/installation/index.md +++ b/docs/manual/installation/index.md @@ -115,14 +115,14 @@ The settings that matter most when installing: | `PluginsSettings:Directory` | API server | Folder holding installed plugin assemblies, `plugins` by default. | | `ThemeEngine:StoragePath`, `ThemeEngine:BundledThemesPath`, `ThemeEngine:DefaultThemeId` | API server | Where installed and bundled themes live, and which theme is activated by default. | | `ThemeEngine:MaxArchiveBytes`, `MaxExpandedBytes`, `MaxSingleFileBytes`, `MaxEntries` | API server | Limits enforced on uploaded theme packs. | -| `TranscodingSettings:FfmpegPath`, `MaxConcurrentJobs`, `MaxCacheBytes`, `JobTimeoutSeconds`, `EvictionGraceSeconds`, `CacheDirectory` | API server | Where the ffmpeg binary is, how many audio normalization jobs may run at once, the maximum size of the normalized audio cache in bytes, how long a single job may take in seconds, how long a freshly produced or served cache entry is protected from eviction, and where the cache is stored. When `CacheDirectory` is absent, a private directory under the API account's temporary directory is used. | +| `TranscodingSettings:FfmpegPath`, `MaxConcurrentJobs`, `MaxConcurrentJobsPerUser`, `MaxCacheBytes`, `JobTimeoutSeconds`, `EvictionGraceSeconds`, `CacheDirectory` | API server | Where the ffmpeg binary is, how many audio normalization jobs may run at once in total and per user, the maximum size of the normalized audio cache in bytes, how long a single job may take in seconds, how long a freshly produced or served cache entry is protected from eviction, and where the cache is stored. When `CacheDirectory` is absent, a private directory under the API account's temporary directory is used. | | `Telemetry:Enabled`, `Telemetry:Otlp:Endpoint`, `Telemetry:TraceSampleRatio`, `Telemetry:ConsoleExporterEnabled` | API server and web client | Telemetry behavior. The OTLP endpoint also falls back to the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable. Again, while telemetry is enabled as a feature, nothing is sent anywhere. | The `LOG_PATH` environment variable selects where the rolling log files are written. The normalized audio cache must not be placed inside `MediaSettings:RootDirectory`, because that directory is served at the `/media` route, and it must not contain that directory either, because cleaning the cache would remove the media. The startup configuration also rejects a cache directory that is a filesystem root, the application directory or one of its parents, or that overlaps the logs or plugins directories. The default uses a private directory under the API account's temporary directory and avoids all of these. The cache holds transcoded or remuxed audio only while it is useful: at API startup only the entries the cache itself owns are removed, and a directory is cleaned only when it carries Lumina's cache marker file (`.lumina-transcoding-cache`) or is empty, so a directory that belongs to something else is left untouched. Its total footprint is capped by `TranscodingSettings:MaxCacheBytes`, but an entry that is still being read, or that was just produced when the cache was already at the limit, is kept until it can be removed, so the cache can exceed the cap temporarily. The cache is not part of the media library. -The default cache directory is scoped to the API account, but the coordinator, the running jobs and the startup cleanup are per process. Run a single API process per account and host, or configure a distinct `CacheDirectory` for each instance. On a multi-user Unix host the directory is created with private permissions, and a pre-existing directory owned by another account is treated as unavailable rather than reused or deleted. +The default cache directory is scoped to the API account, but the coordinator, the running jobs and the startup cleanup are per process. Run a single API process per account and host, or configure a distinct `CacheDirectory` for each instance. Playback delivery handles are also process local: in a load balanced multi-instance deployment, a track's manifest and its subsequent segment requests must reach the same API instance, so configure sticky routing for them as described for SignalR below. On a multi-user Unix host the directory is created with private permissions, and a pre-existing directory owned by another account is treated as unavailable rather than reused or deleted. ### Keeping the two applications in step diff --git a/docs/manual/using-lumina/index.md b/docs/manual/using-lumina/index.md index 21555490..bcdc3981 100644 --- a/docs/manual/using-lumina/index.md +++ b/docs/manual/using-lumina/index.md @@ -87,6 +87,6 @@ Wherever Lumina needs a folder or a file from the server, it opens the file syst The tools section holds your settings and the language picker. -Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. A final group of options shapes playback: whether the player keeps downloading while it is paused, whether it continues automatically at the end of an album or artist, whether consecutive tracks play without a gap, how ReplayGain normalizes loudness, and the quality cap used when the server has to normalize a track. That cap applies only when the server re-encodes a track into a lossy format; a remux only repackages the stored audio, and a lossless delivery is not reduced. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md). +Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. A final group of options shapes playback: whether the player keeps downloading while it is paused (for a track the server has to normalize, this keeps its bounded one-segment lookahead filled rather than downloading the whole file), whether it continues automatically at the end of an album or artist, whether consecutive tracks play without a gap, how ReplayGain normalizes loudness, and the quality cap used when the server has to normalize a track. That cap applies only when the server re-encodes a track into a lossy format; a remux only repackages the stored audio, and a lossless delivery is not reduced. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md). The **language** picker switches the interface between the languages Lumina ships with, and remembers your choice. diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index a518e8a3..4c5a0b53 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -11,6 +11,9 @@ - [Stream Track](#stream-track) - [Stream Track Request](#stream-track-request) - [Stream Track Response](#stream-track-response) + - [Stream Track Segment](#stream-track-segment) + - [Stream Track Segment Request](#stream-track-segment-request) + - [Stream Track Segment Response](#stream-track-segment-response) - [Get Playback Manifest](#get-playback-manifest) - [Get Playback Manifest Request](#get-playback-manifest-request) - [Get Playback Manifest Response](#get-playback-manifest-response) @@ -347,6 +350,32 @@ Accept-Ranges: bytes The response is the raw bytes of the audio file, served with the media type of the file when it is an audio type, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private` and `Vary: Authorization`, together with a `Last-Modified` and an `ETag` derived from the size and the modification time of the file. +### Stream Track Segment + +#### Stream Track Segment Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0 +Authorization: Bearer +``` + +Streams one segment of the normalized audio of the track identified by the route. A track the player cannot play as it is stored is delivered as time addressed segments instead of bytes: the server produces the whole track into a temporary cache with a target segment duration of `segmentDurationSeconds` seconds, cutting at the first packet at or after each target boundary, and serves each produced segment as an independent container file. A real segment start can therefore differ from an exact multiple of the target duration, and a consumer must use the start the response reports rather than assume the grid. The segment index is zero based. + +The `deliveryId` is the opaque handle the playback manifest reported in `deliveryId`. It is bound to the user the manifest was issued to and to the track it describes, and it captures the delivery decision, the quality cap, the source file version and the library content locations the manifest declared. The segment route resolves that handle instead of recomputing the delivery from a capability list, so the segments always belong to exactly the delivery the manifest declared. Library ownership is re-evaluated on every segment request, so revoked access stops playback immediately; the track membership and the content locations are the ones captured at manifest time, so a deleted track row whose file remains, or a removed content location, stays streamable until the handle expires, within 12 hours. A handle that is unknown, expired, or was issued to another user or track is reported as not found. A track the manifest declared as a direct play has no delivery handle at all, so a segment request for it is also reported as not found with `PlaybackDeliveryNotFound`, never as the end of the audio. A source file that changed since the manifest declared the delivery is reported as a conflict instead of starting a second production. The handle is exactly 32 lowercase hexadecimal characters, and a value that does not match that format is rejected rather than normalized into another handle. + +A byte range cannot be mapped to a time in this delivery, so a player seeks by choosing the segment that covers the target time. A segment is a small independent container file that is already fetched as a whole, so the player reads it from its first packet and discards the packets that end before the target; it never seeks inside the container itself, because a container that numbers its frames across the whole track would then add that number to the segment offset twice. The playback manifest reports the root relative path of this route in `segmentStreamPathTemplate`, with `{deliveryId}` and `{segmentIndex}` placeholders, and the player expands both from the manifest. A segment is served to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track. + +#### Stream Track Segment Response + +```js +200 Ok +Content-Type: audio/aac +Content-Length: 240128 +``` + +The response is the raw bytes of one produced segment, served with the media type of the delivered container when the server can name it, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private, no-store`, `Vary: Authorization`, `X-Lumina-Segment-Count`, the number of segments the production holds, and `X-Segment-Start-Seconds`, the exact start of the segment on the track timeline, in seconds. The count tells a player where the audio ends without probing for the end with a request that returns not found, and the start lets it offset the packets of a container that numbers its frames from the start of the track, instead of assuming that a segment starts at an exact multiple of its duration. Range requests are not used: the segment is the addressing unit, and the next segment is a separate request. The first request for a track can take longer than the following ones, because the whole normalized audio is produced and cached before its first segment is published. A segment index that the production does not hold is reported as not found with the `NormalizedTrackSegmentNotFound` detail, which is the only not-found answer that means the end of the audio. A track, library or audio file that disappeared, a delivery handle that is unknown, expired, or was issued to another user or track, and a cache entry that was evicted, are reported with their own not-found details instead, and a request that arrives while every normalization job slot is in use is reported as unavailable (`503`), because it is a transient condition that a player retries. A delivery handle whose captured shape is not time addressed segments is a conflict (`409`), because the segment route cannot index it. + + ### Get Playback Manifest #### Get Playback Manifest Request @@ -377,17 +406,36 @@ Returns the playback manifest of the track identified by the route: the format o "replayGainTrackPeak": 0.9877, "replayGainAlbumGain": -6.8, "replayGainAlbumPeak": 0.9999, - "directPlay": true, + "isDirectPlay": true, "deliveryContainer": null, "deliveryCodec": null, "deliveryShape": null, "segmentDurationSeconds": null, - "seekable": true, - "streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream" + "isSeekable": true, + "streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream", + "deliveryId": null, + "segmentStreamPathTemplate": null } ``` -When the player can play the stored audio as it is, `directPlay` is `true`, and `deliveryContainer`, `deliveryCodec`, `deliveryShape` and `segmentDurationSeconds` are `null`, because the delivery is the stored file itself. When it cannot, `directPlay` is `false`, and those fields name the container, the codec, the addressing the server produces instead, and the length in seconds of each of its time addressed segments. A normalized delivery is always addressed as `TimeAddressedSegments`, and `segmentDurationSeconds` is the length of each of its segments, so that the server that produces the segments and the player that consumes them agree on it without duplicating the value on both sides. `seekable` reports whether the delivered audio can be seeked by the player. `streamPath` is relative to the API, without a host or a scheme, so that a client reaches the stream through its own application rather than the API server directly. +When the player can play the stored audio as it is, `isDirectPlay` is `true`, and `deliveryContainer`, `deliveryCodec`, `deliveryShape`, `segmentDurationSeconds`, `deliveryId` and `segmentStreamPathTemplate` are `null`, because the delivery is the stored file itself, addressed and seeked by byte range. When it cannot, `isDirectPlay` is `false`, and those fields name the container, the codec, the addressing the server produces instead, the length in seconds of each of its time addressed segments, the opaque handle of the delivery, and the root relative path template of the segment route, with `{deliveryId}` and `{segmentIndex}` placeholders. `durationInSeconds` is the probed duration; a normalized production can be slightly longer or shorter, and its exact produced duration is reported by the `X-Lumina-Track-Duration-Seconds` header of its segments. A normalized delivery is always addressed as `TimeAddressedSegments`, and `segmentDurationSeconds` is the nominal length of each of its segments, so that the server that produces the segments and the player that consumes them agree on the target without duplicating the value on both sides. The `deliveryId` binds the delivery to the user and the track, and it captures the quality cap and the source file version that were in effect when the manifest was read, so a segment request addresses exactly that delivery instead of recomputing it. A player that cannot play a track directly fetches each segment from that template in index order and seeks by segment index, never by byte range. `isSeekable` reports whether the delivered audio can be seeked by the player. `streamPath` is relative to the API, without a host or a scheme, so that a client reaches the stream through its own application rather than the API server directly. + +For example, a delivery of a track the player cannot decode is declared as follows: + +```json +{ + "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "isDirectPlay": false, + "deliveryContainer": "AAC", + "deliveryCodec": "AAC", + "deliveryShape": "TimeAddressedSegments", + "segmentDurationSeconds": 6, + "isSeekable": true, + "streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream", + "deliveryId": "8f14e45fceea167a5a36dedd4bea2543", + "segmentStreamPathTemplate": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream/deliveries/{deliveryId}/segments/{segmentIndex}" +} +``` ### Update Track diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md index 41252610..f438f466 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md @@ -43,7 +43,20 @@ GET /api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{tr ### Delivery shape -The `TimeAddressedSegments` delivery shape is a sequence of fixed duration segments addressed and seeked by time, so that finding a time never requires mapping a byte range to it. The segment duration is 6 seconds, and it is carried in the delivery decision so that the producer of the segments and the player agree on it. Direct play is `ByteRangeSeekable`, because the original file is served by the existing range-capable stream endpoint. +The `TimeAddressedSegments` delivery shape is a sequence of approximately fixed duration segments addressed and seeked by time, so that finding a time never requires mapping a byte range to it. The nominal segment duration is 6 seconds, and it is carried in the delivery decision so that the producer of the segments and the player agree on it. A segment is cut at the first packet at or after its nominal boundary, so its real start is not always an exact multiple of the nominal duration; the producer records the real start in its index, and the segment route reports it in a response header. Direct play is `ByteRangeSeekable`, because the original file is served by the existing range-capable stream endpoint. + +### Segment addressing + +The segments are exposed through a dedicated segment route, `.../stream/deliveries/{deliveryId}/segments/{segmentIndex}`, which extends the track stream endpoint's contract. The playback manifest carries its relative path in `segmentStreamPathTemplate`, with `{deliveryId}` and `{segmentIndex}` placeholders, and the web application rewrites that path to its own segment proxy so that the browser never reaches the API server. The manifest also reports the opaque `deliveryId` the placeholders are expanded with. + +- An index addresses a whole segment, so no byte range is ever sent for a normalized delivery. +- The delivery handle the manifest issued is the only authority on the delivery of the segments. It is a random, opaque value bound to the user and the track, and it captures the delivery decision, the quality cap and the source file version the manifest declared. The segment route resolves it instead of recomputing the decision from a capability list, rereading the user's quality setting, or restating a file that may have changed. A changed file is rejected as a conflict rather than starting a second production whose segments would be mixed with the declared one. +- Library ownership is still evaluated on every segment request, so revoked access stops playback immediately. The track membership and the library content locations are the ones captured when the manifest was issued, so deleting a track row while its file remains, or removing a content location, can keep that media streamable until the handle expires. That is the deliberate trade-off for not reloading the track and library graph for every six second segment; the handle lifetime is bounded to 12 hours. +- The handles are process local, like the normalized audio cache they address. They expire after a bounded lifetime, are bounded globally and per user, and a repeated manifest for the same delivery inputs reuses the existing handle, so the registry cannot grow without bound. Expired handles are removed in issue order from a queue, so the sweep is amortized constant time rather than a scan of every handle. +- A production is atomic: the first segment request may wait for the whole normalized track to be produced and cached, and the following segment requests are served from that cache. +- The player keeps a bounded lookahead of one segment ahead of the segment the demuxer consumed, so the link is not idle between segments and the streamed indicator can run ahead. The lookahead stops while playback is paused unless the user enabled the keep-downloading-while-paused preference, and it never advances itself, so it cannot turn into a full download of the track. +- Gapless prefetch starts only near the end of the current track, not at load time. A normalized next track therefore transitions without a gap only when its production is already cached or finishes within that lead; otherwise it starts normally at the boundary. The lead is deliberately shorter than a long production, because holding a normalization slot for a track the user may never reach is worse than a small gap. +- The player keeps every segment it has fetched for the lifetime of the track, so seeking back into a fetched segment does not fetch it again. A seek reads the target segment from its first packet and drops the packets that end before the target, instead of seeking inside the segment: a container that numbers its frames across the whole track would otherwise add that number to the segment offset twice. A segment is short, so reading it from its start is exact for every delivered container. ## Consequences @@ -63,7 +76,7 @@ The `TimeAddressedSegments` delivery shape is a sequence of fixed duration segme |---|---| | The probe reports a codec as a free form description that does not name the codec the player advertises | The stored description is canonicalized to the advertised codec names before comparison, and the MPEG layer is matched by its layer number, so a description that names no decodable codec is left unmatched and forces a transcode | | A player advertises a container the server cannot produce | The delivered container is always chosen from the containers the server produces the codec in, never from the container the player names, so a client supplied container never reaches the transcoder or a cache name; a codec the player cannot be served in any server container is not used | -| The segment duration drifts between the server and the player | It is part of the delivery decision carried by the manifest, not a constant duplicated on both sides | +| The real segment start drifts from the nominal grid | The nominal duration is carried by the manifest, and the exact indexed start of each segment is reported in `X-Segment-Start-Seconds` and used by the player, so neither side assumes an exact grid | ## Alternatives Considered diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http new file mode 100644 index 00000000..2bd235ae --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0 +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs index 4e28eb18..358f52de 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs @@ -11,25 +11,29 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.P /// Data transfer object for the request to produce the normalized audio of a track, as the delivery decision of a playback manifest describes it. /// /// The Id of the track whose audio is normalized. It binds the produced cache entry to the track the caller authorized. +/// The Id of the user whose request starts the production. It is used for the per-user admission limit, and never for the cache identity. /// The file system path of the stored audio file of the track. /// /// The content locations the source path is allowed to be inside. The service validates the path against them and re-checks it after opening, so a /// caller that forgets to enforce containment cannot hand an arbitrary path to the transcoder. /// -/// The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer. Optional. +/// The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer. /// The way the audio is delivered, which is a remux or a transcode. /// The container of the delivered audio, as chosen by the delivery decision. /// The codec of the delivered audio, as chosen by the delivery decision. /// The duration of each segment of the delivered audio, in seconds. /// The duration of the audio of the track, in seconds. -/// The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec. Optional. +/// The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec. /// The sample rate of the stored audio of the track, in Hz, used to estimate the size of a lossless delivery. /// The number of audio channels of the track, used to estimate the size of a lossless delivery. /// The bit depth of the stored audio of the track, if applicable, used to estimate the size of a lossless delivery. /// The quality cap applied to the delivered audio when it has to be re-encoded. +/// The length the source file had when the delivery was declared, in bytes. The production is rejected when the file no longer matches. +/// The last modification time the source file had when the delivery was declared. The production is rejected when the file no longer matches. [DebuggerDisplay("TrackId: {TrackId} Mode: {Mode} Container: {Container} Codec: {Codec}")] public sealed record NormalizedTrackRequestDto( Guid TrackId, + Guid UserId, string SourcePath, IReadOnlyList AllowedRoots, string? SourceContainer, @@ -42,5 +46,7 @@ public sealed record NormalizedTrackRequestDto( int SampleRate, int Channels, int? BitDepth, - PlaybackStreamingQuality Quality + PlaybackStreamingQuality Quality, + long SourceLength, + DateTime SourceLastModifiedUtc ); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs new file mode 100644 index 00000000..1b767175 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.IO; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for a single produced segment of the normalized audio of a track, ready to be written to the response. +/// +/// +/// The segment owns a live stream over a leased cache entry, so it is an internal delivery object of the API rather than a serializable +/// contract. The caller must dispose the stream once the response is written, which releases the cache reader lease. +/// +/// The read stream over the segment, which the caller owns and must release once the response is written. +/// The length of the segment, in bytes, taken from the index of the normalized audio. +/// The exact start of the segment on the track timeline, in seconds, taken from the index of the normalized audio. +/// The container of the delivered audio, used to resolve the media type of the segment. +/// The number of segments the production holds, so the caller can tell the end of the audio from a missing segment. +/// The duration of the produced normalized audio, in seconds, which can differ from the probed duration. +[DebuggerDisplay("Length: {Length} StartSeconds: {StartSeconds} Container: {Container} SegmentCount: {SegmentCount}")] +public sealed record NormalizedTrackSegmentDataDto( + Stream Content, + long Length, + decimal StartSeconds, + string Container, + int SegmentCount, + int DurationInSeconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs new file mode 100644 index 00000000..5ba7674d --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the delivery a playback manifest issued to a user. It composes the exact normalization request the delivery declares, +/// so a new production input is added in one place and can never drift between the cache identity and the handle. +/// +/// The complete normalization request the delivery declares, including its user, track, decision, quality and source identity. +/// The shape the delivered audio is addressed by, which must be time addressed segments for a segment route. +/// The Id of the library the track belongs to, so the segment route can scope the delivery without querying it again. +/// The Id of the album the track belongs to, so the segment route can scope the delivery without querying it again. +/// The Id of the artist that owns the album, so the segment route can scope the delivery without querying it again. +[DebuggerDisplay("TrackId: {Request.TrackId} Mode: {Request.Mode} Container: {Request.Container} Codec: {Request.Codec}")] +public sealed record PlaybackDeliveryHandleDto( + NormalizedTrackRequestDto Request, + PlaybackDeliveryShape Shape, + Guid LibraryId, + Guid AlbumId, + Guid ArtistId +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs index 08a3d50a..c9059377 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs @@ -7,56 +7,30 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T /// /// Data transfer object for the stored probe result of a track, containing only the fields a playback manifest is built from. /// +/// The file system path of the stored audio file of the track, used to bind a normalized delivery to the file version it was declared for. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. +/// The audio codec used by the audio file of the track, if applicable. +/// The duration of the audio of the track in seconds. +/// The sample rate of the audio of the track in Hz. +/// The number of audio channels of the track. +/// The bit depth of the audio of the track, if applicable. +/// The bitrate of the audio of the track, in kbps, if applicable. +/// The ReplayGain track gain of the track, in decibels, if applicable. +/// The ReplayGain track peak of the track, if applicable. +/// The ReplayGain album gain of the track, in decibels, if applicable. +/// The ReplayGain album peak of the track, if applicable. [DebuggerDisplay("Container: {Container} Codec: {AudioCodec}")] -public sealed record TrackPlaybackManifestDto -{ - /// - /// Gets the container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. - /// - public string? Container { get; init; } - - /// - /// Gets the audio codec used by the audio file of the track, if applicable. - /// - public string? AudioCodec { get; init; } - - /// - /// Gets the duration of the audio of the track in seconds. - /// - public int DurationInSeconds { get; init; } - - /// - /// Gets the sample rate of the audio of the track in Hz. - /// - public int SampleRate { get; init; } - - /// - /// Gets the number of audio channels of the track. - /// - public int Channels { get; init; } - - /// - /// Gets the bit depth of the audio of the track, if applicable. - /// - public int? BitDepth { get; init; } - - /// - /// Gets the ReplayGain track gain of the track, in decibels, if applicable. - /// - public decimal? ReplayGainTrackGain { get; init; } - - /// - /// Gets the ReplayGain track peak of the track, if applicable. - /// - public decimal? ReplayGainTrackPeak { get; init; } - - /// - /// Gets the ReplayGain album gain of the track, in decibels, if applicable. - /// - public decimal? ReplayGainAlbumGain { get; init; } - - /// - /// Gets the ReplayGain album peak of the track, if applicable. - /// - public decimal? ReplayGainAlbumPeak { get; init; } -} +public sealed record TrackPlaybackManifestDto( + string Path, + string? Container, + string? AudioCodec, + int DurationInSeconds, + int SampleRate, + int Channels, + int? BitDepth, + int? Bitrate, + decimal? ReplayGainTrackGain, + decimal? ReplayGainTrackPeak, + decimal? ReplayGainAlbumGain, + decimal? ReplayGainAlbumPeak +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs index 3ecc0f97..bef2ea79 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs @@ -7,55 +7,27 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T /// /// Data transfer object for a track, containing the data needed to stream, or to describe the streaming of, its audio file. /// -public sealed record TrackStreamDto -{ - /// - /// Gets the file system path of the track. - /// - public required string Path { get; init; } - - /// - /// Gets the Id of the media library the track belongs to. - /// - public required Guid LibraryId { get; init; } - - /// - /// Gets the Id of the album the track belongs to. - /// - public required Guid AlbumId { get; init; } - - /// - /// Gets the Id of the artist that owns the album the track belongs to. - /// - public required Guid ArtistId { get; init; } - - /// - /// Gets the audio codec used by the audio file of the track, if applicable. - /// - public string? AudioCodec { get; init; } - - /// - /// Gets the duration of the audio of the track in seconds. - /// - public int DurationInSeconds { get; init; } - - /// - /// Gets the sample rate of the audio of the track in Hz. - /// - public int SampleRate { get; init; } - - /// - /// Gets the number of audio channels of the track. - /// - public int Channels { get; init; } - - /// - /// Gets the bit depth of the audio of the track, if applicable. - /// - public int? BitDepth { get; init; } - - /// - /// Gets the bitrate of the audio of the track in kbps, if applicable. - /// - public int? Bitrate { get; init; } -} +/// The file system path of the track. +/// The Id of the media library the track belongs to. +/// The Id of the album the track belongs to. +/// The Id of the artist that owns the album the track belongs to. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. +/// The audio codec used by the audio file of the track, if applicable. +/// The duration of the audio of the track in seconds. +/// The sample rate of the audio of the track in Hz. +/// The number of audio channels of the track. +/// The bit depth of the audio of the track, if applicable. +/// The bitrate of the audio of the track, in kbps, if applicable. +public sealed record TrackStreamDto( + string Path, + Guid LibraryId, + Guid AlbumId, + Guid ArtistId, + string? Container, + string? AudioCodec, + int DurationInSeconds, + int SampleRate, + int Channels, + int? BitDepth, + int? Bitrate +); diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs new file mode 100644 index 00000000..4fb828d0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Primitives; +using System; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Interface for the service that issues and resolves the opaque delivery handles of the playback manifest. +/// +/// +/// A delivery handle binds the delivery decision, the quality cap, the source file identity and the user to one opaque value, so the segment route +/// never recomputes them from inputs that can change while the track plays. A handle is only accepted from the user it was issued to, and only for +/// the track it describes, so it is not a capability that can be transferred to another user or track. Its format is exactly 32 lowercase +/// hexadecimal characters, the N format of a , and that format is the only rule every producer and consumer applies: a value +/// that does not match it is rejected, never normalized into another handle. +/// +public interface IPlaybackDeliveryHandleService +{ + /// + /// Issues an opaque handle for a delivery, which the playback manifest reports so its segments can be addressed by that handle. + /// + /// The delivery, its source file identity, its quality cap and its user. + /// The opaque delivery handle. + string IssueDeliveryId(PlaybackDeliveryHandleDto delivery); + + /// + /// Resolves the delivery a handle addresses, after verifying that it was issued to the provided user and describes the provided track. + /// + /// The opaque delivery handle reported by the playback manifest. + /// The Id of the current user, which the handle must have been issued to. + /// The Id of the track named by the route, which the handle must describe. + /// + /// An containing either the delivery, or when the handle is unknown, expired, or belongs to another user or track. + /// + Result GetDelivery(string? deliveryId, Guid userId, Guid trackId); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs index 45c2f418..998ab9cc 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using System; using System.IO; using System.Threading; @@ -20,18 +21,18 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playbac /// A production is atomic: the cache entry is published only after ffmpeg has finished the whole track, so the first request waits for a complete /// production. Streaming in this contract means serving the produced segments from the cache without buffering them into memory, not publishing a partial /// track. Incremental publication of segment 0 while the rest is produced would be a different contract. Admission is bounded: when every normalization job -/// slot is in use, a request for an entry that is not cached yet is reported as unavailable instead of being queued behind the running jobs. A production -/// that was admitted outlives the request that started it, so repeated aborts converge to a cached entry. A production that needs a toolchain the startup -/// probe found unusable reports as well, while an entry that is already -/// cached is still served. The playback stream surface that exposes the produced segments is the intended consumer of this contract; no API request path -/// calls it yet. +/// slot is in use, a request for an entry that is not cached yet is reported as unavailable instead of being queued behind the running jobs, and a single +/// user can only occupy a configured number of those slots, so a prefetch or a burst of requests from one user cannot make another user's playback fail. +/// A production that was admitted outlives the request that started it, so repeated aborts converge to a cached entry. A production that needs a toolchain the startup +/// probe found unusable reports as well, while an entry that is already +/// cached is still served. The playback stream surface exposes the produced segments to the player through the segment route of the track stream contract. /// public interface ITrackNormalizationService { /// /// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet. /// - /// The track, the delivery decision, the source file and the quality cap the normalized audio is produced with. + /// The track, the requesting user, the delivery decision, the source file and the quality cap the normalized audio is produced with. /// Cancellation token that can be used to stop the execution. /// /// An containing either the cached normalized audio of the track, or an error message. @@ -47,10 +48,9 @@ public interface ITrackNormalizationService /// /// /// A missing or evicted cache entry, a segment that is no longer present, an entry that cannot be read, or a value that is not a well formed handle is - /// reported with . That is the caller's signal to request the + /// reported with . That is the caller's signal to request the /// playback manifest again, or to trigger a new production, instead of treating the result as a broken transcode. A genuine production failure keeps - /// its own error. A service that has already been disposed reports - /// . + /// its own error. A service that has already been disposed reports . /// /// The opaque identifier of the cached entry that holds the normalized audio. /// The Id of the track the caller authorized and whose segment is opened. diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs new file mode 100644 index 00000000..655ad28d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs @@ -0,0 +1,31 @@ +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Defines the format of the opaque delivery handle of a playback manifest. +/// +/// +/// A handle is a rendered with the N format: exactly 32 lowercase hexadecimal characters, with no separator. Every producer +/// and consumer of a handle uses this rule, so a handle is never silently normalized into another value. +/// +public static class PlaybackDeliveryId +{ + /// + /// The number of characters of a delivery handle. + /// + public const int CHARACTER_COUNT = 32; + + /// + /// Checks whether a value has the format of a delivery handle. + /// + /// The value to check. + /// when the value is exactly 32 lowercase hexadecimal characters, otherwise . + public static bool IsValid(string? value) + { + if (value is null || value.Length != CHARACTER_COUNT) + return false; + foreach (char character in value) + if (!((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'))) + return false; + return true; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs index d72cda22..469ff1c9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs @@ -14,6 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks. /// The unique identifier of the track whose playback manifest is retrieved, taken from the route. /// The container and codec pairs the player advertises it can demux and decode directly, taken from the request, or when it advertises none. /// The path of the track stream, relative to the API, taken from the endpoint so that it always matches the stream route. +/// The path template of the segment route, relative to the API, with a {deliveryId} and a {segmentIndex} placeholder, taken from the endpoint so that it always matches the segment route. [DebuggerDisplay("TrackId: {TrackId}")] public record GetPlaybackManifestQuery( string? LibraryId, @@ -21,5 +22,6 @@ public record GetPlaybackManifestQuery( string? AlbumId, string? TrackId, string? Capabilities, - string StreamPath + string StreamPath, + string SegmentStreamPathTemplate ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs index 9c20966e..b3d33cca 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; @@ -11,9 +13,12 @@ using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Collections.Generic; +using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -28,8 +33,10 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler _validator; /// @@ -37,15 +44,19 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler /// Injected unit of work for interacting with the data access layer repositories. /// Injected service for deciding how a track's audio is delivered to a player. + /// Injected service that issues the opaque delivery handles of a normalized manifest. /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. + /// Injected service for file system path related functionality. /// Injected validator for application validation rules. - public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator validator) { _unitOfWork = unitOfWork; _playbackFormatService = playbackFormatService; + _playbackDeliveryHandleService = playbackDeliveryHandleService; _authorizationService = authorizationService; _currentUserService = currentUserService; + _pathService = pathService; _validator = validator; } @@ -102,6 +113,80 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getSettingsResult.IsFailure) + return getSettingsResult.Errors; + if (getSettingsResult.Value is not null) + quality = getSettingsResult.Value.StreamingQuality; + + // The content locations are captured with the delivery, so the segment route does not have to load the library and the track again + // for every six second segment, and it still re-checks path containment on every request. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return Errors.Library.LibraryNotFound; + IReadOnlyList allowedRoots = [.. getLibraryResult.Value.ContentLocations.Select(contentLocation => contentLocation.Path)]; + // The containment invariant is enforced before the file is even stat'ed, exactly as the stream route does, so a normalized manifest never + // touches a path outside the content locations of its library. A path that is not inside them is not stat'ed, and the segment route is + // what rejects it when it tries to resolve the delivery. + bool isInsideContentLocation = allowedRoots.Count > 0 && allowedRoots.Any(contentLocation => _pathService.IsPathWithin(track.Path, contentLocation)); + + // The identity is captured only when the path is inside the library's content locations. A normalized delivery declared for a missing, + // unreadable or out-of-root file records no identity, and the segment route is the authority that rejects it when the delivery is resolved. + long sourceLength = 0; + DateTime sourceLastModifiedUtc = DateTime.MinValue; + if (isInsideContentLocation) + { + try + { + FileInfo sourceFile = new(track.Path); + if (sourceFile.Exists) + { + sourceLength = sourceFile.Length; + sourceLastModifiedUtc = sourceFile.LastWriteTimeUtc; + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + sourceLength = 0; + sourceLastModifiedUtc = DateTime.MinValue; + } + } + + NormalizedTrackRequestDto normalizationRequest = new( + trackId, + userId, + track.Path, + allowedRoots, + track.Container, + decision.Mode, + decision.Container, + decision.Codec, + decision.SegmentDurationSeconds, + track.DurationInSeconds, + track.Bitrate, + track.SampleRate, + track.Channels, + track.BitDepth, + quality, + sourceLength, + sourceLastModifiedUtc); + PlaybackDeliveryHandleDto delivery = new( + normalizationRequest, + decision.Shape, + libraryId, + albumId, + artistId); + deliveryId = _playbackDeliveryHandleService.IssueDeliveryId(delivery); + } + return new PlaybackManifestResponse( trackId, track.DurationInSeconds, @@ -120,6 +205,8 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler +/// Query for getting a single segment of the normalized audio of a track, for streaming. +/// +/// The unique identifier of the media library the track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track whose normalized audio is streamed, taken from the route. +/// The opaque handle of the normalized delivery the segment belongs to, taken from the route. +/// The zero based index of the segment of the normalized audio, taken from the route. +[DebuggerDisplay("TrackId: {TrackId} DeliveryId: {DeliveryId} SegmentIndex: {SegmentIndex}")] +public record GetTrackSegmentQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId, + string? DeliveryId, + string? SegmentIndex +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs new file mode 100644 index 00000000..fc80f5b5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; + +/// +/// Handler for the query to get a single segment of the normalized audio of a track, for streaming. +/// +public class GetTrackSegmentQueryHandler : IQueryHandler> +{ + private readonly ITrackNormalizationService _trackNormalizationService; + private readonly IPlaybackDeliveryHandleService _playbackDeliveryHandleService; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IPathService _pathService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service that produces, caches and serves the normalized audio of a track. + /// Injected service that resolves the opaque delivery handle of the playback manifest. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for file system path related functionality. + /// Injected validator for application validation rules. + public GetTrackSegmentQueryHandler(ITrackNormalizationService trackNormalizationService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator validator) + { + _trackNormalizationService = trackNormalizationService; + _playbackDeliveryHandleService = playbackDeliveryHandleService; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _pathService = pathService; + _validator = validator; + } + + /// + /// Handles the query to get a single segment of the normalized audio of a track, for streaming. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the data of the requested segment, or an error message. + /// + public async Task> HandleAsync(GetTrackSegmentQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers and the segment index are well formed before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + int segmentIndex = int.Parse(query.SegmentIndex!); + + // Admins can stream the tracks of all libraries; for everyone else, only the tracks of the libraries they own. This is the only database + // read of a segment request: the track, library and delivery context were resolved at manifest time and are carried by the delivery handle. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The delivery handle is the only authority on the delivery of the segments: it was issued to this user for this track, and it holds the + // decision, the quality cap, the source file version and the library context the manifest declared. It is never recomputed from a capability + // list, a setting or a file that may have changed since the manifest was read. + Result getDeliveryResult = _playbackDeliveryHandleService.GetDelivery(query.DeliveryId, userId, trackId); + if (getDeliveryResult.IsFailure) + return getDeliveryResult.Errors; + PlaybackDeliveryHandleDto delivery = getDeliveryResult.Value; + if (delivery.LibraryId != libraryId || delivery.AlbumId != albumId || delivery.ArtistId != artistId) + return Errors.Playback.PlaybackDeliveryNotFound; + // A direct play is served by the stream route itself, so a delivery handle for it has no segment. The delivery must also be addressed as + // time addressed segments with a positive segment duration, or the segment route has nothing it can index. + if (delivery.Request.Mode == PlaybackDeliveryMode.DirectPlay) + return Errors.Playback.NormalizationIsNotRequiredForDirectPlay; + if (delivery.Shape != PlaybackDeliveryShape.TimeAddressedSegments || delivery.Request.SegmentDurationSeconds <= 0) + return Errors.Playback.PlaybackDeliveryChanged; + + // The audio file is only handed to the normalization pipeline when it is stored inside one of the content locations of its library, so + // that a stored path can never be used to read an arbitrary file of the host; the failure is reported as not found without the path. + if (!delivery.Request.AllowedRoots.Any(contentLocation => _pathService.IsPathWithin(delivery.Request.SourcePath, contentLocation))) + return Errors.Music.TrackFileNotFound; + + NormalizedTrackRequestDto normalizationRequest = delivery.Request; + + // The segment is read from a cached production, or the whole track is produced and cached first. A production is atomic, so the first + // segment request waits for the complete normalized audio, and every later segment request is served from the cache. A file that changed + // since the manifest declared the delivery is rejected by the service instead of starting a second, incompatible production. + Result normalizedTrackResult = await _trackNormalizationService.GetOrCreateNormalizedTrackAsync(normalizationRequest, cancellationToken).ConfigureAwait(false); + if (normalizedTrackResult.IsFailure) + return normalizedTrackResult.Errors; + NormalizedTrackDto normalizedTrack = normalizedTrackResult.Value; + + NormalizedTrackSegmentDto? segment = normalizedTrack.Segments.FirstOrDefault(candidate => candidate.Index == segmentIndex); + if (segment is null) + return Errors.Playback.NormalizedTrackSegmentNotFound; + + Result openSegmentResult = _trackNormalizationService.OpenNormalizedSegment(normalizedTrack.CacheId, trackId, segmentIndex); + if (openSegmentResult.IsFailure) + return openSegmentResult.Errors; + + return new NormalizedTrackSegmentDataDto(openSegmentResult.Value, segment.Length, segment.StartSeconds, normalizedTrack.Container, normalizedTrack.Segments.Count, normalizedTrack.DurationInSeconds); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs new file mode 100644 index 00000000..9e80e4e7 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; + +/// +/// Validates the needed validation rules for . +/// +public class GetTrackSegmentQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackSegmentQueryValidator() + { + // Validates the identifier of the media library the track belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track whose normalized audio is streamed, taken from the route. + RuleFor(query => query.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(query => query.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(query => query.TrackId is not null && query.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + // Validates the opaque delivery handle the segment belongs to, taken from the route. + RuleFor(query => query.DeliveryId) + .NotEmpty() + .WithError(Errors.Playback.DeliveryIdCannotBeEmpty); + + RuleFor(query => query.DeliveryId) + .Must(PlaybackDeliveryId.IsValid) + .When(query => query.DeliveryId is not null && query.DeliveryId.Length > 0) + .WithError(Errors.Playback.DeliveryIdIsInvalid); + + // Validates the index of the segment of the normalized audio, taken from the route. + RuleFor(query => query.SegmentIndex) + .NotEmpty() + .WithError(Errors.Playback.SegmentIndexCannotBeEmpty); + + RuleFor(query => query.SegmentIndex) + .Must(segmentIndex => int.TryParse(segmentIndex, out int parsedSegmentIndex) && parsedSegmentIndex >= 0) + .When(query => query.SegmentIndex is not null && query.SegmentIndex.Length > 0) + .WithError(Errors.Playback.SegmentIndexMustBeValid); + } +} diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs index d817359d..54642b46 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs @@ -11,7 +11,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Play /// requesting player, and the path of the track stream, so that a player is told what to fetch and how before it fetches any audio. /// /// The Id of the track the manifest describes. -/// The duration of the audio of the track, in seconds. +/// The duration of the audio of the track, in seconds, as stored by the probe. A normalized production can differ slightly; its exact produced duration is reported by the segment responses. /// The container of the audio file of the track, as stored by the probe, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional. /// The codec of the audio of the track, as stored by the probe. Optional. /// The sample rate of the audio of the track, in Hz. @@ -21,14 +21,22 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Play /// The ReplayGain track peak of the track. Optional. /// The ReplayGain album gain of the track, in decibels. Optional. /// The ReplayGain album peak of the track. Optional. -/// Whether the player can play the stored audio as it is, without the server changing its container or its codec. +/// Whether the player can play the stored audio as it is, without the server changing its container or its codec. /// The container of the audio the server delivers, when the delivery is not a direct play. for a direct play. /// The codec of the audio the server delivers, when the delivery is not a direct play. for a direct play. /// The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play. for a direct play. /// The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments. otherwise. -/// Whether the delivered audio can be seeked by the player. +/// Whether the delivered audio can be seeked by the player. /// The path of the track stream, relative to the API, without a host or a scheme, so that a client never reaches the API directly. -[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")] +/// +/// The opaque handle of the normalized delivery, which the segment route accepts in place of a capability list, so the delivery the +/// manifest declared cannot be recomputed from inputs that change while the track plays. for a direct play. +/// +/// +/// The path of the segment route of the normalized delivery, relative to the API and without a host or a scheme, with a {deliveryId} and a +/// {segmentIndex} placeholder. for a direct play, whose delivery is addressed by byte range. +/// +[DebuggerDisplay("TrackId: {TrackId} IsDirectPlay: {IsDirectPlay}")] public sealed record PlaybackManifestResponse( Guid TrackId, int DurationInSeconds, @@ -41,11 +49,13 @@ public sealed record PlaybackManifestResponse( decimal? ReplayGainTrackPeak, decimal? ReplayGainAlbumGain, decimal? ReplayGainAlbumPeak, - bool DirectPlay, + bool IsDirectPlay, string? DeliveryContainer, string? DeliveryCodec, PlaybackDeliveryShape? DeliveryShape, int? SegmentDurationSeconds, - bool Seekable, - string StreamPath + bool IsSeekable, + string StreamPath, + string? DeliveryId, + string? SegmentStreamPathTemplate ); diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index 5151f37a..54f35802 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -341,19 +341,18 @@ internal sealed class TrackRepository : ITrackRepository return await _luminaDbContext.Tracks .AsNoTracking() .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) - .Select(track => new TrackStreamDto - { - Path = track.Path, - LibraryId = track.LibraryId, - AlbumId = track.AlbumId, - ArtistId = track.Album!.ArtistId, - AudioCodec = track.AudioCodec, - DurationInSeconds = track.DurationInSeconds, - SampleRate = track.SampleRate, - Channels = track.Channels, - BitDepth = track.BitDepth, - Bitrate = track.Bitrate - }) + .Select(track => new TrackStreamDto( + track.Path, + track.LibraryId, + track.AlbumId, + track.Album!.ArtistId, + track.Container, + track.AudioCodec, + track.DurationInSeconds, + track.SampleRate, + track.Channels, + track.BitDepth, + track.Bitrate)) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); } @@ -378,19 +377,19 @@ internal sealed class TrackRepository : ITrackRepository return await _luminaDbContext.Tracks .AsNoTracking() .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) - .Select(track => new TrackPlaybackManifestDto - { - Container = track.Container, - AudioCodec = track.AudioCodec, - DurationInSeconds = track.DurationInSeconds, - SampleRate = track.SampleRate, - Channels = track.Channels, - BitDepth = track.BitDepth, - ReplayGainTrackGain = track.ReplayGainTrackGain, - ReplayGainTrackPeak = track.ReplayGainTrackPeak, - ReplayGainAlbumGain = track.ReplayGainAlbumGain, - ReplayGainAlbumPeak = track.ReplayGainAlbumPeak - }) + .Select(track => new TrackPlaybackManifestDto( + track.Path, + track.Container, + track.AudioCodec, + track.DurationInSeconds, + track.SampleRate, + track.Channels, + track.BitDepth, + track.Bitrate, + track.ReplayGainTrackGain, + track.ReplayGainTrackPeak, + track.ReplayGainAlbumGain, + track.ReplayGainAlbumPeak)) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs index 16292916..c18c8c5a 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs @@ -12,14 +12,21 @@ public static partial class Errors public static class Playback { public static Error NoSupportedPlaybackFormat => Error.Forbidden(description: nameof(NoSupportedPlaybackFormat)); + public static Error PlaybackDeliveryChanged => Error.Conflict(description: nameof(PlaybackDeliveryChanged)); + public static Error PlaybackDeliveryNotFound => Error.NotFound(description: nameof(PlaybackDeliveryNotFound)); + public static Error DeliveryIdCannotBeEmpty => Error.Validation(description: nameof(DeliveryIdCannotBeEmpty)); + public static Error DeliveryIdIsInvalid => Error.Validation(description: nameof(DeliveryIdIsInvalid)); public static Error PlaybackFormatNotImplemented => Error.Internal(description: nameof(PlaybackFormatNotImplemented)); public static Error NormalizedTrackCacheEntryNotFound => Error.NotFound(description: nameof(NormalizedTrackCacheEntryNotFound)); + public static Error NormalizedTrackSegmentNotFound => Error.NotFound(description: nameof(NormalizedTrackSegmentNotFound)); public static Error NormalizationFailed => Error.Failure(description: nameof(NormalizationFailed)); public static Error NormalizationCacheLimitExceeded => Error.Failure(description: nameof(NormalizationCacheLimitExceeded)); public static Error NormalizationTimedOut => Error.Timeout(description: nameof(NormalizationTimedOut)); public static Error NormalizationUnavailable => Error.ResourceUnavailable(description: nameof(NormalizationUnavailable)); - public static Error NormalizationIsNotRequiredForDirectPlay => Error.InvalidOperation(description: nameof(NormalizationIsNotRequiredForDirectPlay)); + public static Error NormalizationIsNotRequiredForDirectPlay => Error.Conflict(description: nameof(NormalizationIsNotRequiredForDirectPlay)); public static Error SegmentDurationMustBePositive => Error.Validation(description: nameof(SegmentDurationMustBePositive)); + public static Error SegmentIndexCannotBeEmpty => Error.Validation(description: nameof(SegmentIndexCannotBeEmpty)); + public static Error SegmentIndexMustBeValid => Error.Validation(description: nameof(SegmentIndexMustBeValid)); public static Error TrackDurationMustBePositive => Error.Validation(description: nameof(TrackDurationMustBePositive)); } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index b36d8d58..06a35358 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -152,12 +152,16 @@ public static class InfrastructureLayerServices // repackaged into another container, or re-encoded into another codec. services.AddSingleton(); + // Music playback: issues and resolves the opaque delivery handles reported by a playback manifest, so the segment route never has to + // recompute the delivery decision, the quality cap or the source file identity from values that can change while the track plays. + services.AddSingleton(); + // Music playback: records the outcome of the ffmpeg probe, so a missing binary or encoder is reported as unavailable for the affected formats. services.AddSingleton(); // Music playback: produces the normalized (remuxed or transcoded) audio of a track with ffmpeg, caches it as fixed duration - // segments and serves it from the cache, bounded in concurrency, cancellable and capped in disk usage. The playback stream surface - // is its intended consumer; no API request path calls it yet. + // segments and serves it from the cache, bounded in concurrency, cancellable and capped in disk usage. The segment route of the + // playback stream surface is its consumer. services.AddSingleton(); // Music playback: owns the normalized audio cache lifecycle and verifies the ffmpeg encoders at startup, so a missing or changed toolchain diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index b13262b8..ff960a4d 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -36,6 +36,9 @@ public static partial class Errors public static Error TranscodingFfmpegPathCannotBeEmpty => Error.Validation(description: nameof(TranscodingFfmpegPathCannotBeEmpty)); public static Error TranscodingMaxConcurrentJobsMustBePositive => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsMustBePositive)); public static Error TranscodingMaxConcurrentJobsIsTooLarge => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsIsTooLarge)); + public static Error TranscodingMaxConcurrentJobsPerUserMustBePositive => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsPerUserMustBePositive)); + public static Error TranscodingMaxConcurrentJobsPerUserIsTooLarge => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsPerUserIsTooLarge)); + public static Error TranscodingMaxConcurrentJobsPerUserExceedsGlobal => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsPerUserExceedsGlobal)); public static Error TranscodingMaxCacheBytesMustBePositive => Error.Validation(description: nameof(TranscodingMaxCacheBytesMustBePositive)); public static Error TranscodingJobTimeoutMustBePositive => Error.Validation(description: nameof(TranscodingJobTimeoutMustBePositive)); public static Error TranscodingJobTimeoutIsTooLong => Error.Validation(description: nameof(TranscodingJobTimeoutIsTooLong)); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs index a533f8e5..140a1771 100644 --- a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs @@ -22,6 +22,12 @@ public sealed class TranscodingSettingsDto /// public int MaxConcurrentJobs { get; set; } = 2; + /// + /// Gets or sets the maximum number of normalization jobs a single user may have running at the same time. A production that was + /// started by another user can still be waited for, because it is shared by every request for the same track and delivery. + /// + public int MaxConcurrentJobsPerUser { get; set; } = 1; + /// /// Gets or sets the maximum total size of the normalized audio cache, in bytes. /// diff --git a/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs index 4d4d5213..7ad7a3db 100644 --- a/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs @@ -53,6 +53,19 @@ public class TranscodingSettingsDtoValidator : AbstractValidator maxConcurrentJobs <= MAX_CONCURRENT_JOBS) .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge); + RuleFor(settings => settings.MaxConcurrentJobsPerUser) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsPerUserMustBePositive); + + RuleFor(settings => settings.MaxConcurrentJobsPerUser) + .Must(maxConcurrentJobsPerUser => maxConcurrentJobsPerUser <= MAX_CONCURRENT_JOBS) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge); + + // A per-user limit above the global one can never be reached, and would hide a misconfiguration that looks like a working cap. + RuleFor(settings => settings.MaxConcurrentJobsPerUser) + .Must((settings, maxConcurrentJobsPerUser) => maxConcurrentJobsPerUser <= settings.MaxConcurrentJobs) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsPerUserExceedsGlobal); + RuleFor(settings => settings.MaxCacheBytes) .GreaterThan(0) .WithError(Errors.Errors.Configuration.TranscodingMaxCacheBytesMustBePositive); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs new file mode 100644 index 00000000..1ae2e490 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs @@ -0,0 +1,251 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Issues and resolves the opaque delivery handles of the playback manifest, which bind a normalized delivery to the user, the track and the inputs the delivery was declared with. +/// +/// +/// The handles are process local, like the normalized audio cache they address. An API process must therefore keep handling both the manifest and +/// the segments of a track for a handle to resolve, which is the deployment the cache already requires: a single API process per cache directory. +/// A handle expires after a bounded lifetime, and the registry is bounded both globally and per user. Expired entries are removed from a queue in +/// issue order, so the sweep is amortized constant time and does not scan every handle. A repeated manifest for the same delivery inputs reuses the +/// handle that already exists for them, so reloading a manifest does not grow the registry. +/// +internal sealed class PlaybackDeliveryHandleService : IPlaybackDeliveryHandleService +{ + private const int MAX_DELIVERIES = 20_000; + private const int MAX_DELIVERIES_PER_USER = 64; + private static readonly TimeSpan s_deliveryLifetime = TimeSpan.FromHours(12); + + private readonly Lock _deliveryLock = new(); + // These dictionaries share one logical invariant: a delivery handle is split across the delivery map, its signature map, its per-user queue and count, + // and the global expiry queue. ConcurrentDictionary would make each collection thread-safe on its own, but not the multi-step issue, reuse, evict and remove sequences, + // which must see all of them consistently. The Lock is held only for short, O(1), non-awaiting work, so replacing these collections with concurrent ones would add + // complexity without removing the lock. Do not "fix" this without redesigning the state into one atomically updated map. + private readonly Dictionary _deliveries = []; + private readonly Dictionary _deliveryIdsBySignature = []; + private readonly Dictionary> _deliveryIdsByUser = []; + private readonly Dictionary _deliveryCountsByUser = []; + private readonly Queue<(string DeliveryId, DateTimeOffset ExpiresAtUtc)> _expiryQueue = []; + + /// + /// Issues an opaque handle for a delivery, which the playback manifest reports so its segments can be addressed by that handle. + /// + /// The delivery, its source file identity, its quality cap and its user. + /// The opaque delivery handle. + public string IssueDeliveryId(PlaybackDeliveryHandleDto delivery) + { + string signature = BuildSignature(delivery); + lock (_deliveryLock) + { + DateTimeOffset now = DateTimeOffset.UtcNow; + RemoveExpiredDeliveries(now); + if (_deliveryIdsBySignature.TryGetValue(signature, out string? existingDeliveryId) + && _deliveries.TryGetValue(existingDeliveryId, out StoredDelivery? existingDelivery) + && existingDelivery.ExpiresAtUtc > now) + return existingDeliveryId; + if (existingDeliveryId is not null) + RemoveDelivery(existingDeliveryId); + + EnforceUserLimit(delivery.Request.UserId); + EnforceGlobalLimit(); + + // The handle is a random opaque value, not a derived one, so it cannot be computed from the track or the file by a caller. + string deliveryId = Guid.NewGuid().ToString("N"); + DateTimeOffset expiresAtUtc = now.Add(s_deliveryLifetime); + _deliveries[deliveryId] = new StoredDelivery(delivery, signature, expiresAtUtc); + _deliveryIdsBySignature[signature] = deliveryId; + _deliveryCountsByUser[delivery.Request.UserId] = _deliveryCountsByUser.GetValueOrDefault(delivery.Request.UserId) + 1; + if (!_deliveryIdsByUser.TryGetValue(delivery.Request.UserId, out Queue? userDeliveryIds)) + { + userDeliveryIds = []; + _deliveryIdsByUser[delivery.Request.UserId] = userDeliveryIds; + } + userDeliveryIds.Enqueue(deliveryId); + _expiryQueue.Enqueue((deliveryId, expiresAtUtc)); + return deliveryId; + } + } + + /// + /// Resolves the delivery a handle addresses, after verifying that it was issued to the provided user and describes the provided track. + /// + /// The opaque delivery handle reported by the playback manifest. + /// The Id of the current user, which the handle must have been issued to. + /// The Id of the track named by the route, which the handle must describe. + /// + /// An containing either the delivery, or when the handle + /// is unknown, expired, or belongs to another user or track. + /// + public Result GetDelivery(string? deliveryId, Guid userId, Guid trackId) + { + if (string.IsNullOrWhiteSpace(deliveryId)) + return Errors.Playback.PlaybackDeliveryNotFound; + + lock (_deliveryLock) + { + if (!_deliveries.TryGetValue(deliveryId, out StoredDelivery? entry)) + return Errors.Playback.PlaybackDeliveryNotFound; + if (entry.ExpiresAtUtc <= DateTimeOffset.UtcNow) + { + RemoveDelivery(deliveryId); + return Errors.Playback.PlaybackDeliveryNotFound; + } + // A handle is not a capability: it is only valid for the user it was issued to and the track it describes, so a leaked handle + // cannot be used to read another user's track or another track of the same user. + if (entry.Delivery.Request.UserId != userId || entry.Delivery.Request.TrackId != trackId) + return Errors.Playback.PlaybackDeliveryNotFound; + return entry.Delivery; + } + } + + /// + /// Enforces the per-user handle limit by evicting the oldest handles of that user. + /// + /// The Id of the user whose handles are bounded. + private void EnforceUserLimit(Guid userId) + { + while (_deliveryCountsByUser.GetValueOrDefault(userId) >= MAX_DELIVERIES_PER_USER) + if (!TryEvictOldestForUser(userId)) + break; + } + + /// + /// Enforces the global handle limit by evicting the oldest handle. + /// + private void EnforceGlobalLimit() + { + while (_deliveries.Count >= MAX_DELIVERIES) + if (!TryEvictOldestDelivery()) + break; + } + + /// + /// Evicts the oldest handle that is still registered for a user. + /// + /// The Id of the user whose oldest handle is evicted. + /// when a handle was evicted, otherwise . + private bool TryEvictOldestForUser(Guid userId) + { + if (!_deliveryIdsByUser.TryGetValue(userId, out Queue? userDeliveryIds)) + return false; + while (userDeliveryIds.Count > 0) + { + string deliveryId = userDeliveryIds.Dequeue(); + if (!_deliveries.ContainsKey(deliveryId)) + continue; + RemoveDelivery(deliveryId); + return true; + } + _deliveryIdsByUser.Remove(userId); + return false; + } + + /// + /// Evicts the oldest handle that is still registered, using the expiry queue as the age order. + /// + /// when a handle was evicted, otherwise . + private bool TryEvictOldestDelivery() + { + while (_expiryQueue.Count > 0) + { + (string deliveryId, DateTimeOffset expiresAtUtc) = _expiryQueue.Dequeue(); + if (!_deliveries.TryGetValue(deliveryId, out StoredDelivery? storedDelivery) || storedDelivery.ExpiresAtUtc != expiresAtUtc) + continue; + RemoveDelivery(deliveryId); + return true; + } + return false; + } + + /// + /// Removes the deliveries whose lifetime ended, in expiry order, so the sweep does not scan the registry. + /// + /// The current time, in UTC. + private void RemoveExpiredDeliveries(DateTimeOffset now) + { + while (_expiryQueue.Count > 0) + { + (string deliveryId, DateTimeOffset expiresAtUtc) = _expiryQueue.Peek(); + if (expiresAtUtc > now) + return; + _expiryQueue.Dequeue(); + if (_deliveries.TryGetValue(deliveryId, out StoredDelivery? storedDelivery) && storedDelivery.ExpiresAtUtc == expiresAtUtc) + RemoveDelivery(deliveryId); + } + } + + /// + /// Removes one delivery and its signature and per-user accounting. + /// + /// The opaque handle of the delivery to remove. + private void RemoveDelivery(string deliveryId) + { + if (!_deliveries.Remove(deliveryId, out StoredDelivery? storedDelivery)) + return; + if (_deliveryIdsBySignature.TryGetValue(storedDelivery.Signature, out string? mappedDeliveryId) && mappedDeliveryId == deliveryId) + _deliveryIdsBySignature.Remove(storedDelivery.Signature); + if (_deliveryCountsByUser.TryGetValue(storedDelivery.Delivery.Request.UserId, out int count)) + { + if (count <= 1) + _deliveryCountsByUser.Remove(storedDelivery.Delivery.Request.UserId); + else + _deliveryCountsByUser[storedDelivery.Delivery.Request.UserId] = count - 1; + } + } + + /// + /// Builds the key that identifies a delivery for de-duplication, from every input that changes the handle's meaning. + /// + /// The delivery to key. + /// The signature of the delivery. + private static string BuildSignature(PlaybackDeliveryHandleDto delivery) + { + return string.Join('\u001F', new string[] + { + delivery.Request.UserId.ToString("N"), + delivery.Request.TrackId.ToString("N"), + delivery.LibraryId.ToString("N"), + delivery.AlbumId.ToString("N"), + delivery.ArtistId.ToString("N"), + ((int)delivery.Request.Mode).ToString(CultureInfo.InvariantCulture), + ((int)delivery.Shape).ToString(CultureInfo.InvariantCulture), + delivery.Request.SourceContainer ?? string.Empty, + delivery.Request.Container, + delivery.Request.Codec, + delivery.Request.SegmentDurationSeconds.ToString(CultureInfo.InvariantCulture), + delivery.Request.DurationInSeconds.ToString(CultureInfo.InvariantCulture), + delivery.Request.Bitrate?.ToString(CultureInfo.InvariantCulture) ?? string.Empty, + delivery.Request.SampleRate.ToString(CultureInfo.InvariantCulture), + delivery.Request.Channels.ToString(CultureInfo.InvariantCulture), + delivery.Request.BitDepth?.ToString(CultureInfo.InvariantCulture) ?? string.Empty, + ((int)delivery.Request.Quality).ToString(CultureInfo.InvariantCulture), + delivery.Request.SourcePath, + delivery.Request.SourceLength.ToString(CultureInfo.InvariantCulture), + delivery.Request.SourceLastModifiedUtc.Ticks.ToString(CultureInfo.InvariantCulture), + string.Join('\u001E', delivery.Request.AllowedRoots) + }); + } + + /// + /// A registered delivery, its de-duplication signature and its expiry. + /// + /// The delivery the handle addresses. + /// The signature of every input that changes the handle's meaning. + /// The time, in UTC, after which the handle is no longer accepted. + private sealed record StoredDelivery( + PlaybackDeliveryHandleDto Delivery, + string Signature, + DateTimeOffset ExpiresAtUtc + ); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs index 0fb9cfec..1ac540be 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs @@ -73,6 +73,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID private const decimal SEGMENT_TIME_TOLERANCE_SECONDS = 0.001m; private const decimal DURATION_TOLERANCE_MIN_SECONDS = 1m; private const decimal DURATION_TOLERANCE_RATIO = 0.02m; + private const int MAX_TRACK_PROJECTIONS = 1024; // The demuxer of each container the probe can report. Pinning the demuxer stops ffmpeg from probing the content of the file and selecting a // demuxer that can open a playlist or another indirection; the file protocol whitelist is the backstop for a container that is not listed here. @@ -124,8 +125,15 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID private readonly TimeSpan _touchThrottleInterval; private readonly SemaphoreSlim _jobSlots; private readonly ConcurrentDictionary _runningProcesses = new(); + // The projection of a cache index is reused between segment requests, so a cached track is not re-projected for every segment. The bound keeps + // the retained metadata small; a cleared cache is repopulated lazily from the index on the next request. + private readonly ConcurrentDictionary<(string CacheRoot, string CacheId), NormalizedTrackDto> _trackProjections = new(); private readonly CancellationTokenSource _shutdownCancellation = new(); private readonly Lock _lifecycleSync = new(); + // The global job slots are shared, but one user must not be able to take all of them and block another user's playback. These two fields guard + // the per-user admission count; they are not part of the cache identity, because a production is shared by every user that requests it. + private readonly Lock _userProductionLock = new(); + private readonly Dictionary _activeProductionsPerUser = []; private readonly ManualResetEventSlim _productionsDrained = new(initialState: true); private readonly string _cacheRoot; private int _activeProductionCount; @@ -176,6 +184,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID return Errors.Playback.NormalizationUnavailable; if (request.TrackId == Guid.Empty) return Errors.Playback.NormalizationFailed; + if (request.UserId == Guid.Empty) + return Errors.Playback.NormalizationFailed; if (string.IsNullOrWhiteSpace(request.SourcePath)) return Errors.Music.TrackPathCannotBeEmpty; // The caller authorizes the request, and the service re-validates the source path against the content locations carried by the request. A path @@ -212,6 +222,11 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID return Errors.Music.TrackFileNotFound; // A file that cannot be read is indistinguishable, to the caller, from a file that does not exist. } + // The delivery was declared against a specific version of the source file. A file that changed since then would produce a new cache + // entry with a different identity, so its segments would be mixed with the segments of the declared delivery. It is rejected instead. + if (request.SourceLength != sourceLength || request.SourceLastModifiedUtc != sourceLastModifiedUtc) + return Errors.Playback.PlaybackDeliveryChanged; + string cacheId = BuildCacheId(request, sourceFile.FullName, sourceLength, sourceLastModifiedUtc, format); // The entry is touched before its index is read, so that a cache hit can never race an eviction that is deciding on the entry at the same time: // an eviction that runs after the touch sees the entry as recently used, and one that ran before the touch makes the read miss and produce anew. @@ -433,30 +448,79 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID /// An containing either the normalized audio of the track, or an error message. private async Task> ProduceAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc) { - lock (_lifecycleSync) - { - // A production that arrives after shutdown has started must not touch the cancellation source, the job slots or the coordinator, because shutdown may already have disposed them. - if (_isDisposed) - return Errors.Playback.NormalizationUnavailable; - // Dispose waits on _productionsDrained before it releases the coordinator and job slots. Counting the production here closes the race - // between the disposal check above and the resources being released while the production is still using them. - _activeProductionCount++; - if (_activeProductionCount == 1) - _productionsDrained.Reset(); - } + // The global job slots are shared by every user, so a user who starts many productions at once could occupy all of them and make + // another user's playback fail. The per-user admission happens before the production is registered, and a request that joins a + // production another user already started does not reach this method, so a shared production is never charged twice. + if (!TryAcquireUserProductionSlot(request.UserId)) + return Errors.Playback.NormalizationUnavailable; try { - return await ProduceCoreAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc).ConfigureAwait(false); + lock (_lifecycleSync) + { + // A production that arrives after shutdown has started must not touch the cancellation source, the job slots or the coordinator, because shutdown may already have disposed them. + if (_isDisposed) + return Errors.Playback.NormalizationUnavailable; + // Dispose waits on _productionsDrained before it releases the coordinator and job slots. Counting the production here closes the race + // between the disposal check above and the resources being released while the production is still using them. + _activeProductionCount++; + if (_activeProductionCount == 1) + _productionsDrained.Reset(); + } + + try + { + return await ProduceCoreAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc).ConfigureAwait(false); + } + finally + { + lock (_lifecycleSync) + { + _activeProductionCount--; + if (_activeProductionCount == 0) + _productionsDrained.Set(); + } + } } finally { - lock (_lifecycleSync) - { - _activeProductionCount--; - if (_activeProductionCount == 0) - _productionsDrained.Set(); - } + ReleaseUserProductionSlot(request.UserId); + } + } + + /// + /// Reserves one of the per-user production slots before a production is admitted, so one user can never occupy every global job slot. + /// + /// The Id of the user whose request starts the production. + /// when the slot was reserved, otherwise. + private bool TryAcquireUserProductionSlot(Guid userId) + { + lock (_userProductionLock) + { + if (userId == Guid.Empty) + return false; + int activeProductions = _activeProductionsPerUser.GetValueOrDefault(userId); + if (activeProductions >= _settings.MaxConcurrentJobsPerUser) + return false; + _activeProductionsPerUser[userId] = activeProductions + 1; + return true; + } + } + + /// + /// Releases a per-user production slot that was reserved by . + /// + /// The Id of the user whose production ended. + private void ReleaseUserProductionSlot(Guid userId) + { + lock (_userProductionLock) + { + if (!_activeProductionsPerUser.TryGetValue(userId, out int activeProductions)) + return; + if (activeProductions <= 1) + _activeProductionsPerUser.Remove(userId); + else + _activeProductionsPerUser[userId] = activeProductions - 1; } } @@ -616,7 +680,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID if (isKeptOverCapacity) _logger.LogWarning("The normalized audio of track {TrackId} in cache entry {CacheId} was produced successfully but exceeds the configured normalized audio cache limit. It is kept readable and will be evicted when it is no longer in use.", request.TrackId, cacheId); - return CreateNormalizedTrackDto(cacheId, index); + return GetOrCreateTrackProjection(cacheId, index); } catch (OperationCanceledException) { @@ -1047,10 +1111,29 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID if (!TryReadIndex(cacheId, out NormalizedTrackIndexDto? index) || index is null) return false; - normalizedTrack = CreateNormalizedTrackDto(cacheId, index); + normalizedTrack = GetOrCreateTrackProjection(cacheId, index); return true; } + /// + /// Projects a validated cache index once and reuses the projection for the following segment requests of the same cached track. + /// + /// The opaque identifier of the cache entry that holds the normalized audio. + /// The validated index of the cache entry. + /// The normalized track described by the index. + private NormalizedTrackDto GetOrCreateTrackProjection(string cacheId, NormalizedTrackIndexDto index) + { + (string CacheRoot, string CacheId) key = (_cacheRoot, cacheId); + if (_trackProjections.TryGetValue(key, out NormalizedTrackDto? existing) && existing.TrackId == index.TrackId) + return existing; + NormalizedTrackDto projection = CreateNormalizedTrackDto(cacheId, index); + // The projection is metadata only, but unbounded retention is not useful: when the bound is reached, the cache is dropped and rebuilt lazily. + if (_trackProjections.Count >= MAX_TRACK_PROJECTIONS) + _trackProjections.Clear(); + _trackProjections[key] = projection; + return projection; + } + /// /// Projects a validated cache index into the normalized track the caller receives. /// diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index b984fd84..59f643fd 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -20,6 +20,7 @@ "TranscodingSettings": { "FfmpegPath": "ffmpeg", "MaxConcurrentJobs": 2, + "MaxConcurrentJobsPerUser": 1, "MaxCacheBytes": 2147483648, "JobTimeoutSeconds": 900, "EvictionGraceSeconds": 120, diff --git a/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs b/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs index 1102517f..50cbda20 100644 --- a/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs +++ b/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; using System.Collections.Frozen; using System.Collections.Generic; #endregion @@ -29,6 +30,20 @@ public static class MusicMimeTypes { AudioFileFormat.MATROSKA, "audio/x-matroska" } }.ToFrozenDictionary(); + // Container names are mapped to the file format enumeration instead of to their own media type strings, so the media type table above stays the + // single source of truth and a new format only needs one entry. + private static readonly FrozenDictionary s_containerToAudioFileFormat = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "MP3", AudioFileFormat.MP3 }, + { "FLAC", AudioFileFormat.FLAC }, + { "MP4", AudioFileFormat.M4A }, + { "M4A", AudioFileFormat.M4A }, + { "AAC", AudioFileFormat.AAC }, + { "OGG", AudioFileFormat.OGG }, + { "OPUS", AudioFileFormat.OPUS }, + { "WAV", AudioFileFormat.WAV } + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + /// /// Gets the MIME content type of . /// @@ -38,4 +53,16 @@ public static class MusicMimeTypes { return s_audioFileFormatToMimeType.TryGetValue(format, out string? mimeType) ? mimeType : "application/octet-stream"; } + + /// + /// Gets the MIME content type of an audio container, as named by the delivery decision of a playback manifest. + /// + /// The canonical container of the delivered audio, for example MP4, AAC, OGG, MP3, FLAC or WAV. + /// The MIME content type of , or application/octet-stream when the container is unknown. + public static string GetContainerMimeType(string? container) + { + return !string.IsNullOrWhiteSpace(container) && s_containerToAudioFileFormat.TryGetValue(container.Trim(), out AudioFileFormat format) + ? GetMimeType(format) + : "application/octet-stream"; + } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs index 34ab9696..963c3c17 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs @@ -15,6 +15,7 @@ public static partial class ApiRoutes public const string UPDATE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string STREAM_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + public const string STREAM_TRACK_SEGMENT = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}"; public const string GET_PLAYBACK_MANIFEST = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs index 2074be09..fb6404fb 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs @@ -45,16 +45,20 @@ public abstract class BaseEndpoint : Endpoint extensionsDictionary = []; - int statusCode = error.Type switch - { - ErrorType.Validation => StatusCodes.Status400BadRequest, - ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in) - ErrorType.Failure => StatusCodes.Status403Forbidden, - ErrorType.Forbidden => StatusCodes.Status403Forbidden, - ErrorType.NotFound => StatusCodes.Status404NotFound, - ErrorType.Conflict => StatusCodes.Status409Conflict, - _ => StatusCodes.Status500InternalServerError, - }; + // A resource that is temporarily unavailable is a transient condition of the server, not an unexpected failure, so it is reported as + // unavailable rather than as an internal error. A client can retry it, and the playback player does. + int statusCode = error is ResourceUnavailableError + ? StatusCodes.Status503ServiceUnavailable + : error.Type switch + { + ErrorType.Validation => StatusCodes.Status400BadRequest, + ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in) + ErrorType.Failure => StatusCodes.Status403Forbidden, + ErrorType.Forbidden => StatusCodes.Status403Forbidden, + ErrorType.NotFound => StatusCodes.Status404NotFound, + ErrorType.Conflict => StatusCodes.Status409Conflict, + _ => StatusCodes.Status500InternalServerError, + }; extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier; @@ -79,15 +83,11 @@ public abstract class BaseEndpoint : Endpoint +/// A response result that writes an owned stream to the response without buffering it and releases the stream once the response is complete. +/// +/// +/// The result owns the stream, so a lease protected resource that is served through it is always released, including when the client disconnects +/// before the whole content was written. Unlike a result built from bytes, it never materializes the content in memory. +/// +public sealed class DisposingStreamResult : IResult +{ + private readonly Stream _content; + private readonly string _contentType; + private readonly long? _contentLength; + + /// + /// Initializes a new instance of the class. + /// + /// The stream to write, which this result owns and releases after the response is complete. + /// The media type of the content. + /// The length of the content, in bytes, or when it is not known in advance. + public DisposingStreamResult(Stream content, string contentType, long? contentLength) + { + _content = content; + _contentType = contentType; + _contentLength = contentLength; + } + + /// + /// Writes the content stream to the response. + /// + /// The HTTP context of the request being answered. + public async Task ExecuteAsync(HttpContext httpContext) + { + if (_contentLength.HasValue) + httpContext.Response.ContentLength = _contentLength.Value; + httpContext.Response.ContentType = _contentType; + await using (_content) + await _content.CopyToAsync(httpContext.Response.Body, httpContext.RequestAborted).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs index ddef6938..15ac1aeb 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs @@ -62,8 +62,23 @@ public class GetPlaybackManifestEndpoint : BaseEndpoint .Replace("{artistId}", artistId, StringComparison.Ordinal) .Replace("{albumId}", albumId, StringComparison.Ordinal) .Replace("{trackId}", trackId, StringComparison.Ordinal); - GetPlaybackManifestQuery query = new(libraryId, artistId, albumId, trackId, capabilities, streamPath); + // The segment route is filled in from the same route values, and its delivery handle and segment index placeholders are kept for the player + // to expand, so the manifest and the segment route can never disagree on the shape of the path either. The delivery handle is what binds + // the segments to the delivery this manifest declared; the capabilities are not repeated in the path. + string segmentStreamPathTemplate = ApiRoutes.Tracks.STREAM_TRACK_SEGMENT + .Replace("{libraryId}", libraryId, StringComparison.Ordinal) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + GetPlaybackManifestQuery query = new(libraryId, artistId, albumId, trackId, capabilities, streamPath, segmentStreamPathTemplate); Result result = await _getPlaybackManifestQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); + return result.Match(success => + { + // The manifest carries delivery metadata specific to the authenticated user, so no intermediary may store it and every response varies by + // the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + return TypedResults.Ok(success); + }, Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs index b5e5c781..14e54f8f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs @@ -34,13 +34,15 @@ public class GetPlaybackManifestEndpointSummary : Summary(r => r.ReplayGainTrackPeak, "The ReplayGain track peak of the track, if applicable."); ResponseParam(r => r.ReplayGainAlbumGain, "The ReplayGain album gain of the track, in decibels, if applicable."); ResponseParam(r => r.ReplayGainAlbumPeak, "The ReplayGain album peak of the track, if applicable."); - ResponseParam(r => r.DirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec."); + ResponseParam(r => r.IsDirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec."); ResponseParam(r => r.DeliveryContainer, "The container of the audio the server delivers, when the delivery is not a direct play."); ResponseParam(r => r.DeliveryCodec, "The codec of the audio the server delivers, when the delivery is not a direct play."); ResponseParam(r => r.DeliveryShape, "The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play."); ResponseParam(r => r.SegmentDurationSeconds, "The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments."); - ResponseParam(r => r.Seekable, "Whether the delivered audio can be seeked by the player."); + ResponseParam(r => r.IsSeekable, "Whether the delivered audio can be seeked by the player."); ResponseParam(r => r.StreamPath, "The path of the track stream, relative to the API, without a host or a scheme."); + ResponseParam(r => r.DeliveryId, "The opaque handle of the normalized delivery, which the segment route accepts. Null for a direct play."); + ResponseParam(r => r.SegmentStreamPathTemplate, "The path template of the segment route of the normalized delivery, relative to the API, with {deliveryId} and {segmentIndex} placeholders. Null for a direct play."); Response(200, "The playback manifest of the track is returned.", example: new PlaybackManifestResponse( @@ -55,13 +57,15 @@ public class GetPlaybackManifestEndpointSummary : Summary +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex} route. +/// +public class GetTrackSegmentEndpoint : BaseEndpoint +{ + // The name is repeated in the web client application, which is a separate project that keeps its own contracts, so both sides must change together. + private const string SEGMENT_COUNT_HEADER_NAME = "X-Lumina-Segment-Count"; + private const string SEGMENT_START_SECONDS_HEADER_NAME = "X-Segment-Start-Seconds"; + private const string TRACK_DURATION_SECONDS_HEADER_NAME = "X-Lumina-Track-Duration-Seconds"; + + private readonly IQueryHandler> _getTrackSegmentQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get track segment queries. + public GetTrackSegmentEndpoint(IQueryHandler> getTrackSegmentQueryHandler) + { + _getTrackSegmentQueryHandler = getTrackSegmentQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Tracks.STREAM_TRACK_SEGMENT); + Version(1); + DontCatchExceptions(); + // The segment stream is limited per user with the same concurrency limiter as the track stream, and it is excluded from the eventual + // consistency pipeline, because a long lived response would otherwise hold the request's database transaction open for its whole duration. + Options(builder => builder + .RequireRateLimiting(PresentationApiLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY) + .WithMetadata(new SkipEventualConsistencyMetadata())); + } + + /// + /// Streams one segment of the normalized audio of the track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers and the segment index from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + string? deliveryId = HttpContext.Request.RouteValues["deliveryId"]?.ToString(); + string? segmentIndex = HttpContext.Request.RouteValues["segmentIndex"]?.ToString(); + GetTrackSegmentQuery query = new(libraryId, artistId, albumId, trackId, deliveryId, segmentIndex); + Result result = await _getTrackSegmentQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + if (result.IsFailure) + return Problem(result.Errors); + + // The produced segment is private to the authenticated user and is served from a temporary cache, so it must never be stored by an + // intermediary, and content sniffing stays disabled, so a segment can never be interpreted as active content. + HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff"; + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // The count lets the player stop at the end of the production instead of probing for it with a request that cannot be told apart + // from a track that was deleted or moved. It is sent on every segment, because any segment can be the first one a player fetches. + HttpContext.Response.Headers[SEGMENT_COUNT_HEADER_NAME] = result.Value.SegmentCount.ToString(); + // The real start of the segment, because ffmpeg cuts at the first packet at or after a segment boundary and a container can number its + // frames from the start of the track. The player offsets the packets by this value instead of assuming an exact multiple of the duration. + HttpContext.Response.Headers[SEGMENT_START_SECONDS_HEADER_NAME] = result.Value.StartSeconds.ToString(CultureInfo.InvariantCulture); + // The produced duration can differ from the probed duration, so the player uses this value for its timeline and progress bar. + HttpContext.Response.Headers[TRACK_DURATION_SECONDS_HEADER_NAME] = result.Value.DurationInSeconds.ToString(CultureInfo.InvariantCulture); + // The length comes from the index of the production, so the response is length delimited without reading the segment into memory first. + return new DisposingStreamResult(result.Value.Content, MusicMimeTypes.GetContainerMimeType(result.Value.Container), result.Value.Length); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs new file mode 100644 index 00000000..342dc56a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTrackSegmentEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackSegmentEndpointSummary() + { + Summary = "Streams one segment of the normalized audio of a track."; + Description = "Streams a single fixed duration segment of the normalized audio of the track identified by the route. A track that is not a direct play is delivered as fixed duration, time addressed segments, so a player seeks by segment index and never maps a byte range to a time. The delivery handle is the opaque value the playback manifest reports in its deliveryId, and the segment index is zero based; together they name a segment of exactly the delivery the manifest declared, including its quality cap and the source file version it was declared for. Library ownership is re-evaluated on every request, while track membership and content locations are those captured at manifest time, so a deleted track row whose file remains can stay streamable until the handle expires. The first request for a track may wait for the whole normalized audio to be produced and cached. The segment is streamed to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track."; + + Response(200, "The requested segment is streamed, with the media type of the delivered container, or application/octet-stream when the container is not an audio type, with the length of the segment as its content length, and with the segment count and its exact start time on the track timeline as the X-Lumina-Segment-Count and X-Segment-Start-Seconds headers.", "*/*"); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the delivery handle is unknown, expired, or was issued to another user or track, the track or its media library does not exist, the track does not belong to the library, album and artist named by the route, the audio file of the track is outside the content locations of its library, missing, or unreadable, or the requested segment does not exist. Only the NormalizedTrackSegmentNotFound detail means the end of the normalized audio; every other not found detail is a playback failure.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaybackDeliveryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "NormalizedTrackSegmentNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/999", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "NormalizedTrackCacheEntryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/999", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The delivery handle does not describe time addressed segments, or the source file changed since the manifest declared the delivery. The player must request the playback manifest again.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "PlaybackDeliveryChanged", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/not-a-handle/segments/-1", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty", + "DeliveryIdCannotBeEmpty", + "DeliveryIdIsInvalid", + "SegmentIndexMustBeValid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + + Response(503, "Every normalization job slot, globally or for this user, is in use. The condition is transient and the request can be retried.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.6.4", + title = "General.ResourceUnavailable", + status = 503, + detail = "NormalizationUnavailable", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs b/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs index b7889d22..a68ff3cc 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs @@ -1,6 +1,9 @@ #region ========================================================================= USING ===================================================================================== using System; +using System.Collections.Generic; +using System.Globalization; using System.IO; +using System.Linq; using System.Net; using System.Net.Http; using System.Threading; @@ -15,6 +18,21 @@ namespace Lumina.Presentation.Web.Common.Api; /// public sealed class ApiStreamResult : IAsyncDisposable { + /// + /// The response header that carries the number of segments of a normalized audio production. It must match the name the API sends. + /// + public const string SEGMENT_COUNT_HEADER_NAME = "X-Lumina-Segment-Count"; + + /// + /// The response header that carries the exact start of a segment on the track timeline, in seconds. It must match the name the API sends. + /// + public const string SEGMENT_START_SECONDS_HEADER_NAME = "X-Segment-Start-Seconds"; + + /// + /// The response header that carries the produced duration of the normalized track, in seconds. It must match the name the API sends. + /// + public const string TRACK_DURATION_SECONDS_HEADER_NAME = "X-Lumina-Track-Duration-Seconds"; + private readonly HttpResponseMessage _response; /// @@ -62,6 +80,22 @@ public sealed class ApiStreamResult : IAsyncDisposable /// public string? CacheControl { get; } + /// + /// Gets the number of segments the normalized audio production holds, when the response is a segment of one and declares it. + /// + public int? SegmentCount { get; } + + /// + /// Gets the exact start of the segment on the track timeline, in seconds, as declared by the API, or when the response + /// declares none. + /// + public string? SegmentStartSeconds { get; } + + /// + /// Gets the produced duration of the normalized track, in seconds, as declared by the API, or when the response declares none. + /// + public int? TrackDurationSeconds { get; } + /// /// Initializes a new instance of the class. /// @@ -79,6 +113,22 @@ public sealed class ApiStreamResult : IAsyncDisposable ETag = response.Headers.ETag?.ToString(); LastModified = response.Content.Headers.LastModified; CacheControl = response.Headers.CacheControl?.ToString(); + // The count is optional, because the same result also represents a track stream, which has no segments. A malformed or negative + // value is treated as absent instead of being passed to a caller that would use it to decide where the audio ends. + SegmentCount = response.Headers.TryGetValues(SEGMENT_COUNT_HEADER_NAME, out IEnumerable? segmentCountValues) + && int.TryParse(segmentCountValues.FirstOrDefault(), NumberStyles.None, CultureInfo.InvariantCulture, out int parsedSegmentCount) + && parsedSegmentCount >= 0 + ? parsedSegmentCount + : null; + // The start is forwarded as the API wrote it, so the web hop never reinterprets a decimal with the culture of this application. + SegmentStartSeconds = response.Headers.TryGetValues(SEGMENT_START_SECONDS_HEADER_NAME, out IEnumerable? segmentStartValues) + ? segmentStartValues.FirstOrDefault() + : null; + TrackDurationSeconds = response.Headers.TryGetValues(TRACK_DURATION_SECONDS_HEADER_NAME, out IEnumerable? trackDurationValues) + && int.TryParse(trackDurationValues.FirstOrDefault(), NumberStyles.None, CultureInfo.InvariantCulture, out int parsedTrackDuration) + && parsedTrackDuration > 0 + ? parsedTrackDuration + : null; } /// diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs index 0e4b2a53..0fa128aa 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs @@ -9,7 +9,7 @@ namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; /// /// Data transfer object for the playback manifest of a track, describing the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream. /// -[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")] +[DebuggerDisplay("TrackId: {TrackId} IsDirectPlay: {IsDirectPlay}")] public class PlaybackManifestDto { /// @@ -70,7 +70,7 @@ public class PlaybackManifestDto /// /// Gets or sets whether the player can play the stored audio as it is, without the server changing its container or its codec. /// - public bool DirectPlay { get; set; } + public bool IsDirectPlay { get; set; } /// /// Gets or sets the container of the audio the server delivers, when the delivery is not a direct play. @@ -95,11 +95,24 @@ public class PlaybackManifestDto /// /// Gets or sets whether the delivered audio can be seeked by the player. /// - public bool Seekable { get; set; } + public bool IsSeekable { get; set; } /// /// Gets or sets the path of the track stream. The API returns it relative to itself; this web application replaces it with /// the URL of its own streaming proxy, so that the browser never reaches the API server directly. /// public string StreamPath { get; set; } = string.Empty; + + /// + /// Gets or sets the opaque handle of the normalized delivery. The API returns it so the segment route can address exactly the delivery + /// the manifest declared. It is for a direct play. + /// + public string? DeliveryId { get; set; } + + /// + /// Gets or sets the path template of the segment route of the normalized delivery. The API returns it relative to itself with a + /// {deliveryId} and a {segmentIndex} placeholder; this web application replaces it with the URL of its own segment proxy, so + /// that the browser never reaches the API server directly. It is for a direct play. + /// + public string? SegmentStreamPathTemplate { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs b/src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs new file mode 100644 index 00000000..6e6ca03f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Microsoft.AspNetCore.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Http; + +/// +/// Writes a streamed API response to the browser, so the direct track stream and the normalized segment proxy share the same status, header, caching and body forwarding rules and cannot drift apart. +/// +public static class ApiStreamProxy +{ + /// + /// Copies the streamed API response to the response sent to the browser, without buffering its content. + /// + /// The response sent to the browser. + /// The streamed response of the API. + /// Cancellation token that can be used to stop the copy when the client disconnects. + /// A that represents the asynchronous copy operation. + public static async Task WriteAsync(HttpResponse response, ApiStreamResult streamResult, CancellationToken cancellationToken) + { + response.StatusCode = (int)streamResult.StatusCode; + if (!string.IsNullOrEmpty(streamResult.ContentType)) + response.ContentType = streamResult.ContentType; + if (streamResult.ContentLength.HasValue) + response.ContentLength = streamResult.ContentLength.Value; + SetHeader(response, "Content-Range", streamResult.ContentRange); + SetHeader(response, "Accept-Ranges", streamResult.AcceptRanges); + SetHeader(response, "ETag", streamResult.ETag); + SetHeader(response, "Last-Modified", streamResult.LastModified?.ToString("R")); + if (streamResult.SegmentCount.HasValue) + SetHeader(response, ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, streamResult.SegmentCount.Value.ToString()); + SetHeader(response, ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, streamResult.SegmentStartSeconds); + if (streamResult.TrackDurationSeconds.HasValue) + SetHeader(response, ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, streamResult.TrackDurationSeconds.Value.ToString()); + // The response is private to the cookie that authenticates this hop, and it never becomes publicly cacheable, whatever the API declared. + response.Headers["Cache-Control"] = BuildCacheControl(streamResult.CacheControl); + response.Headers["Vary"] = "Cookie"; + await streamResult.Content.CopyToAsync(response.Body, cancellationToken).ConfigureAwait(false); + } + + /// + /// Sets a response header to the given value, unless the value is missing. + /// + /// The response to set the header on. + /// The name of the header. + /// The value of the header, or when the API did not send it. + private static void SetHeader(HttpResponse response, string name, string? value) + { + if (!string.IsNullOrEmpty(value)) + response.Headers[name] = value; + } + + /// + /// Builds the caching instructions of the browser response from the instructions of the API. + /// + /// + /// A streamed media response is specific to the authenticated user, so it must never be stored by a shared cache. Every other instruction of + /// the API, like a maximum age for the private cache of the browser or a no-store, is kept, so the web hop never silently ignores a caching + /// decision the API made for the resource. + /// + /// The caching instructions of the API response, or when it declared none. + /// The caching instructions of the response sent to the browser. + private static string BuildCacheControl(string? apiCacheControl) + { + if (!CacheControlHeaderValue.TryParse(apiCacheControl, out CacheControlHeaderValue? cacheControl)) + cacheControl = new CacheControlHeaderValue(); + cacheControl.Public = false; + cacheControl.Private = true; + return cacheControl.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs b/src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs new file mode 100644 index 00000000..6a897aa6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs @@ -0,0 +1,31 @@ +namespace Lumina.Presentation.Web.Common.Playback; + +/// +/// Defines the format of the opaque delivery handle of a playback manifest. +/// +/// +/// The web application is a separate project that keeps its own contracts, so it repeats the API's rule rather than sharing a type: a handle is +/// exactly 32 lowercase hexadecimal characters, the N format of a GUID. A value that does not match it is rejected, never normalized. +/// +public static class PlaybackDeliveryId +{ + /// + /// The number of characters of a delivery handle. + /// + public const int CHARACTER_COUNT = 32; + + /// + /// Checks whether a value has the format of a delivery handle. + /// + /// The value to check. + /// when the value is exactly 32 lowercase hexadecimal characters, otherwise . + public static bool IsValid(string? value) + { + if (value is null || value.Length != CHARACTER_COUNT) + return false; + foreach (char character in value) + if (!((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'))) + return false; + return true; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs new file mode 100644 index 00000000..b87294e8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to stream one segment of the normalized audio of a track. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. Required. +/// The unique identifier of the album the track belongs to, taken from the route. Required. +/// The unique identifier of the track to stream, taken from the route. Required. +/// The opaque handle of the normalized delivery, taken from the route. Required. +/// The zero based index of the segment of the normalized audio, taken from the route. Required. +/// The Id of the media library the track belongs to. Required. +[DebuggerDisplay("TrackId: {TrackId} DeliveryId: {DeliveryId} SegmentIndex: {SegmentIndex}")] +public record StreamMusicTrackSegmentRequest( + string ArtistId, + string AlbumId, + string TrackId, + string DeliveryId, + int SegmentIndex, + Guid LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs index ad360ddd..01222527 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs @@ -25,6 +25,7 @@ public static partial class ApiRoutes public const string UPDATE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string STREAM_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + public const string STREAM_TRACK_SEGMENT = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}"; public const string GET_PLAYBACK_MANIFEST = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs index 490c65fb..d320d927 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs @@ -29,6 +29,7 @@ public static partial class WebRoutes public const string SAVE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track"; public const string DELETE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-delete-track"; public const string STREAM_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track"; + public const string STREAM_TRACK_SEGMENT = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}"; public const string GET_PLAYBACK_MANIFEST = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest"; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs index 9048d86c..793a1a81 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs @@ -4,10 +4,10 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Playback; using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Net; @@ -72,9 +72,31 @@ public class GetPlaybackManifestEndpoint : BaseEndpoint + /// Builds the browser facing relative path template of the segment streaming proxy of this application for the track identified by the given Ids. + /// + /// + /// The placeholders of the route template are replaced with the Ids the manifest was requested for, and the delivery handle and segment index + /// placeholders are kept for the player to expand. The player substitutes the handle the manifest reported, so the segment request addresses + /// exactly the delivery that manifest declared, and the path is built exactly like the track stream path, so it can only ever point at this origin. + /// + /// The Id of the media library the track belongs to. + /// The normalized Id of the artist the album belongs to. + /// The normalized Id of the album the track belongs to. + /// The normalized Id of the track. + /// The root relative path template the browser fetches a segment from, on its own origin. + private string BuildBrowserSegmentStreamPath(Guid libraryId, string artistId, string albumId, string trackId) + { + string culture = IsSafePathSegment(Culture) ? Culture : "en-US"; + string pathBase = IsSafePathBase(HttpContext.Request.PathBase.ToString()) ? HttpContext.Request.PathBase.ToString().TrimEnd('/') : string.Empty; + string segmentPath = WebRoutes.Music.STREAM_TRACK_SEGMENT + .Replace("{culture}", culture, StringComparison.OrdinalIgnoreCase) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + return $"{pathBase}/{segmentPath}?libraryId={libraryId}"; + } + /// /// Checks whether a value can be used safely as a single segment of a path the browser resolves against its own origin. /// /// The value to check. /// when the value cannot introduce a path separator, a query, a fragment, or a control character, otherwise. - private static bool IsSafePathSegment(string value) + private static bool IsSafePathSegment(string? value) { if (string.IsNullOrEmpty(value)) return false; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs index 8b201df0..7cc4d6bf 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs @@ -18,7 +18,7 @@ public class GetPlaybackManifestEndpointSummary : Summary r.ArtistId, "The unique identifier of the artist the album belongs to. Required."); RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs index eb8b455b..4d2c40ef 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Http; using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; @@ -10,7 +11,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; -using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; #endregion @@ -76,16 +76,8 @@ public class StreamMusicTrackEndpoint : BaseEndpoint 0 && !string.IsNullOrWhiteSpace(value.ToString())) headers[name] = value.ToString(); } - - /// - /// Copies the status and resource headers of the streamed API response to the response sent to the browser. - /// - /// The response sent to the browser. - /// The streamed response of the API. - private static void CopyResponseHeaders(HttpResponse response, ApiStreamResult streamResult) - { - if (!string.IsNullOrEmpty(streamResult.ContentType)) - response.ContentType = streamResult.ContentType; - if (streamResult.ContentLength.HasValue) - response.ContentLength = streamResult.ContentLength.Value; - SetHeader(response, "Content-Range", streamResult.ContentRange); - SetHeader(response, "Accept-Ranges", streamResult.AcceptRanges); - SetHeader(response, "ETag", streamResult.ETag); - SetHeader(response, "Last-Modified", streamResult.LastModified?.ToString("R")); - } - - /// - /// Sets a response header to the given value, unless the value is missing. - /// - /// The response to set the header on. - /// The name of the header. - /// The value of the header, or when the API did not send it. - private static void SetHeader(HttpResponse response, string name, string? value) - { - if (!string.IsNullOrEmpty(value)) - response.Headers[name] = value; - } - - /// - /// Builds the caching instructions of the response sent to the browser from the instructions of the API. - /// - /// - /// A stream is specific to the authenticated user, so it must never be stored by a shared cache. Every other instruction of the API, - /// like a maximum age for the private cache of the browser or a no-store, is kept, so that the web hop never silently ignores a caching - /// decision the API made for the resource. - /// - /// The caching instructions of the API response, or when it declared none. - /// The caching instructions of the response sent to the browser. - private static string BuildCacheControl(string? apiCacheControl) - { - if (!CacheControlHeaderValue.TryParse(apiCacheControl, out CacheControlHeaderValue? cacheControl)) - cacheControl = new CacheControlHeaderValue(); - cacheControl.Public = false; - cacheControl.Private = true; - return cacheControl.ToString(); - } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs new file mode 100644 index 00000000..51b377ab --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Playback; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex} route. +/// +public class StreamMusicTrackSegmentEndpoint : BaseEndpoint +{ + private readonly IStreamingApiHttpClient _streamingApiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for streaming interactions with the API. + public StreamMusicTrackSegmentEndpoint(IStreamingApiHttpClient streamingApiHttpClient) + { + _streamingApiHttpClient = streamingApiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Music.STREAM_TRACK_SEGMENT); + DontAutoTag(); + // The segment stream is bounded per user with the same concurrency limit as the track stream, so a single user can never hold an + // unbounded number of long lived responses open at once and exhaust the connections towards the API. + Options(options => options + .WithTags("Music") + .RequireRateLimiting(PresentationWebLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY)); + } + + /// + /// Streams one segment of the normalized audio of the track identified by through the API, without buffering it. + /// + /// The request containing the Ids of the artist, album, track and media library, the delivery handle, and the segment index. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StreamMusicTrackSegmentRequest request, CancellationToken cancellationToken) + { + // The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted route value can never + // escape its URL segment, and an unparseable id is reported by the API as a missing id. + string normalizedArtistId = Guid.TryParse(request.ArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string normalizedAlbumId = Guid.TryParse(request.AlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString(); + string normalizedTrackId = Guid.TryParse(request.TrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString(); + // The handle has exactly one accepted format, so it is never normalized into another value that would silently address a different delivery. + if (!PlaybackDeliveryId.IsValid(request.DeliveryId)) + { + HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound; + HttpContext.Response.ContentLength = 0; + return Results.Empty; + } + string endpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", normalizedArtistId) + .Replace("{albumId}", normalizedAlbumId) + .Replace("{trackId}", normalizedTrackId) + .Replace("{deliveryId}", request.DeliveryId) + .Replace("{segmentIndex}", request.SegmentIndex.ToString()); + + // The API response is disposed once the copy ends, so that the underlying connection is released as soon as the client stops reading. + ApiStreamResult streamResult; + try + { + streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, new Dictionary(), cancellationToken).ConfigureAwait(false); + } + catch (ApiException apiException) when (apiException.HttpStatusCode is HttpStatusCode.ServiceUnavailable or HttpStatusCode.TooManyRequests) + { + // A busy normalization pipeline or the stream concurrency limit is an expected, transient condition that the player retries. It is + // answered with a bare status instead of being logged as an unexpected API failure with a stack trace. + HttpContext.Response.StatusCode = (int)apiException.HttpStatusCode; + HttpContext.Response.ContentLength = 0; + return Results.Empty; + } + await using (streamResult) // The proxy owns the status, header, caching and body rules shared with the direct track stream proxy. + await ApiStreamProxy.WriteAsync(HttpContext.Response, streamResult, cancellationToken).ConfigureAwait(false); + return Results.Empty; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs new file mode 100644 index 00000000..eb9bc92c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StreamMusicTrackSegmentEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StreamMusicTrackSegmentEndpointSummary() + { + Summary = "Streams one segment of the normalized audio of a music track."; + Description = "Streams one fixed duration segment of the normalized audio of the music track identified by the route, through the API. A track the player cannot play directly is delivered as time addressed segments, so the player seeks by segment index instead of by byte range. The delivery handle is the opaque value the playback manifest reported, and it binds the segment to exactly the delivery that manifest declared."; + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to. Required."); + RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required."); + RequestParam(r => r.TrackId, "The unique identifier of the track to stream. Required."); + RequestParam(r => r.DeliveryId, "The opaque handle of the normalized delivery, reported by the playback manifest. Required."); + RequestParam(r => r.SegmentIndex, "The zero based index of the segment of the normalized audio. Required."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required."); + + Response(200, "The requested segment of the normalized audio of the track is streamed."); + Response(401, "The user is not authenticated."); + Response(403, "The user is not allowed to stream the track of the media library."); + Response(404, "The track, the album, the artist, the media library, the delivery handle, or the requested segment was not found, or is out of the scope of the route."); + Response(409, "The delivery handle no longer describes the delivery, or the source file changed. The player requests the manifest again."); + Response(429, "The user is already holding the maximum number of concurrent track streams."); + Response(502, "The remote API did not return the segment of the normalized audio of the track."); + Response(503, "The normalization pipeline is temporarily busy. The player retries the request."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 5485eb9b..2ff409f0 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -43,6 +43,7 @@ updatePlaybackStateUrl: '@_urlService.GetRelativeUrl(WebRoutes.Settings.UPDATE_PLAYBACK_STATE)', getPlaybackManifestUrl: '@_urlService.GetRelativeUrl(WebRoutes.Music.GET_PLAYBACK_MANIFEST)', streamTrackRouteTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Music.STREAM_TRACK)', + streamTrackSegmentRouteTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Music.STREAM_TRACK_SEGMENT)', strings: { play: '@localizer["AudioPlayerPlay"]', pause: '@localizer["AudioPlayerPause"]', @@ -85,5 +86,6 @@ + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js index 25da12a3..05fc64b7 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js @@ -37,11 +37,13 @@ * The needs normalization event * ----------------------------- * It is published on the player event bus as {@link LuminaAudioPlayer.PlayerEvent.NEEDS_NORMALIZATION}, with the payload - * { container, codec, reason }, plus directPlay when the caller supplied it, where the reason is one of the + * { container, codec, reason }, plus isDirectPlay when the caller supplied it, where the reason is one of the * {@link LuminaAudioPlayer.PlayerErrorReason} values NO_DEMUXER, CODEC_UNSUPPORTED or DEMUXER_FAILED. A consumer that - * asked for a normalized delivery uses it to request one. A normalized manifest, whose directPlay flag is false, is + * asked for a normalized delivery uses it to request one. A normalized manifest, whose isDirectPlay flag is false, is * refused by {@link LuminaAudioPlayer.createDemuxerForManifest} without an event, because the server already normalized - * such a track on purpose and its stream is not in the stored container. + * such a track on purpose and its stream is not in the stored container. The normalized delivery is parsed by + * {@link LuminaAudioPlayer.NormalizedSegmentDemuxer}, which builds one of these same demuxers per segment from the + * delivery container and codec of the manifest. */ (function (LuminaAudioPlayer) { 'use strict'; @@ -82,9 +84,9 @@ * @param {string} container - The canonical container of the track. * @param {string} codec - The canonical codec of the track. * @param {string} reason - One of the {@link LuminaAudioPlayer.PlayerErrorReason} values. - * @param {boolean} [directPlay] - The direct play flag of the manifest, when the caller has one. + * @param {boolean} [isDirectPlay] - The direct play flag of the manifest, when the caller has one. */ - function publishNeedsNormalization(events, container, codec, reason, directPlay) { + function publishNeedsNormalization(events, container, codec, reason, isDirectPlay) { if (!events || !LuminaAudioPlayer.PlayerEvent || typeof events.emit !== 'function') return; const payload = { @@ -96,8 +98,8 @@ // know, which is not the same as a false flag, the documented signal that the server already normalized the // track. Coercing an omitted flag to false would make every caller that has no manifest look like one whose // track the server chose to normalize. - if (directPlay !== undefined) - payload.directPlay = directPlay === true; + if (isDirectPlay !== undefined) + payload.isDirectPlay = isDirectPlay === true; events.emit(LuminaAudioPlayer.PlayerEvent.NEEDS_NORMALIZATION, Object.freeze(payload)); } @@ -176,20 +178,20 @@ * would silently drop the only signal that says which delivery to request. * @param {string} container - The container of the track. * @param {string} codec - The codec of the track. - * @param {boolean} [directPlay] - The direct play flag of the manifest, carried into the event. + * @param {boolean} [isDirectPlay] - The direct play flag of the manifest, carried into the event. * @returns {Promise} True when a demuxer exists and the browser can decode the codec. * @throws {TypeError} When no capability detector or no event bus was injected. It is a composition error, not a * property of the track, so it rejects rather than classifying the track. */ - async canPlayDirectlyAsync(container, codec, directPlay) { + async canPlayDirectlyAsync(container, codec, isDirectPlay) { const events = requireInjected(this.events, 'event bus'); const descriptor = this.match(container, codec); if (!descriptor) { - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, isDirectPlay); return false; } if (!await this.isCodecSupportedAsync(descriptor)) { - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, isDirectPlay); return false; } return true; @@ -204,7 +206,7 @@ async canPlayManifestDirectlyAsync(manifest) { if (!manifest) return false; - return await this.canPlayDirectlyAsync(manifest.sourceContainer, manifest.sourceCodec, manifest.directPlay); + return await this.canPlayDirectlyAsync(manifest.sourceContainer, manifest.sourceCodec, manifest.isDirectPlay); } /** @@ -288,7 +290,7 @@ const events = requireInjected(dependencies.events, 'event bus'); const descriptor = dependencies.registry ? dependencies.registry.find(container, codec) : null; if (!descriptor) { - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, settings.directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, settings.isDirectPlay); return null; } let demuxer = null; @@ -307,7 +309,7 @@ // whose bytes could not be fetched, so the failure is propagated and reported as the download failure it is. if (error instanceof LuminaAudioPlayer.PlayerError && error.code === LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED) throw error; - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.DEMUXER_FAILED, settings.directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.DEMUXER_FAILED, settings.isDirectPlay); return null; } const configuration = demuxer.getConfiguration(); @@ -323,7 +325,7 @@ } if (!isConfigurationSupported) { await demuxer.destroyAsync(); - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, settings.directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, settings.isDirectPlay); return null; } // The demuxer is usable, so the caller's error callback is attached from here on: a failure while reading is a @@ -344,9 +346,9 @@ * @returns {Promise} The ready demuxer, or null for a manifest that is not a direct play, or one that must be normalized. */ LuminaAudioPlayer.createDemuxerForManifest = function (manifest, options) { - if (!manifest || manifest.directPlay !== true) + if (!manifest || manifest.isDirectPlay !== true) return Promise.resolve(null); - return LuminaAudioPlayer.createDemuxerFor(manifest.sourceContainer, manifest.sourceCodec, Object.assign({}, options, { directPlay: true })); + return LuminaAudioPlayer.createDemuxerFor(manifest.sourceContainer, manifest.sourceCodec, Object.assign({}, options, { isDirectPlay: true })); }; /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js index b513f41d..13b03307 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -74,12 +74,25 @@ // which reads it as end of file rather than as a failure, so a rename on either side cannot silently turn a // drained window into a fatal read error. WINDOW_UNAVAILABLE: 'window-unavailable', + // A normalized segment that the production says exists could not be read, because the track, the library or the + // audio file is gone, or the cache entry was evicted. Unlike the end of the audio, which is declared by the + // segment count of the production, this is a playback failure; the player refreshes the manifest once and resumes. + SEGMENT_NOT_FOUND: 'segment-not-found', + // A normalized segment belongs to a delivery the server no longer accepts, because the delivery handle expired or the source changed. + // The player refetches the manifest and resumes at the current position instead of failing the track. + PLAYBACK_DELIVERY_CHANGED: 'playback-delivery-changed', + // Every normalization job slot was in use for the whole retry window, so the segment of a normalized track could + // not be produced in time. The request is transient and a later play can succeed. + NORMALIZATION_UNAVAILABLE: 'normalization-unavailable', + // A segment request failed for an HTTP reason that is neither a transient normalization limit nor a missing segment. + // Unlike WINDOW_UNAVAILABLE, which the demuxer byte source reads as end of file, this is always a playback failure. + HTTP_REQUEST_FAILED: 'http-request-failed', // A range request exceeded its timeout. Unlike an intentional abort, this is a failed request and is not retried // by the seek recovery. REQUEST_TIMEOUT: 'request-timeout', - // The playback manifest says the track is not a direct play, so the server has to normalize its container or its - // codec before the bundled player can play it. Published by the media pipeline engine while the normalized - // delivery pipeline does not exist yet, instead of playing the stored bytes. + // The stored format of a track cannot be demuxed and decoded by the bundled player, so the server has to normalize + // its container or its codec. Published by the media pipeline engine instead of playing bytes whose format the + // bundled demuxers cannot read; a normalized manifest is played through the segment pipeline. NORMALIZED_DELIVERY_REQUIRED: 'normalized-delivery-required', // A load was overtaken by a newer play request before it finished. The player ignores it, because the newer // request owns the player state and the queue. diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js index ac8b61b8..6b887568 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js @@ -42,7 +42,7 @@ // A track cannot be demuxed and decoded directly by the bundled player, so the server has to normalize it (remux or // transcode) before it can play. Payload: { container, codec, reason }, where reason is one of the // {@link LuminaAudioPlayer.PlayerErrorReason} values NO_DEMUXER, CODEC_UNSUPPORTED or DEMUXER_FAILED, and, when the - // caller supplied one, directPlay, the direct play flag of the manifest it asked about, so a consumer can tell a + // caller supplied one, isDirectPlay, the direct play flag of the manifest it asked about, so a consumer can tell a // client-side capability gap from a track the server already decided to normalize. The flag is absent, not false, // when the caller had no manifest. NEEDS_NORMALIZATION: 'needsnormalization', diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js index e3d37771..c676f31b 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js @@ -190,6 +190,119 @@ return resolved.href; } + /** + * Checks that a resolved segment path matches the segment route template this application emitted and belongs to the expected track, library and segment index. + * @param {URL} url - The resolved segment URL. + * @param {Object} descriptor - The play descriptor the manifest belongs to. + * @param {Object} configuration - The endpoints configuration of the player. + * @param {number} segmentIndex - The zero based index of the segment. + * @param {string} deliveryId - The opaque delivery handle the manifest reported. + * @throws {LuminaAudioPlayer.PlayerError} When the route template is missing, is on another origin, or the path does not + * match the route, the expected track and library, the expected segment index, or the expected delivery handle. + */ + function validateSegmentStreamRoute(url, descriptor, configuration, segmentIndex, deliveryId) { + const templateValue = configuration && configuration.streamTrackSegmentRouteTemplate; + if (typeof templateValue !== 'string' || templateValue.length === 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment stream route template is not configured.'); + let template; + try { + template = new URL(templateValue, getBaseOrigin()); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment stream route template is not a valid URL.', { cause: error }); + } + if ((template.protocol !== 'http:' && template.protocol !== 'https:') + || (hasWindowOrigin() && template.origin !== window.location.origin) + || template.origin !== url.origin + || template.username !== '' + || template.password !== '') + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment stream route template is not on this origin.'); + const expectedIds = { + artistId: descriptor && descriptor.artistId, + albumId: descriptor && descriptor.albumId, + trackId: descriptor && descriptor.trackId + }; + const templateSegments = template.pathname.split('/'); + const streamSegments = url.pathname.split('/'); + if (templateSegments.length !== streamSegments.length) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not match the segment route.'); + for (let index = 0; index < templateSegments.length; index++) { + let templateSegment; + try { + templateSegment = decodeURIComponent(templateSegments[index]); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment route template carries an invalid escape.', { cause: error }); + } + const placeholder = /^\{([A-Za-z0-9_]+)\}$/.exec(templateSegment); + let actualSegment; + try { + // Decode the actual segment too, so a path base or a static segment that contains an encoded character still compares equal to the template it came from. + actualSegment = decodeURIComponent(streamSegments[index]); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path carries an invalid escape.', { cause: error }); + } + if (placeholder) { + const name = placeholder[1]; + if (name === 'segmentIndex') { + if (!Number.isInteger(segmentIndex) || segmentIndex < 0 || actualSegment !== String(segmentIndex)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not belong to the expected segment index.'); + continue; + } + if (name === 'deliveryId') { + // The path must name the delivery handle the manifest reported, not another delivery of the same track. + if (typeof deliveryId !== 'string' || actualSegment !== deliveryId) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not belong to the expected delivery.'); + continue; + } + if (!Object.prototype.hasOwnProperty.call(expectedIds, name)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment route template carries an unknown placeholder.'); + const expected = expectedIds[name]; + if (!isGuid(expected)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, `The play descriptor carries no valid ${name}.`, { field: name }); + // The path must describe the track of this descriptor, not merely another track of the same library. + if (!isGuid(actualSegment) || actualSegment.toLowerCase() !== expected.toLowerCase()) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not belong to the expected track.'); + continue; + } + if (templateSegment !== actualSegment) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not match the segment route.'); + } + const libraryId = descriptor && descriptor.libraryId; + if (!isGuid(libraryId)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, 'The play descriptor carries no valid library Id.', { field: 'libraryId' }); + const requestedLibraryIds = url.searchParams.getAll('libraryId'); + if (requestedLibraryIds.length !== 1 || requestedLibraryIds[0].toLowerCase() !== libraryId.toLowerCase()) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not belong to the expected library.'); + } + + /** + * Resolves the segment path template of a normalized playback manifest into the URL of one segment. + * @param {Object} manifest - The playback manifest. + * @param {Object} descriptor - The play descriptor the manifest belongs to. + * @param {Object} configuration - The endpoints configuration of the player. + * @param {number} segmentIndex - The zero based index of the segment to fetch. + * @returns {string} The validated resolved segment URL. + * @throws {LuminaAudioPlayer.PlayerError} When the manifest carries no safe segment path, the index is invalid, or the + * path is not the segment route of the expected track, library and index. + */ + function resolveSegmentStreamUrl(manifest, descriptor, configuration, segmentIndex) { + if (!Number.isInteger(segmentIndex) || segmentIndex < 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment index is not valid.'); + const deliveryId = manifest && manifest.deliveryId; + // The delivery handle is an opaque server issued token, so it is confined to the characters a path segment can carry and never contains a + // separator, a query, a fragment or a control character that could change the route it is substituted into. + if (typeof deliveryId !== 'string' || !/^[0-9a-f]{32}$/.test(deliveryId)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The manifest carries no valid delivery handle.'); + const template = manifest && manifest.segmentStreamPathTemplate; + if (typeof template !== 'string' || !template.includes('{deliveryId}') || !template.includes('{segmentIndex}')) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The manifest carries no segment stream path template.'); + const value = template + .split('{deliveryId}').join(deliveryId) + .split('{segmentIndex}').join(String(segmentIndex)); + const resolved = resolveSameOriginUrl(value); + validateSegmentStreamRoute(resolved.url, descriptor, configuration, segmentIndex, deliveryId); + return resolved.href; + } + /** * Builds the URL of the playback manifest endpoint for a descriptor, including the capability list. * @param {Object} configuration - The endpoints configuration of the player. @@ -317,5 +430,6 @@ } LuminaAudioPlayer.resolveStreamUrl = resolveStreamUrl; + LuminaAudioPlayer.resolveSegmentStreamUrl = resolveSegmentStreamUrl; LuminaAudioPlayer.fetchPlaybackManifestAsync = fetchPlaybackManifestAsync; })(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js index e80cc0b9..04941933 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js @@ -40,13 +40,13 @@ * * Gapless transitions * ------------------- - * When the user enabled gapless playback and the player queue holds another item, the engine prefetches the next item as - * soon as the current one is loaded: it fetches the next manifest, opens its demuxer, and pre-decodes the first seconds of - * its audio into memory. The prefetch does not run an open-ended download next to the current one: it fetches only the - * windows its pre-decode needs, as bounded range requests, and leaves the sequential download of the next track stopped - * until the handoff. Once the current decoder has scheduled its last frame, the pre-decoded audio is appended to the - * renderer schedule, exactly after the audio of the current track, the download of the next track resumes from its first - * missing byte, and the rest of the track is decoded into the same schedule. The engine then switches the current item at the exact media position where the next + * When the user enabled gapless playback and the player queue holds another item, the engine waits until the current track is within a short lead + * of its end, then fetches the next manifest and pre-decodes its first audio. Nothing is requested at load time: a normalized next track would start + * a full server side production that is expensive and bounded in concurrency, and a direct track would hold bytes for a track the user may never + * reach. Normalized gapless therefore only happens when the production is already cached or finishes within the lead; otherwise the next track + * starts normally at the boundary. Once the current decoder has scheduled its last frame, the pre-decoded audio is appended to the renderer + * schedule, exactly after the audio of the current track, the download of the next track resumes from its first missing byte, and the rest of the + * track is decoded into the same schedule. The engine then switches the current item at the exact media position where the next * audio starts, reports the new duration and asks the player to advance its queue, so the bar shows the new track while * the audio never stops. Only the last track of a continuous chain declares the stream complete, which is what keeps the * renderer from reporting an end between two gapless items. @@ -56,10 +56,11 @@ * A download, demux or decode failure that happens mid-stream is reported once, through host.reportError, and stops the * pipeline cleanly; it never escapes as an unhandled rejection and never leaves the renderer or the downloader running. * A failure of a prefetch is dropped instead, because it must not interrupt the track that is playing. A track whose - * manifest is not a direct play needs the normalized delivery pipeline, which this engine does not implement yet, so it - * is reported as an engine load failure with the {@link LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED} - * reason. A play descriptor must name a track, not an album or an artist, because the manifest endpoint is addressed by the - * track and its album and artist; expanding an album or an artist context into its tracks is the queue engine's job. + * manifest is not a direct play is played from the fixed duration segments the server produces, through the normalized + * delivery pipeline (audio-player-pipeline-normalized.js), and it is seeked by segment index exactly like a direct play is + * seeked by byte range. A play descriptor must name a track, not an album or an artist, because the manifest endpoint is + * addressed by the track and its album and artist; expanding an album or an artist context into its tracks is the queue + * engine's job. */ (function (LuminaAudioPlayer) { 'use strict'; @@ -108,6 +109,15 @@ */ const PREFETCH_HANDOFF_MAX_WAIT_SECONDS = 5; + /** + * The playback time, in seconds, before the end of the current track at which the next item is prefetched. A direct play needs a few seconds + * to pre-decode its first audio, and a normalized production is expensive and bounded in concurrency, so starting either at load time would + * hold resources for a track the user may never reach. + * @readonly + * @type {number} + */ + const PREFETCH_LEAD_SECONDS = 15; + /** * Coerces a value to a finite number, or null when it is absent or not finite. * @param {*} value - The value to coerce. @@ -195,10 +205,6 @@ const manifest = await this.fetchManifestAsync(descriptor, signal); if (!this.isLoadCurrent(token)) throw this.createSupersededLoadError(); - if (manifest.directPlay !== true) { - // The normalized delivery pipeline is a later stage; until it exists, the track is reported instead of being played as its stored bytes, which would produce noise or a decoder error. - throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The track needs a normalized delivery the player does not support yet.', { reason: LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED }); - } this.renderer.configure(manifest); const item = await this.buildItemAsync(descriptor, manifest, false); if (!this.isLoadCurrent(token) || this.destroyed) { @@ -705,39 +711,83 @@ disposed: false, failed: false, stopped: false, - hasScheduledAudio: false + hasScheduledAudio: false, + // A delivery refresh is attempted once per item. If the refreshed handle is rejected again, the failure is terminal, so a stale or + // broken delivery cannot make the player refetch the manifest forever. + deliveryRecoveryAttempted: false, + deliveryRecoveryInProgress: false }; - const streamPath = LuminaAudioPlayer.resolveStreamUrl(manifest, descriptor, this.getConfiguration()); - item.downloader = LuminaAudioPlayer.createTrackDownloader({ - url: streamPath, - durationInSeconds: duration, - shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, - events: this.events, - onProgress: (downloadedFraction) => { - if (item === this.current) - this.host.reportProgress(downloadedFraction); - }, - onError: (error) => this.handleDownloadFailure(item, error) - }); - if (typeof onItemCreated === 'function') - onItemCreated(item); - // The demuxer reads through the seek aware source, so a seek can fetch a window below the byte target of the download loop instead of waiting for bytes the loop never fetches. - item.source = new LuminaAudioPlayer.SeekAwareByteSource(item.downloader); - if (isPrefetch) { - // A prefetch fetches only the windows its pre-decode needs, through one-shot range requests, instead of - // running a second open-ended download from the moment the current track starts. Its sequential download is - // started at the handoff, from the first byte that is still missing. - item.source.setSeeking(true); - } else { - item.downloader.startAsync(); - } try { - const demuxer = await LuminaAudioPlayer.createDemuxerForManifest(manifest, { - source: item.source, - capabilities: this.capabilities, - events: this.events, - onError: (error) => this.failItem(item, error) - }); + const isNormalizedDelivery = manifest.isDirectPlay !== true; + let demuxer = null; + if (isNormalizedDelivery) { + const segmentDurationSeconds = Number(manifest.segmentDurationSeconds); + if (!manifest.deliveryContainer || !manifest.deliveryCodec || !Number.isInteger(segmentDurationSeconds) || segmentDurationSeconds <= 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The normalized delivery of the track is incomplete.'); + const configuration = this.getConfiguration(); + item.downloader = LuminaAudioPlayer.createNormalizedSegmentDownloader({ + durationInSeconds: duration, + segmentDurationSeconds: segmentDurationSeconds, + urlBuilder: (segmentIndex) => LuminaAudioPlayer.resolveSegmentStreamUrl(manifest, descriptor, configuration, segmentIndex), + shouldRetryUnavailable: !isPrefetch, + shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, + events: this.events, + onProgress: (downloadedFraction) => { + if (item === this.current) + this.host.reportProgress(downloadedFraction); + }, + onError: (error) => this.handleDownloadFailure(item, error) + }); + if (typeof onItemCreated === 'function') + onItemCreated(item); + // The normalized demuxer fetches complete segments itself, so it needs no byte source. The engine still drives a source on + // seek and teardown, so a no-op source of the same shape keeps that path uniform without a download loop behind it. + item.source = { + setSeeking: () => {}, + destroy: () => {} + }; + if (!isPrefetch) + item.downloader.startAsync(); + demuxer = await LuminaAudioPlayer.createNormalizedSegmentDemuxer(manifest, { + downloader: item.downloader, + capabilities: this.capabilities, + events: this.events, + onError: (error) => this.failItem(item, error) + }); + } else { + const streamPath = LuminaAudioPlayer.resolveStreamUrl(manifest, descriptor, this.getConfiguration()); + item.downloader = LuminaAudioPlayer.createTrackDownloader({ + url: streamPath, + durationInSeconds: duration, + shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, + events: this.events, + onProgress: (downloadedFraction) => { + if (item === this.current) + this.host.reportProgress(downloadedFraction); + }, + onError: (error) => this.handleDownloadFailure(item, error) + }); + if (typeof onItemCreated === 'function') + onItemCreated(item); + // The demuxer reads through the seek aware source, so a seek can fetch a window below the byte target of the download loop instead of waiting for bytes the loop never fetches. + item.source = new LuminaAudioPlayer.SeekAwareByteSource(item.downloader); + if (isPrefetch) { + // A prefetch fetches only the windows its pre-decode needs, through one-shot range requests, instead of + // running a second open-ended download from the moment the current track starts. Its sequential download is + // started at the handoff, from the first byte that is still missing. + item.source.setSeeking(true); + } else { + item.downloader.startAsync(); + } + } + if (!demuxer) { + demuxer = await LuminaAudioPlayer.createDemuxerForManifest(manifest, { + source: item.source, + capabilities: this.capabilities, + events: this.events, + onError: (error) => this.failItem(item, error) + }); + } if (!demuxer) { // A cancelled or aborted header probe and a transport failure are not properties of the track, so // they are reported as themselves. Only a probe that actually concluded the bundled player cannot @@ -1112,9 +1162,14 @@ item.prefetch = token; const phase = (async () => { try { + // The prefetch waits for the monitor to report that the current track is close enough to its end. No manifest is requested and no + // normalized production is started before then, so a skipped or abandoned track never holds a delivery handle or a normalization slot. + const isWindowOpen = await this.waitForPrefetchWindowAsync(item, token); + if (!isWindowOpen) + return null; const signal = token.abortController ? token.abortController.signal : undefined; const manifest = await this.fetchManifestAsync(nextDescriptor, signal); - if (token.cancelled || this.destroyed || item.stopped || manifest.directPlay !== true) + if (token.cancelled || this.destroyed || item.stopped) return null; const prefetched = await this.buildItemAsync(nextDescriptor, manifest, true, (created) => { token.item = created; @@ -1157,6 +1212,70 @@ }); } + /** + * Waits until the current track is close enough to its end for the prefetch to start. The wait is resolved by the playback monitor when it + * crosses the lead, and is rejected as false when the prefetch is cancelled, so no timer polls the whole track and a paused track starts nothing until it resumes near the end. + * @param {Object} item - The current item whose successor is prefetched. + * @param {Object} token - The prefetch token of the current item. + * @returns {Promise} True when the prefetch window opened, false when the prefetch was cancelled or the item stopped. + */ + waitForPrefetchWindowAsync(item, token) { + return new Promise((resolve) => { + token.windowResolve = resolve; + this.tryOpenPrefetchWindow(item, token); + }); + } + + /** + * Opens the prefetch window when the current track is within the lead of its end, or closes it when the prefetch is no longer wanted. + * @param {Object} item - The current item whose successor is prefetched. + * @param {Object} token - The prefetch token of the current item. + */ + tryOpenPrefetchWindow(item, token) { + if (!token || !token.windowResolve) + return; + if (token.cancelled || this.destroyed || !item || item.stopped || item.disposed || this.current !== item) { + this.closePrefetchWindow(token); + return; + } + // A completion that already fell back to a normal next-track start has no use for a prefetch, so it is not started only to be thrown away. + if (item.continueToEntry) { + this.closePrefetchWindow(token); + return; + } + if (this.getRemainingPlaybackSeconds(item) > PREFETCH_LEAD_SECONDS) + return; + const resolve = token.windowResolve; + token.windowResolve = null; + resolve(true); + } + + /** + * Closes a pending prefetch window as false, so the prefetch phase ends instead of waiting for a track that is no longer current. + * @param {Object} token - The prefetch token whose window is closed. + */ + closePrefetchWindow(token) { + if (!token || !token.windowResolve) + return; + const resolve = token.windowResolve; + token.windowResolve = null; + resolve(false); + } + + /** + * Gets how much playback time is left in an item, from the shared renderer playhead. + * @param {Object} item - The item whose remaining time is read. + * @returns {number} The remaining time, in seconds, or zero when the duration is unknown or already reached. + */ + getRemainingPlaybackSeconds(item) { + const duration = Number(item && item.duration); + if (!Number.isFinite(duration) || duration <= 0) + return 0; + const absolute = Number(this.renderer.getCurrentTime()); + const local = Number.isFinite(absolute) ? Math.max(0, absolute - Number(item.base || 0)) : 0; + return Math.max(0, duration - local); + } + /** * Appends the pre-decoded audio of the next item to the renderer schedule, exactly after the audio of the current * track, and lets its decode continue into the same schedule. The current item stays current until the media position of the next item begins. @@ -1180,6 +1299,10 @@ next.downloader.setPlaybackPaused(false); next.downloader.startAsync(); } + // Prefetches are built with retries disabled, because an unavailable production abandons the prefetch instead of holding it open. + // After the handoff this item is the track that owns the playhead, so a temporarily unavailable segment is retried like any current track. + if (typeof next.downloader.setShouldRetryUnavailable === 'function') + next.downloader.setShouldRetryUnavailable(true); // The end of the scheduled audio of the current track is the exact media position the next track starts at. next.base = this.renderer.getScheduledMediaDuration(); this.nextItem = next; @@ -1350,6 +1473,8 @@ return; item.prefetch = null; token.cancelled = true; + // A prefetch that is still waiting for its window is released immediately instead of keeping the teardown open. + this.closePrefetchWindow(token); if (token.abortController) { try { token.abortController.abort(); @@ -1426,6 +1551,7 @@ // the monitor neither pauses the renderer nor advances a boundary of the timeline that is being replaced. if (this.current.isSeeking || this.isLoadingTrack) return; + this.tryOpenPrefetchWindow(this.current, this.current.prefetch); this.isMonitoring = true; try { const absolute = this.renderer.getCurrentTime(); @@ -1603,6 +1729,138 @@ this.failItem(item, error); } + /** + * Checks whether a failure is a delivery that the server no longer accepts, which the player can fix by fetching the manifest again. + * @param {Object} item - The item that failed. + * @param {*} error - The failure. + * @returns {boolean} True when the delivery should be refreshed and playback resumed at the current position. + */ + shouldRecoverDelivery(item, error) { + if (!item || item !== this.current || item.deliveryRecoveryAttempted || item.deliveryRecoveryInProgress || this.destroyed) + return false; + if (!error || error.code !== LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED || !error.details) + return false; + const reason = error.details.reason; + return reason === LuminaAudioPlayer.PlayerErrorReason.SEGMENT_NOT_FOUND + || reason === LuminaAudioPlayer.PlayerErrorReason.PLAYBACK_DELIVERY_CHANGED; + } + + /** + * Refetches the manifest of the current track and rebuilds the normalized pipeline at the current playback position, used when the + * delivery handle expired, the API restarted, or the source file changed since the manifest was read. + * @param {Object} item - The item whose delivery must be refreshed. + * @param {*} originalError - The failure that triggered the refresh. + * @returns {Promise} A promise that completes when playback resumed on the refreshed delivery. + */ + async recoverDeliveryAsync(item, originalError) { + // The attempt is marked before the first await, because the teardown below can raise failures, and a second recovery started + // from one of them would race this one for the same item. + item.deliveryRecoveryInProgress = true; + item.deliveryRecoveryAttempted = true; + // An underrun pause is a temporary buffer stall, not a user pause, so it must be resumed after the refresh just like active playback. + const wasPlaying = !this.isUserPaused && (this.renderer.isPlaying() || this.isUnderrunPaused); + // The renderer time is shared by the whole queue, while the position to resume at is relative to this track. + const position = Math.max(0, Number(this.renderer.getCurrentTime()) - Number(item.base || 0)); + // Stop observing the old pipeline before pausing it, so the monitor does not treat the intentional pause as an underrun and does + // not schedule more work against the delivery that is being replaced. + this.stopMonitor(); + this.isUnderrunPaused = false; + this.host.reportBuffering(true); + try { + await this.renderer.pauseAsync(); + } catch (pauseError) { + // The old item is released below regardless, so a renderer that refuses to pause must not abort the recovery. + console.debug('Audio player: the renderer could not be paused before refreshing the delivery.', pauseError); + } + // A prefetched successor was built from the old manifest, so keeping it would hand off to the expired delivery handle. + this.cancelPrefetchWait(item); + if (item.prefetch) { + try { + await this.cancelPrefetchAsync(item); + } catch (prefetchError) { + console.debug('Audio player: the prefetch of the failed delivery could not be released.', prefetchError); + } + } + // An already attached next track may have audio scheduled from the old delivery, so it is released before the new manifest + // is read instead of letting two deliveries meet at the track boundary. + if (this.nextItem) { + const attachedNextItem = this.nextItem; + this.nextItem = null; + await this.disposeItemAsync(attachedNextItem).catch((disposeError) => { + console.debug('Audio player: the attached next track of the failed delivery could not be released.', disposeError); + }); + } + // The old decode loop and downloads must stop before the replacement is built, because their aborts and failures belong to the + // delivery being replaced and must not be mistaken for failures of the new one. + item.loopToken = null; + if (item.downloader) + item.downloader.abort(); + + let manifest; + try { + manifest = await this.fetchManifestAsync(item.descriptor); + } catch (manifestError) { + // The user needs the failure that interrupted playback, not the recovery attempt that also failed. + console.debug('Audio player: the manifest of the failed delivery could not be refreshed.', manifestError); + throw originalError; + } + // The awaits above can be overtaken by a new load or by teardown, and recovery must never touch a different current item. + if (this.destroyed || this.current !== item) + return; + if (manifest.isDirectPlay === true) { + // The server now considers the track a direct play. Converting the running normalized pipeline to the direct stream is a different + // transition, so the track ends with the original failure instead of playing mixed deliveries. + throw originalError; + } + try { + // ReplayGain and timeline metadata can change with the refreshed manifest, so the renderer is configured before the + // replacement pipeline starts producing audio. + this.renderer.configure(manifest); + } catch (configureError) { + console.debug('Audio player: the renderer could not be configured for the refreshed delivery.', configureError); + throw originalError; + } + + let replacement; + try { + // The replacement owns fresh downloader, demuxer and decoder state bound to the new delivery handle. + replacement = await this.buildItemAsync(item.descriptor, manifest, false); + } catch (buildError) { + console.debug('Audio player: the refreshed delivery could not be prepared.', buildError); + throw originalError; + } + // Building the replacement took another await, so it is discarded if the user left this track in the meantime. + if (this.destroyed || this.current !== item) { + await this.disposeItemAsync(replacement); + return; + } + // The replacement starts at the beginning of this track on the shared timeline. The attempted flag is carried over so a delivery + // that is still rejected after the refresh cannot make the player refetch the manifest forever. + replacement.base = 0; + replacement.deliveryRecoveryAttempted = true; + this.current = replacement; + if (replacement.duration > 0) + this.renderer.setTimelineDuration(replacement.duration); + this.host.reportDuration(replacement.duration); + await this.disposeItemAsync(item); + // A seek rebuilds every stage at the requested position. At zero there is nothing to seek, so the decode loop and its prefetch are started explicitly. + if (position > 0) + await this.seekAsync(position); + else { + this.startDecodeLoop(replacement); + this.startGaplessPrefetch(replacement); + } + // Seeking is asynchronous, so the user may have paused, stopped or replaced the track while it ran. Do not resume a pipeline that no longer owns the playhead. + if (this.current !== replacement || replacement.failed || replacement.stopped || this.destroyed) + return; + // Resume only if audio was actually being heard before the refresh and the user has not paused since. A user pause must stay a pause, while an underrun pause is restored. + if (wasPlaying && !this.isUserPaused) { + await this.renderer.playAsync(); + this.startMonitor(); + } + this.host.reportBuffering(false); + } + /** * Records a failure of an item once and reports it to the player when the item is the current one. * @param {Object} item - The item that failed. @@ -1613,6 +1871,17 @@ return; if (LuminaAudioPlayer.isDownloadAbort(error)) return; + // Errors raised by the old pipeline while it is being replaced by a refreshed delivery belong to that teardown, not to a new failure. + if (item.deliveryRecoveryInProgress) + return; + if (this.shouldRecoverDelivery(item, error)) { + this.recoverDeliveryAsync(item, error).catch((recoveryError) => { + console.debug('Audio player: the refreshed delivery could not be applied.', recoveryError); + item.deliveryRecoveryInProgress = false; + this.failItem(item, error); + }); + return; + } item.failed = true; item.stopped = true; try { @@ -1719,10 +1988,12 @@ async disposeItemAsync(item) { if (!item || item.disposed) return; + // The flags are set before any await, so callbacks raised by the teardown itself see the item as dead instead of failing it again. item.disposed = true; item.stopped = true; item.loopToken = null; this.cancelPrefetchWait(item); + // Stop scheduling before the decoder is torn down, so a frame produced during teardown can never enter the renderer schedule. if (item.scheduler) item.scheduler.stop(); // The item may itself have prefetched the track after it, which must not keep downloading or decoding once the @@ -1751,6 +2022,7 @@ } } await this.waitForDecodeLoopAsync(item); + // The loop has exited, so the scheduler and the demuxer it could still touch are released next. if (item.scheduler) { try { item.scheduler.dispose(); @@ -1767,6 +2039,7 @@ } if (item.source) item.source.destroy(); + // The downloader is destroyed last, because the demuxer and the byte source may hold its reads until they are released. if (item.downloader) { try { await item.downloader.destroyAsync(); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-normalized.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-normalized.js new file mode 100644 index 00000000..b714a167 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-normalized.js @@ -0,0 +1,1204 @@ +/** + * Normalized delivery pipeline of the audio player. + * + * A track the player cannot play as stored is produced by the server as a sequence of fixed duration, time addressed + * segments. A byte range cannot be mapped to a time in such a delivery, so the player addresses it by segment index + * instead: the playback manifest carries a segment path template, the downloader fetches one complete segment at a time, + * and the segment demuxer parses each segment with the demuxer of the delivered container and codec, presenting them to + * the decode pipeline as one continuous timeline. + * + * What it owns + * ------------ + * - NormalizedSegmentDownloader fetches the segments named by the manifest, keeps every fetched segment in memory for + * the lifetime of the track so a seek back into a segment never fetches it again, and reports the downloaded time + * ranges and fraction to the player. A segment is an independent container file, so it is fetched whole; the server + * has already cut it at a fixed duration, which is what makes a segment a seek unit. The end of the audio is declared + * by the segment count header of every response, so a segment that returns not found is a failure (a deleted track, a + * moved file or an evicted cache entry), never a silent end of stream. A response that reports every normalization job + * slot busy is retried with backoff while the track is playing, because the production is bounded and shared. + * A bounded lookahead of one segment keeps the next segment in memory before the decoder needs it. It stops while + * playback is paused unless the keep-downloading-while-paused preference is on, and it never advances past the window, + * so the whole track is not downloaded at once. + * - NormalizedSegmentDemuxer wraps the per segment demuxers behind the same interface the bundled demuxers expose. It + * initializes the demuxer of the delivered container, offsets every packet timestamp by the start of its segment, drops + * the packets that end before a seek target, and moves to the next segment when the current one ends. + * + * Seeking + * ------- + * A seek selects the segment that covers the target time, reloads it from its first byte, seeks inside it when the + * container supports a time seek, and reports a segment covering position so the engine's existing seek trim applies. No + * range request is ever issued for a segment, and no byte range is mapped to a time. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The response header that carries the number of segments a normalized audio production holds. + * @readonly + * @type {string} + */ + const SEGMENT_COUNT_HEADER = 'X-Lumina-Segment-Count'; + + /** + * The response header that carries the exact start of a segment on the track timeline, in seconds. + * @readonly + * @type {string} + */ + const SEGMENT_START_SECONDS_HEADER = 'X-Segment-Start-Seconds'; + + /** + * The response header that carries the produced duration of the normalized track, in seconds. + * @readonly + * @type {string} + */ + const TRACK_DURATION_SECONDS_HEADER = 'X-Lumina-Track-Duration-Seconds'; + + /** + * The delays, in milliseconds, between the attempts of a segment request that the server answered as temporarily unavailable. + * The production that serves a segment is bounded in concurrency and shared by every user, so a request that arrives while every + * job slot is in use is a transient condition, not a failure of the track. + * @readonly + * @type {ReadonlyArray} + */ + const UNAVAILABLE_RETRY_DELAYS_MS = Object.freeze([500, 1000, 2000, 4000, 8000, 16000, 30000]); + + /** + * The longest time, in milliseconds, a playing segment waits for a normalization slot before the request becomes a playback failure. It is + * longer than the default normalization job timeout, so a production that legitimately started before this request is not reported as an error. + * @readonly + * @type {number} + */ + const MAX_UNAVAILABLE_RETRY_MS = 16 * 60 * 1000; + + /** + * The number of segments kept fetched ahead of the segment the demuxer is reading. A segment is about six seconds and the + * decoder schedules about five seconds ahead, so one segment of lookahead is enough to keep the link busy and to have the + * next segment ready before it is needed, while keeping the concurrent stream requests and the memory bounded. + * @readonly + * @type {number} + */ + const LOOKAHEAD_SEGMENTS = 1; + + /** + * Converts a time in seconds to whole microseconds, the unit of every packet timestamp of the player. + * @param {number} seconds - The time in seconds. + * @returns {number} The time in microseconds. + */ + function toMicroseconds(seconds) { + const value = Number(seconds); + return Number.isFinite(value) && value > 0 ? Math.round(value * 1000000) : 0; + } + + /** + * Checks whether a Content-Type is one a segment stream may answer with: an audio type, or the generic binary type + * the API falls back to for a container it cannot name. Any other type, in particular the text/html of a sign in page, is not the segment. + * @param {string|null} value - The Content-Type header value. + * @returns {boolean} True when the value is an audio type or application/octet-stream. + */ + function isStreamContentType(value) { + if (!value) + return false; + const type = value.split(';', 1)[0].trim().toLowerCase(); + return type.startsWith('audio/') || type === 'application/octet-stream'; + } + + /** + * Parses the number of segments a normalized audio production declares. + * @param {string|null} value - The header value. + * @returns {number|null} The segment count, or null when the value is absent or malformed. + */ + function parseSegmentCount(value) { + if (typeof value !== 'string' || value.trim() === '') + return null; + const count = Number(value.trim()); + return Number.isInteger(count) && count >= 0 ? count : null; + } + + /** + * Parses the exact start of a segment on the track timeline. + * @param {string|null} value - The header value. + * @returns {number|null} The start in seconds, or null when the value is absent or malformed. + */ + function parseSegmentStartSeconds(value) { + if (typeof value !== 'string' || value.trim() === '') + return null; + const seconds = Number(value.trim()); + return Number.isFinite(seconds) && seconds >= 0 ? seconds : null; + } + + /** + * A random access byte source over the bytes of one segment, so the bundled demuxer of the delivered container reads the segment exactly as it would read a file. + */ + class SegmentByteSource { + /** + * Creates an instance of SegmentByteSource. + * @param {Uint8Array} bytes - The complete bytes of the segment. + */ + constructor(bytes) { + this.bytes = bytes instanceof Uint8Array ? bytes : new Uint8Array(0); + } + + /** + * Gets the length of the segment. + * @returns {number} The length in bytes. + */ + getLength() { + return this.bytes.length; + } + + /** + * Reads a window of the segment at an absolute offset. + * @param {number} offset - The first byte of the window. + * @param {number} length - The number of bytes of the window. + * @returns {Promise} The bytes, possibly shorter at the end of the segment. + */ + async readAsync(offset, length) { + const start = Math.max(0, Math.floor(Number(offset) || 0)); + const size = Math.max(0, Math.floor(Number(length) || 0)); + if (size === 0 || start >= this.bytes.length) + return new Uint8Array(0); + return this.bytes.subarray(start, Math.min(this.bytes.length, start + size)); + } + } + + /** + * Fetches, keeps and reports the fixed duration segments of a normalized track. + */ + class NormalizedSegmentDownloader { + /** + * Creates an instance of NormalizedSegmentDownloader. + * @param {Object} options - The downloader options. + * @param {Function} options.urlBuilder - Builds the URL of a segment from its zero based index. + * @param {number} options.durationInSeconds - The duration of the track, in seconds. + * @param {number} options.segmentDurationSeconds - The duration of one segment, in seconds. + * @param {Function} [options.onProgress] - Called with the downloaded fraction, between 0 and 1. + * @param {Function} [options.onError] - Called with a typed error when a segment cannot be fetched. + * @param {boolean} [options.shouldRetryUnavailable=true] - Whether a request the server reports as temporarily unavailable is retried with backoff. + * @param {boolean} [options.shouldKeepDownloadingWhilePaused=false] - Whether the lookahead keeps fetching while playback is paused. + * @param {Object} [options.events] - The player event bus, used to follow a change of the keep-downloading-while-paused preference. + */ + constructor(options) { + const settings = options || {}; + this.urlBuilder = settings.urlBuilder; + this.durationInSeconds = Math.max(0, Number(settings.durationInSeconds) || 0); + this.segmentDurationSeconds = Math.max(0, Number(settings.segmentDurationSeconds) || 0); + this.onProgress = typeof settings.onProgress === 'function' ? settings.onProgress : null; + this.onError = typeof settings.onError === 'function' ? settings.onError : null; + this.events = settings.events || null; + this.shouldRetryUnavailable = settings.shouldRetryUnavailable !== false; + this.shouldKeepDownloadingWhilePaused = settings.shouldKeepDownloadingWhilePaused === true; + this.isPlaybackPaused = false; + // The last segment the demuxer actually consumed. The lookahead is measured from it, so background fetches can never + // advance it and turn the bounded read ahead into a full download of the track. + this.lookaheadAnchor = -1; + this.unsubscribePreferences = null; + // The production states how many segments it holds, so the end of the audio is known without a request that returns not found. + // Until the first segment response states it, the count is unknown and a missing segment is a failure, never an end of stream. + this.segmentCount = null; + // The server reports the produced duration, which can differ from the probed duration in the manifest. It is kept separately so the + // progress bar and the seek clamp use what was actually produced once the first segment response arrives. + this.producedDurationSeconds = null; + /** @type {Map} */ + this.segmentStartTimes = new Map(); + /** @type {Map} */ + this.segments = new Map(); + /** @type {Map>} */ + this.pending = new Map(); + // Every request has its own controller and all of them are aborted together, because a seek or a teardown must cancel + // requests whose headers have arrived and whose bodies are still being read, not only the newest one. + this.controllers = new Set(); + this.error = null; + this.isAborted = false; + // A set, not one handle, because a required read and a speculative lookahead can be waiting on a retry at the same time and an abort + // must release both immediately. + this.retryWaitCancels = new Set(); + // Incremented by every abort, so a request that was in flight when the downloader stopped can be told apart from a + // request that was started after it, which must be allowed to proceed. + this.abortGeneration = 0; + this.destroyed = false; + this.subscribeToPreferences(); + } + + /** + * Gets the start of a segment on the timeline of the track. The exact start the server indexed is used when it is known, because ffmpeg + * cuts at the first packet at or after a segment boundary, so a segment does not always start at an exact multiple of the duration. + * @param {number} index - The zero based index of the segment. + * @returns {number} The start, in seconds. + */ + getSegmentStartSeconds(index) { + const declaredStart = this.segmentStartTimes.get(index); + if (declaredStart !== undefined) + return declaredStart; + return Math.max(0, index) * this.segmentDurationSeconds; + } + + /** + * Selects the segment that covers a time from the exact starts the server declared, falling back to the nominal grid only for segments whose start is not known yet. + * @param {number} seconds - The time to locate, in seconds. + * @returns {number} The zero based index of the covering segment. + */ + findSegmentIndexForTime(seconds) { + const value = Number(seconds); + const target = Number.isFinite(value) && value > 0 ? value : 0; + if (this.segmentDurationSeconds <= 0) + return 0; + let index = Math.max(0, Math.floor(target / this.segmentDurationSeconds)); + while (index > 0 && this.segmentStartTimes.has(index) && this.segmentStartTimes.get(index) > target) + index--; + while (this.segmentStartTimes.has(index + 1) && this.segmentStartTimes.get(index + 1) <= target) + index++; + return index; + } + + /** + * Gets the duration of a segment on the timeline of the track, from the start of the next segment when it is known, otherwise from the configured segment duration and the end of the track. + * @param {number} index - The zero based index of the segment. + * @returns {number} The duration, in seconds. + */ + getSegmentDurationSeconds(index) { + const start = this.getSegmentStartSeconds(index); + const nextStart = this.segmentStartTimes.get(index + 1); + if (nextStart !== undefined) + return Math.max(0, nextStart - start); + const totalDuration = this.getTotalDurationSeconds(); + if (totalDuration <= 0) + return this.segmentDurationSeconds; + return Math.max(0, Math.min(this.segmentDurationSeconds, totalDuration - start)); + } + + /** + * Gets the duration of the produced normalized audio, which can differ from the probed duration reported by the manifest. + * @returns {number|null} The produced duration in seconds, or null when no segment response has declared it. + */ + getProducedDurationSeconds() { + return this.producedDurationSeconds; + } + + /** + * Gets the duration used for progress, preferring the produced duration over the probed one. + * @returns {number} The duration in seconds, or zero when it is not known. + */ + getTotalDurationSeconds() { + const producedDuration = Number(this.producedDurationSeconds); + if (Number.isFinite(producedDuration) && producedDuration > 0) + return producedDuration; + return this.durationInSeconds; + } + + /** + * Gets one segment, from memory when it was already fetched, otherwise from the segment route. + * @param {number} index - The zero based index of the segment. + * @returns {Promise} The bytes of the segment, or null when the index is past the produced audio. + * @throws {LuminaAudioPlayer.PlayerError} When the segment cannot be fetched, or the download was aborted. + */ + async getSegmentAsync(index) { + if (this.destroyed) + throw this.createAbortError(); + if (!Number.isInteger(index) || index < 0) + throw this.recordError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The segment index is not valid.')); + // The production stated how many segments it holds, so an index at or past that count is the end of the audio and needs no request. + if (this.segmentCount !== null && index >= this.segmentCount) + return null; + let bytes; + if (this.segments.has(index)) + bytes = this.segments.get(index); + else if (this.pending.has(index)) // The segment may already be in flight as lookahead, so the read waits for that request instead of starting a second one. + bytes = await this.pending.get(index); + else + bytes = await this.createSegmentRequest(index, false); + if (bytes) // Only a segment the demuxer actually consumed moves the anchor, so the read ahead stays bounded to the lookahead window. + this.advanceLookaheadAnchor(index); + return bytes; + } + + /** + * Starts a segment request and records it as pending, so a concurrent read or a lookahead never asks for the same segment twice. + * @param {number} index - The zero based index of the segment. + * @param {boolean} isSpeculative - True for a background lookahead, whose failure must not become the failure of the track. + * @returns {Promise} The bytes of the segment, or null when it does not exist. + */ + createSegmentRequest(index, isSpeculative) { + const request = this.fetchSegmentAsync(index, isSpeculative); + this.pending.set(index, request); + request.then( + () => { + if (this.pending.get(index) === request) + this.pending.delete(index); + }, + () => { + // A failed request is forgotten, so a later read of the same segment can try again. The failure itself reaches the + // caller that awaited it, and is only reported through onError when it belongs to the track that is playing. + if (this.pending.get(index) === request) + this.pending.delete(index); + } + ); + return request; + } + + /** + * Moves the read ahead anchor to a consumed segment and starts the lookahead that follows it. + * @param {number} index - The zero based index of the segment the demuxer consumed. + */ + advanceLookaheadAnchor(index) { + if (index <= this.lookaheadAnchor) + return; + this.lookaheadAnchor = index; + this.scheduleLookahead(); + } + + /** + * Fetches up to the configured number of segments after the consumed one, so the next segment is already in memory when the + * decoder needs it. The lookahead is bounded, and it stops while playback is paused unless the user kept downloading enabled. + */ + scheduleLookahead() { + if (this.destroyed || this.isAborted || this.segmentCount === null || this.lookaheadAnchor < 0) + return; + if (this.isPlaybackPaused && !this.shouldKeepDownloadingWhilePaused) + return; + for (let offset = 1; offset <= LOOKAHEAD_SEGMENTS; offset++) { + const index = this.lookaheadAnchor + offset; + if (index >= this.segmentCount) + return; + if (this.segments.has(index) || this.pending.has(index)) + continue; + this.createSegmentRequest(index, true); + } + } + + /** + * Subscribes to the preference changes of the player, so a change of the keep-downloading-while-paused setting is applied to + * the lookahead of a track that is already loaded. + */ + subscribeToPreferences() { + if (!this.events || !LuminaAudioPlayer.PlayerEvent || typeof this.events.on !== 'function') + return; + this.unsubscribePreferences = this.events.on(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, (preferences) => { + if (preferences && typeof preferences.shouldKeepDownloadingWhilePaused === 'boolean') + this.setKeepDownloadingWhilePaused(preferences.shouldKeepDownloadingWhilePaused); + }); + } + + /** + * Fetches one complete segment and stores it, so it is never fetched again for this track. + * @param {number} index - The zero based index of the segment. + * @param {boolean} [isSpeculative=false] - True for a background lookahead, whose failure must not be recorded as the failure of the track. + * @returns {Promise} The bytes of the segment, or null when the server reports no such segment. + * @throws {LuminaAudioPlayer.PlayerError} When the request fails or is aborted. + */ + async fetchSegmentAsync(index, isSpeculative = false) { + if (this.destroyed) + throw this.createAbortError(); + // The generation is captured for the whole call, so an abort or restart invalidates every retry and the body read, even when a later attempt uses a new controller. + const abortGeneration = this.abortGeneration; + // The retry window starts at the first attempt, not at each retry, so a production that stays unavailable cannot keep this request alive indefinitely. + const retryStartedAt = Date.now(); + let attempt = 0; + // Only a transient unavailable status loops back here; every other result leaves through a return or a throw below. + while (true) { + if (this.destroyed || this.abortGeneration !== abortGeneration) + throw this.createAbortError(); + const controller = typeof AbortController === 'function' ? new AbortController() : null; + // The controller stays registered until the body has been read, so an abort during arrayBuffer cancels the transfer instead + // of leaving it to download the discarded segment in full while holding a stream slot on both hops. + if (controller) + this.controllers.add(controller); + try { + let response; + try { + const url = typeof this.urlBuilder === 'function' ? this.urlBuilder(index) : null; + if (typeof url !== 'string' || url.length === 0) + throw this.createRequestFailure('The segment URL is not configured.', null, isSpeculative, LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED); + response = await fetch(url, { + method: 'GET', + credentials: 'same-origin', + redirect: 'manual', + headers: { 'Accept': 'audio/*, application/octet-stream' }, + signal: controller ? controller.signal : undefined + }); + } catch (error) { + if (LuminaAudioPlayer.isAbortError(error) || this.destroyed || this.abortGeneration !== abortGeneration) + throw this.createAbortError(); + // A speculative read must not record the first failure, because the required read that follows owns the + // track's error state; the recorded failure is the one the user should see. + if (error instanceof LuminaAudioPlayer.PlayerError) + throw isSpeculative ? error : this.recordError(error); + throw this.createRequestFailure('The segment could not be requested.', { cause: error }, isSpeculative); + } + if (!response) + throw this.createRequestFailure('The segment request returned no response.', null, isSpeculative); + // Redirects are not followed: an expired session answers with a redirect to the login page, whose HTML must never be parsed as audio. + if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) + throw this.createRequestFailure('The session expired while a segment was requested.', { reason: LuminaAudioPlayer.PlayerErrorReason.SESSION_EXPIRED }, isSpeculative); + if (!response.ok) { + const status = response.status; + // Every non-success path discards the body first, so the connection is released instead of being held by a response nobody reads. + await this.discardResponseAsync(response); + // Every job slot can be in use because productions are shared and bounded, so a temporarily unavailable segment is + // retried for the track that is playing. A prefetch does not retry: it is abandoned and the track starts normally. + if (this.shouldRetryUnavailable && (status === 503 || status === 429) + && Date.now() - retryStartedAt < MAX_UNAVAILABLE_RETRY_MS) { + // The last delay is reused after the array ends, so the backoff stays bounded while the retry window runs. + const delay = UNAVAILABLE_RETRY_DELAYS_MS[Math.min(attempt, UNAVAILABLE_RETRY_DELAYS_MS.length - 1)]; + attempt++; + await this.waitBeforeRetryAsync(delay, abortGeneration); + continue; + } + // The reason is part of the error contract: the engine uses SEGMENT_NOT_FOUND and PLAYBACK_DELIVERY_CHANGED + // to refresh the manifest, and reports the other reasons as ordinary playback failures. + const reason = status === 503 + ? LuminaAudioPlayer.PlayerErrorReason.NORMALIZATION_UNAVAILABLE + : (status === 409 + ? LuminaAudioPlayer.PlayerErrorReason.PLAYBACK_DELIVERY_CHANGED + : (status === 404 ? LuminaAudioPlayer.PlayerErrorReason.SEGMENT_NOT_FOUND : LuminaAudioPlayer.PlayerErrorReason.HTTP_REQUEST_FAILED)); + throw this.createRequestFailure('The segment request failed.', { reason, status }, isSpeculative); + } + // A proxy or an error page can answer 200 with a non-audio body, so the media type is checked before the bytes ever reach a demuxer. + if (!isStreamContentType(response.headers.get('Content-Type'))) { + await this.discardResponseAsync(response); + throw this.createRequestFailure('The segment response is not audio.', null, isSpeculative); + } + // The production declares how many segments exist. It is required, because a player cannot tell a missing + // final segment from the end of the track without it. + const declaredSegmentCount = parseSegmentCount(response.headers.get(SEGMENT_COUNT_HEADER)); + if (declaredSegmentCount === null) { + await this.discardResponseAsync(response); + throw this.createRequestFailure('The segment response carried no segment count.', null, isSpeculative); + } + // A response beyond the declared count means the handle and the production disagree, not that the track ended. + if (index >= declaredSegmentCount) { + await this.discardResponseAsync(response); + throw this.createRequestFailure('The segment response is outside the declared production.', null, isSpeculative); + } + if (this.segmentCount !== null && this.segmentCount !== declaredSegmentCount) { + // A production is immutable, so a different count means the audio was replaced under the track. Mixing the two + // productions would corrupt the timeline, so the track fails instead of playing a splice of both. + await this.discardResponseAsync(response); + throw this.createRequestFailure('The normalized production changed during playback.', null, isSpeculative); + } + this.segmentCount = declaredSegmentCount; + // The produced duration and the exact start of this segment come from the server, because the probe duration and + // the nominal index times can differ slightly after transcoding. + const declaredDuration = parseSegmentStartSeconds(response.headers.get(TRACK_DURATION_SECONDS_HEADER)); + if (declaredDuration !== null) + this.producedDurationSeconds = declaredDuration; + const declaredStart = parseSegmentStartSeconds(response.headers.get(SEGMENT_START_SECONDS_HEADER)); + if (declaredStart !== null) + this.segmentStartTimes.set(index, declaredStart); + let bytes; + try { + // The controller is still registered here, so an abort now cancels this body read instead of after it completed. + bytes = new Uint8Array(await response.arrayBuffer()); + } catch (error) { + if (LuminaAudioPlayer.isAbortError(error) || this.destroyed || this.abortGeneration !== abortGeneration) + throw this.createAbortError(); + throw this.createRequestFailure('The segment body could not be read.', { cause: error }, isSpeculative); + } + if (this.destroyed || this.abortGeneration !== abortGeneration) + throw this.createAbortError(); + // The bytes are cached only after the whole body was read, so a transfer that failed halfway can never be mistaken for a complete segment. + this.segments.set(index, bytes); + this.reportProgress(); + return bytes; + } finally { + if (controller) + this.controllers.delete(controller); + } + } + } + + /** + * Discards the body of a response that is not used, so a connection that will not be read is released. + * @param {Response} response - The response whose body is discarded. + * @returns {Promise} A promise that completes when the body was discarded. + */ + async discardResponseAsync(response) { + try { + if (response && response.body && typeof response.body.cancel === 'function') + await response.body.cancel(); + } catch (error) { + console.debug('Audio player: the unused segment response could not be discarded.', error); + } + } + + /** + * Waits before the next attempt of a temporarily unavailable segment request, unless the downloader is aborted first. + * @param {number} delay - The delay, in milliseconds. + * @param {number} abortGeneration - The abort generation the attempt belongs to. + * @returns {Promise} A promise that completes when the delay elapsed. + * @throws {LuminaAudioPlayer.PlayerError} When the downloader was aborted or released during the delay. + */ + waitBeforeRetryAsync(delay, abortGeneration) { + return new Promise((resolve, reject) => { + let isSettled = false; + let timer = null; + const finish = (isAborted) => { + if (isSettled) + return; + isSettled = true; + if (timer !== null) + clearTimeout(timer); + this.retryWaitCancels.delete(cancel); + if (isAborted) + reject(this.createAbortError()); + else + resolve(); + }; + const cancel = () => finish(true); + timer = setTimeout(() => finish(false), delay); + this.retryWaitCancels.add(cancel); + if (this.destroyed || this.abortGeneration !== abortGeneration) + cancel(); + }); + } + + /** + * Reports the downloaded fraction of the track, mapped through the manifest duration so the streamed indicator is + * time accurate. + */ + reportProgress() { + if (!this.onProgress) + return; + try { + this.onProgress(this.getDownloadedFraction()); + } catch (error) { + console.debug('Audio player: the downloaded fraction of a normalized track could not be reported.', error); + } + } + + /** + * Gets the fraction of the track that was fetched, by the duration of the fetched segments. + * @returns {number} The fraction, between 0 and 1. + */ + getDownloadedFraction() { + const totalDuration = this.getTotalDurationSeconds(); + if (totalDuration <= 0 || this.segmentDurationSeconds <= 0) + return 0; + let downloadedSeconds = 0; + for (const index of this.segments.keys()) + downloadedSeconds += this.getSegmentDurationSeconds(index); + return Math.min(1, Math.max(0, downloadedSeconds / totalDuration)); + } + + /** + * Gets the time ranges of the track that were already fetched, so the three state progress bar can show the + * streamed part and a seek into it needs no loading state. + * @returns {Array<{ start: number, end: number }>} The downloaded time ranges, in seconds. + */ + getTimeRanges() { + const indexes = Array.from(this.segments.keys()).sort((first, second) => first - second); + const ranges = []; + for (const index of indexes) { + const start = this.getSegmentStartSeconds(index); + const end = start + this.getSegmentDurationSeconds(index); + const last = ranges[ranges.length - 1]; + if (last && Math.abs(last.end - start) < 0.000001) + last.end = end; + else + ranges.push({ start, end }); + } + return ranges; + } + + /** + * Checks whether a time is covered by a fetched segment, so the player knows a seek into it needs no loading state. + * @param {number} seconds - The time to check, in seconds. + * @returns {boolean} True when the segment that covers the time was fetched. + */ + coversTime(seconds) { + if (this.segmentDurationSeconds <= 0) + return false; + const value = Number(seconds); + if (!Number.isFinite(value) || value < 0) + return false; + // When the exact starts are known, the segment that covers the time is the one with the greatest declared start at or before it, + // not necessarily the one the assumed grid would pick. + let candidateIndex = null; + let candidateStart = -1; + for (const [index, start] of this.segmentStartTimes) { + if (start <= value && start > candidateStart) { + candidateIndex = index; + candidateStart = start; + } + } + if (candidateIndex !== null && value <= candidateStart + this.getSegmentDurationSeconds(candidateIndex)) + return this.segments.has(candidateIndex); + return this.segments.has(Math.floor(value / this.segmentDurationSeconds)); + } + + /** + * Sets whether playback is paused. The lookahead keeps fetching while paused only when the user enabled the + * keep-downloading-while-paused preference; a request that is already in flight is left to finish, so pausing never + * turns a segment the decoder is waiting for into a failure. + * @param {boolean} isPaused - Whether playback is paused. + */ + setPlaybackPaused(isPaused) { + const next = isPaused === true; + if (next === this.isPlaybackPaused) + return; + this.isPlaybackPaused = next; + if (!next || this.shouldKeepDownloadingWhilePaused) + this.scheduleLookahead(); + } + + /** + * Sets the keep-downloading-while-paused preference. When it is enabled while playback is paused, the lookahead resumes; + * when it is disabled, no new lookahead is started, while a request that is already in flight is left to finish. + * @param {boolean} shouldKeepDownloading - Whether downloading should continue while paused. + */ + setKeepDownloadingWhilePaused(shouldKeepDownloading) { + const next = shouldKeepDownloading === true; + if (next === this.shouldKeepDownloadingWhilePaused) + return; + this.shouldKeepDownloadingWhilePaused = next; + if (next) + this.scheduleLookahead(); + } + + /** + * Enables or disables the retry of a temporarily unavailable segment request. A prefetch starts with it disabled, so an + * unavailable production is abandoned instead of held; the item enables it when it becomes the track that is playing. + * @param {boolean} shouldRetry - Whether a temporarily unavailable request is retried with backoff. + */ + setShouldRetryUnavailable(shouldRetry) { + this.shouldRetryUnavailable = shouldRetry === true; + } + + /** + * Starts, or resumes, the downloader after an abort. It clears the abort flag and resumes the lookahead, because a seek and a resume both call it. + * @returns {Promise} A promise that completes when the downloader is usable again. + */ + async startAsync() { + this.isAborted = false; + this.scheduleLookahead(); + } + + /** + * Moves the read ahead anchor to the segment that covers a seek target, so the lookahead around the new position is fetched + * before the decoder reaches it. The segment of the target itself is fetched by the demuxer. + * @param {number} seconds - The target position, in seconds. + */ + seek(seconds) { + if (this.segmentDurationSeconds <= 0) + return; + const value = Number(seconds); + const target = Number.isFinite(value) && value > 0 ? value : 0; + this.lookaheadAnchor = this.findSegmentIndexForTime(target); + this.scheduleLookahead(); + } + + /** + * Aborts the segment request that is in flight, if any, and rejects the reads that are waiting for it. + */ + abort() { + this.isAborted = true; + // Every pending read belongs to the request that is being stopped, so the entries are dropped here; a read that starts after + // this abort is a new request and is not rejected by the abort that precedes it. + this.abortGeneration += 1; + this.pending.clear(); + for (const cancelRetryWait of this.retryWaitCancels) { + try { + cancelRetryWait(); + } catch (error) { + console.debug('Audio player: a segment retry wait could not be cancelled.', error); + } + } + this.retryWaitCancels.clear(); + // Every request is aborted, including one whose headers arrived and whose body is still being read. The controllers stay + // registered until each body read finishes, which is what makes this cancellation effective on a slow link. + for (const controller of this.controllers) { + try { + controller.abort(); + } catch (error) { + console.debug('Audio player: a segment request could not be aborted.', error); + } + } + this.controllers.clear(); + } + + /** + * Gets the last failure the downloader recorded, or null. + * @returns {LuminaAudioPlayer.PlayerError|null} The recorded failure. + */ + getError() { + return this.error; + } + + /** + * Gets the total size of the track in bytes, which the segment delivery does not expose as a stream length. + * @returns {null} Always null. + */ + getTotalBytes() { + return null; + } + + /** + * Builds the typed failure of a segment request. A failure of a background lookahead is returned without being recorded, so a + * speculative request that is not needed yet can never make the track that is playing fail. + * @param {string} message - The developer facing description of the failure. + * @param {Object|null} details - Optional structured details. + * @param {boolean} isSpeculative - True when the failure belongs to a background lookahead. + * @param {string} [code] - The player error code. Defaults to DOWNLOAD_FAILED. + * @returns {LuminaAudioPlayer.PlayerError} The typed failure, recorded when it is not speculative. + */ + createRequestFailure(message, details, isSpeculative, code = LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED) { + const error = new LuminaAudioPlayer.PlayerError(code, message, details); + return isSpeculative ? error : this.recordError(error); + } + + /** + * Records a failure once and reports it to the caller, so a failed segment is never retried silently and never overwrites the cause of the first failure. + * @param {LuminaAudioPlayer.PlayerError} error - The failure to record. + * @returns {LuminaAudioPlayer.PlayerError} The recorded failure. + */ + recordError(error) { + if (this.error) + return this.error; + this.error = error; + if (this.onError) { + try { + this.onError(error); + } catch (callbackError) { + console.error('Audio player: the normalized download error callback threw.', callbackError); + } + } + return error; + } + + /** + * Creates the typed abort of an intentionally stopped segment request. + * @returns {LuminaAudioPlayer.PlayerError} The abort. + */ + createAbortError() { + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The segment request was aborted.'); + } + + /** + * Releases every fetched segment and aborts the request that is in flight. + * @returns {Promise} A promise that completes when the downloader was released. + */ + async destroyAsync() { + if (this.destroyed) + return; + this.destroyed = true; + if (this.unsubscribePreferences) { + try { + this.unsubscribePreferences(); + } catch (error) { + console.debug('Audio player: the normalized download preference subscription could not be removed.', error); + } + this.unsubscribePreferences = null; + } + this.abort(); + this.segments.clear(); + this.pending.clear(); + } + } + + /** + * Presents the segments of a normalized track to the decode pipeline as one continuous stream. + */ + class NormalizedSegmentDemuxer { + /** + * Creates an instance of NormalizedSegmentDemuxer. + * @param {Object} options - The demuxer options. + * @param {Object} options.manifest - The playback manifest of the normalized track. + * @param {LuminaAudioPlayer.NormalizedSegmentDownloader} options.downloader - The downloader of the segments. + * @param {Object} [options.registry] - The demuxer registry. Defaults to the process wide registry. + * @param {Object} [options.capabilities] - The browser capability detector. + * @param {Object} [options.events] - The player event bus. + * @param {Function} [options.onError] - Called with a typed error when the normalized stream cannot be read. + */ + constructor(options) { + const settings = options || {}; + const manifest = settings.manifest || {}; + this.manifest = manifest; + this.downloader = settings.downloader; + this.registry = settings.registry || LuminaAudioPlayer.demuxerRegistry; + this.capabilities = settings.capabilities || null; + this.events = settings.events || null; + this.onError = typeof settings.onError === 'function' ? settings.onError : null; + this.container = LuminaAudioPlayer.canonicalizeDemuxerContainer(manifest.deliveryContainer); + this.codec = LuminaAudioPlayer.canonicalizeDemuxerCodec(manifest.deliveryCodec); + this.segmentDurationSeconds = Math.max(0, Number(manifest.segmentDurationSeconds) || 0); + this.durationInSeconds = Math.max(0, Number(manifest.durationInSeconds) || 0); + this.inner = null; + this.innerIndex = -1; + this.initialized = false; + this.destroyed = false; + this.error = null; + // Set only when the produced segment count is exhausted, so an ordinary read failure is never treated as the end of the track. + this.hasReachedEnd = false; + this.seekTargetMicros = null; + } + + /** + * Gets the start of a segment on the timeline of the track, from the exact value the server indexed when it is known. + * @param {number} index - The zero based index of the segment. + * @returns {number} The start, in seconds. + */ + getSegmentStartSeconds(index) { + if (this.downloader && typeof this.downloader.getSegmentStartSeconds === 'function') + return this.downloader.getSegmentStartSeconds(index); + return Math.max(0, index) * this.segmentDurationSeconds; + } + + /** + * Loads the demuxer of one segment, replacing the previous one. + * @param {number} index - The zero based index of the segment. + * @param {boolean} [forceReload=false] - True to reload a segment that is already open, used by a seek. + * @returns {Promise} True when the segment was loaded, false when it does not exist. + * @throws {LuminaAudioPlayer.PlayerError} When the segment or its format cannot be read. + */ + async loadSegmentAsync(index, forceReload = false) { + if (this.destroyed) + throw this.createAbortError(); + // A normal sequential read reuses the open segment. A seek forces a reload even for the same index, because its demuxer must + // restart at the first packet so readPacketAsync can drop the frames before the new target. + if (!forceReload && this.inner && this.innerIndex === index) + return true; + // The old segment is detached before it is awaited, so a failure while releasing it can never leave the wrapper pointing at a demuxer that is being destroyed. + const previous = this.inner; + this.inner = null; + this.innerIndex = -1; + if (previous) { + try { + await previous.destroyAsync(); + } catch (error) { + console.debug('Audio player: the previous normalized segment could not be released.', error); + } + } + // A seek can move back before the produced end, so the end marker is only valid until the next forced load. + if (forceReload) + this.hasReachedEnd = false; + if (this.hasReachedEnd) + return false; + let bytes; + try { + bytes = await this.downloader.getSegmentAsync(index); + } catch (error) { + if (LuminaAudioPlayer.isDownloadAbort(error)) + throw this.createAbortError(); + // The downloader has already classified the failure, but this wrapper owns the stream error that the decode pipeline + // reads, so the failure is recorded with the download code before it is thrown. + this.recordFailure(LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED)); + throw this.error; + } + if (bytes === null) { + // No bytes for this index is the declared end of the production, not a corrupt segment. + this.hasReachedEnd = true; + return false; + } + const descriptor = this.registry ? this.registry.find(this.container, this.codec) : null; + if (!descriptor) { + this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The bundled player has no demuxer for the normalized delivery.', { reason: LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER })); + throw this.error; + } + // The inner demuxer reads only from this segment's bytes. Its error callback is left null because this wrapper records and classifies every failure itself. + const inner = descriptor.create({ + source: new SegmentByteSource(bytes), + capabilities: this.capabilities, + events: this.events, + onError: null + }); + try { + await inner.initializeAsync(); + } catch (error) { + // A demuxer that failed to initialize may still hold its byte source or parser state, so it is released before the wrapper records the failure. + try { + await inner.destroyAsync(); + } catch (destroyError) { + console.debug('Audio player: the failed normalized segment could not be released.', destroyError); + } + if (LuminaAudioPlayer.isDownloadAbort(error)) + throw this.createAbortError(); + this.recordFailure(LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED)); + throw this.error; + } + // Initialization is asynchronous, so the stream may have been released while it ran. The new demuxer must be released too, + // and the caller must see an abort rather than a segment that belongs to a track nobody is playing anymore. + if (this.destroyed) { + try { + await inner.destroyAsync(); + } catch (destroyError) { + console.debug('Audio player: the normalized segment of a released stream could not be released.', destroyError); + } + throw this.createAbortError(); + } + // The segment becomes current only after every check and await succeeded, so a failed load never leaves a half usable inner demuxer in place. + this.inner = inner; + this.innerIndex = index; + return true; + } + + /** + * Loads the first segment and prepares the decoder configuration of the normalized stream. + * @returns {Promise} A promise that completes when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the first segment does not exist or is not in the delivered format. + */ + async initializeAsync() { + if (this.destroyed) + throw this.createAbortError(); + if (this.segmentDurationSeconds <= 0) + throw this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The normalized delivery has no segment duration.')); + const loaded = await this.loadSegmentAsync(0); + if (!loaded || !this.inner) + throw this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The normalized delivery has no segments.')); + const configuration = this.inner.getConfiguration(); + if (!configuration) { + const failure = this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The normalized delivery reported no decoder configuration.')); + // The wrapper is not returned to the engine after a failed initialization, so the already opened segment and its demuxer are + // released here instead of waiting for garbage collection. + await this.destroyAsync(); + throw failure; + } + if (this.capabilities && typeof this.capabilities.supportsAudioConfigAsync === 'function') { + const isSupported = await this.capabilities.supportsAudioConfigAsync(configuration); + if (!isSupported) { + const failure = this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The browser cannot decode the normalized delivery.', { reason: LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED })); + await this.destroyAsync(); + throw failure; + } + } + this.initialized = true; + } + + /** + * Gets the decoder configuration of the normalized stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + return this.inner ? this.inner.getConfiguration() : null; + } + + /** + * Gets the duration of the whole normalized stream. The produced duration reported by the server takes precedence over the probed duration + * of the manifest, because a production can run past the probe. + * @returns {number|null} The duration in seconds, or null when it is not known. + */ + getDuration() { + if (this.downloader && typeof this.downloader.getProducedDurationSeconds === 'function') { + const producedDuration = Number(this.downloader.getProducedDurationSeconds()); + if (Number.isFinite(producedDuration) && producedDuration > 0) + return producedDuration; + } + return this.durationInSeconds > 0 ? this.durationInSeconds : null; + } + + /** + * Reads the next encoded packet of the normalized stream, moving to the next segment when the current one ends. + * @returns {Promise} The packet with an absolute timestamp, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When a segment cannot be read. + */ + async readPacketAsync() { + this.ensureInitialized(); + // The loop only continues when a segment boundary is crossed; every packet returned to the decoder leaves through the return at the bottom. + while (!this.destroyed) { + if (!this.inner) { + // This happens after a forced seek load failed or before the first packet. A missing next segment is the end of the production, not an error. + const loaded = await this.loadSegmentAsync(this.innerIndex + 1); + if (!loaded) + return null; + } + const packet = await this.inner.readPacketAsync(); + // The index is captured before moving on, because the packet timestamp is relative to the segment that produced it, even after the next segment was loaded. + const currentIndex = this.innerIndex; + if (packet === null) { + // The current segment is fully drained. Load the following one and continue reading without exposing a null packet + // to the decoder, because null means the whole track ended. + const loaded = await this.loadSegmentAsync(currentIndex + 1); + if (!loaded) + return null; + continue; + } + // Demuxers report timestamps relative to their own segment. Adding the exact start the server indexed places the packet + // on the shared track timeline, so a boundary does not jump or overlap after transcoding. + const startMicros = toMicroseconds(this.getSegmentStartSeconds(currentIndex)); + const timestamp = packet.timestamp + startMicros; + if (this.seekTargetMicros !== null) { + // A demuxer that could not reposition by time starts the segment at its first frame. The frames that end + // before the target belong to audio the user already skipped, so they are dropped before the decoder sees them. + if (timestamp + packet.duration <= this.seekTargetMicros) + continue; + this.seekTargetMicros = null; + } + return { + data: packet.data, + timestamp: timestamp, + duration: packet.duration, + type: packet.type + }; + } + return null; + } + + /** + * Repositions the normalized stream to the segment that covers a time, from the start of that segment. + * @param {number} seconds - The target position, in seconds. + * @returns {Promise} Zero, which is not a byte offset: the normalized stream is always repositioned by loading a new segment + * and dropping the packets before the target, so no container level byte seek is left for the engine to perform. + * @throws {LuminaAudioPlayer.PlayerError} When the target segment cannot be read. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const value = Number(seconds); + const requested = Number.isFinite(value) && value > 0 ? value : 0; + const knownDuration = Number(this.getDuration()); + const target = Number.isFinite(knownDuration) && knownDuration > 0 ? Math.min(requested, knownDuration) : requested; + const index = this.downloader && typeof this.downloader.findSegmentIndexForTime === 'function' + ? this.downloader.findSegmentIndexForTime(target) + : Math.max(0, Math.floor(target / this.segmentDurationSeconds)); + this.seekTargetMicros = toMicroseconds(target); + let loaded = await this.loadSegmentAsync(index, true); + if (!loaded && index > 0) { + // The produced end of the normalized audio can be shorter than the probed duration, so a seek at the very end + // falls back to the last segment that was actually produced instead of ending the track silently. + loaded = await this.loadSegmentAsync(index - 1, true); + } + if (!loaded || !this.inner) + return 0; + // A segment starts at the first packet at or after its boundary, so a target in the gap just before that packet belongs to the + // previous segment. The exact start the server indexed is known now, so the seek does not lose the frame at the boundary. + const loadedIndex = this.innerIndex; + if (this.getSegmentStartSeconds(loadedIndex) > target && loadedIndex > 0) { + const previousLoaded = await this.loadSegmentAsync(loadedIndex - 1, true); + if (!previousLoaded) + await this.loadSegmentAsync(loadedIndex, true); + } + // A segment is at most a few seconds long and is already in memory, so it is always read from its first packet. A segment + // is an independent container file, and a demuxer that seeds its timeline from a frame number counts that number across + // the whole track, so an inner seek would double the offset the segment already carries. Reading from the start and + // dropping the packets that end before the target in readPacketAsync is exact for every container. + return 0; + } + + /** + * Checks whether the stream was initialized and can be read. + * @returns {boolean} True when the stream is initialized. + */ + isInitialized() { + return this.initialized && !this.destroyed && this.error === null; + } + + /** + * Checks whether the stream can no longer be read, because it was destroyed or failed. + * @returns {boolean} True when the stream stopped. + */ + isStopped() { + return this.destroyed || this.error !== null; + } + + /** + * Checks whether the stream was destroyed. + * @returns {boolean} True when the stream was destroyed. + */ + isDestroyed() { + return this.destroyed; + } + + /** + * Gets the last failure the stream recorded, or null. + * @returns {LuminaAudioPlayer.PlayerError|null} The recorded failure. + */ + getError() { + return this.error; + } + + /** + * Records a failure once and reports it to the caller, so the decode pipeline stops with a typed error. + * @param {LuminaAudioPlayer.PlayerError} error - The failure to record. + * @returns {LuminaAudioPlayer.PlayerError} The recorded failure. + */ + recordFailure(error) { + if (this.error) + return this.error; + const typed = LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED); + this.error = typed; + this.initialized = false; + if (this.onError) { + try { + this.onError(typed); + } catch (callbackError) { + console.error('Audio player: the normalized demux error callback threw.', callbackError); + } + } + return typed; + } + + /** + * Creates the typed abort of an intentionally stopped normalized stream. + * @returns {LuminaAudioPlayer.PlayerError} The abort. + */ + createAbortError() { + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The normalized segment stream was aborted.'); + } + + /** + * Ensures the stream was initialized before it is read. + * @returns {void} + * @throws {LuminaAudioPlayer.PlayerError} When the stream was destroyed, failed, or was not initialized. + */ + ensureInitialized() { + if (this.destroyed) + throw this.createAbortError(); + if (this.error) + throw this.error; + if (!this.initialized) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The normalized segment stream is not initialized.'); + } + + /** + * Releases the segment demuxer that is open. + * @returns {Promise} A promise that completes when the stream was released. + */ + async destroyAsync() { + if (this.destroyed) + return; + this.destroyed = true; + this.initialized = false; + if (this.inner) { + const inner = this.inner; + this.inner = null; + try { + await inner.destroyAsync(); + } catch (error) { + console.debug('Audio player: the normalized segment demuxer could not be released.', error); + } + } + } + } + + LuminaAudioPlayer.NormalizedSegmentDownloader = NormalizedSegmentDownloader; + LuminaAudioPlayer.NormalizedSegmentDemuxer = NormalizedSegmentDemuxer; + + /** + * Creates the downloader of the segments of a normalized track. + * @param {Object} options - The downloader options, per {@link LuminaAudioPlayer.NormalizedSegmentDownloader}. + * @returns {LuminaAudioPlayer.NormalizedSegmentDownloader} The downloader. + */ + LuminaAudioPlayer.createNormalizedSegmentDownloader = function (options) { + return new NormalizedSegmentDownloader(options); + }; + + /** + * Creates and initializes the demuxer of a normalized playback manifest. + * @param {Object} manifest - The playback manifest of the normalized track. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.NormalizedSegmentDemuxer}. + * @returns {Promise} The ready demuxer. + * @throws {LuminaAudioPlayer.PlayerError} When the normalized delivery cannot be read. + */ + LuminaAudioPlayer.createNormalizedSegmentDemuxer = async function (manifest, options) { + const demuxer = new NormalizedSegmentDemuxer(Object.assign({}, options, { manifest: manifest })); + try { + await demuxer.initializeAsync(); + return demuxer; + } catch (error) { + // A partially initialized wrapper still holds segment 0 and its demuxer, so it is released before the failure is reported. + try { + await demuxer.destroyAsync(); + } catch (cleanupError) { + console.debug('Audio player: the partially initialized normalized demuxer could not be released.', cleanupError); + } + throw error; + } + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.sln b/src/Lumina.sln index f9cafda0..590b0893 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -288,6 +288,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657 ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\GetPlaybackManifest.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetPlaybackManifest.http ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http + ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrackSegment.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrackSegment.http ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http EndProjectSection diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs index 04d2d75a..6db9f0b4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs @@ -82,7 +82,7 @@ public class GetPlaybackManifestEndpointTests : IClassFixture Date: Sun, 18 Oct 2026 21:44:55 +0300 Subject: [PATCH 23/77] Implements player queue engine --- docs/technical/theming/Theming.md | 19 +- .../Core/Themes/Bundled/editorial-paper.zip | Bin 375101 -> 375454 bytes .../Core/Themes/Bundled/lumina-default.zip | Bin 374564 -> 374917 bytes .../Resources/Views/Shared/_Layout.ar-SA.resx | 36 + .../Resources/Views/Shared/_Layout.de-DE.resx | 36 + .../Resources/Views/Shared/_Layout.en-US.resx | 36 + .../Resources/Views/Shared/_Layout.es-ES.resx | 36 + .../Resources/Views/Shared/_Layout.fr-FR.resx | 36 + .../Resources/Views/Shared/_Layout.it-IT.resx | 36 + .../Resources/Views/Shared/_Layout.ja-JP.resx | 36 + .../Core/Resources/Views/Shared/_Layout.resx | 36 + .../Resources/Views/Shared/_Layout.ro-RO.resx | 36 + .../Resources/Views/Shared/_Layout.uk-UA.resx | 36 + .../Resources/Views/Shared/_Layout.zh-CN.resx | 36 + .../Core/Themes/ThemeAudioPlayerBuilder.cs | 14 +- .../Core/Views/Shared/_AudioPlayer.cshtml | 61 +- .../Views/Shared/_ThemeLayoutScripts.cshtml | 21 +- .../wwwroot/css/site.css | 147 +- .../js/audio-player/audio-player-engine.js | 5 +- .../js/audio-player/audio-player-errors.js | 4 +- .../js/audio-player/audio-player-events.js | 18 +- .../js/audio-player/audio-player-manifest.js | 24 +- .../audio-player-pipeline-engine.js | 34 + .../js/audio-player/audio-player-queue.js | 1719 ++++++++++++++++ .../js/audio-player/audio-player-render.js | 2 +- .../js/audio-player/audio-player-utils.js | 22 + .../wwwroot/js/audio-player/audio-player.js | 1814 +++++++++++++++-- 27 files changed, 4114 insertions(+), 186 deletions(-) create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-queue.js diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index 54df94a4..5122a2a7 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -229,7 +229,7 @@ The rendered page content, navigation and scripts are inserted unescaped with `{ ### The Audio Player Bar -Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar is hidden until the user starts playback of a track, album or artist, and the global audio player script shows it, expands it and hides it again. The markup comes from the `shared/audio-player` template of the active theme; when the theme does not provide that template, the application renders its own fallback markup, so the player always has a bar to bind to. +Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar starts hidden, and the global audio player script shows it when playback starts, expands it and hides it again. The markup comes from the `shared/audio-player` template of the active theme; when the theme does not provide that template, the application renders its own fallback markup, so the player always has a bar to bind to. The bar is fixed to the bottom of the viewport, so the theme owns the room reserved for it on the main content element. A layout must keep these element hooks, which the audio player drives (the two id controls are bound by the global site script, which routes them to the audio player): @@ -251,7 +251,7 @@ The `shared/audio-player` template receives the following model: | `assetBase` | The base URL of the theme assets, used by the theme template to reference its own assets. | | `queueItemTemplate` | The raw source of the `shared/audio-player/queue-item` sub template, inlined by the application into a plain text script element. | | `playlistItemTemplate` | The raw source of the `shared/audio-player/playlist-item` sub template, inlined by the application into a plain text script element. | -| `strings` | The localized strings of the bar, keyed by their resource names. A shell template uses `toggleFullHeight` and `toggleVisibility` for its two controls; the player reads the play, pause, mute, unmute, volume, seek and buffering labels from the global scripts configuration instead, so a themed shell does not need to render them. | +| `strings` | The localized strings of the bar, keyed by their resource names. A shell template uses `toggleFullHeight`, `toggleVisibility`, `previous`, `next`, `shuffle`, `shuffleOff`, `shuffleRelease`, `shuffleArtist`, `shuffleLibrary`, `repeat`, `repeatOff`, `repeatAll`, `repeatOne` and `queue` for its controls; the player reads the play, pause, mute, unmute, volume, seek and buffering labels from the global scripts configuration instead, so a themed shell does not need to render them. | A theme must reserve the space for the bar itself, as the bundled themes do: @@ -272,11 +272,18 @@ main.audio-player-full-height { The application fallback layout, which renders when the active theme cannot be loaded, reserves the room itself, because the application stylesheet does not position the content area of a theme. A theme that omits the rules above leaves the fixed bar overlapping the bottom of the page. -The markup inside the bar exposes the hook attributes the audio player script binds. A theme that replaces the bar markup must keep all of them; the part of the bar whose hook is missing stays inert. The play affordances of the pages use the `data-audio-player-play` trigger attribute. +The markup inside the bar exposes the hook attributes the audio player script binds. A theme that replaces the bar markup must keep all of them; the part of the bar whose hook is missing stays inert. The play affordances of the pages use the `data-audio-player-play` trigger attribute, and a play next affordance uses `data-audio-player-play-next`; both read the same descriptor attributes. A track trigger must supply `libraryId`, `trackId`, `albumId` and `artistId`, because the playback manifest route needs all four Ids. An album context trigger supplies `libraryId`, `albumId` and `artistId`, and an artist context trigger supplies `libraryId` and `artistId`. The deprecated `queuechange` event keeps its ordered descriptor array payload for older theme scripts; new code must use `queuestatechange`, whose payload is the compact queue summary. | Hook attribute | Meaning | | --- | --- | | `data-audio-player-play-pause` | The play and pause control. The player adds the `is-playing` class to it while a track plays. | +| `data-audio-player-previous` | The previous control. It either returns to the previous queue entry or restarts the current track, following the navigation history. | +| `data-audio-player-next` | The next control. It starts the next queue entry and loads another shuffle or autoplay batch when the queue is at its end. The player sets `disabled` and the `is-disabled` class when there is no next entry. | +| `data-audio-player-shuffle-control` | The wrapper of the shuffle toggle and its scope menu, so the player can position the menu and close it on an outside click. The player adds `is-menu-open` to the bar container while the menu is open, so a theme can let the menu overflow the bar. | +| `data-audio-player-shuffle` | The shuffle menu button when a scope menu is present: clicking it always opens the menu, the player sets `aria-haspopup="menu"`, `aria-expanded`, and the `is-active` class while shuffle is on, and it does not set `aria-pressed`. Without a scope menu the control is a plain toggle that exposes `aria-pressed` instead. | +| `data-audio-player-shuffle-menu` | The shuffle scope menu, hidden with the `hidden` attribute while it is closed. | +| `data-audio-player-shuffle-scope` | A scope item inside the menu, with the value `off`, `release`, `artist` or `library`. The player toggles `aria-checked` and the `is-selected` class on it; the `off` item is selected while shuffle is off. A scope whose required Ids cannot be resolved from the current queue is disabled with `disabled`, `aria-disabled="true"` and the `is-disabled` class. | +| `data-audio-player-repeat` | The repeat toggle. The player writes `data-audio-player-repeat-mode` (`off`, `all` or `one`), toggles `aria-pressed`, the `is-active` class and, for one, the `is-one` class. | | `data-audio-player-progress` | The progress bar, a `role="slider"` element with `tabindex="0"` that the player scrubs and whose ARIA value attributes it writes. It carries `data-audio-player-progress-state` (`idle`, `ready` or `buffering`) and the `is-buffering` class while it loads. | | `data-audio-player-progress-played` | The played layer of the bar. The player publishes its start and width as the custom properties `--audio-player-progress-played-start` and `--audio-player-progress-played-width`. | | `data-audio-player-progress-downloaded` | The downloaded but not played layer. `--audio-player-progress-downloaded-start` and `--audio-player-progress-downloaded-width`. | @@ -288,7 +295,7 @@ The markup inside the bar exposes the hook attributes the audio player script bi | `data-audio-player-volume` | The volume slider, a `role="slider"` element with `tabindex="0"` that the player scrubs and whose ARIA value attributes it writes. The fill is published as `--audio-player-volume-start` and `--audio-player-volume-width`. | | `data-audio-player-volume-level` | The volume fill. It carries no geometry of its own: the stylesheet drives it from the custom properties above. | | `data-audio-player-mute` | The mute toggle. The player toggles the `is-muted` class and the `aria-pressed` state on it. | -| `data-audio-player-queue` | The queue list of the expanded bar. | +| `data-audio-player-queue` | The queue list of the expanded bar. The player writes `data-audio-player-queue-entry-id` on every rendered item root, whether it comes from the theme sub template or from the built-in markup, and makes the root focusable, so clicking an item or pressing Enter or Space on it starts that entry. | Each progress layer also carries `data-audio-player-progress-layer` (`played`, `downloaded` or `undownloaded`) in the markup, so a theme can select a layer by its state as well as by its class. The player writes no inline geometry on any of the bar elements: it publishes the geometry of each state as the custom properties above, which the application stylesheet consumes, so a theme restyles or reorients either bar by consuming the same properties. @@ -305,11 +312,13 @@ The sub templates are rendered client side by the audio player script with the s | Template | Fields | | --- | --- | -| `queue-item` | `index` (the one based position in the queue), `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration` (the formatted `m:ss` duration), `durationSeconds`, `coverArtUrl`, `isCurrent`, `isPlayed` and `isLast`. The item root must keep the `audio-player-queue-item` class, the stylesheet hook of a queue item: the player appends the rendered element as-is, so the class is what lets the theme style it. | +| `queue-item` | `entryId` (the identity of this occurrence in the queue), `index` (the one based position in the queue), `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration` (the formatted `m:ss` duration), `durationSeconds`, `coverArtUrl`, `isCurrent`, `isPlayed`, `isLast`, `isContinuation` (the entry was added by the autoplay continuation) and `isShuffled` (the entry was added by a shuffle batch). The item root must keep the `audio-player-queue-item` class, the stylesheet hook of a queue item: the player appends the rendered element as-is, so the class is what lets the theme style it. The built-in item also adds `is-current`, `is-played`, `is-continuation` and `is-shuffled` to the root. The player writes `data-audio-player-queue-entry-id` on the root itself, so a theme item does not need to render the identity. | | `playlist-item` | `index`, `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration`, `durationSeconds`, `coverArtUrl` and `isCurrent`. The item root must keep the `audio-player-playlist-item` class, the stylesheet hook of a playlist item. Saved playlists do not exist yet, so the shell inlines this sub template for theme authors, but nothing renders it yet; the playlist feature renders the entries of a playlist from it. | A theme can omit either sub template: the player then renders that part with its own built-in markup. When a theme replaces the shell, it must keep the two plain text script element ids above, the element hooks of the bar, and the `audio-player-container`, `not-shown` and `full-height` classes the player toggles. +Every field of the `queue-item` and `playlist-item` models is untrusted: titles and identifiers come from file metadata and the music endpoints. Render these fields with the escaped form, `{{field}}`. The template engine also supports the unescaped form `{{{field}}}`, but these models contain no trusted HTML, so unescaped tags must not be used for them. Escaping does not neutralise whitespace in an unquoted attribute, so every model value placed in an attribute must sit inside quoted attribute marks, for example `data-track-id="{{trackId}}"` and never `data-track-id={{trackId}}`. + ### The Navigation Template (shared/nav-menu) The navigation template renders the menu of the active theme. Its model contains the site name and two menu structures, one for the mobile menu and one for the desktop menu bar: diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index 28b833d95508816807bb119bff852568d01e5e4b..0888cd02fb3e6464e0219b5b9a62fd1cd3337096 100644 GIT binary patch delta 3211 zcmZ9Pc_7s3AIE3D-+3hGxW=TNb|^E1Oh>v@POsuxj(P&RV`9K5(xweR5JYi zg8Xy>!$X2CPSpnD`ech~)=YhN7rR20{2*+Mz-KsTQtTvA^6$ZzqbXOEFW$HAi=09sX z82Z$n=>B;k+rz=cp;p7*+^1HeI3dVWv$}0|yYu_wMso4UDinylsHgjW?y{7k?P9hMr zP}ph&0yJQPMNA!kM$p~{SMQ`JtEHHu1^3rw+ZA{v1Y3mFlC+LVFVyq7VL#?sG2~jP z9r=+{+nqeR!J4n2$^Nyq>_(q@iY43hw7k{OwH|i|iCryxpR%5Wh{Gdh?G9GW)g;?I z{zJpzjg-6>PGH~ovF_2&^Q@afl4u+y$D;v02l5=~YV181yEx0W0)oz`-kdY!rzip5x^C&R)CiPy-rb_E-O4MkyoqW@d)E8Sl z)<5S|hK=kn(0TW49WQTPpdQ2OEzw{+dHd-kM@AOZw^S8DTbrL4yvXi* zz`3(hO1bXGdzRy&FWuH&a;L0P5Zin+%TH}T|JE70;``m9cMJ7<6}_oCi3(Rs+Fqo} z25In0d<0ZSsvVx7z4FEwzcnsXw%l03*-eA5*<H1wNE*(8Q z9oFE9KF3fp^IF8?Wu7pg7c`ykL8erlGgix;3Yy>(BgkHQ4Pk-ILjMEMZk< z^_JsD$ zefk8&?GE?%x=xx)xa7rMh51JOz1cJUpHxaS&3vu<)QfAFI?l>6Uuw%fOxH zXPh(+aO!CpZG8W;Pt)11w7b?hTg*SZ1W%?*26OU%ok^EBoxX1LIjrHjS-?cM_xVs8 zYL!N3NVbXOu|kt|_D*Y?c6i-3S{4uzFZNVRWz;Xf+jyhY-*kuNwy|ezztr_TNqN)X zlOy^1$gLAh##N(y%YN=i(0I95Rb&132^ss3?i|>CkttDc8a9@{yED2z_vx1cAG64Z z`Yr!^G&Aq}^Q2oT!mb9Ll||^xTmki%Ko!zs0hyV+QKFtsw)n7y)p_M5rjb!rvwVys zFHH-yE$&r|KM-P|v4mw_RAT!6%Q{*EPQ04HcsQxuslsX6}dE zzO7P+2d&u-F?w1Np2zlE$ysjq-=qAno9y8ze#AZUx2;AfZYrBS|WEpXmlmdiJV1uCDt}t$eQwp9zD5 z0UfN0A==_Sl0oBQ5KjZkFmyD=rU44HNCRuIM50hwVe&Xfj`RZ@5E>@Mp+Y)XPo9t@ z5PZYK{TSi8zxez8vIpj*17%K;3|R_gcW| za8z}aIA#ka;Q^smTY`b77neLc{ zKJK#cna~s#D%4P$3sz!LN1-nlxMB^dv+OS}3S?{ftUrV|A5IhiGN-X+?le1^XPxYG zzyS036V(@U4s}Vx@pGu>ef>~13%Fro(}=5cmd!}Ok}R+cACx9?!opPHR2Eo|=PwqC z9ofJHch(n)>TIBoJ+XvlIbboA$pL!U7hj>+j(v&{mg=x32N+`k$3>3B1mf2S_i%}G zXBU+zGGuaz(vW!`jqP0}8X>ltI8T(6m*-JZ)NZEa0uQX^DJnGJ(OeX_>D$?QUoIM` zK@4uoM-9XCFcs*Xhhl47AS6rS8x>3fUK5gN6A@9!2kS7q?Ly&!i3fX@Yjndg_+JGQszREgDpZ*<|-mL+(?p;Qie#x4iSlWC&`L7 z2BQqE)ItvtUg3#wUOCG3@J`a)Tu=Fm43fW~zMD#rA!^rmhU0!BL&h$W6tpczLk$Lq z$cb`bjwuFz6SDAKInc$>MQ=91)jYKCYr{q24+fg(F&=t)(|*Y3flYYwK@v=kBrSxG zD$t;dE6`*Y#X{2xunD6dg-0vE25ct_{$2srVlW93`A8SD;YL2%o%=YD$wz!|8m!|3 zYpl8!ieCa|czGQOvbBINd?p}~VZtT!z6AAuMVSL6c{nLV%Rl{#=0nfRDCKNT$i55$ zv5%XDr6QEJ1gnH*GA!@{bF)?H`OTmW4_^XQ;pJKd7mo&z7z=)c&Xqt7whK`QLcYmB zJtYnRs8WT-^-P>4#*isg)+c6_24t{-9Nc^bjrG0?J$K^dSH8L$y|_`QU}!bkG;PVS zrW#n|g{J{5g@CSTZ$rcs3E$u2;qz2LS^JU$=G@}{>-*1L_}{mQaOccy42vMB1ahjv j{|4Xv&dqTW2%2fLULA_P4GiF7iYQA9THK;Si%4z?p@nprYLcmxlKt4n9@z$I ztd(1@7Sbk_vb5jcu|+rc%5u+RyqW%ZXZ|?n`+2_S{C?;6obxcUgcGLCrJ>X**R^>xzGA+Ny^vTWgq}RtrvYpQR z>2A*A-z-x;hg|%p-s`(TztA;V%CE8JR?=Ly{eufPcg=g2mDA=f{M_{No1I|e=0lzQ z#rqVG*hdhRL*>?kLx{EKnIdv)*xa+n#KL+DRgN zP~=_V-{P#IQoi_gjKu~MBmdqtRmsW2J$E;@WIJ6>gooEHxcB5~X_mXwJyRVeBjFpS zwui;#ju3}vD^9rT!l!l8&*OqW=116{4*VYUxO8M5?R#HSP@%xpMcyHQ38#h9Y`#cg zal6L%8H+TQFUfhTAGnYEc&S-Hvx>cOvubE2@!&$Xob-pHHCnfsZc^%uh=2pg%gxc| z{VD;^E6u7=yH_K-NhZ4eU?Xc*(Mq@E?AwRCBVDVUX$F~sR5h!lR3kjqm2|17y`6s+4~%H_{*=UscG@ob6X zz9_Zd!osvfW-D3pha3AXtvfB%OLyLn-Pk4NB4Cx-BzS>Y!~PXJba%l-_7^{vanUE= z1c!5e>C<&}EN}jq`T5oS?P(txR%?FVVdDLFBtIyVo=+>LD+ywjUAd!>D$B1^@Mb6{ zvdiC{=~-c{He)1T(ee>jDW+PVxxdqS^KZ8}{vH)?ww@4Xw8Y7IYYC3l4(_w{IIeDc zK%Z#n5V7ud_02GNbCGVaU0%7%AtZ)bD*g6#l~2)D`Rb)jUoOpP{c@tV|9I}w>g-_W z^x%#XmtR^$aRc)!Iu#-Z7jU2L4m`y%dKzsb|9HSn&#!m%zSZ<&v1hsSdg`k~kJ9sw zWwl?Pvn)VabMdyjL0tx=9Oq+g-JJRld5y|$@k8xKhNn3VBci%NFURs-sRMg;(*Jl+ zIk%+pWsUUubCcX!ADK5a84Uk=?cu{l$K3q`FRZUeJ`nEd>(f6J(tj%Ee))w_{*!yF zv_D@m9({N2@~E1#`dfKtQ37P7K zPSZS7vLa`@g!wREO{-_#-y5elr(#|3CSGA?|2l=a8D%;JokQXK)l8N5%<}ywCH3o; zq>!1e-yVAWlk8wVDHz55-ZRhxl5Cw_lV(Tl9-;hv;BD-Y3I{%zqR026U&04o6`93D z18$fe19lf_KTtM|rnZsHm zolk8ytIhlSZO{wz{WZ4NW229~Z>G5k?rhE*)VJzvtM6Vb8$La)f5GY1Rvo-=)c1S0 ziyjHPE7XU)yqwbrG=D)$X}ZG(hd$NE*-bNuUa%~c9OyayqC&Vh0&dQ_lD z`Tx%`gWM~1*t#F@>Qj(z|U^|lisN*~25IqIYVs~gv7ag2}oJs9;dd!=jg1tHM zxUYwl_?YVn&`LhE2bB$D*DLu@ADFj{^_i*A2-trj`%!|AvM3-G`#*mlyLKlPE(P@r zv^x#5krsnG6(!~36fM(miXpQ}yb~DflkF_@HVrNU*Vl=?hUribymb`|Q&%dTOoNG} zk5ZX36XoqVDmHYa!{y-D^I~D1fnz!)i$y{PPHt7XSR@PaJi{3{J@|*1xYSaa$T1U> zqShaTh8V3>IaEzzcAq59f<{CR9Uy8N)I@kJ4f$k23nEW-9Q6hRI%>^=O9Ciqn3Ln4iY2}DP?F5`4mizU%90gx3} zs{Sru%1%@&_1?J6TI zAuqm}E%Jn9q#}h0+a{vK_8R{`T#XJS-1aahlIK`betE zka1;}4-JXCapNj39~uy;MPo_{^%N4aNJoJ8ijL@~yeOUH4jU1UXj*_HDs7~ZD^fz- z0=%7dHlfFba4M?9g1QB*EQE@PznL}#u?q1<(6~CWQw62x-G!74*2{a zX5jT*V*FQ|1c9)`zigVr@D z@fuu#_Flv5jCUr*w&@e!L=*~pV)Npj2r-0E1I??1@~Gz;oC%b;NKOb>sr`6k;7`Sc zKMi?5=FmU^;k)^PpQF&?pF2Zc%=6Ok0FwBs%B=TN%|6)6<0CfaF3t;eJzM&55R zCa**(Daz^{+fz27Rg+Cms^6K$uXbntIQR28-+RvYoOAEFr}TvicT$CLbHoW~2!VQ% zh$|vs^uG`{(qc#(}J^IUP^6{{ifWk<4a>!R3JFq-4)N zX0DEs?u1ak=Q*od$-d~E;7Dtj$xZ(Hb9Wd=yKnLua<3eYR}Gs^Y-l?hTio(e#reBa zQ$E~K`~9nfmL-mU)N-z9LA1wJvDZK6 zu}k2pN4)0f=l)E?e;!&1O06P{W9%o%%-0znS?QiJ1<=HCL6nJ_9x4A0V_V?@s@ip* zwA0`&s$*IOug`{@exhFL-D6Mh_@z~|kd(-jBquL@Q7 z85kBAa>ovhcy3oX6L)8EEoa4PIoI{y(Z>5!=X(t6nFi}yt@xeVb>zXRNWVr#5a;fJ zR5O07Q_7g~JMB!*Ecw5OXzYXloeVbt_Ln?lk@-MUx(tUQyo(QchGZ$_xoO$|Dy_RpY!C_=!b(^8Ls@!MJ>AJVm?Xqm5 zR{q_|9#iR%)$@Z3r}f;~bgegW_Xmm2t4S}Py(5CRl<$(+$FaLiJMX#C)u}_jDMr0H z@RU=!Lin*h;|yMvR)NZaP4C+?9HhgIIcF~8;qMS3^6L(j3ksy;f zZ5cb5%=4-49v*fd8Lb=Re-OwF+6ueqH+km2k3Zx*^V7SXruSB+zTcZO;39pO^vHDg zD(}3*7U5pQeWIRMKZf*X-#vEOp~%VhlTYNkT-iuo*)KD>iq_L-%|AtVpS1~pGZb9B z-BGPYcQC5ZQuaWlrInl4%3go=Mf1hsQ3s{&>#K`4l?_?^KzYG%U*fzk+xc_*$i1U4 zpAHwvPV7H_h!b)9G;Lr)q+%D_rsj|(3d%8;Qf366z ziN9si_w((UIpQ7Y+qN>K9Ov4GHkm4@wHKIiGJcrb#Za(&yMjB|^aRt*t7}^_MJQ6~ z5zf_rX&>Ab#nfHEwXLeLe)ZXkUIy;?Dcg2=-7-FSy}EbzWU8(@IqdkNdJOB_ThoBfLv z$1J_xDimrQR~*0cBGGTh-ZKSvEW%S;l=IRlB|EHFvlxYD?fFIlYx{-l@=v6(vG4(I z!#G`Mi|n@7Qcxd)#bi?Egf5InS6CXEw;TH&UJzSFD1zWe?42~U$N{UcH?nY74zR{r zsjyXChSA`AvA?0pJFBJ!-HxH#4b*w^hRQrc4Oz$+v-VQNdQc?3#*AT6K2YUJnW#gj zTqFYR#6p|5WgP{Ui-onnM7RXV!<=%U0G0B9Iu^ZMV)sSMK>s`xmhh`Yq;M%PHXnsu z5QlZ=e6bMYgB6%dy##{!U>P=WMFP!yz{CRo6oU?=<^ywV$5SyZgj@1~DOm~@<^z9x zj7o-&^MDrAJPuajWjeFOISwpwZvG5cLSQUchSOQ-Hsrh88B>BcdlzeatyjBQ2aP4zs*ieizax4PN@xJ@B^ymRu z9<~;N#klq4teRU4EU<1VC@2QHFrpZ&#d_w8Aqd-JDJ~a5ixOakxq3*Tpae~XbhrdG zBQOe-DMg72_e%`B6y>(+m;}z2qNdFS5^!$7sL-ek#dh?FjV`>_i+u<4#YX+^SEB@N z?qTzxTm@Q=CFN*DEuw$b?JEbi_$3UNj14uQ1V5I8m3ZI0Srt+Nobjs`vvj)xFmbBg zEHT#MGSH$D4SvRVR>}M0b0xFaS^_9gPzmI)<=bFqCGf@ve#0f}XIX`&a0JfMkt$$@ zchr3$W!PDdQ{js$)F%D!S!G-emf=iiLVU9_+*6I76_y*UuLgGbc6S1@JqQg+m)bRG zcxYZ%*8n>#-V<_bz&ecY4gaVCE?Au}q}Ku#7UvH)*8(S8BanbHL4+0@s70N<-$208 zjf9T4YXukXMts@4G` z?0qz3)qyqG>7DR!9bn;WVhLyxN2tM2MPmma!CZuPO#m}GAd?iXjE+E&xT@bzbL51rT+qPIbWB-%n(B&QnZnB&25Y1^1~LTL?rC0B$Y^u%Fm)Gi->0o<2r7+ zO{5{UtzTD^l2&C`QrUhjxny72)t29xIkq1=^T+wVKi}thzR&Z$os%@d5sY$_Jlt?X znMR|@(7d;M>~t`Y$p^zsq(`@gt(mAKo{_|$Co!-j2A;$qni$9-S^+XYE&L6m(Q4&r zG#wD8AZ0ihjpTvVj8I&y*T$?KBl)Y72C4Ul!&;*H{MFQ&O@GOD*!ZPo)VOmipZ{^} z&ZfTdofUcLu*=H!hdqsDdv~_4HBhk>4YKt^94ekCd!2KN%}_V&xh40QoA7JR*=e3(AE`KC{Zs1TCXKDTVV1D_H z!=sr&t^S0$Kv<;Vlz)6pqOXlkEv@ymZ0O^K!wU?1E2VX=>zKT5TM*d$h{Hc~i?#pY z*1h2Y7A7~%E?Oq6>RTIExMCpj(gW?E%zXD`X?&fQrZ>E9JxB3y*QBG{h@)1cUq{ZS zw~PQGr^%hSA6xn{s%6KjT_{gyB9dcO|2l%_l@eL9XqAEEkN*|C`FVv;@zC83OWy4G zGVG7c!gzsn4RJwQMVM`U{u?V|G>=nxATv9UsK0WM461hmQDf z`TBZnR7lI<_7kGgJ}xUvPk6L#dXGoQaV?L7Civaw!<;*B-)Wi;elKnAqp14UD><9p zDEH!*)&uq16|Y!4nn>5|pE%JrdA!QvN_m2RNy77nfYp7&+^H2UBTAXmE8~6&jQK9s zvge$;V)sj80)-p=BRY_v9f^*UF&GoC8pkY;@_G##`+(7HX7SG zRNbW-ocq^+<(j0}yPt+{P4D+@-c>ZU+o0q>_bxAQxcv00oNJ0yaQ_3_yN}F2es$^o z{Vw0C(5WYGKV;q$ee>>}NqF+)ciA1ysWXKS+wJw=q+89rOsSaB@Yi}lQ@(8{7kA2% z`7rxXalm3<#_Mk5MmNu(BZ3unIUkEELwEwMH9HsXD=5oc7Lay;{qw?3cE@h6v2Ke? z!sf&}!K91Q^3o=Q+L6C9LN(T^ezP><&w`@gJ@b8ydRE>Qd%^%8nP7%}k|?~VOvxDFS%B2B4X-7l@K*&WC?LZ< z{vdG}DL@u@3zH7v6=(@K7oxRz)UsKsEJW7$a+6t-DniD1jms?gis?bnED6Qbb##_& zj?xvyIqKuqr)Q;#6uJUPRUtMc=hN8=f7eT+x$$Q$t`#Fo+^Bh$_#(PAmApv_QpYFT zB)Tp{mY_8_zkimP{d5*(H6gZQznj%fOOYj(BMpZtkRC`&W9m>_N|v0fPAM~`$O8My zh5~;9xw_h0DYz*>Yp|yw6u5?9EGlRFGI9bF5-B;cj9f-0kAk>dOcCCfk-=pyP)f8A zV}o}&sid`w6)U(}j!fypFj0<L&Kfq*tT0W){71)zcBicnKY&QPBs zK6hpLO8+#?uSC{Zk<}deQzbH?KLg_`v;({6GpA#n56*zARb)2O2Pj$YJTk*7lf~eT zUE+$L%i!91WQwKLi-7}Ub+`hkR+B!X!<6DajLS+k9UQJE=NaEbh_{Oh2&&25ws13q z*P{h6EQa--6clbDWWlC}j6qJVr2B*?AtRnCHk{f@%&pIL8)eW|L*@{+oq|p;LJ`z! zN&h$>O6m6|bb`UIh%_qaI@S7KQ#E&v?^&?n0b!4E9AWE>ULpIos z-4vwPkqh3kkAl8B@?Z}g_zWztt4FJ`j>BSQ1C|;|_52p`cP6ju$xM`^a)f9D9vDqP z?YG1t@ioGRa3NBsk3p&sInXDdTZn8~rY8wnU_?Z4WW?%-kjP*#&LuxT%F^d0y*C5g zFQ9c;Y$l{%KsNXhE&**oXu-$@vVykDpw@uw@a9$m{{4Y4f-?=s3Xd9+kR{ACAXD7z zFA3QJuYpYCu`ZfB)jT~YZbbVqoV=JC$B zUrql%xnxT*2F69m2*#Tb0exa`o8w^DjI`lcG*Y6x=e<$pc{5IkZH*zn0Wra{iQHJP zP9PXOgLEOL39ZKWrAbH+o}|nMgWpLjY نعم + + المقطع السابق + + + المقطع التالي + + + تشغيل عشوائي + + + تشغيل الألبوم عشوائياً + + + تشغيل الفنان عشوائياً + + + تشغيل المكتبة عشوائياً + + + تكرار + + + التكرار متوقف + + + تكرار الكل + + + تكرار مقطع واحد + + + قائمة التشغيل + + + تشغيل عشوائي متوقف + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx index 66d2225f..2f81b8b7 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx @@ -180,4 +180,40 @@ Ja + + Vorheriger Titel + + + Nächster Titel + + + Zufallswiedergabe + + + Release zufällig abspielen + + + Interpret zufällig abspielen + + + Bibliothek zufällig abspielen + + + Wiederholen + + + Wiederholung aus + + + Alle wiederholen + + + Titel wiederholen + + + Warteschlange + + + Zufallswiedergabe aus + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx index 8af1c8e3..ce26252c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx @@ -180,4 +180,40 @@ Yes + + Previous track + + + Next track + + + Shuffle + + + Shuffle release + + + Shuffle artist + + + Shuffle library + + + Repeat + + + Repeat off + + + Repeat all + + + Repeat one + + + Play queue + + + Shuffle off + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx index aa48670f..b4ca5eb8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx @@ -180,4 +180,40 @@ Sí + + Pista anterior + + + Pista siguiente + + + Reproducción aleatoria + + + Aleatorio por álbum + + + Aleatorio por artista + + + Aleatorio por biblioteca + + + Repetir + + + Repetición desactivada + + + Repetir todo + + + Repetir pista + + + Cola de reproducción + + + Reproducción aleatoria desactivada + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx index 89f415cd..6c76035b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx @@ -180,4 +180,40 @@ Oui + + Piste précédente + + + Piste suivante + + + Lecture aléatoire + + + Aléatoire sur la sortie + + + Aléatoire sur l’artiste + + + Aléatoire sur la bibliothèque + + + Répéter + + + Répétition désactivée + + + Tout répéter + + + Répéter la piste + + + File de lecture + + + Lecture aléatoire désactivée + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx index 96e4c685..b743bc30 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx @@ -180,4 +180,40 @@ Sì + + Brano precedente + + + Brano successivo + + + Riproduzione casuale + + + Casuale per album + + + Casuale per artista + + + Casuale per libreria + + + Ripeti + + + Ripetizione disattivata + + + Ripeti tutto + + + Ripeti brano + + + Coda di riproduzione + + + Riproduzione casuale disattivata + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx index 498740a1..301beb9a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx @@ -180,4 +180,40 @@ はい + + 前の曲 + + + 次の曲 + + + シャッフル + + + アルバムをシャッフル + + + アーティストをシャッフル + + + ライブラリをシャッフル + + + リピート + + + リピートなし + + + すべてリピート + + + 1曲リピート + + + 再生キュー + + + シャッフルなし + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx index 8af1c8e3..ce26252c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx @@ -180,4 +180,40 @@ Yes + + Previous track + + + Next track + + + Shuffle + + + Shuffle release + + + Shuffle artist + + + Shuffle library + + + Repeat + + + Repeat off + + + Repeat all + + + Repeat one + + + Play queue + + + Shuffle off + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx index cc6f9de6..6fe040f3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx @@ -180,4 +180,40 @@ Da + + Piesa anterioară + + + Piesa următoare + + + Redare aleatorie + + + Aleatoriu pe album + + + Aleatoriu pe artist + + + Aleatoriu pe bibliotecă + + + Repetă + + + Repetare oprită + + + Repetă tot + + + Repetă piesa + + + Coada de redare + + + Redare aleatorie oprită + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx index 847d6304..747b667d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx @@ -180,4 +180,40 @@ Так + + Попередній трек + + + Наступний трек + + + Перемішати + + + Перемішати альбом + + + Перемішати виконавця + + + Перемішати бібліотеку + + + Повтор + + + Повтор вимкнено + + + Повторити все + + + Повторити трек + + + Черга відтворення + + + Перемішування вимкнено + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx index 49547c28..63ae135a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx @@ -180,4 +180,40 @@ 是 + + 上一首 + + + 下一首 + + + 随机播放 + + + 随机播放专辑 + + + 随机播放艺术家 + + + 随机播放音乐库 + + + 循环播放 + + + 不循环 + + + 列表循环 + + + 单曲循环 + + + 播放队列 + + + 关闭随机播放 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs index 6f00a28f..5abe0da3 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs @@ -42,7 +42,19 @@ public sealed class ThemeAudioPlayerBuilder Dictionary strings = new() { ["toggleFullHeight"] = Localize("ToggleFullHeight"), - ["toggleVisibility"] = Localize("ToggleVisibility") + ["toggleVisibility"] = Localize("ToggleVisibility"), + ["previous"] = Localize("AudioPlayerPrevious"), + ["next"] = Localize("AudioPlayerNext"), + ["shuffle"] = Localize("AudioPlayerShuffle"), + ["shuffleOff"] = Localize("AudioPlayerShuffleOff"), + ["shuffleRelease"] = Localize("AudioPlayerShuffleRelease"), + ["shuffleArtist"] = Localize("AudioPlayerShuffleArtist"), + ["shuffleLibrary"] = Localize("AudioPlayerShuffleLibrary"), + ["repeat"] = Localize("AudioPlayerRepeat"), + ["repeatOff"] = Localize("AudioPlayerRepeatOff"), + ["repeatAll"] = Localize("AudioPlayerRepeatAll"), + ["repeatOne"] = Localize("AudioPlayerRepeatOne"), + ["queue"] = Localize("AudioPlayerQueue") }; return new ThemeAudioPlayerDto( diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml index 3fb2d034..f2e864f0 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml @@ -27,11 +27,20 @@ while it is expanded. The audio player toggles both classes on it as well. - The elements with the ids 'audio-player-full-height-toggle' and 'audio-player-close', which the global site script binds and routes to the audio player. - - The hook attributes the audio player binds: 'data-audio-player-play-pause', '-progress', '-progress-played', - '-progress-downloaded', '-progress-undownloaded', '-current-time', '-total-time', '-track-name', - '-cover-thumbnail', '-cover-image', '-volume', '-volume-level', '-mute' and '-queue'. The volume fill element - ('-volume-level') is a styling hook the stylesheet drives from the custom properties below, not one the script - writes to. + - The hook attributes the audio player binds: 'data-audio-player-play-pause', '-previous', '-next', '-shuffle', + '-shuffle-control', '-shuffle-menu', '-repeat', '-progress', '-progress-played', '-progress-downloaded', + '-progress-undownloaded', '-current-time', '-total-time', '-track-name', '-cover-thumbnail', '-cover-image', + '-volume', '-volume-level', '-mute' and '-queue'. The volume fill element ('-volume-level') is a styling hook the + stylesheet drives from the custom properties below, not one the script writes to. + - The shuffle scope items carry 'data-audio-player-shuffle-scope' ('off', 'release', 'artist' or 'library'), inside + the menu element carrying 'data-audio-player-shuffle-menu'. The shuffle control carries 'data-audio-player-shuffle' + and is wrapped by 'data-audio-player-shuffle-control', so the player can open the menu near it and close it on an + outside click. It is a menu button: it carries 'aria-haspopup' and 'aria-expanded', gets the 'is-active' class while + shuffle is on, and does not carry 'aria-pressed'. The scope items get 'aria-checked' and the 'is-selected' class, and + the 'off' item is selected while shuffle is off. The repeat toggle carries 'data-audio-player-repeat' and the player + writes 'data-audio-player-repeat-mode' ('off', 'all' or 'one') and toggles the 'is-active' and 'is-one' classes on it. + A queue item root rendered by the player always carries 'data-audio-player-queue-entry-id', whether it comes from the + theme sub template or from the built-in markup, so clicking it starts that entry. - The three state progress bar: the played part carries 'audio-player-progress-played', the downloaded but not played part carries 'audio-player-progress-downloaded', and the not yet downloaded part carries 'audio-player-progress-undownloaded'. Each layer also carries 'data-audio-player-progress-layer' ('played', @@ -43,19 +52,22 @@ geometry, so a theme consumes the properties to style each state and to give either bar its own shape and orientation. The player marks the bar with 'is-buffering' while it is loading, and carries the state in 'data-audio-player-progress-state' ('idle', 'ready' or 'buffering') together with the slider ARIA attributes. - - The plain text script elements that carry the raw source of the 'shared/audio-player/queue-item' and - 'shared/audio-player/playlist-item' sub templates, with the ids 'audio-player-template-queue-item' and - 'audio-player-template-playlist-item'. + - Themed shells only: the plain text script elements that carry the raw source of the + 'shared/audio-player/queue-item' and 'shared/audio-player/playlist-item' sub templates, with the ids + 'audio-player-template-queue-item' and 'audio-player-template-playlist-item'. This application fallback partial + renders neither element; it intentionally uses the built-in queue item markup. - The play affordances the pages hand to the player use the 'data-audio-player-play' trigger attribute. The - 'The Audio Player Bar' section of docs/technical/theming/Theming.md documents this contract for theme authors. + The play affordances the pages hand to the player use the 'data-audio-player-play' trigger attribute, and a play next + affordance uses 'data-audio-player-play-next'. A track trigger must carry libraryId, trackId, albumId and artistId, + because the playback manifest route needs all four Ids. The 'The Audio Player Bar' section of + docs/technical/theming/Theming.md documents this contract for theme authors. *@