diff --git a/lib/l10n/arb/app_en.arb b/lib/l10n/arb/app_en.arb index d50a85e94..6d96df742 100644 --- a/lib/l10n/arb/app_en.arb +++ b/lib/l10n/arb/app_en.arb @@ -8633,6 +8633,35 @@ "@lyricsBlurOff": { "description": "Value of the lyrics blur slider at zero" }, + "lyricsOffset": "Lyrics timing", + "@lyricsOffset": { + "description": "Setting: move synced lyrics earlier or later than playback" + }, + "lyricsOffsetSubtitle": "Show synced lyrics later or earlier, for example when Bluetooth audio arrives late", + "lyricsOffsetNone": "In sync", + "@lyricsOffsetNone": { + "description": "Value of the lyrics timing slider at zero" + }, + "lyricsOffsetLater": "{seconds} s later", + "@lyricsOffsetLater": { + "description": "Value of the lyrics timing slider when lyrics follow playback late", + "placeholders": { + "seconds": { + "type": "String", + "example": "0.3" + } + } + }, + "lyricsOffsetEarlier": "{seconds} s earlier", + "@lyricsOffsetEarlier": { + "description": "Value of the lyrics timing slider when lyrics run ahead of playback", + "placeholders": { + "seconds": { + "type": "String", + "example": "0.3" + } + } + }, "appCrashTitle": "The app previously crashed", "appAnrTitle": "The app previously stopped responding", "@appAnrTitle": { diff --git a/lib/l10n/arb/app_id.arb b/lib/l10n/arb/app_id.arb index 22cca598e..935b8b337 100644 --- a/lib/l10n/arb/app_id.arb +++ b/lib/l10n/arb/app_id.arb @@ -7956,6 +7956,11 @@ "lyricsBlur": "Blur lirik", "lyricsBlurSubtitle": "Seberapa samar baris di sekitar baris yang sedang diputar", "lyricsBlurOff": "Mati", + "lyricsOffset": "Waktu lirik", + "lyricsOffsetSubtitle": "Tampilkan lirik tersinkron lebih lambat atau lebih cepat, misalnya saat audio Bluetooth tertunda", + "lyricsOffsetNone": "Sinkron", + "lyricsOffsetLater": "{seconds} dtk lebih lambat", + "lyricsOffsetEarlier": "{seconds} dtk lebih cepat", "appCrashTitle": "Aplikasi sebelumnya mengalami crash", "appAnrTitle": "Aplikasi sebelumnya berhenti merespons", "@appAnrTitle": { diff --git a/lib/models/theme_settings.dart b/lib/models/theme_settings.dart index b54b54b46..1f5827f72 100644 --- a/lib/models/theme_settings.dart +++ b/lib/models/theme_settings.dart @@ -21,6 +21,15 @@ const String kLyricsBlurKey = 'lyrics_blur'; /// it off, 1 is the default. double normalizeLyricsBlur(num? value) => value != null && value.isFinite ? value.toDouble().clamp(0.0, 1.5) : 1.0; +const String kLyricsOffsetKey = 'lyrics_offset_ms'; +const int kMaxLyricsOffsetMs = 2000; + +/// How much later synced lyrics follow playback, in milliseconds, so they +/// match audio that reaches the ears late (such as over Bluetooth). Negative +/// values show them earlier. +int normalizeLyricsOffsetMs(num? value) => value != null && value.isFinite + ? value.round().clamp(-kMaxLyricsOffsetMs, kMaxLyricsOffsetMs) + : 0; const String kMornyeGlassClarityKey = 'mornye_glass_clarity'; const String kMornyeGlassOutlinesKey = 'mornye_glass_outlines'; const double kDefaultMornyeGlassClarity = 0.75; @@ -65,6 +74,7 @@ class ThemeSettings { final String customFontName; final double lyricsTextScale; final double lyricsBlur; + final int lyricsOffsetMs; final double mornyeGlassClarity; final bool mornyeGlassOutlines; @@ -80,6 +90,7 @@ class ThemeSettings { this.customFontName = '', this.lyricsTextScale = 1, this.lyricsBlur = 1, + this.lyricsOffsetMs = 0, this.mornyeGlassClarity = kDefaultMornyeGlassClarity, this.mornyeGlassOutlines = true, }); @@ -98,6 +109,7 @@ class ThemeSettings { String? customFontName, double? lyricsTextScale, double? lyricsBlur, + int? lyricsOffsetMs, double? mornyeGlassClarity, bool? mornyeGlassOutlines, }) { @@ -115,6 +127,9 @@ class ThemeSettings { lyricsTextScale ?? this.lyricsTextScale, ), lyricsBlur: normalizeLyricsBlur(lyricsBlur ?? this.lyricsBlur), + lyricsOffsetMs: normalizeLyricsOffsetMs( + lyricsOffsetMs ?? this.lyricsOffsetMs, + ), mornyeGlassClarity: normalizeMornyeGlassClarity( mornyeGlassClarity ?? this.mornyeGlassClarity, ), @@ -134,6 +149,7 @@ class ThemeSettings { kCustomFontNameKey: customFontName, kLyricsTextScaleKey: lyricsTextScale, kLyricsBlurKey: lyricsBlur, + kLyricsOffsetKey: lyricsOffsetMs, kMornyeGlassClarityKey: mornyeGlassClarity, kMornyeGlassOutlinesKey: mornyeGlassOutlines, }; @@ -153,6 +169,7 @@ class ThemeSettings { json[kLyricsTextScaleKey] as num?, ), lyricsBlur: normalizeLyricsBlur(json[kLyricsBlurKey] as num?), + lyricsOffsetMs: normalizeLyricsOffsetMs(json[kLyricsOffsetKey] as num?), mornyeGlassClarity: normalizeMornyeGlassClarity( json[kMornyeGlassClarityKey] as num?, ), @@ -175,6 +192,7 @@ class ThemeSettings { other.customFontName == customFontName && other.lyricsTextScale == lyricsTextScale && other.lyricsBlur == lyricsBlur && + other.lyricsOffsetMs == lyricsOffsetMs && other.mornyeGlassClarity == mornyeGlassClarity && other.mornyeGlassOutlines == mornyeGlassOutlines; } @@ -192,6 +210,7 @@ class ThemeSettings { customFontName.hashCode ^ lyricsTextScale.hashCode ^ lyricsBlur.hashCode ^ + lyricsOffsetMs.hashCode ^ mornyeGlassClarity.hashCode ^ mornyeGlassOutlines.hashCode; } diff --git a/lib/providers/theme_provider.dart b/lib/providers/theme_provider.dart index 240ff43de..98e8038be 100644 --- a/lib/providers/theme_provider.dart +++ b/lib/providers/theme_provider.dart @@ -22,6 +22,7 @@ ThemeSettings loadBootstrapThemeSettings(SharedPreferences prefs) { prefs.getDouble(kLyricsTextScaleKey), ), lyricsBlur: normalizeLyricsBlur(prefs.getDouble(kLyricsBlurKey)), + lyricsOffsetMs: normalizeLyricsOffsetMs(prefs.getInt(kLyricsOffsetKey)), mornyeGlassClarity: normalizeMornyeGlassClarity( prefs.getDouble(kMornyeGlassClarityKey), ), @@ -87,6 +88,7 @@ class ThemeNotifier extends Notifier { await prefs.setString(kCustomFontNameKey, snapshot.customFontName); await prefs.setDouble(kLyricsTextScaleKey, snapshot.lyricsTextScale); await prefs.setDouble(kLyricsBlurKey, snapshot.lyricsBlur); + await prefs.setInt(kLyricsOffsetKey, snapshot.lyricsOffsetMs); await prefs.setDouble( kMornyeGlassClarityKey, snapshot.mornyeGlassClarity, @@ -152,6 +154,11 @@ class ThemeNotifier extends Notifier { if (persist) await _saveToStorage(); } + Future setLyricsOffsetMs(int value, {bool persist = true}) async { + _editState((current) => current.copyWith(lyricsOffsetMs: value)); + if (persist) await _saveToStorage(); + } + Future setMornyeGlassClarity( double value, { bool persist = true, diff --git a/lib/screens/settings/lyrics_settings_page.dart b/lib/screens/settings/lyrics_settings_page.dart index 21b31b7bd..8644d388c 100644 --- a/lib/screens/settings/lyrics_settings_page.dart +++ b/lib/screens/settings/lyrics_settings_page.dart @@ -51,6 +51,7 @@ class LyricsSettingsPage extends ConsumerWidget { // Lyrics blur only where the player draws it. if (context.isMornye && ref.watch(mornyeLiquidGlassProvider)) const LyricsBlurSetting(), + const LyricsOffsetSetting(), SettingsSwitchItem( icon: Icons.light_mode_outlined, title: context.l10n.lyricsKeepScreenOn, diff --git a/lib/utils/lyrics_timeline.dart b/lib/utils/lyrics_timeline.dart index 6f3c3f430..1984ae7da 100644 --- a/lib/utils/lyrics_timeline.dart +++ b/lib/utils/lyrics_timeline.dart @@ -273,3 +273,38 @@ Duration _estimatedFinalWordEnd( if (next - start <= nearGap) return next; return estimate; } + +/// Moves every line and word [offset] later (earlier when negative), for the +/// listener's lyrics timing setting. Times stop at the start of the track. +List lyricsShiftedBy(List lines, Duration offset) { + if (offset == Duration.zero) return lines; + Duration shift(Duration time) { + final shifted = time + offset; + return shifted < Duration.zero ? Duration.zero : shifted; + } + + List shiftWords(List words) => [ + for (final word in words) + LyricWord( + time: shift(word.time), + end: word.end == null ? null : shift(word.end!), + text: word.text, + ), + ]; + + return List.unmodifiable([ + for (final line in lines) + LyricLine( + time: shift(line.time), + end: line.end == null ? null : shift(line.end!), + text: line.text, + words: shiftWords(line.words), + romanization: line.romanization, + romanizationWords: shiftWords(line.romanizationWords), + translation: line.translation, + voice: line.voice, + isBackground: line.isBackground, + vocalGroup: line.vocalGroup, + ), + ]); +} diff --git a/lib/widgets/desktop/desktop_mini_player.dart b/lib/widgets/desktop/desktop_mini_player.dart index b7b6c91df..a6790336e 100644 --- a/lib/widgets/desktop/desktop_mini_player.dart +++ b/lib/widgets/desktop/desktop_mini_player.dart @@ -291,6 +291,21 @@ class _MiniPlayerLyricsState extends ConsumerState<_MiniPlayerLyrics> PlayerMetadataController get metadata => widget.metadata; + List? _shiftedSource; + int _shiftedOffsetMs = 0; + List _shifted = const []; + + /// [lines] with the lyrics timing setting applied, kept while neither + /// changes so word-timed lines keep their sweep across rebuilds. + List _withOffset(List lines, int offsetMs) { + if (!identical(lines, _shiftedSource) || offsetMs != _shiftedOffsetMs) { + _shiftedSource = lines; + _shiftedOffsetMs = offsetMs; + _shifted = lyricsShiftedBy(lines, Duration(milliseconds: offsetMs)); + } + return _shifted; + } + @override void initState() { super.initState(); @@ -381,7 +396,10 @@ class _MiniPlayerLyricsState extends ConsumerState<_MiniPlayerLyrics> } return Consumer( builder: (context, ref, _) { - final lines = lyrics.lines; + final lines = _withOffset( + lyrics.lines, + ref.watch(themeProvider.select((theme) => theme.lyricsOffsetMs)), + ); final current = _followPlayback(ref, lines); final next = _leadLineAfter(lines, current); return Padding( diff --git a/lib/widgets/desktop/desktop_player_bar.dart b/lib/widgets/desktop/desktop_player_bar.dart index cf7d329da..8380288f1 100644 --- a/lib/widgets/desktop/desktop_player_bar.dart +++ b/lib/widgets/desktop/desktop_player_bar.dart @@ -8,10 +8,12 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:mornye/controllers/player_metadata_controller.dart'; import 'package:mornye/l10n/l10n.dart'; import 'package:mornye/providers/music_player_provider.dart'; +import 'package:mornye/providers/theme_provider.dart'; import 'package:mornye/theme/app_tokens.dart'; import 'package:mornye/theme/mornye_theme.dart'; import 'package:mornye/theme/player_artwork_theme.dart'; import 'package:mornye/utils/lyrics_parser.dart'; +import 'package:mornye/utils/lyrics_timeline.dart'; import 'package:mornye/utils/string_utils.dart'; import 'package:mornye/widgets/app_icon.dart'; import 'package:mornye/widgets/app_icon_button.dart'; diff --git a/lib/widgets/lyrics_size_setting.dart b/lib/widgets/lyrics_size_setting.dart index 03c404c0a..41858b3e1 100644 --- a/lib/widgets/lyrics_size_setting.dart +++ b/lib/widgets/lyrics_size_setting.dart @@ -3,6 +3,7 @@ import 'dart:ui' show ImageFilter; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:mornye/l10n/l10n.dart'; +import 'package:mornye/models/theme_settings.dart'; import 'package:mornye/providers/theme_provider.dart'; import 'package:mornye/theme/mornye_theme.dart'; import 'package:mornye/widgets/app_icon_button.dart'; @@ -73,6 +74,80 @@ class LyricsSizeSetting extends ConsumerWidget { } } +/// How much later (or earlier) synced lyrics follow playback, for audio that +/// reaches the listener late, such as over Bluetooth. +class LyricsOffsetSetting extends ConsumerWidget { + const LyricsOffsetSetting({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final offsetMs = ref.watch( + themeProvider.select((theme) => theme.lyricsOffsetMs), + ); + final notifier = ref.read(themeProvider.notifier); + String format(double value) { + final ms = value.round(); + if (ms == 0) return context.l10n.lyricsOffsetNone; + final seconds = (ms.abs() / 1000).toStringAsFixed(1); + return ms > 0 + ? context.l10n.lyricsOffsetLater(seconds) + : context.l10n.lyricsOffsetEarlier(seconds); + } + + final value = format(offsetMs.toDouble()); + final reset = AppIconButton( + tooltip: context.l10n.libraryFilterReset, + onPressed: offsetMs == 0 ? null : () => notifier.setLyricsOffsetMs(0), + icon: const Icon(Icons.restart_alt), + ); + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (context.isMornye) + Row( + children: [ + Expanded( + child: Text( + context.l10n.lyricsOffset, + style: Theme.of(context).textTheme.titleMedium, + ), + ), + Text(value), + reset, + ], + ) + else + SliderValueHeader( + title: context.l10n.lyricsOffset, + value: value, + trailing: reset, + ), + Text( + context.l10n.lyricsOffsetSubtitle, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + AppSlider( + value: offsetMs.toDouble(), + min: -kMaxLyricsOffsetMs.toDouble(), + max: kMaxLyricsOffsetMs.toDouble(), + divisions: kMaxLyricsOffsetMs * 2 ~/ 100, + label: value, + semanticLabel: context.l10n.lyricsOffset, + semanticFormatterCallback: format, + onChanged: (value) => + notifier.setLyricsOffsetMs(value.round(), persist: false), + onChangeEnd: (value) => notifier.setLyricsOffsetMs(value.round()), + ), + ], + ), + ); + } +} + /// How strongly Mornye blurs the lyric lines around the current one. The /// preview's second line blurs as much as the line next to the current one. class LyricsBlurSetting extends ConsumerWidget { diff --git a/lib/widgets/player_lyrics.dart b/lib/widgets/player_lyrics.dart index 96f1f808b..17b3d605b 100644 --- a/lib/widgets/player_lyrics.dart +++ b/lib/widgets/player_lyrics.dart @@ -101,6 +101,10 @@ class _SyncedLyricsViewState extends ConsumerState ProviderSubscription? _positionSubscription; ProviderSubscription? _playingSubscription; ProviderSubscription? _loadingSubscription; + ProviderSubscription? _offsetSubscription; + + /// The listener's lyrics timing setting, already applied to [_lines]. + Duration _offset = Duration.zero; Timer? _lineBoundaryTimer; Timer? _userScrollIdleTimer; late List _lines; @@ -223,6 +227,17 @@ class _SyncedLyricsViewState extends ConsumerState void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); + _offsetSubscription = ref.listenManual( + themeProvider.select((theme) => theme.lyricsOffsetMs), + (previous, next) { + setState(() { + _offset = Duration(milliseconds: next); + _resetLineKeys(); + }); + _syncPositionSubscription(resetUserScroll: false); + }, + ); + _offset = Duration(milliseconds: _offsetSubscription!.read()); _resetLineKeys(); widget.seekPreview.addListener(_previewChanged); } @@ -286,7 +301,9 @@ class _SyncedLyricsViewState extends ConsumerState _hasStarted = false; _lineExtents = null; _lineLayoutKey = null; - _lines = lyricsWithDisplayEnds(lyricsTimelineWithGaps(widget.lyrics.lines)); + _lines = lyricsWithDisplayEnds( + lyricsTimelineWithGaps(lyricsShiftedBy(widget.lyrics.lines, _offset)), + ); _timeline = LyricTimelineIndex(_lines); _rowReveal.stop(); _revealFrom = _revealTo = [ @@ -378,6 +395,13 @@ class _SyncedLyricsViewState extends ConsumerState setState(() => _awaitingFirstScroll = false); } + /// Where a line shown at [shown] is sung in the track, before the lyrics + /// timing setting moved it, for seeking to it and sharing it. + Duration _sungTime(Duration shown) { + final time = shown - _offset; + return time < Duration.zero ? Duration.zero : time; + } + Duration get _displayPosition => widget.seekPreview.value ?? ref.read(playbackStateProvider).value?.position ?? @@ -528,6 +552,7 @@ class _SyncedLyricsViewState extends ConsumerState _positionSubscription?.close(); _playingSubscription?.close(); _loadingSubscription?.close(); + _offsetSubscription?.close(); _lineBoundaryTimer?.cancel(); _userScrollIdleTimer?.cancel(); _measurementTimer?.cancel(); @@ -1189,13 +1214,19 @@ class _SyncedLyricsViewState extends ConsumerState Padding( padding: _linePadding(index), child: TvTapTarget( - onTap: () => - ref.read(musicPlayerControllerProvider).seek(line.time), + onTap: () => ref + .read(musicPlayerControllerProvider) + .seek(_sungTime(line.time)), onLongPress: widget.onLongPressLine == null ? null : () { HapticFeedback.mediumImpact(); - widget.onLongPressLine!(line); + widget.onLongPressLine!( + LyricLine( + time: _sungTime(line.time), + text: line.text, + ), + ); }, child: AnimatedScale( // Focus changes paint scale, never font metrics or diff --git a/test/lyrics_appearance_test.dart b/test/lyrics_appearance_test.dart index d01660927..1c81b2e80 100644 --- a/test/lyrics_appearance_test.dart +++ b/test/lyrics_appearance_test.dart @@ -98,6 +98,102 @@ void main() { expect(loadBootstrapThemeSettings(prefs).lyricsBlur, 1); }); + test('lyrics timing validates stored bounds', () { + expect(normalizeLyricsOffsetMs(null), 0); + expect(normalizeLyricsOffsetMs(double.nan), 0); + expect(normalizeLyricsOffsetMs(250.4), 250); + expect(normalizeLyricsOffsetMs(9000), kMaxLyricsOffsetMs); + expect(normalizeLyricsOffsetMs(-9000), -kMaxLyricsOffsetMs); + final settings = const ThemeSettings().copyWith(lyricsOffsetMs: -300); + expect(ThemeSettings.fromJson(settings.toJson()), settings); + }); + + testWidgets('timing slider previews, persists on release and resets', ( + tester, + ) async { + final container = ProviderContainer(); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const Scaffold(body: LyricsOffsetSetting()), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('In sync'), findsOneWidget); + final slider = tester.widget(find.byType(AppSlider)); + slider.onChanged!(300); + await tester.pump(); + expect(find.text('0.3 s later'), findsOneWidget); + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getInt(kLyricsOffsetKey), isNull); + slider.onChangeEnd!(-500); + await tester.pumpAndSettle(); + expect(find.text('0.5 s earlier'), findsOneWidget); + expect(loadBootstrapThemeSettings(prefs).lyricsOffsetMs, -500); + await tester.tap(find.byTooltip('Reset')); + await tester.pumpAndSettle(); + expect(loadBootstrapThemeSettings(prefs).lyricsOffsetMs, 0); + }); + + testWidgets('lyrics timing decides which line is current', (tester) async { + final preview = ValueNotifier(const Duration(seconds: 3)); + addTearDown(preview.dispose); + final container = ProviderContainer(); + addTearDown(container.dispose); + final theme = MornyeTheme.build(Brightness.dark); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + theme: theme, + home: Scaffold( + body: SyncedLyricsView( + lyrics: const ParsedLyrics( + synced: true, + wordSynced: false, + plainText: '', + lines: [ + LyricLine(time: Duration.zero, text: 'First line'), + LyricLine(time: Duration(seconds: 2), text: 'Second line'), + ], + ), + seekPreview: preview, + colorScheme: theme.colorScheme, + isActive: true, + showPronunciation: false, + showTranslation: false, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + double scaleOf(String text) => tester + .widget( + find + .ancestor( + of: find.text(text), + matching: find.byType(AnimatedScale), + ) + .first, + ) + .scale; + expect(scaleOf('Second line'), 1.0); + + // Two seconds later: at 3 s the second line, now at 4 s, has not begun. + await container.read(themeProvider.notifier).setLyricsOffsetMs(2000); + await tester.pumpAndSettle(); + expect(scaleOf('First line'), 1.0); + expect(scaleOf('Second line'), 0.96); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + for (final strength in [0.0, 0.5, 1.5]) { testWidgets('Mornye lyrics blur nearby lines at strength $strength', ( tester, diff --git a/test/lyrics_timeline_test.dart b/test/lyrics_timeline_test.dart index c22f2f7c4..bc2f4ddd1 100644 --- a/test/lyrics_timeline_test.dart +++ b/test/lyrics_timeline_test.dart @@ -376,4 +376,34 @@ void main() { isEmpty, ); }); + + test('lyrics timing moves lines and words, stopping at the start', () { + const lines = [ + LyricLine( + time: Duration(milliseconds: 200), + end: Duration(seconds: 2), + text: 'First', + words: [ + LyricWord( + time: Duration(milliseconds: 200), + end: Duration(seconds: 1), + text: 'First', + ), + ], + ), + LyricLine(time: Duration(seconds: 3), text: 'Second'), + ]; + expect(identical(lyricsShiftedBy(lines, Duration.zero), lines), isTrue); + + final later = lyricsShiftedBy(lines, const Duration(milliseconds: 300)); + expect(later.map((line) => line.time.inMilliseconds), [500, 3300]); + expect(later.first.end, const Duration(milliseconds: 2300)); + expect(later.first.words.single.time, const Duration(milliseconds: 500)); + expect(later.first.words.single.end, const Duration(milliseconds: 1300)); + + final earlier = lyricsShiftedBy(lines, const Duration(milliseconds: -500)); + expect(earlier.map((line) => line.time.inMilliseconds), [0, 2500]); + expect(earlier.first.words.single.time, Duration.zero); + expect(earlier.map((line) => line.text), ['First', 'Second']); + }); }