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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
use crate::error::Result;
use crate::probe::ParseOptions;
use crate::properties::FileProperties;
use crate::resolve::CUSTOM_RESOLVERS;
use crate::tag::{Tag, TagType};
use crate::traits::TagExt;

use std::convert::TryInto;
use std::ffi::OsStr;
use std::fs::{File, OpenOptions};
use std::io::{Read, Seek};
use std::path::Path;

/// Provides various methods for interaction with a file
pub trait AudioFile: Into<TaggedFile> {
	/// The struct the file uses for audio properties
	///
	/// Not all formats can use [`FileProperties`] since they may contain additional information
	type Properties;

	/// Read a file from a reader
	///
	/// # Errors
	///
	/// Errors depend on the file and tags being read. See [`LoftyError`](crate::LoftyError)
	fn read_from<R>(reader: &mut R, parse_options: ParseOptions) -> Result<Self>
	where
		R: Read + Seek,
		Self: Sized;
	/// Returns a reference to the file's properties
	fn properties(&self) -> &Self::Properties;
	/// Checks if the file contains any tags
	fn contains_tag(&self) -> bool;
	/// Checks if the file contains the given [`TagType`]
	fn contains_tag_type(&self, tag_type: TagType) -> bool;
}

/// A generic representation of a file
///
/// This is used when the [`FileType`] has to be guessed
pub struct TaggedFile {
	/// The file's type
	pub(crate) ty: FileType,
	/// The file's audio properties
	pub(crate) properties: FileProperties,
	/// A collection of the file's tags
	pub(crate) tags: Vec<Tag>,
}

impl TaggedFile {
	#[doc(hidden)]
	/// This exists for use in `lofty_attr`, there's no real use for this externally
	pub fn new(ty: FileType, properties: FileProperties, tags: Vec<Tag>) -> Self {
		Self {
			ty,
			properties,
			tags,
		}
	}

	/// Returns the file's [`FileType`]
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::FileType;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// assert_eq!(tagged_file.file_type(), FileType::MPEG);
	/// # Ok(()) }
	/// ```
	pub fn file_type(&self) -> FileType {
		self.ty
	}

	/// Returns all tags
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::FileType;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// // An MP3 file with 3 tags
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// let tags = tagged_file.tags();
	///
	/// assert_eq!(tags.len(), 3);
	/// # Ok(()) }
	/// ```
	pub fn tags(&self) -> &[Tag] {
		self.tags.as_slice()
	}

	/// Returns the file type's primary [`TagType`]
	///
	/// See [`FileType::primary_tag_type`]
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::TagType;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// assert_eq!(tagged_file.primary_tag_type(), TagType::ID3v2);
	/// # Ok(()) }
	/// ```
	pub fn primary_tag_type(&self) -> TagType {
		self.ty.primary_tag_type()
	}

	/// Determines whether the file supports the given [`TagType`]
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::TagType;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// assert!(tagged_file.supports_tag_type(TagType::ID3v2));
	/// # Ok(()) }
	/// ```
	pub fn supports_tag_type(&self, tag_type: TagType) -> bool {
		self.ty.supports_tag_type(tag_type)
	}

	/// Get a reference to a specific [`TagType`]
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::TagType;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// // Read an MP3 file with an ID3v2 tag
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// // An ID3v2 tag
	/// let tag = tagged_file.tag(TagType::ID3v2);
	///
	/// assert!(tag.is_some());
	/// assert_eq!(tag.unwrap().tag_type(), TagType::ID3v2);
	/// # Ok(()) }
	/// ```
	pub fn tag(&self, tag_type: TagType) -> Option<&Tag> {
		self.tags.iter().find(|i| i.tag_type() == tag_type)
	}

	/// Get a mutable reference to a specific [`TagType`]
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::TagType;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// // Read an MP3 file with an ID3v2 tag
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// // An ID3v2 tag
	/// let tag = tagged_file.tag(TagType::ID3v2);
	///
	/// assert!(tag.is_some());
	/// assert_eq!(tag.unwrap().tag_type(), TagType::ID3v2);
	///
	/// // Alter the tag...
	/// # Ok(()) }
	/// ```
	pub fn tag_mut(&mut self, tag_type: TagType) -> Option<&mut Tag> {
		self.tags.iter_mut().find(|i| i.tag_type() == tag_type)
	}

	/// Returns the primary tag
	///
	/// See [`FileType::primary_tag_type`]
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::TagType;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// // Read an MP3 file with an ID3v2 tag
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// // An ID3v2 tag
	/// let tag = tagged_file.primary_tag();
	///
	/// assert!(tag.is_some());
	/// assert_eq!(tag.unwrap().tag_type(), TagType::ID3v2);
	/// # Ok(()) }
	/// ```
	pub fn primary_tag(&self) -> Option<&Tag> {
		self.tag(self.primary_tag_type())
	}

	/// Gets a mutable reference to the file's "Primary tag"
	///
	/// See [`FileType::primary_tag_type`]
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::TagType;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// // Read an MP3 file with an ID3v2 tag
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// // An ID3v2 tag
	/// let tag = tagged_file.primary_tag_mut();
	///
	/// assert!(tag.is_some());
	/// assert_eq!(tag.unwrap().tag_type(), TagType::ID3v2);
	///
	/// // Alter the tag...
	/// # Ok(()) }
	/// ```
	pub fn primary_tag_mut(&mut self) -> Option<&mut Tag> {
		self.tag_mut(self.primary_tag_type())
	}

	/// Gets the first tag, if there are any
	///
	/// NOTE: This will grab the first available tag, you cannot rely on the result being
	/// a specific type
	///
	/// # Examples
	///
	/// ```rust
	/// # fn main() -> lofty::Result<()> {
	/// # let path = "tests/files/assets/minimal/full_test.mp3";
	/// // A file we know has tags
	/// let mut tagged_file = lofty::read_from_path(path)?;
	///
	/// // A tag of a (currently) unknown type
	/// let tag = tagged_file.first_tag();
	/// assert!(tag.is_some());
	/// # Ok(()) }
	/// ```
	pub fn first_tag(&self) -> Option<&Tag> {
		self.tags.first()
	}

	/// Gets a mutable reference to the first tag, if there are any
	///
	/// NOTE: This will grab the first available tag, you cannot rely on the result being
	/// a specific type
	///
	/// # Examples
	///
	/// ```rust
	/// # fn main() -> lofty::Result<()> {
	/// # let path = "tests/files/assets/minimal/full_test.mp3";
	/// // A file we know has tags
	/// let mut tagged_file = lofty::read_from_path(path)?;
	///
	/// // A tag of a (currently) unknown type
	/// let tag = tagged_file.first_tag_mut();
	/// assert!(tag.is_some());
	///
	/// // Alter the tag...
	/// # Ok(()) }
	/// ```
	pub fn first_tag_mut(&mut self) -> Option<&mut Tag> {
		self.tags.first_mut()
	}

	/// Inserts a [`Tag`]
	///
	/// NOTE: This will do nothing if the [`FileType`] does not support
	/// the [`TagType`]. See [`FileType::supports_tag_type`]
	///
	/// If a tag is replaced, it will be returned
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::{AudioFile, Tag, TagType};
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// // Read an MP3 file without an ID3v2 tag
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	/// # let _ = tagged_file.take(TagType::ID3v2); // sneaky
	///
	/// assert!(!tagged_file.contains_tag_type(TagType::ID3v2));
	///
	/// // Insert the ID3v2 tag
	/// let new_id3v2_tag = Tag::new(TagType::ID3v2);
	/// tagged_file.insert_tag(new_id3v2_tag);
	///
	/// assert!(tagged_file.contains_tag_type(TagType::ID3v2));
	/// # Ok(()) }
	/// ```
	pub fn insert_tag(&mut self, tag: Tag) -> Option<Tag> {
		let tag_type = tag.tag_type();

		if self.supports_tag_type(tag_type) {
			let ret = self.take(tag_type);
			self.tags.push(tag);

			return ret;
		}

		None
	}

	/// Removes a specific [`TagType`] and returns it
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::{AudioFile, TagType};
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// // Read an MP3 file containing an ID3v2 tag
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// assert!(tagged_file.contains_tag_type(TagType::ID3v2));
	///
	/// // Take the ID3v2 tag
	/// let id3v2 = tagged_file.take(TagType::ID3v2);
	///
	/// assert!(!tagged_file.contains_tag_type(TagType::ID3v2));
	/// # Ok(()) }
	/// ```
	pub fn take(&mut self, tag_type: TagType) -> Option<Tag> {
		self.tags
			.iter()
			.position(|t| t.tag_type() == tag_type)
			.map(|pos| self.tags.remove(pos))
	}

	/// Changes the [`FileType`]
	///
	/// NOTES:
	///
	/// * This will remove any tag the format does not support. See [`FileType::supports_tag_type`]
	/// * This will reset the [`FileProperties`]
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::{AudioFile, FileType, TagType};
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_mp3 = "tests/files/assets/minimal/full_test.mp3";
	/// // Read an MP3 file containing an ID3v2 tag
	/// let mut tagged_file = lofty::read_from_path(path_to_mp3)?;
	///
	/// assert!(tagged_file.contains_tag_type(TagType::ID3v2));
	///
	/// // Remap our MP3 file to WavPack, which doesn't support ID3v2
	/// tagged_file.change_file_type(FileType::WavPack);
	///
	/// assert!(!tagged_file.contains_tag_type(TagType::ID3v2));
	/// # Ok(()) }
	/// ```
	pub fn change_file_type(&mut self, file_type: FileType) {
		self.ty = file_type;
		self.properties = FileProperties::default();
		self.tags
			.retain(|t| self.ty.supports_tag_type(t.tag_type()));
	}

	/// Removes all tags from the file
	///
	/// # Examples
	///
	/// ```rust
	/// # fn main() -> lofty::Result<()> {
	/// # let path = "tests/files/assets/minimal/full_test.mp3";
	/// let mut tagged_file = lofty::read_from_path(path)?;
	///
	/// tagged_file.clear();
	///
	/// assert!(tagged_file.tags().is_empty());
	/// # Ok(()) }
	/// ```
	pub fn clear(&mut self) {
		self.tags.clear()
	}

	/// Attempts to write all tags to a path
	///
	/// # Errors
	///
	/// See [`TaggedFile::save_to`]
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # fn main() -> lofty::Result<()> {
	/// # let path = "tests/files/assets/minimal/full_test.mp3";
	/// let mut tagged_file = lofty::read_from_path(path)?;
	///
	/// // Edit the tags
	///
	/// tagged_file.save_to_path(path)?;
	/// # Ok(()) }
	/// ```
	pub fn save_to_path(&self, path: impl AsRef<Path>) -> Result<()> {
		self.save_to(&mut OpenOptions::new().read(true).write(true).open(path)?)
	}

	/// Attempts to write all tags to a file
	///
	/// # Errors
	///
	/// See [`Tag::save_to`], however this is applicable to every tag in the `TaggedFile`.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use std::fs::OpenOptions;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path = "tests/files/assets/minimal/full_test.mp3";
	/// let mut tagged_file = lofty::read_from_path(path)?;
	///
	/// // Edit the tags
	///
	/// let mut file = OpenOptions::new().read(true).write(true).open(path)?;
	/// tagged_file.save_to(&mut file)?;
	/// # Ok(()) }
	/// ```
	pub fn save_to(&self, file: &mut File) -> Result<()> {
		for tag in &self.tags {
			tag.save_to(file)?;
		}

		Ok(())
	}
}

impl AudioFile for TaggedFile {
	type Properties = FileProperties;

	fn read_from<R>(reader: &mut R, parse_options: ParseOptions) -> Result<Self>
	where
		R: Read + Seek,
		Self: Sized,
	{
		crate::probe::Probe::new(reader)
			.guess_file_type()?
			.options(parse_options)
			.read()
	}

	fn properties(&self) -> &Self::Properties {
		&self.properties
	}

	fn contains_tag(&self) -> bool {
		!self.tags.is_empty()
	}

	fn contains_tag_type(&self, tag_type: TagType) -> bool {
		self.tags.iter().any(|t| t.tag_type() == tag_type)
	}
}

/// The type of file read
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum FileType {
	AAC,
	AIFF,
	APE,
	FLAC,
	MPEG,
	MP4,
	Opus,
	Vorbis,
	Speex,
	WAV,
	WavPack,
	Custom(&'static str),
}

impl FileType {
	/// Returns the file type's "primary" [`TagType`], or the one most likely to be used in the target format
	///
	/// | [`FileType`]                      | [`TagType`]      |
	/// |-----------------------------------|------------------|
	/// | `AAC`, `AIFF`, `MP3`, `WAV`       | `ID3v2`          |
	/// | `APE` , `WavPack`                 | `APE`            |
	/// | `FLAC`, `Opus`, `Vorbis`, `Speex` | `VorbisComments` |
	/// | `MP4`                             | `MP4ilst`        |
	///
	/// # Panics
	///
	/// If an unregistered `FileType` ([`FileType::Custom`]) is encountered. See [`register_custom_resolver`](crate::resolve::register_custom_resolver).
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::{FileType, TagType};
	///
	/// let file_type = FileType::MPEG;
	/// assert_eq!(file_type.primary_tag_type(), TagType::ID3v2);
	/// ```
	pub fn primary_tag_type(&self) -> TagType {
		match self {
			FileType::AIFF | FileType::MPEG | FileType::WAV | FileType::AAC => TagType::ID3v2,
			FileType::APE | FileType::WavPack => TagType::APE,
			FileType::FLAC | FileType::Opus | FileType::Vorbis | FileType::Speex => {
				TagType::VorbisComments
			},
			FileType::MP4 => TagType::MP4ilst,
			FileType::Custom(c) => {
				let resolver = crate::resolve::lookup_resolver(c);
				resolver.primary_tag_type()
			},
		}
	}

	/// Returns if the target `FileType` supports a [`TagType`]
	///
	/// NOTE: This is feature dependent, meaning if you do not have the
	///       `id3v2` feature enabled, [`FileType::MPEG`] will return `false` for
	///        [`TagType::ID3v2`].
	///
	/// # Panics
	///
	/// If an unregistered `FileType` ([`FileType::Custom`]) is encountered. See [`register_custom_resolver`](crate::resolve::register_custom_resolver).
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::{FileType, TagType};
	///
	/// let file_type = FileType::MPEG;
	/// assert!(file_type.supports_tag_type(TagType::ID3v2));
	/// ```
	pub fn supports_tag_type(&self, tag_type: TagType) -> bool {
		match self {
			#[cfg(feature = "id3v2")]
			FileType::AIFF | FileType::APE | FileType::MPEG | FileType::WAV | FileType::AAC
				if tag_type == TagType::ID3v2 =>
			{
				true
			},
			#[cfg(feature = "aiff_text_chunks")]
			FileType::AIFF if tag_type == TagType::AIFFText => true,
			#[cfg(feature = "id3v1")]
			FileType::APE | FileType::MPEG | FileType::WavPack | FileType::AAC
				if tag_type == TagType::ID3v1 =>
			{
				true
			},
			#[cfg(feature = "ape")]
			FileType::APE | FileType::MPEG | FileType::WavPack if tag_type == TagType::APE => true,
			#[cfg(feature = "vorbis_comments")]
			FileType::Opus | FileType::FLAC | FileType::Vorbis | FileType::Speex => {
				tag_type == TagType::VorbisComments
			},
			#[cfg(feature = "mp4_ilst")]
			FileType::MP4 => tag_type == TagType::MP4ilst,
			#[cfg(feature = "riff_info_list")]
			FileType::WAV => tag_type == TagType::RIFFInfo,
			FileType::Custom(c) => {
				let resolver = crate::resolve::lookup_resolver(c);
				resolver.supported_tag_types().contains(&tag_type)
			},
			_ => false,
		}
	}

	/// Attempts to extract a [`FileType`] from an extension
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::FileType;
	///
	/// let extension = "mp3";
	/// assert_eq!(FileType::from_ext(extension), Some(FileType::MPEG));
	/// ```
	pub fn from_ext<E>(ext: E) -> Option<Self>
	where
		E: AsRef<OsStr>,
	{
		let ext = ext.as_ref().to_str()?.to_ascii_lowercase();

		match ext.as_str() {
			"aac" => Some(Self::AAC),
			"ape" => Some(Self::APE),
			"aiff" | "aif" | "afc" | "aifc" => Some(Self::AIFF),
			"mp3" | "mp2" | "mp1" => Some(Self::MPEG),
			"wav" | "wave" => Some(Self::WAV),
			"wv" => Some(Self::WavPack),
			"opus" => Some(Self::Opus),
			"flac" => Some(Self::FLAC),
			"ogg" => Some(Self::Vorbis),
			"mp4" | "m4a" | "m4b" | "m4p" | "m4r" | "m4v" | "3gp" => Some(Self::MP4),
			"spx" => Some(Self::Speex),
			e => {
				if let Some((ty, _)) = CUSTOM_RESOLVERS
					.lock()
					.ok()?
					.iter()
					.find(|(_, f)| f.extension() == Some(e))
				{
					Some(Self::Custom(ty))
				} else {
					None
				}
			},
		}
	}

	/// Attempts to determine a [`FileType`] from a path
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::FileType;
	/// use std::path::Path;
	///
	/// let path = Path::new("path/to/my.mp3");
	/// assert_eq!(FileType::from_path(path), Some(FileType::MPEG));
	/// ```
	pub fn from_path<P>(path: P) -> Option<Self>
	where
		P: AsRef<Path>,
	{
		let ext = path.as_ref().extension();
		ext.and_then(Self::from_ext)
	}

	/// Attempts to extract a [`FileType`] from a buffer
	///
	/// NOTES:
	///
	/// * This is for use in [`Probe::guess_file_type`], it
	/// is recommended to use it that way
	/// * This **will not** search past tags at the start of the buffer.
	/// For this behavior, use [`Probe::guess_file_type`].
	///
	/// [`Probe::guess_file_type`]: crate::Probe::guess_file_type
	///
	/// # Examples
	///
	/// ```rust
	/// use lofty::FileType;
	/// use std::fs::File;
	/// use std::io::Read;
	///
	/// # fn main() -> lofty::Result<()> {
	/// # let path_to_opus = "tests/files/assets/minimal/full_test.opus";
	/// let mut file = File::open(path_to_opus)?;
	///
	/// let mut buf = [0; 50]; // Search the first 50 bytes of the file
	/// file.read_exact(&mut buf)?;
	///
	/// assert_eq!(FileType::from_buffer(&buf), Some(FileType::Opus));
	/// # Ok(()) }
	/// ```
	pub fn from_buffer(buf: &[u8]) -> Option<Self> {
		match Self::from_buffer_inner(buf) {
			(Some(f_ty), _) => Some(f_ty),
			// We make no attempt to search past an ID3v2 tag here, since
			// we only provided a fixed-sized buffer to search from.
			//
			// That case is handled in `Probe::guess_file_type`
			_ => None,
		}
	}

	// TODO: APE tags in the beginning of the file
	pub(crate) fn from_buffer_inner(buf: &[u8]) -> (Option<Self>, Option<u32>) {
		use crate::id3::v2::util::unsynch_u32;

		// Start out with an empty return: (File type, id3 size)
		// Only one can be set
		let mut ret = (None, None);

		if buf.is_empty() {
			return ret;
		}

		match Self::quick_type_guess(buf) {
			Some(f_ty) => ret.0 = Some(f_ty),
			// Special case for ID3, gets checked in `Probe::guess_file_type`
			// The bare minimum size for an ID3v2 header is 10 bytes
			None if buf.len() >= 10 && &buf[..3] == b"ID3" => {
				// This is infallible, but preferable to an unwrap
				if let Ok(arr) = buf[6..10].try_into() {
					// Set the ID3v2 size
					ret.1 = Some(unsynch_u32(u32::from_be_bytes(arr)));
				}
			},
			// We aren't able to determine a format
			_ => {},
		}

		ret
	}

	fn quick_type_guess(buf: &[u8]) -> Option<Self> {
		use crate::mpeg::header::verify_frame_sync;

		// Safe to index, since we return early on an empty buffer
		match buf[0] {
			77 if buf.starts_with(b"MAC") => Some(Self::APE),
			255 if buf.len() >= 2 && verify_frame_sync([buf[0], buf[1]]) => {
				// ADTS and MPEG frame headers are way too similar

				// ADTS (https://wiki.multimedia.cx/index.php/ADTS#Header):
				//
				// AAAAAAAA AAAABCCX
				//
				// Letter 	Length (bits) 	Description
				// A 	    12 	            Syncword, all bits must be set to 1.
				// B 	    1 	            MPEG Version, set to 0 for MPEG-4 and 1 for MPEG-2.
				// C 	    2 	            Layer, always set to 0.

				// MPEG (http://www.mp3-tech.org/programmer/frame_header.html):
				//
				// AAAAAAAA AAABBCCX
				//
				// Letter 	Length (bits) 	Description
				// A 	    11              Syncword, all bits must be set to 1.
				// B 	    2 	            MPEG Audio version ID
				// C 	    2 	            Layer description

				// The subtle overlap in the ADTS header's frame sync and MPEG's version ID
				// is the first condition to check. However, since 0b10 and 0b11 are valid versions
				// in MPEG, we have to also check the layer.

				// So, if we have a version 1 (0b11) or version 2 (0b10) MPEG frame AND a layer of 0b00,
				// we can assume we have an ADTS header. Awesome!

				if buf[1] & 0b10000 > 0 && buf[1] & 0b110 == 0 {
					return Some(Self::AAC);
				}

				Some(Self::MPEG)
			},
			70 if buf.len() >= 12 && &buf[..4] == b"FORM" => {
				let id = &buf[8..12];

				if id == b"AIFF" || id == b"AIFC" {
					return Some(Self::AIFF);
				}

				None
			},
			79 if buf.len() >= 36 && &buf[..4] == b"OggS" => {
				if &buf[29..35] == b"vorbis" {
					return Some(Self::Vorbis);
				} else if &buf[28..36] == b"OpusHead" {
					return Some(Self::Opus);
				} else if &buf[28..36] == b"Speex   " {
					return Some(Self::Speex);
				}

				None
			},
			102 if buf.starts_with(b"fLaC") => Some(Self::FLAC),
			82 if buf.len() >= 12 && &buf[..4] == b"RIFF" => {
				if &buf[8..12] == b"WAVE" {
					return Some(Self::WAV);
				}

				None
			},
			119 if buf.len() >= 4 && &buf[..4] == b"wvpk" => Some(Self::WavPack),
			_ if buf.len() >= 8 && &buf[4..8] == b"ftyp" => Some(Self::MP4),
			_ => None,
		}
	}
}