- Fix import paths to use public pmoaudio API instead of private modules
- Change AudioError::ConfigurationError to ProcessingError
- Use Node::new_with_input() instead of non-existent Node::new()
- Fix borrow checker issues in IcyClientStream::poll_read()
- Use flatten() on metadata getters to unwrap Result<Option<T>>
- Fix chunk.get_sample_rate() to chunk.sample_rate()
- Remove get_album_artist() call (not in TrackMetadata trait)
- Update pmoparadise Cargo.toml to enable pmoserver feature for axum
- Simplify example init_logging() call to match new pmoserver API
Creates a new example demonstrating StreamingFlacSink usage with pmoserver
for real-world HTTP streaming testing with media players like VLC.
Features:
- Uses pmoserver instead of raw Axum for realistic testing
- Streams a single Radio Paradise block over HTTP
- Supports both pure FLAC and ICY metadata modes
- Provides /test/stream endpoint for streaming
- Provides /test/metadata endpoint for JSON metadata queries
- Includes health check endpoint
Usage:
cargo run --example stream_block --features full -- <channel_id>
Testing with VLC:
# Pure FLAC mode
vlc http://localhost:8080/test/stream
# ICY metadata mode (Now Playing)
vlc --http-continuous --icy-metadata http://localhost:8080/test/stream
Dependencies:
- Requires pmoserver for HTTP server
- Requires StreamingFlacSink from pmoaudio-ext (http-stream feature)
- Integrated with full feature set (pmoaudio + pmoaudio-ext + pmoserver)
This commit fixes two critical issues that prevented covers from being
cached for tracks beyond the first one in Radio Paradise blocks:
1. FlacCacheSink Phase 3 metadata loss:
- When TrackBoundary for track N+1 was received during Phase 3
of track N, the metadata was discarded
- Main loop would then wait for a NEW TrackBoundary that never came
- Solution: Store metadata in next_track_metadata variable and reuse
it in next iteration
- Added wait_for_first_audio_chunk() for when metadata is pre-loaded
2. RadioParadiseStreamSource not sending subsequent TrackBoundaries:
- Code was only checking elapsed_ms >= song.elapsed in loop
- Added debug logging to track TrackBoundary sending
- Improved comments explaining first song special handling
Test results:
- Successfully cached covers for 4 consecutive tracks
- Verified with test showing "Successfully cached cover" for each track
- Cover cache directory contains 4 .webp files with complete markers
Files modified:
- pmoaudio-ext/src/sinks/flac_cache_sink.rs
- pmoparadise/src/radio_paradise_stream_source.rs
Corrige un bug critique qui empêchait la mise en cache des covers :
- RadioParadiseStreamSource envoie maintenant un TrackBoundary pour la première
song IMMÉDIATEMENT après le TopZeroSync, AVANT le premier chunk audio
- Cela garantit que FlacCacheSink reçoit les métadonnées (incluant cover_url)
dès le début du traitement
Le problème :
- Avant, le TrackBoundary n'était envoyé que quand elapsed_ms >= song.elapsed
- Pour la première song avec elapsed > 0, le TrackBoundary arrivait APRÈS
plusieurs chunks audio
- FlacCacheSink recevait le premier chunk SANS métadonnées
- Quand le prebuffer se terminait, track_metadata était None
- Les métadonnées (incluant cover_url) n'étaient jamais copiées dans le cache
- Résultat : aucune cover n'était mise en cache
La solution :
- Envoyer explicitement un TrackBoundary pour la première song avant de
commencer la boucle de chunks
- Les songs suivantes continuent d'être gérées par la logique existante
Test validé :
✓ RadioParadiseStreamSource configure cover_url correctement
✓ FlacCacheSink reçoit cover_url
✓ Les covers sont téléchargées et mises en cache
✓ Les logs montrent : "Successfully cached cover for pk ... with cover pk ..."
Corrige un bug critique de race condition dans RadioParadiseStreamSource :
- Rend song_to_metadata() async et attend que toutes les métadonnées soient configurées
- Supprime le tokio::spawn() qui causait un retour prématuré des métadonnées
- Garantit que cover_url est disponible quand FlacCacheSink lit les métadonnées
- Ajoute des logs de debug pour tracer la configuration des métadonnées
- Remplace eprintln! par tracing::warn! pour une meilleure cohérence
Corrige également un warning de compilation :
- Retire le `mut` inutile sur la variable `writer` dans play_and_cache.rs
Le problème : song_to_metadata() retournait les métadonnées avant que
la task asynchrone ne finisse de les configurer, ce qui causait un
cover_url manquant quand FlacCacheSink essayait de cacher les covers.
Améliore la gestion du cache des covers dans FlacCacheSink :
- Remplace les avertissements génériques par des logs détaillés (debug/info/warn)
- Corrige la gestion des erreurs en retirant le `let _ =` qui ignorait les résultats
- Ajoute des logs de debug pour tracer le processus de mise en cache des covers
- Améliore la gestion des erreurs avec des messages plus informatifs
Corrige la playlist de l'exemple play_and_cache :
- Remplace create_persistent_playlist par get_write_handle pour créer une playlist éphémère
- Une playlist persistante n'est pas nécessaire pour cet exemple de démonstration
Changes:
- Add TimerNode (pmoaudio/src/nodes/timer_node.rs): Rate-limits audio chunk flow based on timestamps with configurable max_lead_time
- Integrate TimerNode into play_and_cache.rs pipeline: PlaylistSource → TimerNode (3s pacing) → AudioSink
- Improve EOF retry in playlist_source.rs: Wait for prebuffer (512KB) before decoding, retry on temporary EOF with 200ms delay
- Export TimerNode in pmoaudio lib.rs and nodes/mod.rs
Known issue: Cache files may still be truncated when TrackBoundary arrives before pump completes flushing.
This requires allowing parallel write tasks as suggested.
Problem Analysis:
- All FLAC files had the same pk (071c5713d5cf485ca688832207bef0f9)
- Root cause: read() can return < 1024 bytes on first call
- If read returned only 400 bytes:
* header.len() = 400
* 400 > 512 = false
* Used header[..] (first 400 bytes = FLAC header)
* All FLAC files have identical headers → same pk!
Solution:
- Added read_exact_or_eof() that loops until 1024 bytes read (or EOF)
- Guarantees we skip FLAC header and use actual audio content
- Works for small files (< 512 bytes) and large files (>= 1024 bytes)
Additional Feature:
- Added AudioSink::with_null_output() for testing without audio device
- Added --null-audio flag to play_and_cache example
- Allows testing in containerized environments
Changes:
1. pmocache/src/download.rs: Added read_exact_or_eof()
2. pmocache/src/cache.rs: Use read_exact_or_eof() for pk calculation
3. pmoaudio/src/nodes/audio_sink.rs: Added null output mode
4. pmoparadise/examples/play_and_cache.rs: Added --null-audio flag
Test Results:
- New pk: 83702c1cbca72074ebf7c123336786ea (was 071c...)
- Null audio output works correctly
- Ready for full testing
Cette correction implémente le cache progressif et le streaming pour permettre
un démarrage quasi immédiat de la lecture pendant le téléchargement.
## Changements dans FlacCacheSink (pmoaudio-ext)
Avant :
- Accumulait tout le FLAC en mémoire dans un buffer
- Attendait la fin complète de l'encodage avant d'ajouter au cache
- Ajoutait à la playlist seulement après ingestion complète
Après :
- Passe le flux FLAC directement à add_from_reader
- add_from_reader retourne dès que le prebuffer (512 KB) est atteint
- Le PK est ajouté à la playlist immédiatement après le prebuffer
- L'encodage et l'écriture continuent en arrière-plan
## Changements dans play_and_cache.rs
- Suppression du sleep de 2 secondes avant le démarrage de la lecture
- Ajout de commentaire expliquant le mécanisme de prebuffer
- La lecture démarre dès que le prebuffer est atteint (~1-2 secondes)
## Résultat
La musique démarre maintenant presque immédiatement après le début du
téléchargement (temps du prebuffer) au lieu d'attendre la fin du
téléchargement complet du premier morceau.
Fix "PlaylistManager not initialized" error without creating circular
dependency between pmoparadise and pmoupnp.
Changes:
- Add AUDIO_CACHE static to pmoplaylist/manager.rs
- Add register_audio_cache() function to register cache
- Export register_audio_cache from pmoplaylist lib.rs
- Update audio_cache() to check local registry first, then pmoupnp
- Update play_and_cache example to use pmoplaylist::register_audio_cache
- Remove pmoupnp::register_*_cache functions (not needed)
The example now calls pmoplaylist::register_audio_cache() to make
the cache available for pk validation in WriteHandle::push().
Fix "PlaylistManager not initialized" error in play_and_cache example.
The error occurred because pmoplaylist's WriteHandle calls
pmoupnp::get_audio_cache() to validate cache pks, but the global
cache registry wasn't initialized.
Changes:
- Add register_audio_cache() and register_cover_cache() functions
- Export them from pmoupnp lib.rs
- Call them in play_and_cache example after creating caches
This mirrors how UpnpServer initializes the cache registry.
- Add pmoconfig to the 'full' feature so PlaylistManager can auto-initialize
- Update play_and_cache example to use AudioSink::new() without volume
- Remove unused PlaylistManager import
Without pmoconfig feature enabled, PlaylistManager::get() fails with
"PlaylistManager not initialized" error.
Corrections pour que l'exemple utilise les bonnes API:
- Utilisation directe de Cache::new() au lieu de méthodes de config
- Suppression des appels à root() qui n'existent pas
- Utilisation du singleton PlaylistManager() au lieu de new()
- Ajout de cache-sink comme dépendance de playlist feature dans pmoaudio-ext
L'exemple devrait maintenant compiler correctement avec:
cargo run --example play_and_cache --features full -- <channel_id>
Crée un nouvel exemple complet qui démontre l'utilisation de tout le pipeline:
- Téléchargement d'un bloc Radio Paradise
- Cache FLAC via FlacCacheSink
- Playlist alimentée automatiquement
- Lecture en temps réel via PlaylistSource et AudioSink
Architecture à deux pipelines :
Pipeline 1 (Download & Cache):
RadioParadiseStreamSource → FlacCacheSink (avec playlist abonnée)
Pipeline 2 (Playback):
PlaylistSource (lit la playlist) → AudioSink (joue l'audio)
Les deux pipelines s'exécutent en parallèle, permettant la lecture pendant le
téléchargement.
Modifications:
- Ajout pmoaudio-ext avec feature playlist dans pmoparadise
- Nouvelle feature "full" combinant pmoaudio + pmoaudio-ext
- Logs détaillés à tous les niveaux (DEBUG)
Usage: cargo run --example play_and_cache --features full -- <channel_id>
Ajoute la possibilité de configurer le channel par défaut de Radio Paradise
de manière persistante et user-friendly.
Fonctionnalités :
- get_paradise_default_channel() : récupère le channel configuré (défaut: 0/main)
- set_paradise_default_channel(u8) : définit le channel par défaut
- Accepte DEUX formats dans le fichier YAML :
* Noms conviviaux : "main", "mellow", "rock", "eclectic"
* IDs numériques : 0, 1, 2, 3
- Stocke les valeurs comme chaînes conviviales pour la lisibilité
- Validation automatique avec fallback sur "main" si invalide
- Persistence automatique de la valeur par défaut lors du premier accès
Exemple de configuration YAML :
```yaml
sources:
radio_paradise:
enabled: true
default_channel: mellow # ou 1
```
Cette amélioration rend la configuration plus accessible aux utilisateurs
qui préfèrent un channel autre que Main Mix par défaut.
Corrections :
1. Supprimé le commentaire obsolète sur block_base (ligne 277)
2. Créé la constante DEFAULT_CHANNEL pour éviter de coder "0" en dur
3. Utilisé DEFAULT_CHANNEL dans with_client(), ClientBuilder::default() et tests
4. Amélioré la documentation de with_client() pour guider vers le builder
Bien que with_client() et ClientBuilder::default() aient encore une structure
similaire, ils utilisent maintenant les mêmes constantes, réduisant ainsi
le risque d'incohérence lors de modifications futures.
Supprime complètement la duplication d'information en transformant
block_base d'un champ stocké en une méthode calculée dynamiquement.
Changements:
- Supprimé le champ block_base de RadioParadiseClient
- Ajouté la constante BLOCK_BASE_URL pour éviter la duplication de l'URL
- Transformé block_base en méthode publique qui calcule à partir de channel
- Simplifié with_client() et clone_with_channel()
- Simplifié le builder qui n'a plus besoin d'initialiser block_base
Cette approche garantit que block_base est toujours cohérent avec channel,
éliminant définitivement toute possibilité de bug de synchronisation.
Le bug identifié était que le block_base n'était pas synchronisé avec
le channel dans le ClientBuilder, causant le téléchargement du même
bloc pour différents channels.
Changements:
- Supprimé le champ block_base du ClientBuilder (duplication)
- Supprimé la constante DEFAULT_BLOCK_BASE (plus nécessaire)
- Supprimé la méthode .block_base() du builder (complexité inutile)
- Le block_base est maintenant calculé dynamiquement dans build()
à partir du channel, éliminant toute possibilité de désynchronisation
Cette approche suit le principe DRY et élimine une source de bugs.
Add a new example that demonstrates downloading a complete Radio Paradise
block and saving each track as a separate FLAC file.
The example:
- Takes a channel ID as argument (0-3)
- Fetches current block metadata
- Creates an output directory ./rp_channel_{id}block{blockid}
- Uses RadioParadiseStreamSource to stream and decode the block
- Uses FlacFileSink to automatically detect TrackBoundary markers
- Saves each track as a separate FLAC file with metadata
Example usage:
cargo run --example download_block --features=pmoaudio -- 0
This demonstrates the full pipeline integration between pmoparadise
and pmoaudio, showing how RadioParadiseStreamSource and FlacFileSink
work together to handle multi-track FLAC blocks seamlessly.
Add async_trait annotation to RadioParadiseExt trait and its implementation
to suppress the "async fn in public traits" warning.
This is the recommended approach for traits with async methods as it ensures
proper Future bounds (Send) are generated.
The old streaming API has been completely replaced by RadioParadiseStreamSource
which integrates directly with the pmoaudio pipeline.
Removed:
- src/stream.rs (179 lines) - BlockStream, stream_block(), download_block()
- src/track.rs - Per-track extraction functionality
- examples/stream_block.rs - Obsolete streaming example
- examples/extract_track.rs - Per-track extraction example
- Feature "per-track" and dependencies (hound, tempfile)
Updated:
- Cargo.toml: Removed per-track feature and obsolete examples
- lib.rs: Removed module declarations and re-exports
The new RadioParadiseStreamSource provides:
- Direct integration with pmoaudio pipeline
- FLAC decoding via pmoflac
- Automatic TrackBoundary insertion
- Better performance and lower latency
Changes:
1. Updated pmoserver_ext.rs to use channels module:
- Changed imports from paradise:: to channels::
- Now uses ChannelDescriptor from channels module
- No longer depends on paradise orchestration code
2. Updated lib.rs:
- Added pub mod channels
- Maintains existing modules for now (will evaluate removal later)
3. Verification:
- All tests pass (25/25)
- No dead code warnings
- Compilation successful with all features
The REST API is now simplified to provide only direct Radio Paradise
API access without the heavy orchestration layer.
Changes:
1. Removed dead code from paradise/worker.rs:
- Unused process_song() method
- Unused DecodedBlock struct
- Unused helper functions: song_duration_ms, ms_to_frames, decode_block_audio
2. Simplified pmoserver_ext.rs (840 → 383 lines):
- Removed complex orchestration endpoints (status, playlist, history, streaming)
- Kept only simple API access endpoints:
* /now-playing
* /block/current
* /block/{event_id}
* /channels
- Removed dependencies on RadioParadiseSource and ParadiseChannel
3. Created channels.rs:
- Extracted channel definitions from paradise/channel.rs
- Pure data module with no orchestration logic
- Contains: ParadiseChannelKind, ChannelDescriptor, ALL_CHANNELS
Note: This is work in progress. Still need to update lib.rs and remove
unused modules once dependencies are fully resolved.
Add support for 32-bit integer audio samples to match FileSource and
HttpSource capabilities, ensuring complete bit depth coverage.
Changes:
- Add I32 case to pcm_to_audio_segment() for 32-bit stereo samples
- Update output_type() comment to document 16/24/32-bit support
- Note that bit depth is auto-detected from FLAC header via pmoflac
The implementation now supports the full range of FLAC bit depths:
- 16-bit: AudioChunk::I16 (most common)
- 24-bit: AudioChunk::I24 (high quality)
- 32-bit: AudioChunk::I32 (maximum precision)
pmoflac reads bits_per_sample from the FLAC STREAMINFO header
(decoder.rs:97), so the actual bit depth is determined by the source
stream, not hardcoded.
Verified: cargo check passes successfully.
Remove unused FFmpeg-based progressive streaming implementation that was
never completed and is not used anywhere in the codebase.
Changes:
- Delete src/ffmpeg_streaming.rs (173 lines of unfinished code with TODOs)
- Remove ffmpeg module import from lib.rs
- Remove ffmpeg feature from Cargo.toml
- Remove ffmpeg-next dependency from Cargo.toml
The current implementation uses claxon (StreamingPCMDecoder) and symphonia
(decode_block_audio) for FLAC decoding, which are fully functional.
Verified: cargo check passes successfully after removal.
Problem:
- Used `let _ = metadata.set_title(...)` which creates unawaited Future
- Futures were never executed → metadata fields never set!
- Ignored Result<(), MetadataError> which could contain errors
Solution:
- Spawn tokio task to configure metadata asynchronously
- Properly await all set_*() calls
- Handle errors with eprintln! warnings instead of silent ignore
- Clone all data upfront for the async task
Type info:
- metadata: MemoryTrackMetadata (concrete type)
- Returns: Arc<RwLock<dyn TrackMetadata>> (trait object)
- Methods: async fn set_*(&mut self) -> MetadataResult<()>
All 7 tests still pass ✅
Refactored RadioParadiseStreamSource to use current pmoaudio API:
Audio Segment Creation:
- Replaced AudioSegment::new_audio() with manual construction using _AudioSegment
- Convert PCM to Vec<[i16; 2]> or Vec<[I24; 2]> stereo pairs
- Use AudioChunkData::new(stereo, sample_rate, gain_db) → Arc
- Wrap in AudioChunk::I16() or AudioChunk::I24()
- Create AudioSegment with order, timestamp_sec, and _AudioSegment::Chunk()
Sync Markers:
- Replaced AudioSegment::new_sync() with AudioSegment::new_track_boundary()
- Created TopZeroSync manually with _AudioSegment::Sync()
- Use AudioSegment::new_end_of_stream() for EOF
Stream Handling:
- Changed from decoder.next() (doesn't exist) to decoder.read()
- Added AsyncReadExt import
- Use buffered read approach like http_source
- Changed decoder.stream_info() to decoder.info()
I24 Construction:
- Changed I24::from_i32() to I24::new_clamped()
- Properly handles 24-bit PCM conversion with sign extension
Metadata:
- Fixed RwLock usage - write().await returns guard directly, no Result
- Added `let _` for Future return values
Testing:
✅ All 7 unit tests pass (cache FIFO behavior)
✅ RadioParadiseStreamSource compiles successfully with pmoaudio feature
Fixed test issues:
- Changed EventId(i) to plain i (EventId is type alias for u64)
- Added create_test_client() helper using RadioParadiseClient::with_client()
- Cast DEFAULT_CHUNK_DURATION_MS to u32 as expected by constructor
Outstanding API incompatibility issues:
- AudioSegment API has evolved (new_audio/new_sync no longer exist)
- AudioChunkData::from_interleaved() doesn't exist
- I24::from_i32() should be I24::new() or I24::new_clamped()
- Need to understand current pmoaudio API for creating audio segments
Tests compile but RadioParadiseStreamSource implementation needs
significant refactoring to match current pmoaudio API.
Problem:
- With `if >= CACHE_SIZE`, only ONE element removed per call
- If cache ever had >10 elements (abnormal state), would stay oversized
- Example: 12 elements → if removes 1 → 11 elements → add 1 → 12 elements ❌
Solution:
- Use `while >= CACHE_SIZE` to remove ALL excess elements
- Example: 12 elements → while removes 2 → 10 elements → add 1 → 10 elements ✅
- Guarantees exactly ≤10 elements regardless of initial state
Changes:
- mark_block_downloaded(): changed `if` to `while`
- Updated comment to reflect "tous les éléments excédentaires"
- Documentation updated with robustness guarantee
Problem:
- Previous logic: push_back() first, then pop_front() if len > 10
- This temporarily creates 11 elements, exceeding VecDeque capacity of 10
- Wastes the benefit of with_capacity() pre-allocation
Solution:
- Check capacity BEFORE adding: if len >= 10, pop_front() first
- Then push_back() new element
- Guarantees never exceeding 10 elements at any time
Changes:
- mark_block_downloaded(): inverted order (pop before push)
- Changed condition from `> CACHE_SIZE` to `>= CACHE_SIZE`
- Documentation updated with correct logic and benefits
Problem:
- HashSet doesn't maintain insertion order
- iter().next() returns arbitrary element, not the oldest
- Cache eviction was unpredictable
Solution:
- Use VecDeque for FIFO ordering
- push_back() adds new block
- pop_front() removes oldest block when cache exceeds 10 elements
- contains() is O(n) but performant for 10 elements
Changes:
- RadioParadiseStreamSourceLogic: recent_blocks now VecDeque<EventId>
- mark_block_downloaded(): simplified with guaranteed FIFO eviction
- Documentation updated with VecDeque usage and advantages
- Add comprehensive technical documentation (RADIO_PARADISE_STREAM_SOURCE.md)
- Add practical usage example (examples/radio_paradise_stream.rs)
- Document architecture, timing algorithm, and API
- Include both basic and advanced usage patterns with nowplaying stream
Implement a new pmoaudio source node that streams Radio Paradise blocks
with automatic TrackBoundary insertion at the correct timing.
Features:
- Downloads and decodes FLAC blocks from Radio Paradise API
- Queue management for block IDs via push_block_id()
- Recent blocks cache (10 blocks) to avoid re-downloads
- Automatic TrackBoundary insertion based on sample count timing
- Converts Song metadata to TrackMetadata with cover URLs
- Timeout of 3 seconds for new block IDs (radio real-time)
- Support for 16-bit and 24-bit FLAC audio
Architecture:
- RadioParadiseStreamSourceLogic: Pure business logic implementing NodeLogic
- RadioParadiseStreamSource: Wrapper using Node<> pattern
- Uses logic_mut() for push_block_id() configuration
The node emits:
- TopZeroSync at block start
- TrackBoundary before each song (with same order as next chunk)
- Audio chunks (I16 or I24)
- EndOfStream on timeout or completion
New pmoaudio feature gate with dependencies on:
- pmoaudio, pmoflac, pmometadata, futures-util