//! One song file read with lofty: the fields the phone's TagLib reader asks //! for (`apps/cotton/Sources/CottonTagReader/CottonTagReader.cpp`), field for //! field, into `cotton_core::music::Tags`. //! //! WHITELISTED KEYS ONLY. Every field is asked for by its own `ItemKey`; //! nothing iterates a tag's items, so the iTunes purchaser atoms (`apID`, //! `ownr`, `purd`, `atID`, `cnID`, `plID`, …) and anything else a file carries //! beyond these fields are never read out of it. use std::fs::File; use std::path::Path; use cotton_core::music::Tags; use lofty::config::ParseOptions; use lofty::file::{AudioFile as _, TaggedFile, TaggedFileExt as _}; use lofty::mp4::{Mp4Codec, Mp4File}; use lofty::picture::PictureType; use lofty::probe::Probe; use lofty::tag::{ItemKey, Tag}; /// What one file says: its tags, and whether it carries a picture. #[derive(Debug, Clone, Default, PartialEq)] pub struct ReadSong { pub tags: Tags, /// The file carries a picture ([`embedded_cover`] reads it when an album /// needs one), so the folder's cover is not looked for. pub embedded_cover: bool, } fn open(path: &Path) -> Option<(TaggedFile, Option)> { let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or_default().to_ascii_lowercase(); if matches!(ext.as_str(), "m4a" | "mp4") { // An `.m4a` holds AAC or ALAC: only the box's own properties say which. let mut file = File::open(path).ok()?; let mp4 = Mp4File::read_from(&mut file, ParseOptions::new()).ok()?; let lossless = match mp4.properties().codec() { Some(Mp4Codec::ALAC) => Some(true), Some(Mp4Codec::AAC) => Some(false), _ => None, }; return Some((TaggedFile::from(mp4), lossless)); } let tagged = Probe::open(path).ok()?.guess_file_type().ok()?.read().ok()?; Some((tagged, None)) } /// Every tag the file carries, its primary one first: a field is the first /// tag's that says it (an MP3's ID3v2 before its ID3v1). fn ordered(file: &TaggedFile) -> Vec<&Tag> { let primary = file.primary_tag(); let mut tags: Vec<&Tag> = primary.into_iter().collect(); tags.extend(file.tags().iter().filter(|tag| primary.is_none_or(|first| !std::ptr::eq(*tag, first)))); tags } fn first(tags: &[&Tag], key: ItemKey) -> Option { tags.iter().find_map(|tag| { let value = tag.get_string(key)?.trim(); (!value.is_empty()).then(|| value.to_string()) }) } /// `3` or `3/12`: the number, and the count after the slash. fn numbered(text: &str) -> (Option, Option) { let (number, of) = match text.split_once('/') { Some((number, of)) => (number, Some(of)), None => (text, None), }; let whole = |text: &str| text.trim().parse::().ok().filter(|n| *n > 0); (whole(number), of.and_then(whole)) } /// The number in front of a text: "-6.54 dB" → -6.54. fn leading_number(text: &str) -> Option { let text = text.trim(); let end = text .char_indices() .find(|(at, c)| !(c.is_ascii_digit() || *c == '.' || ((*c == '-' || *c == '+') && *at == 0))) .map_or(text.len(), |(at, _)| at); text[..end].parse::().ok().filter(|value| value.is_finite()) } /// An R128 gain (Q7.8 against -23 LUFS) as ReplayGain's dB (against -18). fn r128(text: &str) -> Option { text.trim().parse::().ok().map(|value| value as f64 / 256.0 + 5.0) } /// Whether most of a text's lines carry an LRC time mark (`[mm:ss.xx]`): the /// phone's `LRC.looksTimed`. pub fn looks_timed(text: &str) -> bool { let lines: Vec<&str> = text.lines().map(str::trim).filter(|line| !line.is_empty()).collect(); if lines.is_empty() { return false; } let timed = lines.iter().filter(|line| time_marked(line)).count(); timed * 2 > lines.len() } /// `^\[\d{1,3}:\d{2}([.:]\d{1,3})?\]` fn time_marked(line: &str) -> bool { let Some(rest) = line.strip_prefix('[') else { return false }; let Some((mark, _)) = rest.split_once(']') else { return false }; let Some((minutes, seconds)) = mark.split_once(':') else { return false }; let digits = |text: &str, least: usize, most: usize| (least..=most).contains(&text.len()) && text.chars().all(|c| c.is_ascii_digit()); if !digits(minutes, 1, 3) { return false; } match seconds.find(['.', ':']) { Some(at) => digits(&seconds[..at], 2, 2) && digits(&seconds[at + 1..], 1, 3), None => digits(seconds, 2, 2), } } /// The file's tags and audio properties; `None` when lofty cannot open it as /// audio (the phone then brings it in on its path alone, as here). pub fn read_song(path: &Path) -> Option { let (file, lossless) = open(path)?; let tags = ordered(&file); let text = |key| first(&tags, key); let mut out = Tags { title: text(ItemKey::TrackTitle), artist: text(ItemKey::TrackArtist), album: text(ItemKey::AlbumTitle), album_artist: text(ItemKey::AlbumArtist), genre: text(ItemKey::Genre), composer: text(ItemKey::Composer), isrc: text(ItemKey::Isrc), // lofty's MusicBrainzRecordingId is the recording (MUSICBRAINZ_TRACKID, // ID3's UFID, MP4's `MusicBrainz Track Id`); its MusicBrainzTrackId is // the track on the release (MUSICBRAINZ_RELEASETRACKID), a different // id that never stands in for the recording. mb_recording: text(ItemKey::MusicBrainzRecordingId), mb_release_track: text(ItemKey::MusicBrainzTrackId), artist_sort: text(ItemKey::TrackArtistSortOrder), album_artist_sort: text(ItemKey::AlbumArtistSortOrder), original_date: text(ItemKey::OriginalReleaseDate), // ID3's TPUB reads as Publisher: the label Picard writes there. label: text(ItemKey::Label).or_else(|| text(ItemKey::Publisher)), catalog_number: text(ItemKey::CatalogNumber), barcode: text(ItemKey::Barcode), release_type: text(ItemKey::MusicBrainzReleaseType), mb_release: text(ItemKey::MusicBrainzReleaseId), mb_release_group: text(ItemKey::MusicBrainzReleaseGroupId), mb_artist: text(ItemKey::MusicBrainzArtistId), mb_album_artist: text(ItemKey::MusicBrainzReleaseArtistId), lossless, ..Tags::default() }; out.track = text(ItemKey::TrackNumber).and_then(|track| numbered(&track).0); if let Some(disc) = text(ItemKey::DiscNumber) { let (disc, discs) = numbered(&disc); out.disc = disc; out.discs = discs; } out.discs = out.discs.or_else(|| text(ItemKey::DiscTotal).and_then(|total| numbered(&total).0)); let date = [ItemKey::RecordingDate, ItemKey::Year, ItemKey::ReleaseDate, ItemKey::OriginalReleaseDate] .into_iter() .find_map(text); out.year = date.map(|date| date.chars().take(4).collect()); out.compilation = text(ItemKey::FlagCompilation).map(|flag| !(flag == "0" || flag.eq_ignore_ascii_case("false"))); let lyrics = text(ItemKey::Lyrics).or_else(|| text(ItemKey::UnsyncLyrics)); // A lyrics tag written as LRC is timed lyrics: it goes where they go. match lyrics { Some(lyrics) if looks_timed(&lyrics) => out.synced_lyrics = Some(lyrics), lyrics => out.lyrics = lyrics, } out.track_gain = text(ItemKey::ReplayGainTrackGain).as_deref().and_then(leading_number); out.track_peak = text(ItemKey::ReplayGainTrackPeak).as_deref().and_then(leading_number); out.album_gain = text(ItemKey::ReplayGainAlbumGain).as_deref().and_then(leading_number); out.album_peak = text(ItemKey::ReplayGainAlbumPeak).as_deref().and_then(leading_number); if text(ItemKey::ReplayGainTrackGain).is_none() { out.track_gain = text(ItemKey::R128TrackGain).as_deref().and_then(r128); } if text(ItemKey::ReplayGainAlbumGain).is_none() { out.album_gain = text(ItemKey::R128AlbumGain).as_deref().and_then(r128); } let properties = file.properties(); let millis = properties.duration().as_millis(); out.duration = (millis > 0).then(|| millis as f64 / 1000.0); out.bitrate = properties.audio_bitrate().or(properties.overall_bitrate()).filter(|n| *n > 0); out.sample_rate = properties.sample_rate().filter(|n| *n > 0); let embedded_cover = tags.iter().any(|tag| tag.pictures().iter().any(|picture| !picture.data().is_empty())); Some(ReadSong { tags: out, embedded_cover }) } /// What a picture's own first bytes say it is: the extension its key ends in /// and its content type, for the four an album's cover may be (the phone's /// `cover_type`); `None` for anything else. pub fn picture_kind(bytes: &[u8]) -> Option<(&'static str, &'static str)> { if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { Some(("jpg", "image/jpeg")) } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { Some(("png", "image/png")) } else if bytes.starts_with(b"GIF8") { Some(("gif", "image/gif")) } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { Some(("webp", "image/webp")) } else { None } } /// The file's own picture, a front cover first, else its first. pub fn embedded_cover(path: &Path) -> Option> { let (file, _) = open(path)?; let tags = ordered(&file); let pictures: Vec<_> = tags.iter().flat_map(|tag| tag.pictures()).filter(|picture| !picture.data().is_empty()).collect(); let chosen = pictures.iter().find(|picture| picture.pic_type() == PictureType::CoverFront).or(pictures.first())?; Some(chosen.data().to_vec()) } #[cfg(test)] mod tests { use super::*; #[test] fn numbers_read_with_their_count() { assert_eq!(numbered("3/12"), (Some(3), Some(12))); assert_eq!(numbered("07"), (Some(7), None)); assert_eq!(numbered("0"), (None, None)); assert_eq!(numbered("x"), (None, None)); } #[test] fn gains_read_as_decibels() { assert_eq!(leading_number("-6.54 dB"), Some(-6.54)); assert_eq!(leading_number("+1.20 dB"), Some(1.2)); assert_eq!(leading_number("0.988"), Some(0.988)); assert_eq!(leading_number("dB"), None); // R128: Q7.8 against -23 LUFS, so 0 is +5 dB against ReplayGain's -18. assert_eq!(r128("0"), Some(5.0)); assert_eq!(r128("-512"), Some(3.0)); } #[test] fn lrc_is_told_by_its_time_marks() { assert!(looks_timed("[00:01.00]One\n[00:02.50]Two\n")); assert!(looks_timed("[ar: Someone]\n[00:01.00]One\n[00:02.00]Two")); assert!(!looks_timed("One\nTwo\n[00:02.00]Three")); assert!(!looks_timed("")); assert!(time_marked("[1:02:345]x")); assert!(!time_marked("[01:2]x")); } #[test] fn a_picture_is_known_by_its_first_bytes() { assert_eq!(picture_kind(&[0xFF, 0xD8, 0xFF, 0xE0]), Some(("jpg", "image/jpeg"))); assert_eq!(picture_kind(b"\x89PNG\r\n\x1a\n...."), Some(("png", "image/png"))); assert_eq!(picture_kind(b"BM......"), None); } }