Adds seekable normalized audio track delivery

This commit is contained in:
BinaryAlley committed 2026-10-18 14:55:56 +03:00
1 parent 4e13b23f16
commit 45f9aa3bd5
57 files changed
+3452 -344

No files matched your search

@@ -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.
/// </summary>
/// <param name="TrackId">The Id of the track whose audio is normalized. It binds the produced cache entry to the track the caller authorized.</param>
/// <param name="UserId">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.</param>
/// <param name="SourcePath">The file system path of the stored audio file of the track.</param>
/// <param name="AllowedRoots">
/// 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.
/// </param>
/// <param name="SourceContainer">The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer. Optional.</param>
/// <param name="SourceContainer">The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer.</param>
/// <param name="Mode">The way the audio is delivered, which is a remux or a transcode.</param>
/// <param name="Container">The container of the delivered audio, as chosen by the delivery decision.</param>
/// <param name="Codec">The codec of the delivered audio, as chosen by the delivery decision.</param>
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds.</param>
/// <param name="DurationInSeconds">The duration of the audio of the track, in seconds.</param>
/// <param name="Bitrate">The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec. Optional.</param>
/// <param name="Bitrate">The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec.</param>
/// <param name="SampleRate">The sample rate of the stored audio of the track, in Hz, used to estimate the size of a lossless delivery.</param>
/// <param name="Channels">The number of audio channels of the track, used to estimate the size of a lossless delivery.</param>
/// <param name="BitDepth">The bit depth of the stored audio of the track, if applicable, used to estimate the size of a lossless delivery.</param>
/// <param name="Quality">The quality cap applied to the delivered audio when it has to be re-encoded.</param>
/// <param name="SourceLength">The length the source file had when the delivery was declared, in bytes. The production is rejected when the file no longer matches.</param>
/// <param name="SourceLastModifiedUtc">The last modification time the source file had when the delivery was declared. The production is rejected when the file no longer matches.</param>
[DebuggerDisplay("TrackId: {TrackId} Mode: {Mode} Container: {Container} Codec: {Codec}")]
public sealed record NormalizedTrackRequestDto(
Guid TrackId,
Guid UserId,
string SourcePath,
IReadOnlyList<string> 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
);
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using System.IO;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Data transfer object for a single produced segment of the normalized audio of a track, ready to be written to the response.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="Content">The read stream over the segment, which the caller owns and must release once the response is written.</param>
/// <param name="Length">The length of the segment, in bytes, taken from the index of the normalized audio.</param>
/// <param name="StartSeconds">The exact start of the segment on the track timeline, in seconds, taken from the index of the normalized audio.</param>
/// <param name="Container">The container of the delivered audio, used to resolve the media type of the segment.</param>
/// <param name="SegmentCount">The number of segments the production holds, so the caller can tell the end of the audio from a missing segment.</param>
/// <param name="DurationInSeconds">The duration of the produced normalized audio, in seconds, which can differ from the probed duration.</param>
[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
);
@@ -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;
/// <summary>
/// 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.
/// </summary>
/// <param name="Request">The complete normalization request the delivery declares, including its user, track, decision, quality and source identity.</param>
/// <param name="Shape">The shape the delivered audio is addressed by, which must be time addressed segments for a segment route.</param>
/// <param name="LibraryId">The Id of the library the track belongs to, so the segment route can scope the delivery without querying it again.</param>
/// <param name="AlbumId">The Id of the album the track belongs to, so the segment route can scope the delivery without querying it again.</param>
/// <param name="ArtistId">The Id of the artist that owns the album, so the segment route can scope the delivery without querying it again.</param>
[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
);
@@ -7,56 +7,30 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T
/// <summary>
/// Data transfer object for the stored probe result of a track, containing only the fields a playback manifest is built from.
/// </summary>
/// <param name="Path">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.</param>
/// <param name="Container">The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable.</param>
/// <param name="AudioCodec">The audio codec used by the audio file of the track, if applicable.</param>
/// <param name="DurationInSeconds">The duration of the audio of the track in seconds.</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, if applicable.</param>
/// <param name="Bitrate">The bitrate of the audio of the track, in kbps, if applicable.</param>
/// <param name="ReplayGainTrackGain">The ReplayGain track gain of the track, in decibels, if applicable.</param>
/// <param name="ReplayGainTrackPeak">The ReplayGain track peak of the track, if applicable.</param>
/// <param name="ReplayGainAlbumGain">The ReplayGain album gain of the track, in decibels, if applicable.</param>
/// <param name="ReplayGainAlbumPeak">The ReplayGain album peak of the track, if applicable.</param>
[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; }
}
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
);
@@ -7,55 +7,27 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T
/// <summary>
/// Data transfer object for a track, containing the data needed to stream, or to describe the streaming of, its audio file.
/// </summary>
public sealed record TrackStreamDto
{
/// <summary>
/// Gets the file system path of the track.
/// </summary>
public required string Path { get; init; }
/// <summary>
/// Gets the Id of the media library the track belongs to.
/// </summary>
public required Guid LibraryId { get; init; }
/// <summary>
/// Gets the Id of the album the track belongs to.
/// </summary>
public required Guid AlbumId { get; init; }
/// <summary>
/// Gets the Id of the artist that owns the album the track belongs to.
/// </summary>
public required Guid ArtistId { 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 bitrate of the audio of the track in kbps, if applicable.
/// </summary>
public int? Bitrate { get; init; }
}
/// <param name="Path">The file system path of the track.</param>
/// <param name="LibraryId">The Id of the media library the track belongs to.</param>
/// <param name="AlbumId">The Id of the album the track belongs to.</param>
/// <param name="ArtistId">The Id of the artist that owns the album the track belongs to.</param>
/// <param name="Container">The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable.</param>
/// <param name="AudioCodec">The audio codec used by the audio file of the track, if applicable.</param>
/// <param name="DurationInSeconds">The duration of the audio of the track in seconds.</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, if applicable.</param>
/// <param name="Bitrate">The bitrate of the audio of the track, in kbps, if applicable.</param>
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
);
@@ -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;
/// <summary>
/// Interface for the service that issues and resolves the opaque delivery handles of the playback manifest.
/// </summary>
/// <remarks>
/// 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 <c>N</c> format of a <see cref="Guid"/>, 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.
/// </remarks>
public interface IPlaybackDeliveryHandleService
{
/// <summary>
/// Issues an opaque handle for a delivery, which the playback manifest reports so its segments can be addressed by that handle.
/// </summary>
/// <param name="delivery">The delivery, its source file identity, its quality cap and its user.</param>
/// <returns>The opaque delivery handle.</returns>
string IssueDeliveryId(PlaybackDeliveryHandleDto delivery);
/// <summary>
/// Resolves the delivery a handle addresses, after verifying that it was issued to the provided user and describes the provided track.
/// </summary>
/// <param name="deliveryId">The opaque delivery handle reported by the playback manifest.</param>
/// <param name="userId">The Id of the current user, which the handle must have been issued to.</param>
/// <param name="trackId">The Id of the track named by the route, which the handle must describe.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the delivery, or <see cref="Errors.Playback.PlaybackDeliveryNotFound"/> when the handle is unknown, expired, or belongs to another user or track.
/// </returns>
Result<PlaybackDeliveryHandleDto> GetDelivery(string? deliveryId, Guid userId, Guid trackId);
}
@@ -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 <see cref="Domain.Common.Errors.Errors.Playback.NormalizationUnavailable"/> 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 <see cref="Errors.Playback.NormalizationUnavailable"/> 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.
/// </remarks>
public interface ITrackNormalizationService
{
/// <summary>
/// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet.
/// </summary>
/// <param name="request">The track, the delivery decision, the source file and the quality cap the normalized audio is produced with.</param>
/// <param name="request">The track, the requesting user, the delivery decision, the source file and the quality cap the normalized audio is produced with.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the cached normalized audio of the track, or an error message.
@@ -47,10 +48,9 @@ public interface ITrackNormalizationService
/// </summary>
/// <remarks>
/// 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 <see cref="Domain.Common.Errors.Errors.Playback.NormalizedTrackCacheEntryNotFound"/>. That is the caller's signal to request the
/// reported with <see cref="Errors.Playback.NormalizedTrackCacheEntryNotFound"/>. 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
/// <see cref="Domain.Common.Errors.Errors.Playback.NormalizationUnavailable"/>.
/// its own error. A service that has already been disposed reports <see cref="Errors.Playback.NormalizationUnavailable"/>.
/// </remarks>
/// <param name="cacheId">The opaque identifier of the cached entry that holds the normalized audio.</param>
/// <param name="trackId">The Id of the track the caller authorized and whose segment is opened.</param>
@@ -0,0 +1,31 @@
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Defines the format of the opaque delivery handle of a playback manifest.
/// </summary>
/// <remarks>
/// A handle is a <see cref="Guid"/> rendered with the <c>N</c> 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.
/// </remarks>
public static class PlaybackDeliveryId
{
/// <summary>
/// The number of characters of a delivery handle.
/// </summary>
public const int CHARACTER_COUNT = 32;
/// <summary>
/// Checks whether a value has the format of a delivery handle.
/// </summary>
/// <param name="value">The value to check.</param>
/// <returns><see langword="true"/> when the value is exactly 32 lowercase hexadecimal characters, otherwise <see langword="false"/>.</returns>
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;
}
}
@@ -14,6 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.
/// <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>
/// <param name="SegmentStreamPathTemplate">The path template of the segment route, relative to the API, with a <c>{deliveryId}</c> and a <c>{segmentIndex}</c> placeholder, taken from the endpoint so that it always matches the segment route.</param>
[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;
@@ -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<GetPlaybackManifest
{
private readonly IUnitOfWork _unitOfWork;
private readonly IPlaybackFormatService _playbackFormatService;
private readonly IPlaybackDeliveryHandleService _playbackDeliveryHandleService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IPathService _pathService;
private readonly IValidator<GetPlaybackManifestQuery> _validator;
/// <summary>
@@ -37,15 +44,19 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler<GetPlaybackManifest
/// </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="playbackDeliveryHandleService">Injected service that issues the opaque delivery handles of a normalized manifest.</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="pathService">Injected service for file system path related functionality.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetPlaybackManifestQuery> validator)
public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator<GetPlaybackManifestQuery> validator)
{
_unitOfWork = unitOfWork;
_playbackFormatService = playbackFormatService;
_playbackDeliveryHandleService = playbackDeliveryHandleService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_pathService = pathService;
_validator = validator;
}
@@ -102,6 +113,80 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler<GetPlaybackManifest
// 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();
string? deliveryId = null;
if (!isDirectPlay)
{
// The quality cap and the source file version are captured now, so the segment route never recomputes the delivery from a
// setting the user may change, or from a file that may be replaced, while the track is playing.
PlaybackStreamingQuality quality = PlaybackStreamingQuality.Auto;
Result<UserSettingsEntity?> 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<LibraryEntity?> 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<string> 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<GetPlaybackManifest
isDirectPlay ? null : decision.Shape,
decision.Shape == PlaybackDeliveryShape.TimeAddressedSegments ? decision.SegmentDurationSeconds : null,
isSeekable,
query.StreamPath);
query.StreamPath,
deliveryId,
deliveryId is null ? null : query.SegmentStreamPathTemplate);
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
/// <summary>
/// Query for getting a single segment of the normalized audio of a track, for streaming.
/// </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 normalized audio is streamed, taken from the route.</param>
/// <param name="DeliveryId">The opaque handle of the normalized delivery the segment belongs to, taken from the route.</param>
/// <param name="SegmentIndex">The zero based index of the segment of the normalized audio, taken from the route.</param>
[DebuggerDisplay("TrackId: {TrackId} DeliveryId: {DeliveryId} SegmentIndex: {SegmentIndex}")]
public record GetTrackSegmentQuery(
string? LibraryId,
string? ArtistId,
string? AlbumId,
string? TrackId,
string? DeliveryId,
string? SegmentIndex
) : IQuery;
@@ -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;
/// <summary>
/// Handler for the query to get a single segment of the normalized audio of a track, for streaming.
/// </summary>
public class GetTrackSegmentQueryHandler : IQueryHandler<GetTrackSegmentQuery, Result<NormalizedTrackSegmentDataDto>>
{
private readonly ITrackNormalizationService _trackNormalizationService;
private readonly IPlaybackDeliveryHandleService _playbackDeliveryHandleService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IPathService _pathService;
private readonly IValidator<GetTrackSegmentQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackSegmentQueryHandler"/> class.
/// </summary>
/// <param name="trackNormalizationService">Injected service that produces, caches and serves the normalized audio of a track.</param>
/// <param name="playbackDeliveryHandleService">Injected service that resolves the opaque delivery handle of the playback manifest.</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="pathService">Injected service for file system path related functionality.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetTrackSegmentQueryHandler(ITrackNormalizationService trackNormalizationService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator<GetTrackSegmentQuery> validator)
{
_trackNormalizationService = trackNormalizationService;
_playbackDeliveryHandleService = playbackDeliveryHandleService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_pathService = pathService;
_validator = validator;
}
/// <summary>
/// Handles the query to get a single segment of the normalized audio of a track, for streaming.
/// </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 data of the requested segment, or an error message.
/// </returns>
public async Task<Result<NormalizedTrackSegmentDataDto>> HandleAsync(GetTrackSegmentQuery 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 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<ILibraryOwnershipPolicy>(
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<PlaybackDeliveryHandleDto> 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<NormalizedTrackDto> 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<Stream> 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);
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="GetTrackSegmentQuery"/>.
/// </summary>
public class GetTrackSegmentQueryValidator : AbstractValidator<GetTrackSegmentQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackSegmentQueryValidator"/> class.
/// </summary>
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);
}
}