koan-core 0.26.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
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
use std::fs;
use std::path::Path;
use std::time::UNIX_EPOCH;

use lofty::config::ParseOptions;
use lofty::file::AudioFile;
use lofty::mp4::{Mp4Codec, Mp4File};
use lofty::prelude::*;
use symphonia::core::meta::{MetadataRevision, StandardTag};
use thiserror::Error;

use crate::db::queries::TrackMeta;

#[derive(Debug, Error)]
pub enum MetadataError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("tag error: {0}")]
    Tag(#[from] lofty::error::FileParseError),
}

/// Audio file extensions we care about.
const AUDIO_EXTENSIONS: &[&str] = &[
    "flac", "mp3", "m4a", "aac", "ogg", "opus", "wv", "wav", "aiff", "aif", "alac", "ape",
];

/// Check if a path has a supported audio extension.
pub fn is_audio_file(path: &Path) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .is_some_and(|ext| AUDIO_EXTENSIONS.contains(&ext.to_lowercase().as_str()))
}

/// Read metadata from an audio file, returning a TrackMeta ready for DB insertion.
///
/// If lofty fails to parse tags (e.g. corrupted UTF-16 ID3 frames), falls back
/// to Symphonia for duration/properties and infers what we can from the path.
pub fn read_metadata(path: &Path) -> Result<TrackMeta, MetadataError> {
    // Skip empty/tiny files — avoid confusing error messages from lofty/symphonia.
    match std::fs::metadata(path) {
        Ok(m) if m.len() == 0 => {
            return Err(MetadataError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "empty file (0 bytes) — may be a stale mount or incomplete transfer, will retry on next scan: {}",
                    path.display()
                ),
            )));
        }
        Err(e) => return Err(MetadataError::Io(e)),
        _ => {}
    }

    // Embedded art is skipped: a scan wants tags and audio properties, and
    // decoding a few hundred KB of JPEG out of every ID3v2 and FLAC block only
    // to drop it dominated the run. `extract_cover_art` reads it separately,
    // for the one track that needs it at the time it needs it.
    match read_tagged_file(path) {
        Ok(tagged_file) => read_metadata_lofty(path, &tagged_file),
        Err(e) => {
            log::warn!(
                "lofty failed for {}: {}; falling back to probe",
                path.display(),
                e
            );
            read_metadata_fallback(path)
        }
    }
}

/// lofty refuses any tag that would allocate past a global cap, and its default
/// is 16 MB — small enough that one record with 4000x4000 cover art in its
/// Vorbis comments fails to parse at all, dropping every track on it to the
/// Symphonia fallback with worse metadata and three file parses instead of one.
/// The cap exists to stop a hostile file exhausting memory, which 256 MB still
/// does on any machine that can run a music player.
fn raise_allocation_limit() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        lofty::config::apply_global_options(
            lofty::config::GlobalOptions::new().allocation_limit(256 * 1024 * 1024),
        );
    });
}

/// lofty's own reader, minus the pictures.
///
/// `extract_cover_art` still reads them, with the defaults, for whichever
/// single track actually needs artwork.
fn read_tagged_file(path: &Path) -> Result<lofty::file::TaggedFile, Box<dyn std::error::Error>> {
    raise_allocation_limit();
    Ok(lofty::probe::Probe::open(path)?
        .options(ParseOptions::new().read_cover_art(false))
        .read()?)
}

/// Full metadata read via lofty (happy path).
fn read_metadata_lofty(
    path: &Path,
    tagged_file: &lofty::file::TaggedFile,
) -> Result<TrackMeta, MetadataError> {
    let properties = tagged_file.properties();
    let duration_ms = properties.duration().as_millis() as i64;
    let sample_rate = properties.sample_rate().map(|r| r as i32);
    let bit_depth = properties.bit_depth().map(|b| b as i32);
    let channels = properties.channels().map(|c| c as i32);
    let bitrate = properties.audio_bitrate().map(|b| b as i32);

    let tag = tagged_file
        .primary_tag()
        .or_else(|| tagged_file.first_tag());

    let (title, artist, album_artist, album, date, disc, track_number, genre, label) =
        if let Some(tag) = tag {
            (
                tag.title().map(|s| s.to_string()),
                tag.artist().map(|s| s.to_string()),
                tag.get_string(ItemKey::AlbumArtist).map(|s| s.to_string()),
                tag.album().map(|s| s.to_string()),
                // Prefer the track date, falling back to the recording date.
                tag.get_string(ItemKey::Year)
                    .or_else(|| tag.get_string(ItemKey::RecordingDate))
                    .map(|s| s.to_string()),
                tag.disk().map(|d| d as i32),
                tag.track().map(|t| t as i32),
                tag.genre().map(|s| s.to_string()),
                tag.get_string(ItemKey::Label).map(|s| s.to_string()),
            )
        } else {
            (None, None, None, None, None, None, None, None, None)
        };

    let title = title.unwrap_or_else(|| {
        path.file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("Unknown")
            .to_string()
    });
    let artist = artist.unwrap_or_else(|| "Unknown Artist".to_string());
    let album = album.unwrap_or_else(|| "Unknown Album".to_string());

    let file_meta = fs::metadata(path)?;
    let size_bytes = file_meta.len() as i64;
    let mtime = file_meta
        .modified()
        .ok()
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
        .map(|d| d.as_secs() as i64);

    let codec = if tagged_file.file_type() == lofty::file::FileType::Mp4 {
        mp4_codec(path)
    } else {
        codec_string(tagged_file.file_type()).to_string()
    };

    Ok(TrackMeta {
        title,
        artist,
        album_artist,
        album,
        date,
        disc,
        track_number,
        genre,
        label,
        duration_ms: Some(duration_ms),
        codec: Some(codec),
        sample_rate,
        bit_depth,
        channels,
        bitrate,
        size_bytes: Some(size_bytes),
        mtime,
        path: Some(path.to_string_lossy().to_string()),
        source: "local".to_string(),
        remote_id: None,
        album_remote_id: None,
        artist_remote_id: None,
        remote_url: None,
        album_added_at: mtime.and_then(iso8601_utc),
    })
}

/// Fallback metadata read when lofty fails. Uses Symphonia to probe
/// duration/codec/properties, and infers artist/album/title from the path.
fn read_metadata_fallback(path: &Path) -> Result<TrackMeta, MetadataError> {
    let file_meta = fs::metadata(path)?;
    let size_bytes = file_meta.len() as i64;
    let mtime = file_meta
        .modified()
        .ok()
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
        .map(|d| d.as_secs() as i64);

    // Probe via Symphonia for duration, codec, and audio properties.
    let props = probe_symphonia(path);

    // Try to extract tags from Symphonia's metadata (it's more lenient than lofty
    // for corrupted frames — it skips bad frames instead of erroring).
    //
    // Everything it offers is taken, not just the three obvious fields: a row
    // missing its track number cannot content-match the same track synced from
    // a remote server, so a file that lands here would stay a duplicate even
    // once its tags read correctly.
    let tags = probe_symphonia_tags(path);

    let title = tags.title.unwrap_or_else(|| {
        path.file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("Unknown")
            .to_string()
    });
    let artist = tags.artist.unwrap_or_else(|| "Unknown Artist".to_string());
    let album = tags.album.unwrap_or_else(|| "Unknown Album".to_string());

    Ok(TrackMeta {
        title,
        artist,
        album_artist: tags.album_artist,
        album,
        date: tags.date,
        disc: tags.disc,
        track_number: tags.track_number,
        genre: tags.genre,
        label: None,
        duration_ms: props.duration_ms,
        codec: props.codec,
        sample_rate: props.sample_rate,
        bit_depth: props.bit_depth,
        channels: props.channels,
        bitrate: props.bitrate,
        size_bytes: Some(size_bytes),
        mtime,
        path: Some(path.to_string_lossy().to_string()),
        source: "local".to_string(),
        remote_id: None,
        album_remote_id: None,
        artist_remote_id: None,
        remote_url: None,
        album_added_at: mtime.and_then(iso8601_utc),
    })
}

/// A unix timestamp as the same ISO 8601 UTC string a Subsonic server uses for
/// `created`, so a library mixing local files and remote entries can be ordered
/// by one column without comparing two date formats.
fn iso8601_utc(unix_secs: i64) -> Option<String> {
    chrono::DateTime::from_timestamp(unix_secs, 0)
        .map(|t| t.format("%Y-%m-%dT%H:%M:%SZ").to_string())
}

/// Probed audio properties from Symphonia.
struct SymphoniaProps {
    duration_ms: Option<i64>,
    sample_rate: Option<i32>,
    bit_depth: Option<i32>,
    channels: Option<i32>,
    bitrate: Option<i32>,
    codec: Option<String>,
}

/// Probe audio properties via Symphonia (duration, sample rate, codec, etc.).
fn probe_symphonia(path: &Path) -> SymphoniaProps {
    use symphonia::core::codecs::audio::CODEC_ID_NULL_AUDIO;
    use symphonia::core::formats::probe::Hint;
    use symphonia::core::formats::{FormatOptions, TrackType};
    use symphonia::core::io::MediaSourceStream;
    use symphonia::core::meta::MetadataOptions;

    let empty = SymphoniaProps {
        duration_ms: None,
        sample_rate: None,
        bit_depth: None,
        channels: None,
        bitrate: None,
        codec: None,
    };

    let file = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(_) => return empty,
    };
    let mss = MediaSourceStream::new(Box::new(file), Default::default());
    let mut hint = Hint::new();
    if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
        hint.with_extension(ext);
    }

    let reader = match symphonia::default::get_probe().probe(
        &hint,
        mss,
        FormatOptions::default(),
        MetadataOptions::default(),
    ) {
        Ok(r) => r,
        Err(_) => return empty,
    };

    let track = match reader.default_track(TrackType::Audio) {
        Some(t) => t,
        None => return empty,
    };

    let params = match track.codec_params.as_ref().and_then(|p| p.audio()) {
        Some(p) => p,
        None => return empty,
    };
    let sample_rate = params.sample_rate.map(|r| r as i32);
    let bit_depth = params.bits_per_sample.map(|b| b as i32);
    let channels = params.channels.as_ref().map(|c| c.count() as i32);

    let duration_ms = params.sample_rate.and_then(|sr| {
        let ms = crate::audio::buffer::track_duration_ms(&*reader, track, sr);
        (ms > 0).then_some(ms as i64)
    });

    let bitrate = params.sample_rate.and_then(|sr| {
        params.bits_per_sample.and_then(|bps| {
            params
                .channels
                .as_ref()
                .map(|ch| (sr as i32 * bps as i32 * ch.count() as i32) / 1000)
        })
    });

    let codec = if params.codec != CODEC_ID_NULL_AUDIO {
        Some(symphonia_codec_name(params.codec))
    } else {
        None
    };

    SymphoniaProps {
        duration_ms,
        sample_rate,
        bit_depth,
        channels,
        bitrate,
        codec,
    }
}

/// Map Symphonia codec type to a human-readable string.
fn symphonia_codec_name(codec: symphonia::core::codecs::audio::AudioCodecId) -> String {
    use symphonia::core::codecs::audio::well_known as ids;
    match codec {
        ids::CODEC_ID_FLAC => "FLAC".to_string(),
        ids::CODEC_ID_MP3 => "MP3".to_string(),
        ids::CODEC_ID_AAC => "AAC".to_string(),
        ids::CODEC_ID_ALAC => "ALAC".to_string(),
        ids::CODEC_ID_VORBIS => "Vorbis".to_string(),
        ids::CODEC_ID_OPUS => "Opus".to_string(),
        ids::CODEC_ID_WAVPACK => "WavPack".to_string(),
        ids::CODEC_ID_PCM_S16LE
        | ids::CODEC_ID_PCM_S24LE
        | ids::CODEC_ID_PCM_S32LE
        | ids::CODEC_ID_PCM_F32LE
        | ids::CODEC_ID_PCM_F64LE
        | ids::CODEC_ID_PCM_S16BE
        | ids::CODEC_ID_PCM_S24BE
        | ids::CODEC_ID_PCM_S32BE
        | ids::CODEC_ID_PCM_F32BE
        | ids::CODEC_ID_PCM_F64BE
        | ids::CODEC_ID_PCM_U8 => "PCM".to_string(),
        _ => "Unknown".to_string(),
    }
}

/// Try to extract basic tags (title, artist, album) via Symphonia's metadata reader.
/// Symphonia is more lenient with corrupted ID3 frames than lofty.
/// Tags Symphonia can give us when lofty cannot parse the file at all.
#[derive(Default)]
struct SymphoniaTags {
    title: Option<String>,
    artist: Option<String>,
    album_artist: Option<String>,
    album: Option<String>,
    date: Option<String>,
    track_number: Option<i32>,
    disc: Option<i32>,
    genre: Option<String>,
}

fn probe_symphonia_tags(path: &Path) -> SymphoniaTags {
    use symphonia::core::formats::FormatOptions;
    use symphonia::core::formats::probe::Hint;
    use symphonia::core::io::MediaSourceStream;
    use symphonia::core::meta::{MetadataOptions, StandardTag};

    let file = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(_) => return SymphoniaTags::default(),
    };
    let mss = MediaSourceStream::new(Box::new(file), Default::default());
    let mut hint = Hint::new();
    if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
        hint.with_extension(ext);
    }

    let mut reader = match symphonia::default::get_probe().probe(
        &hint,
        mss,
        FormatOptions::default(),
        MetadataOptions::default(),
    ) {
        Ok(r) => r,
        Err(_) => return SymphoniaTags::default(),
    };

    let mut tags = SymphoniaTags::default();

    // Later revisions win. Symphonia's log is time-ordered and `current()` is
    // the *oldest* revision, not the best one — an MP3 carrying both tags
    // surfaces ID3v1 first and ID3v2 second. ID3v1 is never the one you want:
    // its fields are a fixed 30 bytes, so anything longer arrives silently
    // truncated, and a truncated title then matches nothing on a remote server.
    //
    // This walk accumulates rather than calling `skip_to_latest()`, so a field
    // present only in an older revision still fills a gap the newest one leaves.
    let mut log = reader.metadata();
    loop {
        if let Some(rev) = log.current() {
            for tag in &rev.media.tags {
                match &tag.std {
                    Some(StandardTag::TrackTitle(v)) => tags.title = Some(v.to_string()),
                    Some(StandardTag::Artist(v)) => tags.artist = Some(v.to_string()),
                    Some(StandardTag::AlbumArtist(v)) => tags.album_artist = Some(v.to_string()),
                    Some(StandardTag::Album(v)) => tags.album = Some(v.to_string()),
                    Some(StandardTag::Genre(v)) => tags.genre = Some(v.to_string()),
                    Some(StandardTag::RecordingDate(v)) => tags.date = Some(v.to_string()),
                    Some(StandardTag::RecordingYear(v)) => tags.date = Some(v.to_string()),
                    Some(StandardTag::TrackNumber(v)) => tags.track_number = Some(*v as i32),
                    Some(StandardTag::DiscNumber(v)) => tags.disc = Some(*v as i32),
                    _ => {}
                }
            }
        }
        if log.pop().is_none() {
            break;
        }
    }

    tags
}

/// Determine codec for an MP4 container file (AAC, ALAC, etc.).
/// Falls back to "AAC" if the file cannot be parsed as Mp4File.
fn mp4_codec(path: &Path) -> String {
    let file = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(_) => return "AAC".to_string(),
    };
    let mut reader = std::io::BufReader::new(file);
    match Mp4File::read_from(&mut reader, ParseOptions::new()) {
        Ok(mp4) => match mp4.properties().codec() {
            Some(Mp4Codec::ALAC) => "ALAC".to_string(),
            Some(Mp4Codec::MP3) => "MP3".to_string(),
            Some(Mp4Codec::FLAC) => "FLAC".to_string(),
            _ => "AAC".to_string(),
        },
        Err(_) => "AAC".to_string(),
    }
}

/// Map lofty file type to a human-readable codec string.
pub fn codec_string(ft: lofty::file::FileType) -> &'static str {
    match ft {
        lofty::file::FileType::Flac => "FLAC",
        lofty::file::FileType::Mpeg => "MP3",
        lofty::file::FileType::Mp4 => "AAC",
        lofty::file::FileType::Opus => "Opus",
        lofty::file::FileType::Vorbis => "Vorbis",
        lofty::file::FileType::WavPack => "WavPack",
        lofty::file::FileType::Wav => "WAV",
        lofty::file::FileType::Aiff => "AIFF",
        lofty::file::FileType::Ape => "APE",
        _ => "Unknown",
    }
}

/// Extract embedded front cover art bytes from an audio file.
/// Returns raw image bytes (JPEG/PNG) or None. TIFF images are
/// skipped — the `image` crate only has jpeg+png features and macOS
/// CGImageDestination rejects TIFF for Now Playing artwork.
pub fn extract_cover_art(path: &Path) -> Option<Vec<u8>> {
    raise_allocation_limit();
    let tagged_file = lofty::read_from_path(path).ok()?;
    let tag = tagged_file
        .primary_tag()
        .or_else(|| tagged_file.first_tag())?;

    // Prefer CoverFront, fall back to first picture.
    let pictures = tag.pictures();
    let pic = pictures
        .iter()
        .find(|p| p.pic_type() == lofty::picture::PictureType::CoverFront && !is_tiff(p.data()))
        .or_else(|| pictures.iter().find(|p| !is_tiff(p.data())))?;

    Some(pic.data().to_vec())
}

/// TIFF magic bytes: `II*\0` (little-endian) or `MM\0*` (big-endian).
fn is_tiff(data: &[u8]) -> bool {
    data.len() >= 4
        && ((data[0] == 0x49 && data[1] == 0x49 && data[2] == 0x2A && data[3] == 0x00)
            || (data[0] == 0x4D && data[1] == 0x4D && data[2] == 0x00 && data[3] == 0x2A))
}

/// Extract partial track metadata from a Symphonia probe `MetadataRevision`.
///
/// Used during streaming playback to populate track info before the full file
/// is downloaded (and before lofty can read complete tags).
///
/// Fields not present in the probe metadata are left as `None` or defaults.
/// Callers should merge this with a full `read_metadata()` result once the
/// download completes.
pub fn metadata_from_probe_result(meta: &MetadataRevision, fallback_title: &str) -> TrackMeta {
    let mut title: Option<String> = None;
    let mut artist: Option<String> = None;
    let mut album_artist: Option<String> = None;
    let mut album: Option<String> = None;
    let mut date: Option<String> = None;
    let mut disc: Option<i32> = None;
    let mut track_number: Option<i32> = None;
    let mut genre: Option<String> = None;
    let mut label: Option<String> = None;

    // A non-empty text tag replaces the field; empty values are ignored so a
    // blank tag never shadows a later populated one or the fallback.
    let set_text = |slot: &mut Option<String>, value: &str| {
        if !value.is_empty() {
            *slot = Some(value.to_string());
        }
    };

    for tag in &meta.media.tags {
        let Some(std) = &tag.std else { continue };
        match std {
            StandardTag::TrackTitle(v) => set_text(&mut title, v),
            StandardTag::Artist(v) => set_text(&mut artist, v),
            StandardTag::AlbumArtist(v) => set_text(&mut album_artist, v),
            StandardTag::Album(v) => set_text(&mut album, v),
            StandardTag::ReleaseDate(v) | StandardTag::RecordingDate(v) => set_text(&mut date, v),
            StandardTag::ReleaseYear(y) | StandardTag::RecordingYear(y) if date.is_none() => {
                date = Some(y.to_string())
            }
            StandardTag::OriginalReleaseDate(v) | StandardTag::OriginalRecordingDate(v)
                if date.is_none() =>
            {
                set_text(&mut date, v)
            }
            StandardTag::OriginalReleaseYear(y) | StandardTag::OriginalRecordingYear(y)
                if date.is_none() =>
            {
                date = Some(y.to_string())
            }
            StandardTag::TrackNumber(n) => track_number = Some(*n as i32),
            StandardTag::DiscNumber(n) => disc = Some(*n as i32),
            StandardTag::Genre(v) => set_text(&mut genre, v),
            StandardTag::Label(v) => set_text(&mut label, v),
            _ => {}
        }
    }

    TrackMeta {
        title: title.unwrap_or_else(|| fallback_title.to_string()),
        artist: artist.unwrap_or_else(|| "Unknown Artist".to_string()),
        album_artist,
        album: album.unwrap_or_else(|| "Unknown Album".to_string()),
        date,
        disc,
        track_number,
        genre,
        label,
        duration_ms: None,
        codec: None,
        sample_rate: None,
        bit_depth: None,
        channels: None,
        bitrate: None,
        size_bytes: None,
        mtime: None,
        path: None,
        source: "streaming".to_string(),
        remote_id: None,
        album_remote_id: None,
        artist_remote_id: None,
        remote_url: None,
        album_added_at: None,
    }
}

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

    /// A file carrying both tags must be read from ID3v2. ID3v1's fields are a
    /// fixed 30 bytes, so preferring it silently truncates every longer title —
    /// which then matches nothing on a remote server, splitting one record into
    /// two albums. Symphonia surfaces the v1 tag as the *first* metadata
    /// revision, so "take the first" is exactly the wrong rule.
    #[test]
    fn id3v2_beats_id3v1() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("both.mp3");
        crate::test_utils::generate_mp3_with_both_tags(
            &path,
            "Golden Skans (David E Sugar Remix)",
            "Golden Skans (David E Sugar R",
        );

        let tags = probe_symphonia_tags(&path);
        assert_eq!(
            tags.title.as_deref(),
            Some("Golden Skans (David E Sugar Remix)")
        );
        // ID3v1 has no track number at all, so this also proves the v2 frame
        // was reached rather than the walk stopping at the first revision.
        assert_eq!(tags.track_number, Some(7));
    }

    #[test]
    fn test_is_audio_file() {
        assert!(is_audio_file(Path::new("track.flac")));
        assert!(is_audio_file(Path::new("track.FLAC")));
        assert!(is_audio_file(Path::new("track.mp3")));
        assert!(is_audio_file(Path::new("track.m4a")));
        assert!(is_audio_file(Path::new("track.ogg")));
        assert!(is_audio_file(Path::new("track.opus")));
        assert!(is_audio_file(Path::new("track.wv")));
        assert!(is_audio_file(Path::new("track.wav")));
        assert!(is_audio_file(Path::new("track.aiff")));
        assert!(is_audio_file(Path::new("track.ape")));

        assert!(!is_audio_file(Path::new("cover.jpg")));
        assert!(!is_audio_file(Path::new("notes.txt")));
        assert!(!is_audio_file(Path::new("playlist.m3u")));
        assert!(!is_audio_file(Path::new("track.pdf")));
        assert!(!is_audio_file(Path::new("noext")));
    }

    #[test]
    fn test_is_audio_file_paths() {
        assert!(is_audio_file(Path::new("/music/artist/album/01.flac")));
        assert!(!is_audio_file(Path::new("/music/artist/album/cover.png")));
    }

    #[test]
    fn test_read_metadata_nonexistent() {
        let result = read_metadata(Path::new("/nonexistent/track.flac"));
        assert!(result.is_err());
    }

    #[test]
    fn test_codec_string() {
        assert_eq!(codec_string(lofty::file::FileType::Flac), "FLAC");
        assert_eq!(codec_string(lofty::file::FileType::Mpeg), "MP3");
        assert_eq!(codec_string(lofty::file::FileType::Opus), "Opus");
        assert_eq!(codec_string(lofty::file::FileType::Wav), "WAV");
    }

    // --- metadata_from_probe_result tests ---

    use symphonia::core::meta::well_known::METADATA_ID_ID3V2;
    use symphonia::core::meta::{MetadataBuilder, MetadataInfo, StandardTag, Tag};

    const TEST_META_INFO: MetadataInfo = MetadataInfo {
        metadata: METADATA_ID_ID3V2,
        short_name: "id3v2",
        long_name: "ID3v2",
    };

    fn make_revision(tags: &[StandardTag]) -> symphonia::core::meta::MetadataRevision {
        let mut builder = MetadataBuilder::new(TEST_META_INFO);
        for std in tags {
            builder.add_tag(Tag::new_from_parts("", "", Some(std.clone())));
        }
        builder.build()
    }

    #[test]
    fn test_probe_track_and_disc_numbers() {
        let rev = make_revision(&[
            StandardTag::TrackTitle("My Song".to_string().into()),
            StandardTag::Artist("Artist".to_string().into()),
            StandardTag::Album("Album".to_string().into()),
            StandardTag::TrackNumber(3),
            StandardTag::TrackTotal(12),
            StandardTag::DiscNumber(2),
        ]);
        let meta = metadata_from_probe_result(&rev, "fallback");
        assert_eq!(
            meta.track_number,
            Some(3),
            "track number should come from the track number tag, not the total"
        );
        assert_eq!(meta.disc, Some(2));
    }

    #[test]
    fn test_probe_original_date_fallback() {
        // When no release/recording date is present, the original date is used.
        let rev = make_revision(&[
            StandardTag::TrackTitle("My Song".to_string().into()),
            StandardTag::OriginalReleaseDate("1991".to_string().into()),
        ]);
        let meta = metadata_from_probe_result(&rev, "fallback");
        assert_eq!(
            meta.date,
            Some("1991".to_string()),
            "original release date should be used when the release date is missing"
        );
    }

    #[test]
    fn test_probe_original_date_not_used_when_date_present() {
        // The release date takes precedence over the original release date.
        let rev = make_revision(&[
            StandardTag::ReleaseDate("2005".to_string().into()),
            StandardTag::OriginalReleaseDate("1991".to_string().into()),
        ]);
        let meta = metadata_from_probe_result(&rev, "fallback");
        assert_eq!(
            meta.date,
            Some("2005".to_string()),
            "release date should take precedence over original release date"
        );
    }

    #[test]
    fn test_probe_empty_values_skipped() {
        // Tags with empty string values should be silently skipped,
        // leaving the corresponding fields as None (or falling back to defaults).
        let rev = make_revision(&[
            StandardTag::Artist(String::new().into()),
            StandardTag::Album(String::new().into()),
            StandardTag::Genre(String::new().into()),
        ]);
        let meta = metadata_from_probe_result(&rev, "Title");
        // Empty artist/album fall back to defaults, not empty string.
        assert_eq!(
            meta.artist, "Unknown Artist",
            "empty artist tag should fall back to 'Unknown Artist'"
        );
        assert_eq!(
            meta.album, "Unknown Album",
            "empty album tag should fall back to 'Unknown Album'"
        );
        assert_eq!(meta.genre, None, "empty genre tag should produce None");
    }

    #[test]
    fn test_probe_defaults() {
        // When no tags are present, artist and album should use the hardcoded defaults.
        // Title should fall back to the fallback_title argument.
        let rev = make_revision(&[]);
        let meta = metadata_from_probe_result(&rev, "Fallback Title");
        assert_eq!(
            meta.title, "Fallback Title",
            "missing title should use fallback_title argument"
        );
        assert_eq!(
            meta.artist, "Unknown Artist",
            "missing artist should default to 'Unknown Artist'"
        );
        assert_eq!(
            meta.album, "Unknown Album",
            "missing album should default to 'Unknown Album'"
        );
        assert_eq!(meta.track_number, None);
        assert_eq!(meta.date, None);
        assert_eq!(meta.genre, None);
        assert_eq!(meta.source, "streaming");
    }

    #[test]
    fn test_mp4_codec_nonexistent_file_falls_back_to_aac() {
        assert_eq!(mp4_codec(Path::new("/nonexistent/track.m4a")), "AAC");
    }

    #[test]
    fn test_mp4_codec_non_mp4_file_falls_back_to_aac() {
        // A non-MP4 file should fail to parse and fall back to "AAC".
        let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
        assert_eq!(mp4_codec(&manifest), "AAC");
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_mp4_codec_real_alac_file() {
        // Integration test: verify that a real ALAC .m4a file is correctly
        // identified as "ALAC" rather than "AAC". Skipped silently when the
        // Turtlehead volume is not mounted.
        let alac_path = Path::new(
            "/Volumes/Turtlehead/music/Valet Girls/(2017) PERENNIAL VICE [ALAC]/0101. Valet Girls - Tis the Season.m4a",
        );
        if !alac_path.exists() {
            eprintln!("SKIP: ALAC test file not found (volume not mounted)");
            return;
        }
        assert_eq!(
            mp4_codec(alac_path),
            "ALAC",
            "real ALAC .m4a should be identified as ALAC, not AAC"
        );
    }
}