| 55 | } |
| 56 | |
| 57 | bool test_audio_processor() { |
| 58 | std::cout << "\n╔══════════════════════════════════════════╗\n" |
| 59 | << "║ AUDIO PROCESSOR TEST ║\n" |
| 60 | << "╚══════════════════════════════════════════╝\n"; |
| 61 | using namespace cactus::engine; |
| 62 | |
| 63 | Timer t; |
| 64 | |
| 65 | const size_t n_fft = 400; |
| 66 | const size_t hop_length = 160; |
| 67 | const size_t sampling_rate = 16000; |
| 68 | const size_t feature_size = 80; |
| 69 | const size_t num_frequency_bins = 1 + n_fft / 2; |
| 70 | |
| 71 | AudioProcessor audio_proc; |
| 72 | audio_proc.init_mel_filters(num_frequency_bins, feature_size, 0.0f, 8000.0f, sampling_rate); |
| 73 | |
| 74 | const size_t n_samples = sampling_rate; |
| 75 | std::vector<float> waveform(n_samples); |
| 76 | for (size_t i = 0; i < n_samples; i++) { |
| 77 | waveform[i] = std::sin(2.0f * M_PI * 440.0f * i / sampling_rate); |
| 78 | } |
| 79 | |
| 80 | AudioProcessor::SpectrogramConfig config; |
| 81 | config.n_fft = n_fft; |
| 82 | config.hop_length = hop_length; |
| 83 | config.frame_length = n_fft; |
| 84 | config.power = 2.0f; |
| 85 | config.center = true; |
| 86 | config.log_mel = "log10"; |
| 87 | |
| 88 | auto log_mel_spec = audio_proc.compute_spectrogram(waveform, config); |
| 89 | |
| 90 | double elapsed = t.elapsed_ms(); |
| 91 | |
| 92 | const float expected[] = {1.133450f, 1.142660f, 1.161900f, 1.196580f, 1.229480f}; |
| 93 | |
| 94 | const size_t pad_length = n_fft / 2; |
| 95 | const size_t padded_length = n_samples + 2 * pad_length; |
| 96 | const size_t num_frames = 1 + (padded_length - n_fft) / hop_length; |
| 97 | |
| 98 | bool passed = true; |
| 99 | if (log_mel_spec.size() != feature_size * num_frames) { |
| 100 | std::cerr << " [audio_processor] unexpected output size: got " << log_mel_spec.size() |
| 101 | << ", expected " << (feature_size * num_frames) << std::endl; |
| 102 | passed = false; |
| 103 | } |
| 104 | |
| 105 | #ifdef __APPLE__ |
| 106 | const float abs_tolerance = 1e-4f; |
| 107 | const float rel_tolerance = 1e-4f; |
| 108 | for (size_t i = 0; i < 5 && passed; i++) { |
| 109 | float actual = log_mel_spec[i * num_frames]; |
| 110 | float diff = std::abs(actual - expected[i]); |
| 111 | float allowed = std::max(abs_tolerance, rel_tolerance * std::abs(expected[i])); |
| 112 | if (diff > allowed) { |
| 113 | std::cerr << " [audio_processor][mac] idx=" << i |
| 114 | << " expected=" << expected[i] |
no test coverage detected