1 /*
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 "Configuration.h"
23 #include <linux/futex.h>
24 #include <math.h>
25 #include <sys/syscall.h>
26 #include <utils/Log.h>
27
28 #include <private/media/AudioTrackShared.h>
29
30 #include <common_time/cc_helper.h>
31 #include <common_time/local_clock.h>
32
33 #include "AudioMixer.h"
34 #include "AudioFlinger.h"
35 #include "ServiceUtilities.h"
36
37 #include <media/nbaio/Pipe.h>
38 #include <media/nbaio/PipeReader.h>
39 #include <audio_utils/minifloat.h>
40
41 // ----------------------------------------------------------------------------
42
43 // Note: the following macro is used for extremely verbose logging message. In
44 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
45 // 0; but one side effect of this is to turn all LOGV's as well. Some messages
46 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
47 // turned on. Do not uncomment the #def below unless you really know what you
48 // are doing and want to see all of the extremely verbose messages.
49 //#define VERY_VERY_VERBOSE_LOGGING
50 #ifdef VERY_VERY_VERBOSE_LOGGING
51 #define ALOGVV ALOGV
52 #else
53 #define ALOGVV(a...) do { } while(0)
54 #endif
55
56 namespace android {
57
58 // ----------------------------------------------------------------------------
59 // TrackBase
60 // ----------------------------------------------------------------------------
61
62 static volatile int32_t nextTrackId = 55;
63
64 // TrackBase constructor must be called with AudioFlinger::mLock held
TrackBase(ThreadBase * thread,const sp<Client> & client,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,void * buffer,int sessionId,int clientUid,IAudioFlinger::track_flags_t flags,bool isOut,alloc_type alloc,track_type type)65 AudioFlinger::ThreadBase::TrackBase::TrackBase(
66 ThreadBase *thread,
67 const sp<Client>& client,
68 uint32_t sampleRate,
69 audio_format_t format,
70 audio_channel_mask_t channelMask,
71 size_t frameCount,
72 void *buffer,
73 int sessionId,
74 int clientUid,
75 IAudioFlinger::track_flags_t flags,
76 bool isOut,
77 alloc_type alloc,
78 track_type type)
79 : RefBase(),
80 mThread(thread),
81 mClient(client),
82 mCblk(NULL),
83 // mBuffer
84 mState(IDLE),
85 mSampleRate(sampleRate),
86 mFormat(format),
87 mChannelMask(channelMask),
88 mChannelCount(isOut ?
89 audio_channel_count_from_out_mask(channelMask) :
90 audio_channel_count_from_in_mask(channelMask)),
91 mFrameSize(audio_is_linear_pcm(format) ?
92 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
93 mFrameCount(frameCount),
94 mSessionId(sessionId),
95 mFlags(flags),
96 mIsOut(isOut),
97 mServerProxy(NULL),
98 mId(android_atomic_inc(&nextTrackId)),
99 mTerminated(false),
100 mType(type),
101 mThreadIoHandle(thread->id())
102 {
103 // if the caller is us, trust the specified uid
104 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
105 int newclientUid = IPCThreadState::self()->getCallingUid();
106 if (clientUid != -1 && clientUid != newclientUid) {
107 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
108 }
109 clientUid = newclientUid;
110 }
111 // clientUid contains the uid of the app that is responsible for this track, so we can blame
112 // battery usage on it.
113 mUid = clientUid;
114
115 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
116 size_t size = sizeof(audio_track_cblk_t);
117 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
118 if (buffer == NULL && alloc == ALLOC_CBLK) {
119 size += bufferSize;
120 }
121
122 if (client != 0) {
123 mCblkMemory = client->heap()->allocate(size);
124 if (mCblkMemory == 0 ||
125 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
126 ALOGE("not enough memory for AudioTrack size=%u", size);
127 client->heap()->dump("AudioTrack");
128 mCblkMemory.clear();
129 return;
130 }
131 } else {
132 // this syntax avoids calling the audio_track_cblk_t constructor twice
133 mCblk = (audio_track_cblk_t *) new uint8_t[size];
134 // assume mCblk != NULL
135 }
136
137 // construct the shared structure in-place.
138 if (mCblk != NULL) {
139 new(mCblk) audio_track_cblk_t();
140 switch (alloc) {
141 case ALLOC_READONLY: {
142 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
143 if (roHeap == 0 ||
144 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
145 (mBuffer = mBufferMemory->pointer()) == NULL) {
146 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
147 if (roHeap != 0) {
148 roHeap->dump("buffer");
149 }
150 mCblkMemory.clear();
151 mBufferMemory.clear();
152 return;
153 }
154 memset(mBuffer, 0, bufferSize);
155 } break;
156 case ALLOC_PIPE:
157 mBufferMemory = thread->pipeMemory();
158 // mBuffer is the virtual address as seen from current process (mediaserver),
159 // and should normally be coming from mBufferMemory->pointer().
160 // However in this case the TrackBase does not reference the buffer directly.
161 // It should references the buffer via the pipe.
162 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
163 mBuffer = NULL;
164 break;
165 case ALLOC_CBLK:
166 // clear all buffers
167 if (buffer == NULL) {
168 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
169 memset(mBuffer, 0, bufferSize);
170 } else {
171 mBuffer = buffer;
172 #if 0
173 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
174 #endif
175 }
176 break;
177 case ALLOC_LOCAL:
178 mBuffer = calloc(1, bufferSize);
179 break;
180 case ALLOC_NONE:
181 mBuffer = buffer;
182 break;
183 }
184
185 #ifdef TEE_SINK
186 if (mTeeSinkTrackEnabled) {
187 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
188 if (Format_isValid(pipeFormat)) {
189 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
190 size_t numCounterOffers = 0;
191 const NBAIO_Format offers[1] = {pipeFormat};
192 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
193 ALOG_ASSERT(index == 0);
194 PipeReader *pipeReader = new PipeReader(*pipe);
195 numCounterOffers = 0;
196 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
197 ALOG_ASSERT(index == 0);
198 mTeeSink = pipe;
199 mTeeSource = pipeReader;
200 }
201 }
202 #endif
203
204 }
205 }
206
initCheck() const207 status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
208 {
209 status_t status;
210 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
211 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
212 } else {
213 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
214 }
215 return status;
216 }
217
~TrackBase()218 AudioFlinger::ThreadBase::TrackBase::~TrackBase()
219 {
220 #ifdef TEE_SINK
221 dumpTee(-1, mTeeSource, mId);
222 #endif
223 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
224 delete mServerProxy;
225 if (mCblk != NULL) {
226 if (mClient == 0) {
227 delete mCblk;
228 } else {
229 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
230 }
231 }
232 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
233 if (mClient != 0) {
234 // Client destructor must run with AudioFlinger client mutex locked
235 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
236 // If the client's reference count drops to zero, the associated destructor
237 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
238 // relying on the automatic clear() at end of scope.
239 mClient.clear();
240 }
241 // flush the binder command buffer
242 IPCThreadState::self()->flushCommands();
243 }
244
245 // AudioBufferProvider interface
246 // getNextBuffer() = 0;
247 // This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
releaseBuffer(AudioBufferProvider::Buffer * buffer)248 void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
249 {
250 #ifdef TEE_SINK
251 if (mTeeSink != 0) {
252 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
253 }
254 #endif
255
256 ServerProxy::Buffer buf;
257 buf.mFrameCount = buffer->frameCount;
258 buf.mRaw = buffer->raw;
259 buffer->frameCount = 0;
260 buffer->raw = NULL;
261 mServerProxy->releaseBuffer(&buf);
262 }
263
setSyncEvent(const sp<SyncEvent> & event)264 status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
265 {
266 mSyncEvents.add(event);
267 return NO_ERROR;
268 }
269
270 // ----------------------------------------------------------------------------
271 // Playback
272 // ----------------------------------------------------------------------------
273
TrackHandle(const sp<AudioFlinger::PlaybackThread::Track> & track)274 AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
275 : BnAudioTrack(),
276 mTrack(track)
277 {
278 }
279
~TrackHandle()280 AudioFlinger::TrackHandle::~TrackHandle() {
281 // just stop the track on deletion, associated resources
282 // will be freed from the main thread once all pending buffers have
283 // been played. Unless it's not in the active track list, in which
284 // case we free everything now...
285 mTrack->destroy();
286 }
287
getCblk() const288 sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
289 return mTrack->getCblk();
290 }
291
start()292 status_t AudioFlinger::TrackHandle::start() {
293 return mTrack->start();
294 }
295
stop()296 void AudioFlinger::TrackHandle::stop() {
297 mTrack->stop();
298 }
299
flush()300 void AudioFlinger::TrackHandle::flush() {
301 mTrack->flush();
302 }
303
pause()304 void AudioFlinger::TrackHandle::pause() {
305 mTrack->pause();
306 }
307
attachAuxEffect(int EffectId)308 status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
309 {
310 return mTrack->attachAuxEffect(EffectId);
311 }
312
allocateTimedBuffer(size_t size,sp<IMemory> * buffer)313 status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
314 sp<IMemory>* buffer) {
315 if (!mTrack->isTimedTrack())
316 return INVALID_OPERATION;
317
318 PlaybackThread::TimedTrack* tt =
319 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
320 return tt->allocateTimedBuffer(size, buffer);
321 }
322
queueTimedBuffer(const sp<IMemory> & buffer,int64_t pts)323 status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
324 int64_t pts) {
325 if (!mTrack->isTimedTrack())
326 return INVALID_OPERATION;
327
328 if (buffer == 0 || buffer->pointer() == NULL) {
329 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
330 return BAD_VALUE;
331 }
332
333 PlaybackThread::TimedTrack* tt =
334 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
335 return tt->queueTimedBuffer(buffer, pts);
336 }
337
setMediaTimeTransform(const LinearTransform & xform,int target)338 status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
339 const LinearTransform& xform, int target) {
340
341 if (!mTrack->isTimedTrack())
342 return INVALID_OPERATION;
343
344 PlaybackThread::TimedTrack* tt =
345 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
346 return tt->setMediaTimeTransform(
347 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
348 }
349
setParameters(const String8 & keyValuePairs)350 status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
351 return mTrack->setParameters(keyValuePairs);
352 }
353
getTimestamp(AudioTimestamp & timestamp)354 status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
355 {
356 return mTrack->getTimestamp(timestamp);
357 }
358
359
signal()360 void AudioFlinger::TrackHandle::signal()
361 {
362 return mTrack->signal();
363 }
364
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)365 status_t AudioFlinger::TrackHandle::onTransact(
366 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
367 {
368 return BnAudioTrack::onTransact(code, data, reply, flags);
369 }
370
371 // ----------------------------------------------------------------------------
372
373 // Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Track(PlaybackThread * thread,const sp<Client> & client,audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,void * buffer,const sp<IMemory> & sharedBuffer,int sessionId,int uid,IAudioFlinger::track_flags_t flags,track_type type)374 AudioFlinger::PlaybackThread::Track::Track(
375 PlaybackThread *thread,
376 const sp<Client>& client,
377 audio_stream_type_t streamType,
378 uint32_t sampleRate,
379 audio_format_t format,
380 audio_channel_mask_t channelMask,
381 size_t frameCount,
382 void *buffer,
383 const sp<IMemory>& sharedBuffer,
384 int sessionId,
385 int uid,
386 IAudioFlinger::track_flags_t flags,
387 track_type type)
388 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
389 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
390 sessionId, uid, flags, true /*isOut*/,
391 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
392 type),
393 mFillingUpStatus(FS_INVALID),
394 // mRetryCount initialized later when needed
395 mSharedBuffer(sharedBuffer),
396 mStreamType(streamType),
397 mName(-1), // see note below
398 mMainBuffer(thread->mixBuffer()),
399 mAuxBuffer(NULL),
400 mAuxEffectId(0), mHasVolumeController(false),
401 mPresentationCompleteFrames(0),
402 mFastIndex(-1),
403 mCachedVolume(1.0),
404 mIsInvalid(false),
405 mAudioTrackServerProxy(NULL),
406 mResumeToStopping(false),
407 mFlushHwPending(false)
408 {
409 // client == 0 implies sharedBuffer == 0
410 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
411
412 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
413 sharedBuffer->size());
414
415 if (mCblk == NULL) {
416 return;
417 }
418
419 if (sharedBuffer == 0) {
420 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
421 mFrameSize, !isExternalTrack(), sampleRate);
422 } else {
423 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
424 mFrameSize);
425 }
426 mServerProxy = mAudioTrackServerProxy;
427
428 mName = thread->getTrackName_l(channelMask, format, sessionId);
429 if (mName < 0) {
430 ALOGE("no more track names available");
431 return;
432 }
433 // only allocate a fast track index if we were able to allocate a normal track name
434 if (flags & IAudioFlinger::TRACK_FAST) {
435 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
436 // race with setSyncEvent(). However, if we call it, we cannot properly start
437 // static fast tracks (SoundPool) immediately after stopping.
438 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
439 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
440 int i = __builtin_ctz(thread->mFastTrackAvailMask);
441 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
442 // FIXME This is too eager. We allocate a fast track index before the
443 // fast track becomes active. Since fast tracks are a scarce resource,
444 // this means we are potentially denying other more important fast tracks from
445 // being created. It would be better to allocate the index dynamically.
446 mFastIndex = i;
447 thread->mFastTrackAvailMask &= ~(1 << i);
448 }
449 }
450
~Track()451 AudioFlinger::PlaybackThread::Track::~Track()
452 {
453 ALOGV("PlaybackThread::Track destructor");
454
455 // The destructor would clear mSharedBuffer,
456 // but it will not push the decremented reference count,
457 // leaving the client's IMemory dangling indefinitely.
458 // This prevents that leak.
459 if (mSharedBuffer != 0) {
460 mSharedBuffer.clear();
461 }
462 }
463
initCheck() const464 status_t AudioFlinger::PlaybackThread::Track::initCheck() const
465 {
466 status_t status = TrackBase::initCheck();
467 if (status == NO_ERROR && mName < 0) {
468 status = NO_MEMORY;
469 }
470 return status;
471 }
472
destroy()473 void AudioFlinger::PlaybackThread::Track::destroy()
474 {
475 // NOTE: destroyTrack_l() can remove a strong reference to this Track
476 // by removing it from mTracks vector, so there is a risk that this Tracks's
477 // destructor is called. As the destructor needs to lock mLock,
478 // we must acquire a strong reference on this Track before locking mLock
479 // here so that the destructor is called only when exiting this function.
480 // On the other hand, as long as Track::destroy() is only called by
481 // TrackHandle destructor, the TrackHandle still holds a strong ref on
482 // this Track with its member mTrack.
483 sp<Track> keep(this);
484 { // scope for mLock
485 bool wasActive = false;
486 sp<ThreadBase> thread = mThread.promote();
487 if (thread != 0) {
488 Mutex::Autolock _l(thread->mLock);
489 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
490 wasActive = playbackThread->destroyTrack_l(this);
491 }
492 if (isExternalTrack() && !wasActive) {
493 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
494 }
495 }
496 }
497
appendDumpHeader(String8 & result)498 /*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
499 {
500 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
501 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
502 }
503
dump(char * buffer,size_t size,bool active)504 void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
505 {
506 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
507 if (isFastTrack()) {
508 sprintf(buffer, " F %2d", mFastIndex);
509 } else if (mName >= AudioMixer::TRACK0) {
510 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
511 } else {
512 sprintf(buffer, " none");
513 }
514 track_state state = mState;
515 char stateChar;
516 if (isTerminated()) {
517 stateChar = 'T';
518 } else {
519 switch (state) {
520 case IDLE:
521 stateChar = 'I';
522 break;
523 case STOPPING_1:
524 stateChar = 's';
525 break;
526 case STOPPING_2:
527 stateChar = '5';
528 break;
529 case STOPPED:
530 stateChar = 'S';
531 break;
532 case RESUMING:
533 stateChar = 'R';
534 break;
535 case ACTIVE:
536 stateChar = 'A';
537 break;
538 case PAUSING:
539 stateChar = 'p';
540 break;
541 case PAUSED:
542 stateChar = 'P';
543 break;
544 case FLUSHED:
545 stateChar = 'F';
546 break;
547 default:
548 stateChar = '?';
549 break;
550 }
551 }
552 char nowInUnderrun;
553 switch (mObservedUnderruns.mBitFields.mMostRecent) {
554 case UNDERRUN_FULL:
555 nowInUnderrun = ' ';
556 break;
557 case UNDERRUN_PARTIAL:
558 nowInUnderrun = '<';
559 break;
560 case UNDERRUN_EMPTY:
561 nowInUnderrun = '*';
562 break;
563 default:
564 nowInUnderrun = '?';
565 break;
566 }
567 snprintf(&buffer[8], size-8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u %5.2g %5.2g "
568 "%08X %p %p 0x%03X %9u%c\n",
569 active ? "yes" : "no",
570 (mClient == 0) ? getpid_cached : mClient->pid(),
571 mStreamType,
572 mFormat,
573 mChannelMask,
574 mSessionId,
575 mFrameCount,
576 stateChar,
577 mFillingUpStatus,
578 mAudioTrackServerProxy->getSampleRate(),
579 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
580 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
581 mCblk->mServer,
582 mMainBuffer,
583 mAuxBuffer,
584 mCblk->mFlags,
585 mAudioTrackServerProxy->getUnderrunFrames(),
586 nowInUnderrun);
587 }
588
sampleRate() const589 uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
590 return mAudioTrackServerProxy->getSampleRate();
591 }
592
593 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer,int64_t pts __unused)594 status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
595 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
596 {
597 ServerProxy::Buffer buf;
598 size_t desiredFrames = buffer->frameCount;
599 buf.mFrameCount = desiredFrames;
600 status_t status = mServerProxy->obtainBuffer(&buf);
601 buffer->frameCount = buf.mFrameCount;
602 buffer->raw = buf.mRaw;
603 if (buf.mFrameCount == 0) {
604 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
605 }
606 return status;
607 }
608
609 // releaseBuffer() is not overridden
610
611 // ExtendedAudioBufferProvider interface
612
613 // framesReady() may return an approximation of the number of frames if called
614 // from a different thread than the one calling Proxy->obtainBuffer() and
615 // Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
616 // AudioTrackServerProxy so be especially careful calling with FastTracks.
framesReady() const617 size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
618 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
619 // Static tracks return zero frames immediately upon stopping (for FastTracks).
620 // The remainder of the buffer is not drained.
621 return 0;
622 }
623 return mAudioTrackServerProxy->framesReady();
624 }
625
framesReleased() const626 size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
627 {
628 return mAudioTrackServerProxy->framesReleased();
629 }
630
631 // Don't call for fast tracks; the framesReady() could result in priority inversion
isReady() const632 bool AudioFlinger::PlaybackThread::Track::isReady() const {
633 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
634 return true;
635 }
636
637 if (isStopping()) {
638 if (framesReady() > 0) {
639 mFillingUpStatus = FS_FILLED;
640 }
641 return true;
642 }
643
644 if (framesReady() >= mFrameCount ||
645 (mCblk->mFlags & CBLK_FORCEREADY)) {
646 mFillingUpStatus = FS_FILLED;
647 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
648 return true;
649 }
650 return false;
651 }
652
start(AudioSystem::sync_event_t event __unused,int triggerSession __unused)653 status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
654 int triggerSession __unused)
655 {
656 status_t status = NO_ERROR;
657 ALOGV("start(%d), calling pid %d session %d",
658 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
659
660 sp<ThreadBase> thread = mThread.promote();
661 if (thread != 0) {
662 if (isOffloaded()) {
663 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
664 Mutex::Autolock _lth(thread->mLock);
665 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
666 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
667 (ec != 0 && ec->isNonOffloadableEnabled())) {
668 invalidate();
669 return PERMISSION_DENIED;
670 }
671 }
672 Mutex::Autolock _lth(thread->mLock);
673 track_state state = mState;
674 // here the track could be either new, or restarted
675 // in both cases "unstop" the track
676
677 // initial state-stopping. next state-pausing.
678 // What if resume is called ?
679
680 if (state == PAUSED || state == PAUSING) {
681 if (mResumeToStopping) {
682 // happened we need to resume to STOPPING_1
683 mState = TrackBase::STOPPING_1;
684 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
685 } else {
686 mState = TrackBase::RESUMING;
687 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
688 }
689 } else {
690 mState = TrackBase::ACTIVE;
691 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
692 }
693
694 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
695 if (isFastTrack()) {
696 // refresh fast track underruns on start because that field is never cleared
697 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
698 // after stop.
699 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
700 }
701 status = playbackThread->addTrack_l(this);
702 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
703 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
704 // restore previous state if start was rejected by policy manager
705 if (status == PERMISSION_DENIED) {
706 mState = state;
707 }
708 }
709 // track was already in the active list, not a problem
710 if (status == ALREADY_EXISTS) {
711 status = NO_ERROR;
712 } else {
713 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
714 // It is usually unsafe to access the server proxy from a binder thread.
715 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
716 // isn't looking at this track yet: we still hold the normal mixer thread lock,
717 // and for fast tracks the track is not yet in the fast mixer thread's active set.
718 // For static tracks, this is used to acknowledge change in position or loop.
719 ServerProxy::Buffer buffer;
720 buffer.mFrameCount = 1;
721 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
722 }
723 } else {
724 status = BAD_VALUE;
725 }
726 return status;
727 }
728
stop()729 void AudioFlinger::PlaybackThread::Track::stop()
730 {
731 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
732 sp<ThreadBase> thread = mThread.promote();
733 if (thread != 0) {
734 Mutex::Autolock _l(thread->mLock);
735 track_state state = mState;
736 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
737 // If the track is not active (PAUSED and buffers full), flush buffers
738 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
739 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
740 reset();
741 mState = STOPPED;
742 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
743 mState = STOPPED;
744 } else {
745 // For fast tracks prepareTracks_l() will set state to STOPPING_2
746 // presentation is complete
747 // For an offloaded track this starts a drain and state will
748 // move to STOPPING_2 when drain completes and then STOPPED
749 mState = STOPPING_1;
750 }
751 playbackThread->broadcast_l();
752 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
753 playbackThread);
754 }
755 }
756 }
757
pause()758 void AudioFlinger::PlaybackThread::Track::pause()
759 {
760 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
761 sp<ThreadBase> thread = mThread.promote();
762 if (thread != 0) {
763 Mutex::Autolock _l(thread->mLock);
764 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
765 switch (mState) {
766 case STOPPING_1:
767 case STOPPING_2:
768 if (!isOffloaded()) {
769 /* nothing to do if track is not offloaded */
770 break;
771 }
772
773 // Offloaded track was draining, we need to carry on draining when resumed
774 mResumeToStopping = true;
775 // fall through...
776 case ACTIVE:
777 case RESUMING:
778 mState = PAUSING;
779 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
780 playbackThread->broadcast_l();
781 break;
782
783 default:
784 break;
785 }
786 }
787 }
788
flush()789 void AudioFlinger::PlaybackThread::Track::flush()
790 {
791 ALOGV("flush(%d)", mName);
792 sp<ThreadBase> thread = mThread.promote();
793 if (thread != 0) {
794 Mutex::Autolock _l(thread->mLock);
795 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
796
797 if (isOffloaded()) {
798 // If offloaded we allow flush during any state except terminated
799 // and keep the track active to avoid problems if user is seeking
800 // rapidly and underlying hardware has a significant delay handling
801 // a pause
802 if (isTerminated()) {
803 return;
804 }
805
806 ALOGV("flush: offload flush");
807 reset();
808
809 if (mState == STOPPING_1 || mState == STOPPING_2) {
810 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
811 mState = ACTIVE;
812 }
813
814 if (mState == ACTIVE) {
815 ALOGV("flush called in active state, resetting buffer time out retry count");
816 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
817 }
818
819 mFlushHwPending = true;
820 mResumeToStopping = false;
821 } else {
822 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
823 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
824 return;
825 }
826 // No point remaining in PAUSED state after a flush => go to
827 // FLUSHED state
828 mState = FLUSHED;
829 // do not reset the track if it is still in the process of being stopped or paused.
830 // this will be done by prepareTracks_l() when the track is stopped.
831 // prepareTracks_l() will see mState == FLUSHED, then
832 // remove from active track list, reset(), and trigger presentation complete
833 if (isDirect()) {
834 mFlushHwPending = true;
835 }
836 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
837 reset();
838 }
839 }
840 // Prevent flush being lost if the track is flushed and then resumed
841 // before mixer thread can run. This is important when offloading
842 // because the hardware buffer could hold a large amount of audio
843 playbackThread->broadcast_l();
844 }
845 }
846
847 // must be called with thread lock held
flushAck()848 void AudioFlinger::PlaybackThread::Track::flushAck()
849 {
850 if (!isOffloaded() && !isDirect())
851 return;
852
853 mFlushHwPending = false;
854 }
855
reset()856 void AudioFlinger::PlaybackThread::Track::reset()
857 {
858 // Do not reset twice to avoid discarding data written just after a flush and before
859 // the audioflinger thread detects the track is stopped.
860 if (!mResetDone) {
861 // Force underrun condition to avoid false underrun callback until first data is
862 // written to buffer
863 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
864 mFillingUpStatus = FS_FILLING;
865 mResetDone = true;
866 if (mState == FLUSHED) {
867 mState = IDLE;
868 }
869 }
870 }
871
setParameters(const String8 & keyValuePairs)872 status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
873 {
874 sp<ThreadBase> thread = mThread.promote();
875 if (thread == 0) {
876 ALOGE("thread is dead");
877 return FAILED_TRANSACTION;
878 } else if ((thread->type() == ThreadBase::DIRECT) ||
879 (thread->type() == ThreadBase::OFFLOAD)) {
880 return thread->setParameters(keyValuePairs);
881 } else {
882 return PERMISSION_DENIED;
883 }
884 }
885
getTimestamp(AudioTimestamp & timestamp)886 status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
887 {
888 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
889 if (isFastTrack()) {
890 return INVALID_OPERATION;
891 }
892 sp<ThreadBase> thread = mThread.promote();
893 if (thread == 0) {
894 return INVALID_OPERATION;
895 }
896
897 Mutex::Autolock _l(thread->mLock);
898 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
899
900 status_t result = INVALID_OPERATION;
901 if (!isOffloaded() && !isDirect()) {
902 if (!playbackThread->mLatchQValid) {
903 return INVALID_OPERATION;
904 }
905 // FIXME Not accurate under dynamic changes of sample rate and speed.
906 // Do not use track's mSampleRate as it is not current for mixer tracks.
907 uint32_t sampleRate = mAudioTrackServerProxy->getSampleRate();
908 AudioPlaybackRate playbackRate = mAudioTrackServerProxy->getPlaybackRate();
909 uint32_t unpresentedFrames = ((double) playbackThread->mLatchQ.mUnpresentedFrames *
910 sampleRate * playbackRate.mSpeed)/ playbackThread->mSampleRate;
911 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
912 // for a brand new track to share the same address as a recently destroyed
913 // track, and thus for us to get the frames released of the wrong track.
914 // It is unlikely that we would be able to call getTimestamp() so quickly
915 // right after creating a new track. Nevertheless, the index here should
916 // be changed to something that is unique. Or use a completely different strategy.
917 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
918 uint32_t framesWritten = i >= 0 ?
919 playbackThread->mLatchQ.mFramesReleased[i] :
920 mAudioTrackServerProxy->framesReleased();
921 if (framesWritten >= unpresentedFrames) {
922 timestamp.mPosition = framesWritten - unpresentedFrames;
923 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
924 result = NO_ERROR;
925 }
926 } else { // offloaded or direct
927 result = playbackThread->getTimestamp_l(timestamp);
928 }
929
930 return result;
931 }
932
attachAuxEffect(int EffectId)933 status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
934 {
935 status_t status = DEAD_OBJECT;
936 sp<ThreadBase> thread = mThread.promote();
937 if (thread != 0) {
938 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
939 sp<AudioFlinger> af = mClient->audioFlinger();
940
941 Mutex::Autolock _l(af->mLock);
942
943 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
944
945 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
946 Mutex::Autolock _dl(playbackThread->mLock);
947 Mutex::Autolock _sl(srcThread->mLock);
948 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
949 if (chain == 0) {
950 return INVALID_OPERATION;
951 }
952
953 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
954 if (effect == 0) {
955 return INVALID_OPERATION;
956 }
957 srcThread->removeEffect_l(effect);
958 status = playbackThread->addEffect_l(effect);
959 if (status != NO_ERROR) {
960 srcThread->addEffect_l(effect);
961 return INVALID_OPERATION;
962 }
963 // removeEffect_l() has stopped the effect if it was active so it must be restarted
964 if (effect->state() == EffectModule::ACTIVE ||
965 effect->state() == EffectModule::STOPPING) {
966 effect->start();
967 }
968
969 sp<EffectChain> dstChain = effect->chain().promote();
970 if (dstChain == 0) {
971 srcThread->addEffect_l(effect);
972 return INVALID_OPERATION;
973 }
974 AudioSystem::unregisterEffect(effect->id());
975 AudioSystem::registerEffect(&effect->desc(),
976 srcThread->id(),
977 dstChain->strategy(),
978 AUDIO_SESSION_OUTPUT_MIX,
979 effect->id());
980 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
981 }
982 status = playbackThread->attachAuxEffect(this, EffectId);
983 }
984 return status;
985 }
986
setAuxBuffer(int EffectId,int32_t * buffer)987 void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
988 {
989 mAuxEffectId = EffectId;
990 mAuxBuffer = buffer;
991 }
992
presentationComplete(size_t framesWritten,size_t audioHalFrames)993 bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
994 size_t audioHalFrames)
995 {
996 // a track is considered presented when the total number of frames written to audio HAL
997 // corresponds to the number of frames written when presentationComplete() is called for the
998 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
999 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1000 // to detect when all frames have been played. In this case framesWritten isn't
1001 // useful because it doesn't always reflect whether there is data in the h/w
1002 // buffers, particularly if a track has been paused and resumed during draining
1003 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1004 mPresentationCompleteFrames, framesWritten);
1005 if (mPresentationCompleteFrames == 0) {
1006 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1007 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1008 mPresentationCompleteFrames, audioHalFrames);
1009 }
1010
1011 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
1012 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1013 mAudioTrackServerProxy->setStreamEndDone();
1014 return true;
1015 }
1016 return false;
1017 }
1018
triggerEvents(AudioSystem::sync_event_t type)1019 void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1020 {
1021 for (size_t i = 0; i < mSyncEvents.size(); i++) {
1022 if (mSyncEvents[i]->type() == type) {
1023 mSyncEvents[i]->trigger();
1024 mSyncEvents.removeAt(i);
1025 i--;
1026 }
1027 }
1028 }
1029
1030 // implement VolumeBufferProvider interface
1031
getVolumeLR()1032 gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
1033 {
1034 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1035 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
1036 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1037 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1038 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
1039 // track volumes come from shared memory, so can't be trusted and must be clamped
1040 if (vl > GAIN_FLOAT_UNITY) {
1041 vl = GAIN_FLOAT_UNITY;
1042 }
1043 if (vr > GAIN_FLOAT_UNITY) {
1044 vr = GAIN_FLOAT_UNITY;
1045 }
1046 // now apply the cached master volume and stream type volume;
1047 // this is trusted but lacks any synchronization or barrier so may be stale
1048 float v = mCachedVolume;
1049 vl *= v;
1050 vr *= v;
1051 // re-combine into packed minifloat
1052 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
1053 // FIXME look at mute, pause, and stop flags
1054 return vlr;
1055 }
1056
setSyncEvent(const sp<SyncEvent> & event)1057 status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1058 {
1059 if (isTerminated() || mState == PAUSED ||
1060 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1061 (mState == STOPPED)))) {
1062 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1063 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1064 event->cancel();
1065 return INVALID_OPERATION;
1066 }
1067 (void) TrackBase::setSyncEvent(event);
1068 return NO_ERROR;
1069 }
1070
invalidate()1071 void AudioFlinger::PlaybackThread::Track::invalidate()
1072 {
1073 // FIXME should use proxy, and needs work
1074 audio_track_cblk_t* cblk = mCblk;
1075 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1076 android_atomic_release_store(0x40000000, &cblk->mFutex);
1077 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1078 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
1079 mIsInvalid = true;
1080 }
1081
signal()1082 void AudioFlinger::PlaybackThread::Track::signal()
1083 {
1084 sp<ThreadBase> thread = mThread.promote();
1085 if (thread != 0) {
1086 PlaybackThread *t = (PlaybackThread *)thread.get();
1087 Mutex::Autolock _l(t->mLock);
1088 t->broadcast_l();
1089 }
1090 }
1091
1092 //To be called with thread lock held
isResumePending()1093 bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1094
1095 if (mState == RESUMING)
1096 return true;
1097 /* Resume is pending if track was stopping before pause was called */
1098 if (mState == STOPPING_1 &&
1099 mResumeToStopping)
1100 return true;
1101
1102 return false;
1103 }
1104
1105 //To be called with thread lock held
resumeAck()1106 void AudioFlinger::PlaybackThread::Track::resumeAck() {
1107
1108
1109 if (mState == RESUMING)
1110 mState = ACTIVE;
1111
1112 // Other possibility of pending resume is stopping_1 state
1113 // Do not update the state from stopping as this prevents
1114 // drain being called.
1115 if (mState == STOPPING_1) {
1116 mResumeToStopping = false;
1117 }
1118 }
1119 // ----------------------------------------------------------------------------
1120
1121 sp<AudioFlinger::PlaybackThread::TimedTrack>
create(PlaybackThread * thread,const sp<Client> & client,audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,const sp<IMemory> & sharedBuffer,int sessionId,int uid)1122 AudioFlinger::PlaybackThread::TimedTrack::create(
1123 PlaybackThread *thread,
1124 const sp<Client>& client,
1125 audio_stream_type_t streamType,
1126 uint32_t sampleRate,
1127 audio_format_t format,
1128 audio_channel_mask_t channelMask,
1129 size_t frameCount,
1130 const sp<IMemory>& sharedBuffer,
1131 int sessionId,
1132 int uid)
1133 {
1134 if (!client->reserveTimedTrack())
1135 return 0;
1136
1137 return new TimedTrack(
1138 thread, client, streamType, sampleRate, format, channelMask, frameCount,
1139 sharedBuffer, sessionId, uid);
1140 }
1141
TimedTrack(PlaybackThread * thread,const sp<Client> & client,audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,const sp<IMemory> & sharedBuffer,int sessionId,int uid)1142 AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1143 PlaybackThread *thread,
1144 const sp<Client>& client,
1145 audio_stream_type_t streamType,
1146 uint32_t sampleRate,
1147 audio_format_t format,
1148 audio_channel_mask_t channelMask,
1149 size_t frameCount,
1150 const sp<IMemory>& sharedBuffer,
1151 int sessionId,
1152 int uid)
1153 : Track(thread, client, streamType, sampleRate, format, channelMask,
1154 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1155 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
1156 mQueueHeadInFlight(false),
1157 mTrimQueueHeadOnRelease(false),
1158 mFramesPendingInQueue(0),
1159 mTimedSilenceBuffer(NULL),
1160 mTimedSilenceBufferSize(0),
1161 mTimedAudioOutputOnTime(false),
1162 mMediaTimeTransformValid(false)
1163 {
1164 LocalClock lc;
1165 mLocalTimeFreq = lc.getLocalFreq();
1166
1167 mLocalTimeToSampleTransform.a_zero = 0;
1168 mLocalTimeToSampleTransform.b_zero = 0;
1169 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1170 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1171 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1172 &mLocalTimeToSampleTransform.a_to_b_denom);
1173
1174 mMediaTimeToSampleTransform.a_zero = 0;
1175 mMediaTimeToSampleTransform.b_zero = 0;
1176 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1177 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1178 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1179 &mMediaTimeToSampleTransform.a_to_b_denom);
1180 }
1181
~TimedTrack()1182 AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1183 mClient->releaseTimedTrack();
1184 delete [] mTimedSilenceBuffer;
1185 }
1186
allocateTimedBuffer(size_t size,sp<IMemory> * buffer)1187 status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1188 size_t size, sp<IMemory>* buffer) {
1189
1190 Mutex::Autolock _l(mTimedBufferQueueLock);
1191
1192 trimTimedBufferQueue_l();
1193
1194 // lazily initialize the shared memory heap for timed buffers
1195 if (mTimedMemoryDealer == NULL) {
1196 const int kTimedBufferHeapSize = 512 << 10;
1197
1198 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1199 "AudioFlingerTimed");
1200 if (mTimedMemoryDealer == NULL) {
1201 return NO_MEMORY;
1202 }
1203 }
1204
1205 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
1206 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
1207 return NO_MEMORY;
1208 }
1209
1210 *buffer = newBuffer;
1211 return NO_ERROR;
1212 }
1213
1214 // caller must hold mTimedBufferQueueLock
trimTimedBufferQueue_l()1215 void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1216 int64_t mediaTimeNow;
1217 {
1218 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1219 if (!mMediaTimeTransformValid)
1220 return;
1221
1222 int64_t targetTimeNow;
1223 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1224 ? mCCHelper.getCommonTime(&targetTimeNow)
1225 : mCCHelper.getLocalTime(&targetTimeNow);
1226
1227 if (OK != res)
1228 return;
1229
1230 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1231 &mediaTimeNow)) {
1232 return;
1233 }
1234 }
1235
1236 size_t trimEnd;
1237 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1238 int64_t bufEnd;
1239
1240 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1241 // We have a next buffer. Just use its PTS as the PTS of the frame
1242 // following the last frame in this buffer. If the stream is sparse
1243 // (ie, there are deliberate gaps left in the stream which should be
1244 // filled with silence by the TimedAudioTrack), then this can result
1245 // in one extra buffer being left un-trimmed when it could have
1246 // been. In general, this is not typical, and we would rather
1247 // optimized away the TS calculation below for the more common case
1248 // where PTSes are contiguous.
1249 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1250 } else {
1251 // We have no next buffer. Compute the PTS of the frame following
1252 // the last frame in this buffer by computing the duration of of
1253 // this frame in media time units and adding it to the PTS of the
1254 // buffer.
1255 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1256 / mFrameSize;
1257
1258 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1259 &bufEnd)) {
1260 ALOGE("Failed to convert frame count of %lld to media time"
1261 " duration" " (scale factor %d/%u) in %s",
1262 frameCount,
1263 mMediaTimeToSampleTransform.a_to_b_numer,
1264 mMediaTimeToSampleTransform.a_to_b_denom,
1265 __PRETTY_FUNCTION__);
1266 break;
1267 }
1268 bufEnd += mTimedBufferQueue[trimEnd].pts();
1269 }
1270
1271 if (bufEnd > mediaTimeNow)
1272 break;
1273
1274 // Is the buffer we want to use in the middle of a mix operation right
1275 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1276 // from the mixer which should be coming back shortly.
1277 if (!trimEnd && mQueueHeadInFlight) {
1278 mTrimQueueHeadOnRelease = true;
1279 }
1280 }
1281
1282 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1283 if (trimStart < trimEnd) {
1284 // Update the bookkeeping for framesReady()
1285 for (size_t i = trimStart; i < trimEnd; ++i) {
1286 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1287 }
1288
1289 // Now actually remove the buffers from the queue.
1290 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1291 }
1292 }
1293
trimTimedBufferQueueHead_l(const char * logTag)1294 void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1295 const char* logTag) {
1296 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1297 "%s called (reason \"%s\"), but timed buffer queue has no"
1298 " elements to trim.", __FUNCTION__, logTag);
1299
1300 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1301 mTimedBufferQueue.removeAt(0);
1302 }
1303
updateFramesPendingAfterTrim_l(const TimedBuffer & buf,const char * logTag __unused)1304 void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1305 const TimedBuffer& buf,
1306 const char* logTag __unused) {
1307 uint32_t bufBytes = buf.buffer()->size();
1308 uint32_t consumedAlready = buf.position();
1309
1310 ALOG_ASSERT(consumedAlready <= bufBytes,
1311 "Bad bookkeeping while updating frames pending. Timed buffer is"
1312 " only %u bytes long, but claims to have consumed %u"
1313 " bytes. (update reason: \"%s\")",
1314 bufBytes, consumedAlready, logTag);
1315
1316 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1317 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1318 "Bad bookkeeping while updating frames pending. Should have at"
1319 " least %u queued frames, but we think we have only %u. (update"
1320 " reason: \"%s\")",
1321 bufFrames, mFramesPendingInQueue, logTag);
1322
1323 mFramesPendingInQueue -= bufFrames;
1324 }
1325
queueTimedBuffer(const sp<IMemory> & buffer,int64_t pts)1326 status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1327 const sp<IMemory>& buffer, int64_t pts) {
1328
1329 {
1330 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1331 if (!mMediaTimeTransformValid)
1332 return INVALID_OPERATION;
1333 }
1334
1335 Mutex::Autolock _l(mTimedBufferQueueLock);
1336
1337 uint32_t bufFrames = buffer->size() / mFrameSize;
1338 mFramesPendingInQueue += bufFrames;
1339 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1340
1341 return NO_ERROR;
1342 }
1343
setMediaTimeTransform(const LinearTransform & xform,TimedAudioTrack::TargetTimeline target)1344 status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1345 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1346
1347 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1348 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1349 target);
1350
1351 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1352 target == TimedAudioTrack::COMMON_TIME)) {
1353 return BAD_VALUE;
1354 }
1355
1356 Mutex::Autolock lock(mMediaTimeTransformLock);
1357 mMediaTimeTransform = xform;
1358 mMediaTimeTransformTarget = target;
1359 mMediaTimeTransformValid = true;
1360
1361 return NO_ERROR;
1362 }
1363
1364 #define min(a, b) ((a) < (b) ? (a) : (b))
1365
1366 // implementation of getNextBuffer for tracks whose buffers have timestamps
getNextBuffer(AudioBufferProvider::Buffer * buffer,int64_t pts)1367 status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1368 AudioBufferProvider::Buffer* buffer, int64_t pts)
1369 {
1370 if (pts == AudioBufferProvider::kInvalidPTS) {
1371 buffer->raw = NULL;
1372 buffer->frameCount = 0;
1373 mTimedAudioOutputOnTime = false;
1374 return INVALID_OPERATION;
1375 }
1376
1377 Mutex::Autolock _l(mTimedBufferQueueLock);
1378
1379 ALOG_ASSERT(!mQueueHeadInFlight,
1380 "getNextBuffer called without releaseBuffer!");
1381
1382 while (true) {
1383
1384 // if we have no timed buffers, then fail
1385 if (mTimedBufferQueue.isEmpty()) {
1386 buffer->raw = NULL;
1387 buffer->frameCount = 0;
1388 return NOT_ENOUGH_DATA;
1389 }
1390
1391 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1392
1393 // calculate the PTS of the head of the timed buffer queue expressed in
1394 // local time
1395 int64_t headLocalPTS;
1396 {
1397 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1398
1399 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1400
1401 if (mMediaTimeTransform.a_to_b_denom == 0) {
1402 // the transform represents a pause, so yield silence
1403 timedYieldSilence_l(buffer->frameCount, buffer);
1404 return NO_ERROR;
1405 }
1406
1407 int64_t transformedPTS;
1408 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1409 &transformedPTS)) {
1410 // the transform failed. this shouldn't happen, but if it does
1411 // then just drop this buffer
1412 ALOGW("timedGetNextBuffer transform failed");
1413 buffer->raw = NULL;
1414 buffer->frameCount = 0;
1415 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1416 return NO_ERROR;
1417 }
1418
1419 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1420 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1421 &headLocalPTS)) {
1422 buffer->raw = NULL;
1423 buffer->frameCount = 0;
1424 return INVALID_OPERATION;
1425 }
1426 } else {
1427 headLocalPTS = transformedPTS;
1428 }
1429 }
1430
1431 uint32_t sr = sampleRate();
1432
1433 // adjust the head buffer's PTS to reflect the portion of the head buffer
1434 // that has already been consumed
1435 int64_t effectivePTS = headLocalPTS +
1436 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
1437
1438 // Calculate the delta in samples between the head of the input buffer
1439 // queue and the start of the next output buffer that will be written.
1440 // If the transformation fails because of over or underflow, it means
1441 // that the sample's position in the output stream is so far out of
1442 // whack that it should just be dropped.
1443 int64_t sampleDelta;
1444 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1445 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1446 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1447 " mix");
1448 continue;
1449 }
1450 if (!mLocalTimeToSampleTransform.doForwardTransform(
1451 (effectivePTS - pts) << 32, &sampleDelta)) {
1452 ALOGV("*** too late during sample rate transform: dropped buffer");
1453 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1454 continue;
1455 }
1456
1457 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1458 " sampleDelta=[%d.%08x]",
1459 head.pts(), head.position(), pts,
1460 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1461 + (sampleDelta >> 32)),
1462 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1463
1464 // if the delta between the ideal placement for the next input sample and
1465 // the current output position is within this threshold, then we will
1466 // concatenate the next input samples to the previous output
1467 const int64_t kSampleContinuityThreshold =
1468 (static_cast<int64_t>(sr) << 32) / 250;
1469
1470 // if this is the first buffer of audio that we're emitting from this track
1471 // then it should be almost exactly on time.
1472 const int64_t kSampleStartupThreshold = 1LL << 32;
1473
1474 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1475 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1476 // the next input is close enough to being on time, so concatenate it
1477 // with the last output
1478 timedYieldSamples_l(buffer);
1479
1480 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1481 head.position(), buffer->frameCount);
1482 return NO_ERROR;
1483 }
1484
1485 // Looks like our output is not on time. Reset our on timed status.
1486 // Next time we mix samples from our input queue, then should be within
1487 // the StartupThreshold.
1488 mTimedAudioOutputOnTime = false;
1489 if (sampleDelta > 0) {
1490 // the gap between the current output position and the proper start of
1491 // the next input sample is too big, so fill it with silence
1492 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1493
1494 timedYieldSilence_l(framesUntilNextInput, buffer);
1495 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1496 return NO_ERROR;
1497 } else {
1498 // the next input sample is late
1499 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1500 size_t onTimeSamplePosition =
1501 head.position() + lateFrames * mFrameSize;
1502
1503 if (onTimeSamplePosition > head.buffer()->size()) {
1504 // all the remaining samples in the head are too late, so
1505 // drop it and move on
1506 ALOGV("*** too late: dropped buffer");
1507 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1508 continue;
1509 } else {
1510 // skip over the late samples
1511 head.setPosition(onTimeSamplePosition);
1512
1513 // yield the available samples
1514 timedYieldSamples_l(buffer);
1515
1516 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1517 return NO_ERROR;
1518 }
1519 }
1520 }
1521 }
1522
1523 // Yield samples from the timed buffer queue head up to the given output
1524 // buffer's capacity.
1525 //
1526 // Caller must hold mTimedBufferQueueLock
timedYieldSamples_l(AudioBufferProvider::Buffer * buffer)1527 void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1528 AudioBufferProvider::Buffer* buffer) {
1529
1530 const TimedBuffer& head = mTimedBufferQueue[0];
1531
1532 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1533 head.position());
1534
1535 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1536 mFrameSize);
1537 size_t framesRequested = buffer->frameCount;
1538 buffer->frameCount = min(framesLeftInHead, framesRequested);
1539
1540 mQueueHeadInFlight = true;
1541 mTimedAudioOutputOnTime = true;
1542 }
1543
1544 // Yield samples of silence up to the given output buffer's capacity
1545 //
1546 // Caller must hold mTimedBufferQueueLock
timedYieldSilence_l(uint32_t numFrames,AudioBufferProvider::Buffer * buffer)1547 void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1548 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1549
1550 // lazily allocate a buffer filled with silence
1551 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1552 delete [] mTimedSilenceBuffer;
1553 mTimedSilenceBufferSize = numFrames * mFrameSize;
1554 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1555 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1556 }
1557
1558 buffer->raw = mTimedSilenceBuffer;
1559 size_t framesRequested = buffer->frameCount;
1560 buffer->frameCount = min(numFrames, framesRequested);
1561
1562 mTimedAudioOutputOnTime = false;
1563 }
1564
1565 // AudioBufferProvider interface
releaseBuffer(AudioBufferProvider::Buffer * buffer)1566 void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1567 AudioBufferProvider::Buffer* buffer) {
1568
1569 Mutex::Autolock _l(mTimedBufferQueueLock);
1570
1571 // If the buffer which was just released is part of the buffer at the head
1572 // of the queue, be sure to update the amt of the buffer which has been
1573 // consumed. If the buffer being returned is not part of the head of the
1574 // queue, its either because the buffer is part of the silence buffer, or
1575 // because the head of the timed queue was trimmed after the mixer called
1576 // getNextBuffer but before the mixer called releaseBuffer.
1577 if (buffer->raw == mTimedSilenceBuffer) {
1578 ALOG_ASSERT(!mQueueHeadInFlight,
1579 "Queue head in flight during release of silence buffer!");
1580 goto done;
1581 }
1582
1583 ALOG_ASSERT(mQueueHeadInFlight,
1584 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1585 " head in flight.");
1586
1587 if (mTimedBufferQueue.size()) {
1588 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1589
1590 void* start = head.buffer()->pointer();
1591 void* end = reinterpret_cast<void*>(
1592 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1593 + head.buffer()->size());
1594
1595 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1596 "released buffer not within the head of the timed buffer"
1597 " queue; qHead = [%p, %p], released buffer = %p",
1598 start, end, buffer->raw);
1599
1600 head.setPosition(head.position() +
1601 (buffer->frameCount * mFrameSize));
1602 mQueueHeadInFlight = false;
1603
1604 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1605 "Bad bookkeeping during releaseBuffer! Should have at"
1606 " least %u queued frames, but we think we have only %u",
1607 buffer->frameCount, mFramesPendingInQueue);
1608
1609 mFramesPendingInQueue -= buffer->frameCount;
1610
1611 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1612 || mTrimQueueHeadOnRelease) {
1613 trimTimedBufferQueueHead_l("releaseBuffer");
1614 mTrimQueueHeadOnRelease = false;
1615 }
1616 } else {
1617 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1618 " buffers in the timed buffer queue");
1619 }
1620
1621 done:
1622 buffer->raw = 0;
1623 buffer->frameCount = 0;
1624 }
1625
framesReady() const1626 size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1627 Mutex::Autolock _l(mTimedBufferQueueLock);
1628 return mFramesPendingInQueue;
1629 }
1630
TimedBuffer()1631 AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1632 : mPTS(0), mPosition(0) {}
1633
TimedBuffer(const sp<IMemory> & buffer,int64_t pts)1634 AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1635 const sp<IMemory>& buffer, int64_t pts)
1636 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1637
1638
1639 // ----------------------------------------------------------------------------
1640
OutputTrack(PlaybackThread * playbackThread,DuplicatingThread * sourceThread,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,int uid)1641 AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1642 PlaybackThread *playbackThread,
1643 DuplicatingThread *sourceThread,
1644 uint32_t sampleRate,
1645 audio_format_t format,
1646 audio_channel_mask_t channelMask,
1647 size_t frameCount,
1648 int uid)
1649 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1650 sampleRate, format, channelMask, frameCount,
1651 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
1652 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
1653 {
1654
1655 if (mCblk != NULL) {
1656 mOutBuffer.frameCount = 0;
1657 playbackThread->mTracks.add(this);
1658 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
1659 "frameCount %u, mChannelMask 0x%08x",
1660 mCblk, mBuffer,
1661 frameCount, mChannelMask);
1662 // since client and server are in the same process,
1663 // the buffer has the same virtual address on both sides
1664 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1665 true /*clientInServer*/);
1666 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
1667 mClientProxy->setSendLevel(0.0);
1668 mClientProxy->setSampleRate(sampleRate);
1669 } else {
1670 ALOGW("Error creating output track on thread %p", playbackThread);
1671 }
1672 }
1673
~OutputTrack()1674 AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1675 {
1676 clearBufferQueue();
1677 delete mClientProxy;
1678 // superclass destructor will now delete the server proxy and shared memory both refer to
1679 }
1680
start(AudioSystem::sync_event_t event,int triggerSession)1681 status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1682 int triggerSession)
1683 {
1684 status_t status = Track::start(event, triggerSession);
1685 if (status != NO_ERROR) {
1686 return status;
1687 }
1688
1689 mActive = true;
1690 mRetryCount = 127;
1691 return status;
1692 }
1693
stop()1694 void AudioFlinger::PlaybackThread::OutputTrack::stop()
1695 {
1696 Track::stop();
1697 clearBufferQueue();
1698 mOutBuffer.frameCount = 0;
1699 mActive = false;
1700 }
1701
write(void * data,uint32_t frames)1702 bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
1703 {
1704 Buffer *pInBuffer;
1705 Buffer inBuffer;
1706 bool outputBufferFull = false;
1707 inBuffer.frameCount = frames;
1708 inBuffer.raw = data;
1709
1710 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1711
1712 if (!mActive && frames != 0) {
1713 (void) start();
1714 }
1715
1716 while (waitTimeLeftMs) {
1717 // First write pending buffers, then new data
1718 if (mBufferQueue.size()) {
1719 pInBuffer = mBufferQueue.itemAt(0);
1720 } else {
1721 pInBuffer = &inBuffer;
1722 }
1723
1724 if (pInBuffer->frameCount == 0) {
1725 break;
1726 }
1727
1728 if (mOutBuffer.frameCount == 0) {
1729 mOutBuffer.frameCount = pInBuffer->frameCount;
1730 nsecs_t startTime = systemTime();
1731 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1732 if (status != NO_ERROR) {
1733 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1734 mThread.unsafe_get(), status);
1735 outputBufferFull = true;
1736 break;
1737 }
1738 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1739 if (waitTimeLeftMs >= waitTimeMs) {
1740 waitTimeLeftMs -= waitTimeMs;
1741 } else {
1742 waitTimeLeftMs = 0;
1743 }
1744 }
1745
1746 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1747 pInBuffer->frameCount;
1748 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
1749 Proxy::Buffer buf;
1750 buf.mFrameCount = outFrames;
1751 buf.mRaw = NULL;
1752 mClientProxy->releaseBuffer(&buf);
1753 pInBuffer->frameCount -= outFrames;
1754 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
1755 mOutBuffer.frameCount -= outFrames;
1756 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
1757
1758 if (pInBuffer->frameCount == 0) {
1759 if (mBufferQueue.size()) {
1760 mBufferQueue.removeAt(0);
1761 free(pInBuffer->mBuffer);
1762 delete pInBuffer;
1763 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1764 mThread.unsafe_get(), mBufferQueue.size());
1765 } else {
1766 break;
1767 }
1768 }
1769 }
1770
1771 // If we could not write all frames, allocate a buffer and queue it for next time.
1772 if (inBuffer.frameCount) {
1773 sp<ThreadBase> thread = mThread.promote();
1774 if (thread != 0 && !thread->standby()) {
1775 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1776 pInBuffer = new Buffer;
1777 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
1778 pInBuffer->frameCount = inBuffer.frameCount;
1779 pInBuffer->raw = pInBuffer->mBuffer;
1780 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
1781 mBufferQueue.add(pInBuffer);
1782 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1783 mThread.unsafe_get(), mBufferQueue.size());
1784 } else {
1785 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1786 mThread.unsafe_get(), this);
1787 }
1788 }
1789 }
1790
1791 // Calling write() with a 0 length buffer means that no more data will be written:
1792 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1793 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1794 stop();
1795 }
1796
1797 return outputBufferFull;
1798 }
1799
obtainBuffer(AudioBufferProvider::Buffer * buffer,uint32_t waitTimeMs)1800 status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1801 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1802 {
1803 ClientProxy::Buffer buf;
1804 buf.mFrameCount = buffer->frameCount;
1805 struct timespec timeout;
1806 timeout.tv_sec = waitTimeMs / 1000;
1807 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1808 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1809 buffer->frameCount = buf.mFrameCount;
1810 buffer->raw = buf.mRaw;
1811 return status;
1812 }
1813
clearBufferQueue()1814 void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1815 {
1816 size_t size = mBufferQueue.size();
1817
1818 for (size_t i = 0; i < size; i++) {
1819 Buffer *pBuffer = mBufferQueue.itemAt(i);
1820 free(pBuffer->mBuffer);
1821 delete pBuffer;
1822 }
1823 mBufferQueue.clear();
1824 }
1825
1826
PatchTrack(PlaybackThread * playbackThread,audio_stream_type_t streamType,uint32_t sampleRate,audio_channel_mask_t channelMask,audio_format_t format,size_t frameCount,void * buffer,IAudioFlinger::track_flags_t flags)1827 AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
1828 audio_stream_type_t streamType,
1829 uint32_t sampleRate,
1830 audio_channel_mask_t channelMask,
1831 audio_format_t format,
1832 size_t frameCount,
1833 void *buffer,
1834 IAudioFlinger::track_flags_t flags)
1835 : Track(playbackThread, NULL, streamType,
1836 sampleRate, format, channelMask, frameCount,
1837 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1838 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1839 {
1840 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1841 playbackThread->sampleRate();
1842 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1843 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1844
1845 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1846 this, sampleRate,
1847 (int)mPeerTimeout.tv_sec,
1848 (int)(mPeerTimeout.tv_nsec / 1000000));
1849 }
1850
~PatchTrack()1851 AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1852 {
1853 }
1854
1855 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer,int64_t pts)1856 status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1857 AudioBufferProvider::Buffer* buffer, int64_t pts)
1858 {
1859 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1860 Proxy::Buffer buf;
1861 buf.mFrameCount = buffer->frameCount;
1862 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1863 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
1864 buffer->frameCount = buf.mFrameCount;
1865 if (buf.mFrameCount == 0) {
1866 return WOULD_BLOCK;
1867 }
1868 status = Track::getNextBuffer(buffer, pts);
1869 return status;
1870 }
1871
releaseBuffer(AudioBufferProvider::Buffer * buffer)1872 void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1873 {
1874 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1875 Proxy::Buffer buf;
1876 buf.mFrameCount = buffer->frameCount;
1877 buf.mRaw = buffer->raw;
1878 mPeerProxy->releaseBuffer(&buf);
1879 TrackBase::releaseBuffer(buffer);
1880 }
1881
obtainBuffer(Proxy::Buffer * buffer,const struct timespec * timeOut)1882 status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1883 const struct timespec *timeOut)
1884 {
1885 return mProxy->obtainBuffer(buffer, timeOut);
1886 }
1887
releaseBuffer(Proxy::Buffer * buffer)1888 void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1889 {
1890 mProxy->releaseBuffer(buffer);
1891 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1892 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1893 start();
1894 }
1895 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1896 }
1897
1898 // ----------------------------------------------------------------------------
1899 // Record
1900 // ----------------------------------------------------------------------------
1901
RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack> & recordTrack)1902 AudioFlinger::RecordHandle::RecordHandle(
1903 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1904 : BnAudioRecord(),
1905 mRecordTrack(recordTrack)
1906 {
1907 }
1908
~RecordHandle()1909 AudioFlinger::RecordHandle::~RecordHandle() {
1910 stop_nonvirtual();
1911 mRecordTrack->destroy();
1912 }
1913
start(int event,int triggerSession)1914 status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1915 int triggerSession) {
1916 ALOGV("RecordHandle::start()");
1917 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1918 }
1919
stop()1920 void AudioFlinger::RecordHandle::stop() {
1921 stop_nonvirtual();
1922 }
1923
stop_nonvirtual()1924 void AudioFlinger::RecordHandle::stop_nonvirtual() {
1925 ALOGV("RecordHandle::stop()");
1926 mRecordTrack->stop();
1927 }
1928
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)1929 status_t AudioFlinger::RecordHandle::onTransact(
1930 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1931 {
1932 return BnAudioRecord::onTransact(code, data, reply, flags);
1933 }
1934
1935 // ----------------------------------------------------------------------------
1936
1937 // RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
RecordTrack(RecordThread * thread,const sp<Client> & client,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,void * buffer,int sessionId,int uid,IAudioFlinger::track_flags_t flags,track_type type)1938 AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1939 RecordThread *thread,
1940 const sp<Client>& client,
1941 uint32_t sampleRate,
1942 audio_format_t format,
1943 audio_channel_mask_t channelMask,
1944 size_t frameCount,
1945 void *buffer,
1946 int sessionId,
1947 int uid,
1948 IAudioFlinger::track_flags_t flags,
1949 track_type type)
1950 : TrackBase(thread, client, sampleRate, format,
1951 channelMask, frameCount, buffer, sessionId, uid,
1952 flags, false /*isOut*/,
1953 (type == TYPE_DEFAULT) ?
1954 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1955 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1956 type),
1957 mOverflow(false),
1958 mFramesToDrop(0),
1959 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1960 mRecordBufferConverter(NULL)
1961 {
1962 if (mCblk == NULL) {
1963 return;
1964 }
1965
1966 mRecordBufferConverter = new RecordBufferConverter(
1967 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1968 channelMask, format, sampleRate);
1969 // Check if the RecordBufferConverter construction was successful.
1970 // If not, don't continue with construction.
1971 //
1972 // NOTE: It would be extremely rare that the record track cannot be created
1973 // for the current device, but a pending or future device change would make
1974 // the record track configuration valid.
1975 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1976 ALOGE("RecordTrack unable to create record buffer converter");
1977 return;
1978 }
1979
1980 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1981 mFrameSize, !isExternalTrack());
1982 mResamplerBufferProvider = new ResamplerBufferProvider(this);
1983
1984 if (flags & IAudioFlinger::TRACK_FAST) {
1985 ALOG_ASSERT(thread->mFastTrackAvail);
1986 thread->mFastTrackAvail = false;
1987 }
1988 }
1989
~RecordTrack()1990 AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1991 {
1992 ALOGV("%s", __func__);
1993 delete mRecordBufferConverter;
1994 delete mResamplerBufferProvider;
1995 }
1996
initCheck() const1997 status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1998 {
1999 status_t status = TrackBase::initCheck();
2000 if (status == NO_ERROR && mServerProxy == 0) {
2001 status = BAD_VALUE;
2002 }
2003 return status;
2004 }
2005
2006 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer,int64_t pts __unused)2007 status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
2008 int64_t pts __unused)
2009 {
2010 ServerProxy::Buffer buf;
2011 buf.mFrameCount = buffer->frameCount;
2012 status_t status = mServerProxy->obtainBuffer(&buf);
2013 buffer->frameCount = buf.mFrameCount;
2014 buffer->raw = buf.mRaw;
2015 if (buf.mFrameCount == 0) {
2016 // FIXME also wake futex so that overrun is noticed more quickly
2017 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
2018 }
2019 return status;
2020 }
2021
start(AudioSystem::sync_event_t event,int triggerSession)2022 status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2023 int triggerSession)
2024 {
2025 sp<ThreadBase> thread = mThread.promote();
2026 if (thread != 0) {
2027 RecordThread *recordThread = (RecordThread *)thread.get();
2028 return recordThread->start(this, event, triggerSession);
2029 } else {
2030 return BAD_VALUE;
2031 }
2032 }
2033
stop()2034 void AudioFlinger::RecordThread::RecordTrack::stop()
2035 {
2036 sp<ThreadBase> thread = mThread.promote();
2037 if (thread != 0) {
2038 RecordThread *recordThread = (RecordThread *)thread.get();
2039 if (recordThread->stop(this) && isExternalTrack()) {
2040 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2041 }
2042 }
2043 }
2044
destroy()2045 void AudioFlinger::RecordThread::RecordTrack::destroy()
2046 {
2047 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2048 sp<RecordTrack> keep(this);
2049 {
2050 if (isExternalTrack()) {
2051 if (mState == ACTIVE || mState == RESUMING) {
2052 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2053 }
2054 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
2055 }
2056 sp<ThreadBase> thread = mThread.promote();
2057 if (thread != 0) {
2058 Mutex::Autolock _l(thread->mLock);
2059 RecordThread *recordThread = (RecordThread *) thread.get();
2060 recordThread->destroyTrack_l(this);
2061 }
2062 }
2063 }
2064
invalidate()2065 void AudioFlinger::RecordThread::RecordTrack::invalidate()
2066 {
2067 // FIXME should use proxy, and needs work
2068 audio_track_cblk_t* cblk = mCblk;
2069 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2070 android_atomic_release_store(0x40000000, &cblk->mFutex);
2071 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
2072 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
2073 }
2074
2075
appendDumpHeader(String8 & result)2076 /*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2077 {
2078 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
2079 }
2080
dump(char * buffer,size_t size,bool active)2081 void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
2082 {
2083 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
2084 active ? "yes" : "no",
2085 (mClient == 0) ? getpid_cached : mClient->pid(),
2086 mFormat,
2087 mChannelMask,
2088 mSessionId,
2089 mState,
2090 mCblk->mServer,
2091 mFrameCount,
2092 mSampleRate);
2093
2094 }
2095
handleSyncStartEvent(const sp<SyncEvent> & event)2096 void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2097 {
2098 if (event == mSyncStartEvent) {
2099 ssize_t framesToDrop = 0;
2100 sp<ThreadBase> threadBase = mThread.promote();
2101 if (threadBase != 0) {
2102 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2103 // from audio HAL
2104 framesToDrop = threadBase->mFrameCount * 2;
2105 }
2106 mFramesToDrop = framesToDrop;
2107 }
2108 }
2109
clearSyncStartEvent()2110 void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2111 {
2112 if (mSyncStartEvent != 0) {
2113 mSyncStartEvent->cancel();
2114 mSyncStartEvent.clear();
2115 }
2116 mFramesToDrop = 0;
2117 }
2118
2119
PatchRecord(RecordThread * recordThread,uint32_t sampleRate,audio_channel_mask_t channelMask,audio_format_t format,size_t frameCount,void * buffer,IAudioFlinger::track_flags_t flags)2120 AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2121 uint32_t sampleRate,
2122 audio_channel_mask_t channelMask,
2123 audio_format_t format,
2124 size_t frameCount,
2125 void *buffer,
2126 IAudioFlinger::track_flags_t flags)
2127 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2128 buffer, 0, getuid(), flags, TYPE_PATCH),
2129 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2130 {
2131 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2132 recordThread->sampleRate();
2133 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2134 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2135
2136 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2137 this, sampleRate,
2138 (int)mPeerTimeout.tv_sec,
2139 (int)(mPeerTimeout.tv_nsec / 1000000));
2140 }
2141
~PatchRecord()2142 AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2143 {
2144 }
2145
2146 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer,int64_t pts)2147 status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2148 AudioBufferProvider::Buffer* buffer, int64_t pts)
2149 {
2150 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2151 Proxy::Buffer buf;
2152 buf.mFrameCount = buffer->frameCount;
2153 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2154 ALOGV_IF(status != NO_ERROR,
2155 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
2156 buffer->frameCount = buf.mFrameCount;
2157 if (buf.mFrameCount == 0) {
2158 return WOULD_BLOCK;
2159 }
2160 status = RecordTrack::getNextBuffer(buffer, pts);
2161 return status;
2162 }
2163
releaseBuffer(AudioBufferProvider::Buffer * buffer)2164 void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2165 {
2166 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2167 Proxy::Buffer buf;
2168 buf.mFrameCount = buffer->frameCount;
2169 buf.mRaw = buffer->raw;
2170 mPeerProxy->releaseBuffer(&buf);
2171 TrackBase::releaseBuffer(buffer);
2172 }
2173
obtainBuffer(Proxy::Buffer * buffer,const struct timespec * timeOut)2174 status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2175 const struct timespec *timeOut)
2176 {
2177 return mProxy->obtainBuffer(buffer, timeOut);
2178 }
2179
releaseBuffer(Proxy::Buffer * buffer)2180 void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2181 {
2182 mProxy->releaseBuffer(buffer);
2183 }
2184
2185 } // namespace android
2186