blob: 6ea6f2f06d173a18b31ef43ded2c595c5197f512 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080023#include <math.h>
Eric Laurent81784c32012-11-19 14:55:58 -080024#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
Eric Laurent81784c32012-11-19 14:55:58 -080077 mState(IDLE),
78 mSampleRate(sampleRate),
79 mFormat(format),
80 mChannelMask(channelMask),
81 mChannelCount(popcount(channelMask)),
82 mFrameSize(audio_is_linear_pcm(format) ?
83 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
84 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080085 mSessionId(sessionId),
86 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080087 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080088 mId(android_atomic_inc(&nextTrackId)),
89 mTerminated(false)
Eric Laurent81784c32012-11-19 14:55:58 -080090{
91 // client == 0 implies sharedBuffer == 0
92 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
93
94 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
95 sharedBuffer->size());
96
97 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
98 size_t size = sizeof(audio_track_cblk_t);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080099 size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -0800100 if (sharedBuffer == 0) {
101 size += bufferSize;
102 }
103
104 if (client != 0) {
105 mCblkMemory = client->heap()->allocate(size);
106 if (mCblkMemory != 0) {
107 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
108 // can't assume mCblk != NULL
109 } else {
110 ALOGE("not enough memory for AudioTrack size=%u", size);
111 client->heap()->dump("AudioTrack");
112 return;
113 }
114 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800115 // this syntax avoids calling the audio_track_cblk_t constructor twice
116 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800117 // assume mCblk != NULL
118 }
119
120 // construct the shared structure in-place.
121 if (mCblk != NULL) {
122 new(mCblk) audio_track_cblk_t();
123 // clear all buffers
124 mCblk->frameCount_ = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800125 if (sharedBuffer == 0) {
126 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
127 memset(mBuffer, 0, bufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -0800128 } else {
129 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800130#if 0
Glenn Kasten96f60d82013-07-12 10:21:18 -0700131 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800132#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800133 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800134
Glenn Kasten46909e72013-02-26 09:20:22 -0800135#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800136 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800137 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
138 if (pipeFormat != Format_Invalid) {
139 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
140 size_t numCounterOffers = 0;
141 const NBAIO_Format offers[1] = {pipeFormat};
142 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
143 ALOG_ASSERT(index == 0);
144 PipeReader *pipeReader = new PipeReader(*pipe);
145 numCounterOffers = 0;
146 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
147 ALOG_ASSERT(index == 0);
148 mTeeSink = pipe;
149 mTeeSource = pipeReader;
150 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800151 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800152#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800153
Eric Laurent81784c32012-11-19 14:55:58 -0800154 }
155}
156
157AudioFlinger::ThreadBase::TrackBase::~TrackBase()
158{
Glenn Kasten46909e72013-02-26 09:20:22 -0800159#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800160 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800161#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800162 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
163 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800164 if (mCblk != NULL) {
165 if (mClient == 0) {
166 delete mCblk;
167 } else {
168 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
169 }
170 }
171 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
172 if (mClient != 0) {
173 // Client destructor must run with AudioFlinger mutex locked
174 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
175 // If the client's reference count drops to zero, the associated destructor
176 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
177 // relying on the automatic clear() at end of scope.
178 mClient.clear();
179 }
180}
181
182// AudioBufferProvider interface
183// getNextBuffer() = 0;
184// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
185void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
186{
Glenn Kasten46909e72013-02-26 09:20:22 -0800187#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800188 if (mTeeSink != 0) {
189 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
190 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800191#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800192
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800193 ServerProxy::Buffer buf;
194 buf.mFrameCount = buffer->frameCount;
195 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800196 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800197 buffer->raw = NULL;
198 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800199}
200
Eric Laurent81784c32012-11-19 14:55:58 -0800201status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
202{
203 mSyncEvents.add(event);
204 return NO_ERROR;
205}
206
207// ----------------------------------------------------------------------------
208// Playback
209// ----------------------------------------------------------------------------
210
211AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
212 : BnAudioTrack(),
213 mTrack(track)
214{
215}
216
217AudioFlinger::TrackHandle::~TrackHandle() {
218 // just stop the track on deletion, associated resources
219 // will be freed from the main thread once all pending buffers have
220 // been played. Unless it's not in the active track list, in which
221 // case we free everything now...
222 mTrack->destroy();
223}
224
225sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
226 return mTrack->getCblk();
227}
228
229status_t AudioFlinger::TrackHandle::start() {
230 return mTrack->start();
231}
232
233void AudioFlinger::TrackHandle::stop() {
234 mTrack->stop();
235}
236
237void AudioFlinger::TrackHandle::flush() {
238 mTrack->flush();
239}
240
Eric Laurent81784c32012-11-19 14:55:58 -0800241void AudioFlinger::TrackHandle::pause() {
242 mTrack->pause();
243}
244
245status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
246{
247 return mTrack->attachAuxEffect(EffectId);
248}
249
250status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
251 sp<IMemory>* buffer) {
252 if (!mTrack->isTimedTrack())
253 return INVALID_OPERATION;
254
255 PlaybackThread::TimedTrack* tt =
256 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
257 return tt->allocateTimedBuffer(size, buffer);
258}
259
260status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
261 int64_t pts) {
262 if (!mTrack->isTimedTrack())
263 return INVALID_OPERATION;
264
265 PlaybackThread::TimedTrack* tt =
266 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
267 return tt->queueTimedBuffer(buffer, pts);
268}
269
270status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
271 const LinearTransform& xform, int target) {
272
273 if (!mTrack->isTimedTrack())
274 return INVALID_OPERATION;
275
276 PlaybackThread::TimedTrack* tt =
277 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
278 return tt->setMediaTimeTransform(
279 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
280}
281
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700282status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
283 return mTrack->setParameters(keyValuePairs);
284}
285
Eric Laurent81784c32012-11-19 14:55:58 -0800286status_t AudioFlinger::TrackHandle::onTransact(
287 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
288{
289 return BnAudioTrack::onTransact(code, data, reply, flags);
290}
291
292// ----------------------------------------------------------------------------
293
294// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
295AudioFlinger::PlaybackThread::Track::Track(
296 PlaybackThread *thread,
297 const sp<Client>& client,
298 audio_stream_type_t streamType,
299 uint32_t sampleRate,
300 audio_format_t format,
301 audio_channel_mask_t channelMask,
302 size_t frameCount,
303 const sp<IMemory>& sharedBuffer,
304 int sessionId,
305 IAudioFlinger::track_flags_t flags)
306 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -0800307 sessionId, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800308 mFillingUpStatus(FS_INVALID),
309 // mRetryCount initialized later when needed
310 mSharedBuffer(sharedBuffer),
311 mStreamType(streamType),
312 mName(-1), // see note below
313 mMainBuffer(thread->mixBuffer()),
314 mAuxBuffer(NULL),
315 mAuxEffectId(0), mHasVolumeController(false),
316 mPresentationCompleteFrames(0),
317 mFlags(flags),
318 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800319 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800320 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800321 mAudioTrackServerProxy(NULL),
322 mResumeToStopping(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800323{
324 if (mCblk != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800325 if (sharedBuffer == 0) {
326 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
327 mFrameSize);
328 } else {
329 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
330 mFrameSize);
331 }
332 mServerProxy = mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800333 // to avoid leaking a track name, do not allocate one unless there is an mCblk
334 mName = thread->getTrackName_l(channelMask, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800335 if (mName < 0) {
336 ALOGE("no more track names available");
337 return;
338 }
339 // only allocate a fast track index if we were able to allocate a normal track name
340 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800341 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Eric Laurent81784c32012-11-19 14:55:58 -0800342 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
343 int i = __builtin_ctz(thread->mFastTrackAvailMask);
344 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
345 // FIXME This is too eager. We allocate a fast track index before the
346 // fast track becomes active. Since fast tracks are a scarce resource,
347 // this means we are potentially denying other more important fast tracks from
348 // being created. It would be better to allocate the index dynamically.
349 mFastIndex = i;
Eric Laurent81784c32012-11-19 14:55:58 -0800350 // Read the initial underruns because this field is never cleared by the fast mixer
351 mObservedUnderruns = thread->getFastTrackUnderruns(i);
352 thread->mFastTrackAvailMask &= ~(1 << i);
353 }
354 }
355 ALOGV("Track constructor name %d, calling pid %d", mName,
356 IPCThreadState::self()->getCallingPid());
357}
358
359AudioFlinger::PlaybackThread::Track::~Track()
360{
361 ALOGV("PlaybackThread::Track destructor");
362}
363
364void AudioFlinger::PlaybackThread::Track::destroy()
365{
366 // NOTE: destroyTrack_l() can remove a strong reference to this Track
367 // by removing it from mTracks vector, so there is a risk that this Tracks's
368 // destructor is called. As the destructor needs to lock mLock,
369 // we must acquire a strong reference on this Track before locking mLock
370 // here so that the destructor is called only when exiting this function.
371 // On the other hand, as long as Track::destroy() is only called by
372 // TrackHandle destructor, the TrackHandle still holds a strong ref on
373 // this Track with its member mTrack.
374 sp<Track> keep(this);
375 { // scope for mLock
376 sp<ThreadBase> thread = mThread.promote();
377 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800378 Mutex::Autolock _l(thread->mLock);
379 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800380 bool wasActive = playbackThread->destroyTrack_l(this);
381 if (!isOutputTrack() && !wasActive) {
382 AudioSystem::releaseOutput(thread->id());
383 }
Eric Laurent81784c32012-11-19 14:55:58 -0800384 }
385 }
386}
387
388/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
389{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -0700390 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700391 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800392}
393
394void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
395{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800396 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800397 if (isFastTrack()) {
398 sprintf(buffer, " F %2d", mFastIndex);
399 } else {
400 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
401 }
402 track_state state = mState;
403 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800404 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800405 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800406 } else {
407 switch (state) {
408 case IDLE:
409 stateChar = 'I';
410 break;
411 case STOPPING_1:
412 stateChar = 's';
413 break;
414 case STOPPING_2:
415 stateChar = '5';
416 break;
417 case STOPPED:
418 stateChar = 'S';
419 break;
420 case RESUMING:
421 stateChar = 'R';
422 break;
423 case ACTIVE:
424 stateChar = 'A';
425 break;
426 case PAUSING:
427 stateChar = 'p';
428 break;
429 case PAUSED:
430 stateChar = 'P';
431 break;
432 case FLUSHED:
433 stateChar = 'F';
434 break;
435 default:
436 stateChar = '?';
437 break;
438 }
Eric Laurent81784c32012-11-19 14:55:58 -0800439 }
440 char nowInUnderrun;
441 switch (mObservedUnderruns.mBitFields.mMostRecent) {
442 case UNDERRUN_FULL:
443 nowInUnderrun = ' ';
444 break;
445 case UNDERRUN_PARTIAL:
446 nowInUnderrun = '<';
447 break;
448 case UNDERRUN_EMPTY:
449 nowInUnderrun = '*';
450 break;
451 default:
452 nowInUnderrun = '?';
453 break;
454 }
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -0700455 snprintf(&buffer[7], size-7, " %6u %4u %3u %08X %7u %6u %1c %1d %5u %5.2g %5.2g "
456 "%08X %08X %08X 0x%03X %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800457 (mClient == 0) ? getpid_cached : mClient->pid(),
458 mStreamType,
459 mFormat,
460 mChannelMask,
461 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800462 mFrameCount,
463 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800464 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800465 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800466 20.0 * log10((vlr & 0xFFFF) / 4096.0),
467 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700468 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -0800469 (int)mMainBuffer,
470 (int)mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700471 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700472 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800473 nowInUnderrun);
474}
475
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800476uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
477 return mAudioTrackServerProxy->getSampleRate();
478}
479
Eric Laurent81784c32012-11-19 14:55:58 -0800480// AudioBufferProvider interface
481status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
482 AudioBufferProvider::Buffer* buffer, int64_t pts)
483{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800484 ServerProxy::Buffer buf;
485 size_t desiredFrames = buffer->frameCount;
486 buf.mFrameCount = desiredFrames;
487 status_t status = mServerProxy->obtainBuffer(&buf);
488 buffer->frameCount = buf.mFrameCount;
489 buffer->raw = buf.mRaw;
490 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700491 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800492 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800493 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800494}
495
496// Note that framesReady() takes a mutex on the control block using tryLock().
497// This could result in priority inversion if framesReady() is called by the normal mixer,
498// as the normal mixer thread runs at lower
499// priority than the client's callback thread: there is a short window within framesReady()
500// during which the normal mixer could be preempted, and the client callback would block.
501// Another problem can occur if framesReady() is called by the fast mixer:
502// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
503// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
504size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800505 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800506}
507
508// Don't call for fast tracks; the framesReady() could result in priority inversion
509bool AudioFlinger::PlaybackThread::Track::isReady() const {
510 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
511 return true;
512 }
513
514 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700515 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800516 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700517 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800518 return true;
519 }
520 return false;
521}
522
523status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
524 int triggerSession)
525{
526 status_t status = NO_ERROR;
527 ALOGV("start(%d), calling pid %d session %d",
528 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
529
530 sp<ThreadBase> thread = mThread.promote();
531 if (thread != 0) {
532 Mutex::Autolock _l(thread->mLock);
533 track_state state = mState;
534 // here the track could be either new, or restarted
535 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800536
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800537 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800538 if (mResumeToStopping) {
539 // happened we need to resume to STOPPING_1
540 mState = TrackBase::STOPPING_1;
541 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
542 } else {
543 mState = TrackBase::RESUMING;
544 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
545 }
Eric Laurent81784c32012-11-19 14:55:58 -0800546 } else {
547 mState = TrackBase::ACTIVE;
548 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
549 }
550
Eric Laurentbfb1b832013-01-07 09:53:42 -0800551 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
552 status = playbackThread->addTrack_l(this);
553 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800554 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800555 // restore previous state if start was rejected by policy manager
556 if (status == PERMISSION_DENIED) {
557 mState = state;
558 }
559 }
560 // track was already in the active list, not a problem
561 if (status == ALREADY_EXISTS) {
562 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -0800563 }
564 } else {
565 status = BAD_VALUE;
566 }
567 return status;
568}
569
570void AudioFlinger::PlaybackThread::Track::stop()
571{
572 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
573 sp<ThreadBase> thread = mThread.promote();
574 if (thread != 0) {
575 Mutex::Autolock _l(thread->mLock);
576 track_state state = mState;
577 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
578 // If the track is not active (PAUSED and buffers full), flush buffers
579 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
580 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
581 reset();
582 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800583 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800584 mState = STOPPED;
585 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800586 // For fast tracks prepareTracks_l() will set state to STOPPING_2
587 // presentation is complete
588 // For an offloaded track this starts a drain and state will
589 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800590 mState = STOPPING_1;
591 }
592 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
593 playbackThread);
594 }
Eric Laurent81784c32012-11-19 14:55:58 -0800595 }
596}
597
598void AudioFlinger::PlaybackThread::Track::pause()
599{
600 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
601 sp<ThreadBase> thread = mThread.promote();
602 if (thread != 0) {
603 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800604 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
605 switch (mState) {
606 case STOPPING_1:
607 case STOPPING_2:
608 if (!isOffloaded()) {
609 /* nothing to do if track is not offloaded */
610 break;
611 }
612
613 // Offloaded track was draining, we need to carry on draining when resumed
614 mResumeToStopping = true;
615 // fall through...
616 case ACTIVE:
617 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800618 mState = PAUSING;
619 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -0800620 playbackThread->signal_l();
621 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800622
Eric Laurentbfb1b832013-01-07 09:53:42 -0800623 default:
624 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800625 }
626 }
627}
628
629void AudioFlinger::PlaybackThread::Track::flush()
630{
631 ALOGV("flush(%d)", mName);
632 sp<ThreadBase> thread = mThread.promote();
633 if (thread != 0) {
634 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800635 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800636
637 if (isOffloaded()) {
638 // If offloaded we allow flush during any state except terminated
639 // and keep the track active to avoid problems if user is seeking
640 // rapidly and underlying hardware has a significant delay handling
641 // a pause
642 if (isTerminated()) {
643 return;
644 }
645
646 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800647 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800648
649 if (mState == STOPPING_1 || mState == STOPPING_2) {
650 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
651 mState = ACTIVE;
652 }
653
654 if (mState == ACTIVE) {
655 ALOGV("flush called in active state, resetting buffer time out retry count");
656 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
657 }
658
659 mResumeToStopping = false;
660 } else {
661 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
662 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
663 return;
664 }
665 // No point remaining in PAUSED state after a flush => go to
666 // FLUSHED state
667 mState = FLUSHED;
668 // do not reset the track if it is still in the process of being stopped or paused.
669 // this will be done by prepareTracks_l() when the track is stopped.
670 // prepareTracks_l() will see mState == FLUSHED, then
671 // remove from active track list, reset(), and trigger presentation complete
672 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
673 reset();
674 }
Eric Laurent81784c32012-11-19 14:55:58 -0800675 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800676 // Prevent flush being lost if the track is flushed and then resumed
677 // before mixer thread can run. This is important when offloading
678 // because the hardware buffer could hold a large amount of audio
679 playbackThread->flushOutput_l();
680 playbackThread->signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800681 }
682}
683
684void AudioFlinger::PlaybackThread::Track::reset()
685{
686 // Do not reset twice to avoid discarding data written just after a flush and before
687 // the audioflinger thread detects the track is stopped.
688 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800689 // Force underrun condition to avoid false underrun callback until first data is
690 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700691 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800692 mFillingUpStatus = FS_FILLING;
693 mResetDone = true;
694 if (mState == FLUSHED) {
695 mState = IDLE;
696 }
697 }
698}
699
Eric Laurentbfb1b832013-01-07 09:53:42 -0800700status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
701{
702 sp<ThreadBase> thread = mThread.promote();
703 if (thread == 0) {
704 ALOGE("thread is dead");
705 return FAILED_TRANSACTION;
706 } else if ((thread->type() == ThreadBase::DIRECT) ||
707 (thread->type() == ThreadBase::OFFLOAD)) {
708 return thread->setParameters(keyValuePairs);
709 } else {
710 return PERMISSION_DENIED;
711 }
712}
713
Eric Laurent81784c32012-11-19 14:55:58 -0800714status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
715{
716 status_t status = DEAD_OBJECT;
717 sp<ThreadBase> thread = mThread.promote();
718 if (thread != 0) {
719 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
720 sp<AudioFlinger> af = mClient->audioFlinger();
721
722 Mutex::Autolock _l(af->mLock);
723
724 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
725
726 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
727 Mutex::Autolock _dl(playbackThread->mLock);
728 Mutex::Autolock _sl(srcThread->mLock);
729 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
730 if (chain == 0) {
731 return INVALID_OPERATION;
732 }
733
734 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
735 if (effect == 0) {
736 return INVALID_OPERATION;
737 }
738 srcThread->removeEffect_l(effect);
739 playbackThread->addEffect_l(effect);
740 // removeEffect_l() has stopped the effect if it was active so it must be restarted
741 if (effect->state() == EffectModule::ACTIVE ||
742 effect->state() == EffectModule::STOPPING) {
743 effect->start();
744 }
745
746 sp<EffectChain> dstChain = effect->chain().promote();
747 if (dstChain == 0) {
748 srcThread->addEffect_l(effect);
749 return INVALID_OPERATION;
750 }
751 AudioSystem::unregisterEffect(effect->id());
752 AudioSystem::registerEffect(&effect->desc(),
753 srcThread->id(),
754 dstChain->strategy(),
755 AUDIO_SESSION_OUTPUT_MIX,
756 effect->id());
757 }
758 status = playbackThread->attachAuxEffect(this, EffectId);
759 }
760 return status;
761}
762
763void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
764{
765 mAuxEffectId = EffectId;
766 mAuxBuffer = buffer;
767}
768
769bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
770 size_t audioHalFrames)
771{
772 // a track is considered presented when the total number of frames written to audio HAL
773 // corresponds to the number of frames written when presentationComplete() is called for the
774 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800775 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
776 // to detect when all frames have been played. In this case framesWritten isn't
777 // useful because it doesn't always reflect whether there is data in the h/w
778 // buffers, particularly if a track has been paused and resumed during draining
779 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
780 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800781 if (mPresentationCompleteFrames == 0) {
782 mPresentationCompleteFrames = framesWritten + audioHalFrames;
783 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
784 mPresentationCompleteFrames, audioHalFrames);
785 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800786
787 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800788 ALOGV("presentationComplete() session %d complete: framesWritten %d",
789 mSessionId, framesWritten);
790 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800791 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800792 return true;
793 }
794 return false;
795}
796
797void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
798{
799 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
800 if (mSyncEvents[i]->type() == type) {
801 mSyncEvents[i]->trigger();
802 mSyncEvents.removeAt(i);
803 i--;
804 }
805 }
806}
807
808// implement VolumeBufferProvider interface
809
810uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
811{
812 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
813 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800814 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800815 uint32_t vl = vlr & 0xFFFF;
816 uint32_t vr = vlr >> 16;
817 // track volumes come from shared memory, so can't be trusted and must be clamped
818 if (vl > MAX_GAIN_INT) {
819 vl = MAX_GAIN_INT;
820 }
821 if (vr > MAX_GAIN_INT) {
822 vr = MAX_GAIN_INT;
823 }
824 // now apply the cached master volume and stream type volume;
825 // this is trusted but lacks any synchronization or barrier so may be stale
826 float v = mCachedVolume;
827 vl *= v;
828 vr *= v;
829 // re-combine into U4.16
830 vlr = (vr << 16) | (vl & 0xFFFF);
831 // FIXME look at mute, pause, and stop flags
832 return vlr;
833}
834
835status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
836{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800837 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800838 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
839 (mState == STOPPED)))) {
840 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
841 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
842 event->cancel();
843 return INVALID_OPERATION;
844 }
845 (void) TrackBase::setSyncEvent(event);
846 return NO_ERROR;
847}
848
Glenn Kasten5736c352012-12-04 12:12:34 -0800849void AudioFlinger::PlaybackThread::Track::invalidate()
850{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800851 // FIXME should use proxy, and needs work
852 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700853 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800854 android_atomic_release_store(0x40000000, &cblk->mFutex);
855 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
856 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800857 mIsInvalid = true;
858}
859
Eric Laurent81784c32012-11-19 14:55:58 -0800860// ----------------------------------------------------------------------------
861
862sp<AudioFlinger::PlaybackThread::TimedTrack>
863AudioFlinger::PlaybackThread::TimedTrack::create(
864 PlaybackThread *thread,
865 const sp<Client>& client,
866 audio_stream_type_t streamType,
867 uint32_t sampleRate,
868 audio_format_t format,
869 audio_channel_mask_t channelMask,
870 size_t frameCount,
871 const sp<IMemory>& sharedBuffer,
872 int sessionId) {
873 if (!client->reserveTimedTrack())
874 return 0;
875
876 return new TimedTrack(
877 thread, client, streamType, sampleRate, format, channelMask, frameCount,
878 sharedBuffer, sessionId);
879}
880
881AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
882 PlaybackThread *thread,
883 const sp<Client>& client,
884 audio_stream_type_t streamType,
885 uint32_t sampleRate,
886 audio_format_t format,
887 audio_channel_mask_t channelMask,
888 size_t frameCount,
889 const sp<IMemory>& sharedBuffer,
890 int sessionId)
891 : Track(thread, client, streamType, sampleRate, format, channelMask,
892 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
893 mQueueHeadInFlight(false),
894 mTrimQueueHeadOnRelease(false),
895 mFramesPendingInQueue(0),
896 mTimedSilenceBuffer(NULL),
897 mTimedSilenceBufferSize(0),
898 mTimedAudioOutputOnTime(false),
899 mMediaTimeTransformValid(false)
900{
901 LocalClock lc;
902 mLocalTimeFreq = lc.getLocalFreq();
903
904 mLocalTimeToSampleTransform.a_zero = 0;
905 mLocalTimeToSampleTransform.b_zero = 0;
906 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
907 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
908 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
909 &mLocalTimeToSampleTransform.a_to_b_denom);
910
911 mMediaTimeToSampleTransform.a_zero = 0;
912 mMediaTimeToSampleTransform.b_zero = 0;
913 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
914 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
915 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
916 &mMediaTimeToSampleTransform.a_to_b_denom);
917}
918
919AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
920 mClient->releaseTimedTrack();
921 delete [] mTimedSilenceBuffer;
922}
923
924status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
925 size_t size, sp<IMemory>* buffer) {
926
927 Mutex::Autolock _l(mTimedBufferQueueLock);
928
929 trimTimedBufferQueue_l();
930
931 // lazily initialize the shared memory heap for timed buffers
932 if (mTimedMemoryDealer == NULL) {
933 const int kTimedBufferHeapSize = 512 << 10;
934
935 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
936 "AudioFlingerTimed");
937 if (mTimedMemoryDealer == NULL)
938 return NO_MEMORY;
939 }
940
941 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
942 if (newBuffer == NULL) {
943 newBuffer = mTimedMemoryDealer->allocate(size);
944 if (newBuffer == NULL)
945 return NO_MEMORY;
946 }
947
948 *buffer = newBuffer;
949 return NO_ERROR;
950}
951
952// caller must hold mTimedBufferQueueLock
953void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
954 int64_t mediaTimeNow;
955 {
956 Mutex::Autolock mttLock(mMediaTimeTransformLock);
957 if (!mMediaTimeTransformValid)
958 return;
959
960 int64_t targetTimeNow;
961 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
962 ? mCCHelper.getCommonTime(&targetTimeNow)
963 : mCCHelper.getLocalTime(&targetTimeNow);
964
965 if (OK != res)
966 return;
967
968 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
969 &mediaTimeNow)) {
970 return;
971 }
972 }
973
974 size_t trimEnd;
975 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
976 int64_t bufEnd;
977
978 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
979 // We have a next buffer. Just use its PTS as the PTS of the frame
980 // following the last frame in this buffer. If the stream is sparse
981 // (ie, there are deliberate gaps left in the stream which should be
982 // filled with silence by the TimedAudioTrack), then this can result
983 // in one extra buffer being left un-trimmed when it could have
984 // been. In general, this is not typical, and we would rather
985 // optimized away the TS calculation below for the more common case
986 // where PTSes are contiguous.
987 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
988 } else {
989 // We have no next buffer. Compute the PTS of the frame following
990 // the last frame in this buffer by computing the duration of of
991 // this frame in media time units and adding it to the PTS of the
992 // buffer.
993 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
994 / mFrameSize;
995
996 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
997 &bufEnd)) {
998 ALOGE("Failed to convert frame count of %lld to media time"
999 " duration" " (scale factor %d/%u) in %s",
1000 frameCount,
1001 mMediaTimeToSampleTransform.a_to_b_numer,
1002 mMediaTimeToSampleTransform.a_to_b_denom,
1003 __PRETTY_FUNCTION__);
1004 break;
1005 }
1006 bufEnd += mTimedBufferQueue[trimEnd].pts();
1007 }
1008
1009 if (bufEnd > mediaTimeNow)
1010 break;
1011
1012 // Is the buffer we want to use in the middle of a mix operation right
1013 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1014 // from the mixer which should be coming back shortly.
1015 if (!trimEnd && mQueueHeadInFlight) {
1016 mTrimQueueHeadOnRelease = true;
1017 }
1018 }
1019
1020 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1021 if (trimStart < trimEnd) {
1022 // Update the bookkeeping for framesReady()
1023 for (size_t i = trimStart; i < trimEnd; ++i) {
1024 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1025 }
1026
1027 // Now actually remove the buffers from the queue.
1028 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1029 }
1030}
1031
1032void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1033 const char* logTag) {
1034 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1035 "%s called (reason \"%s\"), but timed buffer queue has no"
1036 " elements to trim.", __FUNCTION__, logTag);
1037
1038 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1039 mTimedBufferQueue.removeAt(0);
1040}
1041
1042void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1043 const TimedBuffer& buf,
1044 const char* logTag) {
1045 uint32_t bufBytes = buf.buffer()->size();
1046 uint32_t consumedAlready = buf.position();
1047
1048 ALOG_ASSERT(consumedAlready <= bufBytes,
1049 "Bad bookkeeping while updating frames pending. Timed buffer is"
1050 " only %u bytes long, but claims to have consumed %u"
1051 " bytes. (update reason: \"%s\")",
1052 bufBytes, consumedAlready, logTag);
1053
1054 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1055 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1056 "Bad bookkeeping while updating frames pending. Should have at"
1057 " least %u queued frames, but we think we have only %u. (update"
1058 " reason: \"%s\")",
1059 bufFrames, mFramesPendingInQueue, logTag);
1060
1061 mFramesPendingInQueue -= bufFrames;
1062}
1063
1064status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1065 const sp<IMemory>& buffer, int64_t pts) {
1066
1067 {
1068 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1069 if (!mMediaTimeTransformValid)
1070 return INVALID_OPERATION;
1071 }
1072
1073 Mutex::Autolock _l(mTimedBufferQueueLock);
1074
1075 uint32_t bufFrames = buffer->size() / mFrameSize;
1076 mFramesPendingInQueue += bufFrames;
1077 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1078
1079 return NO_ERROR;
1080}
1081
1082status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1083 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1084
1085 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1086 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1087 target);
1088
1089 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1090 target == TimedAudioTrack::COMMON_TIME)) {
1091 return BAD_VALUE;
1092 }
1093
1094 Mutex::Autolock lock(mMediaTimeTransformLock);
1095 mMediaTimeTransform = xform;
1096 mMediaTimeTransformTarget = target;
1097 mMediaTimeTransformValid = true;
1098
1099 return NO_ERROR;
1100}
1101
1102#define min(a, b) ((a) < (b) ? (a) : (b))
1103
1104// implementation of getNextBuffer for tracks whose buffers have timestamps
1105status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1106 AudioBufferProvider::Buffer* buffer, int64_t pts)
1107{
1108 if (pts == AudioBufferProvider::kInvalidPTS) {
1109 buffer->raw = NULL;
1110 buffer->frameCount = 0;
1111 mTimedAudioOutputOnTime = false;
1112 return INVALID_OPERATION;
1113 }
1114
1115 Mutex::Autolock _l(mTimedBufferQueueLock);
1116
1117 ALOG_ASSERT(!mQueueHeadInFlight,
1118 "getNextBuffer called without releaseBuffer!");
1119
1120 while (true) {
1121
1122 // if we have no timed buffers, then fail
1123 if (mTimedBufferQueue.isEmpty()) {
1124 buffer->raw = NULL;
1125 buffer->frameCount = 0;
1126 return NOT_ENOUGH_DATA;
1127 }
1128
1129 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1130
1131 // calculate the PTS of the head of the timed buffer queue expressed in
1132 // local time
1133 int64_t headLocalPTS;
1134 {
1135 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1136
1137 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1138
1139 if (mMediaTimeTransform.a_to_b_denom == 0) {
1140 // the transform represents a pause, so yield silence
1141 timedYieldSilence_l(buffer->frameCount, buffer);
1142 return NO_ERROR;
1143 }
1144
1145 int64_t transformedPTS;
1146 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1147 &transformedPTS)) {
1148 // the transform failed. this shouldn't happen, but if it does
1149 // then just drop this buffer
1150 ALOGW("timedGetNextBuffer transform failed");
1151 buffer->raw = NULL;
1152 buffer->frameCount = 0;
1153 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1154 return NO_ERROR;
1155 }
1156
1157 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1158 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1159 &headLocalPTS)) {
1160 buffer->raw = NULL;
1161 buffer->frameCount = 0;
1162 return INVALID_OPERATION;
1163 }
1164 } else {
1165 headLocalPTS = transformedPTS;
1166 }
1167 }
1168
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001169 uint32_t sr = sampleRate();
1170
Eric Laurent81784c32012-11-19 14:55:58 -08001171 // adjust the head buffer's PTS to reflect the portion of the head buffer
1172 // that has already been consumed
1173 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001174 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001175
1176 // Calculate the delta in samples between the head of the input buffer
1177 // queue and the start of the next output buffer that will be written.
1178 // If the transformation fails because of over or underflow, it means
1179 // that the sample's position in the output stream is so far out of
1180 // whack that it should just be dropped.
1181 int64_t sampleDelta;
1182 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1183 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1184 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1185 " mix");
1186 continue;
1187 }
1188 if (!mLocalTimeToSampleTransform.doForwardTransform(
1189 (effectivePTS - pts) << 32, &sampleDelta)) {
1190 ALOGV("*** too late during sample rate transform: dropped buffer");
1191 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1192 continue;
1193 }
1194
1195 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1196 " sampleDelta=[%d.%08x]",
1197 head.pts(), head.position(), pts,
1198 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1199 + (sampleDelta >> 32)),
1200 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1201
1202 // if the delta between the ideal placement for the next input sample and
1203 // the current output position is within this threshold, then we will
1204 // concatenate the next input samples to the previous output
1205 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001206 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001207
1208 // if this is the first buffer of audio that we're emitting from this track
1209 // then it should be almost exactly on time.
1210 const int64_t kSampleStartupThreshold = 1LL << 32;
1211
1212 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1213 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1214 // the next input is close enough to being on time, so concatenate it
1215 // with the last output
1216 timedYieldSamples_l(buffer);
1217
1218 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1219 head.position(), buffer->frameCount);
1220 return NO_ERROR;
1221 }
1222
1223 // Looks like our output is not on time. Reset our on timed status.
1224 // Next time we mix samples from our input queue, then should be within
1225 // the StartupThreshold.
1226 mTimedAudioOutputOnTime = false;
1227 if (sampleDelta > 0) {
1228 // the gap between the current output position and the proper start of
1229 // the next input sample is too big, so fill it with silence
1230 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1231
1232 timedYieldSilence_l(framesUntilNextInput, buffer);
1233 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1234 return NO_ERROR;
1235 } else {
1236 // the next input sample is late
1237 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1238 size_t onTimeSamplePosition =
1239 head.position() + lateFrames * mFrameSize;
1240
1241 if (onTimeSamplePosition > head.buffer()->size()) {
1242 // all the remaining samples in the head are too late, so
1243 // drop it and move on
1244 ALOGV("*** too late: dropped buffer");
1245 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1246 continue;
1247 } else {
1248 // skip over the late samples
1249 head.setPosition(onTimeSamplePosition);
1250
1251 // yield the available samples
1252 timedYieldSamples_l(buffer);
1253
1254 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1255 return NO_ERROR;
1256 }
1257 }
1258 }
1259}
1260
1261// Yield samples from the timed buffer queue head up to the given output
1262// buffer's capacity.
1263//
1264// Caller must hold mTimedBufferQueueLock
1265void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1266 AudioBufferProvider::Buffer* buffer) {
1267
1268 const TimedBuffer& head = mTimedBufferQueue[0];
1269
1270 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1271 head.position());
1272
1273 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1274 mFrameSize);
1275 size_t framesRequested = buffer->frameCount;
1276 buffer->frameCount = min(framesLeftInHead, framesRequested);
1277
1278 mQueueHeadInFlight = true;
1279 mTimedAudioOutputOnTime = true;
1280}
1281
1282// Yield samples of silence up to the given output buffer's capacity
1283//
1284// Caller must hold mTimedBufferQueueLock
1285void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1286 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1287
1288 // lazily allocate a buffer filled with silence
1289 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1290 delete [] mTimedSilenceBuffer;
1291 mTimedSilenceBufferSize = numFrames * mFrameSize;
1292 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1293 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1294 }
1295
1296 buffer->raw = mTimedSilenceBuffer;
1297 size_t framesRequested = buffer->frameCount;
1298 buffer->frameCount = min(numFrames, framesRequested);
1299
1300 mTimedAudioOutputOnTime = false;
1301}
1302
1303// AudioBufferProvider interface
1304void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1305 AudioBufferProvider::Buffer* buffer) {
1306
1307 Mutex::Autolock _l(mTimedBufferQueueLock);
1308
1309 // If the buffer which was just released is part of the buffer at the head
1310 // of the queue, be sure to update the amt of the buffer which has been
1311 // consumed. If the buffer being returned is not part of the head of the
1312 // queue, its either because the buffer is part of the silence buffer, or
1313 // because the head of the timed queue was trimmed after the mixer called
1314 // getNextBuffer but before the mixer called releaseBuffer.
1315 if (buffer->raw == mTimedSilenceBuffer) {
1316 ALOG_ASSERT(!mQueueHeadInFlight,
1317 "Queue head in flight during release of silence buffer!");
1318 goto done;
1319 }
1320
1321 ALOG_ASSERT(mQueueHeadInFlight,
1322 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1323 " head in flight.");
1324
1325 if (mTimedBufferQueue.size()) {
1326 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1327
1328 void* start = head.buffer()->pointer();
1329 void* end = reinterpret_cast<void*>(
1330 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1331 + head.buffer()->size());
1332
1333 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1334 "released buffer not within the head of the timed buffer"
1335 " queue; qHead = [%p, %p], released buffer = %p",
1336 start, end, buffer->raw);
1337
1338 head.setPosition(head.position() +
1339 (buffer->frameCount * mFrameSize));
1340 mQueueHeadInFlight = false;
1341
1342 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1343 "Bad bookkeeping during releaseBuffer! Should have at"
1344 " least %u queued frames, but we think we have only %u",
1345 buffer->frameCount, mFramesPendingInQueue);
1346
1347 mFramesPendingInQueue -= buffer->frameCount;
1348
1349 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1350 || mTrimQueueHeadOnRelease) {
1351 trimTimedBufferQueueHead_l("releaseBuffer");
1352 mTrimQueueHeadOnRelease = false;
1353 }
1354 } else {
1355 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1356 " buffers in the timed buffer queue");
1357 }
1358
1359done:
1360 buffer->raw = 0;
1361 buffer->frameCount = 0;
1362}
1363
1364size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1365 Mutex::Autolock _l(mTimedBufferQueueLock);
1366 return mFramesPendingInQueue;
1367}
1368
1369AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1370 : mPTS(0), mPosition(0) {}
1371
1372AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1373 const sp<IMemory>& buffer, int64_t pts)
1374 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1375
1376
1377// ----------------------------------------------------------------------------
1378
1379AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1380 PlaybackThread *playbackThread,
1381 DuplicatingThread *sourceThread,
1382 uint32_t sampleRate,
1383 audio_format_t format,
1384 audio_channel_mask_t channelMask,
1385 size_t frameCount)
1386 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1387 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001388 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001389{
1390
1391 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001392 mOutBuffer.frameCount = 0;
1393 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001394 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001395 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001396 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001397 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001398 // since client and server are in the same process,
1399 // the buffer has the same virtual address on both sides
1400 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001401 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1402 mClientProxy->setSendLevel(0.0);
1403 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001404 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1405 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001406 } else {
1407 ALOGW("Error creating output track on thread %p", playbackThread);
1408 }
1409}
1410
1411AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1412{
1413 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001414 delete mClientProxy;
1415 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001416}
1417
1418status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1419 int triggerSession)
1420{
1421 status_t status = Track::start(event, triggerSession);
1422 if (status != NO_ERROR) {
1423 return status;
1424 }
1425
1426 mActive = true;
1427 mRetryCount = 127;
1428 return status;
1429}
1430
1431void AudioFlinger::PlaybackThread::OutputTrack::stop()
1432{
1433 Track::stop();
1434 clearBufferQueue();
1435 mOutBuffer.frameCount = 0;
1436 mActive = false;
1437}
1438
1439bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1440{
1441 Buffer *pInBuffer;
1442 Buffer inBuffer;
1443 uint32_t channelCount = mChannelCount;
1444 bool outputBufferFull = false;
1445 inBuffer.frameCount = frames;
1446 inBuffer.i16 = data;
1447
1448 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1449
1450 if (!mActive && frames != 0) {
1451 start();
1452 sp<ThreadBase> thread = mThread.promote();
1453 if (thread != 0) {
1454 MixerThread *mixerThread = (MixerThread *)thread.get();
1455 if (mFrameCount > frames) {
1456 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1457 uint32_t startFrames = (mFrameCount - frames);
1458 pInBuffer = new Buffer;
1459 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1460 pInBuffer->frameCount = startFrames;
1461 pInBuffer->i16 = pInBuffer->mBuffer;
1462 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1463 mBufferQueue.add(pInBuffer);
1464 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001465 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001466 }
1467 }
1468 }
1469 }
1470
1471 while (waitTimeLeftMs) {
1472 // First write pending buffers, then new data
1473 if (mBufferQueue.size()) {
1474 pInBuffer = mBufferQueue.itemAt(0);
1475 } else {
1476 pInBuffer = &inBuffer;
1477 }
1478
1479 if (pInBuffer->frameCount == 0) {
1480 break;
1481 }
1482
1483 if (mOutBuffer.frameCount == 0) {
1484 mOutBuffer.frameCount = pInBuffer->frameCount;
1485 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001486 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1487 if (status != NO_ERROR) {
1488 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1489 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001490 outputBufferFull = true;
1491 break;
1492 }
1493 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1494 if (waitTimeLeftMs >= waitTimeMs) {
1495 waitTimeLeftMs -= waitTimeMs;
1496 } else {
1497 waitTimeLeftMs = 0;
1498 }
1499 }
1500
1501 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1502 pInBuffer->frameCount;
1503 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001504 Proxy::Buffer buf;
1505 buf.mFrameCount = outFrames;
1506 buf.mRaw = NULL;
1507 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001508 pInBuffer->frameCount -= outFrames;
1509 pInBuffer->i16 += outFrames * channelCount;
1510 mOutBuffer.frameCount -= outFrames;
1511 mOutBuffer.i16 += outFrames * channelCount;
1512
1513 if (pInBuffer->frameCount == 0) {
1514 if (mBufferQueue.size()) {
1515 mBufferQueue.removeAt(0);
1516 delete [] pInBuffer->mBuffer;
1517 delete pInBuffer;
1518 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1519 mThread.unsafe_get(), mBufferQueue.size());
1520 } else {
1521 break;
1522 }
1523 }
1524 }
1525
1526 // If we could not write all frames, allocate a buffer and queue it for next time.
1527 if (inBuffer.frameCount) {
1528 sp<ThreadBase> thread = mThread.promote();
1529 if (thread != 0 && !thread->standby()) {
1530 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1531 pInBuffer = new Buffer;
1532 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1533 pInBuffer->frameCount = inBuffer.frameCount;
1534 pInBuffer->i16 = pInBuffer->mBuffer;
1535 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1536 sizeof(int16_t));
1537 mBufferQueue.add(pInBuffer);
1538 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1539 mThread.unsafe_get(), mBufferQueue.size());
1540 } else {
1541 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1542 mThread.unsafe_get(), this);
1543 }
1544 }
1545 }
1546
1547 // Calling write() with a 0 length buffer, means that no more data will be written:
1548 // If no more buffers are pending, fill output track buffer to make sure it is started
1549 // by output mixer.
1550 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001551 // FIXME borken, replace by getting framesReady() from proxy
1552 size_t user = 0; // was mCblk->user
1553 if (user < mFrameCount) {
1554 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001555 pInBuffer = new Buffer;
1556 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1557 pInBuffer->frameCount = frames;
1558 pInBuffer->i16 = pInBuffer->mBuffer;
1559 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1560 mBufferQueue.add(pInBuffer);
1561 } else if (mActive) {
1562 stop();
1563 }
1564 }
1565
1566 return outputBufferFull;
1567}
1568
1569status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1570 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1571{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001572 ClientProxy::Buffer buf;
1573 buf.mFrameCount = buffer->frameCount;
1574 struct timespec timeout;
1575 timeout.tv_sec = waitTimeMs / 1000;
1576 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1577 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1578 buffer->frameCount = buf.mFrameCount;
1579 buffer->raw = buf.mRaw;
1580 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001581}
1582
Eric Laurent81784c32012-11-19 14:55:58 -08001583void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1584{
1585 size_t size = mBufferQueue.size();
1586
1587 for (size_t i = 0; i < size; i++) {
1588 Buffer *pBuffer = mBufferQueue.itemAt(i);
1589 delete [] pBuffer->mBuffer;
1590 delete pBuffer;
1591 }
1592 mBufferQueue.clear();
1593}
1594
1595
1596// ----------------------------------------------------------------------------
1597// Record
1598// ----------------------------------------------------------------------------
1599
1600AudioFlinger::RecordHandle::RecordHandle(
1601 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1602 : BnAudioRecord(),
1603 mRecordTrack(recordTrack)
1604{
1605}
1606
1607AudioFlinger::RecordHandle::~RecordHandle() {
1608 stop_nonvirtual();
1609 mRecordTrack->destroy();
1610}
1611
1612sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1613 return mRecordTrack->getCblk();
1614}
1615
1616status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1617 int triggerSession) {
1618 ALOGV("RecordHandle::start()");
1619 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1620}
1621
1622void AudioFlinger::RecordHandle::stop() {
1623 stop_nonvirtual();
1624}
1625
1626void AudioFlinger::RecordHandle::stop_nonvirtual() {
1627 ALOGV("RecordHandle::stop()");
1628 mRecordTrack->stop();
1629}
1630
1631status_t AudioFlinger::RecordHandle::onTransact(
1632 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1633{
1634 return BnAudioRecord::onTransact(code, data, reply, flags);
1635}
1636
1637// ----------------------------------------------------------------------------
1638
1639// RecordTrack constructor must be called with AudioFlinger::mLock held
1640AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1641 RecordThread *thread,
1642 const sp<Client>& client,
1643 uint32_t sampleRate,
1644 audio_format_t format,
1645 audio_channel_mask_t channelMask,
1646 size_t frameCount,
1647 int sessionId)
1648 : TrackBase(thread, client, sampleRate, format,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001649 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001650 mOverflow(false)
1651{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001652 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001653 if (mCblk != NULL) {
Glenn Kasten6ae6b812013-08-05 15:16:21 -07001654 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001655 }
Eric Laurent81784c32012-11-19 14:55:58 -08001656}
1657
1658AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1659{
1660 ALOGV("%s", __func__);
1661}
1662
1663// AudioBufferProvider interface
1664status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1665 int64_t pts)
1666{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001667 ServerProxy::Buffer buf;
1668 buf.mFrameCount = buffer->frameCount;
1669 status_t status = mServerProxy->obtainBuffer(&buf);
1670 buffer->frameCount = buf.mFrameCount;
1671 buffer->raw = buf.mRaw;
1672 if (buf.mFrameCount == 0) {
1673 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001674 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001675 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001676 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001677}
1678
1679status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1680 int triggerSession)
1681{
1682 sp<ThreadBase> thread = mThread.promote();
1683 if (thread != 0) {
1684 RecordThread *recordThread = (RecordThread *)thread.get();
1685 return recordThread->start(this, event, triggerSession);
1686 } else {
1687 return BAD_VALUE;
1688 }
1689}
1690
1691void AudioFlinger::RecordThread::RecordTrack::stop()
1692{
1693 sp<ThreadBase> thread = mThread.promote();
1694 if (thread != 0) {
1695 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001696 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001697 AudioSystem::stopInput(recordThread->id());
1698 }
1699 }
1700}
1701
1702void AudioFlinger::RecordThread::RecordTrack::destroy()
1703{
1704 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1705 sp<RecordTrack> keep(this);
1706 {
1707 sp<ThreadBase> thread = mThread.promote();
1708 if (thread != 0) {
1709 if (mState == ACTIVE || mState == RESUMING) {
1710 AudioSystem::stopInput(thread->id());
1711 }
1712 AudioSystem::releaseInput(thread->id());
1713 Mutex::Autolock _l(thread->mLock);
1714 RecordThread *recordThread = (RecordThread *) thread.get();
1715 recordThread->destroyTrack_l(this);
1716 }
1717 }
1718}
1719
1720
1721/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1722{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001723 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001724}
1725
1726void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1727{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001728 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001729 (mClient == 0) ? getpid_cached : mClient->pid(),
1730 mFormat,
1731 mChannelMask,
1732 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001733 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001734 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001735 mFrameCount);
1736}
1737
Eric Laurent81784c32012-11-19 14:55:58 -08001738}; // namespace android