bevy_ym2149 0.9.1

Bevy audio plugin for YM2149 PSG emulator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! Playlist support for sequential track playback.
//!
//! This module provides playlist loading and automatic track advancement,
//! including seamless crossfade transitions between tracks.
//!
//! # Quick Start
//!
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_ym2149::{Ym2149Playback, Ym2149Playlist, Ym2149PlaylistPlayer};
//!
//! fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
//!     let playlist = asset_server.load("music/playlist.ymplaylist");
//!     commands.spawn((Ym2149Playback::default(), Ym2149PlaylistPlayer::new(playlist)));
//! }
//! ```

use crate::audio_source::Ym2149AudioSource;
use crate::error::BevyYm2149Error;
use crate::events::{PlaylistAdvanceRequest, TrackFinished};
use crate::playback::{CrossfadeRequest, TrackSource, YM2149_SAMPLE_RATE_F32, Ym2149Playback};
use bevy::asset::{AssetLoader, LoadContext, io::Reader};
use bevy::prelude::*;
use bevy::reflect::TypePath;
use serde::Deserialize;
use std::sync::Arc;

const PLAYLIST_EXTENSIONS: &[&str] = &["ymplaylist", "ympl", "ymlist"];

/// Behaviour when the playlist reaches the last entry.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PlaylistMode {
    /// Restart from the first track after the last one finishes.
    #[default]
    Loop,
    /// Stop playback after the last track finishes.
    Once,
}

/// A single playlist entry.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PlaylistSource {
    /// Play a YM file from a filesystem path.
    File {
        /// Path to the YM file.
        path: String,
    },
    /// Play a `Ym2149AudioSource` asset registered with Bevy's asset server.
    Asset {
        /// Asset path (e.g., "music/song.ym").
        path: String,
    },
    /// Play YM data embedded directly in the playlist.
    Bytes {
        /// Raw YM file data.
        data: Vec<u8>,
    },
}

/// Configuration for seamless playlist crossfades.
///
/// Controls when a crossfade begins and how long both tracks overlap.
#[derive(Debug, Clone)]
pub struct CrossfadeConfig {
    /// When to start the crossfade.
    pub trigger: CrossfadeTrigger,
    /// How long both tracks play simultaneously.
    pub window: CrossfadeWindow,
}

impl CrossfadeConfig {
    /// Start the crossfade once the given ratio of the song has elapsed (0.0 - 1.0).
    pub fn start_at_ratio(ratio: f32) -> Self {
        Self {
            trigger: CrossfadeTrigger::SongRatio(ratio),
            window: CrossfadeWindow::UntilSongEnd,
        }
    }

    /// Start the crossfade after a fixed amount of seconds from the beginning of the track.
    pub fn start_at_seconds(seconds: f32) -> Self {
        Self {
            trigger: CrossfadeTrigger::Seconds(seconds),
            window: CrossfadeWindow::UntilSongEnd,
        }
    }

    /// Override the amount of time both decks overlap once the fade begins.
    pub fn with_window_seconds(mut self, seconds: f32) -> Self {
        self.window = CrossfadeWindow::FixedSeconds(seconds.max(0.001));
        self
    }
}

impl Default for CrossfadeConfig {
    fn default() -> Self {
        Self::start_at_ratio(0.9)
    }
}

/// Trigger used to decide when to begin the hand-off to the next deck.
#[derive(Debug, Clone, Copy)]
pub enum CrossfadeTrigger {
    /// Begin crossfade when the given ratio (0.0-1.0) of the song has elapsed.
    SongRatio(f32),
    /// Begin crossfade after this many seconds from track start.
    Seconds(f32),
}

/// Duration of the overlap between decks once a fade starts.
#[derive(Debug, Clone, Copy)]
pub enum CrossfadeWindow {
    /// Crossfade lasts until the current track ends.
    UntilSongEnd,
    /// Crossfade lasts exactly this many seconds.
    FixedSeconds(f32),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum CrossfadeStage {
    #[default]
    Idle,
    Loading {
        target_index: usize,
    },
    Active {
        target_index: usize,
    },
}

impl CrossfadeStage {
    fn is_active(&self) -> bool {
        matches!(self, CrossfadeStage::Active { .. })
    }
}

/// Playlist asset describing a set of YM tracks.
///
/// Load from `.ymplaylist` files (RON format) or construct programmatically.
#[derive(Asset, Clone, TypePath, Deserialize)]
pub struct Ym2149Playlist {
    /// Ordered list of tracks in the playlist.
    pub tracks: Vec<PlaylistSource>,
    /// What happens when the last track finishes.
    #[serde(default)]
    pub mode: PlaylistMode,
}

impl Ym2149Playlist {
    /// Returns true if the playlist has no tracks.
    pub fn is_empty(&self) -> bool {
        self.tracks.is_empty()
    }
}

/// Loader for `.ymplaylist` assets.
#[derive(Default)]
pub struct Ym2149PlaylistLoader;

impl AssetLoader for Ym2149PlaylistLoader {
    type Asset = Ym2149Playlist;
    type Settings = ();
    type Error = BevyYm2149Error;

    async fn load(
        &self,
        reader: &mut dyn Reader,
        _settings: &Self::Settings,
        _load_context: &mut LoadContext<'_>,
    ) -> Result<Self::Asset, Self::Error> {
        let mut bytes = Vec::new();
        reader
            .read_to_end(&mut bytes)
            .await
            .map_err(|e| BevyYm2149Error::AssetLoad(e.to_string()))?;
        let playlist: Ym2149Playlist =
            ron::de::from_bytes(&bytes).map_err(|e| BevyYm2149Error::AssetLoad(e.to_string()))?;
        Ok(playlist)
    }

    fn extensions(&self) -> &[&str] {
        PLAYLIST_EXTENSIONS
    }
}

/// Component that drives a [`Ym2149Playback`] using a playlist asset.
///
/// Attach this alongside a `Ym2149Playback` to enable automatic track advancement.
#[derive(Component)]
pub struct Ym2149PlaylistPlayer {
    /// Handle to the playlist asset.
    pub playlist: Handle<Ym2149Playlist>,
    /// Index of the currently playing track.
    pub current_index: usize,
    /// Optional crossfade configuration enabling seamless transitions.
    pub crossfade: Option<CrossfadeConfig>,
    pub(crate) crossfade_stage: CrossfadeStage,
}

impl Ym2149PlaylistPlayer {
    /// Create a new playlist player without crossfade.
    pub fn new(playlist: Handle<Ym2149Playlist>) -> Self {
        Self {
            playlist,
            current_index: 0,
            crossfade: None,
            crossfade_stage: CrossfadeStage::Idle,
        }
    }

    /// Create a new playlist player with crossfade enabled.
    pub fn with_crossfade(playlist: Handle<Ym2149Playlist>, config: CrossfadeConfig) -> Self {
        Self {
            playlist,
            current_index: 0,
            crossfade: Some(config),
            crossfade_stage: CrossfadeStage::Idle,
        }
    }
}

/// Register playlist asset types and loaders with the Bevy app.
pub fn register_playlist_assets(app: &mut App) {
    app.init_asset_loader::<Ym2149PlaylistLoader>();
}

/// Respond to finished tracks by advancing the playlist and loading the next entry.
pub fn advance_playlist_players(
    mut finished: MessageReader<TrackFinished>,
    mut players: Query<(&mut Ym2149Playback, &mut Ym2149PlaylistPlayer)>,
    playlists: Res<Assets<Ym2149Playlist>>,
    asset_server: Res<AssetServer>,
) {
    for event in finished.read() {
        if let Ok((mut playback, mut controller)) = players.get_mut(event.entity)
            && let Some(playlist_asset) = playlists.get(&controller.playlist)
        {
            if playlist_asset.is_empty() {
                continue;
            }

            if controller.crossfade.is_some()
                && (controller.crossfade_stage.is_active()
                    || playback.is_crossfade_pending()
                    || playback.has_pending_playlist_index())
            {
                continue;
            }

            let Some(next_index) = next_playlist_index(controller.current_index, playlist_asset)
            else {
                continue;
            };

            controller.current_index = next_index;
            controller.crossfade_stage = CrossfadeStage::Idle;
            playback.clear_crossfade_request();

            if let Some(entry) = playlist_asset.tracks.get(controller.current_index) {
                apply_playlist_entry(entry, &mut playback, &asset_server);
                playback.restart();
                playback.play();
            }
        }
    }
}

pub(crate) fn apply_playlist_entry(
    entry: &PlaylistSource,
    playback: &mut Ym2149Playback,
    asset_server: &AssetServer,
) {
    match entry {
        PlaylistSource::File { path } => playback.set_source_path(path.clone()),
        PlaylistSource::Asset { path } => {
            let handle: Handle<crate::audio_source::Ym2149AudioSource> = asset_server.load(path);
            playback.set_source_asset(handle);
        }
        PlaylistSource::Bytes { data } => playback.set_source_bytes(data.clone()),
    }
}

/// Process explicit playlist advance requests (e.g. from UI input).
pub fn handle_playlist_requests(
    mut commands: Commands,
    mut requests: MessageReader<PlaylistAdvanceRequest>,
    mut players: Query<(&mut Ym2149Playback, &mut Ym2149PlaylistPlayer)>,
    playlists: Res<Assets<Ym2149Playlist>>,
    asset_server: Res<AssetServer>,
) {
    for request in requests.read() {
        let Ok((mut playback, mut controller)) = players.get_mut(request.entity) else {
            warn!(
                "Playlist advance request for entity {:?} without controller",
                request.entity
            );
            continue;
        };

        let Some(playlist_asset) = playlists.get(&controller.playlist) else {
            warn!(
                "Playlist asset for entity {:?} not yet loaded; skipping advance",
                request.entity
            );
            continue;
        };

        if playlist_asset.is_empty() {
            continue;
        }

        let mut target_index = request
            .index
            .unwrap_or_else(|| controller.current_index + 1);

        if target_index >= playlist_asset.tracks.len() {
            match playlist_asset.mode {
                PlaylistMode::Loop => target_index %= playlist_asset.tracks.len(),
                PlaylistMode::Once => target_index = playlist_asset.tracks.len() - 1,
            }
        }

        // If nothing is loaded yet, load immediately (first play).
        if playback.player.is_none() {
            controller.current_index = target_index;
            controller.crossfade_stage = CrossfadeStage::Idle;
            if let Some(entry) = playlist_asset.tracks.get(target_index) {
                apply_playlist_entry(entry, &mut playback, &asset_server);
                playback.restart();
                playback.play();
            }
            continue;
        }

        if let Some(cfg) = controller.crossfade.clone() {
            // Cancel any pending/active crossfade and enqueue a fresh one.
            if let Some(cf) = playback.crossfade.take()
                && let Some(cf_entity) = cf.crossfade_entity
            {
                commands.entity(cf_entity).despawn();
            }
            playback.clear_crossfade_request();
            playback.pending_playlist_index = None;

            if let Some(entry) = playlist_asset.tracks.get(target_index) {
                let source = resolve_track_source(entry, &asset_server);
                let desired = match cfg.window {
                    CrossfadeWindow::FixedSeconds(sec) => sec,
                    CrossfadeWindow::UntilSongEnd => {
                        if let Some(metrics) = playback.metrics() {
                            let elapsed = frames_to_seconds(
                                playback.frame_position,
                                metrics.samples_per_frame,
                            );
                            (metrics.duration_seconds() - elapsed).max(0.1)
                        } else {
                            5.0
                        }
                    }
                };
                playback.set_crossfade_request(CrossfadeRequest {
                    source,
                    duration: desired.max(0.1),
                    target_index,
                });
                controller.crossfade_stage = CrossfadeStage::Loading { target_index };
                continue;
            }
        }

        controller.current_index = target_index;
        controller.crossfade_stage = CrossfadeStage::Idle;
        playback.clear_crossfade_request();
        playback.pending_playlist_index = None;

        if let Some(entry) = playlist_asset.tracks.get(target_index) {
            apply_playlist_entry(entry, &mut playback, &asset_server);
            playback.restart();
            playback.play();
        }
    }
}

/// Drive automatic crossfades for playlist-enabled playbacks.
pub fn drive_crossfade_playlists(
    mut players: Query<(&mut Ym2149Playback, &mut Ym2149PlaylistPlayer)>,
    playlists: Res<Assets<Ym2149Playlist>>,
    asset_server: Res<AssetServer>,
) {
    for (mut playback, mut controller) in players.iter_mut() {
        let Some(config) = controller.crossfade.clone() else {
            continue;
        };

        if let Some(new_index) = playback.take_pending_playlist_index() {
            controller.current_index = new_index;
            controller.crossfade_stage = CrossfadeStage::Idle;
        } else if matches!(controller.crossfade_stage, CrossfadeStage::Loading { .. })
            && !playback.is_crossfade_pending()
        {
            controller.crossfade_stage = CrossfadeStage::Idle;
        }

        if let CrossfadeStage::Loading { target_index } = controller.crossfade_stage
            && playback.is_crossfade_active()
        {
            controller.crossfade_stage = CrossfadeStage::Active { target_index };
        }

        let Some(playlist_asset) = playlists.get(&controller.playlist) else {
            continue;
        };
        if playlist_asset.is_empty() {
            continue;
        }

        if playback.is_crossfade_pending() {
            continue;
        }

        let Some(metrics) = playback.metrics() else {
            continue;
        };

        let duration = metrics.duration_seconds();
        if duration <= f32::EPSILON {
            continue;
        }

        let elapsed = frames_to_seconds(playback.frame_position(), metrics.samples_per_frame);
        let trigger_point = match config.trigger {
            CrossfadeTrigger::SongRatio(ratio) => duration * ratio.clamp(0.0, 0.99),
            CrossfadeTrigger::Seconds(seconds) => seconds.max(0.0).min(duration.max(0.0)),
        };

        if elapsed < trigger_point {
            continue;
        }

        let remaining = (duration - elapsed).max(0.0);
        if remaining <= f32::EPSILON {
            continue;
        }

        let Some(next_index) = next_playlist_index(controller.current_index, playlist_asset) else {
            continue;
        };

        let fade_duration = match config.window {
            CrossfadeWindow::UntilSongEnd => remaining,
            CrossfadeWindow::FixedSeconds(seconds) => seconds,
        }
        .max(0.001);

        let Some(entry) = playlist_asset.tracks.get(next_index) else {
            continue;
        };
        let source = resolve_track_source(entry, &asset_server);

        playback.set_crossfade_request(CrossfadeRequest {
            source,
            duration: fade_duration,
            target_index: next_index,
        });
        controller.crossfade_stage = CrossfadeStage::Loading {
            target_index: next_index,
        };
    }
}

fn next_playlist_index(current: usize, playlist: &Ym2149Playlist) -> Option<usize> {
    if playlist.tracks.is_empty() {
        return None;
    }

    let mut next = current + 1;
    if next >= playlist.tracks.len() {
        match playlist.mode {
            PlaylistMode::Loop => next = 0,
            PlaylistMode::Once => return None,
        }
    }

    Some(next)
}

fn frames_to_seconds(frame: u32, samples_per_frame: u32) -> f32 {
    let samples = (frame as usize).saturating_mul(samples_per_frame as usize);
    samples as f32 / YM2149_SAMPLE_RATE_F32
}

fn resolve_track_source(entry: &PlaylistSource, asset_server: &AssetServer) -> TrackSource {
    match entry {
        PlaylistSource::File { path } => TrackSource::File(path.clone()),
        PlaylistSource::Asset { path } => {
            let handle: Handle<Ym2149AudioSource> = asset_server.load(path);
            TrackSource::Asset(handle)
        }
        PlaylistSource::Bytes { data } => TrackSource::Bytes(Arc::new(data.clone())),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::playback::{PlaybackMetrics, PlaybackState};
    use bevy::asset::AssetPlugin;

    #[test]
    fn crossfade_request_is_created_after_threshold() {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
        app.world_mut().init_resource::<Assets<Ym2149Playlist>>();

        let playlist_handle = {
            let mut assets = app.world_mut().resource_mut::<Assets<Ym2149Playlist>>();
            assets.add(Ym2149Playlist {
                tracks: vec![
                    PlaylistSource::Bytes { data: vec![0; 16] },
                    PlaylistSource::Bytes { data: vec![1; 16] },
                ],
                mode: PlaylistMode::Loop,
            })
        };

        let playback = Ym2149Playback {
            metrics: Some(PlaybackMetrics {
                frame_count: 1_000,
                samples_per_frame: 882,
            }),
            frame_position: 950,
            state: PlaybackState::Playing,
            ..Default::default()
        };

        let controller = Ym2149PlaylistPlayer {
            playlist: playlist_handle,
            current_index: 0,
            crossfade: Some(CrossfadeConfig::default()),
            crossfade_stage: CrossfadeStage::Idle,
        };

        let entity = app.world_mut().spawn((playback, controller)).id();

        app.add_systems(Update, drive_crossfade_playlists);
        app.update();

        let playback = app.world().entity(entity).get::<Ym2149Playback>().unwrap();
        assert!(
            playback.pending_crossfade.is_some(),
            "crossfade should be queued"
        );
        let request = playback.pending_crossfade.as_ref().unwrap();
        assert_eq!(request.target_index, 1);

        let controller = app
            .world()
            .entity(entity)
            .get::<Ym2149PlaylistPlayer>()
            .unwrap();
        assert!(matches!(
            controller.crossfade_stage,
            CrossfadeStage::Loading { target_index: 1 }
        ));
    }

    #[test]
    fn fixed_window_crossfade_uses_requested_duration() {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
        app.world_mut().init_resource::<Assets<Ym2149Playlist>>();

        let playlist_handle = {
            let mut assets = app.world_mut().resource_mut::<Assets<Ym2149Playlist>>();
            assets.add(Ym2149Playlist {
                tracks: vec![
                    PlaylistSource::Bytes { data: vec![0; 16] },
                    PlaylistSource::Bytes { data: vec![1; 16] },
                ],
                mode: PlaylistMode::Loop,
            })
        };

        let playback = Ym2149Playback {
            metrics: Some(PlaybackMetrics {
                frame_count: 1_000,
                samples_per_frame: 882,
            }),
            frame_position: 0,
            state: PlaybackState::Playing,
            ..Default::default()
        };

        let controller = Ym2149PlaylistPlayer {
            playlist: playlist_handle,
            current_index: 0,
            crossfade: Some(CrossfadeConfig::start_at_seconds(0.0).with_window_seconds(15.0)),
            crossfade_stage: CrossfadeStage::Idle,
        };

        let entity = app.world_mut().spawn((playback, controller)).id();

        app.add_systems(Update, drive_crossfade_playlists);
        app.update();

        let playback = app.world().entity(entity).get::<Ym2149Playback>().unwrap();
        let request = playback
            .pending_crossfade
            .as_ref()
            .expect("crossfade with fixed window should be queued");
        assert_eq!(request.target_index, 1);
        assert!(
            (request.duration - 15.0).abs() < f32::EPSILON,
            "expected fixed 15 second window, got {}",
            request.duration
        );
    }

    #[test]
    fn crossfade_completion_updates_playlist_index() {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
        app.world_mut().init_resource::<Assets<Ym2149Playlist>>();

        let playlist_handle = {
            let mut assets = app.world_mut().resource_mut::<Assets<Ym2149Playlist>>();
            assets.add(Ym2149Playlist {
                tracks: vec![
                    PlaylistSource::Bytes { data: vec![0; 16] },
                    PlaylistSource::Bytes { data: vec![1; 16] },
                ],
                mode: PlaylistMode::Loop,
            })
        };

        let playback = Ym2149Playback {
            metrics: Some(PlaybackMetrics {
                frame_count: 1_000,
                samples_per_frame: 882,
            }),
            pending_playlist_index: Some(1),
            ..Default::default()
        };

        let controller = Ym2149PlaylistPlayer {
            playlist: playlist_handle,
            current_index: 0,
            crossfade: Some(CrossfadeConfig::default()),
            crossfade_stage: CrossfadeStage::Active { target_index: 1 },
        };

        let entity = app.world_mut().spawn((playback, controller)).id();

        app.add_systems(Update, drive_crossfade_playlists);
        app.update();

        let playback = app.world().entity(entity).get::<Ym2149Playback>().unwrap();
        assert!(playback.pending_playlist_index.is_none());

        let controller = app
            .world()
            .entity(entity)
            .get::<Ym2149PlaylistPlayer>()
            .unwrap();
        assert_eq!(controller.current_index, 1);
        assert!(matches!(controller.crossfade_stage, CrossfadeStage::Idle));
    }

    #[test]
    fn track_finished_ignored_during_crossfade() {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
        app.add_message::<TrackFinished>();
        app.world_mut().init_resource::<Assets<Ym2149Playlist>>();

        let playlist_handle = {
            let mut assets = app.world_mut().resource_mut::<Assets<Ym2149Playlist>>();
            assets.add(Ym2149Playlist {
                tracks: vec![
                    PlaylistSource::Bytes { data: vec![0; 16] },
                    PlaylistSource::Bytes { data: vec![1; 16] },
                ],
                mode: PlaylistMode::Loop,
            })
        };

        let playback = Ym2149Playback {
            metrics: Some(PlaybackMetrics {
                frame_count: 1_000,
                samples_per_frame: 882,
            }),
            pending_crossfade: Some(CrossfadeRequest {
                source: TrackSource::Bytes(Arc::new(vec![2; 16])),
                duration: 1.0,
                target_index: 1,
            }),
            ..Default::default()
        };

        let controller = Ym2149PlaylistPlayer {
            playlist: playlist_handle,
            current_index: 0,
            crossfade: Some(CrossfadeConfig::default()),
            crossfade_stage: CrossfadeStage::Active { target_index: 1 },
        };

        let entity = app.world_mut().spawn((playback, controller)).id();

        app.add_systems(Update, advance_playlist_players);

        app.world_mut()
            .resource_mut::<Messages<TrackFinished>>()
            .write(TrackFinished { entity });

        app.update();

        let controller = app
            .world()
            .entity(entity)
            .get::<Ym2149PlaylistPlayer>()
            .unwrap();
        assert_eq!(controller.current_index, 0);
    }
}