mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 23:11:10 +00:00
Adds the playback manifest endpoint
This commit is contained in:
1 parent
7dc5953e1d
commit
d7c1ae60c2
17 files changed
+993
-10
No files matched your search
+62
@@ -0,0 +1,62 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the stored probe result of a track, containing only the fields a playback manifest is built from.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Container: {Container} Codec: {AudioCodec}")]
|
||||
public sealed record TrackPlaybackManifestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable.
|
||||
/// </summary>
|
||||
public string? Container { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the audio codec used by the audio file of the track, if applicable.
|
||||
/// </summary>
|
||||
public string? AudioCodec { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the audio of the track in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the sample rate of the audio of the track in Hz.
|
||||
/// </summary>
|
||||
public int SampleRate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of audio channels of the track.
|
||||
/// </summary>
|
||||
public int Channels { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bit depth of the audio of the track, if applicable.
|
||||
/// </summary>
|
||||
public int? BitDepth { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ReplayGain track gain of the track, in decibels, if applicable.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainTrackGain { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ReplayGain track peak of the track, if applicable.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainTrackPeak { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ReplayGain album gain of the track, in decibels, if applicable.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainAlbumGain { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ReplayGain album peak of the track, if applicable.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainAlbumPeak { get; init; }
|
||||
}
|
||||
+16
@@ -74,6 +74,22 @@ public interface ITrackRepository : IRepository<TrackEntity>,
|
||||
/// </returns>
|
||||
Task<Result<TrackStreamDto?>> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the stored probe result needed to build the playback manifest of the track identified by <paramref name="trackId"/>, when it belongs to
|
||||
/// the album identified by <paramref name="albumId"/> and to the media library identified by <paramref name="libraryId"/>, and that album belongs
|
||||
/// to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track must belong to.</param>
|
||||
/// <param name="albumId">The Id of the album the track must belong to.</param>
|
||||
/// <param name="artistId">The Id of the artist that must own the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track whose playback manifest data is retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the <see cref="TrackPlaybackManifestDto"/> of the track, <see langword="null"/> when no track
|
||||
/// matches the provided identifiers, or an error.
|
||||
/// </returns>
|
||||
Task<Result<TrackPlaybackManifestDto?>> GetPlaybackManifestInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Resets the enrichment state of the tracks stored at the provided <paramref name="paths"/> in the media library identified by
|
||||
/// <paramref name="libraryId"/>, together with their albums and artists, so that they are re-enriched, because their content changed since the last scan.
|
||||
|
||||
+22
-8
@@ -14,8 +14,9 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playbac
|
||||
/// The input is a comma separated list of <c>container/codec</c> pairs, for example
|
||||
/// <c>mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac</c>. 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
|
||||
/// <see cref="Default"/> 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 <see cref="Default"/> capabilities of the bundled player apply.
|
||||
/// </remarks>
|
||||
public static class PlaybackCapabilitiesParser
|
||||
{
|
||||
@@ -58,17 +59,30 @@ public static class PlaybackCapabilitiesParser
|
||||
return Default;
|
||||
|
||||
List<PlaybackCapabilityDto> 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<char> 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<char> entry = entrySeparatorIndex < 0 ? remainingEntries : remainingEntries[..entrySeparatorIndex];
|
||||
remainingEntries = entrySeparatorIndex < 0 ? ReadOnlySpan<char>.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<char> container = entry[..containerCodecSeparatorIndex].Trim();
|
||||
ReadOnlySpan<char> 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;
|
||||
|
||||
+25
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the playback manifest of a track.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library the track belongs to, taken from the route.</param>
|
||||
/// <param name="ArtistId">The unique identifier of the artist the album of the track belongs to, taken from the route.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track whose playback manifest is retrieved, taken from the route.</param>
|
||||
/// <param name="Capabilities">The container and codec pairs the player advertises it can demux and decode directly, taken from the request, or <see langword="null"/> when it advertises none.</param>
|
||||
/// <param name="StreamPath">The path of the track stream, relative to the API, taken from the endpoint so that it always matches the stream route.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}")]
|
||||
public record GetPlaybackManifestQuery(
|
||||
string? LibraryId,
|
||||
string? ArtistId,
|
||||
string? AlbumId,
|
||||
string? TrackId,
|
||||
string? Capabilities,
|
||||
string StreamPath
|
||||
) : IQuery;
|
||||
+125
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the playback manifest of a track.
|
||||
/// </summary>
|
||||
public class GetPlaybackManifestQueryHandler : IQueryHandler<GetPlaybackManifestQuery, Result<PlaybackManifestResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IPlaybackFormatService _playbackFormatService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<GetPlaybackManifestQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="playbackFormatService">Injected service for deciding how a track's audio is delivered to a player.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetPlaybackManifestQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_playbackFormatService = playbackFormatService;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the playback manifest of a track.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the playback manifest of the track, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaybackManifestResponse>> HandleAsync(GetPlaybackManifestQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<ILibraryOwnershipPolicy>(
|
||||
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<TrackPlaybackManifestDto?> 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<PlaybackCapabilityDto> capabilities = PlaybackCapabilitiesParser.Parse(query.Capabilities);
|
||||
Result<PlaybackDeliveryDecisionDto> 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);
|
||||
}
|
||||
}
|
||||
+60
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetPlaybackManifestQuery"/>.
|
||||
/// </summary>
|
||||
public class GetPlaybackManifestQueryValidator : AbstractValidator<GetPlaybackManifestQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestQueryValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+51
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="TrackId">The Id of the track the manifest describes.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the audio of the track, in seconds.</param>
|
||||
/// <param name="SourceContainer">The container of the audio file of the track, as stored by the probe, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional.</param>
|
||||
/// <param name="SourceCodec">The codec of the audio of the track, as stored by the probe. Optional.</param>
|
||||
/// <param name="SampleRate">The sample rate of the audio of the track, in Hz.</param>
|
||||
/// <param name="Channels">The number of audio channels of the track.</param>
|
||||
/// <param name="BitDepth">The bit depth of the audio of the track. Optional.</param>
|
||||
/// <param name="ReplayGainTrackGain">The ReplayGain track gain of the track, in decibels. Optional.</param>
|
||||
/// <param name="ReplayGainTrackPeak">The ReplayGain track peak of the track. Optional.</param>
|
||||
/// <param name="ReplayGainAlbumGain">The ReplayGain album gain of the track, in decibels. Optional.</param>
|
||||
/// <param name="ReplayGainAlbumPeak">The ReplayGain album peak of the track. Optional.</param>
|
||||
/// <param name="DirectPlay">Whether the player can play the stored audio as it is, without the server changing its container or its codec.</param>
|
||||
/// <param name="DeliveryContainer">The container of the audio the server delivers, when the delivery is not a direct play. <see langword="null"/> for a direct play.</param>
|
||||
/// <param name="DeliveryCodec">The codec of the audio the server delivers, when the delivery is not a direct play. <see langword="null"/> for a direct play.</param>
|
||||
/// <param name="DeliveryShape">The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play. <see langword="null"/> for a direct play.</param>
|
||||
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments. <see langword="null"/> otherwise.</param>
|
||||
/// <param name="Seekable">Whether the delivered audio can be seeked by the player.</param>
|
||||
/// <param name="StreamPath">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.</param>
|
||||
[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
|
||||
);
|
||||
@@ -357,6 +357,43 @@ internal sealed class TrackRepository : ITrackRepository
|
||||
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the stored probe result needed to build the playback manifest of the track identified by <paramref name="trackId"/>, when it belongs to
|
||||
/// the album identified by <paramref name="albumId"/> and to the media library identified by <paramref name="libraryId"/>, and that album belongs
|
||||
/// to the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track must belong to.</param>
|
||||
/// <param name="albumId">The Id of the album the track must belong to.</param>
|
||||
/// <param name="artistId">The Id of the artist that must own the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track whose playback manifest data is retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the <see cref="TrackPlaybackManifestDto"/> of the track, <see langword="null"/> when no track
|
||||
/// matches the provided identifiers, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<TrackPlaybackManifestDto?>> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the track identified by <paramref name="id"/>, together with its owned collections and contributions, by the database cascade.
|
||||
/// </summary>
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for <see cref="PlaybackDeliveryShape"/>.
|
||||
/// </summary>
|
||||
public static class PlaybackDeliveryShapeExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets whether the audio delivered in the provided <paramref name="shape"/> can be seeked by a player.
|
||||
/// </summary>
|
||||
/// <param name="shape">The shape the delivered audio is addressed and seeked by.</param>
|
||||
/// <returns>
|
||||
/// <see langword="true"/> when the shape can be seeked, otherwise <see langword="false"/>. 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 <see langword="false"/>.
|
||||
/// </returns>
|
||||
public static bool IsSeekable(this PlaybackDeliveryShape shape)
|
||||
{
|
||||
return shape is PlaybackDeliveryShape.ByteRangeSeekable or PlaybackDeliveryShape.TimeAddressedSegments;
|
||||
}
|
||||
}
|
||||
+1
@@ -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";
|
||||
}
|
||||
}
|
||||
+69
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest</c> route.
|
||||
/// </summary>
|
||||
public class GetPlaybackManifestEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetPlaybackManifestQuery, Result<PlaybackManifestResponse>> _getPlaybackManifestQueryHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="getPlaybackManifestQueryHandler">Injected service for handling get playback manifest queries.</param>
|
||||
public GetPlaybackManifestEndpoint(IQueryHandler<GetPlaybackManifestQuery, Result<PlaybackManifestResponse>> getPlaybackManifestQueryHandler)
|
||||
{
|
||||
_getPlaybackManifestQueryHandler = getPlaybackManifestQueryHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(Http.GET);
|
||||
Routes(ApiRoutes.Tracks.GET_PLAYBACK_MANIFEST);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playback manifest of the track identified by the route.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> 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<PlaybackManifestResponse> result = await _getPlaybackManifestQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+161
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetPlaybackManifestEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackManifestEndpointSummary : Summary<GetPlaybackManifestEndpoint, EmptyRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
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<PlaybackManifestResponse>(r => r.TrackId, "The Id of the track the manifest describes.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DurationInSeconds, "The duration of the audio of the track, in seconds.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.SourceContainer, "The container of the stored audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.SourceCodec, "The codec of the stored audio of the track.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.SampleRate, "The sample rate of the audio of the track, in Hz.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.Channels, "The number of audio channels of the track.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.BitDepth, "The bit depth of the audio of the track, if applicable.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainTrackGain, "The ReplayGain track gain of the track, in decibels, if applicable.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainTrackPeak, "The ReplayGain track peak of the track, if applicable.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainAlbumGain, "The ReplayGain album gain of the track, in decibels, if applicable.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainAlbumPeak, "The ReplayGain album peak of the track, if applicable.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryContainer, "The container of the audio the server delivers, when the delivery is not a direct play.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryCodec, "The codec of the audio the server delivers, when the delivery is not a direct play.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryShape, "The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.SegmentDurationSeconds, "The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.Seekable, "Whether the delivered audio can be seeked by the player.");
|
||||
ResponseParam<PlaybackManifestResponse>(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<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"LibraryIdCannotBeEmpty",
|
||||
"ArtistIdCannotBeEmpty",
|
||||
"AlbumIdCannotBeEmpty",
|
||||
"TrackIdCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user