Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
// Renderer
renderOffline,
renderToAudioBuffer,
resampleAudioBuffer,
// Waveform
initWaveSurfer,
destroyWaveSurfer,
Expand Down Expand Up @@ -1418,12 +1419,24 @@ async function processAudio() {
throw new Error('Cancelled');
}

updateProgress(85, 'Encoding WAV...');
let exportBuffer = result.audioBuffer;
if (exportBuffer.sampleRate !== parsedSampleRate) {
updateProgress(83, `Resampling to ${parsedSampleRate / 1000}kHz...`);
let exportBuffer = result.audioBuffer;
if (exportBuffer.sampleRate !== parsedSampleRate) {
updateProgress(86, `Resampling to ${parsedSampleRate / 1000}kHz...`);
exportBuffer = await resampleAudioBuffer(exportBuffer, parsedSampleRate);
}
Comment thread
entrepeneur4lyf marked this conversation as resolved.
if (processingCancelled) {
throw new Error('Cancelled');
}

updateProgress(88, 'Encoding WAV...');
// Yield so the UI can repaint before encoding begins.
await new Promise(resolve => setTimeout(resolve, 0));

outputData = await encodeWAVAsync(result.audioBuffer, parsedSampleRate, parsedBitDepth, {
onProgress: (p) => updateProgress(Math.round(85 + p * 10), 'Encoding WAV...'),
outputData = await encodeWAVAsync(exportBuffer, parsedSampleRate, parsedBitDepth, {
onProgress: (p) => updateProgress(Math.round(88 + p * 10), 'Encoding WAV...'),
shouldCancel: () => processingCancelled
});
Comment thread
entrepeneur4lyf marked this conversation as resolved.
} catch (workerErr) {
Expand Down
45 changes: 35 additions & 10 deletions web/ui/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,20 @@ import { applyFinalFilters } from '../lib/dsp/final-filters.js';
// WAV Encoding
// ============================================================================

const DITHER_BUFFER_SIZE = 256;
const ditherBuffer = new Float32Array(DITHER_BUFFER_SIZE);
for (let i = 0; i < DITHER_BUFFER_SIZE; i++) {
ditherBuffer[i] = (Math.random() + Math.random()) - 1;
}
let ditherIndex = 0;

function triangularDither() {
// TPDF in integer (LSB) domain: [-1, 1]
const dither = ditherBuffer[ditherIndex];
ditherIndex = (ditherIndex + 1) % DITHER_BUFFER_SIZE;
return dither;
}
Comment thread
entrepeneur4lyf marked this conversation as resolved.

/**
* Encode an AudioBuffer to WAV format (supports 16-bit and 24-bit)
* @param {AudioBuffer} audioBuffer - Source audio buffer
Expand All @@ -18,8 +32,9 @@ import { applyFinalFilters } from '../lib/dsp/final-filters.js';
*/
export function encodeWAV(audioBuffer, targetSampleRate, bitDepth) {
const numChannels = audioBuffer.numberOfChannels;
const safeBitDepth = bitDepth === 24 ? 24 : 16;
const sampleRate = targetSampleRate || audioBuffer.sampleRate;
const bytesPerSample = bitDepth / 8;
const bytesPerSample = safeBitDepth / 8;

const channelData = [];
for (let ch = 0; ch < numChannels; ch++) {
Expand Down Expand Up @@ -47,22 +62,27 @@ export function encodeWAV(audioBuffer, targetSampleRate, bitDepth) {
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * numChannels * bytesPerSample, true);
view.setUint16(32, numChannels * bytesPerSample, true);
view.setUint16(34, bitDepth, true);
view.setUint16(34, safeBitDepth, true);
writeString(36, 'data');
view.setUint32(40, dataSize, true);

let offset = 44;
const maxVal = bitDepth === 16 ? 32767 : 8388607;
const maxVal = safeBitDepth === 16 ? 32767 : 8388607;

for (let i = 0; i < numSamples; i++) {
for (let ch = 0; ch < numChannels; ch++) {
const sample = Math.max(-1, Math.min(1, channelData[ch][i]));
const intSample = Math.round(sample * maxVal);

if (bitDepth === 16) {
view.setInt16(offset, intSample, true);
const scaled = sample * maxVal;
// Dither is only needed for 16-bit export where quantization noise is audible.
const intSample = safeBitDepth === 16
? Math.round(scaled + triangularDither())
: Math.round(scaled);

if (safeBitDepth === 16) {
const clampedSample = Math.max(-32768, Math.min(32767, intSample));
view.setInt16(offset, clampedSample, true);
Comment thread
entrepeneur4lyf marked this conversation as resolved.
offset += 2;
} else if (bitDepth === 24) {
} else if (safeBitDepth === 24) {
// Clamp to prevent overflow in bitwise operations
const clampedSample = Math.max(-8388607, Math.min(8388607, intSample));
view.setUint8(offset, clampedSample & 0xFF);
Expand Down Expand Up @@ -145,10 +165,15 @@ export async function encodeWAVAsync(audioBuffer, targetSampleRate, bitDepth, op
for (let s = i; s < end; s++) {
for (let ch = 0; ch < numChannels; ch++) {
const sample = Math.max(-1, Math.min(1, channelData[ch][s]));
const intSample = Math.round(sample * maxVal);
const scaled = sample * maxVal;
// Dither is only needed for 16-bit export where quantization noise is audible.
const intSample = safeBitDepth === 16
? Math.round(scaled + triangularDither())
: Math.round(scaled);

if (safeBitDepth === 16) {
view.setInt16(offset, intSample, true);
const clampedSample = Math.max(-32768, Math.min(32767, intSample));
view.setInt16(offset, clampedSample, true);
offset += 2;
} else {
const clampedSample = Math.max(-8388607, Math.min(8388607, intSample));
Expand Down
24 changes: 24 additions & 0 deletions web/ui/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,30 @@ function applyDSPChain(buffer, settings, onProgress = null, logPrefix = '[DSP]')
return { buffer: renderedBuffer, measuredLufs };
}

/**
* Resample an AudioBuffer to a target sample rate.
* Uses OfflineAudioContext so output sample data and WAV header stay aligned.
* @param {AudioBuffer} sourceBuffer - Source audio buffer
* @param {number} targetSampleRate - Target sample rate in Hz
* @returns {Promise<AudioBuffer>} Resampled buffer (or original if unchanged)
*/
export async function resampleAudioBuffer(sourceBuffer, targetSampleRate) {
if (!sourceBuffer || !targetSampleRate || sourceBuffer.sampleRate === targetSampleRate) {
return sourceBuffer;
}

const numChannels = sourceBuffer.numberOfChannels;
const numSamples = Math.ceil(sourceBuffer.duration * targetSampleRate);
const offlineCtx = new OfflineAudioContext(numChannels, numSamples, targetSampleRate);
const source = offlineCtx.createBufferSource();

source.buffer = sourceBuffer;
source.connect(offlineCtx.destination);
source.start(0);

return offlineCtx.startRendering();
}

// ============================================================================
// Offline Rendering (Export)
// ============================================================================
Expand Down
Loading