blob: 30fe1f2726f1fcf50fb2ca4d4a49bb2df1b92e6d [file] [log] [blame]
Eric Laurentca7cc822012-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 Kastendd4abb52013-01-10 12:31:01 -080035#include <media/nbaio/Pipe.h>
36#include <media/nbaio/PipeReader.h>
37
Eric Laurentca7cc822012-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 Kastendd4abb52013-01-10 12:31:01 -080059static volatile int32_t nextTrackId = 55;
60
Eric Laurentca7cc822012-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 Kasten552f2742012-12-04 12:22:46 -080070 int sessionId,
71 bool isOut)
Eric Laurentca7cc822012-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 Kasten552f2742012-12-04 12:22:46 -080088 mSessionId(sessionId),
89 mIsOut(isOut),
Glenn Kastendd4abb52013-01-10 12:31:01 -080090 mServerProxy(NULL),
91 mId(android_atomic_inc(&nextTrackId))
Eric Laurentca7cc822012-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 Kasten552f2742012-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 Laurentca7cc822012-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 Laurentca7cc822012-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 Kasten552f2742012-12-04 12:22:46 -0800142 mServerProxy = new ServerProxy(mCblk, mBuffer, frameCount, mFrameSize, isOut);
Glenn Kastendd4abb52013-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 Laurentca7cc822012-11-19 14:55:58 -0800161 }
162}
163
164AudioFlinger::ThreadBase::TrackBase::~TrackBase()
165{
Glenn Kastendd4abb52013-01-10 12:31:01 -0800166 dumpTee(-1, mTeeSource, mId);
Glenn Kasten552f2742012-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 Laurentca7cc822012-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 Kastendd4abb52013-01-10 12:31:01 -0800192 if (mTeeSink != 0) {
193 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
194 }
195
Eric Laurentca7cc822012-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 Kasten552f2742012-12-04 12:22:46 -0800204 bool result = mServerProxy->step(mStepCount);
Eric Laurentca7cc822012-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 Kasten552f2742012-12-04 12:22:46 -0800224 return mServerProxy->getSampleRate();
Eric Laurentca7cc822012-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 Laurentca7cc822012-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 Kasten552f2742012-12-04 12:22:46 -0800345 sessionId, true /*isOut*/),
Eric Laurentca7cc822012-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 Kasten30c01812012-12-04 12:12:34 -0800358 mCachedVolume(1.0),
359 mIsInvalid(false)
Eric Laurentca7cc822012-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 Kasten4b3a49e2012-11-29 13:38:14 -0800428 result.append(" Name Client Type Fmt Chn mask Session StpCnt fCount S F SRate "
Eric Laurentca7cc822012-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 Kasten552f2742012-12-04 12:22:46 -0800434 uint32_t vlr = mServerProxy->getVolumeLR();
Eric Laurentca7cc822012-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 Kasten4b3a49e2012-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 Laurentca7cc822012-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 Laurentca7cc822012-11-19 14:55:58 -0800502 mFillingUpStatus,
Glenn Kasten552f2742012-12-04 12:22:46 -0800503 mServerProxy->getSampleRate(),
Eric Laurentca7cc822012-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 Kasten552f2742012-12-04 12:22:46 -0800538 framesReady = mServerProxy->framesReady();
Eric Laurentca7cc822012-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 Kasten552f2742012-12-04 12:22:46 -0800573 return mServerProxy->framesReady();
Eric Laurentca7cc822012-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);
601 track_state state = mState;
602 // here the track could be either new, or restarted
603 // in both cases "unstop" the track
604 if (mState == PAUSED) {
605 mState = TrackBase::RESUMING;
606 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
607 } else {
608 mState = TrackBase::ACTIVE;
609 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
610 }
611
612 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
613 thread->mLock.unlock();
614 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
615 thread->mLock.lock();
616
617#ifdef ADD_BATTERY_DATA
618 // to track the speaker usage
619 if (status == NO_ERROR) {
620 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
621 }
622#endif
623 }
624 if (status == NO_ERROR) {
625 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
626 playbackThread->addTrack_l(this);
627 } else {
628 mState = state;
629 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
630 }
631 } else {
632 status = BAD_VALUE;
633 }
634 return status;
635}
636
637void AudioFlinger::PlaybackThread::Track::stop()
638{
639 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
640 sp<ThreadBase> thread = mThread.promote();
641 if (thread != 0) {
642 Mutex::Autolock _l(thread->mLock);
643 track_state state = mState;
644 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
645 // If the track is not active (PAUSED and buffers full), flush buffers
646 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
647 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
648 reset();
649 mState = STOPPED;
650 } else if (!isFastTrack()) {
651 mState = STOPPED;
652 } else {
653 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
654 // and then to STOPPED and reset() when presentation is complete
655 mState = STOPPING_1;
656 }
657 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
658 playbackThread);
659 }
660 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
661 thread->mLock.unlock();
662 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
663 thread->mLock.lock();
664
665#ifdef ADD_BATTERY_DATA
666 // to track the speaker usage
667 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
668#endif
669 }
670 }
671}
672
673void AudioFlinger::PlaybackThread::Track::pause()
674{
675 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
676 sp<ThreadBase> thread = mThread.promote();
677 if (thread != 0) {
678 Mutex::Autolock _l(thread->mLock);
679 if (mState == ACTIVE || mState == RESUMING) {
680 mState = PAUSING;
681 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
682 if (!isOutputTrack()) {
683 thread->mLock.unlock();
684 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
685 thread->mLock.lock();
686
687#ifdef ADD_BATTERY_DATA
688 // to track the speaker usage
689 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
690#endif
691 }
692 }
693 }
694}
695
696void AudioFlinger::PlaybackThread::Track::flush()
697{
698 ALOGV("flush(%d)", mName);
699 sp<ThreadBase> thread = mThread.promote();
700 if (thread != 0) {
701 Mutex::Autolock _l(thread->mLock);
702 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
703 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
704 return;
705 }
706 // No point remaining in PAUSED state after a flush => go to
707 // FLUSHED state
708 mState = FLUSHED;
709 // do not reset the track if it is still in the process of being stopped or paused.
710 // this will be done by prepareTracks_l() when the track is stopped.
711 // prepareTracks_l() will see mState == FLUSHED, then
712 // remove from active track list, reset(), and trigger presentation complete
713 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
714 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
715 reset();
716 }
717 }
718}
719
720void AudioFlinger::PlaybackThread::Track::reset()
721{
722 // Do not reset twice to avoid discarding data written just after a flush and before
723 // the audioflinger thread detects the track is stopped.
724 if (!mResetDone) {
725 TrackBase::reset();
726 // Force underrun condition to avoid false underrun callback until first data is
727 // written to buffer
728 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
729 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
730 mFillingUpStatus = FS_FILLING;
731 mResetDone = true;
732 if (mState == FLUSHED) {
733 mState = IDLE;
734 }
735 }
736}
737
Eric Laurentca7cc822012-11-19 14:55:58 -0800738status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
739{
740 status_t status = DEAD_OBJECT;
741 sp<ThreadBase> thread = mThread.promote();
742 if (thread != 0) {
743 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
744 sp<AudioFlinger> af = mClient->audioFlinger();
745
746 Mutex::Autolock _l(af->mLock);
747
748 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
749
750 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
751 Mutex::Autolock _dl(playbackThread->mLock);
752 Mutex::Autolock _sl(srcThread->mLock);
753 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
754 if (chain == 0) {
755 return INVALID_OPERATION;
756 }
757
758 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
759 if (effect == 0) {
760 return INVALID_OPERATION;
761 }
762 srcThread->removeEffect_l(effect);
763 playbackThread->addEffect_l(effect);
764 // removeEffect_l() has stopped the effect if it was active so it must be restarted
765 if (effect->state() == EffectModule::ACTIVE ||
766 effect->state() == EffectModule::STOPPING) {
767 effect->start();
768 }
769
770 sp<EffectChain> dstChain = effect->chain().promote();
771 if (dstChain == 0) {
772 srcThread->addEffect_l(effect);
773 return INVALID_OPERATION;
774 }
775 AudioSystem::unregisterEffect(effect->id());
776 AudioSystem::registerEffect(&effect->desc(),
777 srcThread->id(),
778 dstChain->strategy(),
779 AUDIO_SESSION_OUTPUT_MIX,
780 effect->id());
781 }
782 status = playbackThread->attachAuxEffect(this, EffectId);
783 }
784 return status;
785}
786
787void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
788{
789 mAuxEffectId = EffectId;
790 mAuxBuffer = buffer;
791}
792
793bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
794 size_t audioHalFrames)
795{
796 // a track is considered presented when the total number of frames written to audio HAL
797 // corresponds to the number of frames written when presentationComplete() is called for the
798 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
799 if (mPresentationCompleteFrames == 0) {
800 mPresentationCompleteFrames = framesWritten + audioHalFrames;
801 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
802 mPresentationCompleteFrames, audioHalFrames);
803 }
804 if (framesWritten >= mPresentationCompleteFrames) {
805 ALOGV("presentationComplete() session %d complete: framesWritten %d",
806 mSessionId, framesWritten);
807 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
808 return true;
809 }
810 return false;
811}
812
813void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
814{
815 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
816 if (mSyncEvents[i]->type() == type) {
817 mSyncEvents[i]->trigger();
818 mSyncEvents.removeAt(i);
819 i--;
820 }
821 }
822}
823
824// implement VolumeBufferProvider interface
825
826uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
827{
828 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
829 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten552f2742012-12-04 12:22:46 -0800830 uint32_t vlr = mServerProxy->getVolumeLR();
Eric Laurentca7cc822012-11-19 14:55:58 -0800831 uint32_t vl = vlr & 0xFFFF;
832 uint32_t vr = vlr >> 16;
833 // track volumes come from shared memory, so can't be trusted and must be clamped
834 if (vl > MAX_GAIN_INT) {
835 vl = MAX_GAIN_INT;
836 }
837 if (vr > MAX_GAIN_INT) {
838 vr = MAX_GAIN_INT;
839 }
840 // now apply the cached master volume and stream type volume;
841 // this is trusted but lacks any synchronization or barrier so may be stale
842 float v = mCachedVolume;
843 vl *= v;
844 vr *= v;
845 // re-combine into U4.16
846 vlr = (vr << 16) | (vl & 0xFFFF);
847 // FIXME look at mute, pause, and stop flags
848 return vlr;
849}
850
851status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
852{
853 if (mState == TERMINATED || mState == PAUSED ||
854 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
855 (mState == STOPPED)))) {
856 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
857 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
858 event->cancel();
859 return INVALID_OPERATION;
860 }
861 (void) TrackBase::setSyncEvent(event);
862 return NO_ERROR;
863}
864
Glenn Kasten30c01812012-12-04 12:12:34 -0800865void AudioFlinger::PlaybackThread::Track::invalidate()
866{
867 // FIXME should use proxy
868 android_atomic_or(CBLK_INVALID, &mCblk->flags);
869 mCblk->cv.signal();
870 mIsInvalid = true;
871}
872
Eric Laurentca7cc822012-11-19 14:55:58 -0800873// ----------------------------------------------------------------------------
874
875sp<AudioFlinger::PlaybackThread::TimedTrack>
876AudioFlinger::PlaybackThread::TimedTrack::create(
877 PlaybackThread *thread,
878 const sp<Client>& client,
879 audio_stream_type_t streamType,
880 uint32_t sampleRate,
881 audio_format_t format,
882 audio_channel_mask_t channelMask,
883 size_t frameCount,
884 const sp<IMemory>& sharedBuffer,
885 int sessionId) {
886 if (!client->reserveTimedTrack())
887 return 0;
888
889 return new TimedTrack(
890 thread, client, streamType, sampleRate, format, channelMask, frameCount,
891 sharedBuffer, sessionId);
892}
893
894AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
895 PlaybackThread *thread,
896 const sp<Client>& client,
897 audio_stream_type_t streamType,
898 uint32_t sampleRate,
899 audio_format_t format,
900 audio_channel_mask_t channelMask,
901 size_t frameCount,
902 const sp<IMemory>& sharedBuffer,
903 int sessionId)
904 : Track(thread, client, streamType, sampleRate, format, channelMask,
905 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
906 mQueueHeadInFlight(false),
907 mTrimQueueHeadOnRelease(false),
908 mFramesPendingInQueue(0),
909 mTimedSilenceBuffer(NULL),
910 mTimedSilenceBufferSize(0),
911 mTimedAudioOutputOnTime(false),
912 mMediaTimeTransformValid(false)
913{
914 LocalClock lc;
915 mLocalTimeFreq = lc.getLocalFreq();
916
917 mLocalTimeToSampleTransform.a_zero = 0;
918 mLocalTimeToSampleTransform.b_zero = 0;
919 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
920 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
921 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
922 &mLocalTimeToSampleTransform.a_to_b_denom);
923
924 mMediaTimeToSampleTransform.a_zero = 0;
925 mMediaTimeToSampleTransform.b_zero = 0;
926 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
927 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
928 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
929 &mMediaTimeToSampleTransform.a_to_b_denom);
930}
931
932AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
933 mClient->releaseTimedTrack();
934 delete [] mTimedSilenceBuffer;
935}
936
937status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
938 size_t size, sp<IMemory>* buffer) {
939
940 Mutex::Autolock _l(mTimedBufferQueueLock);
941
942 trimTimedBufferQueue_l();
943
944 // lazily initialize the shared memory heap for timed buffers
945 if (mTimedMemoryDealer == NULL) {
946 const int kTimedBufferHeapSize = 512 << 10;
947
948 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
949 "AudioFlingerTimed");
950 if (mTimedMemoryDealer == NULL)
951 return NO_MEMORY;
952 }
953
954 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
955 if (newBuffer == NULL) {
956 newBuffer = mTimedMemoryDealer->allocate(size);
957 if (newBuffer == NULL)
958 return NO_MEMORY;
959 }
960
961 *buffer = newBuffer;
962 return NO_ERROR;
963}
964
965// caller must hold mTimedBufferQueueLock
966void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
967 int64_t mediaTimeNow;
968 {
969 Mutex::Autolock mttLock(mMediaTimeTransformLock);
970 if (!mMediaTimeTransformValid)
971 return;
972
973 int64_t targetTimeNow;
974 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
975 ? mCCHelper.getCommonTime(&targetTimeNow)
976 : mCCHelper.getLocalTime(&targetTimeNow);
977
978 if (OK != res)
979 return;
980
981 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
982 &mediaTimeNow)) {
983 return;
984 }
985 }
986
987 size_t trimEnd;
988 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
989 int64_t bufEnd;
990
991 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
992 // We have a next buffer. Just use its PTS as the PTS of the frame
993 // following the last frame in this buffer. If the stream is sparse
994 // (ie, there are deliberate gaps left in the stream which should be
995 // filled with silence by the TimedAudioTrack), then this can result
996 // in one extra buffer being left un-trimmed when it could have
997 // been. In general, this is not typical, and we would rather
998 // optimized away the TS calculation below for the more common case
999 // where PTSes are contiguous.
1000 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1001 } else {
1002 // We have no next buffer. Compute the PTS of the frame following
1003 // the last frame in this buffer by computing the duration of of
1004 // this frame in media time units and adding it to the PTS of the
1005 // buffer.
1006 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1007 / mFrameSize;
1008
1009 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1010 &bufEnd)) {
1011 ALOGE("Failed to convert frame count of %lld to media time"
1012 " duration" " (scale factor %d/%u) in %s",
1013 frameCount,
1014 mMediaTimeToSampleTransform.a_to_b_numer,
1015 mMediaTimeToSampleTransform.a_to_b_denom,
1016 __PRETTY_FUNCTION__);
1017 break;
1018 }
1019 bufEnd += mTimedBufferQueue[trimEnd].pts();
1020 }
1021
1022 if (bufEnd > mediaTimeNow)
1023 break;
1024
1025 // Is the buffer we want to use in the middle of a mix operation right
1026 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1027 // from the mixer which should be coming back shortly.
1028 if (!trimEnd && mQueueHeadInFlight) {
1029 mTrimQueueHeadOnRelease = true;
1030 }
1031 }
1032
1033 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1034 if (trimStart < trimEnd) {
1035 // Update the bookkeeping for framesReady()
1036 for (size_t i = trimStart; i < trimEnd; ++i) {
1037 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1038 }
1039
1040 // Now actually remove the buffers from the queue.
1041 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1042 }
1043}
1044
1045void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1046 const char* logTag) {
1047 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1048 "%s called (reason \"%s\"), but timed buffer queue has no"
1049 " elements to trim.", __FUNCTION__, logTag);
1050
1051 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1052 mTimedBufferQueue.removeAt(0);
1053}
1054
1055void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1056 const TimedBuffer& buf,
1057 const char* logTag) {
1058 uint32_t bufBytes = buf.buffer()->size();
1059 uint32_t consumedAlready = buf.position();
1060
1061 ALOG_ASSERT(consumedAlready <= bufBytes,
1062 "Bad bookkeeping while updating frames pending. Timed buffer is"
1063 " only %u bytes long, but claims to have consumed %u"
1064 " bytes. (update reason: \"%s\")",
1065 bufBytes, consumedAlready, logTag);
1066
1067 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1068 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1069 "Bad bookkeeping while updating frames pending. Should have at"
1070 " least %u queued frames, but we think we have only %u. (update"
1071 " reason: \"%s\")",
1072 bufFrames, mFramesPendingInQueue, logTag);
1073
1074 mFramesPendingInQueue -= bufFrames;
1075}
1076
1077status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1078 const sp<IMemory>& buffer, int64_t pts) {
1079
1080 {
1081 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1082 if (!mMediaTimeTransformValid)
1083 return INVALID_OPERATION;
1084 }
1085
1086 Mutex::Autolock _l(mTimedBufferQueueLock);
1087
1088 uint32_t bufFrames = buffer->size() / mFrameSize;
1089 mFramesPendingInQueue += bufFrames;
1090 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1091
1092 return NO_ERROR;
1093}
1094
1095status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1096 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1097
1098 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1099 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1100 target);
1101
1102 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1103 target == TimedAudioTrack::COMMON_TIME)) {
1104 return BAD_VALUE;
1105 }
1106
1107 Mutex::Autolock lock(mMediaTimeTransformLock);
1108 mMediaTimeTransform = xform;
1109 mMediaTimeTransformTarget = target;
1110 mMediaTimeTransformValid = true;
1111
1112 return NO_ERROR;
1113}
1114
1115#define min(a, b) ((a) < (b) ? (a) : (b))
1116
1117// implementation of getNextBuffer for tracks whose buffers have timestamps
1118status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1119 AudioBufferProvider::Buffer* buffer, int64_t pts)
1120{
1121 if (pts == AudioBufferProvider::kInvalidPTS) {
1122 buffer->raw = NULL;
1123 buffer->frameCount = 0;
1124 mTimedAudioOutputOnTime = false;
1125 return INVALID_OPERATION;
1126 }
1127
1128 Mutex::Autolock _l(mTimedBufferQueueLock);
1129
1130 ALOG_ASSERT(!mQueueHeadInFlight,
1131 "getNextBuffer called without releaseBuffer!");
1132
1133 while (true) {
1134
1135 // if we have no timed buffers, then fail
1136 if (mTimedBufferQueue.isEmpty()) {
1137 buffer->raw = NULL;
1138 buffer->frameCount = 0;
1139 return NOT_ENOUGH_DATA;
1140 }
1141
1142 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1143
1144 // calculate the PTS of the head of the timed buffer queue expressed in
1145 // local time
1146 int64_t headLocalPTS;
1147 {
1148 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1149
1150 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1151
1152 if (mMediaTimeTransform.a_to_b_denom == 0) {
1153 // the transform represents a pause, so yield silence
1154 timedYieldSilence_l(buffer->frameCount, buffer);
1155 return NO_ERROR;
1156 }
1157
1158 int64_t transformedPTS;
1159 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1160 &transformedPTS)) {
1161 // the transform failed. this shouldn't happen, but if it does
1162 // then just drop this buffer
1163 ALOGW("timedGetNextBuffer transform failed");
1164 buffer->raw = NULL;
1165 buffer->frameCount = 0;
1166 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1167 return NO_ERROR;
1168 }
1169
1170 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1171 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1172 &headLocalPTS)) {
1173 buffer->raw = NULL;
1174 buffer->frameCount = 0;
1175 return INVALID_OPERATION;
1176 }
1177 } else {
1178 headLocalPTS = transformedPTS;
1179 }
1180 }
1181
1182 // adjust the head buffer's PTS to reflect the portion of the head buffer
1183 // that has already been consumed
1184 int64_t effectivePTS = headLocalPTS +
1185 ((head.position() / mFrameSize) * mLocalTimeFreq / sampleRate());
1186
1187 // Calculate the delta in samples between the head of the input buffer
1188 // queue and the start of the next output buffer that will be written.
1189 // If the transformation fails because of over or underflow, it means
1190 // that the sample's position in the output stream is so far out of
1191 // whack that it should just be dropped.
1192 int64_t sampleDelta;
1193 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1194 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1195 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1196 " mix");
1197 continue;
1198 }
1199 if (!mLocalTimeToSampleTransform.doForwardTransform(
1200 (effectivePTS - pts) << 32, &sampleDelta)) {
1201 ALOGV("*** too late during sample rate transform: dropped buffer");
1202 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1203 continue;
1204 }
1205
1206 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1207 " sampleDelta=[%d.%08x]",
1208 head.pts(), head.position(), pts,
1209 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1210 + (sampleDelta >> 32)),
1211 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1212
1213 // if the delta between the ideal placement for the next input sample and
1214 // the current output position is within this threshold, then we will
1215 // concatenate the next input samples to the previous output
1216 const int64_t kSampleContinuityThreshold =
1217 (static_cast<int64_t>(sampleRate()) << 32) / 250;
1218
1219 // if this is the first buffer of audio that we're emitting from this track
1220 // then it should be almost exactly on time.
1221 const int64_t kSampleStartupThreshold = 1LL << 32;
1222
1223 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1224 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1225 // the next input is close enough to being on time, so concatenate it
1226 // with the last output
1227 timedYieldSamples_l(buffer);
1228
1229 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1230 head.position(), buffer->frameCount);
1231 return NO_ERROR;
1232 }
1233
1234 // Looks like our output is not on time. Reset our on timed status.
1235 // Next time we mix samples from our input queue, then should be within
1236 // the StartupThreshold.
1237 mTimedAudioOutputOnTime = false;
1238 if (sampleDelta > 0) {
1239 // the gap between the current output position and the proper start of
1240 // the next input sample is too big, so fill it with silence
1241 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1242
1243 timedYieldSilence_l(framesUntilNextInput, buffer);
1244 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1245 return NO_ERROR;
1246 } else {
1247 // the next input sample is late
1248 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1249 size_t onTimeSamplePosition =
1250 head.position() + lateFrames * mFrameSize;
1251
1252 if (onTimeSamplePosition > head.buffer()->size()) {
1253 // all the remaining samples in the head are too late, so
1254 // drop it and move on
1255 ALOGV("*** too late: dropped buffer");
1256 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1257 continue;
1258 } else {
1259 // skip over the late samples
1260 head.setPosition(onTimeSamplePosition);
1261
1262 // yield the available samples
1263 timedYieldSamples_l(buffer);
1264
1265 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1266 return NO_ERROR;
1267 }
1268 }
1269 }
1270}
1271
1272// Yield samples from the timed buffer queue head up to the given output
1273// buffer's capacity.
1274//
1275// Caller must hold mTimedBufferQueueLock
1276void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1277 AudioBufferProvider::Buffer* buffer) {
1278
1279 const TimedBuffer& head = mTimedBufferQueue[0];
1280
1281 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1282 head.position());
1283
1284 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1285 mFrameSize);
1286 size_t framesRequested = buffer->frameCount;
1287 buffer->frameCount = min(framesLeftInHead, framesRequested);
1288
1289 mQueueHeadInFlight = true;
1290 mTimedAudioOutputOnTime = true;
1291}
1292
1293// Yield samples of silence up to the given output buffer's capacity
1294//
1295// Caller must hold mTimedBufferQueueLock
1296void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1297 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1298
1299 // lazily allocate a buffer filled with silence
1300 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1301 delete [] mTimedSilenceBuffer;
1302 mTimedSilenceBufferSize = numFrames * mFrameSize;
1303 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1304 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1305 }
1306
1307 buffer->raw = mTimedSilenceBuffer;
1308 size_t framesRequested = buffer->frameCount;
1309 buffer->frameCount = min(numFrames, framesRequested);
1310
1311 mTimedAudioOutputOnTime = false;
1312}
1313
1314// AudioBufferProvider interface
1315void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1316 AudioBufferProvider::Buffer* buffer) {
1317
1318 Mutex::Autolock _l(mTimedBufferQueueLock);
1319
1320 // If the buffer which was just released is part of the buffer at the head
1321 // of the queue, be sure to update the amt of the buffer which has been
1322 // consumed. If the buffer being returned is not part of the head of the
1323 // queue, its either because the buffer is part of the silence buffer, or
1324 // because the head of the timed queue was trimmed after the mixer called
1325 // getNextBuffer but before the mixer called releaseBuffer.
1326 if (buffer->raw == mTimedSilenceBuffer) {
1327 ALOG_ASSERT(!mQueueHeadInFlight,
1328 "Queue head in flight during release of silence buffer!");
1329 goto done;
1330 }
1331
1332 ALOG_ASSERT(mQueueHeadInFlight,
1333 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1334 " head in flight.");
1335
1336 if (mTimedBufferQueue.size()) {
1337 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1338
1339 void* start = head.buffer()->pointer();
1340 void* end = reinterpret_cast<void*>(
1341 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1342 + head.buffer()->size());
1343
1344 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1345 "released buffer not within the head of the timed buffer"
1346 " queue; qHead = [%p, %p], released buffer = %p",
1347 start, end, buffer->raw);
1348
1349 head.setPosition(head.position() +
1350 (buffer->frameCount * mFrameSize));
1351 mQueueHeadInFlight = false;
1352
1353 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1354 "Bad bookkeeping during releaseBuffer! Should have at"
1355 " least %u queued frames, but we think we have only %u",
1356 buffer->frameCount, mFramesPendingInQueue);
1357
1358 mFramesPendingInQueue -= buffer->frameCount;
1359
1360 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1361 || mTrimQueueHeadOnRelease) {
1362 trimTimedBufferQueueHead_l("releaseBuffer");
1363 mTrimQueueHeadOnRelease = false;
1364 }
1365 } else {
1366 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1367 " buffers in the timed buffer queue");
1368 }
1369
1370done:
1371 buffer->raw = 0;
1372 buffer->frameCount = 0;
1373}
1374
1375size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1376 Mutex::Autolock _l(mTimedBufferQueueLock);
1377 return mFramesPendingInQueue;
1378}
1379
1380AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1381 : mPTS(0), mPosition(0) {}
1382
1383AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1384 const sp<IMemory>& buffer, int64_t pts)
1385 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1386
1387
1388// ----------------------------------------------------------------------------
1389
1390AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1391 PlaybackThread *playbackThread,
1392 DuplicatingThread *sourceThread,
1393 uint32_t sampleRate,
1394 audio_format_t format,
1395 audio_channel_mask_t channelMask,
1396 size_t frameCount)
1397 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1398 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kasten552f2742012-12-04 12:22:46 -08001399 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurentca7cc822012-11-19 14:55:58 -08001400{
1401
1402 if (mCblk != NULL) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001403 mOutBuffer.frameCount = 0;
1404 playbackThread->mTracks.add(this);
Glenn Kasten552f2742012-12-04 12:22:46 -08001405 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
1406 "mCblk->frameCount_ %u, mChannelMask 0x%08x mBufferEnd %p",
1407 mCblk, mBuffer,
1408 mCblk->frameCount_, mChannelMask, mBufferEnd);
1409 // since client and server are in the same process,
1410 // the buffer has the same virtual address on both sides
1411 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurentca7cc822012-11-19 14:55:58 -08001412 } else {
1413 ALOGW("Error creating output track on thread %p", playbackThread);
1414 }
1415}
1416
1417AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1418{
1419 clearBufferQueue();
Glenn Kasten552f2742012-12-04 12:22:46 -08001420 delete mClientProxy;
1421 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurentca7cc822012-11-19 14:55:58 -08001422}
1423
1424status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1425 int triggerSession)
1426{
1427 status_t status = Track::start(event, triggerSession);
1428 if (status != NO_ERROR) {
1429 return status;
1430 }
1431
1432 mActive = true;
1433 mRetryCount = 127;
1434 return status;
1435}
1436
1437void AudioFlinger::PlaybackThread::OutputTrack::stop()
1438{
1439 Track::stop();
1440 clearBufferQueue();
1441 mOutBuffer.frameCount = 0;
1442 mActive = false;
1443}
1444
1445bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1446{
1447 Buffer *pInBuffer;
1448 Buffer inBuffer;
1449 uint32_t channelCount = mChannelCount;
1450 bool outputBufferFull = false;
1451 inBuffer.frameCount = frames;
1452 inBuffer.i16 = data;
1453
1454 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1455
1456 if (!mActive && frames != 0) {
1457 start();
1458 sp<ThreadBase> thread = mThread.promote();
1459 if (thread != 0) {
1460 MixerThread *mixerThread = (MixerThread *)thread.get();
1461 if (mFrameCount > frames) {
1462 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1463 uint32_t startFrames = (mFrameCount - frames);
1464 pInBuffer = new Buffer;
1465 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1466 pInBuffer->frameCount = startFrames;
1467 pInBuffer->i16 = pInBuffer->mBuffer;
1468 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1469 mBufferQueue.add(pInBuffer);
1470 } else {
1471 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
1472 }
1473 }
1474 }
1475 }
1476
1477 while (waitTimeLeftMs) {
1478 // First write pending buffers, then new data
1479 if (mBufferQueue.size()) {
1480 pInBuffer = mBufferQueue.itemAt(0);
1481 } else {
1482 pInBuffer = &inBuffer;
1483 }
1484
1485 if (pInBuffer->frameCount == 0) {
1486 break;
1487 }
1488
1489 if (mOutBuffer.frameCount == 0) {
1490 mOutBuffer.frameCount = pInBuffer->frameCount;
1491 nsecs_t startTime = systemTime();
1492 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
1493 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this,
1494 mThread.unsafe_get());
1495 outputBufferFull = true;
1496 break;
1497 }
1498 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1499 if (waitTimeLeftMs >= waitTimeMs) {
1500 waitTimeLeftMs -= waitTimeMs;
1501 } else {
1502 waitTimeLeftMs = 0;
1503 }
1504 }
1505
1506 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1507 pInBuffer->frameCount;
1508 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten552f2742012-12-04 12:22:46 -08001509 mClientProxy->stepUser(outFrames);
Eric Laurentca7cc822012-11-19 14:55:58 -08001510 pInBuffer->frameCount -= outFrames;
1511 pInBuffer->i16 += outFrames * channelCount;
1512 mOutBuffer.frameCount -= outFrames;
1513 mOutBuffer.i16 += outFrames * channelCount;
1514
1515 if (pInBuffer->frameCount == 0) {
1516 if (mBufferQueue.size()) {
1517 mBufferQueue.removeAt(0);
1518 delete [] pInBuffer->mBuffer;
1519 delete pInBuffer;
1520 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1521 mThread.unsafe_get(), mBufferQueue.size());
1522 } else {
1523 break;
1524 }
1525 }
1526 }
1527
1528 // If we could not write all frames, allocate a buffer and queue it for next time.
1529 if (inBuffer.frameCount) {
1530 sp<ThreadBase> thread = mThread.promote();
1531 if (thread != 0 && !thread->standby()) {
1532 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1533 pInBuffer = new Buffer;
1534 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1535 pInBuffer->frameCount = inBuffer.frameCount;
1536 pInBuffer->i16 = pInBuffer->mBuffer;
1537 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1538 sizeof(int16_t));
1539 mBufferQueue.add(pInBuffer);
1540 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1541 mThread.unsafe_get(), mBufferQueue.size());
1542 } else {
1543 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1544 mThread.unsafe_get(), this);
1545 }
1546 }
1547 }
1548
1549 // Calling write() with a 0 length buffer, means that no more data will be written:
1550 // If no more buffers are pending, fill output track buffer to make sure it is started
1551 // by output mixer.
1552 if (frames == 0 && mBufferQueue.size() == 0) {
1553 if (mCblk->user < mFrameCount) {
1554 frames = mFrameCount - mCblk->user;
1555 pInBuffer = new Buffer;
1556 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1557 pInBuffer->frameCount = frames;
1558 pInBuffer->i16 = pInBuffer->mBuffer;
1559 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1560 mBufferQueue.add(pInBuffer);
1561 } else if (mActive) {
1562 stop();
1563 }
1564 }
1565
1566 return outputBufferFull;
1567}
1568
1569status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1570 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1571{
Eric Laurentca7cc822012-11-19 14:55:58 -08001572 audio_track_cblk_t* cblk = mCblk;
1573 uint32_t framesReq = buffer->frameCount;
1574
1575 ALOGVV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
1576 buffer->frameCount = 0;
1577
Glenn Kasten552f2742012-12-04 12:22:46 -08001578 size_t framesAvail;
1579 {
Eric Laurentca7cc822012-11-19 14:55:58 -08001580 Mutex::Autolock _l(cblk->lock);
Glenn Kasten552f2742012-12-04 12:22:46 -08001581
1582 // read the server count again
1583 while (!(framesAvail = mClientProxy->framesAvailable_l())) {
1584 if (CC_UNLIKELY(!mActive)) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001585 ALOGV("Not active and NO_MORE_BUFFERS");
1586 return NO_MORE_BUFFERS;
1587 }
Glenn Kasten552f2742012-12-04 12:22:46 -08001588 status_t result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurentca7cc822012-11-19 14:55:58 -08001589 if (result != NO_ERROR) {
1590 return NO_MORE_BUFFERS;
1591 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001592 }
1593 }
1594
Eric Laurentca7cc822012-11-19 14:55:58 -08001595 if (framesReq > framesAvail) {
1596 framesReq = framesAvail;
1597 }
1598
1599 uint32_t u = cblk->user;
1600 uint32_t bufferEnd = cblk->userBase + mFrameCount;
1601
1602 if (framesReq > bufferEnd - u) {
1603 framesReq = bufferEnd - u;
1604 }
1605
1606 buffer->frameCount = framesReq;
Glenn Kasten552f2742012-12-04 12:22:46 -08001607 buffer->raw = mClientProxy->buffer(u);
Eric Laurentca7cc822012-11-19 14:55:58 -08001608 return NO_ERROR;
1609}
1610
1611
1612void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1613{
1614 size_t size = mBufferQueue.size();
1615
1616 for (size_t i = 0; i < size; i++) {
1617 Buffer *pBuffer = mBufferQueue.itemAt(i);
1618 delete [] pBuffer->mBuffer;
1619 delete pBuffer;
1620 }
1621 mBufferQueue.clear();
1622}
1623
1624
1625// ----------------------------------------------------------------------------
1626// Record
1627// ----------------------------------------------------------------------------
1628
1629AudioFlinger::RecordHandle::RecordHandle(
1630 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1631 : BnAudioRecord(),
1632 mRecordTrack(recordTrack)
1633{
1634}
1635
1636AudioFlinger::RecordHandle::~RecordHandle() {
1637 stop_nonvirtual();
1638 mRecordTrack->destroy();
1639}
1640
1641sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1642 return mRecordTrack->getCblk();
1643}
1644
1645status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1646 int triggerSession) {
1647 ALOGV("RecordHandle::start()");
1648 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1649}
1650
1651void AudioFlinger::RecordHandle::stop() {
1652 stop_nonvirtual();
1653}
1654
1655void AudioFlinger::RecordHandle::stop_nonvirtual() {
1656 ALOGV("RecordHandle::stop()");
1657 mRecordTrack->stop();
1658}
1659
1660status_t AudioFlinger::RecordHandle::onTransact(
1661 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1662{
1663 return BnAudioRecord::onTransact(code, data, reply, flags);
1664}
1665
1666// ----------------------------------------------------------------------------
1667
1668// RecordTrack constructor must be called with AudioFlinger::mLock held
1669AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1670 RecordThread *thread,
1671 const sp<Client>& client,
1672 uint32_t sampleRate,
1673 audio_format_t format,
1674 audio_channel_mask_t channelMask,
1675 size_t frameCount,
1676 int sessionId)
1677 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten552f2742012-12-04 12:22:46 -08001678 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurentca7cc822012-11-19 14:55:58 -08001679 mOverflow(false)
1680{
1681 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
1682}
1683
1684AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1685{
1686 ALOGV("%s", __func__);
1687}
1688
1689// AudioBufferProvider interface
1690status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1691 int64_t pts)
1692{
1693 audio_track_cblk_t* cblk = this->cblk();
1694 uint32_t framesAvail;
1695 uint32_t framesReq = buffer->frameCount;
1696
1697 // Check if last stepServer failed, try to step now
1698 if (mStepServerFailed) {
1699 if (!step()) {
1700 goto getNextBuffer_exit;
1701 }
1702 ALOGV("stepServer recovered");
1703 mStepServerFailed = false;
1704 }
1705
1706 // FIXME lock is not actually held, so overrun is possible
Glenn Kasten552f2742012-12-04 12:22:46 -08001707 framesAvail = mServerProxy->framesAvailableIn_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08001708
1709 if (CC_LIKELY(framesAvail)) {
1710 uint32_t s = cblk->server;
1711 uint32_t bufferEnd = cblk->serverBase + mFrameCount;
1712
1713 if (framesReq > framesAvail) {
1714 framesReq = framesAvail;
1715 }
1716 if (framesReq > bufferEnd - s) {
1717 framesReq = bufferEnd - s;
1718 }
1719
1720 buffer->raw = getBuffer(s, framesReq);
1721 buffer->frameCount = framesReq;
1722 return NO_ERROR;
1723 }
1724
1725getNextBuffer_exit:
1726 buffer->raw = NULL;
1727 buffer->frameCount = 0;
1728 return NOT_ENOUGH_DATA;
1729}
1730
1731status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1732 int triggerSession)
1733{
1734 sp<ThreadBase> thread = mThread.promote();
1735 if (thread != 0) {
1736 RecordThread *recordThread = (RecordThread *)thread.get();
1737 return recordThread->start(this, event, triggerSession);
1738 } else {
1739 return BAD_VALUE;
1740 }
1741}
1742
1743void AudioFlinger::RecordThread::RecordTrack::stop()
1744{
1745 sp<ThreadBase> thread = mThread.promote();
1746 if (thread != 0) {
1747 RecordThread *recordThread = (RecordThread *)thread.get();
1748 recordThread->mLock.lock();
1749 bool doStop = recordThread->stop_l(this);
1750 if (doStop) {
1751 TrackBase::reset();
1752 // Force overrun condition to avoid false overrun callback until first data is
1753 // read from buffer
1754 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
1755 }
1756 recordThread->mLock.unlock();
1757 if (doStop) {
1758 AudioSystem::stopInput(recordThread->id());
1759 }
1760 }
1761}
1762
1763void AudioFlinger::RecordThread::RecordTrack::destroy()
1764{
1765 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1766 sp<RecordTrack> keep(this);
1767 {
1768 sp<ThreadBase> thread = mThread.promote();
1769 if (thread != 0) {
1770 if (mState == ACTIVE || mState == RESUMING) {
1771 AudioSystem::stopInput(thread->id());
1772 }
1773 AudioSystem::releaseInput(thread->id());
1774 Mutex::Autolock _l(thread->mLock);
1775 RecordThread *recordThread = (RecordThread *) thread.get();
1776 recordThread->destroyTrack_l(this);
1777 }
1778 }
1779}
1780
1781
1782/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1783{
Glenn Kasten552f2742012-12-04 12:22:46 -08001784 result.append(" Clien Fmt Chn mask Session Step S Serv User FrameCount\n");
Eric Laurentca7cc822012-11-19 14:55:58 -08001785}
1786
1787void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1788{
Glenn Kasten552f2742012-12-04 12:22:46 -08001789 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %08x %08x %05d\n",
Eric Laurentca7cc822012-11-19 14:55:58 -08001790 (mClient == 0) ? getpid_cached : mClient->pid(),
1791 mFormat,
1792 mChannelMask,
1793 mSessionId,
1794 mStepCount,
1795 mState,
Eric Laurentca7cc822012-11-19 14:55:58 -08001796 mCblk->server,
1797 mCblk->user,
1798 mFrameCount);
1799}
1800
Eric Laurentca7cc822012-11-19 14:55:58 -08001801}; // namespace android