blob: 962270956eb5afcc8f9ad540eeba68b81d0371d8 [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
Glenn Kasten53cec222013-08-29 09:01:02 -0700286status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
287{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700288 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700289}
290
Eric Laurent81784c32012-11-19 14:55:58 -0800291status_t AudioFlinger::TrackHandle::onTransact(
292 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
293{
294 return BnAudioTrack::onTransact(code, data, reply, flags);
295}
296
297// ----------------------------------------------------------------------------
298
299// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
300AudioFlinger::PlaybackThread::Track::Track(
301 PlaybackThread *thread,
302 const sp<Client>& client,
303 audio_stream_type_t streamType,
304 uint32_t sampleRate,
305 audio_format_t format,
306 audio_channel_mask_t channelMask,
307 size_t frameCount,
308 const sp<IMemory>& sharedBuffer,
309 int sessionId,
310 IAudioFlinger::track_flags_t flags)
311 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -0800312 sessionId, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800313 mFillingUpStatus(FS_INVALID),
314 // mRetryCount initialized later when needed
315 mSharedBuffer(sharedBuffer),
316 mStreamType(streamType),
317 mName(-1), // see note below
318 mMainBuffer(thread->mixBuffer()),
319 mAuxBuffer(NULL),
320 mAuxEffectId(0), mHasVolumeController(false),
321 mPresentationCompleteFrames(0),
322 mFlags(flags),
323 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800324 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800325 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800326 mAudioTrackServerProxy(NULL),
327 mResumeToStopping(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800328{
329 if (mCblk != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800330 if (sharedBuffer == 0) {
331 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
332 mFrameSize);
333 } else {
334 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
335 mFrameSize);
336 }
337 mServerProxy = mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800338 // to avoid leaking a track name, do not allocate one unless there is an mCblk
339 mName = thread->getTrackName_l(channelMask, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800340 if (mName < 0) {
341 ALOGE("no more track names available");
342 return;
343 }
344 // only allocate a fast track index if we were able to allocate a normal track name
345 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800346 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Eric Laurent81784c32012-11-19 14:55:58 -0800347 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
348 int i = __builtin_ctz(thread->mFastTrackAvailMask);
349 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
350 // FIXME This is too eager. We allocate a fast track index before the
351 // fast track becomes active. Since fast tracks are a scarce resource,
352 // this means we are potentially denying other more important fast tracks from
353 // being created. It would be better to allocate the index dynamically.
354 mFastIndex = i;
Eric Laurent81784c32012-11-19 14:55:58 -0800355 // Read the initial underruns because this field is never cleared by the fast mixer
356 mObservedUnderruns = thread->getFastTrackUnderruns(i);
357 thread->mFastTrackAvailMask &= ~(1 << i);
358 }
359 }
360 ALOGV("Track constructor name %d, calling pid %d", mName,
361 IPCThreadState::self()->getCallingPid());
362}
363
364AudioFlinger::PlaybackThread::Track::~Track()
365{
366 ALOGV("PlaybackThread::Track destructor");
367}
368
369void AudioFlinger::PlaybackThread::Track::destroy()
370{
371 // NOTE: destroyTrack_l() can remove a strong reference to this Track
372 // by removing it from mTracks vector, so there is a risk that this Tracks's
373 // destructor is called. As the destructor needs to lock mLock,
374 // we must acquire a strong reference on this Track before locking mLock
375 // here so that the destructor is called only when exiting this function.
376 // On the other hand, as long as Track::destroy() is only called by
377 // TrackHandle destructor, the TrackHandle still holds a strong ref on
378 // this Track with its member mTrack.
379 sp<Track> keep(this);
380 { // scope for mLock
381 sp<ThreadBase> thread = mThread.promote();
382 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800383 Mutex::Autolock _l(thread->mLock);
384 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800385 bool wasActive = playbackThread->destroyTrack_l(this);
386 if (!isOutputTrack() && !wasActive) {
387 AudioSystem::releaseOutput(thread->id());
388 }
Eric Laurent81784c32012-11-19 14:55:58 -0800389 }
390 }
391}
392
393/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
394{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -0700395 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700396 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800397}
398
399void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
400{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800401 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800402 if (isFastTrack()) {
403 sprintf(buffer, " F %2d", mFastIndex);
404 } else {
405 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
406 }
407 track_state state = mState;
408 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800409 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800410 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800411 } else {
412 switch (state) {
413 case IDLE:
414 stateChar = 'I';
415 break;
416 case STOPPING_1:
417 stateChar = 's';
418 break;
419 case STOPPING_2:
420 stateChar = '5';
421 break;
422 case STOPPED:
423 stateChar = 'S';
424 break;
425 case RESUMING:
426 stateChar = 'R';
427 break;
428 case ACTIVE:
429 stateChar = 'A';
430 break;
431 case PAUSING:
432 stateChar = 'p';
433 break;
434 case PAUSED:
435 stateChar = 'P';
436 break;
437 case FLUSHED:
438 stateChar = 'F';
439 break;
440 default:
441 stateChar = '?';
442 break;
443 }
Eric Laurent81784c32012-11-19 14:55:58 -0800444 }
445 char nowInUnderrun;
446 switch (mObservedUnderruns.mBitFields.mMostRecent) {
447 case UNDERRUN_FULL:
448 nowInUnderrun = ' ';
449 break;
450 case UNDERRUN_PARTIAL:
451 nowInUnderrun = '<';
452 break;
453 case UNDERRUN_EMPTY:
454 nowInUnderrun = '*';
455 break;
456 default:
457 nowInUnderrun = '?';
458 break;
459 }
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -0700460 snprintf(&buffer[7], size-7, " %6u %4u %3u %08X %7u %6u %1c %1d %5u %5.2g %5.2g "
461 "%08X %08X %08X 0x%03X %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800462 (mClient == 0) ? getpid_cached : mClient->pid(),
463 mStreamType,
464 mFormat,
465 mChannelMask,
466 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800467 mFrameCount,
468 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800469 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800470 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800471 20.0 * log10((vlr & 0xFFFF) / 4096.0),
472 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700473 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -0800474 (int)mMainBuffer,
475 (int)mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700476 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700477 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800478 nowInUnderrun);
479}
480
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800481uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
482 return mAudioTrackServerProxy->getSampleRate();
483}
484
Eric Laurent81784c32012-11-19 14:55:58 -0800485// AudioBufferProvider interface
486status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
487 AudioBufferProvider::Buffer* buffer, int64_t pts)
488{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 ServerProxy::Buffer buf;
490 size_t desiredFrames = buffer->frameCount;
491 buf.mFrameCount = desiredFrames;
492 status_t status = mServerProxy->obtainBuffer(&buf);
493 buffer->frameCount = buf.mFrameCount;
494 buffer->raw = buf.mRaw;
495 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700496 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800497 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800498 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800499}
500
501// Note that framesReady() takes a mutex on the control block using tryLock().
502// This could result in priority inversion if framesReady() is called by the normal mixer,
503// as the normal mixer thread runs at lower
504// priority than the client's callback thread: there is a short window within framesReady()
505// during which the normal mixer could be preempted, and the client callback would block.
506// Another problem can occur if framesReady() is called by the fast mixer:
507// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
508// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
509size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800510 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800511}
512
513// Don't call for fast tracks; the framesReady() could result in priority inversion
514bool AudioFlinger::PlaybackThread::Track::isReady() const {
515 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
516 return true;
517 }
518
519 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700520 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800521 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700522 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800523 return true;
524 }
525 return false;
526}
527
528status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
529 int triggerSession)
530{
531 status_t status = NO_ERROR;
532 ALOGV("start(%d), calling pid %d session %d",
533 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
534
535 sp<ThreadBase> thread = mThread.promote();
536 if (thread != 0) {
537 Mutex::Autolock _l(thread->mLock);
538 track_state state = mState;
539 // here the track could be either new, or restarted
540 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800541
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800542 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800543 if (mResumeToStopping) {
544 // happened we need to resume to STOPPING_1
545 mState = TrackBase::STOPPING_1;
546 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
547 } else {
548 mState = TrackBase::RESUMING;
549 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
550 }
Eric Laurent81784c32012-11-19 14:55:58 -0800551 } else {
552 mState = TrackBase::ACTIVE;
553 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
554 }
555
Eric Laurentbfb1b832013-01-07 09:53:42 -0800556 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
557 status = playbackThread->addTrack_l(this);
558 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800559 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800560 // restore previous state if start was rejected by policy manager
561 if (status == PERMISSION_DENIED) {
562 mState = state;
563 }
564 }
565 // track was already in the active list, not a problem
566 if (status == ALREADY_EXISTS) {
567 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -0800568 }
569 } else {
570 status = BAD_VALUE;
571 }
572 return status;
573}
574
575void AudioFlinger::PlaybackThread::Track::stop()
576{
577 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
578 sp<ThreadBase> thread = mThread.promote();
579 if (thread != 0) {
580 Mutex::Autolock _l(thread->mLock);
581 track_state state = mState;
582 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
583 // If the track is not active (PAUSED and buffers full), flush buffers
584 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
585 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
586 reset();
587 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800588 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800589 mState = STOPPED;
590 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800591 // For fast tracks prepareTracks_l() will set state to STOPPING_2
592 // presentation is complete
593 // For an offloaded track this starts a drain and state will
594 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800595 mState = STOPPING_1;
596 }
597 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
598 playbackThread);
599 }
Eric Laurent81784c32012-11-19 14:55:58 -0800600 }
601}
602
603void AudioFlinger::PlaybackThread::Track::pause()
604{
605 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
606 sp<ThreadBase> thread = mThread.promote();
607 if (thread != 0) {
608 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800609 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
610 switch (mState) {
611 case STOPPING_1:
612 case STOPPING_2:
613 if (!isOffloaded()) {
614 /* nothing to do if track is not offloaded */
615 break;
616 }
617
618 // Offloaded track was draining, we need to carry on draining when resumed
619 mResumeToStopping = true;
620 // fall through...
621 case ACTIVE:
622 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800623 mState = PAUSING;
624 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -0800625 playbackThread->signal_l();
626 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800627
Eric Laurentbfb1b832013-01-07 09:53:42 -0800628 default:
629 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800630 }
631 }
632}
633
634void AudioFlinger::PlaybackThread::Track::flush()
635{
636 ALOGV("flush(%d)", mName);
637 sp<ThreadBase> thread = mThread.promote();
638 if (thread != 0) {
639 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800640 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800641
642 if (isOffloaded()) {
643 // If offloaded we allow flush during any state except terminated
644 // and keep the track active to avoid problems if user is seeking
645 // rapidly and underlying hardware has a significant delay handling
646 // a pause
647 if (isTerminated()) {
648 return;
649 }
650
651 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800652 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800653
654 if (mState == STOPPING_1 || mState == STOPPING_2) {
655 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
656 mState = ACTIVE;
657 }
658
659 if (mState == ACTIVE) {
660 ALOGV("flush called in active state, resetting buffer time out retry count");
661 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
662 }
663
664 mResumeToStopping = false;
665 } else {
666 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
667 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
668 return;
669 }
670 // No point remaining in PAUSED state after a flush => go to
671 // FLUSHED state
672 mState = FLUSHED;
673 // do not reset the track if it is still in the process of being stopped or paused.
674 // this will be done by prepareTracks_l() when the track is stopped.
675 // prepareTracks_l() will see mState == FLUSHED, then
676 // remove from active track list, reset(), and trigger presentation complete
677 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
678 reset();
679 }
Eric Laurent81784c32012-11-19 14:55:58 -0800680 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800681 // Prevent flush being lost if the track is flushed and then resumed
682 // before mixer thread can run. This is important when offloading
683 // because the hardware buffer could hold a large amount of audio
684 playbackThread->flushOutput_l();
685 playbackThread->signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800686 }
687}
688
689void AudioFlinger::PlaybackThread::Track::reset()
690{
691 // Do not reset twice to avoid discarding data written just after a flush and before
692 // the audioflinger thread detects the track is stopped.
693 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800694 // Force underrun condition to avoid false underrun callback until first data is
695 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700696 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800697 mFillingUpStatus = FS_FILLING;
698 mResetDone = true;
699 if (mState == FLUSHED) {
700 mState = IDLE;
701 }
702 }
703}
704
Eric Laurentbfb1b832013-01-07 09:53:42 -0800705status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
706{
707 sp<ThreadBase> thread = mThread.promote();
708 if (thread == 0) {
709 ALOGE("thread is dead");
710 return FAILED_TRANSACTION;
711 } else if ((thread->type() == ThreadBase::DIRECT) ||
712 (thread->type() == ThreadBase::OFFLOAD)) {
713 return thread->setParameters(keyValuePairs);
714 } else {
715 return PERMISSION_DENIED;
716 }
717}
718
Glenn Kasten573d80a2013-08-26 09:36:23 -0700719status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
720{
721 sp<ThreadBase> thread = mThread.promote();
722 if (thread == 0) {
723 return false;
724 }
725 Mutex::Autolock _l(thread->mLock);
726 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700727 if (!playbackThread->mLatchQValid) {
728 return INVALID_OPERATION;
729 }
730 uint32_t unpresentedFrames =
731 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
732 playbackThread->mSampleRate;
733 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
734 if (framesWritten < unpresentedFrames) {
735 return INVALID_OPERATION;
736 }
737 timestamp.mPosition = framesWritten - unpresentedFrames;
738 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
739 return NO_ERROR;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700740}
741
Eric Laurent81784c32012-11-19 14:55:58 -0800742status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
743{
744 status_t status = DEAD_OBJECT;
745 sp<ThreadBase> thread = mThread.promote();
746 if (thread != 0) {
747 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
748 sp<AudioFlinger> af = mClient->audioFlinger();
749
750 Mutex::Autolock _l(af->mLock);
751
752 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
753
754 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
755 Mutex::Autolock _dl(playbackThread->mLock);
756 Mutex::Autolock _sl(srcThread->mLock);
757 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
758 if (chain == 0) {
759 return INVALID_OPERATION;
760 }
761
762 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
763 if (effect == 0) {
764 return INVALID_OPERATION;
765 }
766 srcThread->removeEffect_l(effect);
767 playbackThread->addEffect_l(effect);
768 // removeEffect_l() has stopped the effect if it was active so it must be restarted
769 if (effect->state() == EffectModule::ACTIVE ||
770 effect->state() == EffectModule::STOPPING) {
771 effect->start();
772 }
773
774 sp<EffectChain> dstChain = effect->chain().promote();
775 if (dstChain == 0) {
776 srcThread->addEffect_l(effect);
777 return INVALID_OPERATION;
778 }
779 AudioSystem::unregisterEffect(effect->id());
780 AudioSystem::registerEffect(&effect->desc(),
781 srcThread->id(),
782 dstChain->strategy(),
783 AUDIO_SESSION_OUTPUT_MIX,
784 effect->id());
785 }
786 status = playbackThread->attachAuxEffect(this, EffectId);
787 }
788 return status;
789}
790
791void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
792{
793 mAuxEffectId = EffectId;
794 mAuxBuffer = buffer;
795}
796
797bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
798 size_t audioHalFrames)
799{
800 // a track is considered presented when the total number of frames written to audio HAL
801 // corresponds to the number of frames written when presentationComplete() is called for the
802 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800803 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
804 // to detect when all frames have been played. In this case framesWritten isn't
805 // useful because it doesn't always reflect whether there is data in the h/w
806 // buffers, particularly if a track has been paused and resumed during draining
807 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
808 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800809 if (mPresentationCompleteFrames == 0) {
810 mPresentationCompleteFrames = framesWritten + audioHalFrames;
811 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
812 mPresentationCompleteFrames, audioHalFrames);
813 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800814
815 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800816 ALOGV("presentationComplete() session %d complete: framesWritten %d",
817 mSessionId, framesWritten);
818 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800819 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800820 return true;
821 }
822 return false;
823}
824
825void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
826{
827 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
828 if (mSyncEvents[i]->type() == type) {
829 mSyncEvents[i]->trigger();
830 mSyncEvents.removeAt(i);
831 i--;
832 }
833 }
834}
835
836// implement VolumeBufferProvider interface
837
838uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
839{
840 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
841 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800842 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800843 uint32_t vl = vlr & 0xFFFF;
844 uint32_t vr = vlr >> 16;
845 // track volumes come from shared memory, so can't be trusted and must be clamped
846 if (vl > MAX_GAIN_INT) {
847 vl = MAX_GAIN_INT;
848 }
849 if (vr > MAX_GAIN_INT) {
850 vr = MAX_GAIN_INT;
851 }
852 // now apply the cached master volume and stream type volume;
853 // this is trusted but lacks any synchronization or barrier so may be stale
854 float v = mCachedVolume;
855 vl *= v;
856 vr *= v;
857 // re-combine into U4.16
858 vlr = (vr << 16) | (vl & 0xFFFF);
859 // FIXME look at mute, pause, and stop flags
860 return vlr;
861}
862
863status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
864{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800865 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800866 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
867 (mState == STOPPED)))) {
868 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
869 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
870 event->cancel();
871 return INVALID_OPERATION;
872 }
873 (void) TrackBase::setSyncEvent(event);
874 return NO_ERROR;
875}
876
Glenn Kasten5736c352012-12-04 12:12:34 -0800877void AudioFlinger::PlaybackThread::Track::invalidate()
878{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800879 // FIXME should use proxy, and needs work
880 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700881 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882 android_atomic_release_store(0x40000000, &cblk->mFutex);
883 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
884 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800885 mIsInvalid = true;
886}
887
Eric Laurent81784c32012-11-19 14:55:58 -0800888// ----------------------------------------------------------------------------
889
890sp<AudioFlinger::PlaybackThread::TimedTrack>
891AudioFlinger::PlaybackThread::TimedTrack::create(
892 PlaybackThread *thread,
893 const sp<Client>& client,
894 audio_stream_type_t streamType,
895 uint32_t sampleRate,
896 audio_format_t format,
897 audio_channel_mask_t channelMask,
898 size_t frameCount,
899 const sp<IMemory>& sharedBuffer,
900 int sessionId) {
901 if (!client->reserveTimedTrack())
902 return 0;
903
904 return new TimedTrack(
905 thread, client, streamType, sampleRate, format, channelMask, frameCount,
906 sharedBuffer, sessionId);
907}
908
909AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
910 PlaybackThread *thread,
911 const sp<Client>& client,
912 audio_stream_type_t streamType,
913 uint32_t sampleRate,
914 audio_format_t format,
915 audio_channel_mask_t channelMask,
916 size_t frameCount,
917 const sp<IMemory>& sharedBuffer,
918 int sessionId)
919 : Track(thread, client, streamType, sampleRate, format, channelMask,
920 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
921 mQueueHeadInFlight(false),
922 mTrimQueueHeadOnRelease(false),
923 mFramesPendingInQueue(0),
924 mTimedSilenceBuffer(NULL),
925 mTimedSilenceBufferSize(0),
926 mTimedAudioOutputOnTime(false),
927 mMediaTimeTransformValid(false)
928{
929 LocalClock lc;
930 mLocalTimeFreq = lc.getLocalFreq();
931
932 mLocalTimeToSampleTransform.a_zero = 0;
933 mLocalTimeToSampleTransform.b_zero = 0;
934 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
935 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
936 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
937 &mLocalTimeToSampleTransform.a_to_b_denom);
938
939 mMediaTimeToSampleTransform.a_zero = 0;
940 mMediaTimeToSampleTransform.b_zero = 0;
941 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
942 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
943 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
944 &mMediaTimeToSampleTransform.a_to_b_denom);
945}
946
947AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
948 mClient->releaseTimedTrack();
949 delete [] mTimedSilenceBuffer;
950}
951
952status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
953 size_t size, sp<IMemory>* buffer) {
954
955 Mutex::Autolock _l(mTimedBufferQueueLock);
956
957 trimTimedBufferQueue_l();
958
959 // lazily initialize the shared memory heap for timed buffers
960 if (mTimedMemoryDealer == NULL) {
961 const int kTimedBufferHeapSize = 512 << 10;
962
963 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
964 "AudioFlingerTimed");
965 if (mTimedMemoryDealer == NULL)
966 return NO_MEMORY;
967 }
968
969 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
970 if (newBuffer == NULL) {
971 newBuffer = mTimedMemoryDealer->allocate(size);
972 if (newBuffer == NULL)
973 return NO_MEMORY;
974 }
975
976 *buffer = newBuffer;
977 return NO_ERROR;
978}
979
980// caller must hold mTimedBufferQueueLock
981void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
982 int64_t mediaTimeNow;
983 {
984 Mutex::Autolock mttLock(mMediaTimeTransformLock);
985 if (!mMediaTimeTransformValid)
986 return;
987
988 int64_t targetTimeNow;
989 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
990 ? mCCHelper.getCommonTime(&targetTimeNow)
991 : mCCHelper.getLocalTime(&targetTimeNow);
992
993 if (OK != res)
994 return;
995
996 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
997 &mediaTimeNow)) {
998 return;
999 }
1000 }
1001
1002 size_t trimEnd;
1003 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1004 int64_t bufEnd;
1005
1006 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1007 // We have a next buffer. Just use its PTS as the PTS of the frame
1008 // following the last frame in this buffer. If the stream is sparse
1009 // (ie, there are deliberate gaps left in the stream which should be
1010 // filled with silence by the TimedAudioTrack), then this can result
1011 // in one extra buffer being left un-trimmed when it could have
1012 // been. In general, this is not typical, and we would rather
1013 // optimized away the TS calculation below for the more common case
1014 // where PTSes are contiguous.
1015 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1016 } else {
1017 // We have no next buffer. Compute the PTS of the frame following
1018 // the last frame in this buffer by computing the duration of of
1019 // this frame in media time units and adding it to the PTS of the
1020 // buffer.
1021 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1022 / mFrameSize;
1023
1024 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1025 &bufEnd)) {
1026 ALOGE("Failed to convert frame count of %lld to media time"
1027 " duration" " (scale factor %d/%u) in %s",
1028 frameCount,
1029 mMediaTimeToSampleTransform.a_to_b_numer,
1030 mMediaTimeToSampleTransform.a_to_b_denom,
1031 __PRETTY_FUNCTION__);
1032 break;
1033 }
1034 bufEnd += mTimedBufferQueue[trimEnd].pts();
1035 }
1036
1037 if (bufEnd > mediaTimeNow)
1038 break;
1039
1040 // Is the buffer we want to use in the middle of a mix operation right
1041 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1042 // from the mixer which should be coming back shortly.
1043 if (!trimEnd && mQueueHeadInFlight) {
1044 mTrimQueueHeadOnRelease = true;
1045 }
1046 }
1047
1048 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1049 if (trimStart < trimEnd) {
1050 // Update the bookkeeping for framesReady()
1051 for (size_t i = trimStart; i < trimEnd; ++i) {
1052 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1053 }
1054
1055 // Now actually remove the buffers from the queue.
1056 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1057 }
1058}
1059
1060void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1061 const char* logTag) {
1062 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1063 "%s called (reason \"%s\"), but timed buffer queue has no"
1064 " elements to trim.", __FUNCTION__, logTag);
1065
1066 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1067 mTimedBufferQueue.removeAt(0);
1068}
1069
1070void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1071 const TimedBuffer& buf,
1072 const char* logTag) {
1073 uint32_t bufBytes = buf.buffer()->size();
1074 uint32_t consumedAlready = buf.position();
1075
1076 ALOG_ASSERT(consumedAlready <= bufBytes,
1077 "Bad bookkeeping while updating frames pending. Timed buffer is"
1078 " only %u bytes long, but claims to have consumed %u"
1079 " bytes. (update reason: \"%s\")",
1080 bufBytes, consumedAlready, logTag);
1081
1082 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1083 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1084 "Bad bookkeeping while updating frames pending. Should have at"
1085 " least %u queued frames, but we think we have only %u. (update"
1086 " reason: \"%s\")",
1087 bufFrames, mFramesPendingInQueue, logTag);
1088
1089 mFramesPendingInQueue -= bufFrames;
1090}
1091
1092status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1093 const sp<IMemory>& buffer, int64_t pts) {
1094
1095 {
1096 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1097 if (!mMediaTimeTransformValid)
1098 return INVALID_OPERATION;
1099 }
1100
1101 Mutex::Autolock _l(mTimedBufferQueueLock);
1102
1103 uint32_t bufFrames = buffer->size() / mFrameSize;
1104 mFramesPendingInQueue += bufFrames;
1105 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1106
1107 return NO_ERROR;
1108}
1109
1110status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1111 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1112
1113 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1114 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1115 target);
1116
1117 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1118 target == TimedAudioTrack::COMMON_TIME)) {
1119 return BAD_VALUE;
1120 }
1121
1122 Mutex::Autolock lock(mMediaTimeTransformLock);
1123 mMediaTimeTransform = xform;
1124 mMediaTimeTransformTarget = target;
1125 mMediaTimeTransformValid = true;
1126
1127 return NO_ERROR;
1128}
1129
1130#define min(a, b) ((a) < (b) ? (a) : (b))
1131
1132// implementation of getNextBuffer for tracks whose buffers have timestamps
1133status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1134 AudioBufferProvider::Buffer* buffer, int64_t pts)
1135{
1136 if (pts == AudioBufferProvider::kInvalidPTS) {
1137 buffer->raw = NULL;
1138 buffer->frameCount = 0;
1139 mTimedAudioOutputOnTime = false;
1140 return INVALID_OPERATION;
1141 }
1142
1143 Mutex::Autolock _l(mTimedBufferQueueLock);
1144
1145 ALOG_ASSERT(!mQueueHeadInFlight,
1146 "getNextBuffer called without releaseBuffer!");
1147
1148 while (true) {
1149
1150 // if we have no timed buffers, then fail
1151 if (mTimedBufferQueue.isEmpty()) {
1152 buffer->raw = NULL;
1153 buffer->frameCount = 0;
1154 return NOT_ENOUGH_DATA;
1155 }
1156
1157 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1158
1159 // calculate the PTS of the head of the timed buffer queue expressed in
1160 // local time
1161 int64_t headLocalPTS;
1162 {
1163 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1164
1165 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1166
1167 if (mMediaTimeTransform.a_to_b_denom == 0) {
1168 // the transform represents a pause, so yield silence
1169 timedYieldSilence_l(buffer->frameCount, buffer);
1170 return NO_ERROR;
1171 }
1172
1173 int64_t transformedPTS;
1174 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1175 &transformedPTS)) {
1176 // the transform failed. this shouldn't happen, but if it does
1177 // then just drop this buffer
1178 ALOGW("timedGetNextBuffer transform failed");
1179 buffer->raw = NULL;
1180 buffer->frameCount = 0;
1181 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1182 return NO_ERROR;
1183 }
1184
1185 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1186 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1187 &headLocalPTS)) {
1188 buffer->raw = NULL;
1189 buffer->frameCount = 0;
1190 return INVALID_OPERATION;
1191 }
1192 } else {
1193 headLocalPTS = transformedPTS;
1194 }
1195 }
1196
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001197 uint32_t sr = sampleRate();
1198
Eric Laurent81784c32012-11-19 14:55:58 -08001199 // adjust the head buffer's PTS to reflect the portion of the head buffer
1200 // that has already been consumed
1201 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001202 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001203
1204 // Calculate the delta in samples between the head of the input buffer
1205 // queue and the start of the next output buffer that will be written.
1206 // If the transformation fails because of over or underflow, it means
1207 // that the sample's position in the output stream is so far out of
1208 // whack that it should just be dropped.
1209 int64_t sampleDelta;
1210 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1211 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1212 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1213 " mix");
1214 continue;
1215 }
1216 if (!mLocalTimeToSampleTransform.doForwardTransform(
1217 (effectivePTS - pts) << 32, &sampleDelta)) {
1218 ALOGV("*** too late during sample rate transform: dropped buffer");
1219 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1220 continue;
1221 }
1222
1223 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1224 " sampleDelta=[%d.%08x]",
1225 head.pts(), head.position(), pts,
1226 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1227 + (sampleDelta >> 32)),
1228 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1229
1230 // if the delta between the ideal placement for the next input sample and
1231 // the current output position is within this threshold, then we will
1232 // concatenate the next input samples to the previous output
1233 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001234 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001235
1236 // if this is the first buffer of audio that we're emitting from this track
1237 // then it should be almost exactly on time.
1238 const int64_t kSampleStartupThreshold = 1LL << 32;
1239
1240 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1241 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1242 // the next input is close enough to being on time, so concatenate it
1243 // with the last output
1244 timedYieldSamples_l(buffer);
1245
1246 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1247 head.position(), buffer->frameCount);
1248 return NO_ERROR;
1249 }
1250
1251 // Looks like our output is not on time. Reset our on timed status.
1252 // Next time we mix samples from our input queue, then should be within
1253 // the StartupThreshold.
1254 mTimedAudioOutputOnTime = false;
1255 if (sampleDelta > 0) {
1256 // the gap between the current output position and the proper start of
1257 // the next input sample is too big, so fill it with silence
1258 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1259
1260 timedYieldSilence_l(framesUntilNextInput, buffer);
1261 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1262 return NO_ERROR;
1263 } else {
1264 // the next input sample is late
1265 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1266 size_t onTimeSamplePosition =
1267 head.position() + lateFrames * mFrameSize;
1268
1269 if (onTimeSamplePosition > head.buffer()->size()) {
1270 // all the remaining samples in the head are too late, so
1271 // drop it and move on
1272 ALOGV("*** too late: dropped buffer");
1273 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1274 continue;
1275 } else {
1276 // skip over the late samples
1277 head.setPosition(onTimeSamplePosition);
1278
1279 // yield the available samples
1280 timedYieldSamples_l(buffer);
1281
1282 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1283 return NO_ERROR;
1284 }
1285 }
1286 }
1287}
1288
1289// Yield samples from the timed buffer queue head up to the given output
1290// buffer's capacity.
1291//
1292// Caller must hold mTimedBufferQueueLock
1293void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1294 AudioBufferProvider::Buffer* buffer) {
1295
1296 const TimedBuffer& head = mTimedBufferQueue[0];
1297
1298 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1299 head.position());
1300
1301 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1302 mFrameSize);
1303 size_t framesRequested = buffer->frameCount;
1304 buffer->frameCount = min(framesLeftInHead, framesRequested);
1305
1306 mQueueHeadInFlight = true;
1307 mTimedAudioOutputOnTime = true;
1308}
1309
1310// Yield samples of silence up to the given output buffer's capacity
1311//
1312// Caller must hold mTimedBufferQueueLock
1313void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1314 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1315
1316 // lazily allocate a buffer filled with silence
1317 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1318 delete [] mTimedSilenceBuffer;
1319 mTimedSilenceBufferSize = numFrames * mFrameSize;
1320 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1321 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1322 }
1323
1324 buffer->raw = mTimedSilenceBuffer;
1325 size_t framesRequested = buffer->frameCount;
1326 buffer->frameCount = min(numFrames, framesRequested);
1327
1328 mTimedAudioOutputOnTime = false;
1329}
1330
1331// AudioBufferProvider interface
1332void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1333 AudioBufferProvider::Buffer* buffer) {
1334
1335 Mutex::Autolock _l(mTimedBufferQueueLock);
1336
1337 // If the buffer which was just released is part of the buffer at the head
1338 // of the queue, be sure to update the amt of the buffer which has been
1339 // consumed. If the buffer being returned is not part of the head of the
1340 // queue, its either because the buffer is part of the silence buffer, or
1341 // because the head of the timed queue was trimmed after the mixer called
1342 // getNextBuffer but before the mixer called releaseBuffer.
1343 if (buffer->raw == mTimedSilenceBuffer) {
1344 ALOG_ASSERT(!mQueueHeadInFlight,
1345 "Queue head in flight during release of silence buffer!");
1346 goto done;
1347 }
1348
1349 ALOG_ASSERT(mQueueHeadInFlight,
1350 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1351 " head in flight.");
1352
1353 if (mTimedBufferQueue.size()) {
1354 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1355
1356 void* start = head.buffer()->pointer();
1357 void* end = reinterpret_cast<void*>(
1358 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1359 + head.buffer()->size());
1360
1361 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1362 "released buffer not within the head of the timed buffer"
1363 " queue; qHead = [%p, %p], released buffer = %p",
1364 start, end, buffer->raw);
1365
1366 head.setPosition(head.position() +
1367 (buffer->frameCount * mFrameSize));
1368 mQueueHeadInFlight = false;
1369
1370 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1371 "Bad bookkeeping during releaseBuffer! Should have at"
1372 " least %u queued frames, but we think we have only %u",
1373 buffer->frameCount, mFramesPendingInQueue);
1374
1375 mFramesPendingInQueue -= buffer->frameCount;
1376
1377 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1378 || mTrimQueueHeadOnRelease) {
1379 trimTimedBufferQueueHead_l("releaseBuffer");
1380 mTrimQueueHeadOnRelease = false;
1381 }
1382 } else {
1383 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1384 " buffers in the timed buffer queue");
1385 }
1386
1387done:
1388 buffer->raw = 0;
1389 buffer->frameCount = 0;
1390}
1391
1392size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1393 Mutex::Autolock _l(mTimedBufferQueueLock);
1394 return mFramesPendingInQueue;
1395}
1396
1397AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1398 : mPTS(0), mPosition(0) {}
1399
1400AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1401 const sp<IMemory>& buffer, int64_t pts)
1402 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1403
1404
1405// ----------------------------------------------------------------------------
1406
1407AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1408 PlaybackThread *playbackThread,
1409 DuplicatingThread *sourceThread,
1410 uint32_t sampleRate,
1411 audio_format_t format,
1412 audio_channel_mask_t channelMask,
1413 size_t frameCount)
1414 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1415 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001416 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001417{
1418
1419 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001420 mOutBuffer.frameCount = 0;
1421 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001422 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001423 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001424 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001425 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001426 // since client and server are in the same process,
1427 // the buffer has the same virtual address on both sides
1428 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001429 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1430 mClientProxy->setSendLevel(0.0);
1431 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001432 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1433 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001434 } else {
1435 ALOGW("Error creating output track on thread %p", playbackThread);
1436 }
1437}
1438
1439AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1440{
1441 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001442 delete mClientProxy;
1443 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001444}
1445
1446status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1447 int triggerSession)
1448{
1449 status_t status = Track::start(event, triggerSession);
1450 if (status != NO_ERROR) {
1451 return status;
1452 }
1453
1454 mActive = true;
1455 mRetryCount = 127;
1456 return status;
1457}
1458
1459void AudioFlinger::PlaybackThread::OutputTrack::stop()
1460{
1461 Track::stop();
1462 clearBufferQueue();
1463 mOutBuffer.frameCount = 0;
1464 mActive = false;
1465}
1466
1467bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1468{
1469 Buffer *pInBuffer;
1470 Buffer inBuffer;
1471 uint32_t channelCount = mChannelCount;
1472 bool outputBufferFull = false;
1473 inBuffer.frameCount = frames;
1474 inBuffer.i16 = data;
1475
1476 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1477
1478 if (!mActive && frames != 0) {
1479 start();
1480 sp<ThreadBase> thread = mThread.promote();
1481 if (thread != 0) {
1482 MixerThread *mixerThread = (MixerThread *)thread.get();
1483 if (mFrameCount > frames) {
1484 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1485 uint32_t startFrames = (mFrameCount - frames);
1486 pInBuffer = new Buffer;
1487 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1488 pInBuffer->frameCount = startFrames;
1489 pInBuffer->i16 = pInBuffer->mBuffer;
1490 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1491 mBufferQueue.add(pInBuffer);
1492 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001493 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001494 }
1495 }
1496 }
1497 }
1498
1499 while (waitTimeLeftMs) {
1500 // First write pending buffers, then new data
1501 if (mBufferQueue.size()) {
1502 pInBuffer = mBufferQueue.itemAt(0);
1503 } else {
1504 pInBuffer = &inBuffer;
1505 }
1506
1507 if (pInBuffer->frameCount == 0) {
1508 break;
1509 }
1510
1511 if (mOutBuffer.frameCount == 0) {
1512 mOutBuffer.frameCount = pInBuffer->frameCount;
1513 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001514 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1515 if (status != NO_ERROR) {
1516 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1517 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001518 outputBufferFull = true;
1519 break;
1520 }
1521 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1522 if (waitTimeLeftMs >= waitTimeMs) {
1523 waitTimeLeftMs -= waitTimeMs;
1524 } else {
1525 waitTimeLeftMs = 0;
1526 }
1527 }
1528
1529 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1530 pInBuffer->frameCount;
1531 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001532 Proxy::Buffer buf;
1533 buf.mFrameCount = outFrames;
1534 buf.mRaw = NULL;
1535 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001536 pInBuffer->frameCount -= outFrames;
1537 pInBuffer->i16 += outFrames * channelCount;
1538 mOutBuffer.frameCount -= outFrames;
1539 mOutBuffer.i16 += outFrames * channelCount;
1540
1541 if (pInBuffer->frameCount == 0) {
1542 if (mBufferQueue.size()) {
1543 mBufferQueue.removeAt(0);
1544 delete [] pInBuffer->mBuffer;
1545 delete pInBuffer;
1546 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1547 mThread.unsafe_get(), mBufferQueue.size());
1548 } else {
1549 break;
1550 }
1551 }
1552 }
1553
1554 // If we could not write all frames, allocate a buffer and queue it for next time.
1555 if (inBuffer.frameCount) {
1556 sp<ThreadBase> thread = mThread.promote();
1557 if (thread != 0 && !thread->standby()) {
1558 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1559 pInBuffer = new Buffer;
1560 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1561 pInBuffer->frameCount = inBuffer.frameCount;
1562 pInBuffer->i16 = pInBuffer->mBuffer;
1563 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1564 sizeof(int16_t));
1565 mBufferQueue.add(pInBuffer);
1566 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1567 mThread.unsafe_get(), mBufferQueue.size());
1568 } else {
1569 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1570 mThread.unsafe_get(), this);
1571 }
1572 }
1573 }
1574
1575 // Calling write() with a 0 length buffer, means that no more data will be written:
1576 // If no more buffers are pending, fill output track buffer to make sure it is started
1577 // by output mixer.
1578 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001579 // FIXME borken, replace by getting framesReady() from proxy
1580 size_t user = 0; // was mCblk->user
1581 if (user < mFrameCount) {
1582 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001583 pInBuffer = new Buffer;
1584 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1585 pInBuffer->frameCount = frames;
1586 pInBuffer->i16 = pInBuffer->mBuffer;
1587 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1588 mBufferQueue.add(pInBuffer);
1589 } else if (mActive) {
1590 stop();
1591 }
1592 }
1593
1594 return outputBufferFull;
1595}
1596
1597status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1598 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1599{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001600 ClientProxy::Buffer buf;
1601 buf.mFrameCount = buffer->frameCount;
1602 struct timespec timeout;
1603 timeout.tv_sec = waitTimeMs / 1000;
1604 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1605 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1606 buffer->frameCount = buf.mFrameCount;
1607 buffer->raw = buf.mRaw;
1608 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001609}
1610
Eric Laurent81784c32012-11-19 14:55:58 -08001611void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1612{
1613 size_t size = mBufferQueue.size();
1614
1615 for (size_t i = 0; i < size; i++) {
1616 Buffer *pBuffer = mBufferQueue.itemAt(i);
1617 delete [] pBuffer->mBuffer;
1618 delete pBuffer;
1619 }
1620 mBufferQueue.clear();
1621}
1622
1623
1624// ----------------------------------------------------------------------------
1625// Record
1626// ----------------------------------------------------------------------------
1627
1628AudioFlinger::RecordHandle::RecordHandle(
1629 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1630 : BnAudioRecord(),
1631 mRecordTrack(recordTrack)
1632{
1633}
1634
1635AudioFlinger::RecordHandle::~RecordHandle() {
1636 stop_nonvirtual();
1637 mRecordTrack->destroy();
1638}
1639
1640sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1641 return mRecordTrack->getCblk();
1642}
1643
1644status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1645 int triggerSession) {
1646 ALOGV("RecordHandle::start()");
1647 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1648}
1649
1650void AudioFlinger::RecordHandle::stop() {
1651 stop_nonvirtual();
1652}
1653
1654void AudioFlinger::RecordHandle::stop_nonvirtual() {
1655 ALOGV("RecordHandle::stop()");
1656 mRecordTrack->stop();
1657}
1658
1659status_t AudioFlinger::RecordHandle::onTransact(
1660 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1661{
1662 return BnAudioRecord::onTransact(code, data, reply, flags);
1663}
1664
1665// ----------------------------------------------------------------------------
1666
1667// RecordTrack constructor must be called with AudioFlinger::mLock held
1668AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1669 RecordThread *thread,
1670 const sp<Client>& client,
1671 uint32_t sampleRate,
1672 audio_format_t format,
1673 audio_channel_mask_t channelMask,
1674 size_t frameCount,
1675 int sessionId)
1676 : TrackBase(thread, client, sampleRate, format,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001677 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001678 mOverflow(false)
1679{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001680 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001681 if (mCblk != NULL) {
1682 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1683 mFrameSize);
1684 mServerProxy = mAudioRecordServerProxy;
1685 }
Eric Laurent81784c32012-11-19 14:55:58 -08001686}
1687
1688AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1689{
1690 ALOGV("%s", __func__);
1691}
1692
1693// AudioBufferProvider interface
1694status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1695 int64_t pts)
1696{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001697 ServerProxy::Buffer buf;
1698 buf.mFrameCount = buffer->frameCount;
1699 status_t status = mServerProxy->obtainBuffer(&buf);
1700 buffer->frameCount = buf.mFrameCount;
1701 buffer->raw = buf.mRaw;
1702 if (buf.mFrameCount == 0) {
1703 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001704 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001705 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001706 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001707}
1708
1709status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1710 int triggerSession)
1711{
1712 sp<ThreadBase> thread = mThread.promote();
1713 if (thread != 0) {
1714 RecordThread *recordThread = (RecordThread *)thread.get();
1715 return recordThread->start(this, event, triggerSession);
1716 } else {
1717 return BAD_VALUE;
1718 }
1719}
1720
1721void AudioFlinger::RecordThread::RecordTrack::stop()
1722{
1723 sp<ThreadBase> thread = mThread.promote();
1724 if (thread != 0) {
1725 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001726 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001727 AudioSystem::stopInput(recordThread->id());
1728 }
1729 }
1730}
1731
1732void AudioFlinger::RecordThread::RecordTrack::destroy()
1733{
1734 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1735 sp<RecordTrack> keep(this);
1736 {
1737 sp<ThreadBase> thread = mThread.promote();
1738 if (thread != 0) {
1739 if (mState == ACTIVE || mState == RESUMING) {
1740 AudioSystem::stopInput(thread->id());
1741 }
1742 AudioSystem::releaseInput(thread->id());
1743 Mutex::Autolock _l(thread->mLock);
1744 RecordThread *recordThread = (RecordThread *) thread.get();
1745 recordThread->destroyTrack_l(this);
1746 }
1747 }
1748}
1749
1750
1751/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1752{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001753 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001754}
1755
1756void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1757{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001758 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001759 (mClient == 0) ? getpid_cached : mClient->pid(),
1760 mFormat,
1761 mChannelMask,
1762 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001763 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001764 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001765 mFrameCount);
1766}
1767
Eric Laurent81784c32012-11-19 14:55:58 -08001768}; // namespace android