lofty 0.24.0

Audio metadata library
Documentation
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Various traits for reading and writing to file-like objects

use crate::error::{LoftyError, Result};
use crate::util::math::F80;

use std::collections::VecDeque;
use std::fs::File;
use std::io::{Cursor, Read, Seek, SeekFrom, Write};

// TODO: https://github.com/rust-lang/rust/issues/59359
pub(crate) trait SeekStreamLen: Seek {
	fn stream_len_hack(&mut self) -> crate::error::Result<u64> {
		use std::io::SeekFrom;

		let current_pos = self.stream_position()?;
		let len = self.seek(SeekFrom::End(0))?;

		self.seek(SeekFrom::Start(current_pos))?;

		Ok(len)
	}
}

impl<T> SeekStreamLen for T where T: Seek {}

/// Provides a method to truncate an object to the specified length
///
/// This is one component of the [`FileLike`] trait, which is used to provide implementors access to any
/// file saving methods such as [`AudioFile::save_to`](crate::file::AudioFile::save_to).
///
/// Take great care in implementing this for downstream types, as Lofty will assume that the
/// container has the new length specified. If this assumption were to be broken, files **will** become corrupted.
///
/// # Examples
///
/// ```rust
/// use lofty::io::Truncate;
///
/// let mut data = vec![1, 2, 3, 4, 5];
/// data.truncate(3);
///
/// assert_eq!(data, vec![1, 2, 3]);
/// ```
pub trait Truncate {
	/// The error type of the truncation operation
	type Error: Into<LoftyError>;

	/// Truncate a storage object to the specified length
	///
	/// # Errors
	///
	/// Errors depend on the object being truncated, which may not always be fallible.
	fn truncate(&mut self, new_len: u64) -> std::result::Result<(), Self::Error>;
}

impl Truncate for File {
	type Error = std::io::Error;

	fn truncate(&mut self, new_len: u64) -> std::result::Result<(), Self::Error> {
		self.set_len(new_len)
	}
}

impl Truncate for Vec<u8> {
	type Error = std::convert::Infallible;

	fn truncate(&mut self, new_len: u64) -> std::result::Result<(), Self::Error> {
		self.truncate(new_len as usize);
		Ok(())
	}
}

impl Truncate for VecDeque<u8> {
	type Error = std::convert::Infallible;

	fn truncate(&mut self, new_len: u64) -> std::result::Result<(), Self::Error> {
		self.truncate(new_len as usize);
		Ok(())
	}
}

impl<T> Truncate for Cursor<T>
where
	T: Truncate,
{
	type Error = <T as Truncate>::Error;

	fn truncate(&mut self, new_len: u64) -> std::result::Result<(), Self::Error> {
		self.get_mut().truncate(new_len)
	}
}

impl<T> Truncate for Box<T>
where
	T: Truncate,
{
	type Error = <T as Truncate>::Error;

	fn truncate(&mut self, new_len: u64) -> std::result::Result<(), Self::Error> {
		self.as_mut().truncate(new_len)
	}
}

impl<T> Truncate for &mut T
where
	T: Truncate,
{
	type Error = <T as Truncate>::Error;

	fn truncate(&mut self, new_len: u64) -> std::result::Result<(), Self::Error> {
		(**self).truncate(new_len)
	}
}

/// Provides a method to get the length of a storage object
///
/// This is one component of the [`FileLike`] trait, which is used to provide implementors access to any
/// file saving methods such as [`AudioFile::save_to`](crate::file::AudioFile::save_to).
///
/// Take great care in implementing this for downstream types, as Lofty will assume that the
/// container has the exact length specified. If this assumption were to be broken, files **may** become corrupted.
///
/// # Examples
///
/// ```rust
/// use lofty::io::Length;
///
/// let data = vec![1, 2, 3, 4, 5];
/// assert_eq!(data.len(), 5);
/// ```
pub trait Length {
	/// The error type of the length operation
	type Error: Into<LoftyError>;

	/// Get the length of a storage object
	///
	/// # Errors
	///
	/// Errors depend on the object being read, which may not always be fallible.
	fn len(&self) -> std::result::Result<u64, Self::Error>;
}

impl Length for File {
	type Error = std::io::Error;

	fn len(&self) -> std::result::Result<u64, Self::Error> {
		self.metadata().map(|m| m.len())
	}
}

impl Length for Vec<u8> {
	type Error = std::convert::Infallible;

	fn len(&self) -> std::result::Result<u64, Self::Error> {
		Ok(self.len() as u64)
	}
}

impl Length for VecDeque<u8> {
	type Error = std::convert::Infallible;

	fn len(&self) -> std::result::Result<u64, Self::Error> {
		Ok(self.len() as u64)
	}
}

impl<T> Length for Cursor<T>
where
	T: Length,
{
	type Error = <T as Length>::Error;

	fn len(&self) -> std::result::Result<u64, Self::Error> {
		Length::len(self.get_ref())
	}
}

impl<T> Length for Box<T>
where
	T: Length,
{
	type Error = <T as Length>::Error;

	fn len(&self) -> std::result::Result<u64, Self::Error> {
		Length::len(self.as_ref())
	}
}

impl<T> Length for &T
where
	T: Length,
{
	type Error = <T as Length>::Error;

	fn len(&self) -> std::result::Result<u64, Self::Error> {
		Length::len(*self)
	}
}

impl<T> Length for &mut T
where
	T: Length,
{
	type Error = <T as Length>::Error;

	fn len(&self) -> std::result::Result<u64, Self::Error> {
		Length::len(*self)
	}
}

/// Provides a set of methods to read and write to a file-like object
///
/// This is a combination of the [`Read`], [`Write`], [`Seek`], [`Truncate`], and [`Length`] traits.
/// It is used to provide implementors access to any file saving methods such as [`AudioFile::save_to`](crate::file::AudioFile::save_to).
///
/// Take great care in implementing this for downstream types, as Lofty will assume that the
/// trait implementations are correct. If this assumption were to be broken, files **may** become corrupted.
pub trait FileLike: Read + Write + Seek + Truncate + Length
where
	<Self as Truncate>::Error: Into<LoftyError>,
	<Self as Length>::Error: Into<LoftyError>,
{
}

impl<T> FileLike for T
where
	T: Read + Write + Seek + Truncate + Length,
	<T as Truncate>::Error: Into<LoftyError>,
	<T as Length>::Error: Into<LoftyError>,
{
}

pub(crate) trait ReadExt: Read {
	/// Read a big-endian [`F80`] from the current position.
	fn read_f80(&mut self) -> Result<F80>;
}

impl<R> ReadExt for R
where
	R: Read,
{
	fn read_f80(&mut self) -> Result<F80> {
		let mut bytes = [0; 10];
		self.read_exact(&mut bytes)?;

		Ok(F80::from_be_bytes(bytes))
	}
}

#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub(crate) enum RevSearchStart {
	/// Start the search from the end of the stream
	#[default]
	FromEnd,
	/// Start the search from the current position
	FromCurrent,
}

#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub(crate) enum RevSearchEnd {
	/// End the search at the start of the stream
	StreamStart,
	/// End the search at the current position
	///
	/// Collides with [`RevSearchStart::FromCurrent`]
	#[default]
	FromCurrent,
	/// End the search at a specific position
	Pos(u64),
}

pub(crate) struct RevPatternSearcher<'a, T> {
	start: RevSearchStart,
	end: RevSearchEnd,
	buffer_size: u64,
	pattern: &'a [u8],
	reader: &'a mut T,
}

impl<T> RevPatternSearcher<'_, T>
where
	T: Read + Seek,
{
	pub(crate) fn buffer_size(&mut self, buffer_size: u64) -> &mut Self {
		self.buffer_size = buffer_size;
		self
	}

	pub(crate) fn start_pos(&mut self, start: RevSearchStart) -> &mut Self {
		self.start = start;
		self
	}

	pub(crate) fn end_pos(&mut self, end: RevSearchEnd) -> &mut Self {
		self.end = end;
		self
	}

	/// Search for `pattern` in the stream, from the end up to the current position.
	///
	/// If found, this will leave the reader at the start of the pattern. Otherwise, the reader will
	/// be at the original position.
	pub(crate) fn search(&mut self) -> std::io::Result<bool> {
		if self.pattern.is_empty() {
			return Ok(true);
		}

		let original_pos = self.reader.stream_position()?;
		let pattern_len = self.pattern.len();

		let start_pos = match self.start {
			RevSearchStart::FromEnd => self.reader.seek(SeekFrom::End(0))?,
			RevSearchStart::FromCurrent => original_pos,
		};

		let end_pos = match self.end {
			RevSearchEnd::StreamStart => 0,
			RevSearchEnd::FromCurrent => original_pos,
			RevSearchEnd::Pos(p) => p,
		};

		if start_pos < end_pos
			|| (start_pos - end_pos) < pattern_len as u64
			|| self.buffer_size < pattern_len as u64
		{
			self.reader.seek(SeekFrom::Start(original_pos))?;
			return Ok(false);
		}

		// To handle partial matches, the `current_pos` gets decremented in "steps". Which is the
		// `buffer_size`, but with just enough room at the end for the pattern.
		let overlap_step = self.buffer_size - ((pattern_len as u64) - 1);

		let mut current_pos = start_pos;
		let mut buf = vec![0; self.buffer_size as usize];

		while current_pos > end_pos {
			let window_size = current_pos - end_pos;
			let read_size = std::cmp::min(self.buffer_size, window_size);

			let read_start = current_pos - read_size;
			self.reader.seek(SeekFrom::Start(read_start))?;

			let window = &mut buf[..read_size as usize];
			self.reader.read_exact(window)?;

			if let Some(match_offset) = window
				.windows(self.pattern.len())
				.enumerate()
				.rev()
				.find_map(|(idx, window)| {
					if window == self.pattern {
						Some(idx)
					} else {
						None
					}
				}) {
				self.reader
					.seek(SeekFrom::Start(read_start + match_offset as u64))?;
				return Ok(true);
			}

			current_pos -= std::cmp::min(read_size, overlap_step);
		}

		Ok(false)
	}
}

pub(crate) trait ReadFindExt: Read + Seek + Sized {
	/// Construct a [`RevPatternSearcher`]
	fn rfind<'a>(&'a mut self, pattern: &'a [u8]) -> RevPatternSearcher<'a, Self> {
		RevPatternSearcher {
			start: RevSearchStart::default(),
			end: RevSearchEnd::StreamStart,
			buffer_size: 1024,
			pattern,
			reader: self,
		}
	}
}

impl<T> ReadFindExt for T where T: Read + Seek {}

#[cfg(test)]
mod tests {
	use crate::config::{ParseOptions, WriteOptions};
	use crate::file::AudioFile;
	use crate::io::{ReadFindExt, RevSearchEnd, RevSearchStart};
	use crate::mpeg::MpegFile;
	use crate::tag::Accessor;

	use std::io::{Cursor, Read, Seek, SeekFrom, Write};
	use std::iter::repeat_n;
	use std::ops::Neg;

	const TEST_ASSET: &str = "tests/files/assets/minimal/full_test.mp3";

	fn test_asset_contents() -> Vec<u8> {
		std::fs::read(TEST_ASSET).unwrap()
	}

	fn file() -> MpegFile {
		let file_contents = test_asset_contents();
		let mut reader = Cursor::new(file_contents);
		MpegFile::read_from(&mut reader, ParseOptions::new()).unwrap()
	}

	fn alter_tag(file: &mut MpegFile) {
		let tag = file.id3v2_mut().unwrap();
		tag.set_artist(String::from("Bar artist"));
	}

	fn revert_tag(file: &mut MpegFile) {
		let tag = file.id3v2_mut().unwrap();
		tag.set_artist(String::from("Foo artist"));
	}

	#[test_log::test]
	fn io_save_to_file() {
		// Read the file and change the artist
		let mut file = file();
		alter_tag(&mut file);

		let mut temp_file = tempfile::tempfile().unwrap();
		let file_content = std::fs::read(TEST_ASSET).unwrap();
		temp_file.write_all(&file_content).unwrap();
		temp_file.rewind().unwrap();

		// Save the new artist
		file.save_to(&mut temp_file, WriteOptions::new().preferred_padding(0))
			.expect("Failed to save to file");

		// Read the file again and change the artist back
		temp_file.rewind().unwrap();
		let mut file = MpegFile::read_from(&mut temp_file, ParseOptions::new()).unwrap();
		revert_tag(&mut file);

		temp_file.rewind().unwrap();
		file.save_to(&mut temp_file, WriteOptions::new().preferred_padding(0))
			.expect("Failed to save to file");

		// The contents should be the same as the original file
		temp_file.rewind().unwrap();
		let mut current_file_contents = Vec::new();
		temp_file.read_to_end(&mut current_file_contents).unwrap();

		assert_eq!(current_file_contents, test_asset_contents());
	}

	#[test_log::test]
	fn io_save_to_vec() {
		// Same test as above, but using a Cursor<Vec<u8>> instead of a file
		let mut file = file();
		alter_tag(&mut file);

		let file_content = std::fs::read(TEST_ASSET).unwrap();

		let mut reader = Cursor::new(file_content);
		file.save_to(&mut reader, WriteOptions::new().preferred_padding(0))
			.expect("Failed to save to vec");

		reader.rewind().unwrap();
		let mut file = MpegFile::read_from(&mut reader, ParseOptions::new()).unwrap();
		revert_tag(&mut file);

		reader.rewind().unwrap();
		file.save_to(&mut reader, WriteOptions::new().preferred_padding(0))
			.expect("Failed to save to vec");

		let current_file_contents = reader.into_inner();
		assert_eq!(current_file_contents, test_asset_contents());
	}

	#[test_log::test]
	fn io_save_using_references() {
		struct File {
			buf: Vec<u8>,
		}

		let mut f = File {
			buf: std::fs::read(TEST_ASSET).unwrap(),
		};

		// Same test as above, but using references instead of owned values
		let mut file = file();
		alter_tag(&mut file);

		{
			let mut reader = Cursor::new(&mut f.buf);
			file.save_to(&mut reader, WriteOptions::new().preferred_padding(0))
				.expect("Failed to save to vec");
		}

		{
			let mut reader = Cursor::new(&f.buf[..]);
			file = MpegFile::read_from(&mut reader, ParseOptions::new()).unwrap();
			revert_tag(&mut file);
		}

		{
			let mut reader = Cursor::new(&mut f.buf);
			file.save_to(&mut reader, WriteOptions::new().preferred_padding(0))
				.expect("Failed to save to vec");
		}

		let current_file_contents = f.buf;
		assert_eq!(current_file_contents, test_asset_contents());
	}

	#[test_log::test]
	fn rev_search() {
		// Basic search
		const PAT: &[u8] = b"PATTERN";
		let mut data1 = PAT.to_vec();
		data1.extend(repeat_n(0, 5000));

		let mut stream1 = Cursor::new(data1);
		assert!(stream1.rfind(PAT).search().unwrap());

		// Search across boundaries
		let mut data2 = PAT.to_vec();
		data2.extend(repeat_n(0, 1023));

		let mut stream2 = Cursor::new(data2);
		assert!(stream2.rfind(PAT).search().unwrap());

		// Multiple occurrences, should find the last one
		let mut data3 = PAT.to_vec();
		let junk_len = 20;
		data3.extend(repeat_n(0, junk_len));
		data3.extend(PAT);
		data3.extend(repeat_n(0, junk_len));
		let last_occurence_offset = data3.len() - (junk_len + PAT.len());

		let mut stream3 = Cursor::new(data3);
		assert!(stream3.rfind(PAT).search().unwrap());
		assert_eq!(stream3.position(), last_occurence_offset as u64);

		// Multiple occurrences, search starts within a partial match
		let mut data4 = PAT.to_vec();
		data4.extend(repeat_n(0, junk_len));
		data4.extend(PAT);
		data4.extend(repeat_n(0, junk_len));
		data4.extend(PAT);

		let middle_match_offset = PAT.len() + junk_len;

		let mut stream4 = Cursor::new(data4);
		// Eat partially into the first match
		stream4
			.seek(SeekFrom::End(((PAT.len() - 3) as i64).neg()))
			.unwrap();

		assert!(
			stream4
				.rfind(PAT)
				.start_pos(RevSearchStart::FromCurrent)
				.end_pos(RevSearchEnd::StreamStart)
				.search()
				.unwrap()
		);
		assert_eq!(stream4.position(), middle_match_offset as u64);
	}
}