#include #include "helpers/FakeAudioSink.hpp" #include #include #include #include #include #include #include #include #include using namespace Echoion; using namespace Echoion::Core; namespace { std::string fixture(const char* name) { return std::string(ECHOION_TEST_FIXTURE_DIR) + "/" + name; } // Host backed by a plain vector queue mapping track id -> fixture path. class FakeHost : public IPlaybackHost { public: Test::FakeAudioSink sink; std::atomic tracksStarted{0}; std::atomic tracksFinished{0}; std::atomic idleCount{0}; std::atomic playbackErrors{0}; std::atomic repeat{false}; std::chrono::milliseconds resolveDelay{0}; void push(const std::string& id, const std::string& path) { std::lock_guard lock(mutex_); Api::QueueEntry e; e.queueId = nextId_++; e.track.id = id; e.track.title = id; e.track.streamUrl = path; queue_.push_back(std::move(e)); } void emitAudio(std::span samples) override { sink.onChunk(samples); } Api::Result resolveStream(const Api::QueueEntry& entry, bool /*preferDownload*/) override { if (resolveDelay.count() > 0) { std::this_thread::sleep_for(resolveDelay); } if (!entry.track.streamUrl) { return Api::fail(Api::ErrorCode::NotFound, "no url"); } return *entry.track.streamUrl; } std::optional peekNextTrack() override { std::lock_guard lock(mutex_); if (queue_.empty()) { return std::nullopt; } return queue_.front(); } std::optional takeNextTrack(uint64_t expectedQueueId) override { std::lock_guard lock(mutex_); if (queue_.empty() || queue_.front().queueId != expectedQueueId) { return std::nullopt; } auto e = queue_.front(); queue_.pop_front(); return e; } std::optional takeAnyNextTrack() override { std::lock_guard lock(mutex_); if (queue_.empty()) { return std::nullopt; } auto e = queue_.front(); queue_.pop_front(); return e; } bool repeatEnabled() const override { return repeat.load(); } void onTrackStarted(const Api::QueueEntry&) override { ++tracksStarted; } void onTrackFinished(const Api::QueueEntry&, std::chrono::milliseconds) override { ++tracksFinished; } void onPositionTick(const Api::QueueEntry&, std::chrono::milliseconds, std::chrono::milliseconds) override { } void onEngineIdle() override { ++idleCount; } void onLocalFileDone(const std::string&) override {} void onPlaybackError(const Api::Error&, const std::optional&) override { ++playbackErrors; } private: std::mutex mutex_; std::deque queue_; uint64_t nextId_ = 1; }; bool waitFor(const std::function& pred, std::chrono::seconds timeout) { const auto deadline = std::chrono::steady_clock::now() + timeout; while (std::chrono::steady_clock::now() < deadline) { if (pred()) { return true; } std::this_thread::sleep_for(std::chrono::milliseconds(20)); } return pred(); } // Goertzel power of one frequency bin over a PCM window (mono-summed). double goertzelPower(const std::vector& pcm, size_t offset, size_t samples, double frequency, double sampleRate) { const double k = 2.0 * std::cos(2.0 * 3.14159265358979 * frequency / sampleRate); double s0 = 0, s1 = 0, s2 = 0; // Interleaved stereo: use the left channel. for (size_t i = 0; i + 1 < samples; i += 2) { const double x = static_cast(pcm[offset + i]); s0 = x + k * s1 - s2; s2 = s1; s1 = s0; } return s1 * s1 + s2 * s2 - k * s1 * s2; } double windowRmsDb(const std::vector& pcm, size_t offset, size_t samples) { double sum = 0; for (size_t i = 0; i < samples; ++i) { const double v = static_cast(pcm[offset + i]); sum += v * v; } const double ms = sum / static_cast(samples); return 10.0 * std::log10(ms / (32768.0 * 32768.0) + 1e-12); } } // namespace TEST_CASE("PlaybackEngine plays two tracks back to back with no gap" * doctest::timeout(60)) { FakeHost host; host.push("one", fixture("sine5.wav")); host.push("two", fixture("sine4.wav")); PlaybackEngine engine(host); REQUIRE(engine.initialize(std::nullopt).has_value()); engine.setVolume(1.0f); engine.start(); // 5s + 4s of audio; allow slack for decode startup. REQUIRE(waitFor([&] { return host.idleCount.load() > 0; }, std::chrono::seconds(30))); engine.shutdown(); CHECK(host.tracksStarted.load() == 2); CHECK(host.tracksFinished.load() == 2); // Emission must never stall: chunks are 20ms apart, so anything over // ~100ms means the cadence broke. CHECK(host.sink.maxInterChunkGap() < std::chrono::milliseconds(150)); // The seam must be seamless: after playback settles (first second), // there must be no fully-silent chunk anywhere — including the boundary // between the two tracks. (A sine wave never yields 7680 consecutive // zero samples.) const auto pcm = host.sink.pcm(); const size_t chunk = PlaybackEngine::SHORTS_PER_CHUNK; const size_t settle = 50 * chunk; // skip initial resolve silence size_t silentChunksAfterSettle = 0; for (size_t off = settle; off + chunk <= pcm.size(); off += chunk) { bool allZero = true; for (size_t i = 0; i < chunk; ++i) { if (pcm[off + i] != 0) { allZero = false; break; } } // The final chunk may be zero-padded tail; tolerate exactly the // last one. if (allZero && off + 2 * chunk <= pcm.size()) { ++silentChunksAfterSettle; } } CHECK(silentChunksAfterSettle == 0); // Sanity: roughly 9 seconds of stereo 192kHz audio arrived. const size_t expected = 9u * PlaybackEngine::SAMPLE_RATE * PlaybackEngine::CHANNELS; CHECK(host.sink.totalSamples() > expected * 90 / 100); } TEST_CASE("PlaybackEngine skip advances to the next track" * doctest::timeout(60)) { FakeHost host; host.push("one", fixture("sine5.wav")); host.push("two", fixture("sine4.wav")); PlaybackEngine engine(host); REQUIRE(engine.initialize(std::nullopt).has_value()); engine.setVolume(1.0f); engine.start(); REQUIRE(waitFor([&] { return host.tracksStarted.load() >= 1; }, std::chrono::seconds(10))); std::this_thread::sleep_for(std::chrono::milliseconds(500)); engine.skip(1); REQUIRE(waitFor([&] { return host.tracksStarted.load() >= 2; }, std::chrono::seconds(10))); auto current = engine.currentEntry(); REQUIRE(current.has_value()); CHECK(current->track.id == "two"); engine.stopPlayback(); REQUIRE(waitFor([&] { return !engine.isPlaying(); }, std::chrono::seconds(5))); engine.shutdown(); } TEST_CASE("PlaybackEngine crossfades between tracks when configured" * doctest::timeout(60)) { FakeHost host; host.push("one", fixture("sine5.wav")); // 440 Hz, 5s host.push("two", fixture("sine4.wav")); // 880 Hz, 4s PlaybackEngine engine(host); REQUIRE(engine.initialize(std::nullopt).has_value()); engine.setVolume(1.0f); engine.setCrossfade(std::chrono::milliseconds(500)); engine.start(); REQUIRE(waitFor([&] { return host.idleCount.load() > 0; }, std::chrono::seconds(30))); engine.shutdown(); CHECK(host.tracksStarted.load() == 2); CHECK(host.tracksFinished.load() == 2); const auto pcm = host.sink.pcm(); constexpr double rate = PlaybackEngine::SAMPLE_RATE; const size_t window = PlaybackEngine::SHORTS_PER_CHUNK; // 20ms stereo // Locate the seam: the first window (after the start) where 880 Hz // dominates. During the 500ms overlap BOTH tones must be present and // 440 must decay while 880 rises. size_t seam = 0; for (size_t off = 50 * window; off + window <= pcm.size(); off += window) { const double p440 = goertzelPower(pcm, off, window, 440.0, rate); const double p880 = goertzelPower(pcm, off, window, 880.0, rate); if (p880 > p440) { seam = off; break; } } REQUIRE(seam > 0); // Walk backwards ~200ms: both tones audible (overlap, not a hard cut). const size_t before = seam - 10 * window; const double before440 = goertzelPower(pcm, before, window, 440.0, rate); const double before880 = goertzelPower(pcm, before, window, 880.0, rate); CHECK(before440 > 0); CHECK(before880 > 0); // 440 decays across the overlap. const double later440 = goertzelPower(pcm, seam + 5 * window, window, 440.0, rate); CHECK(later440 < before440); // Total duration ≈ 5s + 4s − 0.5s of overlap (generous tolerance for // decode padding). const double seconds = static_cast(host.sink.totalSamples()) / (rate * PlaybackEngine::CHANNELS); CHECK(seconds > 7.9); CHECK(seconds < 8.9); // The TS3 capture device must never be starved: chunks arrive on the // 20ms cadence throughout, including across the crossfade seam. CHECK(host.sink.maxInterChunkGap() < std::chrono::milliseconds(120)); } TEST_CASE("PlaybackEngine keeps feeding the device while a stream is slow " "to resolve" * doctest::timeout(60)) { FakeHost host; host.push("slow", fixture("sine2.wav")); // Resolution stalls ~1s: the engine must emit silence on cadence the // whole time (no "device reopen" gap), then play the track. host.resolveDelay = std::chrono::milliseconds(1000); PlaybackEngine engine(host); REQUIRE(engine.initialize(std::nullopt).has_value()); engine.start(); // Chunks must start arriving well before the 1s resolve completes. REQUIRE(waitFor([&] { return host.sink.chunkCount() > 20; }, std::chrono::seconds(2))); REQUIRE(waitFor([&] { return host.idleCount.load() > 0; }, std::chrono::seconds(20))); engine.shutdown(); // No stall over ~120ms at any point (device stayed fed through the // slow resolve and the start of playback). CHECK(host.sink.maxInterChunkGap() < std::chrono::milliseconds(120)); CHECK(host.tracksStarted.load() == 1); } TEST_CASE("PlaybackEngine AGC lifts a quiet track toward the target" * doctest::timeout(60)) { FakeHost host; host.push("quiet", fixture("quiet.wav")); // sine at 5% volume ≈ -29dB PlaybackEngine engine(host); REQUIRE(engine.initialize(std::nullopt).has_value()); engine.setVolume(1.0f); engine.setNormalization(true, -14.0f); engine.start(); REQUIRE(waitFor([&] { return host.idleCount.load() > 0; }, std::chrono::seconds(30))); engine.shutdown(); const auto pcm = host.sink.pcm(); REQUIRE(pcm.size() > PlaybackEngine::SHORTS_PER_CHUNK * 200); // The AGC boost is clamped at +12dB (deliberately — unbounded gain // would amplify noise floors), so assert the *behavior*: a monotonic // lift approaching the clamp, never overshooting the target. const size_t half = PlaybackEngine::SAMPLE_RATE; // 0.5s stereo const double startDb = windowRmsDb(pcm, half, half); // skip warmup const double endDb = windowRmsDb(pcm, pcm.size() - 2 * half, half); MESSAGE("AGC lift: ", startDb, " dB -> ", endDb, " dB"); CHECK(endDb - startDb > 6.0); // meaningful lift happened CHECK(endDb < -12.0); // never louder than target } TEST_CASE("PlaybackEngine reports errors and advances past a dead track" * doctest::timeout(60)) { FakeHost host; host.push("dead", ""); // no streamUrl -> resolveStream fails host.push("good", fixture("sine2.wav")); PlaybackEngine engine(host); REQUIRE(engine.initialize(std::nullopt).has_value()); engine.start(); // The dead track must surface an error and playback must continue with // the good one. REQUIRE(waitFor([&] { return host.playbackErrors.load() >= 1; }, std::chrono::seconds(10))); REQUIRE(waitFor([&] { return host.tracksStarted.load() >= 1; }, std::chrono::seconds(10))); auto current = engine.currentEntry(); REQUIRE(current.has_value()); CHECK(current->track.id == "good"); engine.shutdown(); } TEST_CASE("PlaybackEngine pause halts emission and resume continues" * doctest::timeout(60)) { FakeHost host; host.push("one", fixture("sine5.wav")); PlaybackEngine engine(host); REQUIRE(engine.initialize(std::nullopt).has_value()); engine.start(); REQUIRE(waitFor([&] { return host.sink.chunkCount() > 10; }, std::chrono::seconds(10))); engine.pause(); std::this_thread::sleep_for(std::chrono::milliseconds(200)); const auto paused = host.sink.chunkCount(); std::this_thread::sleep_for(std::chrono::milliseconds(300)); CHECK(host.sink.chunkCount() == paused); // nothing emitted while paused CHECK(engine.isPaused()); const auto positionWhilePaused = engine.position(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); CHECK(engine.position() == positionWhilePaused); // clock frozen engine.resume(); REQUIRE(waitFor([&] { return host.sink.chunkCount() > paused; }, std::chrono::seconds(5))); engine.shutdown(); }