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