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