1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "IsochronousClockModel"
18 //#define LOG_NDEBUG 0
19 #include <log/log.h>
20
21 #define __STDC_FORMAT_MACROS
22 #include <inttypes.h>
23 #include <stdint.h>
24 #include <algorithm>
25
26 #include "utility/AudioClock.h"
27 #include "utility/AAudioUtilities.h"
28 #include "IsochronousClockModel.h"
29
30 using namespace aaudio;
31
32 using namespace android::audio_utils;
33
34 #ifndef ICM_LOG_DRIFT
35 #define ICM_LOG_DRIFT 0
36 #endif // ICM_LOG_DRIFT
37
38 // To enable the timestamp histogram, enter this before opening the stream:
39 // adb root
40 // adb shell setprop aaudio.log_mask 1
41 // A histogram of the lateness of the timestamps will be cleared when the stream is started.
42 // It will be updated when the model is stable and receives a timestamp,
43 // and dumped to the log when the stream is stopped.
44
IsochronousClockModel()45 IsochronousClockModel::IsochronousClockModel()
46 : mLatenessForDriftNanos(kInitialLatenessForDriftNanos)
47 {
48 if ((AAudioProperty_getLogMask() & AAUDIO_LOG_CLOCK_MODEL_HISTOGRAM) != 0) {
49 mHistogramMicros = std::make_unique<Histogram>(kHistogramBinCount,
50 kHistogramBinWidthMicros);
51 }
52 }
53
setPositionAndTime(int64_t framePosition,int64_t nanoTime)54 void IsochronousClockModel::setPositionAndTime(int64_t framePosition, int64_t nanoTime) {
55 ALOGV("setPositionAndTime, %lld, %lld", (long long) framePosition, (long long) nanoTime);
56 mMarkerFramePosition = framePosition;
57 mMarkerNanoTime = nanoTime;
58 }
59
start(int64_t nanoTime)60 void IsochronousClockModel::start(int64_t nanoTime) {
61 ALOGV("start(nanos = %lld)\n", (long long) nanoTime);
62 mMarkerNanoTime = nanoTime;
63 mState = STATE_STARTING;
64 if (mHistogramMicros) {
65 mHistogramMicros->clear();
66 }
67 }
68
stop(int64_t nanoTime)69 void IsochronousClockModel::stop(int64_t nanoTime) {
70 ALOGD("stop(nanos = %lld) max lateness = %d micros\n",
71 (long long) nanoTime,
72 (int) (mMaxMeasuredLatenessNanos / 1000));
73 setPositionAndTime(convertTimeToPosition(nanoTime), nanoTime);
74 // TODO should we set position?
75 mState = STATE_STOPPED;
76 if (mHistogramMicros) {
77 dumpHistogram();
78 }
79 }
80
isStarting() const81 bool IsochronousClockModel::isStarting() const {
82 return mState == STATE_STARTING;
83 }
84
isRunning() const85 bool IsochronousClockModel::isRunning() const {
86 return mState == STATE_RUNNING;
87 }
88
processTimestamp(int64_t framePosition,int64_t nanoTime)89 void IsochronousClockModel::processTimestamp(int64_t framePosition, int64_t nanoTime) {
90 mTimestampCount++;
91 // Log position and time in CSV format so we can import it easily into spreadsheets.
92 //ALOGD("%s() CSV, %d, %lld, %lld", __func__,
93 //mTimestampCount, (long long)framePosition, (long long)nanoTime);
94 int64_t framesDelta = framePosition - mMarkerFramePosition;
95 int64_t nanosDelta = nanoTime - mMarkerNanoTime;
96 if (nanosDelta < 1000) {
97 return;
98 }
99
100 // ALOGD("processTimestamp() - mMarkerFramePosition = %lld at mMarkerNanoTime %llu",
101 // (long long)mMarkerFramePosition,
102 // (long long)mMarkerNanoTime);
103
104 int64_t expectedNanosDelta = convertDeltaPositionToTime(framesDelta);
105 // ALOGD("processTimestamp() - expectedNanosDelta = %lld, nanosDelta = %llu",
106 // (long long)expectedNanosDelta,
107 // (long long)nanosDelta);
108
109 // ALOGD("processTimestamp() - mSampleRate = %d", mSampleRate);
110 // ALOGD("processTimestamp() - mState = %d", mState);
111 int64_t latenessNanos = nanosDelta - expectedNanosDelta;
112 switch (mState) {
113 case STATE_STOPPED:
114 break;
115 case STATE_STARTING:
116 setPositionAndTime(framePosition, nanoTime);
117 mState = STATE_SYNCING;
118 break;
119 case STATE_SYNCING:
120 // This will handle a burst of rapid transfer at the beginning.
121 if (latenessNanos < 0) {
122 setPositionAndTime(framePosition, nanoTime);
123 } else {
124 // ALOGD("processTimestamp() - advance to STATE_RUNNING");
125 mState = STATE_RUNNING;
126 }
127 break;
128 case STATE_RUNNING:
129 if (mHistogramMicros) {
130 mHistogramMicros->add(latenessNanos / AAUDIO_NANOS_PER_MICROSECOND);
131 }
132 // Modify estimated position based on lateness.
133 // This affects the "early" side of the window, which controls output glitches.
134 if (latenessNanos < 0) {
135 // Earlier than expected timestamp.
136 // This data is probably more accurate, so use it.
137 // Or we may be drifting due to a fast HW clock.
138 setPositionAndTime(framePosition, nanoTime);
139 #if ICM_LOG_DRIFT
140 int earlyDeltaMicros = (int) ((expectedNanosDelta - nanosDelta)/ 1000);
141 ALOGD("%s() - STATE_RUNNING - #%d, %4d micros EARLY",
142 __func__, mTimestampCount, earlyDeltaMicros);
143 #endif
144 } else if (latenessNanos > mLatenessForDriftNanos) {
145 // When we are on the late side, it may be because of preemption in the kernel,
146 // or timing jitter caused by resampling in the DSP,
147 // or we may be drifting due to a slow HW clock.
148 // We add slight drift value just in case there is actual long term drift
149 // forward caused by a slower clock.
150 // If the clock is faster than the model will get pushed earlier
151 // by the code in the earlier branch.
152 // The two opposing forces should allow the model to track the real clock
153 // over a long time.
154 int64_t driftingTime = mMarkerNanoTime + expectedNanosDelta + kDriftNanos;
155 setPositionAndTime(framePosition, driftingTime);
156 #if ICM_LOG_DRIFT
157 ALOGD("%s() - STATE_RUNNING - #%d, DRIFT, lateness = %d micros",
158 __func__,
159 mTimestampCount,
160 (int) (latenessNanos / 1000));
161 #endif
162 }
163
164 // Modify mMaxMeasuredLatenessNanos.
165 // This affects the "late" side of the window, which controls input glitches.
166 if (latenessNanos > mMaxMeasuredLatenessNanos) { // increase
167 #if ICM_LOG_DRIFT
168 ALOGD("%s() - STATE_RUNNING - #%d, newmax %d - oldmax %d = %4d micros LATE",
169 __func__,
170 mTimestampCount,
171 (int) (latenessNanos / 1000),
172 mMaxMeasuredLatenessNanos / 1000,
173 (int) ((latenessNanos - mMaxMeasuredLatenessNanos) / 1000)
174 );
175 #endif
176 mMaxMeasuredLatenessNanos = (int32_t) latenessNanos;
177 // Calculate upper region that will trigger a drift forwards.
178 mLatenessForDriftNanos = mMaxMeasuredLatenessNanos - (mMaxMeasuredLatenessNanos >> 4);
179 } else { // decrease
180 // If this is an outlier in lateness then mMaxMeasuredLatenessNanos can go high
181 // and stay there. So we slowly reduce mMaxMeasuredLatenessNanos for better
182 // long term stability. The two opposing forces will keep mMaxMeasuredLatenessNanos
183 // within a reasonable range.
184 mMaxMeasuredLatenessNanos -= kDriftNanos;
185 }
186 break;
187 default:
188 break;
189 }
190 }
191
setSampleRate(int32_t sampleRate)192 void IsochronousClockModel::setSampleRate(int32_t sampleRate) {
193 mSampleRate = sampleRate;
194 update();
195 }
196
setFramesPerBurst(int32_t framesPerBurst)197 void IsochronousClockModel::setFramesPerBurst(int32_t framesPerBurst) {
198 mFramesPerBurst = framesPerBurst;
199 update();
200 }
201
202 // Update expected lateness based on sampleRate and framesPerBurst
update()203 void IsochronousClockModel::update() {
204 mBurstPeriodNanos = convertDeltaPositionToTime(mFramesPerBurst); // uses mSampleRate
205 }
206
convertDeltaPositionToTime(int64_t framesDelta) const207 int64_t IsochronousClockModel::convertDeltaPositionToTime(int64_t framesDelta) const {
208 return (AAUDIO_NANOS_PER_SECOND * framesDelta) / mSampleRate;
209 }
210
convertDeltaTimeToPosition(int64_t nanosDelta) const211 int64_t IsochronousClockModel::convertDeltaTimeToPosition(int64_t nanosDelta) const {
212 return (mSampleRate * nanosDelta) / AAUDIO_NANOS_PER_SECOND;
213 }
214
convertPositionToTime(int64_t framePosition) const215 int64_t IsochronousClockModel::convertPositionToTime(int64_t framePosition) const {
216 if (mState == STATE_STOPPED) {
217 return mMarkerNanoTime;
218 }
219 int64_t nextBurstIndex = (framePosition + mFramesPerBurst - 1) / mFramesPerBurst;
220 int64_t nextBurstPosition = mFramesPerBurst * nextBurstIndex;
221 int64_t framesDelta = nextBurstPosition - mMarkerFramePosition;
222 int64_t nanosDelta = convertDeltaPositionToTime(framesDelta);
223 int64_t time = mMarkerNanoTime + nanosDelta;
224 // ALOGD("convertPositionToTime: pos = %llu --> time = %llu",
225 // (unsigned long long)framePosition,
226 // (unsigned long long)time);
227 return time;
228 }
229
convertTimeToPosition(int64_t nanoTime) const230 int64_t IsochronousClockModel::convertTimeToPosition(int64_t nanoTime) const {
231 if (mState == STATE_STOPPED) {
232 return mMarkerFramePosition;
233 }
234 int64_t nanosDelta = nanoTime - mMarkerNanoTime;
235 int64_t framesDelta = convertDeltaTimeToPosition(nanosDelta);
236 int64_t nextBurstPosition = mMarkerFramePosition + framesDelta;
237 int64_t nextBurstIndex = nextBurstPosition / mFramesPerBurst;
238 int64_t position = nextBurstIndex * mFramesPerBurst;
239 // ALOGD("convertTimeToPosition: time = %llu --> pos = %llu",
240 // (unsigned long long)nanoTime,
241 // (unsigned long long)position);
242 // ALOGD("convertTimeToPosition: framesDelta = %llu, mFramesPerBurst = %d",
243 // (long long) framesDelta, mFramesPerBurst);
244 return position;
245 }
246
getLateTimeOffsetNanos() const247 int32_t IsochronousClockModel::getLateTimeOffsetNanos() const {
248 return mMaxMeasuredLatenessNanos + kExtraLatenessNanos;
249 }
250
convertPositionToLatestTime(int64_t framePosition) const251 int64_t IsochronousClockModel::convertPositionToLatestTime(int64_t framePosition) const {
252 return convertPositionToTime(framePosition) + getLateTimeOffsetNanos();
253 }
254
convertLatestTimeToPosition(int64_t nanoTime) const255 int64_t IsochronousClockModel::convertLatestTimeToPosition(int64_t nanoTime) const {
256 return convertTimeToPosition(nanoTime - getLateTimeOffsetNanos());
257 }
258
dump() const259 void IsochronousClockModel::dump() const {
260 ALOGD("mMarkerFramePosition = %" PRIu64, mMarkerFramePosition);
261 ALOGD("mMarkerNanoTime = %" PRIu64, mMarkerNanoTime);
262 ALOGD("mSampleRate = %6d", mSampleRate);
263 ALOGD("mFramesPerBurst = %6d", mFramesPerBurst);
264 ALOGD("mMaxMeasuredLatenessNanos = %6d", mMaxMeasuredLatenessNanos);
265 ALOGD("mState = %6d", mState);
266 }
267
dumpHistogram() const268 void IsochronousClockModel::dumpHistogram() const {
269 if (!mHistogramMicros) return;
270 std::istringstream istr(mHistogramMicros->dump());
271 std::string line;
272 while (std::getline(istr, line)) {
273 ALOGD("lateness, %s", line.c_str());
274 }
275 }
276