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 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
//! Utilities for working with unsynchronized ID3v2 content
//!
//! See [`FrameFlags::unsynchronisation`](crate::id3::v2::FrameFlags::unsynchronisation) for an explanation.
use crate::error::Result;
use std::io::Read;
/// A reader for unsynchronized content
///
/// See [`FrameFlags::unsynchronisation`](crate::id3::v2::FrameFlags::unsynchronisation) for an explanation.
///
/// # Examples
///
/// ```rust
/// use std::io::{Cursor, Read};
/// use lofty::id3::v2::util::synchsafe::UnsynchronizedStream;
///
/// fn main() -> lofty::Result<()> {
/// // The content has two `0xFF 0x00` pairs, which will be removed
/// let content = [0xFF, 0x00, 0x1A, 0xFF, 0x00, 0x15];
///
/// let mut unsynchronized_reader = UnsynchronizedStream::new(Cursor::new(content));
///
/// let mut unsynchronized_content = Vec::new();
/// unsynchronized_reader.read_to_end(&mut unsynchronized_content)?;
///
/// // All null bytes following `0xFF` have been removed
/// assert_eq!(unsynchronized_content, [0xFF, 0x1A, 0xFF, 0x15]);
/// # Ok(()) }
/// ```
pub struct UnsynchronizedStream<R> {
reader: R,
// Same buffer size as `BufReader`
buf: [u8; 8 * 1024],
bytes_available: usize,
pos: usize,
encountered_ff: bool,
}
impl<R> UnsynchronizedStream<R> {
/// Create a new [`UnsynchronizedStream`]
///
/// # Examples
///
/// ```rust
/// use lofty::id3::v2::util::synchsafe::UnsynchronizedStream;
/// use std::io::Cursor;
///
/// let reader = Cursor::new([0xFF, 0x00, 0x1A]);
/// let unsynchronized_reader = UnsynchronizedStream::new(reader);
/// ```
pub fn new(reader: R) -> Self {
Self {
reader,
buf: [0; 8 * 1024],
bytes_available: 0,
pos: 0,
encountered_ff: false,
}
}
/// Extract the reader, discarding the [`UnsynchronizedStream`]
///
/// # Examples
///
/// ```rust
/// use lofty::id3::v2::util::synchsafe::UnsynchronizedStream;
/// use std::io::Cursor;
///
/// # fn main() -> lofty::Result<()> {
/// let reader = Cursor::new([0xFF, 0x00, 0x1A]);
/// let unsynchronized_reader = UnsynchronizedStream::new(reader);
///
/// let reader = unsynchronized_reader.into_inner();
/// # Ok(()) }
/// ```
pub fn into_inner(self) -> R {
self.reader
}
}
impl<R: Read> Read for UnsynchronizedStream<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let dest_len = buf.len();
if dest_len == 0 {
return Ok(0);
}
let mut dest_pos = 0;
loop {
if dest_pos == dest_len {
break;
}
if self.pos >= self.bytes_available {
self.bytes_available = self.reader.read(&mut self.buf)?;
self.pos = 0;
}
// Exhausted the reader
if self.bytes_available == 0 {
break;
}
if self.encountered_ff {
self.encountered_ff = false;
// Only skip the next byte if this is valid unsynchronization
// Otherwise just continue as normal
if self.buf[self.pos] == 0 {
self.pos += 1;
continue;
}
}
let current_byte = self.buf[self.pos];
buf[dest_pos] = current_byte;
dest_pos += 1;
self.pos += 1;
if current_byte == 0xFF {
self.encountered_ff = true;
}
}
Ok(dest_pos)
}
}
/// An integer that can be converted to and from synchsafe variants
pub trait SynchsafeInteger: Sized {
/// The integer type that this can be widened to for use in [`SynchsafeInteger::widening_synch`]
type WideningType;
/// Create a synchsafe integer
///
/// See [`FrameFlags::unsynchronisation`](crate::id3::v2::FrameFlags::unsynchronisation) for an explanation.
///
/// # Errors
///
/// `self` doesn't fit in <`INTEGER_TYPE::BITS - size_of::<INTEGER_TYPE>()`> bits
///
/// # Examples
///
/// ```rust
/// use lofty::id3::v2::util::synchsafe::SynchsafeInteger;
///
/// # fn main() -> lofty::error::Result<()> {
/// // Maximum value we can represent in a synchsafe u32
/// let unsynch_number = 0xFFF_FFFF_u32;
/// let synch_number = unsynch_number.synch()?;
///
/// // Our synchronized number should be something completely different
/// assert_ne!(synch_number, unsynch_number);
///
/// // Each byte should have 7 set bits and an MSB of 0
/// assert_eq!(synch_number, 0b01111111_01111111_01111111_01111111_u32);
/// # Ok(()) }
/// ```
fn synch(self) -> Result<Self>;
/// Create a synchsafe integer, widening to the next available integer type
///
/// See [`FrameFlags::unsynchronisation`](crate::id3::v2::FrameFlags::unsynchronisation) for an explanation.
///
/// # Examples
///
/// ```rust
/// use lofty::id3::v2::util::synchsafe::SynchsafeInteger;
///
/// // 0b11111111
/// let large_number = u8::MAX;
///
/// // Widened to a u16
/// // 0b00000001_01111111
/// let large_number_synchsafe = large_number.widening_synch();
///
/// // Unsynchronizing the number will get us back to 255
/// assert_eq!(large_number_synchsafe.unsynch(), large_number as u16);
/// ```
fn widening_synch(self) -> Self::WideningType;
/// Unsynchronise a synchsafe integer
///
/// See [`FrameFlags::unsynchronisation`](crate::id3::v2::FrameFlags::unsynchronisation) for an explanation.
///
/// # Examples
///
/// ```rust
/// use lofty::id3::v2::util::synchsafe::SynchsafeInteger;
///
/// # fn main() -> lofty::error::Result<()> {
/// let unsynch_number = 0xFFF_FFFF_u32;
/// let synch_number = unsynch_number.synch()?;
///
/// // Our synchronized number should be something completely different
/// assert_ne!(synch_number, unsynch_number);
///
/// // Now, our re-unsynchronized number should match our original
/// let re_unsynch_number = synch_number.unsynch();
/// assert_eq!(re_unsynch_number, unsynch_number);
/// # Ok(()) }
/// ```
fn unsynch(self) -> Self;
}
macro_rules! impl_synchsafe {
(
$ty:ty, $widening_ty:ty,
synch($n:ident) $body:block;
widening_synch($w:ident) $widening_body:block;
unsynch($u:ident) $unsynch_body:block
) => {
#[allow(unused_parens)]
impl SynchsafeInteger for $ty {
type WideningType = $widening_ty;
fn synch(self) -> Result<Self> {
const MAXIMUM_INTEGER: $ty = {
let num_bytes = core::mem::size_of::<$ty>();
// 7 bits are available per byte, shave off 1 bit per byte
<$ty>::MAX >> num_bytes
};
if self > MAXIMUM_INTEGER {
crate::macros::err!(TooMuchData);
}
let $n = self;
Ok($body)
}
fn widening_synch(self) -> Self::WideningType {
let mut $w = <$widening_ty>::MIN;
let $n = self;
$widening_body;
$w
}
fn unsynch(self) -> Self {
let $u = self;
$unsynch_body
}
}
};
}
impl_synchsafe! {
u8, u16,
synch(n) {
(n & 0x7F)
};
widening_synch(w) {
w |= u16::from(n & 0x7F);
w |= u16::from(n & 0x80) << 1;
};
unsynch(u) {
(u & 0x7F)
}
}
impl_synchsafe! {
u16, u32,
synch(n) {
(n & 0x7F) |
((n & (0x7F << 7)) << 1)
};
widening_synch(w) {
w |= u32::from(n & 0x7F);
w |= u32::from((n & (0x7F << 7)) << 1);
w |= u32::from(n & (0x03 << 14)) << 2;
};
unsynch(u) {
((u & 0x7F00) >> 1) | (u & 0x7F)
}
}
impl_synchsafe! {
u32, u64,
synch(n) {
(n & 0x7F) |
((n & (0x7F << 7)) << 1) |
((n & (0x7F << 14)) << 2) |
((n & (0x7F << 21)) << 3)
};
widening_synch(w) {
w |= u64::from(n & 0x7F);
w |= u64::from(n & (0x7F << 7)) << 1;
w |= u64::from(n & (0x7F << 14)) << 2;
w |= u64::from(n & (0x7F << 21)) << 3;
w |= u64::from(n & (0x0F << 28)) << 4;
};
unsynch(u) {
((u & 0x7F00_0000) >> 3) | ((u & 0x7F_0000) >> 2) | ((u & 0x7F00) >> 1) | (u & 0x7F)
}
}
#[cfg(test)]
mod tests {
const UNSYNCHRONIZED_CONTENT: &[u8] =
&[0xFF, 0x00, 0x00, 0xFF, 0x12, 0xB0, 0x05, 0xFF, 0x00, 0x00];
const EXPECTED: &[u8] = &[0xFF, 0x00, 0xFF, 0x12, 0xB0, 0x05, 0xFF, 0x00];
#[test]
fn unsynchronized_stream() {
let reader = Cursor::new(UNSYNCHRONIZED_CONTENT);
let mut unsynchronized_reader = UnsynchronizedStream::new(reader);
let mut final_content = Vec::new();
unsynchronized_reader
.read_to_end(&mut final_content)
.unwrap();
assert_eq!(final_content, EXPECTED);
}
#[test]
fn unsynchronized_stream_large() {
// Create a buffer >10k to force a buffer reset
let reader = Cursor::new(UNSYNCHRONIZED_CONTENT.repeat(1000));
let mut unsynchronized_reader = UnsynchronizedStream::new(reader);
let mut final_content = Vec::new();
unsynchronized_reader
.read_to_end(&mut final_content)
.unwrap();
// UNSYNCHRONIZED_CONTENT * 1000 should equal EXPECTED * 1000
assert_eq!(final_content, EXPECTED.repeat(1000));
}
#[test]
fn unsynchronized_stream_should_not_replace_unrelated() {
const ORIGINAL_CONTENT: &[u8] = &[0xFF, 0x1A, 0xFF, 0xC0, 0x10, 0x01];
let reader = Cursor::new(ORIGINAL_CONTENT);
let mut unsynchronized_reader = UnsynchronizedStream::new(reader);
let mut final_content = Vec::new();
unsynchronized_reader
.read_to_end(&mut final_content)
.unwrap();
assert_eq!(final_content, ORIGINAL_CONTENT);
}
use crate::id3::v2::util::synchsafe::{SynchsafeInteger, UnsynchronizedStream};
use std::io::{Cursor, Read};
macro_rules! synchsafe_integer_tests {
(
$($int:ty => {
synch: $original:literal, $new:literal;
unsynch: $original_unsync:literal, $new_unsynch:literal;
widen: $original_widen:literal, $new_widen:literal;
});+
) => {
$(
paste::paste! {
#[test]
fn [<$int _synch>]() {
assert_eq!($original.synch().unwrap(), $new);
}
#[test]
fn [<$int _unsynch>]() {
assert_eq!($original_unsync.unsynch(), $new_unsynch);
}
#[test]
fn [<$int _widen>]() {
assert_eq!($original_widen.widening_synch(), $new_widen);
}
}
)+
};
}
synchsafe_integer_tests! {
u8 => {
synch: 0x7F_u8, 0x7F_u8;
unsynch: 0x7F_u8, 0x7F_u8;
widen: 0xFF_u8, 0x017F_u16;
};
u16 => {
synch: 0x3FFF_u16, 0x7F7F_u16;
unsynch: 0x7F7F_u16, 0x3FFF_u16;
widen: 0xFFFF_u16, 0x0003_7F7F_u32;
};
u32 => {
synch: 0xFFF_FFFF_u32, 0x7F7F_7F7F_u32;
unsynch: 0x7F7F_7F7F_u32, 0xFFF_FFFF_u32;
widen: 0xFFFF_FFFF_u32, 0x000F_7F7F_7F7F_u64;
}
}
}