Spaces:
Sleeping
Sleeping
File size: 2,385 Bytes
3c56493 | 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 | import type { AudioQuality, Track } from '$lib/types';
const QUALITY_PRIORITY: readonly AudioQuality[] = [
'HI_RES_LOSSLESS',
'LOSSLESS',
'HIGH',
'LOW'
];
const QUALITY_TOKENS: Record<AudioQuality, readonly string[]> = {
HI_RES_LOSSLESS: [
'HI_RES_LOSSLESS',
'HIRES_LOSSLESS',
'HIRESLOSSLESS',
'HIFI_PLUS',
'HI_RES_FLAC',
'HI_RES',
'HIRES',
'MASTER',
'MASTER_QUALITY',
'MQA'
],
LOSSLESS: ['LOSSLESS', 'HIFI'],
HIGH: ['HIGH', 'HIGH_QUALITY'],
LOW: ['LOW', 'LOW_QUALITY']
};
const QUALITY_RANK = new Map<AudioQuality, number>(
QUALITY_PRIORITY.map((quality, index) => [quality, index])
);
const sanitizeToken = (value: string): string => value.trim().toUpperCase().replace(/[^A-Z0-9]+/g, '_');
export function normalizeQualityToken(value?: string | null): AudioQuality | null {
if (!value) {
return null;
}
const token = sanitizeToken(value);
for (const [quality, aliases] of Object.entries(QUALITY_TOKENS) as Array<[
AudioQuality,
readonly string[]
]>) {
if (aliases.includes(token)) {
return quality;
}
}
return null;
}
export function deriveQualityFromTags(rawTags?: unknown): AudioQuality | null {
if (!Array.isArray(rawTags)) {
return null;
}
const candidates: AudioQuality[] = [];
for (const tag of rawTags) {
if (typeof tag !== 'string') {
continue;
}
const normalized = normalizeQualityToken(tag);
if (normalized && !candidates.includes(normalized)) {
candidates.push(normalized);
}
}
return pickBestQuality(candidates);
}
export function pickBestQuality(
candidates: Array<AudioQuality | null | undefined>
): AudioQuality | null {
let best: AudioQuality | null = null;
for (const candidate of candidates) {
if (!candidate) {
continue;
}
if (!best) {
best = candidate;
continue;
}
const currentRank = QUALITY_RANK.get(candidate) ?? Number.POSITIVE_INFINITY;
const bestRank = QUALITY_RANK.get(best) ?? Number.POSITIVE_INFINITY;
if (currentRank < bestRank) {
best = candidate;
}
}
return best;
}
export function deriveTrackQuality(track?: Track | null): AudioQuality | null {
if (!track) {
return null;
}
const candidates: Array<AudioQuality | null> = [
deriveQualityFromTags(track.mediaMetadata?.tags),
deriveQualityFromTags(track.album?.mediaMetadata?.tags),
normalizeQualityToken(track.audioQuality)
];
return pickBestQuality(candidates);
}
|