1 /*
2 * Copyright (C) 2012 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 "MonoPipe"
18 //#define LOG_NDEBUG 0
19
20 #include <common_time/cc_helper.h>
21 #include <cutils/atomic.h>
22 #include <cutils/compiler.h>
23 #include <utils/LinearTransform.h>
24 #include <utils/Log.h>
25 #include <utils/Trace.h>
26 #include <media/AudioBufferProvider.h>
27 #include <media/nbaio/MonoPipe.h>
28 #include <media/nbaio/roundup.h>
29
30
31 namespace android {
32
MonoPipe(size_t reqFrames,NBAIO_Format format,bool writeCanBlock)33 MonoPipe::MonoPipe(size_t reqFrames, NBAIO_Format format, bool writeCanBlock) :
34 NBAIO_Sink(format),
35 mUpdateSeq(0),
36 mReqFrames(reqFrames),
37 mMaxFrames(roundup(reqFrames)),
38 mBuffer(malloc(mMaxFrames * Format_frameSize(format))),
39 mFront(0),
40 mRear(0),
41 mWriteTsValid(false),
42 // mWriteTs
43 mSetpoint((reqFrames * 11) / 16),
44 mWriteCanBlock(writeCanBlock),
45 mIsShutdown(false),
46 // mTimestampShared
47 mTimestampMutator(&mTimestampShared),
48 mTimestampObserver(&mTimestampShared)
49 {
50 CCHelper tmpHelper;
51 status_t res;
52 uint64_t N, D;
53
54 mNextRdPTS = AudioBufferProvider::kInvalidPTS;
55
56 mSamplesToLocalTime.a_zero = 0;
57 mSamplesToLocalTime.b_zero = 0;
58 mSamplesToLocalTime.a_to_b_numer = 0;
59 mSamplesToLocalTime.a_to_b_denom = 0;
60
61 D = Format_sampleRate(format);
62 if (OK != (res = tmpHelper.getLocalFreq(&N))) {
63 ALOGE("Failed to fetch local time frequency when constructing a"
64 " MonoPipe (res = %d). getNextWriteTimestamp calls will be"
65 " non-functional", res);
66 return;
67 }
68
69 LinearTransform::reduce(&N, &D);
70 static const uint64_t kSignedHiBitsMask = ~(0x7FFFFFFFull);
71 static const uint64_t kUnsignedHiBitsMask = ~(0xFFFFFFFFull);
72 if ((N & kSignedHiBitsMask) || (D & kUnsignedHiBitsMask)) {
73 ALOGE("Cannot reduce sample rate to local clock frequency ratio to fit"
74 " in a 32/32 bit rational. (max reduction is 0x%016llx/0x%016llx"
75 "). getNextWriteTimestamp calls will be non-functional", N, D);
76 return;
77 }
78
79 mSamplesToLocalTime.a_to_b_numer = static_cast<int32_t>(N);
80 mSamplesToLocalTime.a_to_b_denom = static_cast<uint32_t>(D);
81 }
82
~MonoPipe()83 MonoPipe::~MonoPipe()
84 {
85 free(mBuffer);
86 }
87
availableToWrite() const88 ssize_t MonoPipe::availableToWrite() const
89 {
90 if (CC_UNLIKELY(!mNegotiated)) {
91 return NEGOTIATE;
92 }
93 // uses mMaxFrames not mReqFrames, so allows "over-filling" the pipe beyond requested limit
94 ssize_t ret = mMaxFrames - (mRear - android_atomic_acquire_load(&mFront));
95 ALOG_ASSERT((0 <= ret) && (ret <= mMaxFrames));
96 return ret;
97 }
98
write(const void * buffer,size_t count)99 ssize_t MonoPipe::write(const void *buffer, size_t count)
100 {
101 if (CC_UNLIKELY(!mNegotiated)) {
102 return NEGOTIATE;
103 }
104 size_t totalFramesWritten = 0;
105 while (count > 0) {
106 // can't return a negative value, as we already checked for !mNegotiated
107 size_t avail = availableToWrite();
108 size_t written = avail;
109 if (CC_LIKELY(written > count)) {
110 written = count;
111 }
112 size_t rear = mRear & (mMaxFrames - 1);
113 size_t part1 = mMaxFrames - rear;
114 if (part1 > written) {
115 part1 = written;
116 }
117 if (CC_LIKELY(part1 > 0)) {
118 memcpy((char *) mBuffer + (rear << mBitShift), buffer, part1 << mBitShift);
119 if (CC_UNLIKELY(rear + part1 == mMaxFrames)) {
120 size_t part2 = written - part1;
121 if (CC_LIKELY(part2 > 0)) {
122 memcpy(mBuffer, (char *) buffer + (part1 << mBitShift), part2 << mBitShift);
123 }
124 }
125 android_atomic_release_store(written + mRear, &mRear);
126 totalFramesWritten += written;
127 }
128 if (!mWriteCanBlock || mIsShutdown) {
129 break;
130 }
131 count -= written;
132 buffer = (char *) buffer + (written << mBitShift);
133 // Simulate blocking I/O by sleeping at different rates, depending on a throttle.
134 // The throttle tries to keep the mean pipe depth near the setpoint, with a slight jitter.
135 uint32_t ns;
136 if (written > 0) {
137 size_t filled = (mMaxFrames - avail) + written;
138 // FIXME cache these values to avoid re-computation
139 if (filled <= mSetpoint / 2) {
140 // pipe is (nearly) empty, fill quickly
141 ns = written * ( 500000000 / Format_sampleRate(mFormat));
142 } else if (filled <= (mSetpoint * 3) / 4) {
143 // pipe is below setpoint, fill at slightly faster rate
144 ns = written * ( 750000000 / Format_sampleRate(mFormat));
145 } else if (filled <= (mSetpoint * 5) / 4) {
146 // pipe is at setpoint, fill at nominal rate
147 ns = written * (1000000000 / Format_sampleRate(mFormat));
148 } else if (filled <= (mSetpoint * 3) / 2) {
149 // pipe is above setpoint, fill at slightly slower rate
150 ns = written * (1150000000 / Format_sampleRate(mFormat));
151 } else if (filled <= (mSetpoint * 7) / 4) {
152 // pipe is overflowing, fill slowly
153 ns = written * (1350000000 / Format_sampleRate(mFormat));
154 } else {
155 // pipe is severely overflowing
156 ns = written * (1750000000 / Format_sampleRate(mFormat));
157 }
158 } else {
159 ns = count * (1350000000 / Format_sampleRate(mFormat));
160 }
161 if (ns > 999999999) {
162 ns = 999999999;
163 }
164 struct timespec nowTs;
165 bool nowTsValid = !clock_gettime(CLOCK_MONOTONIC, &nowTs);
166 // deduct the elapsed time since previous write() completed
167 if (nowTsValid && mWriteTsValid) {
168 time_t sec = nowTs.tv_sec - mWriteTs.tv_sec;
169 long nsec = nowTs.tv_nsec - mWriteTs.tv_nsec;
170 ALOGE_IF(sec < 0 || (sec == 0 && nsec < 0),
171 "clock_gettime(CLOCK_MONOTONIC) failed: was %ld.%09ld but now %ld.%09ld",
172 mWriteTs.tv_sec, mWriteTs.tv_nsec, nowTs.tv_sec, nowTs.tv_nsec);
173 if (nsec < 0) {
174 --sec;
175 nsec += 1000000000;
176 }
177 if (sec == 0) {
178 if ((long) ns > nsec) {
179 ns -= nsec;
180 } else {
181 ns = 0;
182 }
183 }
184 }
185 if (ns > 0) {
186 const struct timespec req = {0, ns};
187 nanosleep(&req, NULL);
188 }
189 // record the time that this write() completed
190 if (nowTsValid) {
191 mWriteTs = nowTs;
192 if ((mWriteTs.tv_nsec += ns) >= 1000000000) {
193 mWriteTs.tv_nsec -= 1000000000;
194 ++mWriteTs.tv_sec;
195 }
196 }
197 mWriteTsValid = nowTsValid;
198 }
199 mFramesWritten += totalFramesWritten;
200 return totalFramesWritten;
201 }
202
setAvgFrames(size_t setpoint)203 void MonoPipe::setAvgFrames(size_t setpoint)
204 {
205 mSetpoint = setpoint;
206 }
207
getNextWriteTimestamp(int64_t * timestamp)208 status_t MonoPipe::getNextWriteTimestamp(int64_t *timestamp)
209 {
210 int32_t front;
211
212 ALOG_ASSERT(NULL != timestamp);
213
214 if (0 == mSamplesToLocalTime.a_to_b_denom)
215 return UNKNOWN_ERROR;
216
217 observeFrontAndNRPTS(&front, timestamp);
218
219 if (AudioBufferProvider::kInvalidPTS != *timestamp) {
220 // If we have a valid read-pointer and next read timestamp pair, then
221 // use the current value of the write pointer to figure out how many
222 // frames are in the buffer, and offset the timestamp by that amt. Then
223 // next time we write to the MonoPipe, the data will hit the speakers at
224 // the next read timestamp plus the current amount of data in the
225 // MonoPipe.
226 size_t pendingFrames = (mRear - front) & (mMaxFrames - 1);
227 *timestamp = offsetTimestampByAudioFrames(*timestamp, pendingFrames);
228 }
229
230 return OK;
231 }
232
updateFrontAndNRPTS(int32_t newFront,int64_t newNextRdPTS)233 void MonoPipe::updateFrontAndNRPTS(int32_t newFront, int64_t newNextRdPTS)
234 {
235 // Set the MSB of the update sequence number to indicate that there is a
236 // multi-variable update in progress. Use an atomic store with an "acquire"
237 // barrier to make sure that the next operations cannot be re-ordered and
238 // take place before the change to mUpdateSeq is commited..
239 int32_t tmp = mUpdateSeq | 0x80000000;
240 android_atomic_acquire_store(tmp, &mUpdateSeq);
241
242 // Update mFront and mNextRdPTS
243 mFront = newFront;
244 mNextRdPTS = newNextRdPTS;
245
246 // We are finished with the update. Compute the next sequnce number (which
247 // should be the old sequence number, plus one, and with the MSB cleared)
248 // and then store it in mUpdateSeq using an atomic store with a "release"
249 // barrier so our update operations cannot be re-ordered past the update of
250 // the sequence number.
251 tmp = (tmp + 1) & 0x7FFFFFFF;
252 android_atomic_release_store(tmp, &mUpdateSeq);
253 }
254
observeFrontAndNRPTS(int32_t * outFront,int64_t * outNextRdPTS)255 void MonoPipe::observeFrontAndNRPTS(int32_t *outFront, int64_t *outNextRdPTS)
256 {
257 // Perform an atomic observation of mFront and mNextRdPTS. Basically,
258 // atomically observe the sequence number, then observer the variables, then
259 // atomically observe the sequence number again. If the two observations of
260 // the sequence number match, and the update-in-progress bit was not set,
261 // then we know we have a successful atomic observation. Otherwise, we loop
262 // around and try again.
263 //
264 // Note, it is very important that the observer be a lower priority thread
265 // than the updater. If the updater is lower than the observer, or they are
266 // the same priority and running with SCHED_FIFO (implying that quantum
267 // based premption is disabled) then we run the risk of deadlock.
268 int32_t seqOne, seqTwo;
269
270 do {
271 seqOne = android_atomic_acquire_load(&mUpdateSeq);
272 *outFront = mFront;
273 *outNextRdPTS = mNextRdPTS;
274 seqTwo = android_atomic_release_load(&mUpdateSeq);
275 } while ((seqOne != seqTwo) || (seqOne & 0x80000000));
276 }
277
offsetTimestampByAudioFrames(int64_t ts,size_t audFrames)278 int64_t MonoPipe::offsetTimestampByAudioFrames(int64_t ts, size_t audFrames)
279 {
280 if (0 == mSamplesToLocalTime.a_to_b_denom)
281 return AudioBufferProvider::kInvalidPTS;
282
283 if (ts == AudioBufferProvider::kInvalidPTS)
284 return AudioBufferProvider::kInvalidPTS;
285
286 int64_t frame_lt_duration;
287 if (!mSamplesToLocalTime.doForwardTransform(audFrames,
288 &frame_lt_duration)) {
289 // This should never fail, but if there is a bug which is causing it
290 // to fail, this message would probably end up flooding the logs
291 // because the conversion would probably fail forever. Log the
292 // error, but then zero out the ratio in the linear transform so
293 // that we don't try to do any conversions from now on. This
294 // MonoPipe's getNextWriteTimestamp is now broken for good.
295 ALOGE("Overflow when attempting to convert %d audio frames to"
296 " duration in local time. getNextWriteTimestamp will fail from"
297 " now on.", audFrames);
298 mSamplesToLocalTime.a_to_b_numer = 0;
299 mSamplesToLocalTime.a_to_b_denom = 0;
300 return AudioBufferProvider::kInvalidPTS;
301 }
302
303 return ts + frame_lt_duration;
304 }
305
shutdown(bool newState)306 void MonoPipe::shutdown(bool newState)
307 {
308 mIsShutdown = newState;
309 }
310
isShutdown()311 bool MonoPipe::isShutdown()
312 {
313 return mIsShutdown;
314 }
315
getTimestamp(AudioTimestamp & timestamp)316 status_t MonoPipe::getTimestamp(AudioTimestamp& timestamp)
317 {
318 if (mTimestampObserver.poll(timestamp)) {
319 return OK;
320 }
321 return INVALID_OPERATION;
322 }
323
324 } // namespace android
325