Merge cms-track-replace-gating into dev
Replace track audio in CMS edit form + gate last-track delete.
This commit is contained in:
@@ -499,6 +499,86 @@ public class TrackController : ControllerBase
|
||||
return StatusCode(500, error);
|
||||
}
|
||||
|
||||
// POST api/track/{id}/replace-audio ([ApiKeyAuthorize])
|
||||
// Swap an existing track's audio bytes from a raw upload, preserving the track's id, EntryKey,
|
||||
// release membership, position, and metadata. UnifiedTrackService.ReplaceAudioAsync owns the
|
||||
// vault swap + waveform regen; nothing in SQL is written. Mirrors the upload endpoint's temp-file
|
||||
// streaming and 1 GB ceiling (a WAV replace is a large-body upload like the original). The
|
||||
// literal "{id:long}/replace-audio" segment is declared in the literal-route block so it never
|
||||
// resolves to the parameterized "{trackId}" GET.
|
||||
[ApiKeyAuthorize]
|
||||
[HttpPost("{id:long}/replace-audio")]
|
||||
[RequestSizeLimit(1_073_741_824)]
|
||||
[RequestFormLimits(MultipartBodyLengthLimit = 1_073_741_824)]
|
||||
public async Task<ActionResult> ReplaceAudio(
|
||||
long id,
|
||||
[FromForm] IFormFile? audioFile,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("ReplaceAudio called: id={Id}, size={Size}", id, audioFile?.Length);
|
||||
|
||||
if (audioFile is null || audioFile.Length == 0)
|
||||
{
|
||||
return BadRequest("Audio file is required");
|
||||
}
|
||||
|
||||
var uploadExtension = Path.GetExtension(audioFile.FileName).ToLowerInvariant();
|
||||
if (uploadExtension is not (".wav" or ".mp3" or ".flac"))
|
||||
{
|
||||
return BadRequest("Uploaded file must have a .wav, .mp3, or .flac extension");
|
||||
}
|
||||
|
||||
// The processor router selects by extension and reads from disk, so the temp file must carry
|
||||
// the upload's real extension. Mirrors UploadTrack — Path.GetTempFileName() yields .tmp.
|
||||
var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + uploadExtension);
|
||||
|
||||
try
|
||||
{
|
||||
await using (var tempStream = new FileStream(
|
||||
tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None,
|
||||
bufferSize: 81920, useAsync: true))
|
||||
await using (var uploadStream = audioFile.OpenReadStream())
|
||||
{
|
||||
await uploadStream.CopyToAsync(tempStream, cancellationToken);
|
||||
}
|
||||
|
||||
var result = await _unifiedService.ReplaceAudioAsync(id, tempPath, cancellationToken);
|
||||
if (result.Success)
|
||||
{
|
||||
_logger.LogInformation("ReplaceAudio succeeded: id={Id}", id);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
var error = result.Messages.FirstOrDefault()?.Message ?? "Failed to replace audio";
|
||||
if (string.Equals(error, UnifiedTrackService.TrackNotFoundMessage, StringComparison.Ordinal))
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
_logger.LogError("ReplaceAudio failed for id {Id}: {Error}", id, error);
|
||||
return StatusCode(500, error);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "ReplaceAudio failed for id {Id}", id);
|
||||
return StatusCode(500, "Internal server error");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
if (System.IO.File.Exists(tempPath))
|
||||
{
|
||||
System.IO.File.Delete(tempPath);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "ReplaceAudio: failed to delete temp file {TempPath}", tempPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE api/track/release/{id} ([ApiKeyAuthorize])
|
||||
// Soft-delete a release row directly. Used by the albums browser to remove an orphaned release
|
||||
// (one with no live tracks). "release" is a literal segment, declared here in the literal-route
|
||||
|
||||
@@ -166,6 +166,55 @@ public class UnifiedTrackService
|
||||
return saveResult;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replace an existing track's audio in place: look up the SQL row, swap only the vault bytes
|
||||
/// keyed by its EntryKey, then regenerate both waveform datums from the new audio. Track id,
|
||||
/// EntryKey, release membership, track number, and all metadata are preserved — nothing in SQL
|
||||
/// is written. The waveform regen is best-effort (a missing datum renders as a flat seekbar /
|
||||
/// blank visualizer downstream), so a datum failure is logged and swallowed rather than failing
|
||||
/// the replace. No release-cardinality cascade applies: the track count is unchanged, so the
|
||||
/// single-track-Mix case stays intact.
|
||||
/// </summary>
|
||||
public async Task<Result> ReplaceAudioAsync(long trackId, string tempFilePath, CancellationToken ct)
|
||||
{
|
||||
var lookup = await _sqlTrackService.GetById(trackId);
|
||||
if (!lookup.Success)
|
||||
{
|
||||
var error = lookup.Messages.FirstOrDefault()?.Message ?? "unknown error";
|
||||
_logger.LogError("ReplaceAudioAsync: GetById failed for track {TrackId}: {Error}", trackId, error);
|
||||
return Result.CreateFailResult("Failed to load track.");
|
||||
}
|
||||
|
||||
if (lookup.Value is null)
|
||||
{
|
||||
return Result.CreateFailResult(TrackNotFoundMessage);
|
||||
}
|
||||
|
||||
var entryKey = lookup.Value.EntryKey;
|
||||
|
||||
var newAudio = await _contentTrackContentService.ReplaceTrackAudioAsync(entryKey, tempFilePath);
|
||||
if (newAudio is null)
|
||||
{
|
||||
_logger.LogWarning("ReplaceAudioAsync: content swap returned null for track {TrackId} ({EntryKey})", trackId, entryKey);
|
||||
return Result.CreateFailResult("Failed to process and store the replacement audio.");
|
||||
}
|
||||
|
||||
// The old waveform no longer matches the new bytes. Regenerate both datums in place; keyed
|
||||
// by the same EntryKey, the re-run overwrites the stale data (proven re-runnable). The
|
||||
// freshly stored buffer is the authoritative source — no re-read of the vault needed.
|
||||
try
|
||||
{
|
||||
await _waveformProfileService.ComputeAndStoreAsync(newAudio.Buffer, entryKey);
|
||||
await _waveformProfileService.ComputeAndStoreHighResAsync(newAudio.Buffer, entryKey, newAudio.Duration);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogError(ex, "ReplaceAudioAsync: waveform regen failed for {EntryKey}; replace unaffected.", entryKey);
|
||||
}
|
||||
|
||||
return Result.CreatePassResult();
|
||||
}
|
||||
|
||||
// Compute and store both waveform datums for a freshly uploaded track: the fixed 512-bucket profile
|
||||
// the player-bar seeker consumes, and the duration-derived high-res datum the lava visualizer
|
||||
// consumes (phase-12 §5 — every track now carries one, computed at upload). Both source the same
|
||||
|
||||
@@ -103,6 +103,84 @@ public class TrackContentService
|
||||
string? originalFileName = null) =>
|
||||
AddTrackAsync(wavFilePath, trackName, artist, album, genre, releaseDate, originalFileName);
|
||||
|
||||
/// <summary>
|
||||
/// Swaps the audio bytes for an existing track in place: processes a new audio file and
|
||||
/// re-registers it under the SAME <paramref name="entryKey"/> in the tracks vault. The track's
|
||||
/// vault key — and therefore its SQL link, release membership, position, and metadata — is
|
||||
/// untouched; only the binary changes. The new audio is written first; only on confirmed success
|
||||
/// is a stale old backing file cleaned up. A cross-format replacement (e.g. .wav → .flac) leaves
|
||||
/// the old file on disk under its former filename once the index is updated; the post-success
|
||||
/// cleanup removes it. For a same-extension overwrite the register alone suffices — the file is
|
||||
/// written in place. If the register fails the original audio is left intact and null is returned,
|
||||
/// so the track remains playable. Returns the freshly stored <see cref="AudioBinary"/> on success
|
||||
/// (so the caller can regenerate waveform data from the same bytes) — matching the FileDatabase
|
||||
/// swallow-and-return-null contract.
|
||||
/// </summary>
|
||||
public async Task<AudioBinary?> ReplaceTrackAudioAsync(string entryKey, string audioFilePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Capture the old extension before touching the vault. After register the index
|
||||
// will point to the new extension, so we need the old value now to detect a
|
||||
// cross-format swap and clean up the stale file post-success.
|
||||
var existing = await _fileDatabase.LoadResourceAsync<AudioBinary>(VaultConstants.Tracks, entryKey);
|
||||
var oldExtension = existing?.Extension;
|
||||
|
||||
var audioBinary = await _audioProcessorRouter.ProcessAudioFileAsync(audioFilePath);
|
||||
if (audioBinary == null)
|
||||
{
|
||||
Console.WriteLine($"TrackContentService.ReplaceTrackAudioAsync: processing returned null for {entryKey}");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!_fileDatabase.HasVault(VaultConstants.Tracks))
|
||||
{
|
||||
await _fileDatabase.CreateVaultAsync(VaultConstants.Tracks, MediaVaultType.Audio);
|
||||
}
|
||||
|
||||
// Register the new audio. This upserts the index entry (new extension recorded) and
|
||||
// writes the new file to disk. If this fails the original entry and file are untouched.
|
||||
var success = await _fileDatabase.RegisterResourceAsync(VaultConstants.Tracks, entryKey, audioBinary);
|
||||
if (!success)
|
||||
{
|
||||
Console.WriteLine($"TrackContentService.ReplaceTrackAudioAsync: vault write failed for {entryKey}; original audio preserved");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Post-success stale-file cleanup for cross-format swaps. The register wrote the new
|
||||
// file (e.g. .flac) and updated the index to the new extension, but the old backing
|
||||
// file (e.g. .wav) is now unreferenced on disk. Delete it directly by constructing the
|
||||
// old path — RemoveResourceAsync would now resolve to the new extension and delete the
|
||||
// wrong file. Non-fatal: an orphaned old file is a disk-hygiene concern, not a
|
||||
// playback issue (the index no longer references it).
|
||||
if (oldExtension != null && oldExtension != audioBinary.Extension)
|
||||
{
|
||||
var vault = _fileDatabase.GetVault(VaultConstants.Tracks);
|
||||
if (vault != null)
|
||||
{
|
||||
var sanitizedKey = System.Text.RegularExpressions.Regex.Replace(entryKey, @"[^a-zA-Z0-9]", "-");
|
||||
var staleFilePath = Path.Combine(vault.RootPath, $"{sanitizedKey}{oldExtension}");
|
||||
try
|
||||
{
|
||||
if (File.Exists(staleFilePath))
|
||||
File.Delete(staleFilePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"TrackContentService.ReplaceTrackAudioAsync: stale backing-file removal failed for {entryKey} ({staleFilePath}): {ex.Message} — new audio is live; orphaned file may remain on disk");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return audioBinary;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
Console.WriteLine($"TrackContentService.ReplaceTrackAudioAsync failed: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves audio binary from FileDatabase
|
||||
/// </summary>
|
||||
|
||||
@@ -59,14 +59,19 @@
|
||||
single-track medium, mirroring BatchUpload's same-named collapse. Cut keeps the full list. *@
|
||||
<MudGrid>
|
||||
<MudItem xs="12" md="5">
|
||||
@* ExistingTrackCount counts edit-session persisted rows (Id.HasValue), not authoritative
|
||||
live release count — acceptable because this gate only hides a UI control; the
|
||||
TrySoftDeleteEmptyReleaseAsync backstop remains the authoritative guard. *@
|
||||
<BatchTrackList Tracks="_tracks"
|
||||
@bind-SelectedIndex="_selectedIndex"
|
||||
Disabled="_saving"
|
||||
AllowNewTracks="@(_medium == ReleaseMedium.Cut)"
|
||||
ExistingTrackCount="@_tracks.Count(t => t.Id.HasValue)"
|
||||
OnWavFilesSelected="HandleWavFilesSelected"
|
||||
OnMoveUp="MoveUp"
|
||||
OnMoveDown="MoveDown"
|
||||
OnRemove="RemoveRow" />
|
||||
OnRemove="RemoveRow"
|
||||
OnReplaceFileSelected="HandleReplaceFileSelected" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" md="7">
|
||||
@@ -322,6 +327,85 @@
|
||||
if (_selectedIndex >= _tracks.Count) _selectedIndex = _tracks.Count - 1;
|
||||
}
|
||||
|
||||
private async Task HandleReplaceFileSelected((int Index, IBrowserFile File) picked)
|
||||
{
|
||||
var (index, file) = picked;
|
||||
if (index < 0 || index >= _tracks.Count) return;
|
||||
|
||||
var row = _tracks[index];
|
||||
if (!row.Id.HasValue)
|
||||
{
|
||||
// Defensive: replace is only offered on persisted rows. A new row would have no track to
|
||||
// swap against — it takes the upload path on save instead.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!file.Name.EndsWith(".wav", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Snackbar.Add($"'{file.Name}' is not a .wav file.", Severity.Warning);
|
||||
return;
|
||||
}
|
||||
|
||||
var confirmed = await DialogService.ShowMessageBox(
|
||||
"Replace audio",
|
||||
$"Replace the audio for '{row.TrackName}' with '{file.Name}'? " +
|
||||
"Metadata stays the same; the waveform is regenerated for the new audio.",
|
||||
yesText: "Replace", cancelText: "Cancel");
|
||||
if (confirmed != true) return;
|
||||
|
||||
row.Status = BatchRowStatus.Uploading;
|
||||
row.UploadedBytes = 0;
|
||||
row.TotalBytes = file.Size;
|
||||
row.ErrorMessage = null;
|
||||
StateHasChanged();
|
||||
|
||||
try
|
||||
{
|
||||
await using var wavStream = file.OpenReadStream(MaxUploadBytes);
|
||||
|
||||
var lastPercent = -1;
|
||||
var progress = new Progress<long>(written =>
|
||||
{
|
||||
row.UploadedBytes = written;
|
||||
if (row.UploadPercent != lastPercent)
|
||||
{
|
||||
lastPercent = row.UploadPercent;
|
||||
StateHasChanged();
|
||||
}
|
||||
});
|
||||
|
||||
var result = await CmsTrackService.ReplaceTrackAudioAsync(
|
||||
row.Id.Value, wavStream, file.Size, file.Name, file.ContentType, progress);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
var error = result.Messages.FirstOrDefault()?.Message ?? "Unknown error";
|
||||
row.Status = BatchRowStatus.Failed;
|
||||
row.ErrorMessage = error;
|
||||
Snackbar.Add($"Replace failed: {error}", Severity.Error);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Reset to Queued (not Done): a Done row is skipped by SaveAsync, but the admin may
|
||||
// still want to save pending metadata edits. The audio swap is already persisted.
|
||||
row.Status = BatchRowStatus.Queued;
|
||||
row.OriginalFileName = file.Name;
|
||||
Snackbar.Add($"Replaced audio for '{row.TrackName}'.", Severity.Success);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Replace audio failed for track id {Id}", row.Id);
|
||||
row.Status = BatchRowStatus.Failed;
|
||||
row.ErrorMessage = "Replace failed — please try again.";
|
||||
Snackbar.Add("Replace failed — please try again.", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveCover()
|
||||
{
|
||||
// Defer the actual clear to save: pass "" to UpdateAsync's tri-state imagePath. Nulling
|
||||
|
||||
@@ -21,7 +21,7 @@ else
|
||||
{
|
||||
<MudField Label="Original File" Variant="Variant.Outlined" InnerPadding="false">
|
||||
<MudText Typo="Typo.body2">@(string.IsNullOrEmpty(SelectedTrack.OriginalFileName) ? "—" : SelectedTrack.OriginalFileName)</MudText>
|
||||
<MudText Typo="Typo.caption" Color="Color.Default">Existing track — audio is not editable.</MudText>
|
||||
<MudText Typo="Typo.caption" Color="Color.Default">Use the Replace audio action in the list to swap this track's audio.</MudText>
|
||||
</MudField>
|
||||
}
|
||||
else
|
||||
|
||||
@@ -34,12 +34,37 @@
|
||||
Disabled="@(index == Tracks.Count - 1 || Disabled)"
|
||||
OnClick="@(() => OnMoveDown.InvokeAsync(index))"
|
||||
aria-label="Move track down" />
|
||||
@* Replace audio: existing (persisted) rows only. New rows still pick their WAV
|
||||
via the file input above, so a replace control there would be redundant. A
|
||||
native <label for> drives a per-row hidden InputFile — clicking the icon
|
||||
opens that row's picker with zero JS (no eval, no programmatic .click()). *@
|
||||
@if (row.Id.HasValue)
|
||||
{
|
||||
<label for="@ReplaceInputId(index)" @onclick:stopPropagation="true"
|
||||
style="display: inline-flex; @(Disabled ? "pointer-events: none; opacity: 0.5;" : "cursor: pointer;")">
|
||||
<MudIcon Icon="@Icons.Material.Filled.SwapHoriz"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Small"
|
||||
aria-label="Replace audio" />
|
||||
</label>
|
||||
<InputFile id="@ReplaceInputId(index)"
|
||||
OnChange="@(e => OnReplaceFileSelected.InvokeAsync((index, e.File)))"
|
||||
accept=".wav,audio/wav,audio/x-wav"
|
||||
disabled="@Disabled"
|
||||
style="display: none;" />
|
||||
}
|
||||
@* Remove: hidden for the sole remaining persisted track so a release can never
|
||||
be track-deleted down to zero (that path soft-deletes the whole release). New
|
||||
rows are always removable — dropping one only discards a pending upload. *@
|
||||
@if (!(row.Id.HasValue && ExistingTrackCount <= 1))
|
||||
{
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete"
|
||||
Color="Color.Error"
|
||||
Size="Size.Small"
|
||||
Disabled="@Disabled"
|
||||
OnClick="@(() => OnRemove.InvokeAsync(index))"
|
||||
aria-label="Remove track" />
|
||||
}
|
||||
</MudStack>
|
||||
@if (row.Status == BatchRowStatus.Uploading)
|
||||
{
|
||||
@@ -60,11 +85,28 @@
|
||||
[Parameter] public EventCallback<int> SelectedIndexChanged { get; set; }
|
||||
[Parameter] public bool Disabled { get; set; }
|
||||
[Parameter] public bool AllowNewTracks { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Count of existing (persisted, Id-bearing) tracks in the list. When this is 1, the remove
|
||||
/// control on the sole persisted row is suppressed so a release cannot be track-deleted to zero
|
||||
/// (replace + release-level delete remain). New unsaved rows are excluded from this count.
|
||||
/// </summary>
|
||||
[Parameter] public int ExistingTrackCount { get; set; }
|
||||
|
||||
[Parameter] public EventCallback<IReadOnlyList<IBrowserFile>> OnWavFilesSelected { get; set; }
|
||||
[Parameter] public EventCallback<int> OnMoveUp { get; set; }
|
||||
[Parameter] public EventCallback<int> OnMoveDown { get; set; }
|
||||
[Parameter] public EventCallback<int> OnRemove { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Raised when the admin picks a replacement WAV for an existing row, carrying the list index and
|
||||
/// the chosen file. Only fired for persisted (Id-bearing) rows.
|
||||
/// </summary>
|
||||
[Parameter] public EventCallback<(int Index, IBrowserFile File)> OnReplaceFileSelected { get; set; }
|
||||
|
||||
// Stable per-row DOM id linking the swap-icon <label> to its hidden InputFile.
|
||||
private static string ReplaceInputId(int index) => $"replace-audio-input-{index}";
|
||||
|
||||
private const int MaxFilesPerPick = 50;
|
||||
|
||||
private Task SelectRow(int index) => SelectedIndexChanged.InvokeAsync(index);
|
||||
|
||||
@@ -71,54 +71,11 @@ public class CmsTrackService : ICmsTrackService
|
||||
IProgress<long>? progress = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
// Two-phase cancellation for the upload send:
|
||||
//
|
||||
// BODY-STREAMING phase (while bytes are on the wire):
|
||||
// idleCts fires if no progress tick arrives within the idle window. Each
|
||||
// ProgressStreamContent chunk resets CancelAfter(idle), so a slow-but-moving
|
||||
// upload never trips it; a genuinely stalled socket does.
|
||||
//
|
||||
// RESPONSE-WAIT phase (after the last byte, while the server persists):
|
||||
// The idle heartbeat goes silent once the body is fully sent. responseCts is
|
||||
// armed at that moment with a larger budget so a fully-uploaded file is never
|
||||
// killed mid-persist. idleCts is simultaneously disarmed (CancelAfter(Infinite))
|
||||
// so it cannot misfire during the response-wait.
|
||||
//
|
||||
// sendCts links both so either deadline — plus the caller's ct — cancels the send.
|
||||
using var idleCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
idleCts.CancelAfter(_uploadIdleTimeout);
|
||||
// Build the WAV part once; the two-phase send helper owns the cancellation plumbing.
|
||||
using var phase = new UploadPhase(this, ct);
|
||||
var wavContent = phase.WrapContent(wavStream, contentLength, contentType, progress);
|
||||
|
||||
// responseCts starts disarmed; the body-complete callback below arms it.
|
||||
using var responseCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
|
||||
// Umbrella token passed to SendAsync — either phase token (or the caller) can cancel.
|
||||
using var sendCts = CancellationTokenSource.CreateLinkedTokenSource(idleCts.Token, responseCts.Token);
|
||||
|
||||
// Rebuild the multipart container so the boundary is owned by HttpClient and the
|
||||
// caller-supplied stream (already buffered by the SignalR upload) is the source.
|
||||
using var multipart = new MultipartFormDataContent();
|
||||
var wavContent = new ProgressStreamContent(
|
||||
wavStream,
|
||||
contentLength,
|
||||
written =>
|
||||
{
|
||||
// One mechanism, three consumers: advance the UI meter, reset the idle heartbeat,
|
||||
// and on body-complete transition to the response-wait budget.
|
||||
progress?.Report(written);
|
||||
if (written < contentLength)
|
||||
{
|
||||
// Body still in flight — keep the idle heartbeat alive.
|
||||
idleCts.CancelAfter(_uploadIdleTimeout);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Last byte on the wire. Disarm the idle timer and start the response budget.
|
||||
idleCts.CancelAfter(Timeout.InfiniteTimeSpan);
|
||||
responseCts.CancelAfter(_uploadResponseTimeout);
|
||||
}
|
||||
});
|
||||
wavContent.Headers.ContentType = new MediaTypeHeaderValue(
|
||||
string.IsNullOrWhiteSpace(contentType) ? "audio/wav" : contentType);
|
||||
multipart.Add(wavContent, "audioFile", fileName);
|
||||
multipart.Add(new StringContent(trackName), "trackName");
|
||||
multipart.Add(new StringContent(artist), "artist");
|
||||
@@ -135,36 +92,10 @@ public class CmsTrackService : ICmsTrackService
|
||||
// for an unrecognised value). Authoritative only when this upload creates the release.
|
||||
multipart.Add(new StringContent(medium.ToString()), "medium");
|
||||
|
||||
// Use the dedicated upload client (InfiniteTimeSpan) so the two-phase CTS logic above is the
|
||||
// sole timeout authority. Non-upload operations use the bounded "DeepDrft.Content.Cms" client.
|
||||
var client = _httpClientFactory.CreateClient(UploadClientName);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, UploadPath) { Content = multipart };
|
||||
|
||||
HttpResponseMessage response;
|
||||
try
|
||||
var send = await phase.SendAsync(UploadPath, multipart, $"upload of {trackName}");
|
||||
if (send.Response is not { } response)
|
||||
{
|
||||
response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, sendCts.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
// Either idle window (body-streaming stall) or response-wait budget (server persist too slow).
|
||||
if (idleCts.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning("Upload of {TrackName} stalled — no progress for {IdleSeconds}s; aborting.",
|
||||
trackName, _uploadIdleTimeout.TotalSeconds);
|
||||
return ResultContainer<TrackDto>.CreateFailResult(
|
||||
$"Upload stalled — no data transferred for {_uploadIdleTimeout.TotalSeconds:0}s. Please retry.");
|
||||
}
|
||||
// responseCts fired: body reached the server but persist timed out.
|
||||
_logger.LogWarning("Upload of {TrackName} timed out waiting for server response after {ResponseSeconds}s.",
|
||||
trackName, _uploadResponseTimeout.TotalSeconds);
|
||||
return ResultContainer<TrackDto>.CreateFailResult(
|
||||
$"Upload timed out waiting for the server to respond after {_uploadResponseTimeout.TotalSeconds:0}s. Please retry.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Content API call failed for upload of {TrackName}", trackName);
|
||||
return ResultContainer<TrackDto>.CreateFailResult("Content API is unreachable.");
|
||||
return ResultContainer<TrackDto>.CreateFailResult(send.FailureMessage!);
|
||||
}
|
||||
|
||||
using (response)
|
||||
@@ -208,6 +139,172 @@ public class CmsTrackService : ICmsTrackService
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result> ReplaceTrackAudioAsync(
|
||||
long id,
|
||||
Stream wavStream,
|
||||
long contentLength,
|
||||
string fileName,
|
||||
string contentType,
|
||||
IProgress<long>? progress = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
// Same two-phase send plumbing as UploadTrackAsync — a WAV replace is an equally large body.
|
||||
// The request carries only the audio part; the server resolves the track by route id and
|
||||
// preserves its metadata, so no metadata fields ride along.
|
||||
using var phase = new UploadPhase(this, ct);
|
||||
var wavContent = phase.WrapContent(wavStream, contentLength, contentType, progress);
|
||||
|
||||
using var multipart = new MultipartFormDataContent();
|
||||
multipart.Add(wavContent, "audioFile", fileName);
|
||||
|
||||
var send = await phase.SendAsync($"api/track/{id}/replace-audio", multipart, $"replace of track {id}");
|
||||
if (send.Response is not { } response)
|
||||
{
|
||||
return Result.CreateFailResult(send.FailureMessage!);
|
||||
}
|
||||
|
||||
using (response)
|
||||
{
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
return Result.CreatePassResult();
|
||||
}
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
return Result.CreateFailResult("Track not found.");
|
||||
}
|
||||
|
||||
var body = await response.Content.ReadAsStringAsync(ct);
|
||||
var statusCode = (int)response.StatusCode;
|
||||
if (statusCode >= 500)
|
||||
{
|
||||
_logger.LogError("Content API returned {Status} for replace of track {TrackId}: {Body}", statusCode, id, body);
|
||||
return Result.CreateFailResult("Replace failed on the content server. Please try again.");
|
||||
}
|
||||
|
||||
// 4xx: body is user-friendly validation text from DeepDrftAPI — relay as-is.
|
||||
_logger.LogWarning("Content API rejected replace of track {TrackId}: {Status} {Body}", id, statusCode, body);
|
||||
return Result.CreateFailResult(
|
||||
string.IsNullOrWhiteSpace(body) ? $"Replace rejected ({statusCode})." : body);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Owns the two-phase cancellation for a large-body multipart send (the original upload and the
|
||||
/// audio replace share it identically):
|
||||
///
|
||||
/// BODY-STREAMING phase (while bytes are on the wire): the idle CTS fires if no progress tick
|
||||
/// arrives within the idle window. Each <see cref="ProgressStreamContent"/> chunk resets it, so a
|
||||
/// slow-but-moving body never trips it; a genuinely stalled socket does.
|
||||
///
|
||||
/// RESPONSE-WAIT phase (after the last byte, while the server persists): the idle heartbeat goes
|
||||
/// silent, so a separate, larger budget is armed at body-complete and the idle timer is disarmed,
|
||||
/// guaranteeing a fully-sent body is never killed mid-persist.
|
||||
///
|
||||
/// The send CTS links both phase tokens plus the caller's token. Single-sourcing this here keeps
|
||||
/// the idle/response-wait behaviour identical across every large-body call.
|
||||
/// </summary>
|
||||
private sealed class UploadPhase : IDisposable
|
||||
{
|
||||
private readonly CmsTrackService _owner;
|
||||
private readonly CancellationToken _callerToken;
|
||||
private readonly CancellationTokenSource _idleCts;
|
||||
private readonly CancellationTokenSource _responseCts;
|
||||
private readonly CancellationTokenSource _sendCts;
|
||||
|
||||
public UploadPhase(CmsTrackService owner, CancellationToken callerToken)
|
||||
{
|
||||
_owner = owner;
|
||||
_callerToken = callerToken;
|
||||
_idleCts = CancellationTokenSource.CreateLinkedTokenSource(callerToken);
|
||||
_idleCts.CancelAfter(owner._uploadIdleTimeout);
|
||||
// responseCts starts disarmed; the body-complete callback arms it.
|
||||
_responseCts = CancellationTokenSource.CreateLinkedTokenSource(callerToken);
|
||||
_sendCts = CancellationTokenSource.CreateLinkedTokenSource(_idleCts.Token, _responseCts.Token);
|
||||
}
|
||||
|
||||
public ProgressStreamContent WrapContent(
|
||||
Stream wavStream, long contentLength, string contentType, IProgress<long>? progress)
|
||||
{
|
||||
var content = new ProgressStreamContent(
|
||||
wavStream,
|
||||
contentLength,
|
||||
written =>
|
||||
{
|
||||
// One mechanism, three consumers: advance the UI meter, reset the idle heartbeat,
|
||||
// and on body-complete transition to the response-wait budget.
|
||||
progress?.Report(written);
|
||||
if (written < contentLength)
|
||||
{
|
||||
_idleCts.CancelAfter(_owner._uploadIdleTimeout);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Last byte on the wire. Disarm the idle timer and start the response budget.
|
||||
_idleCts.CancelAfter(Timeout.InfiniteTimeSpan);
|
||||
_responseCts.CancelAfter(_owner._uploadResponseTimeout);
|
||||
}
|
||||
});
|
||||
content.Headers.ContentType = new MediaTypeHeaderValue(
|
||||
string.IsNullOrWhiteSpace(contentType) ? "audio/wav" : contentType);
|
||||
return content;
|
||||
}
|
||||
|
||||
public async Task<LargeBodySendResult> SendAsync(
|
||||
string path, HttpContent content, string operationLabel)
|
||||
{
|
||||
// Dedicated upload client (InfiniteTimeSpan) so the two-phase CTS logic is the sole timeout
|
||||
// authority. Non-upload operations use the bounded "DeepDrft.Content.Cms" client.
|
||||
var client = _owner._httpClientFactory.CreateClient(UploadClientName);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, path) { Content = content };
|
||||
|
||||
try
|
||||
{
|
||||
var response = await client.SendAsync(
|
||||
request, HttpCompletionOption.ResponseHeadersRead, _sendCts.Token);
|
||||
return LargeBodySendResult.Ok(response);
|
||||
}
|
||||
catch (OperationCanceledException) when (!_callerToken.IsCancellationRequested)
|
||||
{
|
||||
if (_idleCts.IsCancellationRequested)
|
||||
{
|
||||
_owner._logger.LogWarning("{Operation} stalled — no progress for {IdleSeconds}s; aborting.",
|
||||
operationLabel, _owner._uploadIdleTimeout.TotalSeconds);
|
||||
return LargeBodySendResult.Fail(
|
||||
$"{operationLabel} stalled — no data transferred for {_owner._uploadIdleTimeout.TotalSeconds:0}s. Please retry.");
|
||||
}
|
||||
_owner._logger.LogWarning("{Operation} timed out waiting for server response after {ResponseSeconds}s.",
|
||||
operationLabel, _owner._uploadResponseTimeout.TotalSeconds);
|
||||
return LargeBodySendResult.Fail(
|
||||
$"{operationLabel} timed out waiting for the server to respond after {_owner._uploadResponseTimeout.TotalSeconds:0}s. Please retry.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_owner._logger.LogError(ex, "Content API call failed for {Operation}", operationLabel);
|
||||
return LargeBodySendResult.Fail("Content API is unreachable.");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_sendCts.Dispose();
|
||||
_responseCts.Dispose();
|
||||
_idleCts.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// Outcome of a two-phase send: either a live response the caller must dispose, or a user-facing
|
||||
// failure message. Exactly one is non-null.
|
||||
private readonly struct LargeBodySendResult
|
||||
{
|
||||
public HttpResponseMessage? Response { get; private init; }
|
||||
public string? FailureMessage { get; private init; }
|
||||
|
||||
public static LargeBodySendResult Ok(HttpResponseMessage response) => new() { Response = response };
|
||||
public static LargeBodySendResult Fail(string message) => new() { FailureMessage = message };
|
||||
}
|
||||
|
||||
public async Task<Result> DeleteTrackAsync(long id, CancellationToken ct = default)
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient(ContentCmsClientName);
|
||||
|
||||
@@ -51,6 +51,24 @@ public interface ICmsTrackService
|
||||
/// </summary>
|
||||
Task<Result> DeleteTrackAsync(long id, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Replace an existing track's audio via <c>POST api/track/{id}/replace-audio</c>. Swaps only the
|
||||
/// vault bytes and regenerates the track's waveform data server-side; the track id, vault key,
|
||||
/// release membership, position, and metadata are preserved. Uses the dedicated upload client and
|
||||
/// the same two-phase (idle / response-wait) cancellation as <see cref="UploadTrackAsync"/>, since
|
||||
/// a WAV replace is a large-body upload. <paramref name="contentLength"/> sets Content-Length and is
|
||||
/// the denominator for <paramref name="progress"/>; each progress tick resets the idle heartbeat.
|
||||
/// Maps a 404 to a "Track not found." failure.
|
||||
/// </summary>
|
||||
Task<Result> ReplaceTrackAudioAsync(
|
||||
long id,
|
||||
Stream wavStream,
|
||||
long contentLength,
|
||||
string fileName,
|
||||
string contentType,
|
||||
IProgress<long>? progress = null,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Soft-delete a release record via DELETE api/track/release/{id}. Use when a release
|
||||
/// has no live tracks and needs to be removed from the albums browser.
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
using System.Text;
|
||||
using DeepDrftContent;
|
||||
using DeepDrftContent.Constants;
|
||||
using DeepDrftContent.FileDatabase.Models;
|
||||
using DeepDrftContent.Processors;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using FileDb = DeepDrftContent.FileDatabase.Services.FileDatabase;
|
||||
|
||||
namespace DeepDrftTests;
|
||||
|
||||
/// <summary>
|
||||
/// Integration tests for the content-side audio-replace seam
|
||||
/// (<see cref="TrackContentService.ReplaceTrackAudioAsync"/>) and the waveform regeneration that the
|
||||
/// API orchestrator runs after it. These exercise the real <see cref="FileDb"/>, the real
|
||||
/// <see cref="AudioProcessorRouter"/>, and the real <see cref="WaveformProfileService"/> over
|
||||
/// temp-directory-isolated vaults — the same pattern as <see cref="WaveformProfileServiceTests"/>.
|
||||
///
|
||||
/// The replace contract under test: the vault key (EntryKey) is preserved, only the bytes change,
|
||||
/// no stale backing file is left behind on a cross-format swap, and the waveform datums are
|
||||
/// re-computed against the new audio. SQL-side preservation (track id, release link, position,
|
||||
/// metadata) is guaranteed structurally — the orchestrator never writes SQL on replace — so it is
|
||||
/// documented here rather than asserted against a database this suite does not stand up.
|
||||
/// </summary>
|
||||
[TestFixture]
|
||||
public class TrackReplaceAudioTests
|
||||
{
|
||||
private string _testDir = string.Empty;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_testDir = Path.Combine(Path.GetTempPath(), "TrackReplaceAudioTests", Guid.NewGuid().ToString());
|
||||
Directory.CreateDirectory(_testDir);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
try { Directory.Delete(_testDir, recursive: true); }
|
||||
catch { /* Best-effort cleanup — ignore failures */ }
|
||||
}
|
||||
|
||||
private static TrackContentService CreateContentService(FileDb fileDatabase) =>
|
||||
new(fileDatabase, new AudioProcessorRouter(
|
||||
new AudioProcessor(), new Mp3AudioProcessor(), new FlacAudioProcessor()));
|
||||
|
||||
private static WaveformProfileService CreateWaveformService(FileDb fileDatabase) =>
|
||||
new(fileDatabase, new AudioProcessor(), new RmsLoudnessAlgorithm(),
|
||||
Options.Create(new WaveformProfileOptions()), NullLogger<WaveformProfileService>.Instance);
|
||||
|
||||
[Test]
|
||||
public async Task ReplaceTrackAudioAsync_SwapsBytes_PreservingEntryKey()
|
||||
{
|
||||
var fileDatabase = await FileDb.FromAsync(_testDir);
|
||||
Assert.That(fileDatabase, Is.Not.Null);
|
||||
var content = CreateContentService(fileDatabase!);
|
||||
|
||||
// Seed a 2-second track, then replace it with a 6-second one. The entry key is the stable
|
||||
// SQL→vault link; replace must reuse it so the track row keeps pointing at live audio.
|
||||
var original = await WriteWavAsync(BuildMinimalPcmWav(2.0), ".wav");
|
||||
var seeded = await content.AddTrackAsync(original, "Original", "Artist");
|
||||
Assert.That(seeded, Is.Not.Null);
|
||||
var entryKey = seeded!.EntryKey;
|
||||
|
||||
var before = await content.GetAudioBinaryAsync(entryKey);
|
||||
Assert.That(before, Is.Not.Null);
|
||||
var originalDuration = before!.Duration;
|
||||
|
||||
var replacement = await WriteWavAsync(BuildMinimalPcmWav(6.0), ".wav");
|
||||
var newAudio = await content.ReplaceTrackAudioAsync(entryKey, replacement);
|
||||
|
||||
Assert.That(newAudio, Is.Not.Null, "Replace should return the freshly stored audio");
|
||||
|
||||
var after = await content.GetAudioBinaryAsync(entryKey);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(after, Is.Not.Null, "The track must remain retrievable under the same EntryKey");
|
||||
Assert.That(after!.Duration, Is.GreaterThan(originalDuration),
|
||||
"The retrieved audio must reflect the longer replacement, not the original");
|
||||
Assert.That(newAudio!.Duration, Is.EqualTo(after.Duration),
|
||||
"The returned binary must match what is stored under the key");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReplaceTrackAudioAsync_CrossFormat_RemovesStaleBackingFile()
|
||||
{
|
||||
var fileDatabase = await FileDb.FromAsync(_testDir);
|
||||
var content = CreateContentService(fileDatabase!);
|
||||
|
||||
// A .wav original replaced by a .flac: the backing filename is keyed by extension, so a
|
||||
// register-only swap would strand the old .wav. The replace writes the new entry first, then
|
||||
// cleans up the stale old backing file (detected by comparing old vs. new extension).
|
||||
var original = await WriteWavAsync(BuildMinimalPcmWav(2.0), ".wav");
|
||||
var seeded = await content.AddTrackAsync(original, "Original", "Artist");
|
||||
var entryKey = seeded!.EntryKey;
|
||||
|
||||
var vaultDir = Path.Combine(_testDir, VaultConstants.Tracks);
|
||||
var wavFilesBefore = Directory.GetFiles(vaultDir, "*.wav");
|
||||
Assert.That(wavFilesBefore, Is.Not.Empty, "Sanity: the original .wav backing file exists");
|
||||
|
||||
var replacement = await WriteFlacAsync();
|
||||
var newAudio = await content.ReplaceTrackAudioAsync(entryKey, replacement);
|
||||
|
||||
Assert.That(newAudio, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(Directory.GetFiles(vaultDir, "*.wav"), Is.Empty,
|
||||
"The stale .wav backing file must be removed on a cross-format replace");
|
||||
Assert.That(Directory.GetFiles(vaultDir, "*.flac"), Is.Not.Empty,
|
||||
"The new .flac backing file must be present");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReplaceThenRegenerate_RewritesWaveformDatumsForNewAudio()
|
||||
{
|
||||
var fileDatabase = await FileDb.FromAsync(_testDir);
|
||||
var content = CreateContentService(fileDatabase!);
|
||||
var waveforms = CreateWaveformService(fileDatabase!);
|
||||
|
||||
// Seed a short track and its waveform datums, then replace with a longer track and regenerate
|
||||
// (the exact sequence UnifiedTrackService.ReplaceAudioAsync runs). The high-res datum is
|
||||
// duration-derived, so a longer replacement yields a denser datum — proving the regen ran
|
||||
// against the new audio rather than leaving the stale datum in place.
|
||||
var original = await WriteWavAsync(BuildMinimalPcmWav(3.0), ".wav");
|
||||
var seeded = await content.AddTrackAsync(original, "Original", "Artist");
|
||||
var entryKey = seeded!.EntryKey;
|
||||
|
||||
var seedAudio = await content.GetAudioBinaryAsync(entryKey);
|
||||
await waveforms.ComputeAndStoreAsync(seedAudio!.Buffer, entryKey);
|
||||
await waveforms.ComputeAndStoreHighResAsync(seedAudio.Buffer, entryKey, seedAudio.Duration);
|
||||
var staleHighRes = await waveforms.GetProfileAsync(entryKey, VaultConstants.TrackWaveforms);
|
||||
Assert.That(staleHighRes, Is.Not.Null);
|
||||
|
||||
var replacement = await WriteWavAsync(BuildMinimalPcmWav(20.0), ".wav");
|
||||
var newAudio = await content.ReplaceTrackAudioAsync(entryKey, replacement);
|
||||
Assert.That(newAudio, Is.Not.Null);
|
||||
|
||||
// Regen step (mirrors the orchestrator).
|
||||
Assert.That(await waveforms.ComputeAndStoreAsync(newAudio!.Buffer, entryKey), Is.True);
|
||||
Assert.That(await waveforms.ComputeAndStoreHighResAsync(newAudio.Buffer, entryKey, newAudio.Duration), Is.True);
|
||||
|
||||
var freshHighRes = await waveforms.GetProfileAsync(entryKey, VaultConstants.TrackWaveforms);
|
||||
var freshProfile = await waveforms.GetProfileAsync(entryKey);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(freshHighRes, Is.Not.Null);
|
||||
Assert.That(freshProfile, Is.Not.Null, "The 512-bucket profile must also be present after regen");
|
||||
Assert.That(freshHighRes!.Length, Is.EqualTo(WaveformResolution.BucketCountForDuration(20.0)),
|
||||
"The high-res datum must track the new (longer) duration");
|
||||
Assert.That(freshHighRes.Length, Is.Not.EqualTo(staleHighRes!.Length),
|
||||
"The regenerated datum must differ from the stale one keyed to the shorter original");
|
||||
});
|
||||
}
|
||||
|
||||
// --- WAV / FLAC test fixtures ---
|
||||
|
||||
private async Task<string> WriteWavAsync(byte[] bytes, string extension)
|
||||
{
|
||||
var path = Path.Combine(_testDir, Guid.NewGuid().ToString("N") + extension);
|
||||
await File.WriteAllBytesAsync(path, bytes);
|
||||
return path;
|
||||
}
|
||||
|
||||
// Minimal valid FLAC: 'fLaC' magic + a STREAMINFO metadata block. The processor reads STREAMINFO
|
||||
// for sample rate / channels / bits / total samples; it does not decode frames, so an empty audio
|
||||
// payload is sufficient to produce a non-null AudioBinary with a .flac extension.
|
||||
private async Task<string> WriteFlacAsync()
|
||||
{
|
||||
var path = Path.Combine(_testDir, Guid.NewGuid().ToString("N") + ".flac");
|
||||
await File.WriteAllBytesAsync(path, BuildMinimalFlac());
|
||||
return path;
|
||||
}
|
||||
|
||||
// Builds a standard-PCM mono 16-bit 44.1 kHz WAV of the requested duration with a full-scale
|
||||
// square wave (non-silent so the loudness algorithm yields a real envelope). Same layout as
|
||||
// WaveformProfileServiceTests.BuildMinimalPcmWav.
|
||||
private static byte[] BuildMinimalPcmWav(double durationSeconds)
|
||||
{
|
||||
const int sampleRate = 44100;
|
||||
const ushort channels = 1;
|
||||
const ushort bitsPerSample = 16;
|
||||
const ushort blockAlign = channels * (bitsPerSample / 8);
|
||||
const uint byteRate = sampleRate * blockAlign;
|
||||
|
||||
var frames = (int)(sampleRate * durationSeconds);
|
||||
var data = new byte[frames * blockAlign];
|
||||
for (var i = 0; i < frames; i++)
|
||||
{
|
||||
var sample = (i % 2 == 0) ? short.MaxValue : short.MinValue;
|
||||
data[i * 2] = (byte)(sample & 0xFF);
|
||||
data[i * 2 + 1] = (byte)((sample >> 8) & 0xFF);
|
||||
}
|
||||
|
||||
using var ms = new MemoryStream();
|
||||
using var w = new BinaryWriter(ms, Encoding.ASCII, leaveOpen: true);
|
||||
|
||||
w.Write(Encoding.ASCII.GetBytes("RIFF"));
|
||||
w.Write((uint)(36 + data.Length));
|
||||
w.Write(Encoding.ASCII.GetBytes("WAVE"));
|
||||
|
||||
w.Write(Encoding.ASCII.GetBytes("fmt "));
|
||||
w.Write(16u);
|
||||
w.Write((ushort)1); // PCM
|
||||
w.Write(channels);
|
||||
w.Write((uint)sampleRate);
|
||||
w.Write(byteRate);
|
||||
w.Write(blockAlign);
|
||||
w.Write(bitsPerSample);
|
||||
|
||||
w.Write(Encoding.ASCII.GetBytes("data"));
|
||||
w.Write((uint)data.Length);
|
||||
w.Write(data);
|
||||
|
||||
w.Flush();
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
// Builds the minimal FLAC the processor can parse: 'fLaC' + one STREAMINFO block (type 0, last).
|
||||
// STREAMINFO is 34 bytes; the processor reads the bit-packed 20-bit sample rate, 3-bit channels,
|
||||
// 5-bit bits-per-sample, and 36-bit total-samples fields. Values: 44.1 kHz, mono, 16-bit, some
|
||||
// total samples so duration > 0.
|
||||
private static byte[] BuildMinimalFlac()
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
ms.Write(Encoding.ASCII.GetBytes("fLaC"));
|
||||
|
||||
// Metadata block header: last-block flag (0x80) | block type 0 (STREAMINFO), then 24-bit length = 34.
|
||||
ms.WriteByte(0x80);
|
||||
ms.WriteByte(0x00);
|
||||
ms.WriteByte(0x00);
|
||||
ms.WriteByte(34);
|
||||
|
||||
var streamInfo = new byte[34];
|
||||
// Bytes 0-1: min block size; 2-3: max block size — non-zero placeholders.
|
||||
streamInfo[0] = 0x10; streamInfo[2] = 0x10;
|
||||
// Bytes 10-17 hold the packed sampleRate(20) | channels(3) | bitsPerSample(5) | totalSamples(36).
|
||||
const int sampleRate = 44100;
|
||||
const int channels = 1;
|
||||
const int bitsPerSample = 16;
|
||||
const long totalSamples = 44100L * 3; // 3 seconds
|
||||
|
||||
// sampleRate occupies the top 20 bits of bytes 10-12.
|
||||
streamInfo[10] = (byte)((sampleRate >> 12) & 0xFF);
|
||||
streamInfo[11] = (byte)((sampleRate >> 4) & 0xFF);
|
||||
// Low 4 bits of sampleRate into the top nibble of byte 12; then (channels-1) in 3 bits and the
|
||||
// top bit of (bitsPerSample-1).
|
||||
var bps = bitsPerSample - 1; // 5-bit field stores bitsPerSample-1
|
||||
streamInfo[12] = (byte)(((sampleRate & 0x0F) << 4)
|
||||
| (((channels - 1) & 0x07) << 1)
|
||||
| ((bps >> 4) & 0x01));
|
||||
// Remaining 4 bits of bps into the top nibble of byte 13, then top 4 bits of the 36-bit total.
|
||||
streamInfo[13] = (byte)(((bps & 0x0F) << 4) | (int)((totalSamples >> 32) & 0x0F));
|
||||
streamInfo[14] = (byte)((totalSamples >> 24) & 0xFF);
|
||||
streamInfo[15] = (byte)((totalSamples >> 16) & 0xFF);
|
||||
streamInfo[16] = (byte)((totalSamples >> 8) & 0xFF);
|
||||
streamInfo[17] = (byte)(totalSamples & 0xFF);
|
||||
|
||||
ms.Write(streamInfo);
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user