mirror of
https://github.com/zarzet/SpotiFLAC-Mobile.git
synced 2026-11-21 20:00:49 +01:00
feat(player): gapless playback
The next song used to load only after the current one ended, which left a short silence between songs. With Gapless playback on (the default), the player loads the next song on a second deck 30 seconds before the end and starts it the moment the current one completes. The decks gain setNextDeck. The Android fork links its players with MediaPlayer.setNextMediaPlayer, so the platform starts the next song itself; the Darwin fork resumes the linked player first thing in its end-of-item handler, prerolled when linked. libmpv decks cannot hand over their output, so on Windows and Linux the loaded deck starts on the completion event. AutoMix replaces gapless playback while on, and repeat one, USB bit-perfect and exclusive output keep the ordinary transition. A queue, shuffle, repeat or settings change, a pause, a stop or Previous drops the prepared song; a seek keeps it. Playback settings gain the switch, which the settings search finds as well.
This commit is contained in:
1 parent
1b5fde3a2e
commit
c2db8ab4b6
26 files changed
+753
-17
No files matched your search
@@ -7821,6 +7821,14 @@
|
||||
"description": "Selected state of the compact favorite action"
|
||||
},
|
||||
"autoMixDescription": "Blend songs with beat matching and pitch-preserving tempo adjustment. Uses crossfade when beats cannot be matched.",
|
||||
"gaplessPlayback": "Gapless playback",
|
||||
"@gaplessPlayback": {
|
||||
"description": "Playback settings switch that starts the next song the moment one ends"
|
||||
},
|
||||
"gaplessPlaybackDescription": "Start the next song the moment one ends, without silence between them. AutoMix replaces it while on.",
|
||||
"@gaplessPlaybackDescription": {
|
||||
"description": "Subtitle of the Gapless playback switch"
|
||||
},
|
||||
"playerCoverStyle": "Cover art",
|
||||
"@playerCoverStyle": {
|
||||
"description": "Settings section choosing how the player shows cover art"
|
||||
|
||||
@@ -60,6 +60,8 @@ class AppSettings {
|
||||
final String playbackNormalizationMode; // 'track' or 'album'
|
||||
final bool pauseOnMute;
|
||||
final bool playOnHeadphonesConnected;
|
||||
// Start the next song the moment one ends; AutoMix replaces it while on.
|
||||
final bool gaplessPlayback;
|
||||
final bool autoMix;
|
||||
@JsonKey(fromJson: autoMixDurationFromJson)
|
||||
final int autoMixDuration;
|
||||
@@ -261,6 +263,7 @@ class AppSettings {
|
||||
this.playbackNormalizationMode = 'track',
|
||||
this.pauseOnMute = true,
|
||||
this.playOnHeadphonesConnected = false,
|
||||
this.gaplessPlayback = true,
|
||||
this.autoMix = false,
|
||||
this.autoMixDuration = 0,
|
||||
this.autoMixEffect = AutoMixEffect.auto,
|
||||
@@ -405,6 +408,7 @@ class AppSettings {
|
||||
String? playbackNormalizationMode,
|
||||
bool? pauseOnMute,
|
||||
bool? playOnHeadphonesConnected,
|
||||
bool? gaplessPlayback,
|
||||
bool? autoMix,
|
||||
int? autoMixDuration,
|
||||
AutoMixEffect? autoMixEffect,
|
||||
@@ -534,6 +538,7 @@ class AppSettings {
|
||||
pauseOnMute: pauseOnMute ?? this.pauseOnMute,
|
||||
playOnHeadphonesConnected:
|
||||
playOnHeadphonesConnected ?? this.playOnHeadphonesConnected,
|
||||
gaplessPlayback: gaplessPlayback ?? this.gaplessPlayback,
|
||||
autoMix: autoMix ?? this.autoMix,
|
||||
autoMixDuration: autoMixDuration ?? this.autoMixDuration,
|
||||
autoMixEffect: autoMixEffect ?? this.autoMixEffect,
|
||||
|
||||
@@ -40,6 +40,7 @@ AppSettings _$AppSettingsFromJson(Map<String, dynamic> json) => AppSettings(
|
||||
pauseOnMute: json['pauseOnMute'] as bool? ?? true,
|
||||
playOnHeadphonesConnected:
|
||||
json['playOnHeadphonesConnected'] as bool? ?? false,
|
||||
gaplessPlayback: json['gaplessPlayback'] as bool? ?? true,
|
||||
autoMix: json['autoMix'] as bool? ?? false,
|
||||
autoMixDuration: json['autoMixDuration'] == null
|
||||
? 0
|
||||
@@ -203,6 +204,7 @@ Map<String, dynamic> _$AppSettingsToJson(
|
||||
'playbackNormalizationMode': instance.playbackNormalizationMode,
|
||||
'pauseOnMute': instance.pauseOnMute,
|
||||
'playOnHeadphonesConnected': instance.playOnHeadphonesConnected,
|
||||
'gaplessPlayback': instance.gaplessPlayback,
|
||||
'autoMix': instance.autoMix,
|
||||
'autoMixDuration': instance.autoMixDuration,
|
||||
'autoMixEffect': _$AutoMixEffectEnumMap[instance.autoMixEffect]!,
|
||||
|
||||
@@ -626,6 +626,9 @@ class SettingsNotifier extends Notifier<AppSettings> {
|
||||
void setPlayOnHeadphonesConnected(bool enabled) =>
|
||||
_commit(state.copyWith(playOnHeadphonesConnected: enabled));
|
||||
|
||||
void setGaplessPlayback(bool enabled) =>
|
||||
_commit(state.copyWith(gaplessPlayback: enabled));
|
||||
|
||||
void setAutoMix(bool enabled) => _commit(state.copyWith(autoMix: enabled));
|
||||
|
||||
void setAutoMixDuration(int seconds) => _commit(
|
||||
|
||||
@@ -221,6 +221,20 @@ class _PlaybackSettingsPageState extends ConsumerState<PlaybackSettingsPage> {
|
||||
enabled: settings.playerMode == 'internal',
|
||||
),
|
||||
],
|
||||
SettingsSwitchItem(
|
||||
icon: Icons.linear_scale,
|
||||
title: context.l10n.gaplessPlayback,
|
||||
subtitle: context.l10n.gaplessPlaybackDescription,
|
||||
value: settings.gaplessPlayback && !settings.autoMix,
|
||||
enabled:
|
||||
settings.playerMode == 'internal' &&
|
||||
!settings.autoMix &&
|
||||
!settings.usbBitPerfect &&
|
||||
!(isDesktopPlatform && settings.exclusiveOutput),
|
||||
onChanged: (value) => ref
|
||||
.read(settingsProvider.notifier)
|
||||
.setGaplessPlayback(value),
|
||||
),
|
||||
SettingsSwitchItem(
|
||||
icon: Icons.compare_arrows,
|
||||
title: 'AutoMix',
|
||||
|
||||
@@ -205,6 +205,9 @@ class ExclusiveOutputDeck implements PlaybackDeck {
|
||||
@override
|
||||
Future<void> stop() => _active.stop();
|
||||
@override
|
||||
Future<bool> setNextDeck(PlaybackDeck? next) =>
|
||||
_active.setNextDeck(next is ExclusiveOutputDeck ? next._active : next);
|
||||
@override
|
||||
Future<Duration?> getCurrentPosition() => _active.getCurrentPosition();
|
||||
@override
|
||||
Future<Duration?> getDuration() => _active.getDuration();
|
||||
|
||||
@@ -543,6 +543,11 @@ class MediaKitPlaybackDeck implements PlaybackDeck {
|
||||
_setState(PlaybackDeckState.stopped);
|
||||
}
|
||||
|
||||
/// Each deck owns its own libmpv instance, which cannot hand its output to
|
||||
/// another; the next deck starts on the completion event instead.
|
||||
@override
|
||||
Future<bool> setNextDeck(PlaybackDeck? next) async => false;
|
||||
|
||||
@override
|
||||
Future<Duration?> getCurrentPosition() async {
|
||||
// Asked directly: media_kit's cached position trails a pause or seek.
|
||||
|
||||
@@ -111,6 +111,10 @@ class AudioplayersPlaybackDeck implements PlaybackDeck {
|
||||
(Platform.isAndroid ||
|
||||
Platform.isIOS ||
|
||||
(isDesktopPlatform && Platform.isMacOS)),
|
||||
_platformChainsPlayers =
|
||||
Platform.isAndroid ||
|
||||
Platform.isIOS ||
|
||||
(isDesktopPlatform && Platform.isMacOS),
|
||||
_nativeAvailable = nativeAvailable ?? Platform.isAndroid {
|
||||
playbackEqualizer.addListener(_equalizerChanged);
|
||||
playbackOutputVolume.addListener(_outputVolumeChanged);
|
||||
@@ -139,12 +143,18 @@ class AudioplayersPlaybackDeck implements PlaybackDeck {
|
||||
]);
|
||||
}
|
||||
|
||||
/// Forces [setNextDeck] support, for tests on any host.
|
||||
@visibleForTesting
|
||||
static bool? debugChainsPlayers;
|
||||
|
||||
static const _channel = MethodChannel('com.zarz.mornye/usb_pcm');
|
||||
static const _events = EventChannel('com.zarz.mornye/usb_pcm/events');
|
||||
static Stream<dynamic>? _nativeEvents;
|
||||
static int _nextToken = 0;
|
||||
final AudioPlayer _ordinary;
|
||||
final bool _equalizerAvailable;
|
||||
final bool _platformChainsPlayers;
|
||||
bool get _chainsPlayers => debugChainsPlayers ?? _platformChainsPlayers;
|
||||
bool _equalizerDisposed = false;
|
||||
static const _effects = MethodChannel('xyz.luan/audioplayers');
|
||||
bool _equalizerSent = false;
|
||||
@@ -550,6 +560,29 @@ class AudioplayersPlaybackDeck implements PlaybackDeck {
|
||||
if (!_disposed && token == _token && _direct) _positions.add(position);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> setNextDeck(PlaybackDeck? next) async {
|
||||
// The forks chain their own players: Android with
|
||||
// MediaPlayer.setNextMediaPlayer, Darwin from the end notification.
|
||||
if (_direct || !_chainsPlayers) return false;
|
||||
final player = next is AudioplayersPlaybackDeck && !next._direct
|
||||
? next._ordinary
|
||||
: null;
|
||||
if (next != null && player == null) return false;
|
||||
try {
|
||||
await _effects.invokeMethod<void>('setNextPlayer', {
|
||||
'playerId': _ordinary.playerId,
|
||||
'nextPlayerId': ?player?.playerId,
|
||||
});
|
||||
return player != null;
|
||||
} on PlatformException catch (error) {
|
||||
_log.w('Next player link unavailable: $error');
|
||||
return false;
|
||||
} on MissingPluginException {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Duration?> getCurrentPosition() async {
|
||||
if (!_direct) return _ordinary.getCurrentPosition();
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
part of 'music_player_service.dart';
|
||||
|
||||
/// Gapless playback: loads the next song on a second deck shortly before the
|
||||
/// current one ends and starts it the moment the current one completes,
|
||||
/// chained natively where the engine can (see [PlaybackDeck.setNextDeck]).
|
||||
/// AutoMix replaces it while on. Repeat one, USB output and exclusive output
|
||||
/// keep the ordinary transition, which loads the next song after the end.
|
||||
class _MusicGapless {
|
||||
_MusicGapless(this.handler);
|
||||
|
||||
/// How long before the end the next song loads.
|
||||
static const lead = Duration(seconds: 30);
|
||||
|
||||
final MusicPlayerHandler handler;
|
||||
final _pins = <String>{};
|
||||
PlaybackDeck? _prepared;
|
||||
PlayableMedia? _next;
|
||||
String? _nextPath;
|
||||
String? _nextArtwork;
|
||||
Duration? _nextDuration;
|
||||
double _nextVolume = 1;
|
||||
bool _nextIsCopy = false;
|
||||
int _nextIndex = -1;
|
||||
int _queueRevision = -1;
|
||||
int _playGeneration = -1;
|
||||
int _generation = 0;
|
||||
String? _attempt;
|
||||
bool _preparing = false;
|
||||
|
||||
Set<String> get pinnedPaths => _pins;
|
||||
|
||||
bool get _enabled {
|
||||
final settings = handler._settings;
|
||||
return settings.gaplessPlayback &&
|
||||
!settings.autoMix &&
|
||||
!settings.usbBitPerfect &&
|
||||
// A second deck cannot open a device held in exclusive mode.
|
||||
!playbackExclusiveOutput.value &&
|
||||
!handler._player.isDirect &&
|
||||
!handler._disposed &&
|
||||
handler._sourceReady &&
|
||||
handler._repeatMode != AudioServiceRepeatMode.one;
|
||||
}
|
||||
|
||||
bool _current(int generation) =>
|
||||
generation == _generation &&
|
||||
_enabled &&
|
||||
_playGeneration == handler._playRequestGeneration &&
|
||||
_queueRevision == handler._sessionQueueRevision;
|
||||
|
||||
void onPosition(Duration position) {
|
||||
if (_preparing) return;
|
||||
if (_prepared != null) {
|
||||
if (!_current(_generation)) unawaited(cancel());
|
||||
return;
|
||||
}
|
||||
if (!_enabled) return;
|
||||
final duration = handler.mediaItem.value?.duration;
|
||||
if (duration == null ||
|
||||
duration <= Duration.zero ||
|
||||
duration - position > lead) {
|
||||
return;
|
||||
}
|
||||
final key =
|
||||
'${handler._playRequestGeneration}:${handler._sessionQueueRevision}';
|
||||
if (_attempt == key) return;
|
||||
_attempt = key;
|
||||
unawaited(_prepare());
|
||||
}
|
||||
|
||||
Future<void> _prepare() async {
|
||||
_preparing = true;
|
||||
final generation = ++_generation;
|
||||
_playGeneration = handler._playRequestGeneration;
|
||||
_queueRevision = handler._sessionQueueRevision;
|
||||
final index = handler._index;
|
||||
final nextIndex = index + 1 < handler._media.length
|
||||
? index + 1
|
||||
: handler._repeatMode == AudioServiceRepeatMode.all
|
||||
? handler._repeatPassStart()
|
||||
: -1;
|
||||
PlaybackDeck? deck;
|
||||
ContentUriPlaybackLease? lease;
|
||||
try {
|
||||
if (index < 0 || nextIndex < 0 || nextIndex == index) return;
|
||||
final next = handler._media[nextIndex];
|
||||
// DSD needs the USB output, which the ordinary transition opens.
|
||||
if (MusicPlayerHandler._requiresDsd(next)) return;
|
||||
if (handler._dependencies.isAndroid && next.isContentUri) {
|
||||
try {
|
||||
lease = await PlatformBridge.openContentUriPlaybackLease(next.source);
|
||||
} catch (error) {
|
||||
_log.w('Gapless SAF lease unavailable: $error');
|
||||
}
|
||||
if (!_current(generation)) return;
|
||||
}
|
||||
final path = lease?.path ?? await handler._resolveSource(next);
|
||||
if (path == null || !_current(generation)) return;
|
||||
final isCopy = next.isContentUri && lease == null;
|
||||
if (isCopy) _pins.add(path);
|
||||
String? artwork;
|
||||
if (next.networkArtworkSource case final source?) {
|
||||
try {
|
||||
artwork = await handler._dependencies.resolveNetworkSource(source);
|
||||
} catch (_) {
|
||||
// Cover failure must not prevent audio playback.
|
||||
}
|
||||
if (!_current(generation)) return;
|
||||
}
|
||||
final volume = await handler._normalizationVolumeFor(
|
||||
path,
|
||||
cacheKey: next.isContentUri ? next.source : null,
|
||||
displayName: lease?.displayName,
|
||||
);
|
||||
if (!_current(generation)) return;
|
||||
deck = handler._dependencies.createDeck(
|
||||
'music-gapless-$generation-${DateTime.now().microsecondsSinceEpoch}',
|
||||
);
|
||||
handler._listenToPlayer(deck);
|
||||
await deck.configureOutput();
|
||||
await deck.setVolume(volume);
|
||||
if (!_current(generation)) return;
|
||||
if (next.isNetwork ||
|
||||
const {'http', 'https'}.contains(Uri.tryParse(path)?.scheme)) {
|
||||
await deck.setNetworkSource(
|
||||
path,
|
||||
arriving: handler._runtime.streamsArrivingFile(path),
|
||||
);
|
||||
} else {
|
||||
await deck.setFileSource(path);
|
||||
}
|
||||
if (!_current(generation)) return;
|
||||
final duration = await deck.getDuration();
|
||||
if (!_current(generation)) return;
|
||||
final chained = await handler._player.setNextDeck(deck);
|
||||
if (!_current(generation)) {
|
||||
if (chained) await handler._player.setNextDeck(null);
|
||||
return;
|
||||
}
|
||||
_prepared = deck;
|
||||
deck = null;
|
||||
_next = next;
|
||||
_nextIndex = nextIndex;
|
||||
_nextPath = path;
|
||||
_nextArtwork = artwork;
|
||||
_nextDuration = duration != null && duration > Duration.zero
|
||||
? duration
|
||||
: next.duration;
|
||||
_nextVolume = volume;
|
||||
_nextIsCopy = isCopy;
|
||||
_log.d('Gapless prepared (${chained ? 'native' : 'on completion'})');
|
||||
} catch (error) {
|
||||
_log.w('Gapless preparation skipped: $error');
|
||||
} finally {
|
||||
if (lease != null) {
|
||||
await PlatformBridge.closeContentUriPlaybackLease(lease.token);
|
||||
}
|
||||
if (deck != null) await handler._disposeDeck(deck);
|
||||
if (generation == _generation) {
|
||||
_preparing = false;
|
||||
if (_prepared == null) _pins.clear();
|
||||
}
|
||||
await handler._cleanupPendingResolvedPaths();
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the prepared song current as the current one completes. False
|
||||
/// leaves the ordinary transition to the caller.
|
||||
Future<bool> handoff() async {
|
||||
final incoming = _prepared;
|
||||
final next = _next;
|
||||
if (incoming == null || next == null) return false;
|
||||
if (!_current(_generation) ||
|
||||
_nextIndex >= handler._media.length ||
|
||||
!identical(handler._media[_nextIndex], next)) {
|
||||
await cancel();
|
||||
return false;
|
||||
}
|
||||
final generation = _generation;
|
||||
final playGeneration = handler._playRequestGeneration;
|
||||
try {
|
||||
// A natively chained deck already plays; this confirms its state.
|
||||
await incoming.resume();
|
||||
} catch (error) {
|
||||
_log.w('Gapless start failed: $error');
|
||||
if (generation == _generation) await cancel();
|
||||
return playGeneration != handler._playRequestGeneration;
|
||||
}
|
||||
// Another request (Next, a new queue) took over meanwhile.
|
||||
if (generation != _generation) {
|
||||
return playGeneration != handler._playRequestGeneration;
|
||||
}
|
||||
final outgoing = handler._player;
|
||||
final path = _nextPath;
|
||||
_prepared = null;
|
||||
_next = null;
|
||||
_pins.clear();
|
||||
handler._player = incoming;
|
||||
// An index at or before the current one wraps to a new repeat-all pass.
|
||||
final index = _nextIndex > handler._index
|
||||
? _nextIndex
|
||||
: handler._beginRepeatPass(_nextIndex);
|
||||
handler._index = index;
|
||||
final current = ++handler._playRequestGeneration;
|
||||
handler._serverDiedReloads = 0;
|
||||
handler._playbackAutomation.cancelPendingActions();
|
||||
handler._recordPlayHistory(index);
|
||||
handler._normalizationVolume = _nextVolume;
|
||||
handler._activeResolvedPath = _nextIsCopy ? path : null;
|
||||
handler._pendingRestorePosition = null;
|
||||
handler._runtime.personalization.begin(_learningTrack(next));
|
||||
handler.mediaItem.add(
|
||||
handler
|
||||
._toMediaItem(
|
||||
next,
|
||||
resolvedSource: _nextIsCopy ? path : null,
|
||||
resolvedArtwork: _nextArtwork,
|
||||
)
|
||||
.copyWith(duration: _nextDuration),
|
||||
);
|
||||
handler._lastBroadcastPosition = Duration.zero;
|
||||
handler._lastPositionBroadcastAt = null;
|
||||
handler._broadcastPosition(Duration.zero, force: true);
|
||||
handler._broadcastState(playerState: PlaybackDeckState.playing);
|
||||
handler._lastPeriodicPersistAt = DateTime.now();
|
||||
unawaited(handler._persistSession(position: Duration.zero));
|
||||
if (!next.isNetwork) {
|
||||
unawaited(handler._recoverEmbeddedArtwork(next, current));
|
||||
}
|
||||
if (next.source.startsWith('network://')) {
|
||||
unawaited(handler._loadNetworkMetadata(next, current));
|
||||
}
|
||||
unawaited(handler._ensureDurationKnown(next, current));
|
||||
unawaited(handler._autoplay.fill());
|
||||
_log.d('Gapless transition');
|
||||
await handler._disposeDeck(outgoing);
|
||||
await handler._cleanupPendingResolvedPaths();
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> cancel() async {
|
||||
_generation++;
|
||||
_preparing = false;
|
||||
_attempt = null;
|
||||
final prepared = _prepared;
|
||||
_prepared = null;
|
||||
_next = null;
|
||||
_nextPath = null;
|
||||
_nextArtwork = null;
|
||||
_pins.clear();
|
||||
if (prepared == null) return;
|
||||
try {
|
||||
await handler._player.setNextDeck(null);
|
||||
} catch (error) {
|
||||
_log.w('Gapless unlink failed: $error');
|
||||
}
|
||||
await handler._disposeDeck(prepared);
|
||||
await handler._cleanupPendingResolvedPaths();
|
||||
}
|
||||
|
||||
Future<void> dispose() => cancel();
|
||||
}
|
||||
@@ -49,6 +49,7 @@ export 'playback_session_restore.dart';
|
||||
|
||||
part 'music_player_automix.dart';
|
||||
part 'music_player_autoplay.dart';
|
||||
part 'music_player_gapless.dart';
|
||||
|
||||
final _log = AppLogger('MusicPlayer');
|
||||
|
||||
@@ -116,6 +117,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
AppSettings get _settings => _runtime.settings;
|
||||
late PlaybackDeck _player;
|
||||
late final _MusicAutoMix _autoMix;
|
||||
late final _MusicGapless _gapless = _MusicGapless(this);
|
||||
late final _MusicAutoplay _autoplay;
|
||||
late final MusicHaptics _haptics;
|
||||
bool _completing = false;
|
||||
@@ -198,6 +200,12 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
previous.exclusiveOutput != settings.exclusiveOutput) {
|
||||
unawaited(_autoMix.cancel());
|
||||
}
|
||||
if (previous.gaplessPlayback != settings.gaplessPlayback ||
|
||||
previous.autoMix != settings.autoMix ||
|
||||
previous.usbBitPerfect != settings.usbBitPerfect ||
|
||||
previous.exclusiveOutput != settings.exclusiveOutput) {
|
||||
unawaited(_gapless.cancel());
|
||||
}
|
||||
// USB changes apply at the next source boundary, without raising volume.
|
||||
if ((previous.playerMode == 'internal') !=
|
||||
(settings.playerMode == 'internal') ||
|
||||
@@ -239,7 +247,9 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
copy: PlatformBridge.copyContentUriToTemp,
|
||||
isDisposed: () => _disposed,
|
||||
isPinned: (path) =>
|
||||
path == _activeResolvedPath || _autoMix.pinnedPaths.contains(path),
|
||||
path == _activeResolvedPath ||
|
||||
_autoMix.pinnedPaths.contains(path) ||
|
||||
_gapless.pinnedPaths.contains(path),
|
||||
onResolveError: (error) =>
|
||||
_log.e('Failed to resolve content URI for playback: $error'),
|
||||
onDeleteError: (error) =>
|
||||
@@ -518,7 +528,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
unawaited(
|
||||
_serializeSourceChange(() async {
|
||||
if (_disposed || generation != _playRequestGeneration) return;
|
||||
await _autoMix.cancel();
|
||||
await _cancelTransitions();
|
||||
if (_disposed || generation != _playRequestGeneration) return;
|
||||
await player.stop();
|
||||
}).catchError((Object error) {
|
||||
@@ -555,6 +565,12 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Drops a prepared AutoMix or gapless transition.
|
||||
Future<void> _cancelTransitions() async {
|
||||
await _autoMix.cancel();
|
||||
await _gapless.cancel();
|
||||
}
|
||||
|
||||
Future<void> _disposeDeck(PlaybackDeck player) async {
|
||||
final subscriptions = _playerSubscriptions.remove(player);
|
||||
if (subscriptions == null) return;
|
||||
@@ -907,6 +923,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
if (!_sourceReady || _switchingGeneration != 0) return;
|
||||
_broadcastPosition(position);
|
||||
_autoMix.onPosition(position);
|
||||
_gapless.onPosition(position);
|
||||
unawaited(_autoplay.fill());
|
||||
if (_restoringSession ||
|
||||
_player.state != PlaybackDeckState.playing ||
|
||||
@@ -980,7 +997,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
final normalizationGeneration = ++_normalizationGeneration;
|
||||
if (index < 0 || index >= _media.length) return;
|
||||
unawaited(() async {
|
||||
await _autoMix.cancel();
|
||||
await _cancelTransitions();
|
||||
if (generation != _playRequestGeneration ||
|
||||
index != _index ||
|
||||
index >= _media.length ||
|
||||
@@ -1396,7 +1413,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
..clear()
|
||||
..addAll(history);
|
||||
_markSessionQueueChanged();
|
||||
unawaited(_autoMix.cancel());
|
||||
unawaited(_cancelTransitions());
|
||||
queue.add(List<MediaItem>.unmodifiable(_queueItems));
|
||||
_broadcastState();
|
||||
unawaited(_persistSession(position: playbackState.value.position));
|
||||
@@ -1439,7 +1456,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
await _serializeSourceChange(() async {
|
||||
try {
|
||||
if (!_isCurrentPlayRequest(generation, media)) return;
|
||||
await _autoMix.cancel();
|
||||
await _cancelTransitions();
|
||||
if (!_isCurrentPlayRequest(generation, media)) return;
|
||||
// Retire the audible source before publishing another song's title.
|
||||
await _player.stop();
|
||||
@@ -1463,6 +1480,12 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
return operation;
|
||||
}
|
||||
|
||||
static bool _requiresDsd(PlayableMedia media) =>
|
||||
media.bitDepth == 1 ||
|
||||
const ['dsf', 'dff'].contains(media.format?.toLowerCase()) ||
|
||||
media.source.toLowerCase().endsWith('.dsf') ||
|
||||
media.source.toLowerCase().endsWith('.dff');
|
||||
|
||||
Future<void> _startResolvedSource(
|
||||
String path,
|
||||
int generation,
|
||||
@@ -1487,11 +1510,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
allowFixedVolume: _settings.usbAllowFixedVolume,
|
||||
dapExclusive: _settings.dapExclusive,
|
||||
allowDop: _settings.usbDsdOverPcm,
|
||||
requiresDsd:
|
||||
media.bitDepth == 1 ||
|
||||
const ['dsf', 'dff'].contains(media.format?.toLowerCase()) ||
|
||||
media.source.toLowerCase().endsWith('.dsf') ||
|
||||
media.source.toLowerCase().endsWith('.dff'),
|
||||
requiresDsd: _requiresDsd(media),
|
||||
);
|
||||
}
|
||||
if (!_isCurrentPlayRequest(generation, media)) return;
|
||||
@@ -1839,6 +1858,8 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
Future<void> _handlePlayerComplete() async {
|
||||
if (_completing) return;
|
||||
if (_shouldIgnoreComplete) {
|
||||
// A natively chained next song must not keep playing unseen.
|
||||
unawaited(_gapless.cancel());
|
||||
if (_userPaused || _interruptionActive) {
|
||||
_broadcastState(playerState: PlaybackDeckState.paused);
|
||||
}
|
||||
@@ -1848,6 +1869,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
_completing = true;
|
||||
try {
|
||||
_runtime.personalization.finish();
|
||||
if (await _gapless.handoff()) return;
|
||||
await _onComplete();
|
||||
} finally {
|
||||
_completing = false;
|
||||
@@ -1973,7 +1995,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
_switchingGeneration = 0;
|
||||
_userPaused = true;
|
||||
await _player.cancelPreparation();
|
||||
await _autoMix.cancel();
|
||||
await _cancelTransitions();
|
||||
await _serializeSourceChange(() async {
|
||||
if (generation != _playRequestGeneration || _disposed) return;
|
||||
await _player.pause();
|
||||
@@ -1999,7 +2021,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) async {
|
||||
final generation = ++_shuffleRequestGeneration;
|
||||
final enabled = shuffleMode == AudioServiceShuffleMode.all;
|
||||
await _autoMix.cancel();
|
||||
await _cancelTransitions();
|
||||
if (generation != _shuffleRequestGeneration ||
|
||||
_disposed ||
|
||||
enabled == _shuffle) {
|
||||
@@ -2023,7 +2045,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
|
||||
@override
|
||||
Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode) async {
|
||||
await _autoMix.cancel();
|
||||
await _cancelTransitions();
|
||||
// Group repeat has no meaning for a flat queue; treat it as all.
|
||||
_repeatMode = repeatMode == AudioServiceRepeatMode.group
|
||||
? AudioServiceRepeatMode.all
|
||||
@@ -2048,7 +2070,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
_switchingGeneration = 0;
|
||||
_userPaused = true;
|
||||
await _player.cancelPreparation();
|
||||
await _autoMix.cancel();
|
||||
await _cancelTransitions();
|
||||
await _serializeSourceChange(() => _stopSession(generation));
|
||||
}
|
||||
|
||||
@@ -2090,7 +2112,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
|
||||
@override
|
||||
Future<void> skipToPrevious() async {
|
||||
await _autoMix.cancel();
|
||||
await _cancelTransitions();
|
||||
if (playbackState.value.position > const Duration(seconds: 3)) {
|
||||
await _player.seek(Duration.zero);
|
||||
_broadcastPosition(Duration.zero, force: true);
|
||||
@@ -2272,6 +2294,7 @@ class MusicPlayerHandler extends BaseAudioHandler
|
||||
await _player.cancelPreparation();
|
||||
await _sourceChangeTail;
|
||||
await _autoMix.dispose();
|
||||
await _gapless.dispose();
|
||||
_haptics.dispose();
|
||||
for (final sub in _subscriptions) {
|
||||
await sub.cancel();
|
||||
|
||||
@@ -135,6 +135,13 @@ abstract interface class PlaybackDeck {
|
||||
Future<void> seek(Duration position);
|
||||
Future<void> stop();
|
||||
|
||||
/// Has the engine start [next], a paused deck holding a loaded source, the
|
||||
/// moment this deck's source ends, so the two songs join without a gap.
|
||||
/// [resume] on [next] afterwards only confirms the state. Returns false
|
||||
/// when the engine cannot chain these decks; [next] then waits for
|
||||
/// [resume]. Null unlinks a deck set earlier.
|
||||
Future<bool> setNextDeck(PlaybackDeck? next);
|
||||
|
||||
Future<Duration?> getCurrentPosition();
|
||||
Future<Duration?> getDuration();
|
||||
|
||||
|
||||
@@ -339,6 +339,12 @@ class SettingsSearchCatalog {
|
||||
subtitle: l10n.playbackOnHeadphonesConnectedDescription,
|
||||
keywords: const ['earphone', 'headphone', 'bluetooth', 'connect'],
|
||||
),
|
||||
SettingsSearchEntry(
|
||||
icon: Icons.linear_scale,
|
||||
title: l10n.gaplessPlayback,
|
||||
subtitle: l10n.gaplessPlaybackDescription,
|
||||
keywords: const ['gapless', 'gap', 'silence', 'transition', 'album'],
|
||||
),
|
||||
SettingsSearchEntry(
|
||||
icon: Icons.compare_arrows,
|
||||
title: 'AutoMix',
|
||||
|
||||
@@ -76,6 +76,8 @@ class _Deck implements PlaybackDeck {
|
||||
state = PlaybackDeckState.stopped;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> setNextDeck(PlaybackDeck? next) async => false;
|
||||
@override
|
||||
Future<Duration?> getCurrentPosition() async => position;
|
||||
@override
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mornye/models/settings.dart';
|
||||
import 'package:mornye/services/music_playback_deck.dart';
|
||||
|
||||
import 'support/music_player_automix_harness.dart';
|
||||
|
||||
const _tracks = testTracks;
|
||||
const _until = waitUntil;
|
||||
|
||||
Iterable<String> get _gaplessDecks =>
|
||||
native.live.where((id) => id.startsWith('music-gapless-'));
|
||||
|
||||
/// Plays [_tracks] from 45 of 60 seconds, inside the preparation lead.
|
||||
Future<void> _playNearTheEnd() async {
|
||||
await handler.setQueueAndPlay(_tracks);
|
||||
await _until(() => handler.mediaItem.value?.duration != null);
|
||||
await handler.seek(const Duration(seconds: 45));
|
||||
}
|
||||
|
||||
void main() {
|
||||
setUpMusicPlayerHarness();
|
||||
tearDown(() => AudioplayersPlaybackDeck.debugChainsPlayers = null);
|
||||
|
||||
test('Gapless playback is on by default and persists when turned off', () {
|
||||
expect(const AppSettings().gaplessPlayback, isTrue);
|
||||
expect(AppSettings.fromJson({}).gaplessPlayback, isTrue);
|
||||
final off = const AppSettings().copyWith(gaplessPlayback: false);
|
||||
expect(AppSettings.fromJson(off.toJson()).gaplessPlayback, isFalse);
|
||||
});
|
||||
|
||||
test('the next song loads before the end and starts on completion', () async {
|
||||
setGaplessEnabled(true);
|
||||
await _playNearTheEnd();
|
||||
await _until(() => _gaplessDecks.length == 1);
|
||||
final next = _gaplessDecks.single;
|
||||
await _until(() => native.sources[next] == '/two.flac');
|
||||
expect(native.playing, {'music-player'});
|
||||
|
||||
await native.complete('music-player');
|
||||
await _until(() => handler.mediaItem.value?.id == 'two');
|
||||
expect(native.playing, {next});
|
||||
expect(native.live, {next});
|
||||
// The prepared deck played; nothing loaded the song again.
|
||||
expect(native.calls.where((call) => call.$2 == 'setSourceUrl').length, 2);
|
||||
expect(handler.playbackState.value.playing, isTrue);
|
||||
expect(handler.queue.value.map((item) => item.id), ['one', 'two', 'three']);
|
||||
});
|
||||
|
||||
test('chained players hand over natively', () async {
|
||||
AudioplayersPlaybackDeck.debugChainsPlayers = true;
|
||||
setGaplessEnabled(true);
|
||||
await _playNearTheEnd();
|
||||
await _until(() => native.nextPlayers['music-player'] != null);
|
||||
final next = native.nextPlayers['music-player']!;
|
||||
expect(native.playing, {'music-player'});
|
||||
|
||||
await native.complete('music-player');
|
||||
await _until(() => handler.mediaItem.value?.id == 'two');
|
||||
expect(native.playing, {next});
|
||||
expect(native.live, {next});
|
||||
});
|
||||
|
||||
test('repeat all joins the last song to the first', () async {
|
||||
setGaplessEnabled(true);
|
||||
await handler.setRepeatMode(AudioServiceRepeatMode.all);
|
||||
await handler.setQueueAndPlay(_tracks, initialIndex: 2);
|
||||
await _until(() => handler.mediaItem.value?.duration != null);
|
||||
await handler.seek(const Duration(seconds: 45));
|
||||
await _until(() => _gaplessDecks.length == 1);
|
||||
final next = _gaplessDecks.single;
|
||||
await _until(() => native.sources[next] == '/one.flac');
|
||||
|
||||
await native.complete('music-player');
|
||||
await _until(() => handler.mediaItem.value?.id == 'one');
|
||||
expect(native.playing, {next});
|
||||
});
|
||||
|
||||
test('a queue change drops the prepared song and its link', () async {
|
||||
AudioplayersPlaybackDeck.debugChainsPlayers = true;
|
||||
setGaplessEnabled(true);
|
||||
await _playNearTheEnd();
|
||||
await _until(() => native.nextPlayers['music-player'] != null);
|
||||
final next = native.nextPlayers['music-player']!;
|
||||
|
||||
await handler.setRepeatMode(AudioServiceRepeatMode.one);
|
||||
await _until(() => !native.live.contains(next));
|
||||
expect(native.nextPlayers, isEmpty);
|
||||
|
||||
// Repeat one keeps the ordinary transition.
|
||||
await native.complete('music-player');
|
||||
await _until(
|
||||
() =>
|
||||
native.resumedSources
|
||||
.where((source) => source == '/one.flac')
|
||||
.length ==
|
||||
2,
|
||||
);
|
||||
expect(handler.mediaItem.value?.id, 'one');
|
||||
expect(_gaplessDecks, isEmpty);
|
||||
});
|
||||
|
||||
test('turning gapless off drops the prepared song', () async {
|
||||
setGaplessEnabled(true);
|
||||
await _playNearTheEnd();
|
||||
await _until(() => _gaplessDecks.length == 1);
|
||||
|
||||
setGaplessEnabled(false);
|
||||
await _until(() => _gaplessDecks.isEmpty);
|
||||
await native.complete('music-player');
|
||||
await _until(() => handler.mediaItem.value?.id == 'two');
|
||||
expect(native.sources['music-player'], '/two.flac');
|
||||
});
|
||||
|
||||
test('AutoMix replaces gapless playback', () async {
|
||||
setGaplessEnabled(true);
|
||||
setAutoMixEnabled(true);
|
||||
await _playNearTheEnd();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 600));
|
||||
expect(_gaplessDecks, isEmpty);
|
||||
});
|
||||
|
||||
test('a song far from its end does not load the next one', () async {
|
||||
setGaplessEnabled(true);
|
||||
await handler.setQueueAndPlay(_tracks);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 600));
|
||||
expect(_gaplessDecks, isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -102,5 +102,67 @@ void main() {
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Gapless playback yields to AutoMix ($mornye)', (tester) async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
tester.view.physicalSize = const Size(390, 844);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
initialSettingsProvider.overrideWithValue(const AppSettings()),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
theme: mornye
|
||||
? MornyeTheme.build(Brightness.dark, accent: MornyeAccent.blue)
|
||||
: AppTheme.light(),
|
||||
locale: const Locale('en'),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: const PlaybackSettingsPage(),
|
||||
),
|
||||
),
|
||||
);
|
||||
final gapless = find.text('Gapless playback');
|
||||
await tester.scrollUntilVisible(
|
||||
gapless,
|
||||
200,
|
||||
scrollable: find.byType(Scrollable).first,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
SettingsSwitchItem item() => tester.widget<SettingsSwitchItem>(
|
||||
find.byWidgetPredicate(
|
||||
(widget) =>
|
||||
widget is SettingsSwitchItem &&
|
||||
widget.title == 'Gapless playback',
|
||||
),
|
||||
);
|
||||
expect(item().value, isTrue);
|
||||
await tester.tap(gapless);
|
||||
await tester.pumpAndSettle();
|
||||
expect(container.read(settingsProvider).gaplessPlayback, isFalse);
|
||||
|
||||
container.read(settingsProvider.notifier).setGaplessPlayback(true);
|
||||
container.read(settingsProvider.notifier).setAutoMix(true);
|
||||
await tester.pumpAndSettle();
|
||||
expect(item().enabled, isFalse);
|
||||
expect(item().value, isFalse);
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
final catalog = SettingsSearchCatalog(
|
||||
AppLocalizations.of(tester.element(gapless)),
|
||||
);
|
||||
expect(
|
||||
catalog.playback.any(
|
||||
(entry) => entry.matches(SettingsSearchQuery('gapless')),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -219,6 +219,8 @@ class _PreviewDeck implements PlaybackDeck {
|
||||
@override
|
||||
Future<void> stop() async => calls.add('stop');
|
||||
@override
|
||||
Future<bool> setNextDeck(PlaybackDeck? next) async => false;
|
||||
@override
|
||||
Future<Duration?> getCurrentPosition() async => Duration.zero;
|
||||
@override
|
||||
Future<Duration?> getDuration() async => null;
|
||||
|
||||
@@ -103,8 +103,20 @@ class AudioNative {
|
||||
final rates = <String, double>{};
|
||||
final ignoredSeeks = <String>{};
|
||||
final missingPositions = <String>{};
|
||||
final nextPlayers = <String, String>{};
|
||||
bool emitsDuration = true;
|
||||
|
||||
/// Ends [id]'s song the way the forks do: a chained next player starts
|
||||
/// first, then completion is reported.
|
||||
Future<void> complete(String id) async {
|
||||
final next = nextPlayers.remove(id);
|
||||
if (next != null) {
|
||||
playing.add(next);
|
||||
resumedSources.add(sources[next]!);
|
||||
}
|
||||
await event(id, 'audio.onComplete');
|
||||
}
|
||||
|
||||
int currentPosition(String id) =>
|
||||
(positions[id] ?? 0) +
|
||||
(stalled.contains(id)
|
||||
@@ -159,6 +171,13 @@ class AudioNative {
|
||||
clocks[id]?.reset();
|
||||
}
|
||||
unawaited(event(id, 'audio.onSeekComplete'));
|
||||
case 'setNextPlayer':
|
||||
final next = args['nextPlayerId'] as String?;
|
||||
if (next == null) {
|
||||
nextPlayers.remove(id);
|
||||
} else {
|
||||
nextPlayers[id] = next;
|
||||
}
|
||||
case 'setPlaybackRate':
|
||||
positions[id] = currentPosition(id);
|
||||
clocks[id]?.reset();
|
||||
@@ -182,6 +201,7 @@ class AudioNative {
|
||||
playing.remove(id);
|
||||
clocks[id]?.stop();
|
||||
case 'release':
|
||||
nextPlayers.remove(id);
|
||||
releases[id] = (releases[id] ?? 0) + 1;
|
||||
playing.remove(id);
|
||||
sources.remove(id);
|
||||
@@ -287,6 +307,10 @@ void setAutoMixOptions(AutoMixOptions options) => musicPlayerRuntime.configure(
|
||||
),
|
||||
);
|
||||
|
||||
void setGaplessEnabled(bool enabled) => musicPlayerRuntime.configure(
|
||||
musicPlayerRuntime.settings.copyWith(gaplessPlayback: enabled),
|
||||
);
|
||||
|
||||
void setUsbBitPerfectEnabled(bool enabled) => musicPlayerRuntime.configure(
|
||||
musicPlayerRuntime.settings.copyWith(usbBitPerfect: enabled),
|
||||
);
|
||||
@@ -321,6 +345,8 @@ void _setUpPlayer() {
|
||||
);
|
||||
setAutoMixEnabled(false);
|
||||
setAutoMixOptions(const AutoMixOptions());
|
||||
// Gapless tests opt in; others keep the ordinary transition.
|
||||
setGaplessEnabled(false);
|
||||
setUsbBitPerfectEnabled(false);
|
||||
setAutoplayEnabled(false);
|
||||
native = AudioNative(time.stopwatch)..install();
|
||||
|
||||
@@ -42,6 +42,16 @@ Dart caller is `lib/services/music_playback_deck.dart` in the app.
|
||||
relying on `setPlaybackParams` (or, before API 23, `setRate(1.0)`) to start
|
||||
output.
|
||||
|
||||
### Next player
|
||||
|
||||
A `setNextPlayer` method with an optional `nextPlayerId` links two players
|
||||
for gapless playback. `WrappedPlayer.setNext` requires both to hold a
|
||||
prepared source and calls `MediaPlayer.setNextMediaPlayer`, so the platform
|
||||
starts the next player as the current one completes. `onCompletion` then
|
||||
marks the next player as playing before reporting completion, so a later
|
||||
`resume` from Dart confirms its state without restarting it. A new source
|
||||
or a release drops the link; no `nextPlayerId` unlinks it.
|
||||
|
||||
### Error state
|
||||
|
||||
`WrappedPlayer.onError` now marks the player as not prepared and not playing,
|
||||
|
||||
+3
@@ -28,6 +28,9 @@ bit-perfect paths bypass these effects.
|
||||
|
||||
API reference: https://developer.android.com/reference/android/media/audiofx/DynamicsProcessing
|
||||
|
||||
A `setNextPlayer` method links a prepared player to start the moment another
|
||||
completes, through `MediaPlayer.setNextMediaPlayer`, for gapless playback.
|
||||
|
||||
## Usage
|
||||
|
||||
This package is [endorsed](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin),
|
||||
|
||||
third_party/audioplayers_android/android/src/main/kotlin/xyz/luan/audioplayers/AudioplayersPlugin.kt
Vendored
+5
@@ -139,6 +139,11 @@ class AudioplayersPlugin : FlutterPlugin {
|
||||
player.source = BytesSource(bytes)
|
||||
}
|
||||
|
||||
"setNextPlayer" -> {
|
||||
val nextId = call.argument<String>("nextPlayerId")
|
||||
player.setNext(nextId?.let { getPlayer(it) })
|
||||
}
|
||||
|
||||
"resume" -> player.play()
|
||||
"pause" -> player.pause()
|
||||
"stop" -> player.stop()
|
||||
|
||||
+5
@@ -30,6 +30,11 @@ class MediaPlayerWrapper(
|
||||
}
|
||||
}
|
||||
|
||||
/** MediaPlayer starts [next] the moment this player completes; null unlinks. */
|
||||
fun setNext(next: MediaPlayerWrapper?) {
|
||||
mediaPlayer.setNextMediaPlayer(next?.mediaPlayer)
|
||||
}
|
||||
|
||||
private fun createMediaPlayer(wrappedPlayer: WrappedPlayer): MediaPlayer {
|
||||
val mediaPlayer = MediaPlayer().apply {
|
||||
setOnPreparedListener { wrappedPlayer.onPrepared() }
|
||||
|
||||
+35
@@ -24,14 +24,46 @@ class WrappedPlayer internal constructor(
|
||||
) {
|
||||
private var player: PlayerWrapper? = null
|
||||
|
||||
/** The player MediaPlayer starts the moment this one completes. */
|
||||
private var next: WrappedPlayer? = null
|
||||
|
||||
fun setEqualizer(configuration: Map<String, Any?>) {
|
||||
val output = player as? MediaPlayerWrapper
|
||||
if (output != null) output.setEqualizer(configuration)
|
||||
}
|
||||
|
||||
/**
|
||||
* Chains [player], prepared and paused, to start as this source ends,
|
||||
* without a gap. Null unlinks it.
|
||||
*/
|
||||
fun setNext(player: WrappedPlayer?) {
|
||||
val current = this.player as? MediaPlayerWrapper
|
||||
if (player == null) {
|
||||
next = null
|
||||
if (!released && current != null) current.setNext(null)
|
||||
return
|
||||
}
|
||||
check(!released && prepared && current != null) { "This player has no prepared source" }
|
||||
val following = player.player as? MediaPlayerWrapper
|
||||
check(!player.released && player.prepared && following != null) {
|
||||
"The next player has no prepared source"
|
||||
}
|
||||
current.setNext(following)
|
||||
next = player
|
||||
}
|
||||
|
||||
/** MediaPlayer started this player as the previous one completed. */
|
||||
private fun continueAfterPrevious() {
|
||||
if (released || !prepared || playing) return
|
||||
playing = true
|
||||
requestFocusAndStart()
|
||||
}
|
||||
|
||||
var source: Source? = null
|
||||
set(value) {
|
||||
if (field != value) {
|
||||
// Resetting MediaPlayer drops its link to the next player.
|
||||
next = null
|
||||
if (value != null) {
|
||||
val player = getOrCreatePlayer()
|
||||
player.setSource(value)
|
||||
@@ -304,6 +336,9 @@ class WrappedPlayer internal constructor(
|
||||
}
|
||||
|
||||
fun onCompletion() {
|
||||
val following = next
|
||||
next = null
|
||||
following?.continueAfterPrevious()
|
||||
if (releaseMode != ReleaseMode.LOOP) {
|
||||
stop()
|
||||
}
|
||||
|
||||
+12
-2
@@ -74,6 +74,15 @@ cancelled preparation as a completed method call without a playback error.
|
||||
The `getDuration` branch returns after delivering its duration so the same
|
||||
method call cannot receive the default result a second time.
|
||||
|
||||
### Next player
|
||||
|
||||
A `setNextPlayer` method with an optional `nextPlayerId` sets
|
||||
`WrappedMediaPlayer.next` (weak) for gapless playback. Linking prerolls the
|
||||
next player's loaded item. When the current item ends, the completion
|
||||
handler resumes the next player before anything else, then reports
|
||||
completion. Replacing or releasing the current item clears the link; no
|
||||
`nextPlayerId` unlinks it.
|
||||
|
||||
## Tests
|
||||
|
||||
`tests/EqualizerDSPTests.swift` is a standalone `@main` program for the DSP.
|
||||
@@ -105,8 +114,9 @@ The same sources can be compiled with the iOS simulator SDK and run with
|
||||
`simctl spawn` to check the shared iOS implementation.
|
||||
|
||||
`tests/SourceLifecycleTests.swift` uses a deferred AVPlayer for cancellation and
|
||||
real generated WAV files for successful preparation, failed preparation and
|
||||
stale completion delivery. It does not need an external music fixture:
|
||||
real generated WAV files for successful preparation, failed preparation,
|
||||
stale completion delivery and a linked next player starting on completion.
|
||||
It does not need an external music fixture:
|
||||
|
||||
```bash
|
||||
cd third_party/audioplayers_darwin
|
||||
|
||||
+3
@@ -221,6 +221,9 @@ public class AudioplayersDarwinPlugin: NSObject, FlutterPlugin {
|
||||
result(FlutterError(code: "DarwinAudioError", message: "Equalizer is unavailable for this source", details: error.localizedDescription))
|
||||
return
|
||||
}
|
||||
} else if method == "setNextPlayer" {
|
||||
let nextId = args["nextPlayerId"] as? String
|
||||
player.next = nextId.flatMap { self.getPlayer(playerId: $0) }
|
||||
} else if method == "pause" {
|
||||
player.pause()
|
||||
} else if method == "resume" {
|
||||
|
||||
+24
@@ -25,6 +25,12 @@ enum ReleaseMode: String {
|
||||
private(set) var isPlaying: Bool
|
||||
var releaseMode: ReleaseMode
|
||||
|
||||
/// Started the moment this player's item ends, without a gap. Cleared
|
||||
/// with the item.
|
||||
weak var next: WrappedMediaPlayer? {
|
||||
didSet { next?.prerollForStart() }
|
||||
}
|
||||
|
||||
private var reference: AudioplayersDarwinPlugin
|
||||
private var player: AVPlayer
|
||||
private var equalizer = EqualizerAudioTap()
|
||||
@@ -134,6 +140,18 @@ enum ReleaseMode: String {
|
||||
updateDuration()
|
||||
}
|
||||
|
||||
/// Fills the render pipeline of a paused, loaded item so a later
|
||||
/// [resume] starts at once.
|
||||
func prerollForStart() {
|
||||
// preroll raises an exception unless the player itself is ready.
|
||||
guard !isPlaying, player.rate == 0, player.status == .readyToPlay,
|
||||
player.currentItem?.status == .readyToPlay
|
||||
else {
|
||||
return
|
||||
}
|
||||
player.preroll(atRate: Float(playbackRate)) { _ in }
|
||||
}
|
||||
|
||||
func setVolume(volume: Double) {
|
||||
self.volume = volume
|
||||
player.volume = Float(volume)
|
||||
@@ -291,6 +309,7 @@ enum ReleaseMode: String {
|
||||
}
|
||||
|
||||
private func reset() {
|
||||
next = nil
|
||||
finishPlayerItemPreparation(.failure(CancellationError()))
|
||||
if let cObserver = completionObserver {
|
||||
NotificationCenter.default.removeObserver(cObserver.observer)
|
||||
@@ -313,6 +332,11 @@ enum ReleaseMode: String {
|
||||
private func onSoundComplete(_ playerItem: AVPlayerItem) async {
|
||||
guard isPlaying, player.currentItem === playerItem else { return }
|
||||
|
||||
// Start the next song before anything else, so it follows without a gap.
|
||||
if let following = next {
|
||||
next = nil
|
||||
if !following.isPlaying { following.resume() }
|
||||
}
|
||||
reference.controlAudioSession()
|
||||
eventHandler.onComplete()
|
||||
|
||||
|
||||
@@ -116,6 +116,53 @@ final class DeferredPlayer: AVPlayer {
|
||||
await wrapper.dispose()
|
||||
}
|
||||
|
||||
@MainActor static func testNextPlayerStartsOnCompletion() async throws {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let firstURL = root.appendingPathComponent("first.wav")
|
||||
let secondURL = root.appendingPathComponent("second.wav")
|
||||
try writeSilence(to: firstURL)
|
||||
try writeSilence(to: secondURL)
|
||||
|
||||
let plugin = AudioplayersDarwinPlugin()
|
||||
func makePlayer() -> (WrappedMediaPlayer, AudioPlayersStreamHandler, AVPlayer) {
|
||||
let native = AVPlayer()
|
||||
native.isMuted = true
|
||||
let events = AudioPlayersStreamHandler()
|
||||
return (
|
||||
WrappedMediaPlayer(reference: plugin, eventHandler: events, player: native), events, native
|
||||
)
|
||||
}
|
||||
let (current, currentEvents, currentNative) = makePlayer()
|
||||
let (following, followingEvents, _) = makePlayer()
|
||||
try await current.setSourceUrl(url: firstURL.path, isLocal: true)
|
||||
try await following.setSourceUrl(url: secondURL.path, isLocal: true)
|
||||
current.next = following
|
||||
guard current.next === following, !following.isPlaying else {
|
||||
throw Failure.message("Linking started the next player")
|
||||
}
|
||||
|
||||
// A new source drops the link.
|
||||
try await current.setSourceUrl(url: secondURL.path, isLocal: true)
|
||||
guard current.next == nil else {
|
||||
throw Failure.message("A new source kept the link to the next player")
|
||||
}
|
||||
try await current.setSourceUrl(url: firstURL.path, isLocal: true)
|
||||
current.next = following
|
||||
current.resume()
|
||||
NotificationCenter.default.post(
|
||||
name: .AVPlayerItemDidPlayToEndTime, object: currentNative.currentItem)
|
||||
try await waitFor("The next player did not start as the current one completed") {
|
||||
following.isPlaying && currentEvents.completedCount == 1
|
||||
}
|
||||
guard current.next == nil, followingEvents.completedCount == 0 else {
|
||||
throw Failure.message("Completion kept the link or completed the next player")
|
||||
}
|
||||
await current.dispose()
|
||||
await following.dispose()
|
||||
}
|
||||
|
||||
@MainActor static func main() async {
|
||||
do {
|
||||
let native = DeferredPlayer()
|
||||
@@ -144,6 +191,8 @@ final class DeferredPlayer: AVPlayer {
|
||||
print("PASS: replacing and disposing loading sources completes cancelled preparation")
|
||||
try await testNativePreparationAndStaleCompletion()
|
||||
print("PASS: native preparation succeeds or fails once, and ignores old completion events")
|
||||
try await testNextPlayerStartsOnCompletion()
|
||||
print("PASS: a linked next player starts as the current one completes")
|
||||
} catch {
|
||||
print("FAIL: \(error)")
|
||||
exit(1)
|
||||
|
||||
Reference in new issue
Block a user