koan-core 0.19.3

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
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, StandardTagKey};
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::LoftyError),
}

/// 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)),
        _ => {}
    }

    match lofty::read_from_path(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)
        }
    }
}

/// 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()),
                // lofty 0.23 removed year() — use TrackDate or RecordingDate.
                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,
        remote_url: None,
    })
}

/// 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).
    let (title, artist, album) = probe_symphonia_tags(path);

    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());

    Ok(TrackMeta {
        title,
        artist,
        album_artist: None,
        album,
        date: None,
        disc: None,
        track_number: None,
        genre: None,
        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,
        remote_url: None,
    })
}

/// 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::CODEC_TYPE_NULL;
    use symphonia::core::formats::FormatOptions;
    use symphonia::core::io::MediaSourceStream;
    use symphonia::core::meta::MetadataOptions;
    use symphonia::core::probe::Hint;

    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 probed = match symphonia::default::get_probe().format(
        &hint,
        mss,
        &FormatOptions::default(),
        &MetadataOptions::default(),
    ) {
        Ok(p) => p,
        Err(_) => return empty,
    };

    let track = match probed.format.default_track() {
        Some(t) => t,
        None => return empty,
    };

    let params = &track.codec_params;
    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.map(|c| c.count() as i32);

    let duration_ms = params.n_frames.and_then(|frames| {
        params
            .sample_rate
            .map(|sr| (frames as f64 / sr as f64 * 1000.0) as i64)
    });

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

    let codec = if params.codec != CODEC_TYPE_NULL {
        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::CodecType) -> String {
    use symphonia::core::codecs;
    match codec {
        codecs::CODEC_TYPE_FLAC => "FLAC".to_string(),
        codecs::CODEC_TYPE_MP3 => "MP3".to_string(),
        codecs::CODEC_TYPE_AAC => "AAC".to_string(),
        codecs::CODEC_TYPE_ALAC => "ALAC".to_string(),
        codecs::CODEC_TYPE_VORBIS => "Vorbis".to_string(),
        codecs::CODEC_TYPE_OPUS => "Opus".to_string(),
        codecs::CODEC_TYPE_WAVPACK => "WavPack".to_string(),
        codecs::CODEC_TYPE_PCM_S16LE
        | codecs::CODEC_TYPE_PCM_S24LE
        | codecs::CODEC_TYPE_PCM_S32LE
        | codecs::CODEC_TYPE_PCM_F32LE
        | codecs::CODEC_TYPE_PCM_F64LE
        | codecs::CODEC_TYPE_PCM_S16BE
        | codecs::CODEC_TYPE_PCM_S24BE
        | codecs::CODEC_TYPE_PCM_S32BE
        | codecs::CODEC_TYPE_PCM_F32BE
        | codecs::CODEC_TYPE_PCM_F64BE
        | codecs::CODEC_TYPE_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.
fn probe_symphonia_tags(path: &Path) -> (Option<String>, Option<String>, Option<String>) {
    use symphonia::core::formats::FormatOptions;
    use symphonia::core::io::MediaSourceStream;
    use symphonia::core::meta::{MetadataOptions, StandardTagKey};
    use symphonia::core::probe::Hint;

    let file = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(_) => return (None, None, None),
    };
    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 probed = match symphonia::default::get_probe().format(
        &hint,
        mss,
        &FormatOptions::default(),
        &MetadataOptions::default(),
    ) {
        Ok(p) => p,
        Err(_) => return (None, None, None),
    };

    let mut title = None;
    let mut artist = None;
    let mut album = None;

    // Check metadata on the probe result itself.
    if let Some(md) = probed.metadata.get()
        && let Some(rev) = md.current()
    {
        for tag in rev.tags() {
            match tag.std_key {
                Some(StandardTagKey::TrackTitle) => title = Some(tag.value.to_string()),
                Some(StandardTagKey::Artist) => artist = Some(tag.value.to_string()),
                Some(StandardTagKey::Album) => album = Some(tag.value.to_string()),
                _ => {}
            }
        }
    }

    // Also check format-level metadata.
    if let Some(md) = probed.format.metadata().current() {
        for tag in md.tags() {
            match tag.std_key {
                Some(StandardTagKey::TrackTitle) if title.is_none() => {
                    title = Some(tag.value.to_string())
                }
                Some(StandardTagKey::Artist) if artist.is_none() => {
                    artist = Some(tag.value.to_string())
                }
                Some(StandardTagKey::Album) if album.is_none() => {
                    album = Some(tag.value.to_string())
                }
                _ => {}
            }
        }
    }

    (title, artist, album)
}

/// 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() {
            Mp4Codec::ALAC => "ALAC".to_string(),
            Mp4Codec::MP3 => "MP3".to_string(),
            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>> {
    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;

    for tag in meta.tags() {
        let Some(std_key) = tag.std_key else { continue };
        let value = tag.value.to_string();
        if value.is_empty() {
            continue;
        }
        match std_key {
            StandardTagKey::TrackTitle => title = Some(value),
            StandardTagKey::Artist => artist = Some(value),
            StandardTagKey::AlbumArtist => album_artist = Some(value),
            StandardTagKey::Album => album = Some(value),
            StandardTagKey::Date => date = Some(value),
            StandardTagKey::OriginalDate => {
                if date.is_none() {
                    date = Some(value);
                }
            }
            StandardTagKey::TrackNumber => {
                track_number = value.split('/').next().and_then(|s| s.trim().parse().ok());
            }
            StandardTagKey::DiscNumber => {
                disc = value.split('/').next().and_then(|s| s.trim().parse().ok());
            }
            StandardTagKey::Genre => genre = Some(value),
            StandardTagKey::Label => label = Some(value),
            _ => {}
        }
    }

    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,
        remote_url: None,
    }
}

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

    #[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 ---
    //
    // MetadataRevision has private fields and can only be constructed via
    // MetadataBuilder (symphonia::core::meta::MetadataBuilder). Tag::new()
    // is public, so we can build arbitrary revisions in tests.

    use symphonia::core::meta::{MetadataBuilder, StandardTagKey, Tag, Value};

    fn make_revision(tags: &[(StandardTagKey, &str)]) -> symphonia::core::meta::MetadataRevision {
        let mut builder = MetadataBuilder::new();
        for (key, value) in tags {
            builder.add_tag(Tag::new(Some(*key), "", Value::String(value.to_string())));
        }
        builder.metadata()
    }

    #[test]
    fn test_probe_track_number_slash_format() {
        // "3/12" in TrackNumber tag should parse to track_number = Some(3),
        // ignoring the total-tracks part after the slash.
        let rev = make_revision(&[
            (StandardTagKey::TrackTitle, "My Song"),
            (StandardTagKey::Artist, "Artist"),
            (StandardTagKey::Album, "Album"),
            (StandardTagKey::TrackNumber, "3/12"),
        ]);
        let meta = metadata_from_probe_result(&rev, "fallback");
        assert_eq!(
            meta.track_number,
            Some(3),
            "slash-format track number should parse to the first component"
        );
    }

    #[test]
    fn test_probe_original_date_fallback() {
        // When Date is absent, OriginalDate should be used as the date.
        let rev = make_revision(&[
            (StandardTagKey::TrackTitle, "My Song"),
            (StandardTagKey::OriginalDate, "1991"),
        ]);
        let meta = metadata_from_probe_result(&rev, "fallback");
        assert_eq!(
            meta.date,
            Some("1991".to_string()),
            "OriginalDate should be used when Date is missing"
        );
    }

    #[test]
    fn test_probe_original_date_not_used_when_date_present() {
        // When both Date and OriginalDate are present, Date wins.
        let rev = make_revision(&[
            (StandardTagKey::Date, "2005"),
            (StandardTagKey::OriginalDate, "1991"),
        ]);
        let meta = metadata_from_probe_result(&rev, "fallback");
        assert_eq!(
            meta.date,
            Some("2005".to_string()),
            "Date should take precedence over OriginalDate"
        );
    }

    #[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(&[
            (StandardTagKey::Artist, ""),
            (StandardTagKey::Album, ""),
            (StandardTagKey::Genre, ""),
        ]);
        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"
        );
    }
}