@@ -66,6 +66,7 @@ class PlayerService {
6666 _clock = clock ?? DateTime .now,
6767 policy = PlaybackPolicy (clock: clock) {
6868 _driverEvents = _driver.snapshots.listen ((snapshot) {
69+ final seekRevision = _seekRevision;
6970 final recorded =
7071 ! _closed &&
7172 _source != null &&
@@ -86,7 +87,11 @@ class PlayerService {
8687 }
8788 _background (
8889 () => _commands.synchronized (
89- () => _observe (snapshot, stateAlreadyRecorded: recorded),
90+ () => _observe (
91+ snapshot,
92+ seekRevision: seekRevision,
93+ stateAlreadyRecorded: recorded,
94+ ),
9095 ),
9196 );
9297 });
@@ -164,6 +169,7 @@ class PlayerService {
164169 int _prefetchEpoch = - 1 , _prefetchGeneration = - 1 ;
165170 bool _loading = false ;
166171 int _seekRevision = 0 ;
172+ int ? _cloudResumeEpoch;
167173 int _playbackRecoveryRevision = 0 ;
168174
169175 Stream <void > get changes => _changes.stream;
@@ -720,30 +726,87 @@ class PlayerService {
720726 return (position: saved.toDouble (), updatedAt: updated);
721727 }
722728
723- Future <double > _resumePosition (Track track, int request) async {
724- final local = _localProgress (track);
729+ Future <void > _restoreCloudProgress (
730+ Track track,
731+ PlaybackSource source,
732+ int request,
733+ int epoch,
734+ ({double position, int updatedAt})? local, {
735+ required bool preservePosition,
736+ }) async {
725737 final client = _historyClient;
726- if (! _syncHistory || client == null ) return local? .position ?? 0 ;
738+ if (client == null || ! client.accountAvailable) return ;
739+ final identity = client.cacheIdentity;
740+ final listener = accounts.activeClient;
741+ final revision = _seekRevision;
742+ final expectedGeneration = generation;
743+ bool sameSource () =>
744+ ! _closed && epoch == _epoch && identical (source, _source);
745+ bool active () =>
746+ sameSource () &&
747+ request == _request &&
748+ expectedGeneration == generation &&
749+ current? .id == track.id &&
750+ revision == _seekRevision &&
751+ ! accounts.admissionPaused &&
752+ identical (listener, accounts.activeClient) &&
753+ identical (client, _historyClient) &&
754+ identity == client.cacheIdentity;
755+ // Local samples and billing continue, but the initial fallback must not
756+ // overwrite the remote position before this source's read has settled.
757+ _cloudResumeEpoch = epoch;
758+ Map <String , dynamic >? cloud;
759+ var failed = false ;
727760 try {
728- final cloud = await XmlyHistory (client, clock: _clock).progress (
729- albumId: track.albumId,
730- trackId: track.id,
731- timeout: const Duration (seconds: 2 ),
732- );
733- if (cloud != null &&
734- (local == null ||
735- (cloud['updated_at' ] as num ) * 1000 > local.updatedAt)) {
736- if (request == _request && cloud['incomplete' ] == true ) {
737- _sourceWarning = '云历史查询较慢,已使用本次查到的最新进度' ;
738- }
739- return (cloud['position' ] as num ).toDouble ();
761+ try {
762+ cloud = await XmlyHistory (client, clock: _clock).progress (
763+ albumId: track.albumId,
764+ trackId: track.id,
765+ timeout: const Duration (seconds: 2 ),
766+ isActive: active,
767+ );
768+ } catch (_) {
769+ failed = true ;
740770 }
771+ await _commands.synchronized (() async {
772+ try {
773+ if (! active () || preservePosition || _atEnd) return ;
774+ final remote = cloud;
775+ if (remote != null &&
776+ (local == null ||
777+ (remote['updated_at' ] as num ) * 1000 > local.updatedAt)) {
778+ final restored = policy.start (
779+ duration: duration,
780+ resumePosition: (remote['position' ] as num ).toDouble (),
781+ settings: effectiveSettings,
782+ );
783+ await _driver.seek (restored);
784+ if (! active ()) return ;
785+ ++ _seekRevision;
786+ position = restored;
787+ // Only a subsequent device observation may persist the restored
788+ // position; the pre-seek fallback is not an official observation.
789+ _actual = false ;
790+ _observedAt = 0 ;
791+ if (remote['incomplete' ] == true ) {
792+ _sourceWarning = '云历史查询较慢,已使用本次查到的最新进度' ;
793+ }
794+ } else if (failed) {
795+ _sourceWarning = local == null
796+ ? '云进度暂不可用,继续当前播放'
797+ : '云进度暂不可用,已使用本地进度' ;
798+ }
799+ _notify ();
800+ } finally {
801+ if (sameSource () && _cloudResumeEpoch == epoch) {
802+ _cloudResumeEpoch = null ;
803+ }
804+ }
805+ });
741806 } catch (_) {
742- if (request == _request) {
743- _sourceWarning = local == null ? '云进度暂不可用,将从片头开始' : '云进度暂不可用,已使用本地进度' ;
744- }
807+ // A background restore never fails or pauses an otherwise playable source.
808+ if (sameSource () && _cloudResumeEpoch == epoch) _cloudResumeEpoch = null ;
745809 }
746- return local? .position ?? 0 ;
747810 }
748811
749812 Future <void > _openCurrent (
@@ -822,15 +885,9 @@ class PlayerService {
822885 return ;
823886 }
824887 _source = source;
888+ final local = _localProgress (track);
825889 try {
826- final resume =
827- saved ??
828- await _admission (request, () => _resumePosition (track, request)) ??
829- 0.0 ;
830- if (request != _request) {
831- await _release ();
832- return ;
833- }
890+ final resume = saved ?? local? .position ?? 0.0 ;
834891 if (source.requiresReward &&
835892 source.kind == 'online' &&
836893 ledger.isBlocked (source.identity)) {
@@ -871,6 +928,16 @@ class PlayerService {
871928 return ;
872929 }
873930 _official.start ('player' , track, source.identity);
931+ unawaited (
932+ _restoreCloudProgress (
933+ track,
934+ source,
935+ request,
936+ epoch,
937+ local,
938+ preservePosition: saved != null || manualReplay,
939+ ),
940+ );
874941 final sleep = policy.pollSleep ();
875942 if (sleep != null ) {
876943 await _sleep (sleep);
@@ -1263,6 +1330,7 @@ class PlayerService {
12631330 : null ;
12641331 }
12651332 ++ _seekRevision;
1333+ _cloudResumeEpoch = null ;
12661334 // Seeking itself is never an actual listening observation or history POST.
12671335 _notify ();
12681336 }),
@@ -1349,11 +1417,15 @@ class PlayerService {
13491417
13501418 Future <void > _observe (
13511419 AudioSnapshot snapshot, {
1420+ required int seekRevision,
13521421 bool stateAlreadyRecorded = false ,
13531422 }) async {
13541423 if (_closed || _source == null || snapshot.epoch != _epoch) return ;
13551424 if (snapshot.error != null )
13561425 throw const XmlyException ('audio_device' , '音频播放失败' );
1426+ // Billing captured the event at arrival; stale pre-seek positions must not
1427+ // become fresh local/cloud progress when the command queue catches up.
1428+ if (seekRevision != _seekRevision) return ;
13571429 if (! snapshot.position.isFinite ||
13581430 snapshot.position < 0 ||
13591431 ! snapshot.duration.isFinite ||
@@ -1388,7 +1460,7 @@ class PlayerService {
13881460 speed: rate,
13891461 stateAlreadyRecorded: stateAlreadyRecorded,
13901462 );
1391- if (_actual)
1463+ if (_actual && _cloudResumeEpoch != _epoch )
13921464 await _official.observe (
13931465 'player' ,
13941466 _observedPosition,
@@ -1796,7 +1868,7 @@ class PlayerService {
17961868 });
17971869 }
17981870 _savedAt = _clock ().millisecondsSinceEpoch;
1799- if (sync )
1871+ if (sync && _cloudResumeEpoch != _epoch )
18001872 await _official.observe ('player' , actualPosition, terminal: terminal);
18011873 }
18021874
@@ -2022,6 +2094,7 @@ class PlayerService {
20222094 Future <void > _release () async {
20232095 final source = _source;
20242096 _source = null ;
2097+ _cloudResumeEpoch = null ;
20252098 await source? .release? .call ();
20262099 }
20272100
0 commit comments