Files
SpotiFLAC-Mobile/lib/utils/audio_conversion_utils.dart
T
zarzet d2669d13c4 feat(convert): choose the resampler quality with a slider
A lossless conversion that changes the sample rate could only pick SWR
or SoXR, each at one fixed setting. Add a quality slider under the
resampler choice, moved by dragging or by a tap anywhere on its track,
with the level named beside it and what it uses below.

SWR offers Fast, Medium, High, Very high and Best (16, 32, 64, 128 and
256 filter taps; the two highest also raise the Kaiser window's
rejection). SoXR offers Medium, High, Very high and Best (16, 20, 28 and
33 bits of precision; 20 and 28 are SoX's HQ and VHQ recipes).

The defaults are what a conversion used before: the library's own SWR
filter (Medium) and the most SoXR offers (Best). A conversion sent to a
paired computer carries the level; one from an older phone gets the
default.
2026-11-16 18:38:13 +07:00

469 lines
15 KiB
Dart

import 'package:mornye/l10n/app_localizations.dart';
const List<String> audioConversionTargetFormats = [
'ALAC',
'FLAC',
'WAV',
'AIFF',
'AAC',
'MP3',
'Opus',
];
const List<int> losslessConversionSampleRateOptions = [
192000,
96000,
48000,
44100,
];
const List<int> losslessConversionBitDepthOptions = [16, 24];
const List<String> losslessDitherOptions = [
'auto',
'none',
'triangular',
'triangular_hp',
];
const List<String> losslessResamplerOptions = ['swr', 'soxr'];
/// Resampler quality levels, lowest first. Each step up costs conversion
/// time; none changes the output format.
const List<String> losslessResamplerQualityOptions = [
'fast',
'medium',
'high',
'very_high',
'best',
];
/// The levels [resampler] offers. SoXR starts at Medium: FFmpeg does not
/// reach its two quickest recipes.
List<String> losslessResamplerQualityOptionsFor(String resampler) =>
resampler == 'soxr'
? losslessResamplerQualityOptions.sublist(1)
: losslessResamplerQualityOptions;
/// What a conversion used before the level could be chosen: the library's
/// own SWR filter, and the most SoXR offers.
String defaultLosslessResamplerQuality(String resampler) =>
resampler == 'soxr' ? 'best' : 'medium';
// The most SoXR offers: its highest precision (33 bits, above the 28 of its
// Very High Quality preset), a passband without ripple and exact handling of
// rate pairs that are not a simple ratio. Slower, for a conversion that runs
// once per file.
const int soxrPrecisionBits = 33;
const double soxrPassbandEndRatio = 0.95;
/// SoXR precision in bits per level. 20 is SoX's High Quality recipe and 28
/// its Very High Quality one.
int soxrPrecisionBitsFor(String quality) => switch (quality) {
'medium' => 16,
'high' => 20,
'very_high' => 28,
_ => soxrPrecisionBits,
};
/// SWR filter length in taps per level; 32 is the library's own.
int swrFilterSizeFor(String quality) => switch (quality) {
'fast' => 16,
'high' => 64,
'very_high' => 128,
'best' => 256,
_ => 32,
};
class LosslessConversionProcessing {
final String dither;
final String resampler;
/// One of [losslessResamplerQualityOptions]; null means the resampler's
/// default level.
final String? resamplerQuality;
/// Smart dither ('auto') applies high-pass TPDF instead of plain TPDF.
final bool highPass;
const LosslessConversionProcessing({
this.dither = 'auto',
this.resampler = 'swr',
this.resamplerQuality,
this.highPass = false,
});
String get normalizedDither {
final normalized = dither.trim().toLowerCase();
return losslessDitherOptions.contains(normalized) ? normalized : 'none';
}
String get normalizedResampler {
final normalized = resampler.trim().toLowerCase();
return losslessResamplerOptions.contains(normalized) ? normalized : 'swr';
}
/// A level the resampler offers, its default when none or another was
/// given.
String get normalizedResamplerQuality {
final resampler = normalizedResampler;
final normalized = resamplerQuality?.trim().toLowerCase();
return losslessResamplerQualityOptionsFor(resampler).contains(normalized)
? normalized!
: defaultLosslessResamplerQuality(resampler);
}
bool get hasDefaultResamplerQuality =>
normalizedResamplerQuality ==
defaultLosslessResamplerQuality(normalizedResampler);
bool get hasDither =>
normalizedDither == 'triangular' || normalizedDither == 'triangular_hp';
LosslessConversionProcessing resolveDither({
required int? sourceBitDepth,
required int? targetBitDepth,
}) {
if (normalizedDither != 'auto') return this;
final reducesDepth =
sourceBitDepth != null &&
targetBitDepth != null &&
targetBitDepth > 0 &&
sourceBitDepth > targetBitDepth;
return LosslessConversionProcessing(
dither: !reducesDepth
? 'none'
: highPass
? 'triangular_hp'
: 'triangular',
resampler: resampler,
resamplerQuality: resamplerQuality,
);
}
}
List<String> losslessResamplerFilterOptions(
LosslessConversionProcessing processing,
) {
final resampler = processing.normalizedResampler;
final quality = processing.normalizedResamplerQuality;
if (resampler == 'soxr') {
return [
'resampler=soxr',
'precision=${soxrPrecisionBitsFor(quality)}',
if (quality == 'best') ...['cutoff=$soxrPassbandEndRatio', 'cheby=1'],
];
}
return [
'resampler=swr',
// Medium is the library's own filter and names no option. A longer
// filter narrows the band between what is kept and what is removed;
// the two highest levels also raise the Kaiser window's rejection (its
// default 9 reaches about 100 dB), which only a long filter can afford.
if (quality != 'medium') 'filter_size=${swrFilterSizeFor(quality)}',
if (quality == 'very_high') 'kaiser_beta=12',
if (quality == 'best') 'kaiser_beta=16',
];
}
List<int> availableLosslessBitDepthOptions(int? sourceBitDepth) {
if (sourceBitDepth == null || sourceBitDepth <= 0) {
return losslessConversionBitDepthOptions;
}
return losslessConversionBitDepthOptions
.where((depth) => depth < sourceBitDepth)
.toList();
}
List<int> availableLosslessSampleRateOptions(int? sourceSampleRate) {
if (sourceSampleRate == null || sourceSampleRate <= 0) {
return losslessConversionSampleRateOptions;
}
return losslessConversionSampleRateOptions
.where((rate) => rate < sourceSampleRate)
.toList();
}
/// Offer every cap that can reduce a file in the batch. Unknown sources leave
/// the options open; the converter inspects each file before applying a cap.
int? conversionSourceMaximum(Iterable<int?> values) {
int? highest;
for (final value in values) {
if (value == null || value <= 0) return null;
if (highest == null || value > highest) {
highest = value;
}
}
return highest;
}
int normalizeAutoConvertBitDepth(int value) =>
value == 0 || losslessConversionBitDepthOptions.contains(value)
? value
: 16;
int normalizeAutoConvertSampleRate(int value) =>
value == 0 || losslessConversionSampleRateOptions.contains(value)
? value
: 48000;
class LosslessConversionQuality {
final int? maxBitDepth;
final int? maxSampleRate;
const LosslessConversionQuality({this.maxBitDepth, this.maxSampleRate});
bool get hasCaps => maxBitDepth != null || maxSampleRate != null;
int? effectiveBitDepth(int? sourceBitDepth) {
if (maxBitDepth == null) return sourceBitDepth;
if (sourceBitDepth == null || sourceBitDepth <= 0) return maxBitDepth;
return sourceBitDepth > maxBitDepth! ? maxBitDepth : sourceBitDepth;
}
int? effectiveSampleRate(int? sourceSampleRate) {
if (maxSampleRate == null) return sourceSampleRate;
if (sourceSampleRate == null || sourceSampleRate <= 0) {
return maxSampleRate;
}
return sourceSampleRate > maxSampleRate! ? maxSampleRate : sourceSampleRate;
}
}
bool isLosslessConversionTarget(String targetFormat) {
final normalized = targetFormat.trim().toLowerCase();
return normalized == 'alac' ||
normalized == 'flac' ||
normalized == 'wav' ||
normalized == 'aiff' ||
normalized == 'aif';
}
bool isLosslessConversionSource(String sourceFormat) =>
switch (sourceFormat.trim().toUpperCase()) {
'FLAC' || 'ALAC' || 'M4A' || 'WAV' || 'AIFF' || 'AIF' => true,
_ => false,
};
bool canConvertAudioFormat({
required String sourceFormat,
required String targetFormat,
}) {
final normalizedSource = sourceFormat.trim().toUpperCase();
final normalizedTarget = targetFormat.trim().toUpperCase();
if (normalizedSource == normalizedTarget) {
// Same-format lossless re-encoding is useful for reducing bit depth or
// sample rate while selecting the dither and resampler implementation.
return isLosslessConversionSource(normalizedSource) &&
isLosslessConversionTarget(normalizedTarget);
}
if (isLosslessConversionTarget(targetFormat) &&
!isLosslessConversionSource(sourceFormat)) {
return false;
}
return true;
}
String? convertibleAudioSourceFormat({
String? storedFormat,
String? filePath,
String? fileName,
}) {
final fromStored = _convertibleAudioFormatLabel(storedFormat);
if (fromStored != null) return fromStored;
final name = (fileName != null && fileName.trim().isNotEmpty)
? fileName
: filePath;
if (name == null || name.trim().isEmpty) return null;
final normalizedName = name.trim().toLowerCase();
final dotIndex = normalizedName.lastIndexOf('.');
if (dotIndex < 0 || dotIndex == normalizedName.length - 1) {
return null;
}
return _convertibleAudioFormatLabel(normalizedName.substring(dotIndex + 1));
}
String? _convertibleAudioFormatLabel(String? rawFormat) {
final format = rawFormat?.trim().toLowerCase();
if (format == null || format.isEmpty) return null;
return switch (format) {
'flac' => 'FLAC',
'alac' => 'ALAC',
'wav' || 'wave' => 'WAV',
'aiff' || 'aif' || 'aifc' => 'AIFF',
'm4a' || 'mp4' => 'M4A',
'aac' || 'mp4a' => 'AAC',
'mp3' => 'MP3',
'opus' || 'ogg' => 'Opus',
'eac3' || 'ec-3' => 'EAC3',
'ac3' || 'ac-3' => 'AC3',
'ac4' || 'ac-4' => 'AC4',
_ => null,
};
}
class LosslessConversionLabels {
final String original;
final String originalQuality;
final String lossless;
const LosslessConversionLabels({
required this.original,
required this.originalQuality,
required this.lossless,
});
}
extension LosslessConversionLabelsL10n on AppLocalizations {
LosslessConversionLabels get losslessConversionLabels =>
LosslessConversionLabels(
original: trackConvertOriginal,
originalQuality: trackConvertOriginalQuality,
lossless: trackConvertLosslessSuffix,
);
String losslessDitherOptionLabel(String dither) =>
switch (dither.trim().toLowerCase()) {
'auto' => trackConvertDitherSmart,
'triangular' => trackConvertDitherTriangular,
'triangular_hp' => trackConvertDitherTriangularHp,
_ => trackConvertDitherNone,
};
String losslessResamplerOptionLabel(String resampler) =>
switch (resampler.trim().toLowerCase()) {
'soxr' => trackConvertResamplerSoxr,
_ => trackConvertResamplerSwr,
};
String losslessResamplerQualityLabel(String quality) => switch (quality) {
'fast' => trackConvertResamplerQualityFast,
'high' => trackConvertResamplerQualityHigh,
'very_high' => trackConvertResamplerQualityVeryHigh,
'best' => trackConvertResamplerQualityBest,
_ => trackConvertResamplerQualityMedium,
};
/// What a level means for [resampler], such as "64-tap filter" or "28-bit
/// precision, SoX VHQ".
String losslessResamplerQualityDetail(String resampler, String quality) {
if (resampler != 'soxr') {
return trackConvertResamplerSwrDetail(swrFilterSizeFor(quality));
}
final bits = soxrPrecisionBitsFor(quality);
return switch (quality) {
'high' => trackConvertResamplerSoxrPresetDetail(bits, 'HQ'),
'very_high' => trackConvertResamplerSoxrPresetDetail(bits, 'VHQ'),
_ => trackConvertResamplerSoxrDetail(bits),
};
}
}
String losslessBitDepthLabel(int? bitDepth, {required String originalLabel}) {
return bitDepth == null ? originalLabel : '$bitDepth-bit';
}
String losslessSampleRateLabel(
int? sampleRate, {
required String originalLabel,
}) {
if (sampleRate == null) return originalLabel;
final khz = sampleRate / 1000;
final precision = sampleRate % 1000 == 0 ? 0 : 1;
return '${khz.toStringAsFixed(precision)} kHz';
}
String losslessQualityLabel(
LosslessConversionQuality quality, {
required String originalLabel,
required String originalQualityLabel,
}) {
final parts = <String>[];
if (quality.maxBitDepth != null) {
parts.add(
losslessBitDepthLabel(quality.maxBitDepth, originalLabel: originalLabel),
);
}
if (quality.maxSampleRate != null) {
parts.add(
losslessSampleRateLabel(
quality.maxSampleRate,
originalLabel: originalLabel,
),
);
}
return parts.isEmpty ? originalQualityLabel : parts.join(' / ');
}
String convertedAudioQualityLabel({
required String targetFormat,
required String bitrate,
required LosslessConversionLabels labels,
LosslessConversionQuality losslessQuality = const LosslessConversionQuality(),
int? actualBitDepth,
int? actualSampleRate,
}) {
final upper = targetFormat.toUpperCase();
if (isLosslessConversionTarget(targetFormat)) {
if (actualBitDepth != null &&
actualBitDepth > 0 &&
actualSampleRate != null &&
actualSampleRate > 0) {
return '$upper ${losslessBitDepthLabel(actualBitDepth, originalLabel: labels.original)}/${losslessSampleRateLabel(actualSampleRate, originalLabel: labels.original)}';
}
if (losslessQuality.hasCaps) {
return '$upper ${losslessQualityLabel(losslessQuality, originalLabel: labels.original, originalQualityLabel: labels.originalQuality)}';
}
return '$upper ${labels.lossless}';
}
return '$upper ${bitrate.trim().toLowerCase()}';
}
String normalizedConvertedAudioFormat(String targetFormat) {
return targetFormat.trim().toLowerCase();
}
/// Returns the output file extension (with dot) and MIME type for a conversion
/// target format. Used when creating the converted file via SAF so WAV/AIFF and
/// the other formats get the correct extension + MIME.
({String ext, String mime}) convertTargetExtAndMime(String targetFormat) =>
switch (targetFormat.trim().toLowerCase()) {
'opus' => (ext: '.opus', mime: 'audio/opus'),
'alac' || 'aac' => (ext: '.m4a', mime: 'audio/mp4'),
'flac' => (ext: '.flac', mime: 'audio/flac'),
'wav' => (ext: '.wav', mime: 'audio/wav'),
'aiff' || 'aif' => (ext: '.aiff', mime: 'audio/aiff'),
_ => (ext: '.mp3', mime: 'audio/mpeg'),
};
String convertedOutputFileName({
required String originalFileName,
required String targetFormat,
}) {
final dotIndex = originalFileName.lastIndexOf('.');
final baseName = dotIndex > 0
? originalFileName.substring(0, dotIndex)
: originalFileName;
return '$baseName${convertTargetExtAndMime(targetFormat).ext}';
}
String convertedLibraryItemId(String sourceId, String filePath) {
var hash = 5381;
for (final codeUnit in filePath.codeUnits) {
hash = (((hash << 5) + hash) ^ codeUnit) & 0x7fffffff;
}
return '$sourceId:converted:${hash.toRadixString(16)}';
}
int? convertedAudioBitrateKbps({
required String targetFormat,
required String bitrate,
}) {
if (isLosslessConversionTarget(targetFormat)) return null;
final match = RegExp(r'(\d+)').firstMatch(bitrate);
return match != null ? int.tryParse(match.group(1)!) : null;
}