blob: bfc197cdd09380fe37f8826cb4482954989c5d24 [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
253status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
254{
255 return mTrack->attachAuxEffect(EffectId);
256}
257
258status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
259 sp<IMemory>* buffer) {
260 if (!mTrack->isTimedTrack())
261 return INVALID_OPERATION;
262
263 PlaybackThread::TimedTrack* tt =
264 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
265 return tt->allocateTimedBuffer(size, buffer);
266}
267
268status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
269 int64_t pts) {
270 if (!mTrack->isTimedTrack())
271 return INVALID_OPERATION;
272
273 PlaybackThread::TimedTrack* tt =
274 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
275 return tt->queueTimedBuffer(buffer, pts);
276}
277
278status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
279 const LinearTransform& xform, int target) {
280
281 if (!mTrack->isTimedTrack())
282 return INVALID_OPERATION;
283
284 PlaybackThread::TimedTrack* tt =
285 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
286 return tt->setMediaTimeTransform(
287 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
288}
289
290status_t AudioFlinger::TrackHandle::onTransact(
291 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
292{
293 return BnAudioTrack::onTransact(code, data, reply, flags);
294}
295
296// ----------------------------------------------------------------------------
297
298// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
299AudioFlinger::PlaybackThread::Track::Track(
300 PlaybackThread *thread,
301 const sp<Client>& client,
302 audio_stream_type_t streamType,
303 uint32_t sampleRate,
304 audio_format_t format,
305 audio_channel_mask_t channelMask,
306 size_t frameCount,
307 const sp<IMemory>& sharedBuffer,
308 int sessionId,
309 IAudioFlinger::track_flags_t flags)
310 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -0800311 sessionId, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800312 mFillingUpStatus(FS_INVALID),
313 // mRetryCount initialized later when needed
314 mSharedBuffer(sharedBuffer),
315 mStreamType(streamType),
316 mName(-1), // see note below
317 mMainBuffer(thread->mixBuffer()),
318 mAuxBuffer(NULL),
319 mAuxEffectId(0), mHasVolumeController(false),
320 mPresentationCompleteFrames(0),
321 mFlags(flags),
322 mFastIndex(-1),
323 mUnderrunCount(0),
Glenn Kasten5736c352012-12-04 12:12:34 -0800324 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800325 mIsInvalid(false),
326 mAudioTrackServerProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -0800327{
328 if (mCblk != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800329 if (sharedBuffer == 0) {
330 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
331 mFrameSize);
332 } else {
333 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
334 mFrameSize);
335 }
336 mServerProxy = mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800337 // to avoid leaking a track name, do not allocate one unless there is an mCblk
338 mName = thread->getTrackName_l(channelMask, sessionId);
339 mCblk->mName = mName;
340 if (mName < 0) {
341 ALOGE("no more track names available");
342 return;
343 }
344 // only allocate a fast track index if we were able to allocate a normal track name
345 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800346 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Eric Laurent81784c32012-11-19 14:55:58 -0800347 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
348 int i = __builtin_ctz(thread->mFastTrackAvailMask);
349 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
350 // FIXME This is too eager. We allocate a fast track index before the
351 // fast track becomes active. Since fast tracks are a scarce resource,
352 // this means we are potentially denying other more important fast tracks from
353 // being created. It would be better to allocate the index dynamically.
354 mFastIndex = i;
355 mCblk->mName = i;
356 // Read the initial underruns because this field is never cleared by the fast mixer
357 mObservedUnderruns = thread->getFastTrackUnderruns(i);
358 thread->mFastTrackAvailMask &= ~(1 << i);
359 }
360 }
361 ALOGV("Track constructor name %d, calling pid %d", mName,
362 IPCThreadState::self()->getCallingPid());
363}
364
365AudioFlinger::PlaybackThread::Track::~Track()
366{
367 ALOGV("PlaybackThread::Track destructor");
368}
369
370void AudioFlinger::PlaybackThread::Track::destroy()
371{
372 // NOTE: destroyTrack_l() can remove a strong reference to this Track
373 // by removing it from mTracks vector, so there is a risk that this Tracks's
374 // destructor is called. As the destructor needs to lock mLock,
375 // we must acquire a strong reference on this Track before locking mLock
376 // here so that the destructor is called only when exiting this function.
377 // On the other hand, as long as Track::destroy() is only called by
378 // TrackHandle destructor, the TrackHandle still holds a strong ref on
379 // this Track with its member mTrack.
380 sp<Track> keep(this);
381 { // scope for mLock
382 sp<ThreadBase> thread = mThread.promote();
383 if (thread != 0) {
384 if (!isOutputTrack()) {
385 if (mState == ACTIVE || mState == RESUMING) {
386 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
387
388#ifdef ADD_BATTERY_DATA
389 // to track the speaker usage
390 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
391#endif
392 }
393 AudioSystem::releaseOutput(thread->id());
394 }
395 Mutex::Autolock _l(thread->mLock);
396 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
397 playbackThread->destroyTrack_l(this);
398 }
399 }
400}
401
402/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
403{
Glenn Kastene4756fe2012-11-29 13:38:14 -0800404 result.append(" Name Client Type Fmt Chn mask Session StpCnt fCount S F SRate "
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800405 "L dB R dB Server Main buf Aux Buf Flags Underruns\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800406}
407
408void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
409{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800410 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800411 if (isFastTrack()) {
412 sprintf(buffer, " F %2d", mFastIndex);
413 } else {
414 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
415 }
416 track_state state = mState;
417 char stateChar;
418 switch (state) {
419 case IDLE:
420 stateChar = 'I';
421 break;
422 case TERMINATED:
423 stateChar = 'T';
424 break;
425 case STOPPING_1:
426 stateChar = 's';
427 break;
428 case STOPPING_2:
429 stateChar = '5';
430 break;
431 case STOPPED:
432 stateChar = 'S';
433 break;
434 case RESUMING:
435 stateChar = 'R';
436 break;
437 case ACTIVE:
438 stateChar = 'A';
439 break;
440 case PAUSING:
441 stateChar = 'p';
442 break;
443 case PAUSED:
444 stateChar = 'P';
445 break;
446 case FLUSHED:
447 stateChar = 'F';
448 break;
449 default:
450 stateChar = '?';
451 break;
452 }
453 char nowInUnderrun;
454 switch (mObservedUnderruns.mBitFields.mMostRecent) {
455 case UNDERRUN_FULL:
456 nowInUnderrun = ' ';
457 break;
458 case UNDERRUN_PARTIAL:
459 nowInUnderrun = '<';
460 break;
461 case UNDERRUN_EMPTY:
462 nowInUnderrun = '*';
463 break;
464 default:
465 nowInUnderrun = '?';
466 break;
467 }
Glenn Kastene4756fe2012-11-29 13:38:14 -0800468 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 -0800469 "0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800470 (mClient == 0) ? getpid_cached : mClient->pid(),
471 mStreamType,
472 mFormat,
473 mChannelMask,
474 mSessionId,
475 mStepCount,
476 mFrameCount,
477 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800478 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800479 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800480 20.0 * log10((vlr & 0xFFFF) / 4096.0),
481 20.0 * log10((vlr >> 16) / 4096.0),
482 mCblk->server,
Eric Laurent81784c32012-11-19 14:55:58 -0800483 (int)mMainBuffer,
484 (int)mAuxBuffer,
485 mCblk->flags,
486 mUnderrunCount,
487 nowInUnderrun);
488}
489
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800490uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
491 return mAudioTrackServerProxy->getSampleRate();
492}
493
Eric Laurent81784c32012-11-19 14:55:58 -0800494// AudioBufferProvider interface
495status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
496 AudioBufferProvider::Buffer* buffer, int64_t pts)
497{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800498 ServerProxy::Buffer buf;
499 size_t desiredFrames = buffer->frameCount;
500 buf.mFrameCount = desiredFrames;
501 status_t status = mServerProxy->obtainBuffer(&buf);
502 buffer->frameCount = buf.mFrameCount;
503 buffer->raw = buf.mRaw;
504 if (buf.mFrameCount == 0) {
505 // only implemented so far for normal tracks, not fast tracks
506 mCblk->u.mStreaming.mUnderrunFrames += desiredFrames;
507 // FIXME also wake futex so that underrun is noticed more quickly
508 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800510 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800511}
512
513// Note that framesReady() takes a mutex on the control block using tryLock().
514// This could result in priority inversion if framesReady() is called by the normal mixer,
515// as the normal mixer thread runs at lower
516// priority than the client's callback thread: there is a short window within framesReady()
517// during which the normal mixer could be preempted, and the client callback would block.
518// Another problem can occur if framesReady() is called by the fast mixer:
519// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
520// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
521size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800522 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800523}
524
525// Don't call for fast tracks; the framesReady() could result in priority inversion
526bool AudioFlinger::PlaybackThread::Track::isReady() const {
527 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
528 return true;
529 }
530
531 if (framesReady() >= mFrameCount ||
532 (mCblk->flags & CBLK_FORCEREADY)) {
533 mFillingUpStatus = FS_FILLED;
534 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
535 return true;
536 }
537 return false;
538}
539
540status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
541 int triggerSession)
542{
543 status_t status = NO_ERROR;
544 ALOGV("start(%d), calling pid %d session %d",
545 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
546
547 sp<ThreadBase> thread = mThread.promote();
548 if (thread != 0) {
549 Mutex::Autolock _l(thread->mLock);
550 track_state state = mState;
551 // here the track could be either new, or restarted
552 // in both cases "unstop" the track
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800553 if (state == PAUSED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800554 mState = TrackBase::RESUMING;
555 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
556 } else {
557 mState = TrackBase::ACTIVE;
558 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
559 }
560
561 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
562 thread->mLock.unlock();
563 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
564 thread->mLock.lock();
565
566#ifdef ADD_BATTERY_DATA
567 // to track the speaker usage
568 if (status == NO_ERROR) {
569 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
570 }
571#endif
572 }
573 if (status == NO_ERROR) {
574 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
575 playbackThread->addTrack_l(this);
576 } else {
577 mState = state;
578 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
579 }
580 } else {
581 status = BAD_VALUE;
582 }
583 return status;
584}
585
586void AudioFlinger::PlaybackThread::Track::stop()
587{
588 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
589 sp<ThreadBase> thread = mThread.promote();
590 if (thread != 0) {
591 Mutex::Autolock _l(thread->mLock);
592 track_state state = mState;
593 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
594 // If the track is not active (PAUSED and buffers full), flush buffers
595 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
596 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
597 reset();
598 mState = STOPPED;
599 } else if (!isFastTrack()) {
600 mState = STOPPED;
601 } else {
602 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
603 // and then to STOPPED and reset() when presentation is complete
604 mState = STOPPING_1;
605 }
606 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
607 playbackThread);
608 }
609 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
610 thread->mLock.unlock();
611 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
612 thread->mLock.lock();
613
614#ifdef ADD_BATTERY_DATA
615 // to track the speaker usage
616 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
617#endif
618 }
619 }
620}
621
622void AudioFlinger::PlaybackThread::Track::pause()
623{
624 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
625 sp<ThreadBase> thread = mThread.promote();
626 if (thread != 0) {
627 Mutex::Autolock _l(thread->mLock);
628 if (mState == ACTIVE || mState == RESUMING) {
629 mState = PAUSING;
630 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
631 if (!isOutputTrack()) {
632 thread->mLock.unlock();
633 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
634 thread->mLock.lock();
635
636#ifdef ADD_BATTERY_DATA
637 // to track the speaker usage
638 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
639#endif
640 }
641 }
642 }
643}
644
645void AudioFlinger::PlaybackThread::Track::flush()
646{
647 ALOGV("flush(%d)", mName);
648 sp<ThreadBase> thread = mThread.promote();
649 if (thread != 0) {
650 Mutex::Autolock _l(thread->mLock);
651 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
652 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
653 return;
654 }
655 // No point remaining in PAUSED state after a flush => go to
656 // FLUSHED state
657 mState = FLUSHED;
658 // do not reset the track if it is still in the process of being stopped or paused.
659 // this will be done by prepareTracks_l() when the track is stopped.
660 // prepareTracks_l() will see mState == FLUSHED, then
661 // remove from active track list, reset(), and trigger presentation complete
662 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
663 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
664 reset();
665 }
666 }
667}
668
669void AudioFlinger::PlaybackThread::Track::reset()
670{
671 // Do not reset twice to avoid discarding data written just after a flush and before
672 // the audioflinger thread detects the track is stopped.
673 if (!mResetDone) {
674 TrackBase::reset();
675 // Force underrun condition to avoid false underrun callback until first data is
676 // written to buffer
677 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
Eric Laurent81784c32012-11-19 14:55:58 -0800678 mFillingUpStatus = FS_FILLING;
679 mResetDone = true;
680 if (mState == FLUSHED) {
681 mState = IDLE;
682 }
683 }
684}
685
Eric Laurent81784c32012-11-19 14:55:58 -0800686status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
687{
688 status_t status = DEAD_OBJECT;
689 sp<ThreadBase> thread = mThread.promote();
690 if (thread != 0) {
691 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
692 sp<AudioFlinger> af = mClient->audioFlinger();
693
694 Mutex::Autolock _l(af->mLock);
695
696 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
697
698 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
699 Mutex::Autolock _dl(playbackThread->mLock);
700 Mutex::Autolock _sl(srcThread->mLock);
701 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
702 if (chain == 0) {
703 return INVALID_OPERATION;
704 }
705
706 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
707 if (effect == 0) {
708 return INVALID_OPERATION;
709 }
710 srcThread->removeEffect_l(effect);
711 playbackThread->addEffect_l(effect);
712 // removeEffect_l() has stopped the effect if it was active so it must be restarted
713 if (effect->state() == EffectModule::ACTIVE ||
714 effect->state() == EffectModule::STOPPING) {
715 effect->start();
716 }
717
718 sp<EffectChain> dstChain = effect->chain().promote();
719 if (dstChain == 0) {
720 srcThread->addEffect_l(effect);
721 return INVALID_OPERATION;
722 }
723 AudioSystem::unregisterEffect(effect->id());
724 AudioSystem::registerEffect(&effect->desc(),
725 srcThread->id(),
726 dstChain->strategy(),
727 AUDIO_SESSION_OUTPUT_MIX,
728 effect->id());
729 }
730 status = playbackThread->attachAuxEffect(this, EffectId);
731 }
732 return status;
733}
734
735void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
736{
737 mAuxEffectId = EffectId;
738 mAuxBuffer = buffer;
739}
740
741bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
742 size_t audioHalFrames)
743{
744 // a track is considered presented when the total number of frames written to audio HAL
745 // corresponds to the number of frames written when presentationComplete() is called for the
746 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
747 if (mPresentationCompleteFrames == 0) {
748 mPresentationCompleteFrames = framesWritten + audioHalFrames;
749 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
750 mPresentationCompleteFrames, audioHalFrames);
751 }
752 if (framesWritten >= mPresentationCompleteFrames) {
753 ALOGV("presentationComplete() session %d complete: framesWritten %d",
754 mSessionId, framesWritten);
755 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
756 return true;
757 }
758 return false;
759}
760
761void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
762{
763 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
764 if (mSyncEvents[i]->type() == type) {
765 mSyncEvents[i]->trigger();
766 mSyncEvents.removeAt(i);
767 i--;
768 }
769 }
770}
771
772// implement VolumeBufferProvider interface
773
774uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
775{
776 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
777 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800778 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800779 uint32_t vl = vlr & 0xFFFF;
780 uint32_t vr = vlr >> 16;
781 // track volumes come from shared memory, so can't be trusted and must be clamped
782 if (vl > MAX_GAIN_INT) {
783 vl = MAX_GAIN_INT;
784 }
785 if (vr > MAX_GAIN_INT) {
786 vr = MAX_GAIN_INT;
787 }
788 // now apply the cached master volume and stream type volume;
789 // this is trusted but lacks any synchronization or barrier so may be stale
790 float v = mCachedVolume;
791 vl *= v;
792 vr *= v;
793 // re-combine into U4.16
794 vlr = (vr << 16) | (vl & 0xFFFF);
795 // FIXME look at mute, pause, and stop flags
796 return vlr;
797}
798
799status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
800{
801 if (mState == TERMINATED || mState == PAUSED ||
802 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
803 (mState == STOPPED)))) {
804 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
805 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
806 event->cancel();
807 return INVALID_OPERATION;
808 }
809 (void) TrackBase::setSyncEvent(event);
810 return NO_ERROR;
811}
812
Glenn Kasten5736c352012-12-04 12:12:34 -0800813void AudioFlinger::PlaybackThread::Track::invalidate()
814{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800815 // FIXME should use proxy, and needs work
816 audio_track_cblk_t* cblk = mCblk;
817 android_atomic_or(CBLK_INVALID, &cblk->flags);
818 android_atomic_release_store(0x40000000, &cblk->mFutex);
819 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
820 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800821 mIsInvalid = true;
822}
823
Eric Laurent81784c32012-11-19 14:55:58 -0800824// ----------------------------------------------------------------------------
825
826sp<AudioFlinger::PlaybackThread::TimedTrack>
827AudioFlinger::PlaybackThread::TimedTrack::create(
828 PlaybackThread *thread,
829 const sp<Client>& client,
830 audio_stream_type_t streamType,
831 uint32_t sampleRate,
832 audio_format_t format,
833 audio_channel_mask_t channelMask,
834 size_t frameCount,
835 const sp<IMemory>& sharedBuffer,
836 int sessionId) {
837 if (!client->reserveTimedTrack())
838 return 0;
839
840 return new TimedTrack(
841 thread, client, streamType, sampleRate, format, channelMask, frameCount,
842 sharedBuffer, sessionId);
843}
844
845AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
846 PlaybackThread *thread,
847 const sp<Client>& client,
848 audio_stream_type_t streamType,
849 uint32_t sampleRate,
850 audio_format_t format,
851 audio_channel_mask_t channelMask,
852 size_t frameCount,
853 const sp<IMemory>& sharedBuffer,
854 int sessionId)
855 : Track(thread, client, streamType, sampleRate, format, channelMask,
856 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
857 mQueueHeadInFlight(false),
858 mTrimQueueHeadOnRelease(false),
859 mFramesPendingInQueue(0),
860 mTimedSilenceBuffer(NULL),
861 mTimedSilenceBufferSize(0),
862 mTimedAudioOutputOnTime(false),
863 mMediaTimeTransformValid(false)
864{
865 LocalClock lc;
866 mLocalTimeFreq = lc.getLocalFreq();
867
868 mLocalTimeToSampleTransform.a_zero = 0;
869 mLocalTimeToSampleTransform.b_zero = 0;
870 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
871 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
872 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
873 &mLocalTimeToSampleTransform.a_to_b_denom);
874
875 mMediaTimeToSampleTransform.a_zero = 0;
876 mMediaTimeToSampleTransform.b_zero = 0;
877 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
878 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
879 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
880 &mMediaTimeToSampleTransform.a_to_b_denom);
881}
882
883AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
884 mClient->releaseTimedTrack();
885 delete [] mTimedSilenceBuffer;
886}
887
888status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
889 size_t size, sp<IMemory>* buffer) {
890
891 Mutex::Autolock _l(mTimedBufferQueueLock);
892
893 trimTimedBufferQueue_l();
894
895 // lazily initialize the shared memory heap for timed buffers
896 if (mTimedMemoryDealer == NULL) {
897 const int kTimedBufferHeapSize = 512 << 10;
898
899 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
900 "AudioFlingerTimed");
901 if (mTimedMemoryDealer == NULL)
902 return NO_MEMORY;
903 }
904
905 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
906 if (newBuffer == NULL) {
907 newBuffer = mTimedMemoryDealer->allocate(size);
908 if (newBuffer == NULL)
909 return NO_MEMORY;
910 }
911
912 *buffer = newBuffer;
913 return NO_ERROR;
914}
915
916// caller must hold mTimedBufferQueueLock
917void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
918 int64_t mediaTimeNow;
919 {
920 Mutex::Autolock mttLock(mMediaTimeTransformLock);
921 if (!mMediaTimeTransformValid)
922 return;
923
924 int64_t targetTimeNow;
925 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
926 ? mCCHelper.getCommonTime(&targetTimeNow)
927 : mCCHelper.getLocalTime(&targetTimeNow);
928
929 if (OK != res)
930 return;
931
932 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
933 &mediaTimeNow)) {
934 return;
935 }
936 }
937
938 size_t trimEnd;
939 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
940 int64_t bufEnd;
941
942 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
943 // We have a next buffer. Just use its PTS as the PTS of the frame
944 // following the last frame in this buffer. If the stream is sparse
945 // (ie, there are deliberate gaps left in the stream which should be
946 // filled with silence by the TimedAudioTrack), then this can result
947 // in one extra buffer being left un-trimmed when it could have
948 // been. In general, this is not typical, and we would rather
949 // optimized away the TS calculation below for the more common case
950 // where PTSes are contiguous.
951 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
952 } else {
953 // We have no next buffer. Compute the PTS of the frame following
954 // the last frame in this buffer by computing the duration of of
955 // this frame in media time units and adding it to the PTS of the
956 // buffer.
957 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
958 / mFrameSize;
959
960 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
961 &bufEnd)) {
962 ALOGE("Failed to convert frame count of %lld to media time"
963 " duration" " (scale factor %d/%u) in %s",
964 frameCount,
965 mMediaTimeToSampleTransform.a_to_b_numer,
966 mMediaTimeToSampleTransform.a_to_b_denom,
967 __PRETTY_FUNCTION__);
968 break;
969 }
970 bufEnd += mTimedBufferQueue[trimEnd].pts();
971 }
972
973 if (bufEnd > mediaTimeNow)
974 break;
975
976 // Is the buffer we want to use in the middle of a mix operation right
977 // now? If so, don't actually trim it. Just wait for the releaseBuffer
978 // from the mixer which should be coming back shortly.
979 if (!trimEnd && mQueueHeadInFlight) {
980 mTrimQueueHeadOnRelease = true;
981 }
982 }
983
984 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
985 if (trimStart < trimEnd) {
986 // Update the bookkeeping for framesReady()
987 for (size_t i = trimStart; i < trimEnd; ++i) {
988 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
989 }
990
991 // Now actually remove the buffers from the queue.
992 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
993 }
994}
995
996void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
997 const char* logTag) {
998 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
999 "%s called (reason \"%s\"), but timed buffer queue has no"
1000 " elements to trim.", __FUNCTION__, logTag);
1001
1002 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1003 mTimedBufferQueue.removeAt(0);
1004}
1005
1006void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1007 const TimedBuffer& buf,
1008 const char* logTag) {
1009 uint32_t bufBytes = buf.buffer()->size();
1010 uint32_t consumedAlready = buf.position();
1011
1012 ALOG_ASSERT(consumedAlready <= bufBytes,
1013 "Bad bookkeeping while updating frames pending. Timed buffer is"
1014 " only %u bytes long, but claims to have consumed %u"
1015 " bytes. (update reason: \"%s\")",
1016 bufBytes, consumedAlready, logTag);
1017
1018 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1019 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1020 "Bad bookkeeping while updating frames pending. Should have at"
1021 " least %u queued frames, but we think we have only %u. (update"
1022 " reason: \"%s\")",
1023 bufFrames, mFramesPendingInQueue, logTag);
1024
1025 mFramesPendingInQueue -= bufFrames;
1026}
1027
1028status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1029 const sp<IMemory>& buffer, int64_t pts) {
1030
1031 {
1032 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1033 if (!mMediaTimeTransformValid)
1034 return INVALID_OPERATION;
1035 }
1036
1037 Mutex::Autolock _l(mTimedBufferQueueLock);
1038
1039 uint32_t bufFrames = buffer->size() / mFrameSize;
1040 mFramesPendingInQueue += bufFrames;
1041 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1042
1043 return NO_ERROR;
1044}
1045
1046status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1047 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1048
1049 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1050 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1051 target);
1052
1053 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1054 target == TimedAudioTrack::COMMON_TIME)) {
1055 return BAD_VALUE;
1056 }
1057
1058 Mutex::Autolock lock(mMediaTimeTransformLock);
1059 mMediaTimeTransform = xform;
1060 mMediaTimeTransformTarget = target;
1061 mMediaTimeTransformValid = true;
1062
1063 return NO_ERROR;
1064}
1065
1066#define min(a, b) ((a) < (b) ? (a) : (b))
1067
1068// implementation of getNextBuffer for tracks whose buffers have timestamps
1069status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1070 AudioBufferProvider::Buffer* buffer, int64_t pts)
1071{
1072 if (pts == AudioBufferProvider::kInvalidPTS) {
1073 buffer->raw = NULL;
1074 buffer->frameCount = 0;
1075 mTimedAudioOutputOnTime = false;
1076 return INVALID_OPERATION;
1077 }
1078
1079 Mutex::Autolock _l(mTimedBufferQueueLock);
1080
1081 ALOG_ASSERT(!mQueueHeadInFlight,
1082 "getNextBuffer called without releaseBuffer!");
1083
1084 while (true) {
1085
1086 // if we have no timed buffers, then fail
1087 if (mTimedBufferQueue.isEmpty()) {
1088 buffer->raw = NULL;
1089 buffer->frameCount = 0;
1090 return NOT_ENOUGH_DATA;
1091 }
1092
1093 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1094
1095 // calculate the PTS of the head of the timed buffer queue expressed in
1096 // local time
1097 int64_t headLocalPTS;
1098 {
1099 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1100
1101 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1102
1103 if (mMediaTimeTransform.a_to_b_denom == 0) {
1104 // the transform represents a pause, so yield silence
1105 timedYieldSilence_l(buffer->frameCount, buffer);
1106 return NO_ERROR;
1107 }
1108
1109 int64_t transformedPTS;
1110 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1111 &transformedPTS)) {
1112 // the transform failed. this shouldn't happen, but if it does
1113 // then just drop this buffer
1114 ALOGW("timedGetNextBuffer transform failed");
1115 buffer->raw = NULL;
1116 buffer->frameCount = 0;
1117 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1118 return NO_ERROR;
1119 }
1120
1121 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1122 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1123 &headLocalPTS)) {
1124 buffer->raw = NULL;
1125 buffer->frameCount = 0;
1126 return INVALID_OPERATION;
1127 }
1128 } else {
1129 headLocalPTS = transformedPTS;
1130 }
1131 }
1132
1133 // adjust the head buffer's PTS to reflect the portion of the head buffer
1134 // that has already been consumed
1135 int64_t effectivePTS = headLocalPTS +
1136 ((head.position() / mFrameSize) * mLocalTimeFreq / sampleRate());
1137
1138 // Calculate the delta in samples between the head of the input buffer
1139 // queue and the start of the next output buffer that will be written.
1140 // If the transformation fails because of over or underflow, it means
1141 // that the sample's position in the output stream is so far out of
1142 // whack that it should just be dropped.
1143 int64_t sampleDelta;
1144 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1145 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1146 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1147 " mix");
1148 continue;
1149 }
1150 if (!mLocalTimeToSampleTransform.doForwardTransform(
1151 (effectivePTS - pts) << 32, &sampleDelta)) {
1152 ALOGV("*** too late during sample rate transform: dropped buffer");
1153 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1154 continue;
1155 }
1156
1157 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1158 " sampleDelta=[%d.%08x]",
1159 head.pts(), head.position(), pts,
1160 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1161 + (sampleDelta >> 32)),
1162 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1163
1164 // if the delta between the ideal placement for the next input sample and
1165 // the current output position is within this threshold, then we will
1166 // concatenate the next input samples to the previous output
1167 const int64_t kSampleContinuityThreshold =
1168 (static_cast<int64_t>(sampleRate()) << 32) / 250;
1169
1170 // if this is the first buffer of audio that we're emitting from this track
1171 // then it should be almost exactly on time.
1172 const int64_t kSampleStartupThreshold = 1LL << 32;
1173
1174 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1175 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1176 // the next input is close enough to being on time, so concatenate it
1177 // with the last output
1178 timedYieldSamples_l(buffer);
1179
1180 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1181 head.position(), buffer->frameCount);
1182 return NO_ERROR;
1183 }
1184
1185 // Looks like our output is not on time. Reset our on timed status.
1186 // Next time we mix samples from our input queue, then should be within
1187 // the StartupThreshold.
1188 mTimedAudioOutputOnTime = false;
1189 if (sampleDelta > 0) {
1190 // the gap between the current output position and the proper start of
1191 // the next input sample is too big, so fill it with silence
1192 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1193
1194 timedYieldSilence_l(framesUntilNextInput, buffer);
1195 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1196 return NO_ERROR;
1197 } else {
1198 // the next input sample is late
1199 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1200 size_t onTimeSamplePosition =
1201 head.position() + lateFrames * mFrameSize;
1202
1203 if (onTimeSamplePosition > head.buffer()->size()) {
1204 // all the remaining samples in the head are too late, so
1205 // drop it and move on
1206 ALOGV("*** too late: dropped buffer");
1207 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1208 continue;
1209 } else {
1210 // skip over the late samples
1211 head.setPosition(onTimeSamplePosition);
1212
1213 // yield the available samples
1214 timedYieldSamples_l(buffer);
1215
1216 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1217 return NO_ERROR;
1218 }
1219 }
1220 }
1221}
1222
1223// Yield samples from the timed buffer queue head up to the given output
1224// buffer's capacity.
1225//
1226// Caller must hold mTimedBufferQueueLock
1227void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1228 AudioBufferProvider::Buffer* buffer) {
1229
1230 const TimedBuffer& head = mTimedBufferQueue[0];
1231
1232 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1233 head.position());
1234
1235 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1236 mFrameSize);
1237 size_t framesRequested = buffer->frameCount;
1238 buffer->frameCount = min(framesLeftInHead, framesRequested);
1239
1240 mQueueHeadInFlight = true;
1241 mTimedAudioOutputOnTime = true;
1242}
1243
1244// Yield samples of silence up to the given output buffer's capacity
1245//
1246// Caller must hold mTimedBufferQueueLock
1247void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1248 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1249
1250 // lazily allocate a buffer filled with silence
1251 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1252 delete [] mTimedSilenceBuffer;
1253 mTimedSilenceBufferSize = numFrames * mFrameSize;
1254 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1255 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1256 }
1257
1258 buffer->raw = mTimedSilenceBuffer;
1259 size_t framesRequested = buffer->frameCount;
1260 buffer->frameCount = min(numFrames, framesRequested);
1261
1262 mTimedAudioOutputOnTime = false;
1263}
1264
1265// AudioBufferProvider interface
1266void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1267 AudioBufferProvider::Buffer* buffer) {
1268
1269 Mutex::Autolock _l(mTimedBufferQueueLock);
1270
1271 // If the buffer which was just released is part of the buffer at the head
1272 // of the queue, be sure to update the amt of the buffer which has been
1273 // consumed. If the buffer being returned is not part of the head of the
1274 // queue, its either because the buffer is part of the silence buffer, or
1275 // because the head of the timed queue was trimmed after the mixer called
1276 // getNextBuffer but before the mixer called releaseBuffer.
1277 if (buffer->raw == mTimedSilenceBuffer) {
1278 ALOG_ASSERT(!mQueueHeadInFlight,
1279 "Queue head in flight during release of silence buffer!");
1280 goto done;
1281 }
1282
1283 ALOG_ASSERT(mQueueHeadInFlight,
1284 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1285 " head in flight.");
1286
1287 if (mTimedBufferQueue.size()) {
1288 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1289
1290 void* start = head.buffer()->pointer();
1291 void* end = reinterpret_cast<void*>(
1292 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1293 + head.buffer()->size());
1294
1295 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1296 "released buffer not within the head of the timed buffer"
1297 " queue; qHead = [%p, %p], released buffer = %p",
1298 start, end, buffer->raw);
1299
1300 head.setPosition(head.position() +
1301 (buffer->frameCount * mFrameSize));
1302 mQueueHeadInFlight = false;
1303
1304 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1305 "Bad bookkeeping during releaseBuffer! Should have at"
1306 " least %u queued frames, but we think we have only %u",
1307 buffer->frameCount, mFramesPendingInQueue);
1308
1309 mFramesPendingInQueue -= buffer->frameCount;
1310
1311 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1312 || mTrimQueueHeadOnRelease) {
1313 trimTimedBufferQueueHead_l("releaseBuffer");
1314 mTrimQueueHeadOnRelease = false;
1315 }
1316 } else {
1317 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1318 " buffers in the timed buffer queue");
1319 }
1320
1321done:
1322 buffer->raw = 0;
1323 buffer->frameCount = 0;
1324}
1325
1326size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1327 Mutex::Autolock _l(mTimedBufferQueueLock);
1328 return mFramesPendingInQueue;
1329}
1330
1331AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1332 : mPTS(0), mPosition(0) {}
1333
1334AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1335 const sp<IMemory>& buffer, int64_t pts)
1336 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1337
1338
1339// ----------------------------------------------------------------------------
1340
1341AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1342 PlaybackThread *playbackThread,
1343 DuplicatingThread *sourceThread,
1344 uint32_t sampleRate,
1345 audio_format_t format,
1346 audio_channel_mask_t channelMask,
1347 size_t frameCount)
1348 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1349 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001350 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001351{
1352
1353 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001354 mOutBuffer.frameCount = 0;
1355 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001356 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
1357 "mCblk->frameCount_ %u, mChannelMask 0x%08x mBufferEnd %p",
1358 mCblk, mBuffer,
1359 mCblk->frameCount_, mChannelMask, mBufferEnd);
1360 // since client and server are in the same process,
1361 // the buffer has the same virtual address on both sides
1362 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001363 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1364 mClientProxy->setSendLevel(0.0);
1365 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001366 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1367 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001368 } else {
1369 ALOGW("Error creating output track on thread %p", playbackThread);
1370 }
1371}
1372
1373AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1374{
1375 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001376 delete mClientProxy;
1377 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001378}
1379
1380status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1381 int triggerSession)
1382{
1383 status_t status = Track::start(event, triggerSession);
1384 if (status != NO_ERROR) {
1385 return status;
1386 }
1387
1388 mActive = true;
1389 mRetryCount = 127;
1390 return status;
1391}
1392
1393void AudioFlinger::PlaybackThread::OutputTrack::stop()
1394{
1395 Track::stop();
1396 clearBufferQueue();
1397 mOutBuffer.frameCount = 0;
1398 mActive = false;
1399}
1400
1401bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1402{
1403 Buffer *pInBuffer;
1404 Buffer inBuffer;
1405 uint32_t channelCount = mChannelCount;
1406 bool outputBufferFull = false;
1407 inBuffer.frameCount = frames;
1408 inBuffer.i16 = data;
1409
1410 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1411
1412 if (!mActive && frames != 0) {
1413 start();
1414 sp<ThreadBase> thread = mThread.promote();
1415 if (thread != 0) {
1416 MixerThread *mixerThread = (MixerThread *)thread.get();
1417 if (mFrameCount > frames) {
1418 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1419 uint32_t startFrames = (mFrameCount - frames);
1420 pInBuffer = new Buffer;
1421 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1422 pInBuffer->frameCount = startFrames;
1423 pInBuffer->i16 = pInBuffer->mBuffer;
1424 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1425 mBufferQueue.add(pInBuffer);
1426 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001427 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001428 }
1429 }
1430 }
1431 }
1432
1433 while (waitTimeLeftMs) {
1434 // First write pending buffers, then new data
1435 if (mBufferQueue.size()) {
1436 pInBuffer = mBufferQueue.itemAt(0);
1437 } else {
1438 pInBuffer = &inBuffer;
1439 }
1440
1441 if (pInBuffer->frameCount == 0) {
1442 break;
1443 }
1444
1445 if (mOutBuffer.frameCount == 0) {
1446 mOutBuffer.frameCount = pInBuffer->frameCount;
1447 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001448 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1449 if (status != NO_ERROR) {
1450 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1451 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001452 outputBufferFull = true;
1453 break;
1454 }
1455 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1456 if (waitTimeLeftMs >= waitTimeMs) {
1457 waitTimeLeftMs -= waitTimeMs;
1458 } else {
1459 waitTimeLeftMs = 0;
1460 }
1461 }
1462
1463 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1464 pInBuffer->frameCount;
1465 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001466 Proxy::Buffer buf;
1467 buf.mFrameCount = outFrames;
1468 buf.mRaw = NULL;
1469 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001470 pInBuffer->frameCount -= outFrames;
1471 pInBuffer->i16 += outFrames * channelCount;
1472 mOutBuffer.frameCount -= outFrames;
1473 mOutBuffer.i16 += outFrames * channelCount;
1474
1475 if (pInBuffer->frameCount == 0) {
1476 if (mBufferQueue.size()) {
1477 mBufferQueue.removeAt(0);
1478 delete [] pInBuffer->mBuffer;
1479 delete pInBuffer;
1480 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1481 mThread.unsafe_get(), mBufferQueue.size());
1482 } else {
1483 break;
1484 }
1485 }
1486 }
1487
1488 // If we could not write all frames, allocate a buffer and queue it for next time.
1489 if (inBuffer.frameCount) {
1490 sp<ThreadBase> thread = mThread.promote();
1491 if (thread != 0 && !thread->standby()) {
1492 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1493 pInBuffer = new Buffer;
1494 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1495 pInBuffer->frameCount = inBuffer.frameCount;
1496 pInBuffer->i16 = pInBuffer->mBuffer;
1497 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1498 sizeof(int16_t));
1499 mBufferQueue.add(pInBuffer);
1500 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1501 mThread.unsafe_get(), mBufferQueue.size());
1502 } else {
1503 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1504 mThread.unsafe_get(), this);
1505 }
1506 }
1507 }
1508
1509 // Calling write() with a 0 length buffer, means that no more data will be written:
1510 // If no more buffers are pending, fill output track buffer to make sure it is started
1511 // by output mixer.
1512 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001513 // FIXME borken, replace by getting framesReady() from proxy
1514 size_t user = 0; // was mCblk->user
1515 if (user < mFrameCount) {
1516 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001517 pInBuffer = new Buffer;
1518 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1519 pInBuffer->frameCount = frames;
1520 pInBuffer->i16 = pInBuffer->mBuffer;
1521 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1522 mBufferQueue.add(pInBuffer);
1523 } else if (mActive) {
1524 stop();
1525 }
1526 }
1527
1528 return outputBufferFull;
1529}
1530
1531status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1532 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1533{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001534 ClientProxy::Buffer buf;
1535 buf.mFrameCount = buffer->frameCount;
1536 struct timespec timeout;
1537 timeout.tv_sec = waitTimeMs / 1000;
1538 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1539 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1540 buffer->frameCount = buf.mFrameCount;
1541 buffer->raw = buf.mRaw;
1542 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001543}
1544
Eric Laurent81784c32012-11-19 14:55:58 -08001545void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1546{
1547 size_t size = mBufferQueue.size();
1548
1549 for (size_t i = 0; i < size; i++) {
1550 Buffer *pBuffer = mBufferQueue.itemAt(i);
1551 delete [] pBuffer->mBuffer;
1552 delete pBuffer;
1553 }
1554 mBufferQueue.clear();
1555}
1556
1557
1558// ----------------------------------------------------------------------------
1559// Record
1560// ----------------------------------------------------------------------------
1561
1562AudioFlinger::RecordHandle::RecordHandle(
1563 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1564 : BnAudioRecord(),
1565 mRecordTrack(recordTrack)
1566{
1567}
1568
1569AudioFlinger::RecordHandle::~RecordHandle() {
1570 stop_nonvirtual();
1571 mRecordTrack->destroy();
1572}
1573
1574sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1575 return mRecordTrack->getCblk();
1576}
1577
1578status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1579 int triggerSession) {
1580 ALOGV("RecordHandle::start()");
1581 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1582}
1583
1584void AudioFlinger::RecordHandle::stop() {
1585 stop_nonvirtual();
1586}
1587
1588void AudioFlinger::RecordHandle::stop_nonvirtual() {
1589 ALOGV("RecordHandle::stop()");
1590 mRecordTrack->stop();
1591}
1592
1593status_t AudioFlinger::RecordHandle::onTransact(
1594 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1595{
1596 return BnAudioRecord::onTransact(code, data, reply, flags);
1597}
1598
1599// ----------------------------------------------------------------------------
1600
1601// RecordTrack constructor must be called with AudioFlinger::mLock held
1602AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1603 RecordThread *thread,
1604 const sp<Client>& client,
1605 uint32_t sampleRate,
1606 audio_format_t format,
1607 audio_channel_mask_t channelMask,
1608 size_t frameCount,
1609 int sessionId)
1610 : TrackBase(thread, client, sampleRate, format,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001611 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001612 mOverflow(false)
1613{
1614 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001615 if (mCblk != NULL) {
1616 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1617 mFrameSize);
1618 mServerProxy = mAudioRecordServerProxy;
1619 }
Eric Laurent81784c32012-11-19 14:55:58 -08001620}
1621
1622AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1623{
1624 ALOGV("%s", __func__);
1625}
1626
1627// AudioBufferProvider interface
1628status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1629 int64_t pts)
1630{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001631 ServerProxy::Buffer buf;
1632 buf.mFrameCount = buffer->frameCount;
1633 status_t status = mServerProxy->obtainBuffer(&buf);
1634 buffer->frameCount = buf.mFrameCount;
1635 buffer->raw = buf.mRaw;
1636 if (buf.mFrameCount == 0) {
1637 // FIXME also wake futex so that overrun is noticed more quickly
1638 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001639 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001640 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001641}
1642
1643status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1644 int triggerSession)
1645{
1646 sp<ThreadBase> thread = mThread.promote();
1647 if (thread != 0) {
1648 RecordThread *recordThread = (RecordThread *)thread.get();
1649 return recordThread->start(this, event, triggerSession);
1650 } else {
1651 return BAD_VALUE;
1652 }
1653}
1654
1655void AudioFlinger::RecordThread::RecordTrack::stop()
1656{
1657 sp<ThreadBase> thread = mThread.promote();
1658 if (thread != 0) {
1659 RecordThread *recordThread = (RecordThread *)thread.get();
1660 recordThread->mLock.lock();
1661 bool doStop = recordThread->stop_l(this);
1662 if (doStop) {
1663 TrackBase::reset();
1664 // Force overrun condition to avoid false overrun callback until first data is
1665 // read from buffer
1666 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
1667 }
1668 recordThread->mLock.unlock();
1669 if (doStop) {
1670 AudioSystem::stopInput(recordThread->id());
1671 }
1672 }
1673}
1674
1675void AudioFlinger::RecordThread::RecordTrack::destroy()
1676{
1677 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1678 sp<RecordTrack> keep(this);
1679 {
1680 sp<ThreadBase> thread = mThread.promote();
1681 if (thread != 0) {
1682 if (mState == ACTIVE || mState == RESUMING) {
1683 AudioSystem::stopInput(thread->id());
1684 }
1685 AudioSystem::releaseInput(thread->id());
1686 Mutex::Autolock _l(thread->mLock);
1687 RecordThread *recordThread = (RecordThread *) thread.get();
1688 recordThread->destroyTrack_l(this);
1689 }
1690 }
1691}
1692
1693
1694/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1695{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 result.append(" Clien Fmt Chn mask Session Step S Serv FrameCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001697}
1698
1699void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1700{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001701 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %08x %05d\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001702 (mClient == 0) ? getpid_cached : mClient->pid(),
1703 mFormat,
1704 mChannelMask,
1705 mSessionId,
1706 mStepCount,
1707 mState,
Eric Laurent81784c32012-11-19 14:55:58 -08001708 mCblk->server,
Eric Laurent81784c32012-11-19 14:55:58 -08001709 mFrameCount);
1710}
1711
Eric Laurent81784c32012-11-19 14:55:58 -08001712}; // namespace android