blob: 724ce380aaba6e5799e8aa0fab74a014efb2caf1 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <cutils/compiler.h>
24#include <utils/Log.h>
25
26#include <private/media/AudioTrackShared.h>
27
28#include <common_time/cc_helper.h>
29#include <common_time/local_clock.h>
30
31#include "AudioMixer.h"
32#include "AudioFlinger.h"
33#include "ServiceUtilities.h"
34
Glenn Kastenda6ef132013-01-10 12:31:01 -080035#include <media/nbaio/Pipe.h>
36#include <media/nbaio/PipeReader.h>
37
Eric Laurent81784c32012-11-19 14:55:58 -080038// ----------------------------------------------------------------------------
39
40// Note: the following macro is used for extremely verbose logging message. In
41// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
42// 0; but one side effect of this is to turn all LOGV's as well. Some messages
43// are so verbose that we want to suppress them even when we have ALOG_ASSERT
44// turned on. Do not uncomment the #def below unless you really know what you
45// are doing and want to see all of the extremely verbose messages.
46//#define VERY_VERY_VERBOSE_LOGGING
47#ifdef VERY_VERY_VERBOSE_LOGGING
48#define ALOGVV ALOGV
49#else
50#define ALOGVV(a...) do { } while(0)
51#endif
52
53namespace android {
54
55// ----------------------------------------------------------------------------
56// TrackBase
57// ----------------------------------------------------------------------------
58
Glenn Kastenda6ef132013-01-10 12:31:01 -080059static volatile int32_t nextTrackId = 55;
60
Eric Laurent81784c32012-11-19 14:55:58 -080061// TrackBase constructor must be called with AudioFlinger::mLock held
62AudioFlinger::ThreadBase::TrackBase::TrackBase(
63 ThreadBase *thread,
64 const sp<Client>& client,
65 uint32_t sampleRate,
66 audio_format_t format,
67 audio_channel_mask_t channelMask,
68 size_t frameCount,
69 const sp<IMemory>& sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080070 int sessionId,
71 bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -080072 : RefBase(),
73 mThread(thread),
74 mClient(client),
75 mCblk(NULL),
76 // mBuffer
77 // mBufferEnd
78 mStepCount(0),
79 mState(IDLE),
80 mSampleRate(sampleRate),
81 mFormat(format),
82 mChannelMask(channelMask),
83 mChannelCount(popcount(channelMask)),
84 mFrameSize(audio_is_linear_pcm(format) ?
85 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
86 mFrameCount(frameCount),
87 mStepServerFailed(false),
Glenn Kastene3aa6592012-12-04 12:22:46 -080088 mSessionId(sessionId),
89 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080090 mServerProxy(NULL),
91 mId(android_atomic_inc(&nextTrackId))
Eric Laurent81784c32012-11-19 14:55:58 -080092{
93 // client == 0 implies sharedBuffer == 0
94 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
95
96 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
97 sharedBuffer->size());
98
99 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
100 size_t size = sizeof(audio_track_cblk_t);
101 size_t bufferSize = frameCount * mFrameSize;
102 if (sharedBuffer == 0) {
103 size += bufferSize;
104 }
105
106 if (client != 0) {
107 mCblkMemory = client->heap()->allocate(size);
108 if (mCblkMemory != 0) {
109 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
110 // can't assume mCblk != NULL
111 } else {
112 ALOGE("not enough memory for AudioTrack size=%u", size);
113 client->heap()->dump("AudioTrack");
114 return;
115 }
116 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800117 // this syntax avoids calling the audio_track_cblk_t constructor twice
118 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800119 // assume mCblk != NULL
120 }
121
122 // construct the shared structure in-place.
123 if (mCblk != NULL) {
124 new(mCblk) audio_track_cblk_t();
125 // clear all buffers
126 mCblk->frameCount_ = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800127// uncomment the following lines to quickly test 32-bit wraparound
128// mCblk->user = 0xffff0000;
129// mCblk->server = 0xffff0000;
130// mCblk->userBase = 0xffff0000;
131// mCblk->serverBase = 0xffff0000;
132 if (sharedBuffer == 0) {
133 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
134 memset(mBuffer, 0, bufferSize);
135 // Force underrun condition to avoid false underrun callback until first data is
136 // written to buffer (other flags are cleared)
137 mCblk->flags = CBLK_UNDERRUN;
138 } else {
139 mBuffer = sharedBuffer->pointer();
140 }
141 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800142 mServerProxy = new ServerProxy(mCblk, mBuffer, frameCount, mFrameSize, isOut);
Glenn Kastenda6ef132013-01-10 12:31:01 -0800143
144 if (mTeeSinkTrackEnabled) {
145 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
146 if (pipeFormat != Format_Invalid) {
147 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
148 size_t numCounterOffers = 0;
149 const NBAIO_Format offers[1] = {pipeFormat};
150 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
151 ALOG_ASSERT(index == 0);
152 PipeReader *pipeReader = new PipeReader(*pipe);
153 numCounterOffers = 0;
154 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
155 ALOG_ASSERT(index == 0);
156 mTeeSink = pipe;
157 mTeeSource = pipeReader;
158 }
159 }
160
Eric Laurent81784c32012-11-19 14:55:58 -0800161 }
162}
163
164AudioFlinger::ThreadBase::TrackBase::~TrackBase()
165{
Glenn Kastenda6ef132013-01-10 12:31:01 -0800166 dumpTee(-1, mTeeSource, mId);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800167 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
168 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800169 if (mCblk != NULL) {
170 if (mClient == 0) {
171 delete mCblk;
172 } else {
173 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
174 }
175 }
176 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
177 if (mClient != 0) {
178 // Client destructor must run with AudioFlinger mutex locked
179 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
180 // If the client's reference count drops to zero, the associated destructor
181 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
182 // relying on the automatic clear() at end of scope.
183 mClient.clear();
184 }
185}
186
187// AudioBufferProvider interface
188// getNextBuffer() = 0;
189// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
190void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
191{
Glenn Kastenda6ef132013-01-10 12:31:01 -0800192 if (mTeeSink != 0) {
193 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
194 }
195
Eric Laurent81784c32012-11-19 14:55:58 -0800196 buffer->raw = NULL;
197 mStepCount = buffer->frameCount;
198 // FIXME See note at getNextBuffer()
199 (void) step(); // ignore return value of step()
200 buffer->frameCount = 0;
201}
202
203bool AudioFlinger::ThreadBase::TrackBase::step() {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800204 bool result = mServerProxy->step(mStepCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800205 if (!result) {
206 ALOGV("stepServer failed acquiring cblk mutex");
207 mStepServerFailed = true;
208 }
209 return result;
210}
211
212void AudioFlinger::ThreadBase::TrackBase::reset() {
213 audio_track_cblk_t* cblk = this->cblk();
214
215 cblk->user = 0;
216 cblk->server = 0;
217 cblk->userBase = 0;
218 cblk->serverBase = 0;
219 mStepServerFailed = false;
220 ALOGV("TrackBase::reset");
221}
222
223uint32_t AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800224 return mServerProxy->getSampleRate();
Eric Laurent81784c32012-11-19 14:55:58 -0800225}
226
227void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
228 audio_track_cblk_t* cblk = this->cblk();
229 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase) * mFrameSize;
230 int8_t *bufferEnd = bufferStart + frames * mFrameSize;
231
232 // Check validity of returned pointer in case the track control block would have been corrupted.
233 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
234 "TrackBase::getBuffer buffer out of range:\n"
235 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
236 " server %u, serverBase %u, user %u, userBase %u, frameSize %u",
237 bufferStart, bufferEnd, mBuffer, mBufferEnd,
238 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, mFrameSize);
239
240 return bufferStart;
241}
242
243status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
244{
245 mSyncEvents.add(event);
246 return NO_ERROR;
247}
248
249// ----------------------------------------------------------------------------
250// Playback
251// ----------------------------------------------------------------------------
252
253AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
254 : BnAudioTrack(),
255 mTrack(track)
256{
257}
258
259AudioFlinger::TrackHandle::~TrackHandle() {
260 // just stop the track on deletion, associated resources
261 // will be freed from the main thread once all pending buffers have
262 // been played. Unless it's not in the active track list, in which
263 // case we free everything now...
264 mTrack->destroy();
265}
266
267sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
268 return mTrack->getCblk();
269}
270
271status_t AudioFlinger::TrackHandle::start() {
272 return mTrack->start();
273}
274
275void AudioFlinger::TrackHandle::stop() {
276 mTrack->stop();
277}
278
279void AudioFlinger::TrackHandle::flush() {
280 mTrack->flush();
281}
282
Eric Laurent81784c32012-11-19 14:55:58 -0800283void AudioFlinger::TrackHandle::pause() {
284 mTrack->pause();
285}
286
287status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
288{
289 return mTrack->attachAuxEffect(EffectId);
290}
291
292status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
293 sp<IMemory>* buffer) {
294 if (!mTrack->isTimedTrack())
295 return INVALID_OPERATION;
296
297 PlaybackThread::TimedTrack* tt =
298 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
299 return tt->allocateTimedBuffer(size, buffer);
300}
301
302status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
303 int64_t pts) {
304 if (!mTrack->isTimedTrack())
305 return INVALID_OPERATION;
306
307 PlaybackThread::TimedTrack* tt =
308 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
309 return tt->queueTimedBuffer(buffer, pts);
310}
311
312status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
313 const LinearTransform& xform, int target) {
314
315 if (!mTrack->isTimedTrack())
316 return INVALID_OPERATION;
317
318 PlaybackThread::TimedTrack* tt =
319 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
320 return tt->setMediaTimeTransform(
321 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
322}
323
324status_t AudioFlinger::TrackHandle::onTransact(
325 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
326{
327 return BnAudioTrack::onTransact(code, data, reply, flags);
328}
329
330// ----------------------------------------------------------------------------
331
332// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
333AudioFlinger::PlaybackThread::Track::Track(
334 PlaybackThread *thread,
335 const sp<Client>& client,
336 audio_stream_type_t streamType,
337 uint32_t sampleRate,
338 audio_format_t format,
339 audio_channel_mask_t channelMask,
340 size_t frameCount,
341 const sp<IMemory>& sharedBuffer,
342 int sessionId,
343 IAudioFlinger::track_flags_t flags)
344 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -0800345 sessionId, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800346 mFillingUpStatus(FS_INVALID),
347 // mRetryCount initialized later when needed
348 mSharedBuffer(sharedBuffer),
349 mStreamType(streamType),
350 mName(-1), // see note below
351 mMainBuffer(thread->mixBuffer()),
352 mAuxBuffer(NULL),
353 mAuxEffectId(0), mHasVolumeController(false),
354 mPresentationCompleteFrames(0),
355 mFlags(flags),
356 mFastIndex(-1),
357 mUnderrunCount(0),
Glenn Kasten5736c352012-12-04 12:12:34 -0800358 mCachedVolume(1.0),
359 mIsInvalid(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800360{
361 if (mCblk != NULL) {
362 // to avoid leaking a track name, do not allocate one unless there is an mCblk
363 mName = thread->getTrackName_l(channelMask, sessionId);
364 mCblk->mName = mName;
365 if (mName < 0) {
366 ALOGE("no more track names available");
367 return;
368 }
369 // only allocate a fast track index if we were able to allocate a normal track name
370 if (flags & IAudioFlinger::TRACK_FAST) {
371 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
372 int i = __builtin_ctz(thread->mFastTrackAvailMask);
373 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
374 // FIXME This is too eager. We allocate a fast track index before the
375 // fast track becomes active. Since fast tracks are a scarce resource,
376 // this means we are potentially denying other more important fast tracks from
377 // being created. It would be better to allocate the index dynamically.
378 mFastIndex = i;
379 mCblk->mName = i;
380 // Read the initial underruns because this field is never cleared by the fast mixer
381 mObservedUnderruns = thread->getFastTrackUnderruns(i);
382 thread->mFastTrackAvailMask &= ~(1 << i);
383 }
384 }
385 ALOGV("Track constructor name %d, calling pid %d", mName,
386 IPCThreadState::self()->getCallingPid());
387}
388
389AudioFlinger::PlaybackThread::Track::~Track()
390{
391 ALOGV("PlaybackThread::Track destructor");
392}
393
394void AudioFlinger::PlaybackThread::Track::destroy()
395{
396 // NOTE: destroyTrack_l() can remove a strong reference to this Track
397 // by removing it from mTracks vector, so there is a risk that this Tracks's
398 // destructor is called. As the destructor needs to lock mLock,
399 // we must acquire a strong reference on this Track before locking mLock
400 // here so that the destructor is called only when exiting this function.
401 // On the other hand, as long as Track::destroy() is only called by
402 // TrackHandle destructor, the TrackHandle still holds a strong ref on
403 // this Track with its member mTrack.
404 sp<Track> keep(this);
405 { // scope for mLock
406 sp<ThreadBase> thread = mThread.promote();
407 if (thread != 0) {
408 if (!isOutputTrack()) {
409 if (mState == ACTIVE || mState == RESUMING) {
410 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
411
412#ifdef ADD_BATTERY_DATA
413 // to track the speaker usage
414 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
415#endif
416 }
417 AudioSystem::releaseOutput(thread->id());
418 }
419 Mutex::Autolock _l(thread->mLock);
420 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
421 playbackThread->destroyTrack_l(this);
422 }
423 }
424}
425
426/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
427{
Glenn Kastene4756fe2012-11-29 13:38:14 -0800428 result.append(" Name Client Type Fmt Chn mask Session StpCnt fCount S F SRate "
Eric Laurent81784c32012-11-19 14:55:58 -0800429 "L dB R dB Server User Main buf Aux Buf Flags Underruns\n");
430}
431
432void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
433{
Glenn Kastene3aa6592012-12-04 12:22:46 -0800434 uint32_t vlr = mServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800435 if (isFastTrack()) {
436 sprintf(buffer, " F %2d", mFastIndex);
437 } else {
438 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
439 }
440 track_state state = mState;
441 char stateChar;
442 switch (state) {
443 case IDLE:
444 stateChar = 'I';
445 break;
446 case TERMINATED:
447 stateChar = 'T';
448 break;
449 case STOPPING_1:
450 stateChar = 's';
451 break;
452 case STOPPING_2:
453 stateChar = '5';
454 break;
455 case STOPPED:
456 stateChar = 'S';
457 break;
458 case RESUMING:
459 stateChar = 'R';
460 break;
461 case ACTIVE:
462 stateChar = 'A';
463 break;
464 case PAUSING:
465 stateChar = 'p';
466 break;
467 case PAUSED:
468 stateChar = 'P';
469 break;
470 case FLUSHED:
471 stateChar = 'F';
472 break;
473 default:
474 stateChar = '?';
475 break;
476 }
477 char nowInUnderrun;
478 switch (mObservedUnderruns.mBitFields.mMostRecent) {
479 case UNDERRUN_FULL:
480 nowInUnderrun = ' ';
481 break;
482 case UNDERRUN_PARTIAL:
483 nowInUnderrun = '<';
484 break;
485 case UNDERRUN_EMPTY:
486 nowInUnderrun = '*';
487 break;
488 default:
489 nowInUnderrun = '?';
490 break;
491 }
Glenn Kastene4756fe2012-11-29 13:38:14 -0800492 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %5u %5.2g %5.2g "
Eric Laurent81784c32012-11-19 14:55:58 -0800493 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
494 (mClient == 0) ? getpid_cached : mClient->pid(),
495 mStreamType,
496 mFormat,
497 mChannelMask,
498 mSessionId,
499 mStepCount,
500 mFrameCount,
501 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800502 mFillingUpStatus,
Glenn Kastene3aa6592012-12-04 12:22:46 -0800503 mServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800504 20.0 * log10((vlr & 0xFFFF) / 4096.0),
505 20.0 * log10((vlr >> 16) / 4096.0),
506 mCblk->server,
507 mCblk->user,
508 (int)mMainBuffer,
509 (int)mAuxBuffer,
510 mCblk->flags,
511 mUnderrunCount,
512 nowInUnderrun);
513}
514
515// AudioBufferProvider interface
516status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
517 AudioBufferProvider::Buffer* buffer, int64_t pts)
518{
519 audio_track_cblk_t* cblk = this->cblk();
520 uint32_t framesReady;
521 uint32_t framesReq = buffer->frameCount;
522
523 // Check if last stepServer failed, try to step now
524 if (mStepServerFailed) {
525 // FIXME When called by fast mixer, this takes a mutex with tryLock().
526 // Since the fast mixer is higher priority than client callback thread,
527 // it does not result in priority inversion for client.
528 // But a non-blocking solution would be preferable to avoid
529 // fast mixer being unable to tryLock(), and
530 // to avoid the extra context switches if the client wakes up,
531 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
532 if (!step()) goto getNextBuffer_exit;
533 ALOGV("stepServer recovered");
534 mStepServerFailed = false;
535 }
536
537 // FIXME Same as above
Glenn Kastene3aa6592012-12-04 12:22:46 -0800538 framesReady = mServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800539
540 if (CC_LIKELY(framesReady)) {
541 uint32_t s = cblk->server;
542 uint32_t bufferEnd = cblk->serverBase + mFrameCount;
543
544 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
545 if (framesReq > framesReady) {
546 framesReq = framesReady;
547 }
548 if (framesReq > bufferEnd - s) {
549 framesReq = bufferEnd - s;
550 }
551
552 buffer->raw = getBuffer(s, framesReq);
553 buffer->frameCount = framesReq;
554 return NO_ERROR;
555 }
556
557getNextBuffer_exit:
558 buffer->raw = NULL;
559 buffer->frameCount = 0;
560 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
561 return NOT_ENOUGH_DATA;
562}
563
564// Note that framesReady() takes a mutex on the control block using tryLock().
565// This could result in priority inversion if framesReady() is called by the normal mixer,
566// as the normal mixer thread runs at lower
567// priority than the client's callback thread: there is a short window within framesReady()
568// during which the normal mixer could be preempted, and the client callback would block.
569// Another problem can occur if framesReady() is called by the fast mixer:
570// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
571// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
572size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800573 return mServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800574}
575
576// Don't call for fast tracks; the framesReady() could result in priority inversion
577bool AudioFlinger::PlaybackThread::Track::isReady() const {
578 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
579 return true;
580 }
581
582 if (framesReady() >= mFrameCount ||
583 (mCblk->flags & CBLK_FORCEREADY)) {
584 mFillingUpStatus = FS_FILLED;
585 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
586 return true;
587 }
588 return false;
589}
590
591status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
592 int triggerSession)
593{
594 status_t status = NO_ERROR;
595 ALOGV("start(%d), calling pid %d session %d",
596 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
597
598 sp<ThreadBase> thread = mThread.promote();
599 if (thread != 0) {
600 Mutex::Autolock _l(thread->mLock);
Glenn Kasten7f5d3352013-02-15 23:55:04 +0000601 thread->mNBLogWriter->logf("start mName=%d", mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800602 track_state state = mState;
603 // here the track could be either new, or restarted
604 // in both cases "unstop" the track
605 if (mState == PAUSED) {
606 mState = TrackBase::RESUMING;
607 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
608 } else {
609 mState = TrackBase::ACTIVE;
610 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
611 }
612
613 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
614 thread->mLock.unlock();
615 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
616 thread->mLock.lock();
617
618#ifdef ADD_BATTERY_DATA
619 // to track the speaker usage
620 if (status == NO_ERROR) {
621 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
622 }
623#endif
624 }
625 if (status == NO_ERROR) {
626 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
627 playbackThread->addTrack_l(this);
628 } else {
629 mState = state;
630 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
631 }
632 } else {
633 status = BAD_VALUE;
634 }
635 return status;
636}
637
638void AudioFlinger::PlaybackThread::Track::stop()
639{
640 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
641 sp<ThreadBase> thread = mThread.promote();
642 if (thread != 0) {
643 Mutex::Autolock _l(thread->mLock);
Glenn Kasten7f5d3352013-02-15 23:55:04 +0000644 thread->mNBLogWriter->logf("stop mName=%d", mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800645 track_state state = mState;
646 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
647 // If the track is not active (PAUSED and buffers full), flush buffers
648 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
649 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
650 reset();
651 mState = STOPPED;
652 } else if (!isFastTrack()) {
653 mState = STOPPED;
654 } else {
655 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
656 // and then to STOPPED and reset() when presentation is complete
657 mState = STOPPING_1;
658 }
659 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
660 playbackThread);
661 }
662 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
663 thread->mLock.unlock();
664 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
665 thread->mLock.lock();
666
667#ifdef ADD_BATTERY_DATA
668 // to track the speaker usage
669 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
670#endif
671 }
672 }
673}
674
675void AudioFlinger::PlaybackThread::Track::pause()
676{
677 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
678 sp<ThreadBase> thread = mThread.promote();
679 if (thread != 0) {
680 Mutex::Autolock _l(thread->mLock);
Glenn Kasten7f5d3352013-02-15 23:55:04 +0000681 thread->mNBLogWriter->logf("pause mName=%d", mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800682 if (mState == ACTIVE || mState == RESUMING) {
683 mState = PAUSING;
684 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
685 if (!isOutputTrack()) {
686 thread->mLock.unlock();
687 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
688 thread->mLock.lock();
689
690#ifdef ADD_BATTERY_DATA
691 // to track the speaker usage
692 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
693#endif
694 }
695 }
696 }
697}
698
699void AudioFlinger::PlaybackThread::Track::flush()
700{
701 ALOGV("flush(%d)", mName);
702 sp<ThreadBase> thread = mThread.promote();
703 if (thread != 0) {
704 Mutex::Autolock _l(thread->mLock);
Glenn Kasten7f5d3352013-02-15 23:55:04 +0000705 thread->mNBLogWriter->logf("flush mName=%d", mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800706 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
707 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
708 return;
709 }
710 // No point remaining in PAUSED state after a flush => go to
711 // FLUSHED state
712 mState = FLUSHED;
713 // do not reset the track if it is still in the process of being stopped or paused.
714 // this will be done by prepareTracks_l() when the track is stopped.
715 // prepareTracks_l() will see mState == FLUSHED, then
716 // remove from active track list, reset(), and trigger presentation complete
717 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
718 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
719 reset();
720 }
721 }
722}
723
724void AudioFlinger::PlaybackThread::Track::reset()
725{
726 // Do not reset twice to avoid discarding data written just after a flush and before
727 // the audioflinger thread detects the track is stopped.
728 if (!mResetDone) {
729 TrackBase::reset();
730 // Force underrun condition to avoid false underrun callback until first data is
731 // written to buffer
732 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
733 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
734 mFillingUpStatus = FS_FILLING;
735 mResetDone = true;
736 if (mState == FLUSHED) {
737 mState = IDLE;
738 }
739 }
740}
741
Eric Laurent81784c32012-11-19 14:55:58 -0800742status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
743{
744 status_t status = DEAD_OBJECT;
745 sp<ThreadBase> thread = mThread.promote();
746 if (thread != 0) {
747 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
748 sp<AudioFlinger> af = mClient->audioFlinger();
749
750 Mutex::Autolock _l(af->mLock);
751
752 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
753
754 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
755 Mutex::Autolock _dl(playbackThread->mLock);
756 Mutex::Autolock _sl(srcThread->mLock);
757 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
758 if (chain == 0) {
759 return INVALID_OPERATION;
760 }
761
762 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
763 if (effect == 0) {
764 return INVALID_OPERATION;
765 }
766 srcThread->removeEffect_l(effect);
767 playbackThread->addEffect_l(effect);
768 // removeEffect_l() has stopped the effect if it was active so it must be restarted
769 if (effect->state() == EffectModule::ACTIVE ||
770 effect->state() == EffectModule::STOPPING) {
771 effect->start();
772 }
773
774 sp<EffectChain> dstChain = effect->chain().promote();
775 if (dstChain == 0) {
776 srcThread->addEffect_l(effect);
777 return INVALID_OPERATION;
778 }
779 AudioSystem::unregisterEffect(effect->id());
780 AudioSystem::registerEffect(&effect->desc(),
781 srcThread->id(),
782 dstChain->strategy(),
783 AUDIO_SESSION_OUTPUT_MIX,
784 effect->id());
785 }
786 status = playbackThread->attachAuxEffect(this, EffectId);
787 }
788 return status;
789}
790
791void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
792{
793 mAuxEffectId = EffectId;
794 mAuxBuffer = buffer;
795}
796
797bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
798 size_t audioHalFrames)
799{
800 // a track is considered presented when the total number of frames written to audio HAL
801 // corresponds to the number of frames written when presentationComplete() is called for the
802 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
803 if (mPresentationCompleteFrames == 0) {
804 mPresentationCompleteFrames = framesWritten + audioHalFrames;
805 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
806 mPresentationCompleteFrames, audioHalFrames);
807 }
808 if (framesWritten >= mPresentationCompleteFrames) {
809 ALOGV("presentationComplete() session %d complete: framesWritten %d",
810 mSessionId, framesWritten);
811 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
812 return true;
813 }
814 return false;
815}
816
817void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
818{
819 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
820 if (mSyncEvents[i]->type() == type) {
821 mSyncEvents[i]->trigger();
822 mSyncEvents.removeAt(i);
823 i--;
824 }
825 }
826}
827
828// implement VolumeBufferProvider interface
829
830uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
831{
832 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
833 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastene3aa6592012-12-04 12:22:46 -0800834 uint32_t vlr = mServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800835 uint32_t vl = vlr & 0xFFFF;
836 uint32_t vr = vlr >> 16;
837 // track volumes come from shared memory, so can't be trusted and must be clamped
838 if (vl > MAX_GAIN_INT) {
839 vl = MAX_GAIN_INT;
840 }
841 if (vr > MAX_GAIN_INT) {
842 vr = MAX_GAIN_INT;
843 }
844 // now apply the cached master volume and stream type volume;
845 // this is trusted but lacks any synchronization or barrier so may be stale
846 float v = mCachedVolume;
847 vl *= v;
848 vr *= v;
849 // re-combine into U4.16
850 vlr = (vr << 16) | (vl & 0xFFFF);
851 // FIXME look at mute, pause, and stop flags
852 return vlr;
853}
854
855status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
856{
857 if (mState == TERMINATED || mState == PAUSED ||
858 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
859 (mState == STOPPED)))) {
860 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
861 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
862 event->cancel();
863 return INVALID_OPERATION;
864 }
865 (void) TrackBase::setSyncEvent(event);
866 return NO_ERROR;
867}
868
Glenn Kasten5736c352012-12-04 12:12:34 -0800869void AudioFlinger::PlaybackThread::Track::invalidate()
870{
871 // FIXME should use proxy
872 android_atomic_or(CBLK_INVALID, &mCblk->flags);
873 mCblk->cv.signal();
874 mIsInvalid = true;
875}
876
Eric Laurent81784c32012-11-19 14:55:58 -0800877// ----------------------------------------------------------------------------
878
879sp<AudioFlinger::PlaybackThread::TimedTrack>
880AudioFlinger::PlaybackThread::TimedTrack::create(
881 PlaybackThread *thread,
882 const sp<Client>& client,
883 audio_stream_type_t streamType,
884 uint32_t sampleRate,
885 audio_format_t format,
886 audio_channel_mask_t channelMask,
887 size_t frameCount,
888 const sp<IMemory>& sharedBuffer,
889 int sessionId) {
890 if (!client->reserveTimedTrack())
891 return 0;
892
893 return new TimedTrack(
894 thread, client, streamType, sampleRate, format, channelMask, frameCount,
895 sharedBuffer, sessionId);
896}
897
898AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
899 PlaybackThread *thread,
900 const sp<Client>& client,
901 audio_stream_type_t streamType,
902 uint32_t sampleRate,
903 audio_format_t format,
904 audio_channel_mask_t channelMask,
905 size_t frameCount,
906 const sp<IMemory>& sharedBuffer,
907 int sessionId)
908 : Track(thread, client, streamType, sampleRate, format, channelMask,
909 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
910 mQueueHeadInFlight(false),
911 mTrimQueueHeadOnRelease(false),
912 mFramesPendingInQueue(0),
913 mTimedSilenceBuffer(NULL),
914 mTimedSilenceBufferSize(0),
915 mTimedAudioOutputOnTime(false),
916 mMediaTimeTransformValid(false)
917{
918 LocalClock lc;
919 mLocalTimeFreq = lc.getLocalFreq();
920
921 mLocalTimeToSampleTransform.a_zero = 0;
922 mLocalTimeToSampleTransform.b_zero = 0;
923 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
924 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
925 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
926 &mLocalTimeToSampleTransform.a_to_b_denom);
927
928 mMediaTimeToSampleTransform.a_zero = 0;
929 mMediaTimeToSampleTransform.b_zero = 0;
930 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
931 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
932 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
933 &mMediaTimeToSampleTransform.a_to_b_denom);
934}
935
936AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
937 mClient->releaseTimedTrack();
938 delete [] mTimedSilenceBuffer;
939}
940
941status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
942 size_t size, sp<IMemory>* buffer) {
943
944 Mutex::Autolock _l(mTimedBufferQueueLock);
945
946 trimTimedBufferQueue_l();
947
948 // lazily initialize the shared memory heap for timed buffers
949 if (mTimedMemoryDealer == NULL) {
950 const int kTimedBufferHeapSize = 512 << 10;
951
952 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
953 "AudioFlingerTimed");
954 if (mTimedMemoryDealer == NULL)
955 return NO_MEMORY;
956 }
957
958 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
959 if (newBuffer == NULL) {
960 newBuffer = mTimedMemoryDealer->allocate(size);
961 if (newBuffer == NULL)
962 return NO_MEMORY;
963 }
964
965 *buffer = newBuffer;
966 return NO_ERROR;
967}
968
969// caller must hold mTimedBufferQueueLock
970void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
971 int64_t mediaTimeNow;
972 {
973 Mutex::Autolock mttLock(mMediaTimeTransformLock);
974 if (!mMediaTimeTransformValid)
975 return;
976
977 int64_t targetTimeNow;
978 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
979 ? mCCHelper.getCommonTime(&targetTimeNow)
980 : mCCHelper.getLocalTime(&targetTimeNow);
981
982 if (OK != res)
983 return;
984
985 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
986 &mediaTimeNow)) {
987 return;
988 }
989 }
990
991 size_t trimEnd;
992 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
993 int64_t bufEnd;
994
995 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
996 // We have a next buffer. Just use its PTS as the PTS of the frame
997 // following the last frame in this buffer. If the stream is sparse
998 // (ie, there are deliberate gaps left in the stream which should be
999 // filled with silence by the TimedAudioTrack), then this can result
1000 // in one extra buffer being left un-trimmed when it could have
1001 // been. In general, this is not typical, and we would rather
1002 // optimized away the TS calculation below for the more common case
1003 // where PTSes are contiguous.
1004 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1005 } else {
1006 // We have no next buffer. Compute the PTS of the frame following
1007 // the last frame in this buffer by computing the duration of of
1008 // this frame in media time units and adding it to the PTS of the
1009 // buffer.
1010 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1011 / mFrameSize;
1012
1013 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1014 &bufEnd)) {
1015 ALOGE("Failed to convert frame count of %lld to media time"
1016 " duration" " (scale factor %d/%u) in %s",
1017 frameCount,
1018 mMediaTimeToSampleTransform.a_to_b_numer,
1019 mMediaTimeToSampleTransform.a_to_b_denom,
1020 __PRETTY_FUNCTION__);
1021 break;
1022 }
1023 bufEnd += mTimedBufferQueue[trimEnd].pts();
1024 }
1025
1026 if (bufEnd > mediaTimeNow)
1027 break;
1028
1029 // Is the buffer we want to use in the middle of a mix operation right
1030 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1031 // from the mixer which should be coming back shortly.
1032 if (!trimEnd && mQueueHeadInFlight) {
1033 mTrimQueueHeadOnRelease = true;
1034 }
1035 }
1036
1037 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1038 if (trimStart < trimEnd) {
1039 // Update the bookkeeping for framesReady()
1040 for (size_t i = trimStart; i < trimEnd; ++i) {
1041 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1042 }
1043
1044 // Now actually remove the buffers from the queue.
1045 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1046 }
1047}
1048
1049void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1050 const char* logTag) {
1051 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1052 "%s called (reason \"%s\"), but timed buffer queue has no"
1053 " elements to trim.", __FUNCTION__, logTag);
1054
1055 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1056 mTimedBufferQueue.removeAt(0);
1057}
1058
1059void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1060 const TimedBuffer& buf,
1061 const char* logTag) {
1062 uint32_t bufBytes = buf.buffer()->size();
1063 uint32_t consumedAlready = buf.position();
1064
1065 ALOG_ASSERT(consumedAlready <= bufBytes,
1066 "Bad bookkeeping while updating frames pending. Timed buffer is"
1067 " only %u bytes long, but claims to have consumed %u"
1068 " bytes. (update reason: \"%s\")",
1069 bufBytes, consumedAlready, logTag);
1070
1071 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1072 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1073 "Bad bookkeeping while updating frames pending. Should have at"
1074 " least %u queued frames, but we think we have only %u. (update"
1075 " reason: \"%s\")",
1076 bufFrames, mFramesPendingInQueue, logTag);
1077
1078 mFramesPendingInQueue -= bufFrames;
1079}
1080
1081status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1082 const sp<IMemory>& buffer, int64_t pts) {
1083
1084 {
1085 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1086 if (!mMediaTimeTransformValid)
1087 return INVALID_OPERATION;
1088 }
1089
1090 Mutex::Autolock _l(mTimedBufferQueueLock);
1091
1092 uint32_t bufFrames = buffer->size() / mFrameSize;
1093 mFramesPendingInQueue += bufFrames;
1094 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1095
1096 return NO_ERROR;
1097}
1098
1099status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1100 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1101
1102 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1103 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1104 target);
1105
1106 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1107 target == TimedAudioTrack::COMMON_TIME)) {
1108 return BAD_VALUE;
1109 }
1110
1111 Mutex::Autolock lock(mMediaTimeTransformLock);
1112 mMediaTimeTransform = xform;
1113 mMediaTimeTransformTarget = target;
1114 mMediaTimeTransformValid = true;
1115
1116 return NO_ERROR;
1117}
1118
1119#define min(a, b) ((a) < (b) ? (a) : (b))
1120
1121// implementation of getNextBuffer for tracks whose buffers have timestamps
1122status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1123 AudioBufferProvider::Buffer* buffer, int64_t pts)
1124{
1125 if (pts == AudioBufferProvider::kInvalidPTS) {
1126 buffer->raw = NULL;
1127 buffer->frameCount = 0;
1128 mTimedAudioOutputOnTime = false;
1129 return INVALID_OPERATION;
1130 }
1131
1132 Mutex::Autolock _l(mTimedBufferQueueLock);
1133
1134 ALOG_ASSERT(!mQueueHeadInFlight,
1135 "getNextBuffer called without releaseBuffer!");
1136
1137 while (true) {
1138
1139 // if we have no timed buffers, then fail
1140 if (mTimedBufferQueue.isEmpty()) {
1141 buffer->raw = NULL;
1142 buffer->frameCount = 0;
1143 return NOT_ENOUGH_DATA;
1144 }
1145
1146 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1147
1148 // calculate the PTS of the head of the timed buffer queue expressed in
1149 // local time
1150 int64_t headLocalPTS;
1151 {
1152 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1153
1154 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1155
1156 if (mMediaTimeTransform.a_to_b_denom == 0) {
1157 // the transform represents a pause, so yield silence
1158 timedYieldSilence_l(buffer->frameCount, buffer);
1159 return NO_ERROR;
1160 }
1161
1162 int64_t transformedPTS;
1163 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1164 &transformedPTS)) {
1165 // the transform failed. this shouldn't happen, but if it does
1166 // then just drop this buffer
1167 ALOGW("timedGetNextBuffer transform failed");
1168 buffer->raw = NULL;
1169 buffer->frameCount = 0;
1170 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1171 return NO_ERROR;
1172 }
1173
1174 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1175 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1176 &headLocalPTS)) {
1177 buffer->raw = NULL;
1178 buffer->frameCount = 0;
1179 return INVALID_OPERATION;
1180 }
1181 } else {
1182 headLocalPTS = transformedPTS;
1183 }
1184 }
1185
1186 // adjust the head buffer's PTS to reflect the portion of the head buffer
1187 // that has already been consumed
1188 int64_t effectivePTS = headLocalPTS +
1189 ((head.position() / mFrameSize) * mLocalTimeFreq / sampleRate());
1190
1191 // Calculate the delta in samples between the head of the input buffer
1192 // queue and the start of the next output buffer that will be written.
1193 // If the transformation fails because of over or underflow, it means
1194 // that the sample's position in the output stream is so far out of
1195 // whack that it should just be dropped.
1196 int64_t sampleDelta;
1197 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1198 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1199 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1200 " mix");
1201 continue;
1202 }
1203 if (!mLocalTimeToSampleTransform.doForwardTransform(
1204 (effectivePTS - pts) << 32, &sampleDelta)) {
1205 ALOGV("*** too late during sample rate transform: dropped buffer");
1206 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1207 continue;
1208 }
1209
1210 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1211 " sampleDelta=[%d.%08x]",
1212 head.pts(), head.position(), pts,
1213 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1214 + (sampleDelta >> 32)),
1215 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1216
1217 // if the delta between the ideal placement for the next input sample and
1218 // the current output position is within this threshold, then we will
1219 // concatenate the next input samples to the previous output
1220 const int64_t kSampleContinuityThreshold =
1221 (static_cast<int64_t>(sampleRate()) << 32) / 250;
1222
1223 // if this is the first buffer of audio that we're emitting from this track
1224 // then it should be almost exactly on time.
1225 const int64_t kSampleStartupThreshold = 1LL << 32;
1226
1227 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1228 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1229 // the next input is close enough to being on time, so concatenate it
1230 // with the last output
1231 timedYieldSamples_l(buffer);
1232
1233 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1234 head.position(), buffer->frameCount);
1235 return NO_ERROR;
1236 }
1237
1238 // Looks like our output is not on time. Reset our on timed status.
1239 // Next time we mix samples from our input queue, then should be within
1240 // the StartupThreshold.
1241 mTimedAudioOutputOnTime = false;
1242 if (sampleDelta > 0) {
1243 // the gap between the current output position and the proper start of
1244 // the next input sample is too big, so fill it with silence
1245 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1246
1247 timedYieldSilence_l(framesUntilNextInput, buffer);
1248 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1249 return NO_ERROR;
1250 } else {
1251 // the next input sample is late
1252 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1253 size_t onTimeSamplePosition =
1254 head.position() + lateFrames * mFrameSize;
1255
1256 if (onTimeSamplePosition > head.buffer()->size()) {
1257 // all the remaining samples in the head are too late, so
1258 // drop it and move on
1259 ALOGV("*** too late: dropped buffer");
1260 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1261 continue;
1262 } else {
1263 // skip over the late samples
1264 head.setPosition(onTimeSamplePosition);
1265
1266 // yield the available samples
1267 timedYieldSamples_l(buffer);
1268
1269 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1270 return NO_ERROR;
1271 }
1272 }
1273 }
1274}
1275
1276// Yield samples from the timed buffer queue head up to the given output
1277// buffer's capacity.
1278//
1279// Caller must hold mTimedBufferQueueLock
1280void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1281 AudioBufferProvider::Buffer* buffer) {
1282
1283 const TimedBuffer& head = mTimedBufferQueue[0];
1284
1285 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1286 head.position());
1287
1288 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1289 mFrameSize);
1290 size_t framesRequested = buffer->frameCount;
1291 buffer->frameCount = min(framesLeftInHead, framesRequested);
1292
1293 mQueueHeadInFlight = true;
1294 mTimedAudioOutputOnTime = true;
1295}
1296
1297// Yield samples of silence up to the given output buffer's capacity
1298//
1299// Caller must hold mTimedBufferQueueLock
1300void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1301 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1302
1303 // lazily allocate a buffer filled with silence
1304 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1305 delete [] mTimedSilenceBuffer;
1306 mTimedSilenceBufferSize = numFrames * mFrameSize;
1307 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1308 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1309 }
1310
1311 buffer->raw = mTimedSilenceBuffer;
1312 size_t framesRequested = buffer->frameCount;
1313 buffer->frameCount = min(numFrames, framesRequested);
1314
1315 mTimedAudioOutputOnTime = false;
1316}
1317
1318// AudioBufferProvider interface
1319void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1320 AudioBufferProvider::Buffer* buffer) {
1321
1322 Mutex::Autolock _l(mTimedBufferQueueLock);
1323
1324 // If the buffer which was just released is part of the buffer at the head
1325 // of the queue, be sure to update the amt of the buffer which has been
1326 // consumed. If the buffer being returned is not part of the head of the
1327 // queue, its either because the buffer is part of the silence buffer, or
1328 // because the head of the timed queue was trimmed after the mixer called
1329 // getNextBuffer but before the mixer called releaseBuffer.
1330 if (buffer->raw == mTimedSilenceBuffer) {
1331 ALOG_ASSERT(!mQueueHeadInFlight,
1332 "Queue head in flight during release of silence buffer!");
1333 goto done;
1334 }
1335
1336 ALOG_ASSERT(mQueueHeadInFlight,
1337 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1338 " head in flight.");
1339
1340 if (mTimedBufferQueue.size()) {
1341 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1342
1343 void* start = head.buffer()->pointer();
1344 void* end = reinterpret_cast<void*>(
1345 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1346 + head.buffer()->size());
1347
1348 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1349 "released buffer not within the head of the timed buffer"
1350 " queue; qHead = [%p, %p], released buffer = %p",
1351 start, end, buffer->raw);
1352
1353 head.setPosition(head.position() +
1354 (buffer->frameCount * mFrameSize));
1355 mQueueHeadInFlight = false;
1356
1357 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1358 "Bad bookkeeping during releaseBuffer! Should have at"
1359 " least %u queued frames, but we think we have only %u",
1360 buffer->frameCount, mFramesPendingInQueue);
1361
1362 mFramesPendingInQueue -= buffer->frameCount;
1363
1364 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1365 || mTrimQueueHeadOnRelease) {
1366 trimTimedBufferQueueHead_l("releaseBuffer");
1367 mTrimQueueHeadOnRelease = false;
1368 }
1369 } else {
1370 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1371 " buffers in the timed buffer queue");
1372 }
1373
1374done:
1375 buffer->raw = 0;
1376 buffer->frameCount = 0;
1377}
1378
1379size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1380 Mutex::Autolock _l(mTimedBufferQueueLock);
1381 return mFramesPendingInQueue;
1382}
1383
1384AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1385 : mPTS(0), mPosition(0) {}
1386
1387AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1388 const sp<IMemory>& buffer, int64_t pts)
1389 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1390
1391
1392// ----------------------------------------------------------------------------
1393
1394AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1395 PlaybackThread *playbackThread,
1396 DuplicatingThread *sourceThread,
1397 uint32_t sampleRate,
1398 audio_format_t format,
1399 audio_channel_mask_t channelMask,
1400 size_t frameCount)
1401 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1402 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001403 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001404{
1405
1406 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001407 mOutBuffer.frameCount = 0;
1408 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001409 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
1410 "mCblk->frameCount_ %u, mChannelMask 0x%08x mBufferEnd %p",
1411 mCblk, mBuffer,
1412 mCblk->frameCount_, mChannelMask, mBufferEnd);
1413 // since client and server are in the same process,
1414 // the buffer has the same virtual address on both sides
1415 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001416 } else {
1417 ALOGW("Error creating output track on thread %p", playbackThread);
1418 }
1419}
1420
1421AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1422{
1423 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001424 delete mClientProxy;
1425 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001426}
1427
1428status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1429 int triggerSession)
1430{
1431 status_t status = Track::start(event, triggerSession);
1432 if (status != NO_ERROR) {
1433 return status;
1434 }
1435
1436 mActive = true;
1437 mRetryCount = 127;
1438 return status;
1439}
1440
1441void AudioFlinger::PlaybackThread::OutputTrack::stop()
1442{
1443 Track::stop();
1444 clearBufferQueue();
1445 mOutBuffer.frameCount = 0;
1446 mActive = false;
1447}
1448
1449bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1450{
1451 Buffer *pInBuffer;
1452 Buffer inBuffer;
1453 uint32_t channelCount = mChannelCount;
1454 bool outputBufferFull = false;
1455 inBuffer.frameCount = frames;
1456 inBuffer.i16 = data;
1457
1458 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1459
1460 if (!mActive && frames != 0) {
1461 start();
1462 sp<ThreadBase> thread = mThread.promote();
1463 if (thread != 0) {
1464 MixerThread *mixerThread = (MixerThread *)thread.get();
1465 if (mFrameCount > frames) {
1466 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1467 uint32_t startFrames = (mFrameCount - frames);
1468 pInBuffer = new Buffer;
1469 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1470 pInBuffer->frameCount = startFrames;
1471 pInBuffer->i16 = pInBuffer->mBuffer;
1472 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1473 mBufferQueue.add(pInBuffer);
1474 } else {
1475 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
1476 }
1477 }
1478 }
1479 }
1480
1481 while (waitTimeLeftMs) {
1482 // First write pending buffers, then new data
1483 if (mBufferQueue.size()) {
1484 pInBuffer = mBufferQueue.itemAt(0);
1485 } else {
1486 pInBuffer = &inBuffer;
1487 }
1488
1489 if (pInBuffer->frameCount == 0) {
1490 break;
1491 }
1492
1493 if (mOutBuffer.frameCount == 0) {
1494 mOutBuffer.frameCount = pInBuffer->frameCount;
1495 nsecs_t startTime = systemTime();
1496 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
1497 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this,
1498 mThread.unsafe_get());
1499 outputBufferFull = true;
1500 break;
1501 }
1502 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1503 if (waitTimeLeftMs >= waitTimeMs) {
1504 waitTimeLeftMs -= waitTimeMs;
1505 } else {
1506 waitTimeLeftMs = 0;
1507 }
1508 }
1509
1510 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1511 pInBuffer->frameCount;
1512 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kastene3aa6592012-12-04 12:22:46 -08001513 mClientProxy->stepUser(outFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08001514 pInBuffer->frameCount -= outFrames;
1515 pInBuffer->i16 += outFrames * channelCount;
1516 mOutBuffer.frameCount -= outFrames;
1517 mOutBuffer.i16 += outFrames * channelCount;
1518
1519 if (pInBuffer->frameCount == 0) {
1520 if (mBufferQueue.size()) {
1521 mBufferQueue.removeAt(0);
1522 delete [] pInBuffer->mBuffer;
1523 delete pInBuffer;
1524 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1525 mThread.unsafe_get(), mBufferQueue.size());
1526 } else {
1527 break;
1528 }
1529 }
1530 }
1531
1532 // If we could not write all frames, allocate a buffer and queue it for next time.
1533 if (inBuffer.frameCount) {
1534 sp<ThreadBase> thread = mThread.promote();
1535 if (thread != 0 && !thread->standby()) {
1536 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1537 pInBuffer = new Buffer;
1538 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1539 pInBuffer->frameCount = inBuffer.frameCount;
1540 pInBuffer->i16 = pInBuffer->mBuffer;
1541 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1542 sizeof(int16_t));
1543 mBufferQueue.add(pInBuffer);
1544 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1545 mThread.unsafe_get(), mBufferQueue.size());
1546 } else {
1547 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1548 mThread.unsafe_get(), this);
1549 }
1550 }
1551 }
1552
1553 // Calling write() with a 0 length buffer, means that no more data will be written:
1554 // If no more buffers are pending, fill output track buffer to make sure it is started
1555 // by output mixer.
1556 if (frames == 0 && mBufferQueue.size() == 0) {
1557 if (mCblk->user < mFrameCount) {
1558 frames = mFrameCount - mCblk->user;
1559 pInBuffer = new Buffer;
1560 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1561 pInBuffer->frameCount = frames;
1562 pInBuffer->i16 = pInBuffer->mBuffer;
1563 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1564 mBufferQueue.add(pInBuffer);
1565 } else if (mActive) {
1566 stop();
1567 }
1568 }
1569
1570 return outputBufferFull;
1571}
1572
1573status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1574 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1575{
Eric Laurent81784c32012-11-19 14:55:58 -08001576 audio_track_cblk_t* cblk = mCblk;
1577 uint32_t framesReq = buffer->frameCount;
1578
1579 ALOGVV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
1580 buffer->frameCount = 0;
1581
Glenn Kastene3aa6592012-12-04 12:22:46 -08001582 size_t framesAvail;
1583 {
Eric Laurent81784c32012-11-19 14:55:58 -08001584 Mutex::Autolock _l(cblk->lock);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001585
1586 // read the server count again
1587 while (!(framesAvail = mClientProxy->framesAvailable_l())) {
1588 if (CC_UNLIKELY(!mActive)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001589 ALOGV("Not active and NO_MORE_BUFFERS");
1590 return NO_MORE_BUFFERS;
1591 }
Glenn Kastene3aa6592012-12-04 12:22:46 -08001592 status_t result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurent81784c32012-11-19 14:55:58 -08001593 if (result != NO_ERROR) {
1594 return NO_MORE_BUFFERS;
1595 }
Eric Laurent81784c32012-11-19 14:55:58 -08001596 }
1597 }
1598
Eric Laurent81784c32012-11-19 14:55:58 -08001599 if (framesReq > framesAvail) {
1600 framesReq = framesAvail;
1601 }
1602
1603 uint32_t u = cblk->user;
1604 uint32_t bufferEnd = cblk->userBase + mFrameCount;
1605
1606 if (framesReq > bufferEnd - u) {
1607 framesReq = bufferEnd - u;
1608 }
1609
1610 buffer->frameCount = framesReq;
Glenn Kastene3aa6592012-12-04 12:22:46 -08001611 buffer->raw = mClientProxy->buffer(u);
Eric Laurent81784c32012-11-19 14:55:58 -08001612 return NO_ERROR;
1613}
1614
1615
1616void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1617{
1618 size_t size = mBufferQueue.size();
1619
1620 for (size_t i = 0; i < size; i++) {
1621 Buffer *pBuffer = mBufferQueue.itemAt(i);
1622 delete [] pBuffer->mBuffer;
1623 delete pBuffer;
1624 }
1625 mBufferQueue.clear();
1626}
1627
1628
1629// ----------------------------------------------------------------------------
1630// Record
1631// ----------------------------------------------------------------------------
1632
1633AudioFlinger::RecordHandle::RecordHandle(
1634 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1635 : BnAudioRecord(),
1636 mRecordTrack(recordTrack)
1637{
1638}
1639
1640AudioFlinger::RecordHandle::~RecordHandle() {
1641 stop_nonvirtual();
1642 mRecordTrack->destroy();
1643}
1644
1645sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1646 return mRecordTrack->getCblk();
1647}
1648
1649status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1650 int triggerSession) {
1651 ALOGV("RecordHandle::start()");
1652 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1653}
1654
1655void AudioFlinger::RecordHandle::stop() {
1656 stop_nonvirtual();
1657}
1658
1659void AudioFlinger::RecordHandle::stop_nonvirtual() {
1660 ALOGV("RecordHandle::stop()");
1661 mRecordTrack->stop();
1662}
1663
1664status_t AudioFlinger::RecordHandle::onTransact(
1665 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1666{
1667 return BnAudioRecord::onTransact(code, data, reply, flags);
1668}
1669
1670// ----------------------------------------------------------------------------
1671
1672// RecordTrack constructor must be called with AudioFlinger::mLock held
1673AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1674 RecordThread *thread,
1675 const sp<Client>& client,
1676 uint32_t sampleRate,
1677 audio_format_t format,
1678 audio_channel_mask_t channelMask,
1679 size_t frameCount,
1680 int sessionId)
1681 : TrackBase(thread, client, sampleRate, format,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001682 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001683 mOverflow(false)
1684{
1685 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
1686}
1687
1688AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1689{
1690 ALOGV("%s", __func__);
1691}
1692
1693// AudioBufferProvider interface
1694status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1695 int64_t pts)
1696{
1697 audio_track_cblk_t* cblk = this->cblk();
1698 uint32_t framesAvail;
1699 uint32_t framesReq = buffer->frameCount;
1700
1701 // Check if last stepServer failed, try to step now
1702 if (mStepServerFailed) {
1703 if (!step()) {
1704 goto getNextBuffer_exit;
1705 }
1706 ALOGV("stepServer recovered");
1707 mStepServerFailed = false;
1708 }
1709
1710 // FIXME lock is not actually held, so overrun is possible
Glenn Kastene3aa6592012-12-04 12:22:46 -08001711 framesAvail = mServerProxy->framesAvailableIn_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001712
1713 if (CC_LIKELY(framesAvail)) {
1714 uint32_t s = cblk->server;
1715 uint32_t bufferEnd = cblk->serverBase + mFrameCount;
1716
1717 if (framesReq > framesAvail) {
1718 framesReq = framesAvail;
1719 }
1720 if (framesReq > bufferEnd - s) {
1721 framesReq = bufferEnd - s;
1722 }
1723
1724 buffer->raw = getBuffer(s, framesReq);
1725 buffer->frameCount = framesReq;
1726 return NO_ERROR;
1727 }
1728
1729getNextBuffer_exit:
1730 buffer->raw = NULL;
1731 buffer->frameCount = 0;
1732 return NOT_ENOUGH_DATA;
1733}
1734
1735status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1736 int triggerSession)
1737{
1738 sp<ThreadBase> thread = mThread.promote();
1739 if (thread != 0) {
1740 RecordThread *recordThread = (RecordThread *)thread.get();
1741 return recordThread->start(this, event, triggerSession);
1742 } else {
1743 return BAD_VALUE;
1744 }
1745}
1746
1747void AudioFlinger::RecordThread::RecordTrack::stop()
1748{
1749 sp<ThreadBase> thread = mThread.promote();
1750 if (thread != 0) {
1751 RecordThread *recordThread = (RecordThread *)thread.get();
1752 recordThread->mLock.lock();
1753 bool doStop = recordThread->stop_l(this);
1754 if (doStop) {
1755 TrackBase::reset();
1756 // Force overrun condition to avoid false overrun callback until first data is
1757 // read from buffer
1758 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
1759 }
1760 recordThread->mLock.unlock();
1761 if (doStop) {
1762 AudioSystem::stopInput(recordThread->id());
1763 }
1764 }
1765}
1766
1767void AudioFlinger::RecordThread::RecordTrack::destroy()
1768{
1769 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1770 sp<RecordTrack> keep(this);
1771 {
1772 sp<ThreadBase> thread = mThread.promote();
1773 if (thread != 0) {
1774 if (mState == ACTIVE || mState == RESUMING) {
1775 AudioSystem::stopInput(thread->id());
1776 }
1777 AudioSystem::releaseInput(thread->id());
1778 Mutex::Autolock _l(thread->mLock);
1779 RecordThread *recordThread = (RecordThread *) thread.get();
1780 recordThread->destroyTrack_l(this);
1781 }
1782 }
1783}
1784
1785
1786/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1787{
Glenn Kastene3aa6592012-12-04 12:22:46 -08001788 result.append(" Clien Fmt Chn mask Session Step S Serv User FrameCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001789}
1790
1791void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1792{
Glenn Kastene3aa6592012-12-04 12:22:46 -08001793 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %08x %08x %05d\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001794 (mClient == 0) ? getpid_cached : mClient->pid(),
1795 mFormat,
1796 mChannelMask,
1797 mSessionId,
1798 mStepCount,
1799 mState,
Eric Laurent81784c32012-11-19 14:55:58 -08001800 mCblk->server,
1801 mCblk->user,
1802 mFrameCount);
1803}
1804
Eric Laurent81784c32012-11-19 14:55:58 -08001805}; // namespace android