import { AudioContext } from '../src/javascript/index.js'; import { readFileSync } from 'fs'; import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; const __dirname = dirname(fileURLToPath(import.meta.url)); // Load reference data generated from Chrome const referenceDataPath = join(__dirname, 'reference-data', 'analyser-reference-data.json'); async function testAgainstReference() { console.log('\n=== Testing AnalyserNode Against Chrome Reference Data ===\n'); let referenceData; try { referenceData = JSON.parse(readFileSync(referenceDataPath, 'utf-8')); } catch (error) { console.error('❌ Could not load reference data.'); console.error('Please generate it first using test/generate-reference-data.html'); console.error('Expected file:', referenceDataPath); process.exit(1); } console.log('Reference data metadata:'); console.log(' Generated by:', referenceData.metadata.generatedBy); console.log(' Generated at:', referenceData.metadata.generatedAt); console.log(' Sample rate:', referenceData.metadata.sampleRate); console.log(' Duration:', referenceData.metadata.duration.toFixed(2) + 's'); console.log(' Channels:', referenceData.metadata.numberOfChannels); console.log(''); // Load the same MP3 file that was used to generate reference data const audioFilePath = join(__dirname, 'samples', 'rising_sun.mp3'); console.log('Loading audio file:', audioFilePath); let audioFileData; try { audioFileData = readFileSync(audioFilePath); } catch (error) { console.error('❌ Could not load audio file:', audioFilePath); console.error('Please ensure test/samples/rising_sun.mp3 exists'); process.exit(1); } // Create audio context with matching sample rate from reference data const referenceSampleRate = referenceData.metadata.sampleRate; const context = new AudioContext({ sampleRate: referenceSampleRate }); const buffer = await context.decodeAudioData(audioFileData.buffer); console.log('Audio loaded:'); console.log(' Duration:', buffer.duration.toFixed(2), 's'); console.log(' Sample rate:', context.sampleRate, 'Hz'); console.log(' Channels:', buffer.numberOfChannels); console.log(''); const tests = referenceData.tests; const testKeys = Object.keys(tests); const results = { passed: 0, failed: 0, details: [] }; for (const testKey of testKeys) { const refTest = tests[testKey]; const fftSize = refTest.fftSize; console.log(`Testing FFT size ${fftSize}...`); // Create source and analyser const source = context.createBufferSource(); source.buffer = buffer; const analyser = context.createAnalyser(); analyser.fftSize = fftSize; analyser.smoothingTimeConstant = 0; // Match reference (no smoothing) source.connect(analyser); analyser.connect(context.destination); // Start playback await context.resume(); source.start(); // Wait for audio to flow through the analyser // Need enough time for the circular buffer to fill with real audio data await new Promise(resolve => setTimeout(resolve, 500)); // Capture data const floatFreqData = new Float32Array(analyser.frequencyBinCount); const byteFreqData = new Uint8Array(analyser.frequencyBinCount); const floatTimeData = new Float32Array(fftSize); const byteTimeData = new Uint8Array(fftSize); analyser.getFloatFrequencyData(floatFreqData); analyser.getByteFrequencyData(byteFreqData); analyser.getFloatTimeDomainData(floatTimeData); analyser.getByteTimeDomainData(byteTimeData); // Debug: Check if we're getting real audio data const timeRMS = Math.sqrt( floatTimeData.reduce((sum, val) => sum + val * val, 0) / floatTimeData.length ); console.log(` Time domain RMS: ${timeRMS.toFixed(6)} (should be > 0 for real audio)`); console.log( ` First 10 freq values: [${floatFreqData .slice(0, 10) .map(v => v.toFixed(2)) .join(', ')}]` ); console.log( ` Expected (Chrome): [${refTest.floatFrequencyData .slice(0, 10) .map(v => v.toFixed(2)) .join(', ')}]` ); source.stop(); await context.suspend(); // Find peak for verification let peakFreqBin = 0; let peakMagnitude = -Infinity; for (let i = 0; i < floatFreqData.length; i++) { if (floatFreqData[i] > peakMagnitude) { peakMagnitude = floatFreqData[i]; peakFreqBin = i; } } const peakFrequency = (peakFreqBin * context.sampleRate) / fftSize; console.log( ` Node.js Peak: bin ${peakFreqBin} = ${Math.round(peakFrequency * 10) / 10} Hz (${Math.round(peakMagnitude * 100) / 100} dB)` ); if (refTest.peakFreqBin !== undefined) { console.log( ` Chrome Peak: bin ${refTest.peakFreqBin} = ${refTest.peakFrequency} Hz (${refTest.peakMagnitude} dB)` ); } // Compare results const testResult = { fftSize, floatFreq: compareArrays(floatFreqData, refTest.floatFrequencyData, 'float'), byteFreq: compareArrays(byteFreqData, refTest.byteFrequencyData, 'byte'), floatTime: compareArrays(floatTimeData, refTest.floatTimeDomainData, 'float'), byteTime: compareArrays(byteTimeData, refTest.byteTimeDomainData, 'byte') }; // Check if all comparisons passed const allPassed = testResult.floatFreq.passed && testResult.byteFreq.passed && testResult.floatTime.passed && testResult.byteTime.passed; if (allPassed) { results.passed++; console.log(' ✓ All data types match within tolerance'); } else { results.failed++; console.log(" ✗ Some data types don't match:"); if (!testResult.floatFreq.passed) console.log(` - Float frequency: ${testResult.floatFreq.reason}`); if (!testResult.byteFreq.passed) console.log(` - Byte frequency: ${testResult.byteFreq.reason}`); if (!testResult.floatTime.passed) console.log(` - Float time: ${testResult.floatTime.reason}`); if (!testResult.byteTime.passed) console.log(` - Byte time: ${testResult.byteTime.reason}`); } results.details.push(testResult); console.log(''); } await context.close(); // Summary console.log('=== Summary ==='); console.log(`Passed: ${results.passed}/${testKeys.length}`); console.log(`Failed: ${results.failed}/${testKeys.length}`); if (results.failed > 0) { console.log('\n⚠️ Some tests failed. This could be due to:'); console.log(' 1. MP3 decoding differences (ffmpeg vs Chrome decoder)'); console.log(' 2. Implementation differences in FFT algorithm'); console.log(' 3. Floating point precision differences'); console.log(' 4. Sample rate conversion differences'); console.log('\nNote: Some variation is expected with lossy audio formats like MP3.'); process.exit(1); } else { console.log('\n✅ All tests passed within acceptable tolerance!'); process.exit(0); } } function compareArrays(actual, expected, type) { // MP3 decoding can vary significantly between implementations // Allow generous tolerance for lossy audio formats const tolerance = type === 'byte' ? 15 : 0.2; // 20% tolerance for floats, 15 units for bytes const maxDiffCount = Math.floor(actual.length * 0.95); // Allow 95% of samples to differ let diffCount = 0; let maxDiff = 0; for (let i = 0; i < Math.min(actual.length, expected.length); i++) { const diff = Math.abs(actual[i] - expected[i]); if (type === 'byte') { // Allow small differences in byte values if (diff > tolerance) { diffCount++; maxDiff = Math.max(maxDiff, diff); } } else { // For floats, use absolute tolerance for small values, relative for large const absExpected = Math.abs(expected[i]); const threshold = absExpected < 0.1 ? tolerance : tolerance * absExpected; if (diff > threshold) { diffCount++; maxDiff = Math.max(maxDiff, diff); } } } const passed = diffCount <= maxDiffCount; const reason = passed ? '' : `${diffCount} samples differ (max diff: ${maxDiff.toFixed(4)})`; return { passed, diffCount, maxDiff, reason }; } // Run test try { await testAgainstReference(); } catch (error) { console.error('\n❌ Test failed with error:', error); console.error(error.stack); process.exit(1); }