koan-core 0.21.0

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
Documentation
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
use std::path::PathBuf;

use rusqlite::Connection;
use serde::{Deserialize, Serialize};

/// Serializable representation of a queue item for persistence.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersistedQueueItem {
    pub path: String,
    pub title: String,
    pub artist: String,
    pub album_artist: String,
    pub album: String,
    pub year: Option<String>,
    pub codec: Option<String>,
    pub track_number: Option<i64>,
    pub disc: Option<i64>,
    pub duration_ms: Option<u64>,
    /// Database track ID — enables re-downloading on session restore.
    /// Absent in pre-v0.18.2 persisted state; serde default covers migration.
    #[serde(default)]
    pub db_id: Option<i64>,
}

/// Full persisted playback state.
#[derive(Debug, Clone)]
pub struct PersistedPlaybackState {
    pub items: Vec<PersistedQueueItem>,
    pub cursor_path: Option<String>,
    pub position_ms: u64,
}

/// Save the current playback state to the database.
/// Uses UPSERT on the single-row playback_state table (id=1).
pub fn save_playback_state(
    conn: &Connection,
    items: &[PersistedQueueItem],
    cursor_path: Option<&str>,
    position_ms: u64,
) -> rusqlite::Result<()> {
    let json = serde_json::to_string(items).unwrap_or_else(|_| "[]".into());
    conn.execute(
        "INSERT INTO playback_state (id, queue_json, cursor_id, position_ms, updated_at)
         VALUES (1, ?1, ?2, ?3, datetime('now'))
         ON CONFLICT(id) DO UPDATE SET
           queue_json = ?1, cursor_id = ?2, position_ms = ?3, updated_at = datetime('now')",
        rusqlite::params![json, cursor_path, position_ms as i64],
    )?;
    Ok(())
}

/// Load persisted playback state. Returns None if no state has been saved.
pub fn load_playback_state(conn: &Connection) -> rusqlite::Result<Option<PersistedPlaybackState>> {
    let result = conn.query_row(
        "SELECT queue_json, cursor_id, position_ms FROM playback_state WHERE id = 1",
        [],
        |row| {
            let json: String = row.get(0)?;
            let cursor_path: Option<String> = row.get(1)?;
            let position_ms: i64 = row.get(2)?;
            Ok((json, cursor_path, position_ms as u64))
        },
    );

    match result {
        Ok((json, cursor_path, position_ms)) => {
            let items: Vec<PersistedQueueItem> = serde_json::from_str(&json).unwrap_or_default();
            if items.is_empty() {
                return Ok(None);
            }
            Ok(Some(PersistedPlaybackState {
                items,
                cursor_path,
                position_ms,
            }))
        }
        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
        Err(e) => Err(e),
    }
}

/// Clear persisted playback state.
pub fn clear_playback_state(conn: &Connection) -> rusqlite::Result<()> {
    conn.execute("DELETE FROM playback_state", [])?;
    Ok(())
}

impl PersistedQueueItem {
    /// Create from a playlist item's fields.
    pub fn from_playlist_item(item: &crate::player::state::PlaylistItem) -> Self {
        Self {
            path: item.path.to_string_lossy().into_owned(),
            title: item.title.clone(),
            artist: item.artist.clone(),
            album_artist: item.album_artist.clone(),
            album: item.album.clone(),
            year: item.year.clone(),
            codec: item.codec.clone(),
            track_number: item.track_number,
            disc: item.disc,
            duration_ms: item.duration_ms,
            db_id: item.db_id,
        }
    }

    /// Convert back to a PlaylistItem with fresh ID.
    /// Verifies the file path still exists on disk — missing cache files
    /// get `LoadState::Pending` so the player re-triggers their download.
    pub fn to_playlist_item(&self) -> crate::player::state::PlaylistItem {
        let path = PathBuf::from(&self.path);
        let load_state = if path.exists() {
            crate::player::state::LoadState::Ready
        } else {
            log::debug!(
                "session restore: path missing, marking pending: {}",
                self.path,
            );
            crate::player::state::LoadState::Pending
        };
        crate::player::state::PlaylistItem {
            id: crate::player::state::QueueItemId::new(),
            db_id: self.db_id,
            path,
            title: self.title.clone(),
            artist: self.artist.clone(),
            album_artist: self.album_artist.clone(),
            album: self.album.clone(),
            year: self.year.clone(),
            codec: self.codec.clone(),
            track_number: self.track_number,
            disc: self.disc,
            duration_ms: self.duration_ms,
            load_state,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_conn() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        conn.pragma_update(None, "foreign_keys", "on").unwrap();
        crate::db::schema::create_tables(&conn).unwrap();
        conn
    }

    #[test]
    fn test_save_and_load_playback_state() {
        let conn = test_conn();
        let items = vec![
            PersistedQueueItem {
                path: "/music/track1.flac".into(),
                title: "Track 1".into(),
                artist: "Artist".into(),
                album_artist: "Artist".into(),
                album: "Album".into(),
                year: Some("2024".into()),
                codec: Some("FLAC".into()),
                track_number: Some(1),
                disc: Some(1),
                duration_ms: Some(240_000),
                db_id: None,
            },
            PersistedQueueItem {
                path: "/music/track2.flac".into(),
                title: "Track 2".into(),
                artist: "Artist".into(),
                album_artist: "Artist".into(),
                album: "Album".into(),
                year: Some("2024".into()),
                codec: Some("FLAC".into()),
                track_number: Some(2),
                disc: Some(1),
                duration_ms: Some(180_000),
                db_id: None,
            },
        ];

        save_playback_state(&conn, &items, Some("/music/track1.flac"), 42_000).unwrap();

        let loaded = load_playback_state(&conn).unwrap().unwrap();
        assert_eq!(loaded.items.len(), 2);
        assert_eq!(loaded.items[0].title, "Track 1");
        assert_eq!(loaded.items[1].path, "/music/track2.flac");
        assert_eq!(loaded.cursor_path.as_deref(), Some("/music/track1.flac"));
        assert_eq!(loaded.position_ms, 42_000);
    }

    #[test]
    fn test_load_returns_none_when_empty() {
        let conn = test_conn();
        let loaded = load_playback_state(&conn).unwrap();
        assert!(loaded.is_none());
    }

    #[test]
    fn test_clear_playback_state() {
        let conn = test_conn();
        let items = vec![PersistedQueueItem {
            path: "/music/track.flac".into(),
            title: "Track".into(),
            artist: "Artist".into(),
            album_artist: "Artist".into(),
            album: "Album".into(),
            year: None,
            codec: None,
            track_number: None,
            disc: None,
            duration_ms: None,
            db_id: None,
        }];
        save_playback_state(&conn, &items, None, 0).unwrap();
        assert!(load_playback_state(&conn).unwrap().is_some());

        clear_playback_state(&conn).unwrap();
        assert!(load_playback_state(&conn).unwrap().is_none());
    }

    #[test]
    fn test_to_playlist_item_marks_missing_path_as_pending() {
        let item = PersistedQueueItem {
            path: "/nonexistent/path/track.flac".into(),
            title: "Ghost".into(),
            artist: "Nobody".into(),
            album_artist: "Nobody".into(),
            album: "Void".into(),
            year: None,
            codec: None,
            track_number: None,
            disc: None,
            duration_ms: None,
            db_id: Some(42),
        };
        let playlist_item = item.to_playlist_item();
        assert!(
            matches!(
                playlist_item.load_state,
                crate::player::state::LoadState::Pending
            ),
            "missing file should be Pending, got {:?}",
            playlist_item.load_state,
        );
        assert_eq!(playlist_item.db_id, Some(42), "db_id should be preserved");
    }

    #[test]
    fn test_to_playlist_item_marks_existing_path_as_ready() {
        // Use cargo's own manifest as a file that definitely exists.
        let manifest = env!("CARGO_MANIFEST_DIR");
        let existing_path = format!("{}/Cargo.toml", manifest);
        let item = PersistedQueueItem {
            path: existing_path,
            title: "Real".into(),
            artist: "Someone".into(),
            album_artist: "Someone".into(),
            album: "Exists".into(),
            year: None,
            codec: None,
            track_number: None,
            disc: None,
            duration_ms: None,
            db_id: None,
        };
        let playlist_item = item.to_playlist_item();
        assert!(
            matches!(
                playlist_item.load_state,
                crate::player::state::LoadState::Ready
            ),
            "existing file should be Ready, got {:?}",
            playlist_item.load_state,
        );
    }

    #[test]
    fn test_save_overwrites_previous_state() {
        let conn = test_conn();
        let items1 = vec![PersistedQueueItem {
            path: "/music/old.flac".into(),
            title: "Old".into(),
            artist: "A".into(),
            album_artist: "A".into(),
            album: "B".into(),
            year: None,
            codec: None,
            track_number: None,
            disc: None,
            duration_ms: None,
            db_id: None,
        }];
        save_playback_state(&conn, &items1, None, 100).unwrap();

        let items2 = vec![PersistedQueueItem {
            path: "/music/new.flac".into(),
            title: "New".into(),
            artist: "X".into(),
            album_artist: "X".into(),
            album: "Y".into(),
            year: None,
            codec: None,
            track_number: None,
            disc: None,
            duration_ms: None,
            db_id: None,
        }];
        save_playback_state(&conn, &items2, Some("/music/new.flac"), 999).unwrap();

        let loaded = load_playback_state(&conn).unwrap().unwrap();
        assert_eq!(loaded.items.len(), 1);
        assert_eq!(loaded.items[0].title, "New");
        assert_eq!(loaded.position_ms, 999);
    }

    #[test]
    fn test_db_id_round_trip() {
        let conn = test_conn();
        let items = vec![
            PersistedQueueItem {
                path: "/music/local.flac".into(),
                title: "Local".into(),
                artist: "A".into(),
                album_artist: "A".into(),
                album: "B".into(),
                year: None,
                codec: None,
                track_number: None,
                disc: None,
                duration_ms: None,
                db_id: None,
            },
            PersistedQueueItem {
                path: "/cache/remote.flac".into(),
                title: "Remote".into(),
                artist: "C".into(),
                album_artist: "C".into(),
                album: "D".into(),
                year: None,
                codec: None,
                track_number: None,
                disc: None,
                duration_ms: None,
                db_id: Some(99),
            },
        ];
        save_playback_state(&conn, &items, None, 0).unwrap();

        let loaded = load_playback_state(&conn).unwrap().unwrap();
        assert_eq!(
            loaded.items[0].db_id, None,
            "local track should have no db_id"
        );
        assert_eq!(
            loaded.items[1].db_id,
            Some(99),
            "remote track db_id should persist"
        );
    }

    #[test]
    fn test_db_id_migration_from_old_format() {
        // Simulate old-format JSON that lacks the db_id field.
        let conn = test_conn();
        let old_json = r#"[{"path":"/music/track.flac","title":"T","artist":"A","album_artist":"A","album":"B","year":null,"codec":null,"track_number":null,"disc":null,"duration_ms":null}]"#;
        conn.execute(
            "INSERT INTO playback_state (id, queue_json, cursor_id, position_ms, updated_at)
             VALUES (1, ?1, NULL, 0, datetime('now'))",
            rusqlite::params![old_json],
        )
        .unwrap();

        let loaded = load_playback_state(&conn).unwrap().unwrap();
        assert_eq!(loaded.items.len(), 1);
        assert_eq!(
            loaded.items[0].db_id, None,
            "missing field should default to None"
        );
    }

    #[test]
    fn save_and_restore_playback_state_roundtrip() {
        // Full round-trip: build playlist items, save state with cursor and position,
        // clear in-memory, restore from DB, verify everything matches.
        let conn = test_conn();

        let items = vec![
            PersistedQueueItem {
                path: "/music/alpha.flac".into(),
                title: "Alpha".into(),
                artist: "Band".into(),
                album_artist: "Band".into(),
                album: "Debut".into(),
                year: Some("2023".into()),
                codec: Some("FLAC".into()),
                track_number: Some(1),
                disc: Some(1),
                duration_ms: Some(300_000),
                db_id: Some(10),
            },
            PersistedQueueItem {
                path: "/music/beta.flac".into(),
                title: "Beta".into(),
                artist: "Band".into(),
                album_artist: "Band".into(),
                album: "Debut".into(),
                year: Some("2023".into()),
                codec: Some("FLAC".into()),
                track_number: Some(2),
                disc: Some(1),
                duration_ms: Some(250_000),
                db_id: Some(11),
            },
            PersistedQueueItem {
                path: "/music/gamma.flac".into(),
                title: "Gamma".into(),
                artist: "Other".into(),
                album_artist: "Other".into(),
                album: "Solo".into(),
                year: None,
                codec: Some("MP3".into()),
                track_number: Some(1),
                disc: None,
                duration_ms: Some(180_000),
                db_id: None,
            },
        ];

        // Save with cursor on the second track, position 42s in.
        let cursor_path = "/music/beta.flac";
        let position_ms = 42_000u64;
        save_playback_state(&conn, &items, Some(cursor_path), position_ms).unwrap();

        // Simulate "clear in-memory state" by just loading fresh from DB.
        let restored = load_playback_state(&conn)
            .unwrap()
            .expect("should have persisted state");

        // Verify queue integrity.
        assert_eq!(restored.items.len(), 3, "queue length mismatch");

        // Verify item fields survived the round-trip.
        assert_eq!(restored.items[0].title, "Alpha");
        assert_eq!(restored.items[0].path, "/music/alpha.flac");
        assert_eq!(restored.items[0].db_id, Some(10));
        assert_eq!(restored.items[0].track_number, Some(1));

        assert_eq!(restored.items[1].title, "Beta");
        assert_eq!(restored.items[1].artist, "Band");
        assert_eq!(restored.items[1].duration_ms, Some(250_000));
        assert_eq!(restored.items[1].db_id, Some(11));

        assert_eq!(restored.items[2].title, "Gamma");
        assert_eq!(restored.items[2].artist, "Other");
        assert_eq!(restored.items[2].codec.as_deref(), Some("MP3"));
        assert_eq!(restored.items[2].db_id, None);

        // Verify cursor and position.
        assert_eq!(
            restored.cursor_path.as_deref(),
            Some(cursor_path),
            "cursor should point to the second track"
        );
        assert_eq!(
            restored.position_ms, position_ms,
            "position should survive round-trip"
        );

        // Verify to_playlist_item conversion (paths don't exist on disk, so all get Pending).
        let playlist_items: Vec<_> = restored
            .items
            .iter()
            .map(|i| i.to_playlist_item())
            .collect();
        assert_eq!(playlist_items.len(), 3);
        for pi in &playlist_items {
            assert!(
                matches!(pi.load_state, crate::player::state::LoadState::Pending),
                "non-existent paths should be Pending"
            );
        }
        // Each converted item should have a unique QueueItemId.
        let ids: std::collections::HashSet<_> = playlist_items.iter().map(|i| i.id.0).collect();
        assert_eq!(ids.len(), 3, "each item should get a unique QueueItemId");
    }
}