From 94b0752e8a07a4ac49d0608af1fc3fae422d6968 Mon Sep 17 00:00:00 2001 From: mj <8197507+dotkebi@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:40:05 +0900 Subject: [PATCH] fix android: getHardwareOutputLatency drifts when the AAudio position rate differs On some devices AAudioStream_getTimestamp()'s framePosition does not advance at the stream rate. On a Samsung SM-G991N (Android 15) a 44.1 kHz stream's framePosition advanced ~0.912x as fast as framesWritten, so (framesWritten - framePosition) / sampleRate grew by ~88 ms per second of playback (171 ms -> 2.2 s within 25 s). Measure the ratio between the two counters on the same stream and convert framePosition to written frames before subtracting. The ratio is taken against framesWritten, not the wall clock, so stopping the device (idle timeout) and starting it again does not disturb it. Ratios within 2% of 1 are taken as 1, so devices whose counters agree get the same value as before. Returns 0 for the first second of a stream, as documented for warm-up. The state is guarded by a mutex. The math lives in a header with no platform dependencies so it can be tested on the host: test/run_aaudio_timestamp_latency_test.sh replays the SM-G991N readings and simulated streams. --- .../miniaudio/aaudio_timestamp_latency.h | 103 ++++++ .../backend/miniaudio/soloud_miniaudio.cpp | 9 +- test/aaudio_timestamp_latency_test.cpp | 315 ++++++++++++++++++ test/run_aaudio_timestamp_latency_test.sh | 20 ++ 4 files changed, 445 insertions(+), 2 deletions(-) create mode 100644 src/soloud/src/backend/miniaudio/aaudio_timestamp_latency.h create mode 100644 test/aaudio_timestamp_latency_test.cpp create mode 100755 test/run_aaudio_timestamp_latency_test.sh diff --git a/src/soloud/src/backend/miniaudio/aaudio_timestamp_latency.h b/src/soloud/src/backend/miniaudio/aaudio_timestamp_latency.h new file mode 100644 index 00000000..32fd497c --- /dev/null +++ b/src/soloud/src/backend/miniaudio/aaudio_timestamp_latency.h @@ -0,0 +1,103 @@ +// Presentation latency of an AAudio output stream from its own counters. +// +// The usual formula is +// +// latency = (framesWritten - framePosition) / sampleRate - (now - timestamp) +// +// where framePosition and timestamp come from AAudioStream_getTimestamp(). It +// assumes both counters count frames of the stream. Some devices break that: +// on a Samsung SM-G991N (Android 15) the timestamp's framePosition of a +// 44.1 kHz stream advances ~0.912x as fast as framesWritten, so the formula +// grows by ~88 ms for every second of playback. +// +// This helper measures how fast framePosition advances relative to +// framesWritten on the same stream and converts framePosition to written +// frames before subtracting. The ratio is measured against framesWritten +// rather than the wall clock, so it is not disturbed when the device is +// stopped and restarted (both counters stand still while stopped). When the +// ratio is within kUnitRatioTolerance of 1 it is taken as exactly 1, so on +// devices whose counters agree the result is the usual formula. +// +// It has no platform dependencies so it can be unit tested on any host. + +#ifndef SOLOUD_AAUDIO_TIMESTAMP_LATENCY_H +#define SOLOUD_AAUDIO_TIMESTAMP_LATENCY_H + +#include +#include +#include + +namespace SoLoud +{ + class AAudioTimestampLatency + { + public: + // Ratios closer to 1 than this are taken as exactly 1. The measured + // ratio is noisy by roughly (buffer level change) / (measured span); + // 2% leaves room for bursts of ~20 ms over the 1 s minimum span. + static constexpr double kUnitRatioTolerance = 0.02; + // Ratios outside [kMinRatio, kMaxRatio] are treated as a bad reading. + static constexpr double kMinRatio = 0.5; + static constexpr double kMaxRatio = 2.0; + + // Returns the latency in seconds, or 0 while the ratio is not known + // yet (less than one second of written frames since the first sample + // of this stream) or when the reading is not usable. + // + // [stream] identifies the AAudio stream; a different value, or either + // counter going backwards, restarts the measurement. + double update(const void *stream, + int64_t framesWritten, + int64_t framePosition, + int64_t timestampNanos, + int64_t nowNanos, + double sampleRate) + { + if (sampleRate <= 0.0) + return 0.0; + + const double stalenessSec = (double)(nowNanos - timestampNanos) / 1000000000.0; + // framesWritten as it was when framePosition was presented. + const double writtenAtTimestamp = (double)framesWritten - stalenessSec * sampleRate; + + double ratio; + { + std::lock_guard lock(mMutex); + if (stream != mStream || + framesWritten < mAnchorFramesWritten || + framePosition < mAnchorFramePosition) + { + mStream = stream; + mAnchorFramesWritten = framesWritten; + mAnchorWrittenAtTimestamp = writtenAtTimestamp; + mAnchorFramePosition = framePosition; + } + + const double writtenSpan = writtenAtTimestamp - mAnchorWrittenAtTimestamp; + const double positionSpan = (double)(framePosition - mAnchorFramePosition); + // Warming up: not enough frames yet to know the ratio. + if (writtenSpan < sampleRate || positionSpan <= 0.0) + return 0.0; + ratio = positionSpan / writtenSpan; + } + + if (ratio < kMinRatio || ratio > kMaxRatio) + return 0.0; + if (std::fabs(ratio - 1.0) <= kUnitRatioTolerance) + ratio = 1.0; + + const double latencySec = + ((double)framesWritten - (double)framePosition / ratio) / sampleRate - stalenessSec; + return latencySec > 0.0 ? latencySec : 0.0; + } + + private: + std::mutex mMutex; + const void *mStream = nullptr; + int64_t mAnchorFramesWritten = -1; + double mAnchorWrittenAtTimestamp = 0.0; + int64_t mAnchorFramePosition = 0; + }; +} // namespace SoLoud + +#endif // SOLOUD_AAUDIO_TIMESTAMP_LATENCY_H diff --git a/src/soloud/src/backend/miniaudio/soloud_miniaudio.cpp b/src/soloud/src/backend/miniaudio/soloud_miniaudio.cpp index f38d0b21..799d9674 100644 --- a/src/soloud/src/backend/miniaudio/soloud_miniaudio.cpp +++ b/src/soloud/src/backend/miniaudio/soloud_miniaudio.cpp @@ -70,6 +70,7 @@ namespace SoLoud #include "miniaudio.h" #ifdef __ANDROID__ #include +#include "aaudio_timestamp_latency.h" #include #include #endif @@ -1788,8 +1789,12 @@ namespace SoLoud double streamSampleRate = (gDevice.playback.internalSampleRate > 0) ? (double)gDevice.playback.internalSampleRate : (double)gDevice.sampleRate; - double latencySec = ((double)(framesWritten - framePosition) / streamSampleRate) - - ((double)(nowNanos - timeNanos) / 1000000000.0); + // framePosition does not advance at the stream rate on + // every device; see aaudio_timestamp_latency.h. + static AAudioTimestampLatency s_timestampLatency; + double latencySec = s_timestampLatency.update( + gDevice.aaudio.pStreamPlayback, framesWritten, framePosition, + timeNanos, nowNanos, streamSampleRate); if (latencySec > 0.0) return latencySec; } diff --git a/test/aaudio_timestamp_latency_test.cpp b/test/aaudio_timestamp_latency_test.cpp new file mode 100644 index 00000000..bdcdcee1 --- /dev/null +++ b/test/aaudio_timestamp_latency_test.cpp @@ -0,0 +1,315 @@ +// Standalone tests for SoLoud::AAudioTimestampLatency, the helper behind +// getHardwareOutputLatency() on Android (AAudio). +// +// AAudioStream_getTimestamp()'s framePosition does not advance at the stream +// rate on every device. On a Samsung SM-G991N (Android 15) the framePosition +// of a 44.1 kHz stream advanced ~0.912x as fast as framesWritten, so +// (framesWritten - framePosition) / sampleRate grew by ~88 ms per second of +// playback. The helper measures the ratio between the two counters and +// converts framePosition before subtracting. +// +// Build and run from the flutter_soloud repository root with: +// +// ./test/run_aaudio_timestamp_latency_test.sh + +#include "../src/soloud/src/backend/miniaudio/aaudio_timestamp_latency.h" + +#include +#include +#include +#include + +namespace { + +int gFailures = 0; +int gAssertions = 0; + +#define EXPECT(condition, format, ...) do { ++gAssertions; if (!(condition)) { ++gFailures; std::printf("FAIL %s:%d: " format "\n", __FILE__, __LINE__, ##__VA_ARGS__); } } while (0) + +struct Sample { + int64_t framesWritten; + int64_t framePosition; + int64_t timestampNanos; + int64_t nowNanos; +}; + +// The formula used before the helper. +double plainLatency(const Sample &s, double sampleRate) +{ + return (double)(s.framesWritten - s.framePosition) / sampleRate - + (double)(s.nowNanos - s.timestampNanos) / 1e9; +} + +// Raw values read about every 0.4 s from a 44.1 kHz SoLoud stream on a +// Samsung SM-G991N (Android 15, SDK 35, device speaker). Over the run +// framesWritten advances 44,100 frames/s and framePosition ~40,190 frames/s. +const std::vector kSmG991n = { + {73870, 65037, 669654170564742LL, 669654199536395LL}, + {322358, 285898, 669659673460891LL, 669659833342430LL}, + {340336, 302134, 669660078165891LL, 669660240450660LL}, + {358670, 318456, 669660483790429LL, 669660657217929LL}, + {376737, 334588, 669660886199775LL, 669661065667237LL}, + {394804, 350987, 669661292586044LL, 669661475428890LL}, + {412960, 367217, 669661698105121LL, 669661888378505LL}, + {431116, 387859, 669662201099390LL, 669662299290543LL}, + {448916, 404000, 669662603992966LL, 669662704071274LL}, + {467161, 420227, 669663008389081LL, 669663117389927LL}, + {484961, 436532, 669663413629773LL, 669663520243619LL}, + {502761, 452765, 669663817320850LL, 669663923291619LL}, + {520739, 468904, 669664219627696LL, 669664332311119LL}, + {538628, 485138, 669664623340926LL, 669664739361619LL}, + {556784, 501278, 669665025966003LL, 669665148283311LL}, + {575029, 517505, 669665430475580LL, 669665563224426LL}, + {592918, 533637, 669665832458695LL, 669665968250887LL}, + {610718, 549949, 669666237802002LL, 669666372379310LL}, + {628963, 566175, 669666641233886LL, 669666786176656LL}, + {647030, 582412, 669667046432078LL, 669667195347155LL}, + {665097, 602739, 669667550909540LL, 669667604341270LL}, + {683342, 618970, 669667956254655LL, 669668018372155LL}, + {725083, 655603, 669668866921539LL, 669668965130231LL}, + {743239, 671745, 669669269997346LL, 669669376387884LL}, + {761128, 687973, 669669674284423LL, 669669783383192LL}, + {779284, 704188, 669670077385499LL, 669670195279038LL}, + {797262, 720502, 669670483059153LL, 669670601324114LL}, + {815062, 736643, 669670886005922LL, 669671009338268LL}, + {833307, 752780, 669671287754845LL, 669671420386075LL}, + {851552, 769015, 669671691800037LL, 669671833297690LL}, + {869530, 785240, 669672095265344LL, 669672241484305LL}, + {887419, 801477, 669672500275575LL, 669672647197536LL}, + {905575, 817774, 669672905369420LL, 669673057330920LL}, + {923642, 838498, 669673411077882LL, 669673467290497LL}, + {941709, 854727, 669673816191958LL, 669673878424112LL}, + {959598, 870943, 669674219032881LL, 669674283286496LL}, + {977576, 887259, 669674625748535LL, 669674691321342LL}, + {995465, 903484, 669675029004611LL, 669675097344303LL}, + {1013443, 919707, 669675434412688LL, 669675505255380LL}, + {1031510, 935929, 669675836562841LL, 669675914238880LL}, + {1049310, 952157, 669676241284072LL, 669676318337880LL}, + {1067555, 968374, 669676645008110LL, 669676730571956LL}, + {1085711, 984514, 669677047873994LL, 669677142240610LL}, + {1103778, 1000829, 669677453563263LL, 669677553437686LL}, +}; + +void testSmG991nLog() +{ + const double sampleRate = 44100.0; + SoLoud::AAudioTimestampLatency latency; + const int stream = 0; + + double first = -1.0, minValue = 1e9, maxValue = -1e9; + for (size_t i = 0; i < kSmG991n.size(); ++i) + { + const Sample &s = kSmG991n[i]; + const double value = latency.update(&stream, s.framesWritten, s.framePosition, + s.timestampNanos, s.nowNanos, sampleRate); + if (i == 0) + { + EXPECT(value == 0.0, "first sample must be warm-up (0), got %f", value); + continue; + } + if (first < 0.0) + first = value; + if (value < minValue) minValue = value; + if (value > maxValue) maxValue = value; + } + // The plain formula drifts from 171 ms to 2.2 s over this run. + EXPECT(plainLatency(kSmG991n.back(), sampleRate) > 2.0, + "plain formula should show the drift, got %f", + plainLatency(kSmG991n.back(), sampleRate)); + EXPECT(minValue > 0.010 && maxValue < 0.060, + "latency must stay in a plausible range, got [%f, %f]", minValue, maxValue); + EXPECT(maxValue - minValue < 0.030, + "latency must not drift, spread %f s", maxValue - minValue); +} + +// A simulated stream. Running time excludes stops; the wall clock does not. +struct SimStream { + double sampleRate = 48000.0; + double positionRatio = 1.0; // framePosition advance per presented frame + double latencySec = 0.030; // what the helper should report + int64_t burstFrames = 192; // framesWritten advances in bursts + double runningSec = 0.0; + double stoppedSec = 0.0; + + Sample read(double timestampAgeSec) const + { + const double timestampRunningSec = runningSec - timestampAgeSec; + const int64_t written = (int64_t)((runningSec + latencySec) * sampleRate) / + burstFrames * burstFrames; + Sample s; + s.framesWritten = written; + s.framePosition = (int64_t)(timestampRunningSec * sampleRate * positionRatio); + s.nowNanos = 1000000000LL + (int64_t)((runningSec + stoppedSec) * 1e9); + s.timestampNanos = s.nowNanos - (int64_t)(timestampAgeSec * 1e9); + return s; + } +}; + +double ageAt(int i) +{ + // Timestamps are 5..165 ms old, as on the device above. + return 0.005 + 0.010 * (i % 17); +} + +void testConformingDeviceMatchesPlainFormula() +{ + SimStream sim; + SoLoud::AAudioTimestampLatency latency; + const int stream = 0; + int compared = 0; + for (int i = 0; i < 200; ++i) + { + sim.runningSec = 0.2 + 0.1 * i; + const Sample s = sim.read(ageAt(i)); + const double value = latency.update(&stream, s.framesWritten, s.framePosition, + s.timestampNanos, s.nowNanos, sim.sampleRate); + if (sim.runningSec < 1.2 + 0.2) + continue; // warm-up + const double plain = plainLatency(s, sim.sampleRate); + EXPECT(std::fabs(value - (plain > 0.0 ? plain : 0.0)) < 1e-12, + "t=%.1f: %f != plain %f", sim.runningSec, value, plain); + ++compared; + } + EXPECT(compared > 150, "compared only %d samples", compared); +} + +void testWarmUpReturnsZero() +{ + SimStream sim; + sim.positionRatio = 0.912; + SoLoud::AAudioTimestampLatency latency; + const int stream = 0; + for (int i = 0; i < 9; ++i) + { + sim.runningSec = 0.2 + 0.1 * i; // less than 1 s after the first sample + const Sample s = sim.read(0.02); + const double value = latency.update(&stream, s.framesWritten, s.framePosition, + s.timestampNanos, s.nowNanos, sim.sampleRate); + EXPECT(value == 0.0, "t=%.1f: expected warm-up 0, got %f", sim.runningSec, value); + } +} + +double runAndCheck(SoLoud::AAudioTimestampLatency &latency, const void *stream, SimStream &sim, + double fromSec, double toSec, const char *label) +{ + double last = 0.0; + int i = 0; + for (double t = fromSec; t <= toSec + 1e-9; t += 0.1, ++i) + { + sim.runningSec = t; + const Sample s = sim.read(ageAt(i)); + last = latency.update(stream, s.framesWritten, s.framePosition, + s.timestampNanos, s.nowNanos, sim.sampleRate); + EXPECT(std::fabs(last - sim.latencySec) < 0.008, + "%s t=%.1f: got %f, want ~%f", label, t, last, sim.latencySec); + } + return last; +} + +void testSlowPositionDevice() +{ + SimStream sim; + sim.sampleRate = 44100.0; + sim.positionRatio = 0.9117; + SoLoud::AAudioTimestampLatency latency; + const int stream = 0; + sim.runningSec = 0.2; + Sample s = sim.read(0.03); + latency.update(&stream, s.framesWritten, s.framePosition, s.timestampNanos, s.nowNanos, + sim.sampleRate); + runAndCheck(latency, &stream, sim, 1.5, 120.0, "slow position"); + EXPECT(plainLatency(sim.read(0.03), sim.sampleRate) > 10.0, + "the plain formula should have drifted by now"); +} + +void testStopAndRestartKeepsTheRatio() +{ + // Idle timeout stops the device: both counters stand still while the + // wall clock keeps going. The result must stay right after the restart, + // with no new warm-up. + SimStream sim; + sim.sampleRate = 44100.0; + sim.positionRatio = 0.9117; + SoLoud::AAudioTimestampLatency latency; + const int stream = 0; + sim.runningSec = 0.2; + Sample s = sim.read(0.03); + latency.update(&stream, s.framesWritten, s.framePosition, s.timestampNanos, s.nowNanos, + sim.sampleRate); + runAndCheck(latency, &stream, sim, 1.5, 5.0, "before stop"); + sim.stoppedSec += 30.0; + runAndCheck(latency, &stream, sim, 5.1, 10.0, "after restart"); + sim.stoppedSec += 600.0; + runAndCheck(latency, &stream, sim, 10.1, 20.0, "after long stop"); +} + +void testNewStreamRestartsMeasurement() +{ + SimStream sim; + sim.positionRatio = 0.9117; + SoLoud::AAudioTimestampLatency latency; + const int streamA = 0, streamB = 0; + sim.runningSec = 0.2; + Sample s = sim.read(0.03); + latency.update(&streamA, s.framesWritten, s.framePosition, s.timestampNanos, s.nowNanos, + sim.sampleRate); + runAndCheck(latency, &streamA, sim, 1.5, 3.0, "stream A"); + + // A rerouted device opens a new stream whose counters start again. It + // runs at the stream rate. + SimStream next; + next.runningSec = 0.2; + s = next.read(0.03); + double value = latency.update(&streamB, s.framesWritten, s.framePosition, s.timestampNanos, + s.nowNanos, next.sampleRate); + EXPECT(value == 0.0, "new stream must warm up again, got %f", value); + runAndCheck(latency, &streamB, next, 1.5, 3.0, "stream B"); + + // Same stream pointer, but the counters went back (a stream reopened at + // the same address): start over too. + SimStream reopened; + reopened.runningSec = 0.2; + s = reopened.read(0.03); + value = latency.update(&streamB, s.framesWritten, s.framePosition, s.timestampNanos, + s.nowNanos, reopened.sampleRate); + EXPECT(value == 0.0, "counters going back must restart warm-up, got %f", value); + runAndCheck(latency, &streamB, reopened, 1.5, 3.0, "reopened"); +} + +void testImplausibleRatioReturnsZero() +{ + SimStream sim; + sim.positionRatio = 0.3; + SoLoud::AAudioTimestampLatency latency; + const int stream = 0; + for (int i = 0; i < 40; ++i) + { + sim.runningSec = 0.2 + 0.1 * i; + const Sample s = sim.read(0.02); + const double value = latency.update(&stream, s.framesWritten, s.framePosition, + s.timestampNanos, s.nowNanos, sim.sampleRate); + EXPECT(value == 0.0, "t=%.1f: expected 0 for ratio 0.3, got %f", sim.runningSec, value); + } +} + +} // namespace + +int main() +{ + testSmG991nLog(); + testConformingDeviceMatchesPlainFormula(); + testWarmUpReturnsZero(); + testSlowPositionDevice(); + testStopAndRestartKeepsTheRatio(); + testNewStreamRestartsMeasurement(); + testImplausibleRatioReturnsZero(); + + if (gFailures > 0) + { + std::printf("aaudio_timestamp_latency_test: %d of %d assertions failed\n", + gFailures, gAssertions); + return 1; + } + std::printf("aaudio_timestamp_latency_test: all %d assertions passed\n", gAssertions); + return 0; +} diff --git a/test/run_aaudio_timestamp_latency_test.sh b/test/run_aaudio_timestamp_latency_test.sh new file mode 100755 index 00000000..649a3b64 --- /dev/null +++ b/test/run_aaudio_timestamp_latency_test.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Build and run the standalone tests of AAudioTimestampLatency, the helper +# that getHardwareOutputLatency() uses on Android: the result must not drift +# when the AAudio timestamp's framePosition advances at a different rate than +# framesWritten, must match the plain formula when they agree, and must +# survive the device being stopped and restarted. Header-only and free of +# platform APIs, so it runs on any host; no audio device or assets needed. + +set -e + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$REPO_ROOT" + +OUT="${TMPDIR:-/tmp}/aaudio_timestamp_latency_test" + +c++ -std=c++17 -O2 -Wall -Wextra -pthread \ + -o "$OUT" \ + test/aaudio_timestamp_latency_test.cpp + +"$OUT"