Release 1.0.0

Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-04 01:50:44 +03:00
1 parent 52ab1ca24c
commit a3715201e1
23 files changed
+2226 -37

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
# GitLab CI for Echoion.
#
# Requires a runner whose image provides the toolchain the project builds
# with: GCC 16+ (C++26 with experimental reflection, -freflection), CMake
# 4.0+, and the system libraries FFmpeg, SQLite3, OpenSSL, TBB, Qt6 and a
# system Boost (>= 1.87) that matches VoidLibrary — a second, vendored Boost
# in the same process corrupts URL parsing, so the system copy must be used.
# Set the image on the runner or override `image:` below to that container.
stages:
- build
- test
- package
variables:
GIT_SUBMODULE_STRATEGY: recursive
BUILD_DIR: build
CMAKE_BUILD_TYPE: RelWithDebInfo
# Reuse the CMake build tree between jobs on the same ref to skip cold
# reconfigure/rebuild.
cache:
key: "$CI_COMMIT_REF_SLUG"
paths:
- build/
build:
stage: build
script:
- cmake -S . -B "$BUILD_DIR" -DCMAKE_BUILD_TYPE="$CMAKE_BUILD_TYPE" -DBUILD_TESTS=ON
- cmake --build "$BUILD_DIR" -j "$(nproc)"
artifacts:
paths:
- build/plugins/echoion_plugin.so
- build/bin/EchoionDesktop
- build/lib/
expire_in: 1 week
test:
stage: test
needs: ["build"]
script:
- ctest --test-dir "$BUILD_DIR" --output-on-failure
# Produce distributable packages only for tagged releases.
package:
stage: package
needs: ["build", "test"]
rules:
- if: '$CI_COMMIT_TAG'
script:
- cd "$BUILD_DIR"
- cpack -G "TGZ;DEB"
artifacts:
paths:
- build/*.tar.gz
- build/*.deb
expire_in: 1 month
+76
View File
@@ -0,0 +1,76 @@
# Changelog
All notable changes to Echoion are documented here. This project adheres to
[Semantic Versioning](https://semver.org/).
## [1.0.0] — 2026-07-04
The first public release of **Echoion**, a modern, gapless music bot for
TeamSpeak. This entry describes the product as shipped, not an incremental
diff.
### Playback
- **Gapless engine with crossfade.** A dual-decoder pipeline pre-warms the
next track while the current one plays, so track boundaries are seamless;
an optional crossfade (`bot.crossfade`) blends the transition.
- **High-quality audio.** 192 kHz stereo internal pipeline feeding
TeamSpeak's native audio system on a steady 20 ms cadence.
- **Loudness normalization.** An optional slow AGC evens out quiet and loud
tracks (`features.normalizeLoudness`, `features.targetLoudnessDb`).
- **Full transport controls.** Play, pause, resume, stop, skip, seek, volume,
shuffle and repeat.
- **SOCKS5-aware streaming.** Under a SOCKS5 proxy, IP-locked YouTube CDN
URLs are transparently downloaded through the proxy (via yt-dlp) and played
from a local file, so geo-blocked deployments still get audio.
### Catalogs & source routing
- **YouTube** via a native innertube player client (fastest path, one HTTP
POST) with yt-dlp as the resolver/fallback and for search.
- **Yandex Music** (native, unofficial API) — full tracks with a Plus OAuth
token; album, playlist and track URLs, plus in-catalog search.
- **Direct audio URLs / radio streams**, plus the wide range of yt-dlp
extractors (SoundCloud, Bandcamp, VK, …) for non-YouTube links.
- **`SourceRouter`** chains the sources with per-source failure cooldowns,
**hedged resolution** (a slow source is raced by the next candidate after
300 ms; first success wins), and a stream-URL cache.
### Commands
- **Play** — `!play` (searches YouTube + Yandex and lets you `!select`),
`!pyt` (YouTube only), `!pya` (Yandex only); a bare URL plays directly.
- **Search** — `!search` (both catalogs), `!youtube`/`!yb` (YouTube),
`!yandex`/`!ya` (Yandex).
- **Radio / autoplay** — `!radio` / `!autoplay [on|off]` keeps the music
going with related tracks (YouTube radio mix or Yandex similar tracks) when
the queue runs dry; the choice is persisted across restarts.
- **Queue & info** — `!queue`, `!np`, `!skip`, `!remove`, `!move`, `!clear`,
`!shuffle`, `!repeat`, `!seek`, `!volume`.
- **History, favorites, stats** — `!history`, `!fav`, `!stats`, rendered with
short links for YouTube tracks.
- **Subscriptions** — `!subscribe` / `!unsubscribe` / `!subscribers` for
per-user whisper delivery.
- **Admin** — `!announce` broadcasts a message to each subscriber exactly
once (restart-safe); `!reload` / `!reloadconfig` hot-reload the bot.
- **Grouped help** — `!help` renders collapsible sections, with the play and
search command families grouped together.
### Persistence
- SQLite-backed history, favorites, playlists, subscriptions and a generic
key/value store; announcements and the autoplay toggle survive restarts.
### Platform
- TeamSpeak 3 / 6 plugin plus a Qt6 desktop client.
- **Hot reload** of the core without disconnecting from the server.
- HTTP and SOCKS5 proxy support applied across every outbound client.
- JSON configuration with hot-reload across the plugin boundary.
### Build & packaging
- C++26 (GCC 16+, experimental reflection), CMake 4.0+, CPack packaging
(TGZ / DEB / RPM on Linux).
[1.0.0]: https://git.faumaray.ru/echoion/echoion/-/releases/1.0.0
+54 -2
View File
@@ -1,6 +1,31 @@
cmake_minimum_required(VERSION 4.0.0)
project(Echoion VERSION 1.0.0 LANGUAGES CXX)
# Default to a Release build when the developer/CI did not pick a config.
# Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC
# falls back to -O0, so "production" builds shipped unoptimised. Set this before
# any CPMAddPackage() below so fetched dependencies (Void, Boost, quickjs) are
# compiled with the same optimisation level as Echoion itself.
get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(NOT _isMultiConfig AND NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
Debug Release RelWithDebInfo MinSizeRel)
message(STATUS "No CMAKE_BUILD_TYPE set; defaulting to Release")
endif()
# Use ccache (or sccache) as a compiler launcher when available to speed up
# incremental and clean-from-cache rebuilds. Opt-out with -DECHOION_USE_CCACHE=OFF.
option(ECHOION_USE_CCACHE "Use ccache/sccache compiler launcher if found" ON)
if(ECHOION_USE_CCACHE AND NOT CMAKE_CXX_COMPILER_LAUNCHER)
find_program(ECHOION_CCACHE_PROGRAM NAMES ccache sccache)
if(ECHOION_CCACHE_PROGRAM)
set(CMAKE_C_COMPILER_LAUNCHER "${ECHOION_CCACHE_PROGRAM}")
set(CMAKE_CXX_COMPILER_LAUNCHER "${ECHOION_CCACHE_PROGRAM}")
message(STATUS "Compiler cache enabled: ${ECHOION_CCACHE_PROGRAM}")
endif()
endif()
# Include CPM
file(
DOWNLOAD
@@ -26,7 +51,7 @@ CPMAddPackage(
CPMAddPackage(
NAME Void
GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git
GIT_TAG 2c3ff56b677529ed91decf8d4cfb415ffec51042
GIT_TAG main
OPTIONS
"VOID_ENABLE_TESTING OFF"
)
@@ -44,6 +69,33 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_G
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-freflection>)
endif()
# Link-time optimisation for Release configs only (keeps Debug builds fast).
# Experimental C++26 reflection (-freflection) is a front-end feature and is
# orthogonal to GCC's LTO, but gate behind an option so it can be disabled if a
# given toolchain rejects the combination.
option(ECHOION_ENABLE_LTO "Enable interprocedural optimisation for Release builds" ON)
if(ECHOION_ENABLE_LTO)
include(CheckIPOSupported)
check_ipo_supported(RESULT _ipoSupported OUTPUT _ipoError LANGUAGES CXX)
if(_ipoSupported)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO ON)
message(STATUS "Interprocedural optimisation (LTO) enabled for Release")
else()
message(STATUS "IPO/LTO not supported by toolchain: ${_ipoError}")
endif()
endif()
# Unity builds batch translation units to cut compile time. Kept OFF by default
# because reflection TUs and Glaze-heavy headers can blow up unity batch memory;
# enable per-machine with -DECHOION_UNITY_BUILD=ON.
option(ECHOION_UNITY_BUILD "Enable CMake unity (jumbo) builds" OFF)
if(ECHOION_UNITY_BUILD)
set(CMAKE_UNITY_BUILD ON)
set(CMAKE_UNITY_BUILD_BATCH_SIZE 8)
message(STATUS "Unity build enabled (batch size 8)")
endif()
# Enable folder organization in IDEs
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
@@ -86,7 +138,7 @@ endif()
# Tests
if(BUILD_TESTS)
enable_testing()
# add_subdirectory(tests)
add_subdirectory(tests)
endif()
# Packaging configuration
Vendored
+61
View File
@@ -0,0 +1,61 @@
// Jenkins pipeline for Echoion.
//
// The agent must provide the toolchain the project builds with: GCC 16+
// (C++26 with experimental reflection, -freflection), CMake 4.0+, and the
// system libraries FFmpeg, SQLite3, OpenSSL, TBB, Qt6 and a system Boost
// (>= 1.87) matching VoidLibrary. A second vendored Boost in the same
// process corrupts URL parsing, so the system copy must be used. Point the
// `agent` at a container/node with that toolchain (e.g. a custom Docker
// image); the `docker` agent below is a template — adjust `image` to yours.
pipeline {
agent {
docker { image 'echoion/ci:gcc16' args '-u root' }
}
environment {
BUILD_DIR = 'build'
CMAKE_BUILD_TYPE = 'RelWithDebInfo'
}
stages {
stage('Checkout') {
steps {
checkout scm
sh 'git submodule update --init --recursive'
}
}
stage('Build') {
steps {
sh '''
cmake -S . -B "$BUILD_DIR" \
-DCMAKE_BUILD_TYPE="$CMAKE_BUILD_TYPE" \
-DBUILD_TESTS=ON
cmake --build "$BUILD_DIR" -j "$(nproc)"
'''
}
}
stage('Test') {
steps {
sh 'ctest --test-dir "$BUILD_DIR" --output-on-failure'
}
}
stage('Package') {
when { buildingTag() }
steps {
sh 'cd "$BUILD_DIR" && cpack -G "TGZ;DEB"'
}
}
}
post {
success {
archiveArtifacts artifacts: 'build/plugins/echoion_plugin.so, build/bin/EchoionDesktop, build/*.tar.gz, build/*.deb',
allowEmptyArchive: true,
fingerprint: true
}
}
}
+37 -8
View File
@@ -4,9 +4,16 @@ A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist supp
## Features
- 🎵 **YouTube Integration** - Play music directly from YouTube URLs or search queries
- 🎵 **YouTube Integration** - Play music directly from YouTube URLs or search queries via a native innertube client (fastest path) with yt-dlp as the resolver/fallback
- 🎶 **Two Catalogs** - Search and play from YouTube and Yandex Music (native, full tracks with a Plus token). `!play` searches both; `!pyt`/`!pya` target one. Direct audio URLs / radio streams and other yt-dlp extractors (SoundCloud, Bandcamp, VK, …) also work
- ⚡ **Hedged Resolution** - A slow source is raced by the next candidate after 300ms; first success wins
- 🔁 **Gapless Playback & Crossfade** - The next track's decoder is pre-warmed while the current one plays; optional crossfade (`bot.crossfade`)
- 🔊 **Loudness Normalization** - Optional slow AGC evens out quiet/loud tracks (`features.normalizeLoudness`)
- 📻 **Autoplay / Radio Mode** - When the queue runs dry, `!radio` keeps the music going with related tracks from YouTube or Yandex (`features.autoplay`)
- 💾 **Track Cache** - Downloaded audio is reused across plays and restarts (`advanced.cache*`)
- ⭐ **History & Favorites** - `!history`, `!stats`, `!fav add|list|play` backed by SQLite
- 📋 **Playlist Support** - Queue management with shuffle, repeat, and skip functionality
- 🎧 **High Quality Audio** - Supports up to 48kHz stereo audio
- 🎧 **High Quality Audio** - 192kHz stereo internal pipeline
- 🔄 **Hot Reload** - Update the bot without disconnecting from the server
- ⚙️ **Configurable** - JSON-based configuration system
- 🔊 **TeamSpeak Native** - Uses TeamSpeak's native audio system for best quality
@@ -15,11 +22,11 @@ A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist supp
### Requirements
- C++26 compatible compiler (GCC 15+, Clang 18+, or MSVC 2022+)
- CMake 3.28+
- C++26 compatible compiler with reflections (GCC 16+)
- CMake 4.0+
- Qt6 (for desktop client)
- FFmpeg (for audio decoding)
- Glaze library (JSON parsing)
- Boost (system installation preferred; the build vendors one only when absent — mixing a vendored and a system Boost in one process breaks boost.url)
- TeamSpeak 3 Client SDK
### Build Instructions
@@ -30,6 +37,18 @@ cmake ..
cmake --build .
```
### Tests
```bash
cmake .. -DBUILD_TESTS=ON
cmake --build . && ctest
```
The suite covers the decoder (against generated audio fixtures), the queue
and shuffle bookkeeping, the gapless playback engine (asserting a seamless
track boundary), and the source router (fall-through, hedging and stream
caching).
## Configuration
Copy `config.example.json` to your config directory:
@@ -72,13 +91,20 @@ All commands use the configured prefix (default: `!`)
| `!resume` | Resume playback | `!resume` |
| `!stop` | Stop playback | `!stop` |
| `!skip` | Skip current track | `!skip` |
| `!seek <+/-secs>` | Seek within the track | `!seek +30` |
| `!queue` | Show current queue | `!queue` |
| `!clear` | Clear the queue | `!clear` |
| `!shuffle` | Toggle shuffle mode | `!shuffle` |
| `!repeat` | Toggle repeat mode | `!repeat` |
| `!volume <0-100>` | Set volume | `!volume 50` |
| `!nowplaying` | Show current track | `!nowplaying` |
| `!search <query>` | Search YouTube | `!search daft punk` |
| `!search <query>` | Search YouTube + Yandex Music | `!search daft punk` |
| `!youtube <query>` | Search YouTube only (alias `yb`, `yt`) | `!yb daft punk` |
| `!yandex <query>` | Search Yandex Music only (alias `ya`) | `!ya грибы` |
| `!history [n]` | Recently played tracks | `!history 15` |
| `!stats` | Playback statistics | `!stats` |
| `!fav add\|list\|play <n>` | Manage your favorites | `!fav play 2` |
| `!announce <text>` | **Admin:** message all subscribers once | `!announce New update live!` |
## Architecture
@@ -91,10 +117,13 @@ The bot consists of three main components:
### Audio Flow
```
YouTube URL → NetworkClient → AudioDecoder → MusicManager → Core → PluginInterface → TeamSpeak
query → SourceRouter (innertube → Yandex → direct URL → yt-dlp) → PlaybackEngine
(dual AudioDecoder, gapless handoff) → Core → PluginInterface → TeamSpeak
```
Audio is decoded using FFmpeg, processed at 48kHz stereo, and sent to TeamSpeak's custom audio device.
Audio is decoded using FFmpeg at 192kHz stereo and emitted in 20ms chunks to
TeamSpeak's custom audio device by a single real-time engine thread. See
`docs/09-audio-pipeline.md` for details.
## Development
+28 -22
View File
@@ -9,15 +9,10 @@
"commandPrefix": "!",
"defaultVolume": 0.5,
"maxQueueSize": 100,
"trackTimeout": "30000ms",
"_reconnection": "Auto-reconnection settings",
"autoReconnect": true,
"reconnectDelay": "5000ms",
"maxReconnectAttempts": 5,
"_audio": "Audio quality: Low | Medium | High | VeryHigh | Lossless",
"preferredQuality": "High",
"_trackTimeout": "How long the engine waits (emitting silence) for a slow stream resolve before skipping the track",
"trackTimeout": "10s",
"_crossfade": "Crossfade between tracks (e.g. \"3s\"); \"0ms\" = plain gapless handoff",
"crossfade": "0ms",
"allowPlaylistImports": true
},
@@ -51,6 +46,22 @@
"rpcBindAddress": "127.0.0.1"
},
"sources": {
"_section": "Music source resolution chain (native paths first, proxied yt-dlp last)",
"_order": "Sources are tried in this order. innertube is the native YouTube player API; yandex is native Yandex Music; ytdlp-proxied is the proxied fallback and always works when a proxy is configured.",
"order": ["innertube", "yandex", "direct-url", "ytdlp-direct", "ytdlp-proxied"],
"_failureCooldown": "How long a failing source is skipped before being retried",
"failureCooldown": "5m",
"_hedgeDelay": "Race a second source when the first hasn't answered within this delay (first success wins); \"0ms\" disables",
"hedgeDelay": "300ms",
"_yandex": "Native Yandex Music. Full tracks need an OAuth token from an account with Plus (see yandex-music token guides); without one, yandex URLs fall back to yt-dlp.",
"yandexEnabled": true,
"yandexToken": null,
"_innertube": "Native YouTube player API (fastest path, one HTTP POST). Geo-blocked without a proxy; requireProxy skips it when none is configured.",
"innertubeEnabled": true,
"innertubeRequireProxy": true
},
"teamspeak": {
"_section": "TeamSpeak Server Connection",
"address": "localhost",
@@ -92,26 +103,21 @@
"autoStartOnSubscribe": true,
"pauseOnEmptySubscribers": true,
"resumeOnSubscriberReturn": true,
"_autoplay": "Radio mode: when the queue runs dry, enqueue tracks related to the last played one",
"autoplay": false,
"_loudness": "Normalize perceived volume across tracks (slow AGC toward the target level)",
"normalizeLoudness": false,
"targetLoudnessDb": -14.0,
"_queue": "Queue management settings",
"shuffleMode": "random",
"_queue": "Initial queue state on cold start (shuffleMode: off|random, repeatMode: off|all); runtime toggles are not written back",
"shuffleMode": "off",
"repeatMode": "off",
"maxHistorySize": 50
},
"advanced": {
"_section": "Advanced Settings (Modify with caution)",
"_audio": "Low-level audio configuration",
"sampleRate": 192000,
"channels": 2,
"bufferSize": 7680,
"_threading": "Thread pool configuration",
"commandThreadPoolSize": 4,
"networkThreadPoolSize": 4,
"decoderThreads": 2,
"_cache": "Cache and temporary file settings",
"_cache": "Local audio track cache (files reused across plays and restarts)",
"cacheEnabled": true,
"cacheMaxSize": "1GB",
"cacheTTL": 86400,
+1 -1
Submodule docs updated: d4bbb1d4bf...3ad8d88c55.
+80
View File
@@ -0,0 +1,80 @@
#include <doctest/doctest.h>
#include <echoion/core/AudioDecoder.hpp>
#include <string>
#include <vector>
namespace
{
std::string fixture(const char* name)
{
return std::string(ECHOION_TEST_FIXTURE_DIR) + "/" + name;
}
// Drains every chunk out of the decoder until EOF; returns total samples.
std::size_t drain(Echoion::Core::AudioDecoder& decoder)
{
std::size_t total = 0;
std::vector<int16_t> chunk;
while (true) {
if (decoder.getNextChunk(chunk, true)) {
total += chunk.size();
} else if (decoder.isFinished()) {
break;
}
}
return total;
}
} // namespace
TEST_CASE("AudioDecoder decodes a WAV fixture completely")
{
Echoion::Core::AudioDecoder decoder;
REQUIRE(decoder.initialize().has_value());
decoder.setOutputFormat(48000, 2);
auto open = decoder.openSource(fixture("sine1.wav"));
REQUIRE_MESSAGE(open.has_value(),
(open ? std::string{} : open.error().message));
const std::size_t total = drain(decoder);
// 2 seconds @ 48kHz stereo. WAV is exact (no codec delay/padding).
CHECK(total == 2u * 48000u * 2u);
auto info = decoder.getStreamInfo();
REQUIRE(info.has_value());
CHECK(info->sampleRate == 48000);
decoder.closeSource();
decoder.shutdown();
}
TEST_CASE("AudioDecoder survives close/reopen cycles")
{
Echoion::Core::AudioDecoder decoder;
REQUIRE(decoder.initialize().has_value());
decoder.setOutputFormat(48000, 2);
for (int i = 0; i < 3; ++i) {
auto open = decoder.openSource(fixture("sine2.wav"));
REQUIRE(open.has_value());
const std::size_t total = drain(decoder);
CHECK(total == 1u * 48000u * 2u); // 1 second fixture
decoder.closeSource();
}
decoder.shutdown();
}
TEST_CASE("AudioDecoder reports failure for a missing source")
{
Echoion::Core::AudioDecoder decoder;
REQUIRE(decoder.initialize().has_value());
auto open = decoder.openSource(fixture("does-not-exist.wav"));
CHECK_FALSE(open.has_value());
decoder.shutdown();
}
+56
View File
@@ -0,0 +1,56 @@
cmake_minimum_required(VERSION 4.0.0)
CPMAddPackage("gh:doctest/doctest@2.4.12")
# Audio fixtures are generated at build time with ffmpeg; tests decode them
# through the real AudioDecoder, so the binary never ships fixture data.
find_program(FFMPEG_EXECUTABLE ffmpeg REQUIRED)
set(ECHOION_TEST_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures")
file(MAKE_DIRECTORY "${ECHOION_TEST_FIXTURE_DIR}")
set(_fixtures "")
foreach(_spec "sine1;440;2;1.0" "sine2;880;1;1.0" "sine5;440;5;1.0"
"sine4;880;4;1.0" "quiet;440;5;0.05")
list(GET _spec 0 _name)
list(GET _spec 1 _freq)
list(GET _spec 2 _dur)
list(GET _spec 3 _vol)
set(_out "${ECHOION_TEST_FIXTURE_DIR}/${_name}.wav")
add_custom_command(
OUTPUT "${_out}"
COMMAND ${FFMPEG_EXECUTABLE} -y -loglevel error
-f lavfi -i "sine=frequency=${_freq}:duration=${_dur}"
-filter:a "volume=${_vol}"
-ar 48000 -ac 2 -c:a pcm_s16le "${_out}"
COMMENT "Generating audio fixture ${_name}.wav"
VERBATIM
)
list(APPEND _fixtures "${_out}")
endforeach()
add_custom_target(EchoionTestFixtures DEPENDS ${_fixtures})
file(GLOB_RECURSE TEST_SOURCES CONFIGURE_DEPENDS "*.cpp")
add_executable(EchoionCoreTests ${TEST_SOURCES})
add_dependencies(EchoionCoreTests EchoionTestFixtures)
target_compile_definitions(EchoionCoreTests PRIVATE
ECHOION_TEST_FIXTURE_DIR="${ECHOION_TEST_FIXTURE_DIR}"
)
target_include_directories(EchoionCoreTests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
find_package(OpenSSL REQUIRED)
target_link_libraries(EchoionCoreTests PRIVATE
EchoionCore
doctest::doctest
Boost::beast
Boost::asio
OpenSSL::Crypto
Threads::Threads
)
set_target_properties(EchoionCoreTests PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
include(${doctest_SOURCE_DIR}/scripts/cmake/doctest.cmake)
doctest_discover_tests(EchoionCoreTests)
+285
View File
@@ -0,0 +1,285 @@
#include <doctest/doctest.h>
#include <Database.hpp>
#include <chrono>
#include <filesystem>
#include <string>
using Echoion::Api::Database;
using Echoion::Api::DatabaseConfig;
namespace
{
// Fresh on-disk database per test (":memory:" would also work but the
// file path exercises the real open/migrate path).
struct TempDb {
std::filesystem::path path;
Database db;
TempDb()
{
path = std::filesystem::temp_directory_path() /
("echoion-test-" +
std::to_string(
std::chrono::steady_clock::now()
.time_since_epoch()
.count()) +
".db");
REQUIRE(db.initialize(DatabaseConfig{.path = path.string()})
.has_value());
}
~TempDb()
{
db.shutdown();
std::error_code ec;
std::filesystem::remove(path, ec);
std::filesystem::remove(path.string() + "-wal", ec);
std::filesystem::remove(path.string() + "-shm", ec);
}
};
Echoion::Api::TrackInfo track(const std::string& url,
const std::string& title)
{
Echoion::Api::TrackInfo t;
t.originalUrl = url;
t.title = title;
t.artist = "Artist";
return t;
}
} // namespace
TEST_CASE("Database playlist CRUD round-trip")
{
TempDb tdb;
auto& db = tdb.db;
auto id = db.createPlaylist("Mix", "desc", 1);
REQUIRE(id.has_value());
REQUIRE(db.addTrackToPlaylist(*id, track("u1", "One"), 0).has_value());
REQUIRE(db.addTrackToPlaylist(*id, track("u2", "Two"), 1).has_value());
REQUIRE(db.addTrackToPlaylist(*id, track("u3", "Three"), 2).has_value());
auto loaded = db.getPlaylist(*id);
REQUIRE(loaded.has_value());
REQUIRE(loaded->has_value());
CHECK((*loaded)->name == "Mix");
REQUIRE((*loaded)->tracks.size() == 3);
CHECK((*loaded)->tracks[0].title == "One");
CHECK((*loaded)->tracks[2].title == "Three");
REQUIRE(db.updatePlaylist(*id, "Renamed", std::nullopt, true)
.has_value());
auto renamed = db.getPlaylist(*id);
REQUIRE(renamed.has_value());
REQUIRE(renamed->has_value());
CHECK((*renamed)->name == "Renamed");
CHECK((*renamed)->description == "desc"); // untouched via COALESCE
CHECK((*renamed)->isPublic);
}
TEST_CASE("Database getKv/setKv round-trip")
{
TempDb tdb;
auto& db = tdb.db;
auto missing = db.getKv("nope");
REQUIRE(missing.has_value());
CHECK_FALSE(missing->has_value());
REQUIRE(db.setKv("instances.invidious", "[\"https://a\"]").has_value());
auto value = db.getKv("instances.invidious");
REQUIRE(value.has_value());
REQUIRE(value->has_value());
CHECK(**value == "[\"https://a\"]");
// Overwrite
REQUIRE(db.setKv("instances.invidious", "[]").has_value());
auto updated = db.getKv("instances.invidious");
REQUIRE(updated.has_value());
CHECK(**updated == "[]");
}
// Mirrors MusicManager's announcement persistence: id bumped per post,
// per-uid seen-id gate delivers exactly once and survives a "restart"
// (reopening the same DB). This locks the kv contract the delivery code
// relies on.
namespace
{
int64_t kvInt(Database& db, const std::string& key, int64_t def)
{
if (auto v = db.getKv(key); v && *v) {
try {
return std::stoll(**v);
} catch (...) {
return def;
}
}
return def;
}
// Returns true if a "send" would occur for this uid, applying the gate.
bool wouldDeliver(Database& db, const std::string& uid)
{
const int64_t id = kvInt(db, "announcement.id", 0);
auto text = db.getKv("announcement.text");
if (id == 0 || !text || !*text || (*text)->empty()) {
return false;
}
const std::string seenKey = "announcement.seen." + uid;
if (kvInt(db, seenKey, 0) >= id) {
return false;
}
(void)db.setKv(seenKey, std::to_string(id)); // mark delivered
return true;
}
void postAnnouncement(Database& db, const std::string& text)
{
const int64_t id = kvInt(db, "announcement.id", 0) + 1;
(void)db.setKv("announcement.text", text);
(void)db.setKv("announcement.id", std::to_string(id));
}
} // namespace
TEST_CASE("Announcement delivery is once-per-subscriber and restart-safe")
{
TempDb tdb;
auto& db = tdb.db;
// No announcement yet → nothing delivers.
CHECK_FALSE(wouldDeliver(db, "uidA"));
postAnnouncement(db, "v1");
CHECK(wouldDeliver(db, "uidA")); // first delivery
CHECK_FALSE(wouldDeliver(db, "uidA")); // never twice
CHECK(wouldDeliver(db, "uidB")); // a different subscriber still gets it
// Simulate a bot restart: reopen the same database file.
db.shutdown();
REQUIRE(db.initialize(DatabaseConfig{.path = tdb.path.string()})
.has_value());
CHECK_FALSE(wouldDeliver(db, "uidA")); // seen-id persisted, no resend
// A fresh announcement bumps the id and reaches everyone once more.
postAnnouncement(db, "v2");
CHECK(wouldDeliver(db, "uidA"));
CHECK_FALSE(wouldDeliver(db, "uidA"));
}
TEST_CASE("Database history: recently played dedupes, stats add up, trim caps")
{
TempDb tdb;
auto& db = tdb.db;
using std::chrono::milliseconds;
// "a" played twice, "b" once.
REQUIRE(db.recordPlayback(track("a", "A"), 1, milliseconds(1000), true)
.has_value());
REQUIRE(db.recordPlayback(track("b", "B"), 1, milliseconds(2000), true)
.has_value());
REQUIRE(db.recordPlayback(track("a", "A"), 2, milliseconds(3000), true)
.has_value());
auto recent = db.getRecentlyPlayed(0, 10);
REQUIRE(recent.has_value());
CHECK(recent->size() == 2); // deduped by url
auto stats = db.getStatistics(0);
REQUIRE(stats.has_value());
CHECK(stats->totalPlays == 3);
CHECK(stats->totalTracks == 2);
CHECK(stats->totalPlaytimeMs == 6000);
REQUIRE(stats->mostPlayedTrack.has_value());
CHECK(stats->mostPlayedTrack->originalUrl == "a");
CHECK(stats->mostPlayedCount == 2);
auto top = db.getMostPlayed(0, 5);
REQUIRE(top.has_value());
REQUIRE(top->size() == 2);
CHECK(top->front().second == 2);
// Trim to 1 entry.
REQUIRE(db.trimHistory(1).has_value());
auto after = db.getPlaybackHistory(2, 100);
REQUIRE(after.has_value());
auto global = db.getRecentlyPlayed(0, 10);
REQUIRE(global.has_value());
CHECK(global->size() == 1);
}
TEST_CASE("Database persists the shortened track URL across history and favorites")
{
TempDb tdb;
auto& db = tdb.db;
using std::chrono::milliseconds;
auto yt = track("https://www.youtube.com/watch?v=abc", "Shorty");
yt.shortenedUrl = "https://faumaray.ru/x1";
REQUIRE(db.recordPlayback(yt, 7, milliseconds(1000), true).has_value());
REQUIRE(db.addFavorite(7, yt).has_value());
auto history = db.getPlaybackHistory(7, 10);
REQUIRE(history.has_value());
REQUIRE(history->size() == 1);
REQUIRE(history->front().track.shortenedUrl.has_value());
CHECK(*history->front().track.shortenedUrl == "https://faumaray.ru/x1");
auto favs = db.getFavorites(7);
REQUIRE(favs.has_value());
REQUIRE(favs->size() == 1);
REQUIRE(favs->front().track.shortenedUrl.has_value());
CHECK(*favs->front().track.shortenedUrl == "https://faumaray.ru/x1");
auto recent = db.getRecentlyPlayed(0, 10);
REQUIRE(recent.has_value());
REQUIRE(recent->size() == 1);
REQUIRE(recent->front().shortenedUrl.has_value());
CHECK(*recent->front().shortenedUrl == "https://faumaray.ru/x1");
}
TEST_CASE("Database playlist remove and reorder keep positions dense")
{
TempDb tdb;
auto& db = tdb.db;
auto id = db.createPlaylist("Order", "", 1);
REQUIRE(id.has_value());
for (int i = 0; i < 4; ++i) {
REQUIRE(db.addTrackToPlaylist(
*id, track("u" + std::to_string(i),
"T" + std::to_string(i)),
static_cast<uint32_t>(i))
.has_value());
}
// Track db ids are their playlist_tracks rowids (1-based insert order
// in a fresh database).
// Remove the second track (T1): T0,T2,T3 remain in that order.
REQUIRE(db.removeTrackFromPlaylist(*id, 2).has_value());
{
auto loaded = db.getPlaylist(*id);
REQUIRE(loaded.has_value());
REQUIRE(loaded->has_value());
REQUIRE((*loaded)->tracks.size() == 3);
CHECK((*loaded)->tracks[0].title == "T0");
CHECK((*loaded)->tracks[1].title == "T2");
CHECK((*loaded)->tracks[2].title == "T3");
}
// Move T3 (rowid 4) to the front.
REQUIRE(db.reorderPlaylistTrack(*id, 4, 0).has_value());
{
auto loaded = db.getPlaylist(*id);
REQUIRE(loaded.has_value());
REQUIRE(loaded->has_value());
REQUIRE((*loaded)->tracks.size() == 3);
CHECK((*loaded)->tracks[0].title == "T3");
CHECK((*loaded)->tracks[1].title == "T0");
CHECK((*loaded)->tracks[2].title == "T2");
}
}
+105
View File
@@ -0,0 +1,105 @@
#include <doctest/doctest.h>
#include "helpers/StubHttpServer.hpp"
#include <echoion/core/NetworkClient.hpp>
#include <echoion/core/sources/InnertubeSource.hpp>
#include <memory>
using namespace Echoion;
using namespace Echoion::Core;
using Echoion::Test::StubHttpServer;
namespace
{
std::shared_ptr<NetworkClient> makeNetwork()
{
auto n = std::make_shared<NetworkClient>();
REQUIRE(n->initialize().has_value());
return n;
}
constexpr const char* kPlayerJson = R"({
"playabilityStatus": {"status": "OK"},
"videoDetails": {
"videoId": "dQw4w9WgXcQ",
"title": "Inner Video",
"author": "Inner Author",
"lengthSeconds": "212",
"thumbnail": {"thumbnails": [{"url": "https://example.com/t.jpg"}]}
},
"streamingData": {
"adaptiveFormats": [
{"itag": 137, "mimeType": "video/mp4", "bitrate": 4000000,
"url": "https://video.example/ignored"},
{"itag": 140, "mimeType": "audio/mp4; codecs=\"mp4a\"",
"bitrate": 130000, "url": "https://audio.example/aac"},
{"itag": 251, "mimeType": "audio/webm; codecs=\"opus\"",
"bitrate": 160000, "url": "https://audio.example/opus"}
]
}
})";
} // namespace
TEST_CASE("InnertubeSource resolves metadata and picks the best audio URL")
{
StubHttpServer stub;
stub.route("/youtubei/v1/player*", {.body = kPlayerJson});
auto network = makeNetwork();
InnertubeSource source(network, stub.baseUrl());
source.configure(true, /*requireProxy=*/false);
CHECK(source.isAvailable());
CHECK(source.canHandle("https://www.youtube.com/watch?v=dQw4w9WgXcQ"));
CHECK(source.canHandle("dQw4w9WgXcQ"));
CHECK_FALSE(source.canHandle("free text query")); // search stays elsewhere
CHECK_FALSE(source.canHandle("https://soundcloud.com/x/y"));
auto track = source.resolve("https://youtu.be/dQw4w9WgXcQ");
REQUIRE(track.has_value());
CHECK(track->title == "Inner Video");
CHECK(track->artist == "Inner Author");
CHECK(track->duration == std::chrono::milliseconds(212000));
CHECK(track->source == Api::TrackSource::YouTube);
auto handle = source.getStream(*track);
REQUIRE(handle.has_value());
CHECK(handle->url == "https://audio.example/opus"); // 251 over 140
CHECK(handle->sourceName == "innertube");
}
TEST_CASE("InnertubeSource reports unplayable videos as errors")
{
StubHttpServer stub;
stub.route("/youtubei/v1/player*", {.body = R"({
"playabilityStatus": {"status": "LOGIN_REQUIRED",
"reason": "Sign in to confirm your age"}
})"});
auto network = makeNetwork();
InnertubeSource source(network, stub.baseUrl());
source.configure(true, false);
Api::TrackInfo track;
track.id = "dQw4w9WgXcQ";
track.originalUrl = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
auto handle = source.getStream(track);
REQUIRE_FALSE(handle.has_value());
CHECK(handle.error().message.find("LOGIN_REQUIRED") !=
std::string::npos);
}
TEST_CASE("InnertubeSource is skipped without a proxy when required")
{
auto network = makeNetwork(); // no proxy configured
InnertubeSource source(network);
source.configure(true, /*requireProxy=*/true);
CHECK_FALSE(source.isAvailable());
source.configure(true, /*requireProxy=*/false);
CHECK(source.isAvailable());
source.configure(false, false);
CHECK_FALSE(source.isAvailable());
}
+433
View File
@@ -0,0 +1,433 @@
#include <doctest/doctest.h>
#include "helpers/FakeAudioSink.hpp"
#include <echoion/core/playback/PlaybackEngine.hpp>
#include <atomic>
#include <chrono>
#include <cmath>
#include <deque>
#include <functional>
#include <mutex>
#include <string>
#include <thread>
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<int> tracksStarted{0};
std::atomic<int> tracksFinished{0};
std::atomic<int> idleCount{0};
std::atomic<int> playbackErrors{0};
std::atomic<bool> repeat{false};
std::chrono::milliseconds resolveDelay{0};
void push(const std::string& id, const std::string& path)
{
std::lock_guard<std::mutex> 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<const short> samples) override
{
sink.onChunk(samples);
}
Api::Result<std::string>
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<Api::QueueEntry> peekNextTrack() override
{
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty()) {
return std::nullopt;
}
return queue_.front();
}
std::optional<Api::QueueEntry>
takeNextTrack(uint64_t expectedQueueId) override
{
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty() ||
queue_.front().queueId != expectedQueueId) {
return std::nullopt;
}
auto e = queue_.front();
queue_.pop_front();
return e;
}
std::optional<Api::QueueEntry> takeAnyNextTrack() override
{
std::lock_guard<std::mutex> 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<Api::QueueEntry>&)
override
{
++playbackErrors;
}
private:
std::mutex mutex_;
std::deque<Api::QueueEntry> queue_;
uint64_t nextId_ = 1;
};
bool waitFor(const std::function<bool()>& 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<short>& 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<double>(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<short>& pcm, size_t offset,
size_t samples)
{
double sum = 0;
for (size_t i = 0; i < samples; ++i) {
const double v = static_cast<double>(pcm[offset + i]);
sum += v * v;
}
const double ms = sum / static_cast<double>(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<double>(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();
}
+137
View File
@@ -0,0 +1,137 @@
#include <doctest/doctest.h>
#include <echoion/core/playback/QueueService.hpp>
#include <set>
#include <string>
using Echoion::Core::QueueService;
namespace
{
Echoion::Api::TrackInfo track(const std::string& id)
{
Echoion::Api::TrackInfo t;
t.id = id;
t.title = id;
return t;
}
} // namespace
TEST_CASE("QueueService FIFO order without shuffle")
{
QueueService q;
auto a = q.enqueue(track("a"), "tester", 100);
auto b = q.enqueue(track("b"), "tester", 100);
REQUIRE(a.has_value());
REQUIRE(b.has_value());
CHECK(q.size() == 2);
auto peek = q.peekNext();
REQUIRE(peek.has_value());
CHECK(peek->track.id == "a");
auto first = q.popNext();
REQUIRE(first.has_value());
CHECK(first->track.id == "a");
CHECK(first->addedBy == "tester");
CHECK(first->queueId == *a);
auto second = q.popNext();
REQUIRE(second.has_value());
CHECK(second->track.id == "b");
CHECK(q.popNext() == std::nullopt);
}
TEST_CASE("QueueService enforces max size")
{
QueueService q;
CHECK(q.enqueue(track("a"), "t", 1).has_value());
CHECK_FALSE(q.enqueue(track("b"), "t", 1).has_value());
}
TEST_CASE("QueueService popIfNext detects stale peeks")
{
QueueService q;
auto a = q.enqueue(track("a"), "t", 100);
q.enqueue(track("b"), "t", 100).has_value();
REQUIRE(a.has_value());
auto peek = q.peekNext();
REQUIRE(peek.has_value());
// Queue edited after the peek: the peeked entry is removed.
auto removed = q.removeAt(0);
REQUIRE(removed.has_value());
// Commit must fail — "a" is gone, "b" is next now.
CHECK(q.popIfNext(peek->queueId) == std::nullopt);
auto next = q.popNext();
REQUIRE(next.has_value());
CHECK(next->track.id == "b");
}
TEST_CASE("QueueService shuffle plays every track exactly once")
{
QueueService q;
for (int i = 0; i < 10; ++i) {
REQUIRE(q.enqueue(track(std::to_string(i)), "t", 100).has_value());
}
q.setShuffle(true);
std::set<std::string> seen;
for (int i = 0; i < 10; ++i) {
auto e = q.popNext();
REQUIRE(e.has_value());
CHECK(seen.insert(e->track.id).second); // no duplicates
}
CHECK(q.empty());
CHECK(q.popNext() == std::nullopt);
}
TEST_CASE("QueueService shuffle survives removals and moves")
{
QueueService q;
for (int i = 0; i < 8; ++i) {
REQUIRE(q.enqueue(track(std::to_string(i)), "t", 100).has_value());
}
q.setShuffle(true);
// Consume a couple, then mutate the queue between picks.
std::set<std::string> seen;
auto consume = [&] {
auto e = q.popNext();
REQUIRE(e.has_value());
CHECK(seen.insert(e->track.id).second);
};
consume();
consume();
REQUIRE(q.removeAt(0).has_value());
REQUIRE(q.move(0, q.size() - 1).has_value());
REQUIRE(q.enqueue(track("new"), "t", 100).has_value());
// Drain: every pop must be a valid, never-seen entry (the index fixup
// must not point outside the queue or replay a track).
while (!q.empty()) {
consume();
}
CHECK(seen.size() == 8); // 8 original - 1 removed + 1 new
}
TEST_CASE("QueueService peekNext matches popNext under shuffle")
{
QueueService q;
for (int i = 0; i < 6; ++i) {
REQUIRE(q.enqueue(track(std::to_string(i)), "t", 100).has_value());
}
q.setShuffle(true);
while (!q.empty()) {
auto peek = q.peekNext();
REQUIRE(peek.has_value());
auto popped = q.popIfNext(peek->queueId);
REQUIRE(popped.has_value());
CHECK(popped->queueId == peek->queueId);
}
}
+199
View File
@@ -0,0 +1,199 @@
#include <doctest/doctest.h>
#include <echoion/core/sources/DirectUrlSource.hpp>
#include <echoion/core/sources/SourceRouter.hpp>
#include <memory>
using namespace Echoion;
using namespace Echoion::Core;
namespace
{
// Configurable fake source for router-behavior tests.
class FakeSource : public ITrackSource
{
public:
FakeSource(std::string name, std::chrono::milliseconds delay,
bool succeed) :
name_(std::move(name)), delay_(delay), succeed_(succeed)
{
}
std::atomic<int> calls{0};
[[nodiscard]] std::string_view name() const override
{
return name_;
}
[[nodiscard]] bool canHandle(const std::string&) const override
{
return true;
}
[[nodiscard]] bool isAvailable() const override { return true; }
[[nodiscard]] bool supportsSearch() const override
{
return false;
}
Api::Result<Api::SearchResult> search(std::string_view) override
{
return Api::fail(Api::ErrorCode::NotSupported, "no");
}
Api::Result<Api::TrackInfo>
resolve(const std::string&) override
{
return Api::fail(Api::ErrorCode::NotSupported, "no");
}
Api::Result<StreamHandle>
getStream(const Api::TrackInfo&) override
{
++calls;
std::this_thread::sleep_for(delay_);
if (succeed_) {
return StreamHandle{.url = "https://x/" + name_,
.isLocalFile = false,
.sourceName = name_};
}
return Api::fail(Api::ErrorCode::NetworkError, "boom");
}
private:
std::string name_;
std::chrono::milliseconds delay_;
bool succeed_;
};
Api::TrackInfo hedgeTrack(const std::string& id)
{
Api::TrackInfo t;
t.id = id;
t.originalUrl = "https://example.com/" + id;
return t;
}
} // namespace
TEST_CASE("SourceRouter hedges a slow first source")
{
auto slow = std::make_shared<FakeSource>(
"slow", std::chrono::milliseconds(2000), true);
auto fast = std::make_shared<FakeSource>(
"fast", std::chrono::milliseconds(20), true);
SourceRouter router;
router.setSources({slow, fast});
router.setOrder({"slow", "fast"});
router.setHedgeDelay(std::chrono::milliseconds(100));
const auto start = std::chrono::steady_clock::now();
auto handle = router.getStream(hedgeTrack("h1"));
const auto elapsed = std::chrono::steady_clock::now() - start;
REQUIRE(handle.has_value());
CHECK(handle->sourceName == "fast"); // hedge won
CHECK(elapsed < std::chrono::milliseconds(1000)); // didn't wait 2s
CHECK(slow->calls.load() == 1);
CHECK(fast->calls.load() == 1);
}
TEST_CASE("SourceRouter does not hedge when the first source is fast")
{
auto fast = std::make_shared<FakeSource>(
"fast", std::chrono::milliseconds(10), true);
auto second = std::make_shared<FakeSource>(
"second", std::chrono::milliseconds(10), true);
SourceRouter router;
router.setSources({fast, second});
router.setOrder({"fast", "second"});
router.setHedgeDelay(std::chrono::milliseconds(200));
auto handle = router.getStream(hedgeTrack("h2"));
REQUIRE(handle.has_value());
CHECK(handle->sourceName == "fast");
CHECK(second->calls.load() == 0); // never launched
}
TEST_CASE("SourceRouter falls through to a third source when the hedge "
"pair fails")
{
auto bad1 = std::make_shared<FakeSource>(
"bad1", std::chrono::milliseconds(10), false);
auto bad2 = std::make_shared<FakeSource>(
"bad2", std::chrono::milliseconds(10), false);
auto good = std::make_shared<FakeSource>(
"good", std::chrono::milliseconds(10), true);
SourceRouter router;
router.setSources({bad1, bad2, good});
router.setOrder({"bad1", "bad2", "good"});
router.setHedgeDelay(std::chrono::milliseconds(50));
auto handle = router.getStream(hedgeTrack("h3"));
REQUIRE(handle.has_value());
CHECK(handle->sourceName == "good");
}
TEST_CASE("SourceRouter hedgeDelay=0 keeps the sequential path")
{
auto slow = std::make_shared<FakeSource>(
"slow", std::chrono::milliseconds(100), true);
auto fast = std::make_shared<FakeSource>(
"fast", std::chrono::milliseconds(10), true);
SourceRouter router;
router.setSources({slow, fast});
router.setOrder({"slow", "fast"});
router.setHedgeDelay(std::chrono::milliseconds(0));
auto handle = router.getStream(hedgeTrack("h4"));
REQUIRE(handle.has_value());
CHECK(handle->sourceName == "slow"); // sequential: first wins
CHECK(fast->calls.load() == 0);
}
TEST_CASE("SourceRouter falls through a failing source and caches streams")
{
auto dead = std::make_shared<FakeSource>(
"dead", std::chrono::milliseconds(10), false);
auto good = std::make_shared<FakeSource>(
"good", std::chrono::milliseconds(10), true);
SourceRouter router;
router.setSources({dead, good});
router.setOrder({"dead", "good"});
router.setHedgeDelay(std::chrono::milliseconds(0)); // sequential
auto track = hedgeTrack("fall1");
auto handle = router.getStream(track);
REQUIRE(handle.has_value());
CHECK(handle->sourceName == "good"); // fell through the dead source
CHECK(good->calls.load() == 1);
// Second getStream must be served from cache — the source is not hit.
auto cached = router.getStream(track);
REQUIRE(cached.has_value());
CHECK(good->calls.load() == 1);
// Invalidation drops the cache: the next getStream resolves again.
router.invalidate(track.id);
auto refreshed = router.getStream(track);
REQUIRE(refreshed.has_value());
CHECK(good->calls.load() == 2);
}
TEST_CASE("DirectUrlSource passes through audio URLs only")
{
DirectUrlSource source;
CHECK(source.canHandle("https://radio.example/stream"));
CHECK(source.canHandle("http://files.example/song.mp3?token=x"));
CHECK_FALSE(source.canHandle("https://www.youtube.com/watch?v=abc"));
CHECK_FALSE(source.canHandle("plain text query"));
auto track = source.resolve("https://radio.example/stream");
REQUIRE(track.has_value());
auto handle = source.getStream(*track);
REQUIRE(handle.has_value());
CHECK(handle->url == "https://radio.example/stream");
}
+128
View File
@@ -0,0 +1,128 @@
#include <doctest/doctest.h>
#include <echoion/core/TrackCache.hpp>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <string>
#include <thread>
using Echoion::Core::TrackCache;
namespace
{
struct TempDir {
std::filesystem::path path;
TempDir()
{
path = std::filesystem::temp_directory_path() /
("echoion-cache-test-" +
std::to_string(
std::chrono::steady_clock::now()
.time_since_epoch()
.count()));
std::filesystem::create_directories(path);
}
~TempDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
std::string makeFile(const std::filesystem::path& dir,
const std::string& name, size_t bytes)
{
const auto p = dir / name;
std::ofstream out(p, std::ios::binary);
out << std::string(bytes, 'x');
return p.string();
}
} // namespace
TEST_CASE("TrackCache::parseSize handles common suffixes")
{
CHECK(TrackCache::parseSize("1024") == 1024);
CHECK(TrackCache::parseSize("1KB") == 1024);
CHECK(TrackCache::parseSize("500MB") == 500ull << 20);
CHECK(TrackCache::parseSize("1GB") == 1ull << 30);
CHECK(TrackCache::parseSize("2gb") == 2ull << 30);
CHECK(TrackCache::parseSize("garbage") == 0);
CHECK(TrackCache::parseSize("") == 0);
}
TEST_CASE("TrackCache stores, looks up and owns files")
{
TempDir staging;
TempDir cacheDir;
TrackCache cache(
TrackCache::Config{.enabled = true,
.maxBytes = 1 << 20,
.ttl = std::chrono::seconds(3600)},
cacheDir.path);
CHECK_FALSE(cache.lookup("videoA").has_value());
const auto source = makeFile(staging.path, "download.m4a", 100);
const auto cachedPath = cache.store("videoA", source);
CHECK(cachedPath != source);
CHECK(cache.owns(cachedPath));
CHECK_FALSE(cache.owns(source));
CHECK_FALSE(std::filesystem::exists(source)); // moved, not copied
auto hit = cache.lookup("videoA");
REQUIRE(hit.has_value());
CHECK(*hit == cachedPath);
CHECK(std::filesystem::exists(cachedPath));
}
TEST_CASE("TrackCache evicts LRU past the size budget")
{
TempDir staging;
TempDir cacheDir;
TrackCache cache(
TrackCache::Config{.enabled = true,
.maxBytes = 250, // fits two 100-byte files
.ttl = std::chrono::seconds(3600)},
cacheDir.path);
(void)cache.store("first", makeFile(staging.path, "a.m4a", 100));
std::this_thread::sleep_for(std::chrono::milliseconds(20));
(void)cache.store("second", makeFile(staging.path, "b.m4a", 100));
std::this_thread::sleep_for(std::chrono::milliseconds(20));
// Third store pushes the total to 300 > 250: "first" (oldest) goes.
(void)cache.store("third", makeFile(staging.path, "c.m4a", 100));
CHECK_FALSE(cache.lookup("first").has_value());
CHECK(cache.lookup("second").has_value());
CHECK(cache.lookup("third").has_value());
}
TEST_CASE("TrackCache expires entries past the TTL")
{
TempDir staging;
TempDir cacheDir;
TrackCache cache(TrackCache::Config{.enabled = true,
.maxBytes = 1 << 20,
.ttl = std::chrono::seconds(0)},
cacheDir.path);
(void)cache.store("old", makeFile(staging.path, "a.m4a", 10));
std::this_thread::sleep_for(std::chrono::milliseconds(20));
CHECK_FALSE(cache.lookup("old").has_value());
}
TEST_CASE("TrackCache disabled is a transparent pass-through")
{
TempDir staging;
TempDir cacheDir;
TrackCache cache(TrackCache::Config{.enabled = false}, cacheDir.path);
const auto source = makeFile(staging.path, "a.m4a", 10);
CHECK(cache.store("x", source) == source);
CHECK(std::filesystem::exists(source));
CHECK_FALSE(cache.lookup("x").has_value());
}
+239
View File
@@ -0,0 +1,239 @@
#include <doctest/doctest.h>
#include "helpers/StubHttpServer.hpp"
#include <echoion/core/NetworkClient.hpp>
#include <echoion/core/sources/YandexMusicSource.hpp>
#include <memory>
#include <openssl/evp.h>
using namespace Echoion;
using namespace Echoion::Core;
using Echoion::Test::StubHttpServer;
namespace
{
std::shared_ptr<NetworkClient> makeNetwork()
{
auto n = std::make_shared<NetworkClient>();
REQUIRE(n->initialize().has_value());
return n;
}
std::string md5hexRef(const std::string& data)
{
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int length = 0;
REQUIRE(EVP_Digest(data.data(), data.size(), digest, &length,
EVP_md5(), nullptr) == 1);
static constexpr char hex[] = "0123456789abcdef";
std::string out;
for (unsigned int i = 0; i < length; ++i) {
out.push_back(hex[digest[i] >> 4]);
out.push_back(hex[digest[i] & 0xF]);
}
return out;
}
} // namespace
TEST_CASE("YandexMusicSource availability depends on the token")
{
auto network = makeNetwork();
YandexMusicSource source(network);
source.configure(true, "");
CHECK_FALSE(source.isAvailable());
CHECK_FALSE(source.canHandle(
"https://music.yandex.com/album/123/track/456"));
source.configure(true, "token");
CHECK(source.isAvailable());
CHECK(source.canHandle("https://music.yandex.com/album/123/track/456"));
CHECK(source.canHandle("https://music.yandex.com/track/456"));
CHECK(source.canHandle("https://music.yandex.com/album/123"));
CHECK(source.canHandle(
"https://music.yandex.com/users/foo/playlists/42"));
CHECK_FALSE(source.canHandle("https://www.youtube.com/watch?v=abc"));
CHECK_FALSE(source.canHandle("free text"));
source.configure(false, "token");
CHECK_FALSE(source.isAvailable());
}
TEST_CASE("YandexMusicSource resolves track metadata")
{
StubHttpServer stub;
stub.route("/tracks/456", {.body = R"({
"result": [{
"id": "456",
"title": "Yandex Song",
"durationMs": 245000,
"coverUri": "avatars.yandex.net/get-music/abc/%%",
"artists": [{"name": "First"}, {"name": "Second"}],
"albums": [{"id": 123}]
}]
})"});
auto network = makeNetwork();
YandexMusicSource source(network, stub.baseUrl());
source.configure(true, "token");
auto track =
source.resolve("https://music.yandex.com/album/123/track/456");
REQUIRE(track.has_value());
CHECK(track->title == "Yandex Song");
CHECK(track->artist == "First, Second");
CHECK(track->duration == std::chrono::milliseconds(245000));
CHECK(track->thumbnailUrl ==
"https://avatars.yandex.net/get-music/abc/200x200");
CHECK(track->originalUrl ==
"https://music.yandex.com/album/123/track/456");
}
TEST_CASE("YandexMusicSource builds the signed stream URL")
{
StubHttpServer stub;
// download-info offers two codecs; the mp3 with the highest bitrate
// must win.
stub.route("/tracks/456/download-info",
{.body = std::string(R"({
"result": [
{"codec": "aac", "bitrateInKbps": 320,
"downloadInfoUrl": ")") + stub.baseUrl() +
R"(/info-aac"},
{"codec": "mp3", "bitrateInKbps": 192,
"downloadInfoUrl": ")" + stub.baseUrl() +
R"(/info-192"},
{"codec": "mp3", "bitrateInKbps": 320,
"downloadInfoUrl": ")" + stub.baseUrl() +
R"(/info-320"}
]
})"});
stub.route("/info-320",
{.contentType = "text/xml",
.body = "<download-info><host>cdn.example</host>"
"<path>/music/file.mp3</path><ts>12345</ts>"
"<region>ru</region><s>secretvalue</s>"
"</download-info>"});
auto network = makeNetwork();
YandexMusicSource source(network, stub.baseUrl());
source.configure(true, "token");
Api::TrackInfo track;
track.originalUrl = "https://music.yandex.com/album/123/track/456";
auto handle = source.getStream(track);
REQUIRE(handle.has_value());
const std::string expectedSign = md5hexRef(
std::string("XGRlBW9FXlekgbPrRHuSiA") + "music/file.mp3" +
"secretvalue");
CHECK(handle->url == "https://cdn.example/get-mp3/" + expectedSign +
"/12345/music/file.mp3");
CHECK(handle->sourceName == "yandex");
}
TEST_CASE("YandexMusicSource searches for tracks")
{
StubHttpServer stub;
stub.route("/search*", {.body = R"({
"result": {"tracks": {"results": [
{"id": "111", "title": "Lofi One", "durationMs": 180000,
"artists": [{"name": "Artist A"}], "albums": [{"id": 5}]},
{"id": "222", "title": "Lofi Two", "durationMs": 200000,
"artists": [{"name": "Artist B"}], "albums": [{"id": 6}]}
]}}
})"});
auto network = makeNetwork();
YandexMusicSource source(network, stub.baseUrl());
source.configure(true, "token");
auto results = source.search("lofi");
REQUIRE(results.has_value());
REQUIRE(results->tracks.size() == 2);
CHECK(results->tracks[0].title == "Lofi One");
CHECK(results->tracks[0].artist == "Artist A");
CHECK(results->tracks[1].title == "Lofi Two");
CHECK(results->tracks[0].originalUrl ==
"https://music.yandex.com/album/5/track/111");
}
TEST_CASE("YandexMusicSource lists related tracks for radio autoplay")
{
StubHttpServer stub;
stub.route("/tracks/456/similar", {.body = R"({
"result": {"similarTracks": [
{"id": "777", "title": "Similar One", "durationMs": 190000,
"artists": [{"name": "Artist X"}], "albums": [{"id": 7}]},
{"id": "888", "title": "Similar Two", "durationMs": 210000,
"artists": [{"name": "Artist Y"}], "albums": [{"id": 8}]}
]}
})"});
auto network = makeNetwork();
YandexMusicSource source(network, stub.baseUrl());
source.configure(true, "token");
auto results = source.related("456", 10);
REQUIRE(results.has_value());
REQUIRE(results->size() == 2);
CHECK((*results)[0].title == "Similar One");
CHECK((*results)[0].artist == "Artist X");
CHECK((*results)[0].source == Api::TrackSource::Yandex);
CHECK((*results)[0].originalUrl ==
"https://music.yandex.com/album/7/track/777");
CHECK((*results)[1].title == "Similar Two");
}
TEST_CASE("YandexMusicSource related is unavailable without a token")
{
auto network = makeNetwork();
YandexMusicSource source(network);
source.configure(true, "");
CHECK_FALSE(source.related("456").has_value());
}
TEST_CASE("YandexMusicSource search is unavailable without a token")
{
auto network = makeNetwork();
YandexMusicSource source(network);
source.configure(true, "");
CHECK_FALSE(source.search("lofi").has_value());
}
TEST_CASE("YandexMusicSource lists album and playlist tracks")
{
StubHttpServer stub;
stub.route("/albums/123/with-tracks", {.body = R"({
"result": {"volumes": [
[{"id": "1", "title": "A1", "artists": [{"name": "X"}]},
{"id": "2", "title": "A2", "artists": [{"name": "X"}]}],
[{"id": "3", "title": "B1", "artists": [{"name": "X"}]}]
]}
})"});
stub.route("/users/foo/playlists/42", {.body = R"({
"result": {"tracks": [
{"track": {"id": "9", "title": "P1", "artists": [{"name": "Y"}]}},
{"track": {"id": "10", "title": "P2", "artists": [{"name": "Y"}]}}
]}
})"});
auto network = makeNetwork();
YandexMusicSource source(network, stub.baseUrl());
source.configure(true, "token");
auto album =
source.playlistTracks("https://music.yandex.com/album/123");
REQUIRE(album.has_value());
REQUIRE(album->size() == 3);
CHECK((*album)[0].title == "A1");
CHECK((*album)[2].title == "B1");
auto playlist = source.playlistTracks(
"https://music.yandex.com/users/foo/playlists/42");
REQUIRE(playlist.has_value());
REQUIRE(playlist->size() == 2);
CHECK((*playlist)[1].title == "P2");
}
+97
View File
@@ -0,0 +1,97 @@
#pragma once
#include <algorithm>
#include <chrono>
#include <mutex>
#include <span>
#include <vector>
namespace Echoion::Test
{
// Captures every chunk the playback pipeline emits through the audio
// callback and answers the questions the gapless tests care about:
// how many samples arrived, whether any chunk was pure silence, and the
// longest wall-clock stall between consecutive chunks.
class FakeAudioSink
{
public:
void onChunk(std::span<const short> samples)
{
const auto now = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lock(mutex_);
if (chunkCount_ > 0) {
auto gap =
std::chrono::duration_cast<std::chrono::milliseconds>(
now - lastChunkTime_);
maxInterChunkGap_ = std::max(maxInterChunkGap_, gap);
}
lastChunkTime_ = now;
++chunkCount_;
totalSamples_ += samples.size();
const bool allZero = std::ranges::all_of(
samples, [](short s) { return s == 0; });
if (allZero) {
++silentChunkCount_;
}
pcm_.insert(pcm_.end(), samples.begin(), samples.end());
}
[[nodiscard]] std::size_t chunkCount() const
{
std::lock_guard<std::mutex> lock(mutex_);
return chunkCount_;
}
[[nodiscard]] std::size_t totalSamples() const
{
std::lock_guard<std::mutex> lock(mutex_);
return totalSamples_;
}
[[nodiscard]] std::size_t silentChunkCount() const
{
std::lock_guard<std::mutex> lock(mutex_);
return silentChunkCount_;
}
[[nodiscard]] std::chrono::milliseconds maxInterChunkGap() const
{
std::lock_guard<std::mutex> lock(mutex_);
return maxInterChunkGap_;
}
// Full captured PCM stream (interleaved S16), for waveform-level
// assertions such as "no silent seam at the track boundary".
[[nodiscard]] std::vector<short> pcm() const
{
std::lock_guard<std::mutex> lock(mutex_);
return pcm_;
}
void reset()
{
std::lock_guard<std::mutex> lock(mutex_);
chunkCount_ = 0;
totalSamples_ = 0;
silentChunkCount_ = 0;
maxInterChunkGap_ = {};
pcm_.clear();
}
private:
mutable std::mutex mutex_;
std::size_t chunkCount_ = 0;
std::size_t totalSamples_ = 0;
std::size_t silentChunkCount_ = 0;
std::chrono::milliseconds maxInterChunkGap_{0};
std::chrono::steady_clock::time_point lastChunkTime_{};
std::vector<short> pcm_;
};
} // namespace Echoion::Test
+146
View File
@@ -0,0 +1,146 @@
#pragma once
#include <atomic>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <map>
#include <mutex>
#include <string>
#include <thread>
namespace Echoion::Test
{
// Tiny synchronous HTTP/1.1 server for source-router tests. Register
// canned responses per path (query string included); unknown paths get
// 404. Runs its accept loop on one background thread and handles one
// request per connection, which is all the NetworkClient needs.
class StubHttpServer
{
public:
struct Response {
int status = 200;
std::string contentType = "application/json";
std::string body;
};
StubHttpServer() :
acceptor_(io_, {boost::asio::ip::make_address("127.0.0.1"), 0})
{
port_ = acceptor_.local_endpoint().port();
thread_ = std::thread([this] { run(); });
}
~StubHttpServer()
{
stopping_ = true;
// A synchronous accept(2) is NOT interrupted by closing the
// fd from another thread on Linux; poke it with a throwaway
// connection so the loop observes stopping_.
try {
boost::asio::io_context io;
boost::asio::ip::tcp::socket s(io);
s.connect({boost::asio::ip::make_address("127.0.0.1"),
port_});
} catch (...) {
// Server may already be gone; nothing to unblock.
}
boost::system::error_code ec;
acceptor_.close(ec);
if (thread_.joinable()) {
thread_.join();
}
}
[[nodiscard]] uint16_t port() const { return port_; }
[[nodiscard]] std::string baseUrl() const
{
return "http://127.0.0.1:" + std::to_string(port_);
}
// Exact-match route ("/api/v1/stats") or prefix route when the
// registered path ends with '*' ("/api/v1/videos/*").
void route(std::string path, Response response)
{
std::lock_guard<std::mutex> lock(mutex_);
routes_[std::move(path)] = std::move(response);
}
[[nodiscard]] std::size_t requestCount() const
{
return requestCount_.load();
}
private:
void run()
{
while (!stopping_) {
boost::system::error_code ec;
boost::asio::ip::tcp::socket socket(io_);
acceptor_.accept(socket, ec);
if (ec) {
break; // closed by destructor
}
handle(socket);
}
}
void handle(boost::asio::ip::tcp::socket& socket)
{
namespace http = boost::beast::http;
try {
boost::beast::flat_buffer buffer;
http::request<http::string_body> req;
http::read(socket, buffer, req);
++requestCount_;
const Response canned = lookup(std::string(req.target()));
http::response<http::string_body> res{
static_cast<http::status>(canned.status),
req.version()};
res.set(http::field::content_type, canned.contentType);
res.body() = canned.body;
res.prepare_payload();
http::write(socket, res);
boost::system::error_code ec;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send,
ec);
} catch (const std::exception&) {
// Connection torn down mid-request; irrelevant for tests.
}
}
Response lookup(const std::string& target)
{
std::lock_guard<std::mutex> lock(mutex_);
if (auto it = routes_.find(target); it != routes_.end()) {
return it->second;
}
for (const auto& [path, response] : routes_) {
if (path.ends_with('*') &&
target.starts_with(
std::string_view(path).substr(0, path.size() - 1))) {
return response;
}
}
return Response{.status = 404,
.contentType = "text/plain",
.body = "not found"};
}
boost::asio::io_context io_;
boost::asio::ip::tcp::acceptor acceptor_;
uint16_t port_ = 0;
std::thread thread_;
std::atomic<bool> stopping_{false};
std::atomic<std::size_t> requestCount_{0};
std::mutex mutex_;
std::map<std::string, Response> routes_;
};
} // namespace Echoion::Test
+2
View File
@@ -0,0 +1,2 @@
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest/doctest.h>