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
//! Generic user star rating (a.k.a. popularimeter) support
//!
//! Popularimeters, in ID3v2 terms, are star ratings with an associated email and play counter.
//! Most tag formats support ratings in some capacity, usually with a subset of the information available
//! in ID3v2. For example, Vorbis Comments supports star ratings and optionally emails, but not play
//! counters.
//!
//! This module contains a generic [`Popularimeter`], which supports all of the information available
//! in ID3v2, and can (lossily) be converted to all other supported formats.
//!
//! ## Ratings
//!
//! Unfortunately, no tag format has a standard for mapping integer values to star ratings. This means
//! many application-specific mappings have appeared over the years (see [providers](#providers)).
//!
//! Additionally, most applications assume whole-number star ratings. As such, this generic format
//! can **not** be used for fractional ratings.
//!
//! ### Providers
//!
//! Lofty provides multiple rating providers for popular applications (e.g. [`MusicBeeProvider`]).
//! These providers are dispatched by email, as many apps will use the `email` field to store their
//! name (e.g. "Windows Media Player 9 Series"). These providers can **not** be disabled.
//!
//! To define a custom rating provider, see [`RatingProvider`] and [`set_custom_rating_provider()`].
//! However, consider checking out the existing providers to have wider application support.
//!
//! ## Usage
//!
//! ```
//! use lofty::tag::items::popularimeter::{Popularimeter, StarRating};
//! use lofty::tag::{ItemKey, Tag, TagType};
//!
//! // Create a MusicBee-style popularimeter
//! let play_counter = 10;
//! let rating = Popularimeter::musicbee(StarRating::Three, play_counter);
//!
//! // Popularimeters can be inserted like any other text value.
//! // All format-specific encoding is handled behind-the-scenes.
//! let mut tag = Tag::new(TagType::Id3v2);
//! tag.insert_text(ItemKey::Popularimeter, rating.to_string());
//!
//! // Then all ratings can be fetched
//! let ratings = tag.ratings().collect::<Vec<_>>();
//! assert_eq!(ratings.len(), 1);
//! ```

use crate::tag::TagType;

use std::borrow::Cow;
use std::fmt::{Debug, Display, Formatter};
use std::sync::OnceLock;

/// A whole-number star rating
///
/// There is no generic way to handle fractional ratings, as *many* players/taggers will assume
/// integer ratings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StarRating {
	/// One star
	One = 1,
	/// Two stars
	Two = 2,
	/// Three stars
	Three = 3,
	/// Four stars
	Four = 4,
	/// Five stars
	Five = 5,
}

/// A rating provider for [`Popularimeter`]s
///
/// As there is no standard for ratings, there are multiple providers for popular applications
/// available (e.g. [`MusicBeeProvider`]). See [`Popularimeter`] for more details.
///
/// To set a custom rating provider, see [`set_custom_rating_provider()`].
pub trait RatingProvider: Send + Sync {
	/// Whether this provider should be used for the given email
	fn supports_email(&self, email: &str) -> bool;

	/// Converts a [`StarRating`] to a format-specific integer
	fn rate(&self, tag_type: TagType, rating: StarRating) -> u8;

	/// Converts a format-specific rating to a [`StarRating`]
	fn convert_raw(&self, tag_type: TagType, rating: u8) -> StarRating;
}

static CUSTOM_PROVIDER: OnceLock<&'static dyn RatingProvider> = OnceLock::new();

/// Apply a custom rating provider globally
///
/// By default, the fallback provider will be [`DefaultRatingProvider`].
///
/// # Panics
///
/// This will panic if called more than once.
///
/// # Examples
///
/// ```
/// use lofty::tag::TagType;
/// use lofty::tag::items::popularimeter::{
/// 	RatingProvider, StarRating, set_custom_rating_provider,
/// };
///
/// struct MyCustomProvider;
///
/// impl RatingProvider for MyCustomProvider {
/// 	fn supports_email(&self, email: &str) -> bool {
/// 		true // Support all emails
/// 	}
///
/// 	fn rate(&self, tag_type: TagType, rating: StarRating) -> u8 {
/// 		match tag_type {
/// 			_ => todo!("Mapping of `StarRating` to format-specific values"),
/// 		}
/// 	}
///
/// 	fn convert_raw(&self, tag_type: TagType, rating: u8) -> StarRating {
/// 		match tag_type {
/// 			_ => todo!("Mapping of format-specific values to `StarRating`"),
/// 		}
/// 	}
/// }
///
/// set_custom_rating_provider(MyCustomProvider);
/// ```
pub fn set_custom_rating_provider<T>(provider: T)
where
	T: RatingProvider + 'static,
{
	assert!(
		CUSTOM_PROVIDER.set(Box::leak(Box::new(provider))).is_ok(),
		"Multiple calls to `set_custom_rating_provider()`"
	);
}

fn custom_provider() -> &'static dyn RatingProvider {
	CUSTOM_PROVIDER.get().map_or(DEFAULT_PROVIDER, |p| *p)
}

/// The default [`RatingProvider`] used as a fallback for unknown ratings
///
/// This is equivalent to the [`MusicBeeProvider`], except it supports *all* emails.
///
/// This can be overwritten with [`set_custom_rating_provider()`].
pub struct DefaultRatingProvider;

impl RatingProvider for DefaultRatingProvider {
	fn supports_email(&self, _: &str) -> bool {
		true
	}

	// MusicBee-style ratings seem to be the most widely used (?)
	fn rate(&self, tag_type: TagType, rating: StarRating) -> u8 {
		MUSICBEE_PROVIDER.rate(tag_type, rating)
	}

	fn convert_raw(&self, tag_type: TagType, rating: u8) -> StarRating {
		MUSICBEE_PROVIDER.convert_raw(tag_type, rating)
	}
}

static DEFAULT_PROVIDER: &'static dyn RatingProvider = &DefaultRatingProvider;
static MUSICBEE_PROVIDER: &'static dyn RatingProvider = &MusicBeeProvider;
static WMP_PROVIDER: &'static dyn RatingProvider = &WindowsMediaPlayerProvider;
static PICARD_PROVIDER: &'static dyn RatingProvider = &PicardProvider;

/// A [MusicBee]-style rating
///
/// [MusicBee]: https://getmusicbee.com/
pub struct MusicBeeProvider;

impl RatingProvider for MusicBeeProvider {
	fn supports_email(&self, email: &str) -> bool {
		email == Popularimeter::MUSICBEE_EMAIL
	}

	fn rate(&self, tag_type: TagType, rating: StarRating) -> u8 {
		match tag_type {
			TagType::Id3v2 => match rating {
				StarRating::One => 1,
				StarRating::Two => 64,
				StarRating::Three => 128,
				StarRating::Four => 196,
				StarRating::Five => 255,
			},
			_ => {
				let stars = rating as u8;
				stars.saturating_mul(20)
			},
		}
	}

	#[allow(clippy::match_overlapping_arm)]
	fn convert_raw(&self, tag_type: TagType, rating: u8) -> StarRating {
		match tag_type {
			TagType::Id3v2 => match rating {
				..=1 => StarRating::One,
				..=64 => StarRating::Two,
				..=128 => StarRating::Three,
				..=196 => StarRating::Four,
				..=255 => StarRating::Five,
			},
			_ => match rating {
				..=20 => StarRating::One,
				..=40 => StarRating::Two,
				..=60 => StarRating::Three,
				..=80 => StarRating::Four,
				_ => StarRating::Five,
			},
		}
	}
}

/// A [Windows Media Player]-style rating
///
/// [Windows Media Player]: https://en.wikipedia.org/wiki/Windows_Media_Player
pub struct WindowsMediaPlayerProvider;

impl RatingProvider for WindowsMediaPlayerProvider {
	fn supports_email(&self, email: &str) -> bool {
		email == Popularimeter::WMP_EMAIL
	}

	fn rate(&self, _: TagType, rating: StarRating) -> u8 {
		// WMP only supports ID3v2 ratings, and uses the same values as MusicBee
		MusicBeeProvider.rate(TagType::Id3v2, rating)
	}

	fn convert_raw(&self, _: TagType, rating: u8) -> StarRating {
		MusicBeeProvider.convert_raw(TagType::Id3v2, rating)
	}
}

/// A [MusicBrainz Picard]-style rating
///
/// [MusicBrainz Picard]: https://picard.musicbrainz.org/
pub struct PicardProvider;

impl RatingProvider for PicardProvider {
	fn supports_email(&self, email: &str) -> bool {
		email == Popularimeter::PICARD_EMAIL
	}

	fn rate(&self, tag_type: TagType, rating: StarRating) -> u8 {
		match tag_type {
			TagType::Id3v2 => {
				let stars = rating as u8;
				stars.saturating_mul(51)
			},
			_ => {
				let stars = rating as u8;
				stars.saturating_mul(5)
			},
		}
	}

	#[allow(clippy::match_overlapping_arm)]
	fn convert_raw(&self, tag_type: TagType, rating: u8) -> StarRating {
		match tag_type {
			TagType::Id3v2 => match rating {
				..=51 => StarRating::One,
				..=102 => StarRating::Two,
				..=153 => StarRating::Three,
				..=204 => StarRating::Four,
				..=255 => StarRating::Five,
			},
			_ => match rating {
				..=5 => StarRating::One,
				..=10 => StarRating::Two,
				..=15 => StarRating::Three,
				..=20 => StarRating::Four,
				_ => StarRating::Five,
			},
		}
	}
}

/// A generic user rating and play counter
///
/// Unfortunately, there is no widely agreed-upon scale for ratings. There are constructors for multiple
/// popular taggers (e.g. [Popularimeter::musicbee()]), that will create a properly scaled [`StarRating`].
///
/// In most cases, apps will look for ratings with their specific [`email`], meaning it *should* be
/// safe to write multiple application-specific ratings to the same file.
///
/// See the module docs for more information.
///
/// See also: [`StarRating`]
///
/// [`email`]: Popularimeter::email
#[derive(Clone)]
pub struct Popularimeter<'a> {
	// Private since the email is what determines how we handle conversions
	pub(crate) email: Option<Cow<'a, str>>,
	pub(crate) rating_provider: &'static dyn RatingProvider,
	/// The star rating provided by the user
	pub rating: StarRating,
	/// The number of times the user has played the song
	///
	/// NOTE: This is only supported in ID3v2
	pub play_counter: u64,
}

impl Debug for Popularimeter<'_> {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("Popularimeter")
			.field("email", &self.email)
			.field("rating", &self.rating)
			.field("play_counter", &self.play_counter)
			.finish()
	}
}

impl<'a> Popularimeter<'a> {
	const WMP_EMAIL: &'static str = "Windows Media Player 9 Series";
	const MUSICBEE_EMAIL: &'static str = "MusicBee";
	const PICARD_EMAIL: &'static str = "users@musicbrainz.org";

	/// Create a new [`Popularimeter`] using the custom [`RatingProvider`]
	///
	/// NOTES:
	///
	/// * This will use [`DefaultRatingProvider`] if [`set_custom_rating_provider()`] has not been called.
	/// * For wider support, check out the tagger-specific constructors (e.g. [`Popularimeter::musicbee()`])
	///   first, before creating a custom rating scale.
	///
	/// # Examples
	///
	/// ```
	/// use lofty::tag::items::popularimeter::{Popularimeter, StarRating};
	///
	/// let rating = Popularimeter::custom("foo@example.com", StarRating::Three, 5);
	/// assert_eq!(rating.email(), Some("foo@example.com"));
	/// assert_eq!(rating.rating(), StarRating::Three);
	/// assert_eq!(rating.play_counter, 5);
	/// ```
	pub fn custom(email: impl Into<Cow<'a, str>>, rating: StarRating, play_counter: u64) -> Self {
		Self {
			email: Some(email.into()),
			rating_provider: custom_provider(),
			rating,
			play_counter,
		}
	}

	pub(crate) fn mapped(
		email: impl Into<Cow<'a, str>>,
		tag_type: TagType,
		rate: u8,
		play_counter: u64,
	) -> Option<Self> {
		let email = email.into();

		let rating_provider;
		match &*email {
			Popularimeter::WMP_EMAIL => rating_provider = WMP_PROVIDER,
			Popularimeter::MUSICBEE_EMAIL => rating_provider = MUSICBEE_PROVIDER,
			Popularimeter::PICARD_EMAIL => rating_provider = PICARD_PROVIDER,
			_ => {
				rating_provider = custom_provider();
				if !rating_provider.supports_email(&email) {
					return None;
				}
			},
		}

		let star_rating = rating_provider.convert_raw(tag_type, rate);
		Some(Self {
			email: (!email.is_empty()).then_some(email),
			rating_provider,
			rating: star_rating,
			play_counter,
		})
	}

	/// The email associated with this rating
	///
	/// NOTE: In many cases, this will be an application name (e.g. "Windows Media Player 9 Series"), rather
	///       than an actual email.
	///
	/// # Examples
	///
	/// ```
	/// use lofty::tag::items::popularimeter::{Popularimeter, StarRating};
	///
	/// let rating = Popularimeter::custom("foo@example.com", StarRating::Three, 5);
	/// assert_eq!(rating.email(), Some("foo@example.com"))
	/// ```
	pub fn email(&self) -> Option<&str> {
		self.email.as_deref()
	}

	/// The user's rating
	///
	/// # Examples
	///
	/// ```
	/// use lofty::tag::items::popularimeter::{Popularimeter, StarRating};
	///
	/// let rating = Popularimeter::musicbee(StarRating::Three, 5);
	/// assert_eq!(rating.rating(), StarRating::Three);
	/// ```
	pub fn rating(&self) -> StarRating {
		self.rating
	}

	pub(crate) fn mapped_value(&self, tag_type: TagType) -> u8 {
		self.rating_provider.rate(tag_type, self.rating)
	}

	pub(crate) fn from_str(s: &str) -> Result<Self, ()> {
		let mut parts = s.splitn(3, '|');
		let email = parts.next().ok_or(())?;
		let star_rating = parts.next().ok_or(())?;
		let play_counter = parts
			.next()
			.ok_or(())
			.and_then(|p| p.parse::<u64>().map_err(|_| ()))?;

		let star_rating = match star_rating.parse().map_err(|_| ())? {
			1 => StarRating::One,
			2 => StarRating::Two,
			3 => StarRating::Three,
			4 => StarRating::Four,
			5 => StarRating::Five,
			_ => return Err(()),
		};

		let rating_provider;
		match email {
			Popularimeter::WMP_EMAIL => rating_provider = WMP_PROVIDER,
			Popularimeter::MUSICBEE_EMAIL => rating_provider = MUSICBEE_PROVIDER,
			Popularimeter::PICARD_EMAIL => rating_provider = PICARD_PROVIDER,
			_ => {
				rating_provider = custom_provider();
				if !rating_provider.supports_email(email) {
					return Err(());
				}
			},
		}

		Ok(Popularimeter {
			email: (!email.is_empty()).then(|| Cow::Owned(email.to_owned())),
			rating_provider,
			rating: star_rating,
			play_counter,
		})
	}
}

impl Popularimeter<'static> {
	/// Create a new [Windows Media Player]-style rating
	///
	/// [Windows Media Player]: https://en.wikipedia.org/wiki/Windows_Media_Player
	pub fn windows_media_player(rating: StarRating, play_counter: u64) -> Self {
		Self {
			email: Some(Cow::Borrowed(Self::WMP_EMAIL)),
			rating_provider: WMP_PROVIDER,
			rating,
			play_counter,
		}
	}

	/// Create a new [MusicBee]-style rating
	///
	/// [MusicBee]: https://getmusicbee.com/
	pub fn musicbee(rating: StarRating, play_counter: u64) -> Self {
		Self {
			email: Some(Cow::Borrowed(Self::MUSICBEE_EMAIL)),
			rating_provider: MUSICBEE_PROVIDER,
			rating,
			play_counter,
		}
	}

	/// Create a new [MusicBrainz Picard]-style rating
	///
	/// [MusicBrainz Picard]: https://picard.musicbrainz.org/
	pub fn picard(rating: StarRating, play_counter: u64) -> Self {
		Self {
			email: Some(Cow::Borrowed(Self::PICARD_EMAIL)),
			rating_provider: PICARD_PROVIDER,
			rating,
			play_counter,
		}
	}
}

impl Display for Popularimeter<'_> {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		let email = self.email.as_deref().unwrap_or("");
		write!(f, "{email}|{}|{}", self.rating as u8, self.play_counter)
	}
}