blob: 57aad1ed0e61e1eb09685eeb60b28406bf78304b [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");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700367
368 // The destructor would clear mSharedBuffer,
369 // but it will not push the decremented reference count,
370 // leaving the client's IMemory dangling indefinitely.
371 // This prevents that leak.
372 if (mSharedBuffer != 0) {
373 mSharedBuffer.clear();
374 // flush the binder command buffer
375 IPCThreadState::self()->flushCommands();
376 }
Eric Laurent81784c32012-11-19 14:55:58 -0800377}
378
379void AudioFlinger::PlaybackThread::Track::destroy()
380{
381 // NOTE: destroyTrack_l() can remove a strong reference to this Track
382 // by removing it from mTracks vector, so there is a risk that this Tracks's
383 // destructor is called. As the destructor needs to lock mLock,
384 // we must acquire a strong reference on this Track before locking mLock
385 // here so that the destructor is called only when exiting this function.
386 // On the other hand, as long as Track::destroy() is only called by
387 // TrackHandle destructor, the TrackHandle still holds a strong ref on
388 // this Track with its member mTrack.
389 sp<Track> keep(this);
390 { // scope for mLock
391 sp<ThreadBase> thread = mThread.promote();
392 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800393 Mutex::Autolock _l(thread->mLock);
394 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800395 bool wasActive = playbackThread->destroyTrack_l(this);
396 if (!isOutputTrack() && !wasActive) {
397 AudioSystem::releaseOutput(thread->id());
398 }
Eric Laurent81784c32012-11-19 14:55:58 -0800399 }
400 }
401}
402
403/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
404{
Eric Laurent972a1732013-09-04 09:42:59 -0700405 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700406 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800407}
408
409void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
410{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800411 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800412 if (isFastTrack()) {
413 sprintf(buffer, " F %2d", mFastIndex);
414 } else {
415 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
416 }
417 track_state state = mState;
418 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800419 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800420 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800421 } else {
422 switch (state) {
423 case IDLE:
424 stateChar = 'I';
425 break;
426 case STOPPING_1:
427 stateChar = 's';
428 break;
429 case STOPPING_2:
430 stateChar = '5';
431 break;
432 case STOPPED:
433 stateChar = 'S';
434 break;
435 case RESUMING:
436 stateChar = 'R';
437 break;
438 case ACTIVE:
439 stateChar = 'A';
440 break;
441 case PAUSING:
442 stateChar = 'p';
443 break;
444 case PAUSED:
445 stateChar = 'P';
446 break;
447 case FLUSHED:
448 stateChar = 'F';
449 break;
450 default:
451 stateChar = '?';
452 break;
453 }
Eric Laurent81784c32012-11-19 14:55:58 -0800454 }
455 char nowInUnderrun;
456 switch (mObservedUnderruns.mBitFields.mMostRecent) {
457 case UNDERRUN_FULL:
458 nowInUnderrun = ' ';
459 break;
460 case UNDERRUN_PARTIAL:
461 nowInUnderrun = '<';
462 break;
463 case UNDERRUN_EMPTY:
464 nowInUnderrun = '*';
465 break;
466 default:
467 nowInUnderrun = '?';
468 break;
469 }
Eric Laurent972a1732013-09-04 09:42:59 -0700470 snprintf(&buffer[7], size-7, " %6u %4u %08X %08X %7u %6u %1c %1d %5u %5.2g %5.2g "
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -0700471 "%08X %08X %08X 0x%03X %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800472 (mClient == 0) ? getpid_cached : mClient->pid(),
473 mStreamType,
474 mFormat,
475 mChannelMask,
476 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800477 mFrameCount,
478 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800479 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800480 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800481 20.0 * log10((vlr & 0xFFFF) / 4096.0),
482 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700483 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -0800484 (int)mMainBuffer,
485 (int)mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700486 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700487 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800488 nowInUnderrun);
489}
490
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800491uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
492 return mAudioTrackServerProxy->getSampleRate();
493}
494
Eric Laurent81784c32012-11-19 14:55:58 -0800495// AudioBufferProvider interface
496status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
497 AudioBufferProvider::Buffer* buffer, int64_t pts)
498{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800499 ServerProxy::Buffer buf;
500 size_t desiredFrames = buffer->frameCount;
501 buf.mFrameCount = desiredFrames;
502 status_t status = mServerProxy->obtainBuffer(&buf);
503 buffer->frameCount = buf.mFrameCount;
504 buffer->raw = buf.mRaw;
505 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700506 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800507 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800508 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800509}
510
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700511// releaseBuffer() is not overridden
512
513// ExtendedAudioBufferProvider interface
514
Eric Laurent81784c32012-11-19 14:55:58 -0800515// Note that framesReady() takes a mutex on the control block using tryLock().
516// This could result in priority inversion if framesReady() is called by the normal mixer,
517// as the normal mixer thread runs at lower
518// priority than the client's callback thread: there is a short window within framesReady()
519// during which the normal mixer could be preempted, and the client callback would block.
520// Another problem can occur if framesReady() is called by the fast mixer:
521// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
522// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
523size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800524 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800525}
526
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700527size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
528{
529 return mAudioTrackServerProxy->framesReleased();
530}
531
Eric Laurent81784c32012-11-19 14:55:58 -0800532// Don't call for fast tracks; the framesReady() could result in priority inversion
533bool AudioFlinger::PlaybackThread::Track::isReady() const {
534 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
535 return true;
536 }
537
538 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700539 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800540 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700541 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800542 return true;
543 }
544 return false;
545}
546
547status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
548 int triggerSession)
549{
550 status_t status = NO_ERROR;
551 ALOGV("start(%d), calling pid %d session %d",
552 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
553
554 sp<ThreadBase> thread = mThread.promote();
555 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700556 if (isOffloaded()) {
557 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
558 Mutex::Autolock _lth(thread->mLock);
559 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700560 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
561 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700562 invalidate();
563 return PERMISSION_DENIED;
564 }
565 }
566 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800567 track_state state = mState;
568 // here the track could be either new, or restarted
569 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800570
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800571 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800572 if (mResumeToStopping) {
573 // happened we need to resume to STOPPING_1
574 mState = TrackBase::STOPPING_1;
575 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
576 } else {
577 mState = TrackBase::RESUMING;
578 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
579 }
Eric Laurent81784c32012-11-19 14:55:58 -0800580 } else {
581 mState = TrackBase::ACTIVE;
582 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
583 }
584
Eric Laurentbfb1b832013-01-07 09:53:42 -0800585 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
586 status = playbackThread->addTrack_l(this);
587 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800588 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800589 // restore previous state if start was rejected by policy manager
590 if (status == PERMISSION_DENIED) {
591 mState = state;
592 }
593 }
594 // track was already in the active list, not a problem
595 if (status == ALREADY_EXISTS) {
596 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
598 } else {
599 status = BAD_VALUE;
600 }
601 return status;
602}
603
604void AudioFlinger::PlaybackThread::Track::stop()
605{
606 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
607 sp<ThreadBase> thread = mThread.promote();
608 if (thread != 0) {
609 Mutex::Autolock _l(thread->mLock);
610 track_state state = mState;
611 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
612 // If the track is not active (PAUSED and buffers full), flush buffers
613 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
614 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
615 reset();
616 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800617 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800618 mState = STOPPED;
619 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800620 // For fast tracks prepareTracks_l() will set state to STOPPING_2
621 // presentation is complete
622 // For an offloaded track this starts a drain and state will
623 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800624 mState = STOPPING_1;
625 }
626 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
627 playbackThread);
628 }
Eric Laurent81784c32012-11-19 14:55:58 -0800629 }
630}
631
632void AudioFlinger::PlaybackThread::Track::pause()
633{
634 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
635 sp<ThreadBase> thread = mThread.promote();
636 if (thread != 0) {
637 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800638 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
639 switch (mState) {
640 case STOPPING_1:
641 case STOPPING_2:
642 if (!isOffloaded()) {
643 /* nothing to do if track is not offloaded */
644 break;
645 }
646
647 // Offloaded track was draining, we need to carry on draining when resumed
648 mResumeToStopping = true;
649 // fall through...
650 case ACTIVE:
651 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800652 mState = PAUSING;
653 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -0800654 playbackThread->signal_l();
655 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800656
Eric Laurentbfb1b832013-01-07 09:53:42 -0800657 default:
658 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800659 }
660 }
661}
662
663void AudioFlinger::PlaybackThread::Track::flush()
664{
665 ALOGV("flush(%d)", mName);
666 sp<ThreadBase> thread = mThread.promote();
667 if (thread != 0) {
668 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800669 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800670
671 if (isOffloaded()) {
672 // If offloaded we allow flush during any state except terminated
673 // and keep the track active to avoid problems if user is seeking
674 // rapidly and underlying hardware has a significant delay handling
675 // a pause
676 if (isTerminated()) {
677 return;
678 }
679
680 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800681 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800682
683 if (mState == STOPPING_1 || mState == STOPPING_2) {
684 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
685 mState = ACTIVE;
686 }
687
688 if (mState == ACTIVE) {
689 ALOGV("flush called in active state, resetting buffer time out retry count");
690 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
691 }
692
693 mResumeToStopping = false;
694 } else {
695 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
696 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
697 return;
698 }
699 // No point remaining in PAUSED state after a flush => go to
700 // FLUSHED state
701 mState = FLUSHED;
702 // do not reset the track if it is still in the process of being stopped or paused.
703 // this will be done by prepareTracks_l() when the track is stopped.
704 // prepareTracks_l() will see mState == FLUSHED, then
705 // remove from active track list, reset(), and trigger presentation complete
706 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
707 reset();
708 }
Eric Laurent81784c32012-11-19 14:55:58 -0800709 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800710 // Prevent flush being lost if the track is flushed and then resumed
711 // before mixer thread can run. This is important when offloading
712 // because the hardware buffer could hold a large amount of audio
713 playbackThread->flushOutput_l();
714 playbackThread->signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800715 }
716}
717
718void AudioFlinger::PlaybackThread::Track::reset()
719{
720 // Do not reset twice to avoid discarding data written just after a flush and before
721 // the audioflinger thread detects the track is stopped.
722 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800723 // Force underrun condition to avoid false underrun callback until first data is
724 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700725 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800726 mFillingUpStatus = FS_FILLING;
727 mResetDone = true;
728 if (mState == FLUSHED) {
729 mState = IDLE;
730 }
731 }
732}
733
Eric Laurentbfb1b832013-01-07 09:53:42 -0800734status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
735{
736 sp<ThreadBase> thread = mThread.promote();
737 if (thread == 0) {
738 ALOGE("thread is dead");
739 return FAILED_TRANSACTION;
740 } else if ((thread->type() == ThreadBase::DIRECT) ||
741 (thread->type() == ThreadBase::OFFLOAD)) {
742 return thread->setParameters(keyValuePairs);
743 } else {
744 return PERMISSION_DENIED;
745 }
746}
747
Glenn Kasten573d80a2013-08-26 09:36:23 -0700748status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
749{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700750 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
751 if (isFastTrack()) {
752 return INVALID_OPERATION;
753 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700754 sp<ThreadBase> thread = mThread.promote();
755 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700756 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700757 }
758 Mutex::Autolock _l(thread->mLock);
759 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700760 if (!playbackThread->mLatchQValid) {
761 return INVALID_OPERATION;
762 }
763 uint32_t unpresentedFrames =
764 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
765 playbackThread->mSampleRate;
766 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
767 if (framesWritten < unpresentedFrames) {
768 return INVALID_OPERATION;
769 }
770 timestamp.mPosition = framesWritten - unpresentedFrames;
771 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
772 return NO_ERROR;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700773}
774
Eric Laurent81784c32012-11-19 14:55:58 -0800775status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
776{
777 status_t status = DEAD_OBJECT;
778 sp<ThreadBase> thread = mThread.promote();
779 if (thread != 0) {
780 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
781 sp<AudioFlinger> af = mClient->audioFlinger();
782
783 Mutex::Autolock _l(af->mLock);
784
785 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
786
787 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
788 Mutex::Autolock _dl(playbackThread->mLock);
789 Mutex::Autolock _sl(srcThread->mLock);
790 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
791 if (chain == 0) {
792 return INVALID_OPERATION;
793 }
794
795 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
796 if (effect == 0) {
797 return INVALID_OPERATION;
798 }
799 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700800 status = playbackThread->addEffect_l(effect);
801 if (status != NO_ERROR) {
802 srcThread->addEffect_l(effect);
803 return INVALID_OPERATION;
804 }
Eric Laurent81784c32012-11-19 14:55:58 -0800805 // removeEffect_l() has stopped the effect if it was active so it must be restarted
806 if (effect->state() == EffectModule::ACTIVE ||
807 effect->state() == EffectModule::STOPPING) {
808 effect->start();
809 }
810
811 sp<EffectChain> dstChain = effect->chain().promote();
812 if (dstChain == 0) {
813 srcThread->addEffect_l(effect);
814 return INVALID_OPERATION;
815 }
816 AudioSystem::unregisterEffect(effect->id());
817 AudioSystem::registerEffect(&effect->desc(),
818 srcThread->id(),
819 dstChain->strategy(),
820 AUDIO_SESSION_OUTPUT_MIX,
821 effect->id());
822 }
823 status = playbackThread->attachAuxEffect(this, EffectId);
824 }
825 return status;
826}
827
828void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
829{
830 mAuxEffectId = EffectId;
831 mAuxBuffer = buffer;
832}
833
834bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
835 size_t audioHalFrames)
836{
837 // a track is considered presented when the total number of frames written to audio HAL
838 // corresponds to the number of frames written when presentationComplete() is called for the
839 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800840 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
841 // to detect when all frames have been played. In this case framesWritten isn't
842 // useful because it doesn't always reflect whether there is data in the h/w
843 // buffers, particularly if a track has been paused and resumed during draining
844 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
845 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800846 if (mPresentationCompleteFrames == 0) {
847 mPresentationCompleteFrames = framesWritten + audioHalFrames;
848 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
849 mPresentationCompleteFrames, audioHalFrames);
850 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800851
852 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800853 ALOGV("presentationComplete() session %d complete: framesWritten %d",
854 mSessionId, framesWritten);
855 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800856 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800857 return true;
858 }
859 return false;
860}
861
862void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
863{
864 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
865 if (mSyncEvents[i]->type() == type) {
866 mSyncEvents[i]->trigger();
867 mSyncEvents.removeAt(i);
868 i--;
869 }
870 }
871}
872
873// implement VolumeBufferProvider interface
874
875uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
876{
877 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
878 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800879 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800880 uint32_t vl = vlr & 0xFFFF;
881 uint32_t vr = vlr >> 16;
882 // track volumes come from shared memory, so can't be trusted and must be clamped
883 if (vl > MAX_GAIN_INT) {
884 vl = MAX_GAIN_INT;
885 }
886 if (vr > MAX_GAIN_INT) {
887 vr = MAX_GAIN_INT;
888 }
889 // now apply the cached master volume and stream type volume;
890 // this is trusted but lacks any synchronization or barrier so may be stale
891 float v = mCachedVolume;
892 vl *= v;
893 vr *= v;
894 // re-combine into U4.16
895 vlr = (vr << 16) | (vl & 0xFFFF);
896 // FIXME look at mute, pause, and stop flags
897 return vlr;
898}
899
900status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
901{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800902 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800903 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
904 (mState == STOPPED)))) {
905 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
906 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
907 event->cancel();
908 return INVALID_OPERATION;
909 }
910 (void) TrackBase::setSyncEvent(event);
911 return NO_ERROR;
912}
913
Glenn Kasten5736c352012-12-04 12:12:34 -0800914void AudioFlinger::PlaybackThread::Track::invalidate()
915{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800916 // FIXME should use proxy, and needs work
917 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700918 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800919 android_atomic_release_store(0x40000000, &cblk->mFutex);
920 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
921 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800922 mIsInvalid = true;
923}
924
Eric Laurent81784c32012-11-19 14:55:58 -0800925// ----------------------------------------------------------------------------
926
927sp<AudioFlinger::PlaybackThread::TimedTrack>
928AudioFlinger::PlaybackThread::TimedTrack::create(
929 PlaybackThread *thread,
930 const sp<Client>& client,
931 audio_stream_type_t streamType,
932 uint32_t sampleRate,
933 audio_format_t format,
934 audio_channel_mask_t channelMask,
935 size_t frameCount,
936 const sp<IMemory>& sharedBuffer,
937 int sessionId) {
938 if (!client->reserveTimedTrack())
939 return 0;
940
941 return new TimedTrack(
942 thread, client, streamType, sampleRate, format, channelMask, frameCount,
943 sharedBuffer, sessionId);
944}
945
946AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
947 PlaybackThread *thread,
948 const sp<Client>& client,
949 audio_stream_type_t streamType,
950 uint32_t sampleRate,
951 audio_format_t format,
952 audio_channel_mask_t channelMask,
953 size_t frameCount,
954 const sp<IMemory>& sharedBuffer,
955 int sessionId)
956 : Track(thread, client, streamType, sampleRate, format, channelMask,
957 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
958 mQueueHeadInFlight(false),
959 mTrimQueueHeadOnRelease(false),
960 mFramesPendingInQueue(0),
961 mTimedSilenceBuffer(NULL),
962 mTimedSilenceBufferSize(0),
963 mTimedAudioOutputOnTime(false),
964 mMediaTimeTransformValid(false)
965{
966 LocalClock lc;
967 mLocalTimeFreq = lc.getLocalFreq();
968
969 mLocalTimeToSampleTransform.a_zero = 0;
970 mLocalTimeToSampleTransform.b_zero = 0;
971 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
972 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
973 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
974 &mLocalTimeToSampleTransform.a_to_b_denom);
975
976 mMediaTimeToSampleTransform.a_zero = 0;
977 mMediaTimeToSampleTransform.b_zero = 0;
978 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
979 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
980 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
981 &mMediaTimeToSampleTransform.a_to_b_denom);
982}
983
984AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
985 mClient->releaseTimedTrack();
986 delete [] mTimedSilenceBuffer;
987}
988
989status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
990 size_t size, sp<IMemory>* buffer) {
991
992 Mutex::Autolock _l(mTimedBufferQueueLock);
993
994 trimTimedBufferQueue_l();
995
996 // lazily initialize the shared memory heap for timed buffers
997 if (mTimedMemoryDealer == NULL) {
998 const int kTimedBufferHeapSize = 512 << 10;
999
1000 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1001 "AudioFlingerTimed");
1002 if (mTimedMemoryDealer == NULL)
1003 return NO_MEMORY;
1004 }
1005
1006 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
1007 if (newBuffer == NULL) {
1008 newBuffer = mTimedMemoryDealer->allocate(size);
1009 if (newBuffer == NULL)
1010 return NO_MEMORY;
1011 }
1012
1013 *buffer = newBuffer;
1014 return NO_ERROR;
1015}
1016
1017// caller must hold mTimedBufferQueueLock
1018void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1019 int64_t mediaTimeNow;
1020 {
1021 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1022 if (!mMediaTimeTransformValid)
1023 return;
1024
1025 int64_t targetTimeNow;
1026 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1027 ? mCCHelper.getCommonTime(&targetTimeNow)
1028 : mCCHelper.getLocalTime(&targetTimeNow);
1029
1030 if (OK != res)
1031 return;
1032
1033 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1034 &mediaTimeNow)) {
1035 return;
1036 }
1037 }
1038
1039 size_t trimEnd;
1040 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1041 int64_t bufEnd;
1042
1043 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1044 // We have a next buffer. Just use its PTS as the PTS of the frame
1045 // following the last frame in this buffer. If the stream is sparse
1046 // (ie, there are deliberate gaps left in the stream which should be
1047 // filled with silence by the TimedAudioTrack), then this can result
1048 // in one extra buffer being left un-trimmed when it could have
1049 // been. In general, this is not typical, and we would rather
1050 // optimized away the TS calculation below for the more common case
1051 // where PTSes are contiguous.
1052 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1053 } else {
1054 // We have no next buffer. Compute the PTS of the frame following
1055 // the last frame in this buffer by computing the duration of of
1056 // this frame in media time units and adding it to the PTS of the
1057 // buffer.
1058 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1059 / mFrameSize;
1060
1061 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1062 &bufEnd)) {
1063 ALOGE("Failed to convert frame count of %lld to media time"
1064 " duration" " (scale factor %d/%u) in %s",
1065 frameCount,
1066 mMediaTimeToSampleTransform.a_to_b_numer,
1067 mMediaTimeToSampleTransform.a_to_b_denom,
1068 __PRETTY_FUNCTION__);
1069 break;
1070 }
1071 bufEnd += mTimedBufferQueue[trimEnd].pts();
1072 }
1073
1074 if (bufEnd > mediaTimeNow)
1075 break;
1076
1077 // Is the buffer we want to use in the middle of a mix operation right
1078 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1079 // from the mixer which should be coming back shortly.
1080 if (!trimEnd && mQueueHeadInFlight) {
1081 mTrimQueueHeadOnRelease = true;
1082 }
1083 }
1084
1085 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1086 if (trimStart < trimEnd) {
1087 // Update the bookkeeping for framesReady()
1088 for (size_t i = trimStart; i < trimEnd; ++i) {
1089 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1090 }
1091
1092 // Now actually remove the buffers from the queue.
1093 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1094 }
1095}
1096
1097void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1098 const char* logTag) {
1099 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1100 "%s called (reason \"%s\"), but timed buffer queue has no"
1101 " elements to trim.", __FUNCTION__, logTag);
1102
1103 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1104 mTimedBufferQueue.removeAt(0);
1105}
1106
1107void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1108 const TimedBuffer& buf,
1109 const char* logTag) {
1110 uint32_t bufBytes = buf.buffer()->size();
1111 uint32_t consumedAlready = buf.position();
1112
1113 ALOG_ASSERT(consumedAlready <= bufBytes,
1114 "Bad bookkeeping while updating frames pending. Timed buffer is"
1115 " only %u bytes long, but claims to have consumed %u"
1116 " bytes. (update reason: \"%s\")",
1117 bufBytes, consumedAlready, logTag);
1118
1119 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1120 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1121 "Bad bookkeeping while updating frames pending. Should have at"
1122 " least %u queued frames, but we think we have only %u. (update"
1123 " reason: \"%s\")",
1124 bufFrames, mFramesPendingInQueue, logTag);
1125
1126 mFramesPendingInQueue -= bufFrames;
1127}
1128
1129status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1130 const sp<IMemory>& buffer, int64_t pts) {
1131
1132 {
1133 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1134 if (!mMediaTimeTransformValid)
1135 return INVALID_OPERATION;
1136 }
1137
1138 Mutex::Autolock _l(mTimedBufferQueueLock);
1139
1140 uint32_t bufFrames = buffer->size() / mFrameSize;
1141 mFramesPendingInQueue += bufFrames;
1142 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1143
1144 return NO_ERROR;
1145}
1146
1147status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1148 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1149
1150 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1151 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1152 target);
1153
1154 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1155 target == TimedAudioTrack::COMMON_TIME)) {
1156 return BAD_VALUE;
1157 }
1158
1159 Mutex::Autolock lock(mMediaTimeTransformLock);
1160 mMediaTimeTransform = xform;
1161 mMediaTimeTransformTarget = target;
1162 mMediaTimeTransformValid = true;
1163
1164 return NO_ERROR;
1165}
1166
1167#define min(a, b) ((a) < (b) ? (a) : (b))
1168
1169// implementation of getNextBuffer for tracks whose buffers have timestamps
1170status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1171 AudioBufferProvider::Buffer* buffer, int64_t pts)
1172{
1173 if (pts == AudioBufferProvider::kInvalidPTS) {
1174 buffer->raw = NULL;
1175 buffer->frameCount = 0;
1176 mTimedAudioOutputOnTime = false;
1177 return INVALID_OPERATION;
1178 }
1179
1180 Mutex::Autolock _l(mTimedBufferQueueLock);
1181
1182 ALOG_ASSERT(!mQueueHeadInFlight,
1183 "getNextBuffer called without releaseBuffer!");
1184
1185 while (true) {
1186
1187 // if we have no timed buffers, then fail
1188 if (mTimedBufferQueue.isEmpty()) {
1189 buffer->raw = NULL;
1190 buffer->frameCount = 0;
1191 return NOT_ENOUGH_DATA;
1192 }
1193
1194 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1195
1196 // calculate the PTS of the head of the timed buffer queue expressed in
1197 // local time
1198 int64_t headLocalPTS;
1199 {
1200 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1201
1202 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1203
1204 if (mMediaTimeTransform.a_to_b_denom == 0) {
1205 // the transform represents a pause, so yield silence
1206 timedYieldSilence_l(buffer->frameCount, buffer);
1207 return NO_ERROR;
1208 }
1209
1210 int64_t transformedPTS;
1211 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1212 &transformedPTS)) {
1213 // the transform failed. this shouldn't happen, but if it does
1214 // then just drop this buffer
1215 ALOGW("timedGetNextBuffer transform failed");
1216 buffer->raw = NULL;
1217 buffer->frameCount = 0;
1218 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1219 return NO_ERROR;
1220 }
1221
1222 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1223 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1224 &headLocalPTS)) {
1225 buffer->raw = NULL;
1226 buffer->frameCount = 0;
1227 return INVALID_OPERATION;
1228 }
1229 } else {
1230 headLocalPTS = transformedPTS;
1231 }
1232 }
1233
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001234 uint32_t sr = sampleRate();
1235
Eric Laurent81784c32012-11-19 14:55:58 -08001236 // adjust the head buffer's PTS to reflect the portion of the head buffer
1237 // that has already been consumed
1238 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001239 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001240
1241 // Calculate the delta in samples between the head of the input buffer
1242 // queue and the start of the next output buffer that will be written.
1243 // If the transformation fails because of over or underflow, it means
1244 // that the sample's position in the output stream is so far out of
1245 // whack that it should just be dropped.
1246 int64_t sampleDelta;
1247 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1248 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1249 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1250 " mix");
1251 continue;
1252 }
1253 if (!mLocalTimeToSampleTransform.doForwardTransform(
1254 (effectivePTS - pts) << 32, &sampleDelta)) {
1255 ALOGV("*** too late during sample rate transform: dropped buffer");
1256 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1257 continue;
1258 }
1259
1260 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1261 " sampleDelta=[%d.%08x]",
1262 head.pts(), head.position(), pts,
1263 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1264 + (sampleDelta >> 32)),
1265 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1266
1267 // if the delta between the ideal placement for the next input sample and
1268 // the current output position is within this threshold, then we will
1269 // concatenate the next input samples to the previous output
1270 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001271 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001272
1273 // if this is the first buffer of audio that we're emitting from this track
1274 // then it should be almost exactly on time.
1275 const int64_t kSampleStartupThreshold = 1LL << 32;
1276
1277 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1278 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1279 // the next input is close enough to being on time, so concatenate it
1280 // with the last output
1281 timedYieldSamples_l(buffer);
1282
1283 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1284 head.position(), buffer->frameCount);
1285 return NO_ERROR;
1286 }
1287
1288 // Looks like our output is not on time. Reset our on timed status.
1289 // Next time we mix samples from our input queue, then should be within
1290 // the StartupThreshold.
1291 mTimedAudioOutputOnTime = false;
1292 if (sampleDelta > 0) {
1293 // the gap between the current output position and the proper start of
1294 // the next input sample is too big, so fill it with silence
1295 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1296
1297 timedYieldSilence_l(framesUntilNextInput, buffer);
1298 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1299 return NO_ERROR;
1300 } else {
1301 // the next input sample is late
1302 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1303 size_t onTimeSamplePosition =
1304 head.position() + lateFrames * mFrameSize;
1305
1306 if (onTimeSamplePosition > head.buffer()->size()) {
1307 // all the remaining samples in the head are too late, so
1308 // drop it and move on
1309 ALOGV("*** too late: dropped buffer");
1310 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1311 continue;
1312 } else {
1313 // skip over the late samples
1314 head.setPosition(onTimeSamplePosition);
1315
1316 // yield the available samples
1317 timedYieldSamples_l(buffer);
1318
1319 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1320 return NO_ERROR;
1321 }
1322 }
1323 }
1324}
1325
1326// Yield samples from the timed buffer queue head up to the given output
1327// buffer's capacity.
1328//
1329// Caller must hold mTimedBufferQueueLock
1330void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1331 AudioBufferProvider::Buffer* buffer) {
1332
1333 const TimedBuffer& head = mTimedBufferQueue[0];
1334
1335 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1336 head.position());
1337
1338 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1339 mFrameSize);
1340 size_t framesRequested = buffer->frameCount;
1341 buffer->frameCount = min(framesLeftInHead, framesRequested);
1342
1343 mQueueHeadInFlight = true;
1344 mTimedAudioOutputOnTime = true;
1345}
1346
1347// Yield samples of silence up to the given output buffer's capacity
1348//
1349// Caller must hold mTimedBufferQueueLock
1350void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1351 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1352
1353 // lazily allocate a buffer filled with silence
1354 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1355 delete [] mTimedSilenceBuffer;
1356 mTimedSilenceBufferSize = numFrames * mFrameSize;
1357 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1358 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1359 }
1360
1361 buffer->raw = mTimedSilenceBuffer;
1362 size_t framesRequested = buffer->frameCount;
1363 buffer->frameCount = min(numFrames, framesRequested);
1364
1365 mTimedAudioOutputOnTime = false;
1366}
1367
1368// AudioBufferProvider interface
1369void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1370 AudioBufferProvider::Buffer* buffer) {
1371
1372 Mutex::Autolock _l(mTimedBufferQueueLock);
1373
1374 // If the buffer which was just released is part of the buffer at the head
1375 // of the queue, be sure to update the amt of the buffer which has been
1376 // consumed. If the buffer being returned is not part of the head of the
1377 // queue, its either because the buffer is part of the silence buffer, or
1378 // because the head of the timed queue was trimmed after the mixer called
1379 // getNextBuffer but before the mixer called releaseBuffer.
1380 if (buffer->raw == mTimedSilenceBuffer) {
1381 ALOG_ASSERT(!mQueueHeadInFlight,
1382 "Queue head in flight during release of silence buffer!");
1383 goto done;
1384 }
1385
1386 ALOG_ASSERT(mQueueHeadInFlight,
1387 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1388 " head in flight.");
1389
1390 if (mTimedBufferQueue.size()) {
1391 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1392
1393 void* start = head.buffer()->pointer();
1394 void* end = reinterpret_cast<void*>(
1395 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1396 + head.buffer()->size());
1397
1398 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1399 "released buffer not within the head of the timed buffer"
1400 " queue; qHead = [%p, %p], released buffer = %p",
1401 start, end, buffer->raw);
1402
1403 head.setPosition(head.position() +
1404 (buffer->frameCount * mFrameSize));
1405 mQueueHeadInFlight = false;
1406
1407 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1408 "Bad bookkeeping during releaseBuffer! Should have at"
1409 " least %u queued frames, but we think we have only %u",
1410 buffer->frameCount, mFramesPendingInQueue);
1411
1412 mFramesPendingInQueue -= buffer->frameCount;
1413
1414 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1415 || mTrimQueueHeadOnRelease) {
1416 trimTimedBufferQueueHead_l("releaseBuffer");
1417 mTrimQueueHeadOnRelease = false;
1418 }
1419 } else {
1420 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1421 " buffers in the timed buffer queue");
1422 }
1423
1424done:
1425 buffer->raw = 0;
1426 buffer->frameCount = 0;
1427}
1428
1429size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1430 Mutex::Autolock _l(mTimedBufferQueueLock);
1431 return mFramesPendingInQueue;
1432}
1433
1434AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1435 : mPTS(0), mPosition(0) {}
1436
1437AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1438 const sp<IMemory>& buffer, int64_t pts)
1439 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1440
1441
1442// ----------------------------------------------------------------------------
1443
1444AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1445 PlaybackThread *playbackThread,
1446 DuplicatingThread *sourceThread,
1447 uint32_t sampleRate,
1448 audio_format_t format,
1449 audio_channel_mask_t channelMask,
1450 size_t frameCount)
1451 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1452 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001453 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001454{
1455
1456 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001457 mOutBuffer.frameCount = 0;
1458 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001459 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001460 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001461 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001462 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001463 // since client and server are in the same process,
1464 // the buffer has the same virtual address on both sides
1465 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001466 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1467 mClientProxy->setSendLevel(0.0);
1468 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001469 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1470 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001471 } else {
1472 ALOGW("Error creating output track on thread %p", playbackThread);
1473 }
1474}
1475
1476AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1477{
1478 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001479 delete mClientProxy;
1480 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001481}
1482
1483status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1484 int triggerSession)
1485{
1486 status_t status = Track::start(event, triggerSession);
1487 if (status != NO_ERROR) {
1488 return status;
1489 }
1490
1491 mActive = true;
1492 mRetryCount = 127;
1493 return status;
1494}
1495
1496void AudioFlinger::PlaybackThread::OutputTrack::stop()
1497{
1498 Track::stop();
1499 clearBufferQueue();
1500 mOutBuffer.frameCount = 0;
1501 mActive = false;
1502}
1503
1504bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1505{
1506 Buffer *pInBuffer;
1507 Buffer inBuffer;
1508 uint32_t channelCount = mChannelCount;
1509 bool outputBufferFull = false;
1510 inBuffer.frameCount = frames;
1511 inBuffer.i16 = data;
1512
1513 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1514
1515 if (!mActive && frames != 0) {
1516 start();
1517 sp<ThreadBase> thread = mThread.promote();
1518 if (thread != 0) {
1519 MixerThread *mixerThread = (MixerThread *)thread.get();
1520 if (mFrameCount > frames) {
1521 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1522 uint32_t startFrames = (mFrameCount - frames);
1523 pInBuffer = new Buffer;
1524 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1525 pInBuffer->frameCount = startFrames;
1526 pInBuffer->i16 = pInBuffer->mBuffer;
1527 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1528 mBufferQueue.add(pInBuffer);
1529 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001530 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001531 }
1532 }
1533 }
1534 }
1535
1536 while (waitTimeLeftMs) {
1537 // First write pending buffers, then new data
1538 if (mBufferQueue.size()) {
1539 pInBuffer = mBufferQueue.itemAt(0);
1540 } else {
1541 pInBuffer = &inBuffer;
1542 }
1543
1544 if (pInBuffer->frameCount == 0) {
1545 break;
1546 }
1547
1548 if (mOutBuffer.frameCount == 0) {
1549 mOutBuffer.frameCount = pInBuffer->frameCount;
1550 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001551 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1552 if (status != NO_ERROR) {
1553 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1554 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001555 outputBufferFull = true;
1556 break;
1557 }
1558 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1559 if (waitTimeLeftMs >= waitTimeMs) {
1560 waitTimeLeftMs -= waitTimeMs;
1561 } else {
1562 waitTimeLeftMs = 0;
1563 }
1564 }
1565
1566 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1567 pInBuffer->frameCount;
1568 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001569 Proxy::Buffer buf;
1570 buf.mFrameCount = outFrames;
1571 buf.mRaw = NULL;
1572 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001573 pInBuffer->frameCount -= outFrames;
1574 pInBuffer->i16 += outFrames * channelCount;
1575 mOutBuffer.frameCount -= outFrames;
1576 mOutBuffer.i16 += outFrames * channelCount;
1577
1578 if (pInBuffer->frameCount == 0) {
1579 if (mBufferQueue.size()) {
1580 mBufferQueue.removeAt(0);
1581 delete [] pInBuffer->mBuffer;
1582 delete pInBuffer;
1583 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1584 mThread.unsafe_get(), mBufferQueue.size());
1585 } else {
1586 break;
1587 }
1588 }
1589 }
1590
1591 // If we could not write all frames, allocate a buffer and queue it for next time.
1592 if (inBuffer.frameCount) {
1593 sp<ThreadBase> thread = mThread.promote();
1594 if (thread != 0 && !thread->standby()) {
1595 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1596 pInBuffer = new Buffer;
1597 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1598 pInBuffer->frameCount = inBuffer.frameCount;
1599 pInBuffer->i16 = pInBuffer->mBuffer;
1600 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1601 sizeof(int16_t));
1602 mBufferQueue.add(pInBuffer);
1603 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1604 mThread.unsafe_get(), mBufferQueue.size());
1605 } else {
1606 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1607 mThread.unsafe_get(), this);
1608 }
1609 }
1610 }
1611
1612 // Calling write() with a 0 length buffer, means that no more data will be written:
1613 // If no more buffers are pending, fill output track buffer to make sure it is started
1614 // by output mixer.
1615 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001616 // FIXME borken, replace by getting framesReady() from proxy
1617 size_t user = 0; // was mCblk->user
1618 if (user < mFrameCount) {
1619 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001620 pInBuffer = new Buffer;
1621 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1622 pInBuffer->frameCount = frames;
1623 pInBuffer->i16 = pInBuffer->mBuffer;
1624 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1625 mBufferQueue.add(pInBuffer);
1626 } else if (mActive) {
1627 stop();
1628 }
1629 }
1630
1631 return outputBufferFull;
1632}
1633
1634status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1635 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1636{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001637 ClientProxy::Buffer buf;
1638 buf.mFrameCount = buffer->frameCount;
1639 struct timespec timeout;
1640 timeout.tv_sec = waitTimeMs / 1000;
1641 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1642 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1643 buffer->frameCount = buf.mFrameCount;
1644 buffer->raw = buf.mRaw;
1645 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001646}
1647
Eric Laurent81784c32012-11-19 14:55:58 -08001648void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1649{
1650 size_t size = mBufferQueue.size();
1651
1652 for (size_t i = 0; i < size; i++) {
1653 Buffer *pBuffer = mBufferQueue.itemAt(i);
1654 delete [] pBuffer->mBuffer;
1655 delete pBuffer;
1656 }
1657 mBufferQueue.clear();
1658}
1659
1660
1661// ----------------------------------------------------------------------------
1662// Record
1663// ----------------------------------------------------------------------------
1664
1665AudioFlinger::RecordHandle::RecordHandle(
1666 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1667 : BnAudioRecord(),
1668 mRecordTrack(recordTrack)
1669{
1670}
1671
1672AudioFlinger::RecordHandle::~RecordHandle() {
1673 stop_nonvirtual();
1674 mRecordTrack->destroy();
1675}
1676
1677sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1678 return mRecordTrack->getCblk();
1679}
1680
1681status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1682 int triggerSession) {
1683 ALOGV("RecordHandle::start()");
1684 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1685}
1686
1687void AudioFlinger::RecordHandle::stop() {
1688 stop_nonvirtual();
1689}
1690
1691void AudioFlinger::RecordHandle::stop_nonvirtual() {
1692 ALOGV("RecordHandle::stop()");
1693 mRecordTrack->stop();
1694}
1695
1696status_t AudioFlinger::RecordHandle::onTransact(
1697 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1698{
1699 return BnAudioRecord::onTransact(code, data, reply, flags);
1700}
1701
1702// ----------------------------------------------------------------------------
1703
1704// RecordTrack constructor must be called with AudioFlinger::mLock held
1705AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1706 RecordThread *thread,
1707 const sp<Client>& client,
1708 uint32_t sampleRate,
1709 audio_format_t format,
1710 audio_channel_mask_t channelMask,
1711 size_t frameCount,
1712 int sessionId)
1713 : TrackBase(thread, client, sampleRate, format,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001714 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001715 mOverflow(false)
1716{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001717 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001718 if (mCblk != NULL) {
1719 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1720 mFrameSize);
1721 mServerProxy = mAudioRecordServerProxy;
1722 }
Eric Laurent81784c32012-11-19 14:55:58 -08001723}
1724
1725AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1726{
1727 ALOGV("%s", __func__);
1728}
1729
1730// AudioBufferProvider interface
1731status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1732 int64_t pts)
1733{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001734 ServerProxy::Buffer buf;
1735 buf.mFrameCount = buffer->frameCount;
1736 status_t status = mServerProxy->obtainBuffer(&buf);
1737 buffer->frameCount = buf.mFrameCount;
1738 buffer->raw = buf.mRaw;
1739 if (buf.mFrameCount == 0) {
1740 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001741 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001742 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001743 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001744}
1745
1746status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1747 int triggerSession)
1748{
1749 sp<ThreadBase> thread = mThread.promote();
1750 if (thread != 0) {
1751 RecordThread *recordThread = (RecordThread *)thread.get();
1752 return recordThread->start(this, event, triggerSession);
1753 } else {
1754 return BAD_VALUE;
1755 }
1756}
1757
1758void AudioFlinger::RecordThread::RecordTrack::stop()
1759{
1760 sp<ThreadBase> thread = mThread.promote();
1761 if (thread != 0) {
1762 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001763 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001764 AudioSystem::stopInput(recordThread->id());
1765 }
1766 }
1767}
1768
1769void AudioFlinger::RecordThread::RecordTrack::destroy()
1770{
1771 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1772 sp<RecordTrack> keep(this);
1773 {
1774 sp<ThreadBase> thread = mThread.promote();
1775 if (thread != 0) {
1776 if (mState == ACTIVE || mState == RESUMING) {
1777 AudioSystem::stopInput(thread->id());
1778 }
1779 AudioSystem::releaseInput(thread->id());
1780 Mutex::Autolock _l(thread->mLock);
1781 RecordThread *recordThread = (RecordThread *) thread.get();
1782 recordThread->destroyTrack_l(this);
1783 }
1784 }
1785}
1786
Eric Laurent9a54bc22013-09-09 09:08:44 -07001787void AudioFlinger::RecordThread::RecordTrack::invalidate()
1788{
1789 // FIXME should use proxy, and needs work
1790 audio_track_cblk_t* cblk = mCblk;
1791 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1792 android_atomic_release_store(0x40000000, &cblk->mFutex);
1793 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1794 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1795}
1796
Eric Laurent81784c32012-11-19 14:55:58 -08001797
1798/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1799{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001800 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001801}
1802
1803void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1804{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001805 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001806 (mClient == 0) ? getpid_cached : mClient->pid(),
1807 mFormat,
1808 mChannelMask,
1809 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001810 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001811 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001812 mFrameCount);
1813}
1814
Eric Laurent81784c32012-11-19 14:55:58 -08001815}; // namespace android