//! Cotton Music's intake rules, one place for every door (Music definition, //! 4 Nov 2026, sections 6 and 8): what a song row says from a file's tags, //! what its folder and name fill when the tags are silent, which album and //! artist it gathers into, and which of two files of one song is kept. //! //! Pure: no file is read here. The phone reads tags with TagLib and the Mac //! verb with lofty; both hand [`Tags`] and the path the file came in as, and //! both get the same row from [`song_from`]. //! //! - Tags first; the folder and the file's name (`Artist/Album (Year)/01 //! Title.ext`) fill only what the tags left empty ([`path_facts`]). //! - An album is keyed on its album artist and its title ([`album_key`]), so //! it never splits on a compilation mark; "Various Artists" is one artist. //! - The same song in two formats is one song ([`same_song`]): artist, title //! and album alike and lengths within two seconds; the better file is kept //! ([`better`]): lossless over lossy, then the higher bitrate. pub mod m3u; use serde::{Deserialize, Serialize}; pub mod album_zip; /// The album artist of every compilation, one artist row. pub const VARIOUS_ARTISTS: &str = "Various Artists"; /// How far apart two files' lengths may be and still be one song. pub const SAME_LENGTH_SECONDS: f64 = 2.0; /// The formats a song's `format` column holds (`song.json`). pub const FORMATS: [&str; 8] = ["mp3", "aac", "alac", "flac", "opus", "vorbis", "wav", "aiff"]; // The one-time drop of the music before Cotton Music: the lists live in // cotton-rules, which the Worker runs as WASM. pub use cotton_rules::music::{GONE_TABLES, MUSIC_TOOL, OLD_TABLES, RESHAPED_TABLES, SONG}; /// What a reader found in one file: every field optional, none guessed. /// The iTunes purchaser atoms (the buyer's account and name, the purchase /// date) are not here at all: no reader asks for them. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Tags { pub title: Option, pub artist: Option, pub album: Option, pub album_artist: Option, pub track: Option, pub disc: Option, pub discs: Option, pub year: Option, pub genre: Option, pub composer: Option, pub compilation: Option, /// Seconds, as the file's audio properties say. pub duration: Option, /// Kilobits a second. pub bitrate: Option, pub sample_rate: Option, /// The codec inside the box when the extension does not say it: an /// `.m4a` holds AAC or ALAC. pub lossless: Option, pub lyrics: Option, /// LRC text: from a SYLT frame, an LRC-shaped lyrics tag, or a `.lrc` /// beside the file (then `lyrics_beside` says so). pub synced_lyrics: Option, pub lyrics_beside: Option, pub track_gain: Option, pub track_peak: Option, pub album_gain: Option, pub album_peak: Option, pub isrc: Option, pub mb_recording: Option, pub mb_release: Option, pub mb_release_group: Option, pub mb_artist: Option, pub mb_album_artist: Option, /// The MusicBrainz track id of this song on its release /// (MUSICBRAINZ_RELEASETRACKID), never the recording's. pub mb_release_track: Option, /// How the artist's name sorts (ARTISTSORT, TSOP, soar). pub artist_sort: Option, /// How the album artist's name sorts (ALBUMARTISTSORT, TSO2, soaa). pub album_artist_sort: Option, /// When the release first came out (ORIGINALDATE, TDOR), as tagged. pub original_date: Option, /// The release's label (LABEL, TPUB). pub label: Option, pub catalog_number: Option, pub barcode: Option, /// The kind of release as tagged (RELEASETYPE, MusicBrainz Album Type), /// any case, maybe several (`album; live`): [`release_type`] reads it. pub release_type: Option, } /// The fields a reader asks a file for, as [`Tags`] names them: the Mac's /// lofty reader and the phone's TagLib reader read this list, and nothing /// beyond it. pub const TAG_FIELDS: [&str; 36] = [ "title", "artist", "album", "albumArtist", "track", "disc", "discs", "year", "genre", "composer", "compilation", "duration", "bitrate", "sampleRate", "lossless", "lyrics", "syncedLyrics", "lyricsBeside", "trackGain", "trackPeak", "albumGain", "albumPeak", "isrc", "mbRecording", "mbRelease", "mbReleaseGroup", "mbArtist", "mbAlbumArtist", "mbReleaseTrack", "artistSort", "albumArtistSort", "originalDate", "label", "catalogNumber", "barcode", "releaseType", ]; /// The kinds of release `music_album.release_type` holds. pub const RELEASE_TYPES: [&str; 7] = ["album", "single", "ep", "compilation", "live", "soundtrack", "other"]; /// A tagged kind of release as `music_album.release_type` holds it: the /// first of compilation, live or soundtrack it names (MusicBrainz' secondary /// types say more than the primary), else album, single or ep, else `other` /// for any kind named (broadcast, spokenword, …); `None` for an empty tag. pub fn release_type(tagged: &str) -> Option<&'static str> { let kinds: Vec = tagged.split([';', '/', ',', '\0']).map(|kind| kind.trim().to_lowercase()).filter(|kind| !kind.is_empty()).collect(); if kinds.is_empty() { return None; } let named = |wanted: &[&'static str]| kinds.iter().find_map(|kind| wanted.iter().copied().find(|w| *w == kind)); Some(named(&["compilation", "live", "soundtrack"]).or_else(|| named(&["album", "single", "ep"])).unwrap_or("other")) } /// The year in front of a tagged date (`1997`, `1997-03-02`); `None` when it /// does not start with four digits. pub fn year_of(date: &str) -> Option { let year: String = date.trim().chars().take(4).collect(); (year.len() == 4 && year.chars().all(|c| c.is_ascii_digit())).then_some(year) } /// The name an artist row sorts by: the tag's sort name when the file gave /// one for exactly this name, else [`sort_name`]. pub fn sort_name_of(name: &str, tagged: Option<&str>) -> String { tagged.map(str::trim).filter(|sort| !sort.is_empty()).map(str::to_string).unwrap_or_else(|| sort_name(name)) } /// What a song's tags bring its album, column by column, beyond its title, /// artist, compilation mark and cover: a new album takes them all, a held one /// only those it holds empty. One list for the phone's capture and the Mac's /// import. pub fn album_fields(facts: &SongFacts, tags: &Tags) -> Vec<(&'static str, serde_json::Value)> { use serde_json::Value; let text = |value: &Option| words(value).map(Value::from); [ ("year", facts.year.clone().map(Value::from)), ("discs", tags.discs.filter(|n| *n > 0).map(Value::from)), ("album_gain", tags.album_gain.map(Value::from)), ("album_peak", tags.album_peak.map(Value::from)), ("mb_release", text(&tags.mb_release)), ("mb_release_group", text(&tags.mb_release_group)), ("original_year", tags.original_date.as_deref().and_then(year_of).map(Value::from)), ("release_type", tags.release_type.as_deref().and_then(release_type).map(Value::from)), ("label", text(&tags.label)), ("catalog_number", text(&tags.catalog_number)), ("barcode", text(&tags.barcode)), ] .into_iter() .filter_map(|(key, value)| value.map(|value| (key, value))) .collect() } /// The album columns [`album_fields`] may write, in its order. pub const ALBUM_FIELDS: [&str; 11] = ["year", "discs", "album_gain", "album_peak", "mb_release", "mb_release_group", "original_year", "release_type", "label", "catalog_number", "barcode"]; /// A new song's row, column for column, for the phone's capture and the /// Mac's import alike: `key` its file, `artist` and `album` the rows it /// links, `today` its added_on. pub fn song_row(facts: &SongFacts, key: &str, artist: Option, album: Option, today: &str) -> serde_json::Map { use serde_json::Value; let mut data = serde_json::Map::new(); let mut put = |key: &str, value: Option| { if let Some(value) = value { data.insert(key.to_string(), value); } }; let text = |value: &Option| value.clone().map(Value::from); put("title", Some(Value::from(facts.title.clone()))); put("artist_name", text(&facts.artist_name)); put("artist", artist.map(Value::from)); put("album", album.map(Value::from)); put("file", Some(Value::from(key))); put("format", Some(Value::from(facts.format.clone()))); put("duration", facts.duration.map(Value::from)); put("track_number", facts.track_number.map(Value::from)); put("disc_number", facts.disc_number.map(Value::from)); put("year", text(&facts.year)); put("genre", text(&facts.genre)); put("composer", text(&facts.composer)); put("lyrics", text(&facts.lyrics)); put("synced_lyrics", text(&facts.synced_lyrics)); put("lyrics_source", facts.lyrics_source.map(Value::from)); put("track_gain", facts.track_gain.map(Value::from)); put("track_peak", facts.track_peak.map(Value::from)); put("bitrate", facts.bitrate.map(Value::from)); put("sample_rate", facts.sample_rate.map(Value::from)); put("isrc", text(&facts.isrc)); put("mb_recording", text(&facts.mb_recording)); put("mb_release_track", text(&facts.mb_release_track)); put("path", Some(Value::from(facts.path.clone()))); put("source", Some(Value::from(facts.source))); put("added_on", Some(Value::from(today))); data } /// What a path says, read right to left: `…/Artist/Album (Year)/01 Title.ext`. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct PathFacts { pub artist: Option, pub album: Option, pub year: Option, pub disc: Option, pub track: Option, pub title: Option, } /// One song's row as its file and its path say it, before any lookup. #[derive(Debug, Clone, Default, PartialEq, Serialize)] pub struct SongFacts { pub title: String, pub artist_name: Option, pub album_title: Option, pub album_artist: Option, pub track_number: Option, pub disc_number: Option, pub year: Option, pub genre: Option, pub composer: Option, pub format: String, pub duration: Option, pub bitrate: Option, pub sample_rate: Option, pub lyrics: Option, pub synced_lyrics: Option, /// `file` or `sidecar`, with lyrics of either kind. pub lyrics_source: Option<&'static str>, pub track_gain: Option, pub track_peak: Option, pub isrc: Option, pub mb_recording: Option, pub mb_release_track: Option, /// `file` when the tags named the title, `folder` when the path did. pub source: &'static str, pub path: String, } fn words(value: &Option) -> Option { value.as_deref().map(str::trim).filter(|value| !value.is_empty()).map(str::to_string) } /// A song's `format` from its file's extension, and from the codec for a box /// that holds either; `None` for a file no song is. pub fn format_of(ext: &str, lossless: Option) -> Option<&'static str> { Some(match ext.trim_start_matches('.').to_ascii_lowercase().as_str() { "mp3" => "mp3", "m4a" | "mp4" | "aac" => { if lossless == Some(true) { "alac" } else { "aac" } } "flac" => "flac", "opus" => "opus", "ogg" | "oga" => "vorbis", "wav" | "wave" => "wav", "aif" | "aiff" | "aifc" => "aiff", _ => return None, }) } /// Whether a format keeps every sample. pub fn is_lossless(format: &str) -> bool { matches!(format, "flac" | "alac" | "wav" | "aiff") } /// Whether file `a` is the better of two files of one song: lossless over /// lossy, then the higher bitrate. A tie keeps the one already here. pub fn better(a_format: &str, a_bitrate: Option, b_format: &str, b_bitrate: Option) -> bool { match (is_lossless(a_format), is_lossless(b_format)) { (true, false) => true, (false, true) => false, _ => a_bitrate.unwrap_or(0) > b_bitrate.unwrap_or(0), } } /// A name as one key: trimmed, its runs of space one, lower case. pub fn fold(name: &str) -> String { name.split_whitespace().collect::>().join(" ").to_lowercase() } /// Whether two songs are one song in two files: artist, title and album alike /// and their lengths within [`SAME_LENGTH_SECONDS`]. pub fn same_song(a: (&str, &str, &str, Option), b: (&str, &str, &str, Option)) -> bool { let close = match (a.3, b.3) { (Some(x), Some(y)) => (x - y).abs() <= SAME_LENGTH_SECONDS, _ => false, }; close && fold(a.0) == fold(b.0) && fold(a.1) == fold(b.1) && fold(a.2) == fold(b.2) } /// An album's key: its album artist and its title, folded. pub fn album_key(album_artist: &str, title: &str) -> String { format!("{}\u{1f}{}", fold(album_artist), fold(title)) } /// The primary artist of a credit: "A feat. B" is A's song. pub fn primary_artist(credit: &str) -> &str { let lower = credit.to_lowercase(); let cut = [" feat. ", " feat ", " ft. ", " featuring ", " with "] .iter() .filter_map(|mark| lower.find(mark)) .min() .unwrap_or(credit.len()); credit[..cut].trim() } /// The name an artist sorts by: without a leading "The". pub fn sort_name(name: &str) -> String { let name = name.trim(); match name.get(..4) { Some(head) if head.eq_ignore_ascii_case("the ") && name.len() > 4 => name[4..].trim_start().to_string(), _ => name.to_string(), } } fn number(text: &str) -> Option { text.parse::().ok().filter(|n| *n > 0) } /// `01 Title`, `01 - Title`, `1-03 Title` (disc 1, track 3), `01. Title`; /// `(None, None, name)` for a name with no number in front. fn numbered(stem: &str) -> (Option, Option, String) { let stem = stem.trim(); let digits: String = stem.chars().take_while(char::is_ascii_digit).collect(); if digits.is_empty() || digits.len() > 3 { return (None, None, stem.to_string()); } let mut rest = &stem[digits.len()..]; let mut disc = None; let mut track = number(&digits); if let Some(after) = rest.strip_prefix('-') { let second: String = after.chars().take_while(char::is_ascii_digit).collect(); if !second.is_empty() && second.len() <= 3 { disc = track; track = number(&second); rest = &after[second.len()..]; } } let title = rest.trim_start_matches(|c: char| c == ' ' || c == '.' || c == '-' || c == '_').trim(); if title.is_empty() { return (None, None, stem.to_string()); } (disc, track, title.to_string()) } /// `Album (1997)` or `Album [1997]` → the album and its year. fn album_year(folder: &str) -> (String, Option) { let folder = folder.trim(); for (open, close) in [('(', ')'), ('[', ']')] { if let Some(stripped) = folder.strip_suffix(close) { if let Some(at) = stripped.rfind(open) { let year = stripped[at + 1..].trim(); if year.len() == 4 && year.chars().all(|c| c.is_ascii_digit()) { let album = stripped[..at].trim(); if !album.is_empty() { return (album.to_string(), Some(year.to_string())); } } } } } (folder.to_string(), None) } /// A disc folder inside an album's: `CD1`, `Disc 2`, `Disc 02`. fn disc_folder(folder: &str) -> Option { let lower = folder.trim().to_lowercase(); let rest = lower.strip_prefix("cd").or_else(|| lower.strip_prefix("disc")).or_else(|| lower.strip_prefix("disk"))?; number(rest.trim()) } /// What a path says of its song, read from the file's name and the two or /// three folders above it; nothing from a folder a picker or the share sheet /// made up stands, since only `Artist/Album/` layouts are read. pub fn path_facts(path: &str) -> PathFacts { let parts: Vec<&str> = path.split('/').map(str::trim).filter(|part| !part.is_empty()).collect(); let Some(file) = parts.last() else { return PathFacts::default() }; let stem = match file.rfind('.') { Some(at) if at > 0 => &file[..at], _ => file, }; let (disc, track, mut title) = numbered(stem); let mut facts = PathFacts { disc, track, ..PathFacts::default() }; let mut folders: Vec<&str> = parts[..parts.len() - 1].to_vec(); if let Some(disc) = folders.last().and_then(|folder| disc_folder(folder)) { facts.disc = facts.disc.or(Some(disc)); folders.pop(); } // `Artist - Title` in a file's own name, when no folder names the artist. if folders.len() < 2 { if let Some((artist, rest)) = title.split_once(" - ") { if !artist.trim().is_empty() && !rest.trim().is_empty() { facts.artist = Some(artist.trim().to_string()); title = rest.trim().to_string(); } } } if folders.len() >= 2 { let (album, year) = album_year(folders[folders.len() - 1]); facts.album = Some(album); facts.year = year; facts.artist = Some(folders[folders.len() - 2].to_string()); } facts.title = Some(title).filter(|title| !title.is_empty()); facts } /// The song row a file makes: its tags first, its path filling only what /// they left empty and only where it agrees with them: the folders' artist, /// album and year stand when the tags name no album or the same one. The /// album artist is the tags', then Various Artists for a compilation, then /// the agreeing folder's artist, then the song's own tagged artist. `None` /// when the extension is no song's. pub fn song_from(tags: &Tags, path: &str, ext: &str) -> Option { let format = format_of(ext, tags.lossless)?; let tagged_album = words(&tags.album); let mut from_path = path_facts(path); // The folders above a file are `Artist/Album/` only when they agree with // its tags: a folder that names another album than the tags' is a dump // (`scratchpad/music-in/`), and its artist, album and year say nothing. if let (Some(tagged), Some(folder)) = (&tagged_album, &from_path.album) { if fold(tagged) != fold(folder) { from_path.artist = None; from_path.album = None; from_path.year = None; } } let tagged_title = words(&tags.title); let source = if tagged_title.is_some() { "file" } else { "folder" }; let title = tagged_title.or(from_path.title.clone()).unwrap_or_else(|| path.rsplit('/').next().unwrap_or(path).to_string()); let artist_name = words(&tags.artist).or(from_path.artist.clone()); let compilation = tags.compilation == Some(true); let album_artist = words(&tags.album_artist) .or_else(|| compilation.then(|| VARIOUS_ARTISTS.to_string())) .or(from_path.artist.clone()) .or(words(&tags.artist)); let (lyrics_source, synced_lyrics) = match words(&tags.synced_lyrics) { Some(lrc) => (Some(if tags.lyrics_beside == Some(true) { "sidecar" } else { "file" }), Some(lrc)), None => (None, None), }; let lyrics = words(&tags.lyrics).or_else(|| synced_lyrics.as_deref().map(plain_of_lrc).filter(|text| !text.is_empty())); let lyrics_source = lyrics_source.or(lyrics.as_ref().map(|_| "file")); Some(SongFacts { title, artist_name, album_title: tagged_album.or(from_path.album.clone()), album_artist, track_number: tags.track.filter(|n| *n > 0).or(from_path.track), disc_number: tags.disc.filter(|n| *n > 0).or(from_path.disc), year: words(&tags.year).map(|year| year.chars().take(4).collect()).or(from_path.year.clone()), genre: words(&tags.genre), composer: words(&tags.composer), format: format.to_string(), duration: tags.duration.filter(|seconds| *seconds > 0.0), bitrate: tags.bitrate.filter(|n| *n > 0), sample_rate: tags.sample_rate.filter(|n| *n > 0), lyrics, synced_lyrics, lyrics_source, track_gain: tags.track_gain, track_peak: tags.track_peak, isrc: words(&tags.isrc), mb_recording: words(&tags.mb_recording), mb_release_track: words(&tags.mb_release_track), source, path: path.to_string(), }) } /// LRC's words without its time marks, one line a line: the plain lyrics a /// file that carries only timed ones still has. pub fn plain_of_lrc(lrc: &str) -> String { lrc.lines() .filter_map(|line| { let mut rest = line.trim(); let mut timed = false; while let Some(after) = rest.strip_prefix('[') { let Some(end) = after.find(']') else { break }; let mark = &after[..end]; if !mark.chars().next().is_some_and(|c| c.is_ascii_digit()) { // `[ar: …]` and the other header tags carry no words. return None; } timed = true; rest = after[end + 1..].trim_start(); } (timed || !rest.is_empty()).then(|| rest.to_string()) }) .collect::>() .join("\n") .trim() .to_string() } #[cfg(test)] mod tests;