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