diff --git a/lib/services/link/together/link_together_aligner.dart b/lib/services/link/together/link_together_aligner.dart index 3686939d0..2f52cb780 100644 --- a/lib/services/link/together/link_together_aligner.dart +++ b/lib/services/link/together/link_together_aligner.dart @@ -11,7 +11,8 @@ final class LinkTogetherWait extends LinkTogetherStep { } /// Play the follower at [factor] times the normal rate for [durationMs]; -/// a factor of 1 stops a nudge under way. +/// a factor of 1 stops a nudge under way. A nudge at the rate already in +/// force only moves its end. final class LinkTogetherNudge extends LinkTogetherStep { const LinkTogetherNudge(this.factor, this.durationMs); @@ -24,12 +25,81 @@ final class LinkTogetherRejoin extends LinkTogetherStep { const LinkTogetherRejoin(); } +/// How one nudge turned out, read at the first settled check after it. +class LinkTogetherLanding { + const LinkTogetherLanding({ + required this.beforeMs, + required this.expectedMs, + required this.measuredMs, + required this.costMs, + required this.countedCostMs, + required this.holding, + }); + + /// The drift the nudge was planned for. + final int beforeMs; + + /// Where the plan expected the drift to end, the counted cost included. + final int expectedMs; + + /// The drift measured once the follower settled. + final int measuredMs; + + /// What the two rate changes moved the follower this time: the measured + /// drift minus what the rate alone explains. + final int costMs; + + /// The cost the next nudge is planned with. + final int countedCostMs; + + /// This landing made the aligner hold (see [LinkTogetherAligner.holding]). + final bool holding; +} + +/// A nudge under way, or ended and waiting for its landing to be read. +class _Nudge { + _Nudge({ + required this.beforeMs, + required this.sign, + required this.factor, + required this.startMs, + required this.untilMs, + required this.costMs, + required this.knewCost, + }); + + final int beforeMs; + + /// 1 while the follower plays faster (its error grows), -1 slower. + final int sign; + final double factor; + final int startMs; + int untilMs; + + /// The rate change cost the plan counts (updated once entering the rate + /// was measured), and whether an earlier nudge measured one. + int costMs; + final bool knewCost; + + /// What entering the rate moved the follower, once a settled check + /// during the nudge showed it. + int? enterMs; + bool replanned = false; +} + /// Decides, from the follower's error against the leader (positive while it /// runs ahead), how to keep the two in step: leave small errors alone, close /// moderate ones and steady small ones by playing the follower a little /// faster or slower, and rejoin for large ones, without rejoining over and /// over when that does not help. It also learns how late the follower /// sounds after being told to start, which the next cue starts early by. +/// +/// Some engines move the song a little each time their rate changes: a +/// plain AVPlayer change held its clock for 21 to 26 ms. The aligner +/// measures that cost on every nudge and plans the next one with it, so a +/// nudge ends in step instead of short of it. Where nudges still keep +/// missing (the cost varies too much), it holds: no more nudges until the +/// error passes [holdFromMs], so the rate is not toggled for nothing. class LinkTogetherAligner { LinkTogetherAligner({ this.inStepMs = 20, @@ -38,12 +108,17 @@ class LinkTogetherAligner { this.fineSamples = 5, this.rejoinFromMs = 250, this.rejoinWithoutNudgeFromMs = 80, + this.holdFromMs = 80, this.rate = 0.02, - this.maxNudgeMs = 10000, + this.minNudgeMs = 200, + this.maxNudgeMs = 15000, this.settleMs = 1200, + this.rateSettleMs = 1000, this.minRejoinGapMs = 2000, this.maxRejoinGapMs = 16000, - this.maxLeadMs = 400, + this.maxLeadMs = 600, + this.leadAgreeMs = 25, + this.maxMisses = 2, }) : _rejoinGapMs = minRejoinGapMs; /// Errors up to this are in step. @@ -64,17 +139,33 @@ class LinkTogetherAligner { /// row, as a rejoin is heard). final int rejoinWithoutNudgeFromMs; + /// While holding, errors from this, twice in a row, start a nudge. + final int holdFromMs; + /// How much faster or slower a nudge plays: 2 % closes 20 ms a second. final double rate; + final int minNudgeMs; final int maxNudgeMs; /// After a rejoin or a change, samples wait this long: players report a /// fresh start unevenly. final int settleMs; + + /// After a rate change, samples wait this long: the follower's report + /// shows what the change did only once its player has read the engine. + final int rateSettleMs; final int minRejoinGapMs; final int maxRejoinGapMs; final int maxLeadMs; + /// Two settled samples after a rejoin this close together are trusted as + /// the follower's start offset. + final int leadAgreeMs; + + /// Nudges of the last four planned with a measured cost that may end + /// outside [inStepMs] before the aligner holds; once it held, one does. + final int maxMisses; + /// How early the follower is told to start, learned from how late it /// sounded after the last rejoins; negative starts it late, where the /// leader is the slower one to sound after a play. At most [maxLeadMs] @@ -82,124 +173,310 @@ class LinkTogetherAligner { int leadMs = 0; int _settleUntilMs = 0; - int _nudgeUntilMs = 0; - int _nudgeSign = 0; + _Nudge? _nudge; int _overNudge = 0; int _overRejoin = 0; int? _lastRejoinMs; int _rejoinGapMs; - bool _learn = false; + bool _holding = false; + bool _held = false; + int _landed = 0; - /// Errors since the last change, while no nudge ran. + /// 1 for each of the last nudges planned with a measured cost that ended + /// out of step, 0 for one in step. + final _missed = []; + LinkTogetherLanding? _landing; + + /// Errors since the last change, settled and while no nudge ran. final _recent = []; + /// After a rejoin that plays: the lead it used and its settled samples. + bool _learning = false; + int _leadUsed = 0; + final _learnSamples = []; + + /// The leads the last rejoins needed, and what the rate changes of the + /// last nudges cost, in all and on entering the rate. + final _leads = []; + final _costs = []; + final _enterCosts = []; + /// Whether a nudge runs at [nowMs]. - bool nudging(int nowMs) => nowMs < _nudgeUntilMs; + bool nudging(int nowMs) => (_nudge?.untilMs ?? 0) > nowMs; + + /// Whether a sample at [nowMs] would be ignored as unsettled. + bool settling(int nowMs) { + if (nowMs < _settleUntilMs) return true; + final nudge = _nudge; + if (nudge == null) return false; + return nowMs - nudge.startMs < rateSettleMs || + (nowMs >= nudge.untilMs && nowMs - nudge.untilMs < rateSettleMs); + } + + /// Nudges keep missing here: the aligner only acts on errors from + /// [holdFromMs]. Two nudges in a row that end in step lift it, until the + /// next miss. + bool get holding => _holding; + + /// The rate change cost the next nudge is planned with: the median of + /// the last measurements, 0 until one was made. + int get countedCostMs => _median(_costs) ?? 0; + + /// How the last nudge turned out, once; null when none was read since. + LinkTogetherLanding? takeLanding() { + final landing = _landing; + _landing = null; + return landing; + } + + static int? _median(List values) { + if (values.isEmpty) return null; + final sorted = [...values]..sort(); + final middle = sorted.length ~/ 2; + return sorted.length.isOdd + ? sorted[middle] + : ((sorted[middle - 1] + sorted[middle]) / 2).round(); + } + + static void _keep(List values, int value, [int count = 3]) { + values.add(value); + if (values.length > count) values.removeAt(0); + } /// A rejoin ended with the follower started at [startedMs]. The first - /// sample after settling adjusts [leadMs]. Most rejoins follow the leader + /// settled samples after it set [leadMs]. Most rejoins follow the leader /// starting, so the lead also covers how much later the follower's player /// sounds than the leader's. void rejoined(int startedMs) { _settleUntilMs = startedMs + settleMs; _lastRejoinMs = startedMs; - _nudgeUntilMs = 0; + _nudge = null; _overNudge = 0; _overRejoin = 0; _recent.clear(); - _learn = true; + _learning = true; + _leadUsed = leadMs; + _learnSamples.clear(); } /// The leader changed song, play state or position: wait for it to settle /// and learn nothing from what follows. void restart(int nowMs) { _settleUntilMs = nowMs + settleMs; - _nudgeUntilMs = 0; + _nudge = null; _overNudge = 0; _overRejoin = 0; _recent.clear(); - _learn = false; + _learning = false; } /// Takes the follower's error [errorMs] at [nowMs]. LinkTogetherStep sample(int errorMs, int nowMs, {required bool canNudge}) { if (nowMs < _settleUntilMs) return const LinkTogetherWait(); - final magnitude = errorMs.abs(); - if (_learn) { - _learn = false; - // Behind (negative) means it sounded late: start it earlier next time. - if (magnitude <= rejoinFromMs) { - leadMs = (leadMs - errorMs * 0.6).round().clamp(-maxLeadMs, maxLeadMs); + final nudge = _nudge; + if (nudge != null) { + if (nowMs - nudge.startMs < rateSettleMs) return const LinkTogetherWait(); + if (nowMs < nudge.untilMs) { + return _during(nudge, errorMs, nowMs, canNudge); } + if (nowMs - nudge.untilMs < rateSettleMs) return const LinkTogetherWait(); + _nudge = null; + _land(nudge, errorMs); } - final nudging = this.nudging(nowMs); - if (!nudging) { - _recent.add(errorMs); - if (_recent.length > fineSamples) _recent.removeAt(0); + if (_learning) _learn(errorMs); + return _decide(errorMs, nowMs, canNudge: canNudge); + } + + /// Learns the lead from the settled samples after a rejoin, once one + /// confirms the last. + void _learn(int errorMs) { + // Far off is a different problem (a wrong song or place), not a start. + if (errorMs.abs() > maxLeadMs + 200) { + _learning = false; + return; } + _learnSamples.add(errorMs); + final count = _learnSamples.length; + int? settled; + if (count >= 2 && + (_learnSamples[count - 1] - _learnSamples[count - 2]).abs() <= + leadAgreeMs) { + settled = ((_learnSamples[count - 1] + _learnSamples[count - 2]) / 2) + .round(); + } else if (count >= 4) { + settled = _median(_learnSamples.sublist(count - 3)); + } + if (settled != null) _settleLead(settled); + } + + /// The follower settled [settledMs] off after the last rejoin. + void _settleLead(int settledMs) { + _learning = false; + // Behind (negative) means it sounded late: start it earlier next time, + // by all of it, averaged with the last rejoins' needs. + _keep(_leads, _leadUsed - settledMs); + final mean = _leads.reduce((a, b) => a + b) / _leads.length; + leadMs = mean.round().clamp(-maxLeadMs, maxLeadMs); + } + + LinkTogetherStep _decide(int errorMs, int nowMs, {required bool canNudge}) { + final magnitude = errorMs.abs(); + _keep(_recent, errorMs, fineSamples); final rejoinFrom = canNudge ? rejoinFromMs : rejoinWithoutNudgeFromMs; if (magnitude <= inStepMs) { _overNudge = 0; _overRejoin = 0; _rejoinGapMs = minRejoinGapMs; - if (nudging) { - _nudgeUntilMs = 0; - return const LinkTogetherNudge(1, 0); - } return _fine(nowMs, canNudge: canNudge); } - if (nudging) { - // Past the leader: the nudge overshot. - if (errorMs.sign != _nudgeSign) { - _nudgeUntilMs = 0; - return const LinkTogetherNudge(1, 0); - } - if (magnitude <= rejoinFrom) return const LinkTogetherWait(); - } if (magnitude > rejoinFrom) { - _overNudge = 0; - final needed = magnitude > 1500 ? 1 : (canNudge ? 2 : 3); - final last = _lastRejoinMs; - if (++_overRejoin >= needed && - (last == null || nowMs - last >= _rejoinGapMs)) { - _overRejoin = 0; - _nudgeUntilMs = 0; - if (last != null) { - _rejoinGapMs = math.min(_rejoinGapMs * 2, maxRejoinGapMs); - } - return const LinkTogetherRejoin(); - } - return const LinkTogetherWait(); + return _towardsRejoin(magnitude, nowMs, canNudge); } _overRejoin = 0; _rejoinGapMs = minRejoinGapMs; - if (!canNudge || magnitude < nudgeFromMs) { + final from = _holding ? holdFromMs : nudgeFromMs; + if (!canNudge || magnitude < from) { _overNudge = 0; return _fine(nowMs, canNudge: canNudge); } if (++_overNudge < 2) return const LinkTogetherWait(); _overNudge = 0; - return _nudge(errorMs, nowMs); + return _start(errorMs, nowMs); } - /// A short nudge for a small error that stays. + LinkTogetherStep _towardsRejoin(int magnitude, int nowMs, bool canNudge) { + _overNudge = 0; + final needed = magnitude > 1500 ? 1 : (canNudge ? 2 : 3); + final last = _lastRejoinMs; + if (++_overRejoin >= needed && + (last == null || nowMs - last >= _rejoinGapMs)) { + _overRejoin = 0; + _nudge = null; + if (last != null) { + _rejoinGapMs = math.min(_rejoinGapMs * 2, maxRejoinGapMs); + } + return const LinkTogetherRejoin(); + } + return const LinkTogetherWait(); + } + + /// A short nudge for a small error that stays. Where the rate changes + /// move the song more than [inStepMs], only an error that stays out of + /// step is worth them. LinkTogetherStep _fine(int nowMs, {required bool canNudge}) { - if (!canNudge || _recent.length < fineSamples) { + if (!canNudge || _holding || _recent.length < fineSamples) { return const LinkTogetherWait(); } final mean = _recent.reduce((a, b) => a + b) / _recent.length; - if (mean.abs() < fineFromMs) return const LinkTogetherWait(); - return _nudge(mean.round(), nowMs); + final costly = countedCostMs.abs() > inStepMs; + if (costly ? mean.abs() <= inStepMs : mean.abs() < fineFromMs) { + return const LinkTogetherWait(); + } + return _start(mean.round(), nowMs); } - LinkTogetherNudge _nudge(int errorMs, int nowMs) { + /// A nudge that should end with the follower in step: the rate must move + /// it by the error and by what the two rate changes cost. + LinkTogetherNudge _start(int errorMs, int nowMs) { _recent.clear(); - final duration = math - .min(errorMs.abs() / rate, maxNudgeMs.toDouble()) - .round(); - _nudgeSign = errorMs.sign; - _nudgeUntilMs = nowMs + duration; - // Ahead slows down; behind speeds up. - return LinkTogetherNudge(errorMs > 0 ? 1 - rate : 1 + rate, duration); + // The samples after a nudge show the nudge, not the start: learn from + // what came before it. + if (_learning) { + final settled = _median(_learnSamples); + if (settled == null) { + _learning = false; + } else { + _settleLead(settled); + } + } + final cost = countedCostMs; + final need = -errorMs - cost; + final sign = need >= 0 ? 1 : -1; + final duration = (need.abs() / rate).round().clamp(minNudgeMs, maxNudgeMs); + final factor = 1 + sign * rate; + _nudge = _Nudge( + beforeMs: errorMs, + sign: sign, + factor: factor, + startMs: nowMs, + untilMs: nowMs + duration, + costMs: cost, + knewCost: _costs.isNotEmpty, + ); + return LinkTogetherNudge(factor, duration); + } + + /// A settled sample while [nudge] runs. The first one shows what entering + /// the rate cost; when the nudge would then end out of step, its end + /// moves once (same rate, so no extra rate change). + LinkTogetherStep _during( + _Nudge nudge, + int errorMs, + int nowMs, + bool canNudge, + ) { + final rejoinFrom = canNudge ? rejoinFromMs : rejoinWithoutNudgeFromMs; + if (errorMs.abs() > rejoinFrom) { + return _towardsRejoin(errorMs.abs(), nowMs, canNudge); + } + _overRejoin = 0; + final byRate = nudge.beforeMs + nudge.sign * rate * (nowMs - nudge.startMs); + final enter = nudge.enterMs ??= (errorMs - byRate).round(); + if (nudge.replanned) return const LinkTogetherWait(); + // What leaving the rate will cost: what the last nudges cost less what + // entering cost them, or before one landed, what entering cost now + // (AVPlayer loses about as much each way). + final leave = _costs.isEmpty + ? enter + : countedCostMs - (_median(_enterCosts) ?? enter); + nudge.costMs = enter + leave; + final remaining = nudge.untilMs - nowMs; + final landing = errorMs + nudge.sign * rate * remaining + leave; + if (landing.abs() <= inStepMs) return const LinkTogetherWait(); + nudge.replanned = true; + final needed = (-(errorMs + leave) / (nudge.sign * rate)).round(); + if (needed <= 0) { + nudge.untilMs = nowMs; + return const LinkTogetherNudge(1, 0); + } + final duration = math.min(needed, maxNudgeMs); + nudge.untilMs = nowMs + duration; + return LinkTogetherNudge(nudge.factor, duration); + } + + /// Reads how [nudge] ended from the first settled sample after it, and + /// counts what its rate changes cost. + void _land(_Nudge nudge, int errorMs) { + final byRate = + nudge.beforeMs + nudge.sign * rate * (nudge.untilMs - nudge.startMs); + final cost = (errorMs - byRate).round(); + _keep(_costs, cost); + final enter = nudge.enterMs; + if (enter != null) _keep(_enterCosts, enter); + final missed = errorMs.abs() > inStepMs; + if (missed) { + _landed = 0; + } else if (_holding && ++_landed >= 2) { + _holding = false; + _landed = 0; + } + var held = false; + // A first nudge, planned without a measured cost, may miss by it. + if (nudge.knewCost) { + _keep(_missed, missed ? 1 : 0, 4); + final misses = _missed.reduce((a, b) => a + b); + if (missed && !_holding && misses >= (_held ? 1 : maxMisses)) { + _holding = _held = true; + held = true; + } + } + _landing = LinkTogetherLanding( + beforeMs: nudge.beforeMs, + expectedMs: (byRate + nudge.costMs).round(), + measuredMs: errorMs, + costMs: cost, + countedCostMs: countedCostMs, + holding: held, + ); } } diff --git a/lib/services/link/together/link_together_coordinator.dart b/lib/services/link/together/link_together_coordinator.dart index c4acb6398..1b9290977 100644 --- a/lib/services/link/together/link_together_coordinator.dart +++ b/lib/services/link/together/link_together_coordinator.dart @@ -435,20 +435,52 @@ class LinkTogetherCoordinator { final at = desktop.nowMs; if (!_reportFresh || now - at > freshMs || at > now + 50) return; _reportFresh = false; - final phoneError = phone.positionAt(at) - (desktop.positionMs - _shiftMs()); + final phoneAt = phone.positionAt(at); + final phoneError = phoneAt - (desktop.positionMs - _shiftMs()); final error = phoneLeads ? -phoneError : phoneError; lastErrorMs = error; final canNudge = phoneLeads ? raw.canNudge : _phone.canNudge; + final who = phoneLeads ? 'computer' : 'phone'; + // The follower's own report, where it should be, and what it was doing. + final reported = phoneLeads ? desktop.positionMs : phoneAt; + final rate = (phoneLeads ? raw : phone).rate; + final nudging = aligner.nudging(now); + _log.d( + 'Link: together, check: $who at ${reported}ms, expected ' + '${reported - error}ms, drift ${error}ms, rate ' + '${rate?.toStringAsFixed(2) ?? '?'}, nudge ${nudging ? 'on' : 'off'}' + '${aligner.settling(now) ? ', settling' : ''}', + ); final step = aligner.sample(error, now, canNudge: canNudge); + final landing = aligner.takeLanding(); + if (landing != null) { + _log.i( + 'Link: together, nudge ended: drift before ${landing.beforeMs}ms, ' + 'expected ${landing.expectedMs}ms, measured ${landing.measuredMs}ms ' + '(the rate changes moved it ${landing.costMs}ms, now counted as ' + '${landing.countedCostMs}ms)', + ); + if (landing.holding) { + _log.i( + 'Link: together, nudges do not land within ${aligner.inStepMs}ms ' + 'here, holding until the drift passes ${aligner.holdFromMs}ms', + ); + } + } switch (step) { case LinkTogetherWait(): - _log.d('Link: together, drift ${error}ms'); + break; case LinkTogetherNudge(:final factor, :final durationMs): - _log.i( - 'Link: together, drift ${error}ms, nudging the ' - '${phoneLeads ? 'computer' : 'phone'} to $factor for ' - '${durationMs}ms', - ); + _log.i(switch ((factor == 1, nudging)) { + (true, _) => 'Link: together, drift ${error}ms, ending the nudge', + (false, true) => + 'Link: together, drift ${error}ms, the nudge goes on ' + '${durationMs}ms more', + (false, false) => + 'Link: together, drift ${error}ms, nudging the $who to $factor ' + 'for ${durationMs}ms (rate changes counted as ' + '${aligner.countedCostMs}ms)', + }); if (phoneLeads) { await _desktop.nudge(factor, durationMs); } else { diff --git a/test/link_together_aligner_test.dart b/test/link_together_aligner_test.dart index 0d160dc1f..b6a8da1c2 100644 --- a/test/link_together_aligner_test.dart +++ b/test/link_together_aligner_test.dart @@ -37,20 +37,121 @@ void main() { expect(aligner.sample(50, 2000, canNudge: true), isA()); }); - test('a nudge stops once in step or past the leader', () { + test('a nudge on course runs its planned length', () { final aligner = LinkTogetherAligner() ..sample(100, 0, canNudge: true) ..sample(100, 1000, canNudge: true); - expect(aligner.sample(60, 2000, canNudge: true), isA()); - final stop = aligner.sample(15, 3000, canNudge: true); - expect((stop as LinkTogetherNudge).factor, 1); - expect(aligner.nudging(3500), isFalse); + // Just after the rate change the report does not show it yet. + expect(aligner.settling(1500), isTrue); + expect(aligner.sample(0, 1500, canNudge: true), isA()); + // In step at 15 ms, but the plan ends at 0: no stop half way. + expect(aligner.sample(80, 2000, canNudge: true), isA()); + expect(aligner.sample(15, 5250, canNudge: true), isA()); + expect(aligner.nudging(5900), isTrue); + expect(aligner.nudging(6000), isFalse); + }); + test('a nudge that would end out of step is replanned once', () { + // Entering the rate cost 30 ms: 2 % for 5 s would end 60 ms behind + // (leaving costs about as much), so the nudge ends 1 s after the check. + final aligner = LinkTogetherAligner() + ..sample(100, 0, canNudge: true) + ..sample(100, 1000, canNudge: true); + final shorter = aligner.sample(50, 2000, canNudge: true); + expect((shorter as LinkTogetherNudge).factor, closeTo(0.98, 1e-9)); + expect(shorter.durationMs, 1000); + expect(aligner.sample(0, 2500, canNudge: true), isA()); + expect(aligner.sample(0, 3500, canNudge: true), isA()); + expect(aligner.takeLanding(), isNull); + expect( + aligner.sample(-10, 4000, canNudge: true), + isA(), + ); + final landing = aligner.takeLanding()!; + expect(landing.beforeMs, 100); + expect(landing.expectedMs, 0); + expect(landing.measuredMs, -10); + expect(landing.costMs, -70); + expect(landing.countedCostMs, -70); + expect(landing.holding, isFalse); + expect(aligner.takeLanding(), isNull); + + // Already past the leader: the nudge ends at once. final overshoot = LinkTogetherAligner() ..sample(100, 0, canNudge: true) ..sample(100, 1000, canNudge: true); - final flipped = overshoot.sample(-25, 2000, canNudge: true); - expect((flipped as LinkTogetherNudge).factor, 1); + final stop = overshoot.sample(-30, 2000, canNudge: true); + expect((stop as LinkTogetherNudge).factor, 1); + expect(overshoot.nudging(2000), isFalse); + }); + + test('counts what rate changes cost and plans the next nudge with it', () { + // The real run: each nudge pair lost about 48 ms, so a 2.45 s nudge + // for -49 ms ended at -48 ms again, every 4 s. + final aligner = _withCost(-48); + expect(aligner.countedCostMs, -48); + final step = aligner.sample(-49, 8000, canNudge: true); + expect((step as LinkTogetherNudge).factor, closeTo(1.02, 1e-9)); + expect(step.durationMs, 4850); + // Entering cost 26 ms, which the plan expected: no replanning. + expect( + aligner.sample(-55, 9000, canNudge: true), + isA(), + ); + expect( + aligner.sample(-1, 13850, canNudge: true), + isA(), + ); + final landing = aligner.takeLanding()!; + expect(landing.expectedMs, 0); + expect(landing.measuredMs, -1); + expect(landing.costMs, -49); + expect(aligner.holding, isFalse); + }); + + test('where rate changes cost more than 20 ms, a short nudge waits for ' + 'an error that stays out of step', () { + final aligner = _withCost(-45); + var now = 8000; + for (var i = 0; i < 6; i++) { + expect( + aligner.sample(17, now += 1000, canNudge: true), + isA(), + ); + } + LinkTogetherStep step = const LinkTogetherWait(); + for (var i = 0; i < 5 && step is LinkTogetherWait; i++) { + step = aligner.sample(25, now += 1000, canNudge: true); + } + // Ahead, yet faster: slowing down would lose the changes' 45 ms too. + expect((step as LinkTogetherNudge).factor, closeTo(1.02, 1e-9)); + }); + + test('holds when planned nudges keep missing, until 80 ms', () { + final aligner = _withCost(-48); + // Planned for -48 ms, the changes moved it +10 ms: a miss. + aligner.sample(-49, 8000, canNudge: true); + aligner.sample(58, 13850, canNudge: true); + expect(aligner.takeLanding()!.holding, isFalse); + final second = aligner.sample(58, 14850, canNudge: true); + expect((second as LinkTogetherNudge).factor, closeTo(0.98, 1e-9)); + expect(second.durationMs, 1950); + // Then -60 ms: a second miss. + aligner.sample(-41, 17800, canNudge: true); + expect(aligner.takeLanding()!.holding, isTrue); + expect(aligner.holding, isTrue); + var now = 17800; + for (final error in [-41, -60, -79, -79, -50, -79, -20, -79]) { + expect( + aligner.sample(error, now += 1000, canNudge: true), + isA(), + ); + } + aligner.sample(-90, now += 1000, canNudge: true); + expect( + aligner.sample(-90, now += 1000, canNudge: true), + isA(), + ); }); test('a small error that stays is closed by a short nudge', () { @@ -76,10 +177,10 @@ void main() { } }); - test('nudges are capped at ten seconds', () { - final aligner = LinkTogetherAligner()..sample(240, 0, canNudge: true); - final step = aligner.sample(240, 1000, canNudge: true); - expect((step as LinkTogetherNudge).durationMs, 10000); + test('nudges are capped at fifteen seconds', () { + final aligner = _withCost(-100); + final step = aligner.sample(-245, 8000, canNudge: true); + expect((step as LinkTogetherNudge).durationMs, 15000); }); test('rejoins beyond 250 ms on two samples, beyond 1.5 s at once', () { @@ -175,32 +276,72 @@ void main() { ); }); - test('learns how late the follower sounds after a rejoin', () { - // The follower always sounds 60 ms after it is told to start. - final aligner = LinkTogetherAligner(); - var now = 0; - for (var i = 0; i < 8; i++) { - aligner.rejoined(now); - now += 2000; - aligner.sample(aligner.leadMs - 60, now, canNudge: true); - now += 1000; + test('learns how late the follower sounds after a rejoin, in one step', () { + // The real run: lead 0 settled 221 ms behind, and the next cue's lead + // of 133 ms still settled 107 ms behind. + final aligner = LinkTogetherAligner()..rejoined(0); + expect(aligner.settling(1000), isTrue); + // Two settled samples that agree are trusted, the first alone is not. + expect( + aligner.sample(-230, 1500, canNudge: true), + isA(), + ); + expect(aligner.leadMs, 0); + aligner.sample(-226, 2500, canNudge: true); + expect(aligner.leadMs, 228); + + // The next cue starts that early and settles in step; the lead stays. + aligner.rejoined(5000); + aligner + ..sample(-2, 6500, canNudge: true) + ..sample(3, 7500, canNudge: true); + expect(aligner.leadMs, inInclusiveRange(227, 228)); + + // Samples that do not agree yet are waited for. + final unsure = LinkTogetherAligner()..rejoined(0); + for (final (i, error) in [-30, 0, -28].indexed) { + unsure.sample(error, 1500 + i * 1000, canNudge: true); + expect(unsure.leadMs, 0); + } + unsure.sample(-26, 4500, canNudge: true); + expect(unsure.leadMs, 27); + + // A nudge that starts first ends the learning with what came before. + final nudged = LinkTogetherAligner()..rejoined(0); + nudged.sample(-100, 1500, canNudge: true); + final step = nudged.sample(-200, 2500, canNudge: true); + expect(step, isA()); + expect(nudged.leadMs, 150); + }); + + test('a lead stays within 600 ms, either way', () { + LinkTogetherAligner learn(int lead, int settled) { + final aligner = LinkTogetherAligner() + ..leadMs = lead + ..rejoined(0) + ..sample(settled, 1500, canNudge: true) + ..sample(settled, 2500, canNudge: true); + return aligner; } - expect(aligner.leadMs, inInclusiveRange(58, 62)); // Ahead after a rejoin: the leader was the slower one to sound, so the - // follower starts late, by 400 ms at most either way. - final bounded = LinkTogetherAligner(); - bounded.rejoined(0); - bounded.sample(200, 2000, canNudge: true); - expect(bounded.leadMs, -120); - bounded.leadMs = 390; - bounded.rejoined(3000); - bounded.sample(-200, 5000, canNudge: true); - expect(bounded.leadMs, 400); - bounded.leadMs = -390; - bounded.rejoined(6000); - bounded.sample(200, 8000, canNudge: true); - expect(bounded.leadMs, -400); + // follower starts late. + expect(learn(0, 200).leadMs, -200); + expect(learn(590, -200).leadMs, 600); + expect(learn(-590, 200).leadMs, -600); + // Far off is another problem (a wrong song or place), not a start. + expect(learn(0, 900).leadMs, 0); }); }); } + +/// An aligner whose one nudge so far, planned without a cost, ended +/// [costMs] away from where the rate alone took it, read at 7 s. +LinkTogetherAligner _withCost(int costMs) { + final aligner = LinkTogetherAligner() + ..sample(100, 0, canNudge: true) + ..sample(100, 1000, canNudge: true) + ..sample(costMs, 7000, canNudge: true); + aligner.takeLanding(); + return aligner; +}