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