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
use crate::config::ParsingMode;
use crate::error::{Id3v2Error, Id3v2ErrorKind, Result};
use crate::macros::try_vec;
use crate::util::text::{decode_text, encode_text, TextDecodeOptions, TextEncoding};

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::io::Read;

use byteorder::{BigEndian, ReadBytesExt};

/// A channel identifier used in the RVA2 frame
#[repr(u8)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)]
#[allow(missing_docs)]
pub enum ChannelType {
	Other = 0,
	MasterVolume = 1,
	FrontRight = 2,
	FrontLeft = 3,
	BackRight = 4,
	BackLeft = 5,
	FrontCentre = 6,
	BackCentre = 7,
	Subwoofer = 8,
}

impl ChannelType {
	/// Get a [`ChannelType`] from a `u8`
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::id3::v2::ChannelType;
	///
	/// let valid_byte = 1;
	/// assert_eq!(
	/// 	ChannelType::from_u8(valid_byte),
	/// 	Some(ChannelType::MasterVolume)
	/// );
	///
	/// // The valid range is 0..=8
	/// let invalid_byte = 10;
	/// assert_eq!(ChannelType::from_u8(invalid_byte), None);
	/// ```
	pub fn from_u8(byte: u8) -> Option<Self> {
		match byte {
			0 => Some(Self::Other),
			1 => Some(Self::MasterVolume),
			2 => Some(Self::FrontRight),
			3 => Some(Self::FrontLeft),
			4 => Some(Self::BackRight),
			5 => Some(Self::BackLeft),
			6 => Some(Self::FrontCentre),
			7 => Some(Self::BackCentre),
			8 => Some(Self::Subwoofer),
			_ => None,
		}
	}
}

/// Volume adjustment information for a specific channel
///
/// This is used in the RVA2 frame through [`RelativeVolumeAdjustmentFrame`]
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct ChannelInformation {
	/// The type of channel this describes
	pub channel_type: ChannelType,
	/// A fixed point decibel value representing (adjustment*512), giving +/- 64 dB with a precision of 0.001953125 dB.
	pub volume_adjustment: i16,
	/// The number of bits the peak volume field occupies, with 0 meaning there is no peak volume.
	pub bits_representing_peak: u8,
	/// An optional peak volume
	pub peak_volume: Option<Vec<u8>>,
}

/// An `ID3v2` RVA2 frame
///
/// NOTE: The `Eq` and `Hash` implementations depend solely on the `identification` field.
#[derive(Clone, Debug, Eq)]
pub struct RelativeVolumeAdjustmentFrame {
	/// The identifier used to identify the situation and/or device where this adjustment should apply
	pub identification: String,
	/// The information for each channel described in the frame
	pub channels: HashMap<ChannelType, ChannelInformation>,
}

impl PartialEq for RelativeVolumeAdjustmentFrame {
	fn eq(&self, other: &Self) -> bool {
		self.identification == other.identification
	}
}

impl Hash for RelativeVolumeAdjustmentFrame {
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.identification.hash(state)
	}
}

impl RelativeVolumeAdjustmentFrame {
	/// Read an [`RelativeVolumeAdjustmentFrame`]
	///
	/// NOTE: This expects the frame header to have already been skipped
	///
	/// # Errors
	///
	/// * Bad channel type (See [Id3v2ErrorKind::BadRva2ChannelType])
	/// * Not enough data
	pub fn parse<R>(reader: &mut R, parse_mode: ParsingMode) -> Result<Option<Self>>
	where
		R: Read,
	{
		let identification = decode_text(
			reader,
			TextDecodeOptions::new()
				.encoding(TextEncoding::Latin1)
				.terminated(true),
		)?
		.content;

		let mut channels = HashMap::new();
		while let Ok(channel_type_byte) = reader.read_u8() {
			let channel_type;
			match ChannelType::from_u8(channel_type_byte) {
				Some(channel_ty) => channel_type = channel_ty,
				None if parse_mode == ParsingMode::BestAttempt => channel_type = ChannelType::Other,
				_ => return Err(Id3v2Error::new(Id3v2ErrorKind::BadRva2ChannelType).into()),
			}

			let volume_adjustment = reader.read_i16::<BigEndian>()?;

			let bits_representing_peak = reader.read_u8()?;

			let mut peak_volume = None;
			if bits_representing_peak > 0 {
				let bytes_representing_peak = (u16::from(bits_representing_peak) + 7) >> 3;

				let mut peak_volume_bytes = try_vec![0; bytes_representing_peak as usize];
				reader.read_exact(&mut peak_volume_bytes)?;
				peak_volume = Some(peak_volume_bytes);
			}

			channels.insert(
				channel_type,
				ChannelInformation {
					channel_type,
					volume_adjustment,
					bits_representing_peak,
					peak_volume,
				},
			);
		}

		Ok(Some(Self {
			identification,
			channels,
		}))
	}

	/// Convert a [`RelativeVolumeAdjustmentFrame`] to a byte vec
	pub fn as_bytes(&self) -> Vec<u8> {
		let mut content = Vec::new();

		content.extend(encode_text(
			&self.identification,
			TextEncoding::Latin1,
			true,
		));

		for (channel_type, info) in &self.channels {
			let mut bits_representing_peak = info.bits_representing_peak;
			let expected_peak_byte_length = (u16::from(bits_representing_peak) + 7) >> 3;

			content.push(*channel_type as u8);
			content.extend(info.volume_adjustment.to_be_bytes());

			if info.peak_volume.is_none() {
				// Easiest path, no peak
				content.push(0);
				continue;
			}

			if let Some(peak) = &info.peak_volume {
				if peak.len() > expected_peak_byte_length as usize {
					// Recalculate bits representing peak
					bits_representing_peak = 0;

					// Max out at 255 bits
					for b in peak.iter().copied().take(32) {
						bits_representing_peak += b.leading_ones() as u8;
					}
				}

				content.push(bits_representing_peak);
				content.extend(peak.iter().take(32));
			}
		}

		content
	}
}

#[cfg(test)]
mod tests {
	use crate::config::ParsingMode;
	use crate::id3::v2::{ChannelInformation, ChannelType, RelativeVolumeAdjustmentFrame};

	use std::collections::HashMap;
	use std::io::Read;

	fn expected() -> RelativeVolumeAdjustmentFrame {
		let mut channels = HashMap::new();

		channels.insert(
			ChannelType::MasterVolume,
			ChannelInformation {
				channel_type: ChannelType::MasterVolume,
				volume_adjustment: 15,
				bits_representing_peak: 4,
				peak_volume: Some(vec![4]),
			},
		);

		channels.insert(
			ChannelType::FrontLeft,
			ChannelInformation {
				channel_type: ChannelType::FrontLeft,
				volume_adjustment: 21,
				bits_representing_peak: 0,
				peak_volume: None,
			},
		);

		channels.insert(
			ChannelType::Subwoofer,
			ChannelInformation {
				channel_type: ChannelType::Subwoofer,
				volume_adjustment: 30,
				bits_representing_peak: 11,
				peak_volume: Some(vec![0xFF, 0x07]),
			},
		);

		RelativeVolumeAdjustmentFrame {
			identification: String::from("Surround sound"),
			channels,
		}
	}

	#[test]
	fn rva2_decode() {
		let cont = crate::tag::utils::test_utils::read_path("tests/tags/assets/id3v2/test.rva2");

		let parsed_rva2 = RelativeVolumeAdjustmentFrame::parse(&mut &cont[..], ParsingMode::Strict)
			.unwrap()
			.unwrap();

		assert_eq!(parsed_rva2, expected());
	}

	#[test]
	#[allow(unstable_name_collisions)]
	fn rva2_encode() {
		let encoded = expected().as_bytes();

		let expected_bytes =
			crate::tag::utils::test_utils::read_path("tests/tags/assets/id3v2/test.rva2");

		// We have to check the output in fragments, as the order of channels is not guaranteed.
		assert_eq!(encoded.len(), expected_bytes.len());

		let mut needles = vec![
			&[1, 0, 15, 4, 4][..],       // Master volume configuration
			&[8, 0, 30, 11, 255, 7][..], // Front left configuration
			&[3, 0, 21, 0][..],          // Subwoofer configuration
		];

		let encoded_reader = &mut &encoded[..];

		let mut ident = [0; 15];
		encoded_reader.read_exact(&mut ident).unwrap();
		assert_eq!(ident, b"Surround sound\0"[..]);

		loop {
			if needles.is_empty() {
				break;
			}

			let mut remove_idx = None;
			for (idx, needle) in needles.iter().enumerate() {
				if encoded_reader.starts_with(needle) {
					std::io::copy(
						&mut encoded_reader.take(needle.len() as u64),
						&mut std::io::sink(),
					)
					.unwrap();

					remove_idx = Some(idx);
					break;
				}
			}

			let Some(remove_idx) = remove_idx else {
				unreachable!("Unexpected data in RVA2 frame: {:?}", &encoded);
			};

			needles.remove(remove_idx);
		}

		assert!(needles.is_empty());
	}
}