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