use super::tags::{TagItem, TagSet};
use crate::error::Error;
pub const MAX_TAG_BYTES: usize = 1 << 20;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Id3Encoding {
Utf8,
Latin1OrUtf8,
Utf16Le,
Utf16Be,
Utf16BeNoBom,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ArrangerFrame {
Tipl,
Txxx,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AlbumArtistFrame {
None,
Tpe2,
Txxx,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DateFrame {
Tdrl,
Tdrc,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Id3Options {
pub footer: bool,
pub padding: u32,
pub frame_order: Vec<[u8; 4]>,
pub encoding: Id3Encoding,
pub terminate_last: bool,
pub control_replacement: Option<char>,
pub split: Option<String>,
pub arranger: ArrangerFrame,
pub join_messages: Option<String>,
pub phonetic: bool,
pub track_count: bool,
pub album_artist: AlbumArtistFrame,
pub copyright: bool,
pub album_set_alone: bool,
pub date: DateFrame,
pub language: [u8; 3],
pub message_description: String,
pub extra_message_description: String,
pub arranger_description: String,
pub album_artist_description: String,
}
pub const TABLE_ORDER: [[u8; 4]; 18] = [
*b"TIT2", *b"TPE1", *b"TEXT", *b"TCOM", *b"TIPL", *b"COMM", *b"TSOT", *b"TSOP", *b"TRCK", *b"TSRC",
*b"TCON", *b"TALB", *b"TPE2", *b"TXXX", *b"TPUB", *b"TCOP", *b"TPOS", *b"TDRL",
];
impl Default for Id3Options {
fn default() -> Self {
let mut order = TABLE_ORDER.to_vec();
order.push(*b"TDRC");
Id3Options {
footer: true,
padding: 0,
frame_order: order,
encoding: Id3Encoding::Utf8,
terminate_last: false,
control_replacement: None,
split: None,
arranger: ArrangerFrame::Tipl,
join_messages: None,
phonetic: false,
track_count: true,
album_artist: AlbumArtistFrame::None,
copyright: true,
album_set_alone: false,
date: DateFrame::Tdrl,
language: *b"XXX",
message_description: String::new(),
extra_message_description: "extra message".to_owned(),
arranger_description: "arranger".to_owned(),
album_artist_description: "album artist".to_owned(),
}
}
}
impl Id3Options {
pub fn new() -> Self {
Self::default()
}
pub fn with_footer(self, write: bool) -> Self {
Id3Options { footer: write, ..self }
}
pub fn with_padding(self, bytes: u32) -> Self {
Id3Options { padding: bytes, ..self }
}
pub fn with_frame_order(self, order: Vec<[u8; 4]>) -> Self {
Id3Options { frame_order: order, ..self }
}
pub fn with_encoding(self, encoding: Id3Encoding) -> Self {
Id3Options { encoding, ..self }
}
pub fn with_terminate_last(self, terminate: bool) -> Self {
Id3Options { terminate_last: terminate, ..self }
}
pub fn with_control_replacement(self, replacement: Option<char>) -> Self {
Id3Options { control_replacement: replacement, ..self }
}
pub fn with_split(self, separator: Option<&str>) -> Self {
Id3Options { split: separator.map(str::to_owned), ..self }
}
pub fn with_arranger(self, frame: ArrangerFrame) -> Self {
Id3Options { arranger: frame, ..self }
}
pub fn with_join_messages(self, separator: Option<&str>) -> Self {
Id3Options { join_messages: separator.map(str::to_owned), ..self }
}
pub fn with_phonetic(self, write: bool) -> Self {
Id3Options { phonetic: write, ..self }
}
pub fn with_track_count(self, write: bool) -> Self {
Id3Options { track_count: write, ..self }
}
pub fn with_album_artist(self, frame: AlbumArtistFrame) -> Self {
Id3Options { album_artist: frame, ..self }
}
pub fn with_copyright(self, write: bool) -> Self {
Id3Options { copyright: write, ..self }
}
pub fn with_album_set_alone(self, write: bool) -> Self {
Id3Options { album_set_alone: write, ..self }
}
pub fn with_date(self, frame: DateFrame) -> Self {
Id3Options { date: frame, ..self }
}
pub fn with_language(self, language: [u8; 3]) -> Self {
Id3Options { language, ..self }
}
pub fn with_message_description(self, description: &str) -> Self {
Id3Options { message_description: description.to_owned(), ..self }
}
pub fn with_extra_message_description(self, description: &str) -> Self {
Id3Options { extra_message_description: description.to_owned(), ..self }
}
pub fn with_arranger_description(self, description: &str) -> Self {
Id3Options { arranger_description: description.to_owned(), ..self }
}
pub fn with_album_artist_description(self, description: &str) -> Self {
Id3Options { album_artist_description: description.to_owned(), ..self }
}
}
fn control(c: char) -> bool {
matches!(c, '\u{0}'..='\u{1F}' | '\u{7F}'..='\u{9F}')
}
fn clean(s: &str, newlines: bool, o: &Id3Options) -> String {
s.chars()
.filter_map(|c| match c {
'\n' if newlines => Some(c),
c if control(c) => o.control_replacement.filter(|r| !control(*r) || (*r == '\n' && newlines)),
c => Some(c),
})
.collect()
}
fn text_body(prefix: &[u8], strings: &[String], last: bool, o: &Id3Options) -> Vec<u8> {
let latin1 = strings.iter().all(|s| s.chars().all(|c| c == '\n' || ('\u{20}'..='\u{FF}').contains(&c)));
let enc = match o.encoding {
Id3Encoding::Utf8 => 3,
Id3Encoding::Latin1OrUtf8 if latin1 => 0,
Id3Encoding::Latin1OrUtf8 => 3,
Id3Encoding::Utf16Le | Id3Encoding::Utf16Be => 1,
Id3Encoding::Utf16BeNoBom => 2,
};
let mut out = vec![enc];
out.extend_from_slice(prefix);
for (i, s) in strings.iter().enumerate() {
match o.encoding {
Id3Encoding::Utf16Le => {
out.extend(std::iter::once(0xFEFF).chain(s.encode_utf16()).flat_map(u16::to_le_bytes))
}
Id3Encoding::Utf16Be => {
out.extend(std::iter::once(0xFEFF).chain(s.encode_utf16()).flat_map(u16::to_be_bytes))
}
Id3Encoding::Utf16BeNoBom => out.extend(s.encode_utf16().flat_map(u16::to_be_bytes)),
_ if enc == 0 => out.extend(s.chars().map(|c| c as u8)),
_ => out.extend_from_slice(s.as_bytes()),
}
if i + 1 < strings.len() || last {
out.extend_from_slice(if enc == 1 || enc == 2 { &[0, 0] } else { &[0] });
}
}
out
}
fn synchsafe(v: usize) -> [u8; 4] {
[(v >> 21) as u8 & 0x7F, (v >> 14) as u8 & 0x7F, (v >> 7) as u8 & 0x7F, v as u8 & 0x7F]
}
pub(super) fn tag(set: &TagSet, o: &Id3Options) -> Result<Option<Vec<u8>>, Error> {
if !(o.language.iter().all(u8::is_ascii_lowercase) || o.language == *b"XXX") {
return Err(Error::InvalidArgument("the COMM language is three lower-case letters or XXX"));
}
let values = |item| -> Vec<String> {
let v = set.get(item).iter().map(|s| clean(s, false, o));
match &o.split {
Some(sep) if !sep.is_empty() => {
v.flat_map(|s| s.split(sep.as_str()).map(str::to_owned).collect::<Vec<_>>()).collect()
}
_ => v.collect(),
}
};
let digits = |s: &String| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let mut frames: Vec<([u8; 4], Vec<u8>, Option<String>)> = Vec::new();
let text = |frames: &mut Vec<([u8; 4], Vec<u8>, Option<String>)>, id: &[u8; 4], strings: Vec<String>| {
if !strings.is_empty() {
frames.push((*id, text_body(&[], &strings, o.terminate_last, o), None));
}
};
let txxx = |frames: &mut Vec<([u8; 4], Vec<u8>, Option<String>)>, description: &str, value: &str| {
let strings = [clean(description, false, o), clean(value, false, o)];
let key = Some(format!("TXXX {}", strings[0]));
frames.push((*b"TXXX", text_body(&[], &strings, o.terminate_last, o), key));
};
let one_txxx = |frames: &mut Vec<([u8; 4], Vec<u8>, Option<String>)>,
description: &str,
values: &[String]| match values {
[] => Ok(()),
[v] => {
txxx(frames, description, v);
Ok(())
}
_ => Err(Error::InvalidArgument("a TXXX item holds one value")),
};
let comm = |frames: &mut Vec<([u8; 4], Vec<u8>, Option<String>)>, description: &str, value: &str| {
let strings = [clean(description, false, o), clean(value, true, o)];
let key = Some(format!("COMM {}", strings[0]));
frames.push((*b"COMM", text_body(&o.language, &strings, o.terminate_last, o), key));
};
text(&mut frames, b"TIT2", values(TagItem::TrackTitle));
text(&mut frames, b"TPE1", values(TagItem::Performer));
text(&mut frames, b"TEXT", values(TagItem::Songwriter));
text(&mut frames, b"TCOM", values(TagItem::Composer));
let arrangers = values(TagItem::Arranger);
match o.arranger {
ArrangerFrame::Tipl => text(
&mut frames,
b"TIPL",
arrangers.into_iter().flat_map(|a| ["arranger".to_owned(), a]).collect(),
),
ArrangerFrame::Txxx => one_txxx(&mut frames, &o.arranger_description, &arrangers)?,
}
let message = set.get(TagItem::Message).join("\n");
let extra = set.get(TagItem::ExtraMessage).join("\n");
match &o.join_messages {
Some(sep) if !message.is_empty() && !extra.is_empty() => {
comm(&mut frames, &o.message_description, &format!("{message}{sep}{extra}"))
}
_ => {
if !set.get(TagItem::Message).is_empty() {
comm(&mut frames, &o.message_description, &message);
}
if !set.get(TagItem::ExtraMessage).is_empty() {
let d = if o.join_messages.is_some() {
&o.message_description
} else {
&o.extra_message_description
};
comm(&mut frames, d, &extra);
}
}
}
if o.phonetic {
text(&mut frames, b"TSOT", values(TagItem::TitlePhonetic));
text(&mut frames, b"TSOP", values(TagItem::PerformerPhonetic));
}
if let Some(n) = set.get(TagItem::TrackNumber).first().filter(|n| digits(n)) {
let count = set.get(TagItem::TrackCount).first().filter(|c| o.track_count && digits(c));
text(&mut frames, b"TRCK", vec![count.map_or(n.clone(), |c| format!("{n}/{c}"))]);
}
text(&mut frames, b"TSRC", values(TagItem::Isrc));
text(&mut frames, b"TCON", values(TagItem::Genre));
text(&mut frames, b"TALB", values(TagItem::Album));
let artists = values(TagItem::AlbumArtist);
match o.album_artist {
AlbumArtistFrame::None => {}
AlbumArtistFrame::Tpe2 => text(&mut frames, b"TPE2", artists),
AlbumArtistFrame::Txxx => one_txxx(&mut frames, &o.album_artist_description, &artists)?,
}
for (d, v) in set.custom() {
txxx(&mut frames, d, v);
}
text(&mut frames, b"TPUB", values(TagItem::Publisher));
let date = set.get(TagItem::Date).first();
let year =
date.and_then(|d| d.get(..4)).filter(|y| y.bytes().all(|b| b.is_ascii_digit()) && *y != "0000");
if let (true, Some(year)) = (o.copyright, year) {
let v: Vec<String> = values(TagItem::Copyright).into_iter().map(|c| format!("{year} {c}")).collect();
text(&mut frames, b"TCOP", v);
}
if let Some(q) = set.get(TagItem::DiscNumber).first().filter(|q| digits(q)) {
let z = set.get(TagItem::DiscCount).first().filter(|z| digits(z));
text(&mut frames, b"TPOS", vec![z.map_or(q.clone(), |z| format!("{q}/{z}"))]);
}
let date_id = match o.date {
DateFrame::Tdrl => b"TDRL",
DateFrame::Tdrc => b"TDRC",
};
text(&mut frames, date_id, date.map(|d| vec![clean(d, false, o)]).unwrap_or_default());
if frames.is_empty() {
return Ok(None);
}
let mut keys: Vec<&String> = frames.iter().filter_map(|(_, _, k)| k.as_ref()).collect();
let n = keys.len();
keys.sort_unstable();
keys.dedup();
if keys.len() != n {
return Err(Error::InvalidArgument("two TXXX or COMM frames have one description"));
}
frames.sort_by_key(|(id, _, _)| o.frame_order.iter().position(|x| x == id).unwrap_or(usize::MAX));
let mut body = Vec::new();
for (id, b, _) in &frames {
if body.len() + 10 + b.len() > MAX_TAG_BYTES {
return Err(Error::InvalidArgument("the tag is larger than MAX_TAG_BYTES"));
}
body.extend_from_slice(id);
body.extend_from_slice(&synchsafe(b.len()));
body.extend_from_slice(&[0, 0]);
body.extend_from_slice(b);
}
if !o.footer {
let padding = o.padding as usize;
if body.len() + padding + 20 > MAX_TAG_BYTES {
return Err(Error::InvalidArgument("the tag is larger than MAX_TAG_BYTES"));
}
body.resize(body.len() + padding, 0);
}
let flags = if o.footer { 0x10 } else { 0 };
let header = |id: &[u8; 3]| {
let mut h = id.to_vec();
h.extend_from_slice(&[4, 0, flags]);
h.extend_from_slice(&synchsafe(body.len()));
h
};
let mut out = header(b"ID3");
out.extend_from_slice(&body);
if o.footer {
out.extend_from_slice(&header(b"3DI"));
}
Ok(Some(out))
}
pub(super) fn check_raw(tag: &[u8]) -> Result<(), Error> {
if tag.starts_with(b"ID3\x03") {
return check_raw_v23(tag);
}
let bad = Err(Error::InvalidArgument("not an ID3v2.4 tag of its stated size"));
if tag.len() < 10
|| tag.len() > MAX_TAG_BYTES
|| &tag[..5] != b"ID3\x04\x00"
|| tag[6..10].iter().any(|b| b & 0x80 != 0)
{
return bad;
}
let size = tag[6..10].iter().fold(0usize, |v, &b| v << 7 | usize::from(b));
let footer = if tag[5] & 0x10 != 0 { 10 } else { 0 };
if 10 + size + footer != tag.len() {
return bad;
}
Ok(())
}
fn check_raw_v23(tag: &[u8]) -> Result<(), Error> {
if tag.len() < 10
|| tag.len() > MAX_TAG_BYTES
|| &tag[..5] != b"ID3\x03\x00"
|| tag[5] & 0x1F != 0
|| tag[6..10].iter().any(|b| b & 0x80 != 0)
|| tag[6..10].iter().fold(0usize, |v, &b| v << 7 | usize::from(b)) != tag.len() - 10
{
return Err(Error::InvalidArgument("not an ID3v2.3 tag of its stated size"));
}
Ok(())
}