diff --git a/Cargo.lock b/Cargo.lock index 9980282..869349c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4967,6 +4967,9 @@ version = "0.1.0" [[package]] name = "tunal-tags" version = "0.1.0" +dependencies = [ + "lofty", +] [[package]] name = "tunal-theme" diff --git a/Plans/07 Tag editor/S019-tag-model.md b/Plans/07 Tag editor/S019-tag-model.md index 7dcf3e0..f2f49ce 100644 --- a/Plans/07 Tag editor/S019-tag-model.md +++ b/Plans/07 Tag editor/S019-tag-model.md @@ -10,12 +10,12 @@ Read and write music tags for one or many files, merge many files into one edita docs/DECISIONS.md D-011; lofty docs in ~/.cargo/registry. ## Steps -- [ ] `TrackTags`: title, artist, album, album artist, track no/total, disc no/total, date, genre, composer, comment, MusicBrainz ids, pictures. -- [ ] Read/write with lofty, preserving fields we don't edit. -- [ ] `TagSet` for many files: each field Same(v) or Mixed; edits with Keep semantics. -- [ ] Cover: set/replace/remove the front cover (JPEG/PNG). -- [ ] Example `--example tags -- ` dumps and writes a field on fixtures generated with ffmpeg in the scratchpad (mp3, flac, ogg, m4a). -- [ ] PROGRESS entry, INDEX line, commit `S019: …` +- [x] `TrackTags`: title, artist, album, album artist, track no/total, disc no/total, date, genre, composer, comment, MusicBrainz ids, pictures. +- [x] Read/write with lofty, preserving fields we don't edit. +- [x] `TagSet` for many files: each field Same(v) or Mixed; edits with Keep semantics. +- [x] Cover: set/replace/remove the front cover (JPEG/PNG). +- [x] Example `--example tags -- ` dumps and writes a field on fixtures generated with ffmpeg in the scratchpad (mp3, flac, ogg, m4a). +- [x] PROGRESS entry, INDEX line, commit `S019: …` ## End criteria - `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index dc6c63e..19e1fef 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -42,7 +42,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v ## 07 Tag editor -- [ ] [S019 — Tag model with lofty](07%20Tag%20editor/S019-tag-model.md) · Sonnet medium +- [x] [S019 — Tag model with lofty](07%20Tag%20editor/S019-tag-model.md) · Sonnet medium - [ ] [S020 — MusicBrainz and Cover Art Archive client](07%20Tag%20editor/S020-musicbrainz-client.md) · Sonnet high - [ ] [S021 — Tag editor UI](07%20Tag%20editor/S021-tag-editor-ui.md) · Opus medium diff --git a/crates/tunal-tags/Cargo.toml b/crates/tunal-tags/Cargo.toml index ea9bdba..772698c 100644 --- a/crates/tunal-tags/Cargo.toml +++ b/crates/tunal-tags/Cargo.toml @@ -4,3 +4,6 @@ version.workspace = true edition.workspace = true license.workspace = true publish.workspace = true + +[dependencies] +lofty.workspace = true diff --git a/crates/tunal-tags/examples/tags.rs b/crates/tunal-tags/examples/tags.rs new file mode 100644 index 0000000..0fc9589 --- /dev/null +++ b/crates/tunal-tags/examples/tags.rs @@ -0,0 +1,126 @@ +//! `tags [--title T] [--artist A] [--album A] [--comment C] [--track N] [--cover IMG] [--no-cover] ` +//! Dumps the tags of every file; with edit options, writes them first (files are modified in place). + +use std::path::PathBuf; + +use tunal_tags::{Cover, CoverEdit, Edit, Merged, TagEdit, TagSet, TrackTags}; + +fn main() { + let mut edit = TagEdit::default(); + let mut files = Vec::new(); + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + let mut value = |name: &str| { + args.next() + .unwrap_or_else(|| usage(&format!("{name} needs a value"))) + }; + match arg.as_str() { + "--title" => edit.title = Edit::Set(value("--title")), + "--artist" => edit.artist = Edit::Set(value("--artist")), + "--album" => edit.album = Edit::Set(value("--album")), + "--comment" => edit.comment = Edit::Set(value("--comment")), + "--track" => match value("--track").parse() { + Ok(n) => edit.track_no = Edit::Set(n), + Err(_) => usage("--track needs a number"), + }, + "--cover" => { + let path = value("--cover"); + let data = std::fs::read(&path).unwrap_or_else(|e| usage(&format!("{path}: {e}"))); + let mime = if data.starts_with(&[0xFF, 0xD8]) { + "image/jpeg" + } else { + "image/png" + }; + edit.cover = CoverEdit::Set(Cover { + mime: mime.into(), + data, + }); + } + "--no-cover" => edit.cover = CoverEdit::Remove, + s if s.starts_with("--") => usage(&format!("unknown option {s}")), + _ => files.push(PathBuf::from(arg)), + } + } + if files.is_empty() { + usage("no files"); + } + + if !edit.is_empty() { + for (path, result) in tunal_tags::write_many(&files, &edit) { + match result { + Ok(()) => println!("wrote {}", path.display()), + Err(e) => println!("write failed {}: {e}", path.display()), + } + } + } + for path in &files { + match tunal_tags::read(path) { + Ok(t) => dump(path, &t), + Err(e) => println!("{}: {e}", path.display()), + } + } + if files.len() > 1 { + let (set, failed) = tunal_tags::read_set(&files); + println!( + "\nmerged over {} files ({} failed):", + set.count, + failed.len() + ); + dump_set(&set); + } +} + +fn usage(msg: &str) -> ! { + eprintln!( + "{msg}\nusage: tags [--title T] [--artist A] [--album A] [--comment C] [--track N] [--cover IMG] [--no-cover] " + ); + std::process::exit(1); +} + +fn dump(path: &std::path::Path, t: &TrackTags) { + println!("\n{}", path.display()); + let cover = t + .cover + .as_ref() + .map(|c| format!("{} {} bytes", c.mime, c.data.len())); + println!( + " title={:?} artist={:?} album={:?} album_artist={:?}\n track={:?}/{:?} disc={:?}/{:?} date={:?} genre={:?} composer={:?} comment={:?}\n mb_recording={:?} mb_release={:?}\n cover={cover:?} other_pictures={}", + t.title, + t.artist, + t.album, + t.album_artist, + t.track_no, + t.track_total, + t.disc_no, + t.disc_total, + t.date, + t.genre, + t.composer, + t.comment, + t.mb_recording_id, + t.mb_release_id, + t.other_pictures + ); +} + +fn show(m: &Merged) -> String { + match m { + Merged::Same(v) => format!("{v:?}"), + Merged::Mixed => "".into(), + } +} + +fn dump_set(s: &TagSet) { + println!( + " title={} artist={} album={} track={}", + show(&s.title), + show(&s.artist), + show(&s.album), + show(&s.track_no) + ); + let cover = match &s.cover { + Merged::Same(c) => format!("{:?}", c.as_ref().map(|c| c.data.len())), + Merged::Mixed => "".into(), + }; + println!(" cover={cover}"); +} diff --git a/crates/tunal-tags/src/io.rs b/crates/tunal-tags/src/io.rs new file mode 100644 index 0000000..13218e7 --- /dev/null +++ b/crates/tunal-tags/src/io.rs @@ -0,0 +1,257 @@ +//! Reading and writing tags with lofty. Only the fields an edit names are touched. + +use std::fmt; +use std::path::{Path, PathBuf}; + +use lofty::config::WriteOptions; +use lofty::file::{AudioFile, TaggedFile, TaggedFileExt}; +use lofty::picture::{MimeType, Picture, PictureType}; +use lofty::tag::{Accessor, ItemKey, Tag, TagType}; + +use crate::model::{Cover, CoverEdit, Edit, TagEdit, TagSet, TrackTags}; + +#[derive(Debug)] +pub enum Error { + Io(std::io::Error), + /// lofty could not read or write the file. + Tag(String), + /// The cover is neither JPEG nor PNG. + BadImage, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Io(e) => write!(f, "{e}"), + Error::Tag(e) => write!(f, "{e}"), + Error::BadImage => write!(f, "the cover must be a JPEG or PNG image"), + } + } +} + +impl std::error::Error for Error {} + +fn tag_err(e: impl fmt::Display) -> Error { + Error::Tag(e.to_string()) +} + +const MB_KEYS: [ItemKey; 6] = [ + ItemKey::MusicBrainzRecordingId, + ItemKey::MusicBrainzTrackId, + ItemKey::MusicBrainzReleaseId, + ItemKey::MusicBrainzReleaseGroupId, + ItemKey::MusicBrainzArtistId, + ItemKey::MusicBrainzReleaseArtistId, +]; + +fn text(tag: &Tag, key: ItemKey) -> Option { + tag.get_string(key) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) +} + +/// Index of the front cover. MP4 pictures carry no type, so its first picture counts. +fn front_index(tag: &Tag) -> Option { + let pictures = tag.pictures(); + pictures + .iter() + .position(|p| p.pic_type() == PictureType::CoverFront) + .or_else(|| (tag.tag_type() == TagType::Mp4Ilst && !pictures.is_empty()).then_some(0)) +} + +fn front_cover(tag: &Tag) -> Option<&Picture> { + front_index(tag).map(|i| &tag.pictures()[i]) +} + +fn read_tag(tag: &Tag) -> TrackTags { + let cover = front_cover(tag).map(|p| Cover { + mime: p + .mime_type() + .map_or("image/jpeg", |m| m.as_str()) + .to_owned(), + data: p.data().to_vec(), + }); + let fronts = usize::from(cover.is_some()); + let string = |s: Option>| { + s.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()) + }; + TrackTags { + title: string(tag.title()), + artist: string(tag.artist()), + album: string(tag.album()), + album_artist: text(tag, ItemKey::AlbumArtist), + track_no: tag.track(), + track_total: tag.track_total(), + disc_no: tag.disk(), + disc_total: tag.disk_total(), + date: text(tag, ItemKey::RecordingDate).or_else(|| text(tag, ItemKey::Year)), + genre: string(tag.genre()), + composer: text(tag, ItemKey::Composer), + comment: text(tag, ItemKey::Comment), + mb_recording_id: text(tag, MB_KEYS[0]), + mb_track_id: text(tag, MB_KEYS[1]), + mb_release_id: text(tag, MB_KEYS[2]), + mb_release_group_id: text(tag, MB_KEYS[3]), + mb_artist_id: text(tag, MB_KEYS[4]), + mb_release_artist_id: text(tag, MB_KEYS[5]), + cover, + other_pictures: tag.picture_count() as usize - fronts, + } +} + +fn open(path: &Path) -> Result { + lofty::read_from_path(path).map_err(tag_err) +} + +/// Reads the tags of one file. A file without a tag gives empty tags. +pub fn read(path: &Path) -> Result { + let tagged = open(path)?; + Ok(tagged + .primary_tag() + .or_else(|| tagged.first_tag()) + .map(read_tag) + .unwrap_or_default()) +} + +/// Reads many files and merges them. Files that fail are returned with their error and left out. +pub fn read_set(paths: &[PathBuf]) -> (TagSet, Vec<(PathBuf, Error)>) { + let mut tracks = Vec::new(); + let mut failed = Vec::new(); + for path in paths { + match read(path) { + Ok(t) => tracks.push(t), + Err(e) => failed.push((path.clone(), e)), + } + } + (TagSet::merge(&tracks), failed) +} + +fn set_text(tag: &mut Tag, key: ItemKey, edit: &Edit) { + match edit { + Edit::Keep => {} + Edit::Set(v) if !v.trim().is_empty() => { + tag.insert_text(key, v.trim().to_owned()); + } + Edit::Set(_) | Edit::Clear => tag.remove_key(key), + } +} + +fn set_number(tag: &mut Tag, edit: &Edit, set: fn(&mut Tag, u32), remove: fn(&mut Tag)) { + match edit { + Edit::Keep => {} + Edit::Set(v) => set(tag, *v), + Edit::Clear => remove(tag), + } +} + +fn apply_to_tag(tag: &mut Tag, edit: &TagEdit) -> Result<(), Error> { + set_text(tag, ItemKey::TrackTitle, &edit.title); + set_text(tag, ItemKey::TrackArtist, &edit.artist); + set_text(tag, ItemKey::AlbumTitle, &edit.album); + set_text(tag, ItemKey::AlbumArtist, &edit.album_artist); + set_text(tag, ItemKey::Genre, &edit.genre); + set_text(tag, ItemKey::Composer, &edit.composer); + set_text(tag, ItemKey::Comment, &edit.comment); + set_text(tag, ItemKey::RecordingDate, &edit.date); + set_number( + tag, + &edit.track_no, + |t, v| t.set_track(v), + |t| t.remove_track(), + ); + set_number( + tag, + &edit.track_total, + |t, v| t.set_track_total(v), + |t| t.remove_track_total(), + ); + set_number( + tag, + &edit.disc_no, + |t, v| t.set_disk(v), + |t| t.remove_disk(), + ); + set_number( + tag, + &edit.disc_total, + |t, v| t.set_disk_total(v), + |t| t.remove_disk_total(), + ); + let mb = [ + &edit.mb_recording_id, + &edit.mb_track_id, + &edit.mb_release_id, + &edit.mb_release_group_id, + &edit.mb_artist_id, + &edit.mb_release_artist_id, + ]; + for (key, value) in MB_KEYS.into_iter().zip(mb) { + set_text(tag, key, value); + } + match &edit.cover { + CoverEdit::Keep => {} + CoverEdit::Remove => { + if let Some(i) = front_index(tag) { + tag.remove_picture(i); + } + } + CoverEdit::Set(cover) => { + let mime = image_mime(&cover.data).ok_or(Error::BadImage)?; + let picture = Picture::unchecked(cover.data.clone()) + .pic_type(PictureType::CoverFront) + .mime_type(mime) + .build(); + // Replace the front cover and keep every other picture. + match front_index(tag) { + Some(i) => tag.set_picture(i, picture), + None => tag.push_picture(picture), + } + } + } + Ok(()) +} + +fn image_mime(data: &[u8]) -> Option { + if data.starts_with(&[0xFF, 0xD8, 0xFF]) { + Some(MimeType::Jpeg) + } else if data.starts_with(&[0x89, b'P', b'N', b'G']) { + Some(MimeType::Png) + } else { + None + } +} + +/// Applies an edit to one file, leaving every field it does not name as it was. +/// The file is rewritten in place by lofty. +pub fn write(path: &Path, edit: &TagEdit) -> Result<(), Error> { + if edit.is_empty() { + return Ok(()); + } + let mut tagged = open(path)?; + if tagged.primary_tag().is_none() { + let tag = match tagged.first_tag_mut() { + Some(_) => None, + None => Some(Tag::new(tagged.primary_tag_type())), + }; + if let Some(tag) = tag { + tagged.insert_tag(tag); + } + } + let tag = match tagged.primary_tag_mut() { + Some(t) => t, + None => tagged + .first_tag_mut() + .ok_or_else(|| Error::Tag("the format has no tags".into()))?, + }; + apply_to_tag(tag, edit)?; + tagged + .save_to_path(path, WriteOptions::default()) + .map_err(tag_err)?; + Ok(()) +} + +/// Applies the same edit to many files; one result per file, in order. +pub fn write_many(paths: &[PathBuf], edit: &TagEdit) -> Vec<(PathBuf, Result<(), Error>)> { + paths.iter().map(|p| (p.clone(), write(p, edit))).collect() +} diff --git a/crates/tunal-tags/src/lib.rs b/crates/tunal-tags/src/lib.rs index c31abc7..31e1685 100644 --- a/crates/tunal-tags/src/lib.rs +++ b/crates/tunal-tags/src/lib.rs @@ -1 +1,7 @@ //! Music tags and the MusicBrainz and Cover Art Archive client. + +mod io; +mod model; + +pub use io::{Error, read, read_set, write, write_many}; +pub use model::{Cover, CoverEdit, Edit, Merged, TagEdit, TagSet, TrackTags}; diff --git a/crates/tunal-tags/src/model.rs b/crates/tunal-tags/src/model.rs new file mode 100644 index 0000000..45c60ca --- /dev/null +++ b/crates/tunal-tags/src/model.rs @@ -0,0 +1,152 @@ +//! Tag values for one file, the merged view of many files and edits with Keep semantics. + +/// A front cover image (JPEG or PNG). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Cover { + pub mime: String, + pub data: Vec, +} + +/// One field over many files: every file has the same value, or they differ. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Merged { + /// `None` when no file has a value. + Same(Option), + Mixed, +} + +/// What to do with one field: leave each file as it is (Keep), set a value or clear it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum Edit { + #[default] + Keep, + Set(T), + Clear, +} + +/// What to do with the front cover. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum CoverEdit { + #[default] + Keep, + Set(Cover), + Remove, +} + +macro_rules! fields { + ($($name:ident: $ty:ty),+ $(,)?) => { + /// The tags of one file. Empty values are `None`. + #[derive(Clone, Debug, Default, PartialEq, Eq)] + pub struct TrackTags { + $(pub $name: Option<$ty>,)+ + pub cover: Option, + /// Pictures other than the front cover (read-only; kept when writing). + pub other_pictures: usize, + } + + /// The tags of many files, field by field. + #[derive(Clone, Debug, PartialEq, Eq)] + pub struct TagSet { + pub count: usize, + $(pub $name: Merged<$ty>,)+ + pub cover: Merged, + } + + /// Edits for many files; every field starts as Keep. + #[derive(Clone, Debug, Default, PartialEq, Eq)] + pub struct TagEdit { + $(pub $name: Edit<$ty>,)+ + pub cover: CoverEdit, + } + + impl TagSet { + /// Merges the tags of several files. An empty slice gives an all-empty set. + pub fn merge(tracks: &[TrackTags]) -> TagSet { + TagSet { + count: tracks.len(), + $($name: merge_field(tracks.iter().map(|t| &t.$name)),)+ + cover: merge_field(tracks.iter().map(|t| &t.cover)), + } + } + } + + impl TagEdit { + /// True when every field is Keep. + pub fn is_empty(&self) -> bool { + true $(&& self.$name == Edit::Keep)+ && self.cover == CoverEdit::Keep + } + + /// Applies the edit to in-memory tags. + pub fn apply(&self, tags: &mut TrackTags) { + $(self.$name.apply(&mut tags.$name);)+ + match &self.cover { + CoverEdit::Keep => {} + CoverEdit::Set(c) => tags.cover = Some(c.clone()), + CoverEdit::Remove => tags.cover = None, + } + } + + /// An edit that sets every field to what `tags` holds (empty fields are cleared). + pub fn set_all(tags: &TrackTags) -> TagEdit { + TagEdit { + $($name: Edit::from_option(&tags.$name),)+ + cover: match &tags.cover { + Some(c) => CoverEdit::Set(c.clone()), + None => CoverEdit::Remove, + }, + } + } + } + }; +} + +fields! { + title: String, + artist: String, + album: String, + album_artist: String, + track_no: u32, + track_total: u32, + disc_no: u32, + disc_total: u32, + date: String, + genre: String, + composer: String, + comment: String, + mb_recording_id: String, + mb_track_id: String, + mb_release_id: String, + mb_release_group_id: String, + mb_artist_id: String, + mb_release_artist_id: String, +} + +fn merge_field<'a, T: Clone + PartialEq + 'a>( + mut values: impl Iterator>, +) -> Merged { + let Some(first) = values.next() else { + return Merged::Same(None); + }; + if values.all(|v| v == first) { + Merged::Same(first.clone()) + } else { + Merged::Mixed + } +} + +impl Edit { + fn apply(&self, field: &mut Option) { + match self { + Edit::Keep => {} + Edit::Set(v) => *field = Some(v.clone()), + Edit::Clear => *field = None, + } + } + + fn from_option(value: &Option) -> Edit { + match value { + Some(v) => Edit::Set(v.clone()), + None => Edit::Clear, + } + } +} diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 04df37b..40bb1d8 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -56,5 +56,11 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: cancel and timeout paths not exercised (code only); SVG `` did not render in the smoke run (system fonts not found in this environment; geometry fine); local files only — remote requests are gated by the flag, the pool reads `std::fs` (S018/UI must hand remote files over another way). - Later: stale-thumbnail cleanup; video thumbnails of very short clips use first frame only when seek fails. +## S019 — Tag model with lofty +- Done: `tunal-tags` (lofty only). `TrackTags` (`Option` fields: title, artist, album, album_artist, track_no/total, disc_no/total, date, genre, composer, comment, six `mb_*_id`, `cover: Option`, `other_pictures` count). `TagSet::merge(&[TrackTags])` → per field `Merged::{Same(Option), Mixed}`. `TagEdit` (same fields as `Edit::{Keep, Set(v), Clear}`, `cover: CoverEdit::{Keep, Set(Cover), Remove}`; `is_empty`, `apply(&mut TrackTags)`, `TagEdit::set_all(&TrackTags)` for MusicBrainz apply). I/O: `read(path)`, `read_set(&[PathBuf]) -> (TagSet, Vec<(PathBuf, Error)>)`, `write(path, &TagEdit)` (touches only named fields; other items and non-front pictures kept; Keep-only edit writes nothing), `write_many`. `Error::{Io, Tag(String), BadImage}`. Cover must be JPEG/PNG (checked by magic bytes); MP4 front cover = its first picture. Example `tags [--title/--artist/--album/--comment/--track T] [--cover IMG|--no-cover] ` (edits in place: scratch copies only). +- Verified: workspace build, clippy -D warnings, fmt --check; ffmpeg fixtures mp3/flac/ogg/m4a in the scratchpad: title+track+cover written and read back on all four, PNG→JPEG replace, cover remove, non-image cover refused, comment/album round trip, untouched artist/genre kept, merged view over four files (cover Mixed when they differ). +- Not done: tracker artifact not updated (session had no ArtifactData). Dates are the raw string (`RecordingDate`, falls back to `Year`); no Timestamp parsing. +- Later: Vorbis `COMMENT` key (non-standard, ffmpeg writes it) is not read as the comment, only `DESCRIPTION`; lofty rewrites the file in place (no temp-file + rename); sort-order and lyrics fields; multi-value artists. + ## Later -