blob: 436d4de61ed545f9a160b216190da17a74250e36 [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,
Alok Kediya601e9b52013-09-27 11:55:10 +053069 uint32_t flags,
Eric Laurent81784c32012-11-19 14:55:58 -080070 const sp<IMemory>& sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080071 int sessionId,
72 bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -080073 : RefBase(),
74 mThread(thread),
75 mClient(client),
76 mCblk(NULL),
77 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080078 mState(IDLE),
79 mSampleRate(sampleRate),
80 mFormat(format),
81 mChannelMask(channelMask),
82 mChannelCount(popcount(channelMask)),
Alok Kediya601e9b52013-09-27 11:55:10 +053083 mFrameSize((audio_is_linear_pcm(format) || audio_is_supported_compressed(format)) ?
84 ((flags & IAudioFlinger::TRACK_VOICE_COMMUNICATION)? mChannelCount * sizeof(int16_t) : mChannelCount * audio_bytes_per_sample(format)) : sizeof(int8_t)),
Eric Laurent81784c32012-11-19 14:55:58 -080085 mFrameCount(frameCount),
Alok Kediya601e9b52013-09-27 11:55:10 +053086 mFlags(0),
Glenn Kastene3aa6592012-12-04 12:22:46 -080087 mSessionId(sessionId),
88 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080089 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080090 mId(android_atomic_inc(&nextTrackId)),
91 mTerminated(false)
Eric Laurent81784c32012-11-19 14:55:58 -080092{
93 // client == 0 implies sharedBuffer == 0
94 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
95
96 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
97 sharedBuffer->size());
98
99 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
100 size_t size = sizeof(audio_track_cblk_t);
Alok Kediya601e9b52013-09-27 11:55:10 +0530101 uint8_t channelCount = popcount(channelMask);
102 size_t bufferSize = 0;
103 if (flags & IAudioFlinger::TRACK_VOICE_COMMUNICATION) {
104 bufferSize = roundup(frameCount) * channelCount * mFrameSize;
105 } else {
106 if ( (format == AUDIO_FORMAT_PCM_16_BIT) ||
107 (format == AUDIO_FORMAT_PCM_8_BIT)) {
108 bufferSize = frameCount * channelCount * sizeof(int16_t);
109 } else if (format == AUDIO_FORMAT_AMR_NB) {
110 bufferSize = frameCount * channelCount * AMR_FRAMESIZE; // full rate frame size
111 } else if (format == AUDIO_FORMAT_EVRC) {
112 bufferSize = frameCount * channelCount * EVRC_FRAMESIZE; // full rate frame size
113 } else if (format == AUDIO_FORMAT_QCELP) {
114 bufferSize = frameCount * channelCount * QCELP_FRAMESIZE; // full rate frame size
115 } else if (format == AUDIO_FORMAT_AAC) {
116 bufferSize = frameCount * AAC_FRAMESIZE; // full rate frame size
117 } else if (format == AUDIO_FORMAT_AMR_WB) {
118 bufferSize = frameCount * channelCount * AMR_WB_FRAMESIZE; // full rate frame size
119 }
120 }
121
Eric Laurent81784c32012-11-19 14:55:58 -0800122 if (sharedBuffer == 0) {
123 size += bufferSize;
124 }
125
126 if (client != 0) {
127 mCblkMemory = client->heap()->allocate(size);
128 if (mCblkMemory != 0) {
129 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
130 // can't assume mCblk != NULL
131 } else {
132 ALOGE("not enough memory for AudioTrack size=%u", size);
133 client->heap()->dump("AudioTrack");
134 return;
135 }
136 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800137 // this syntax avoids calling the audio_track_cblk_t constructor twice
138 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800139 // assume mCblk != NULL
140 }
141
142 // construct the shared structure in-place.
143 if (mCblk != NULL) {
144 new(mCblk) audio_track_cblk_t();
145 // clear all buffers
146 mCblk->frameCount_ = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800147 if (sharedBuffer == 0) {
148 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
Alok Kediya601e9b52013-09-27 11:55:10 +0530149 if (flags & IAudioFlinger::TRACK_VOICE_COMMUNICATION) {
150 memset(mBuffer, 0, bufferSize);
151 } else {
152 if ((format == AUDIO_FORMAT_PCM_16_BIT) ||
153 (format == AUDIO_FORMAT_PCM_8_BIT)) {
154 memset(mBuffer, 0, bufferSize);
155 } else if (format == AUDIO_FORMAT_AMR_NB) {
156 // full rate frame size
157 memset(mBuffer, 0, frameCount * channelCount * AMR_FRAMESIZE);
158 } else if (format == AUDIO_FORMAT_EVRC) {
159 // full rate frame size
160 memset(mBuffer, 0, frameCount * channelCount * EVRC_FRAMESIZE);
161 } else if (format == AUDIO_FORMAT_QCELP) {
162 // full rate frame size
163 memset(mBuffer, 0, frameCount * channelCount * QCELP_FRAMESIZE);
164 } else if (format == AUDIO_FORMAT_AAC) {
165 // full rate frame size
166 memset(mBuffer, 0, frameCount * AAC_FRAMESIZE);
167 } else if (format == AUDIO_FORMAT_AMR_WB) {
168 // full rate frame size
169 memset(mBuffer, 0, frameCount * channelCount * AMR_WB_FRAMESIZE);
170 }
171 }
Eric Laurent81784c32012-11-19 14:55:58 -0800172 } else {
173 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800174#if 0
Glenn Kasten96f60d82013-07-12 10:21:18 -0700175 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800176#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800177 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800178
Glenn Kasten46909e72013-02-26 09:20:22 -0800179#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800180 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800181 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
182 if (pipeFormat != Format_Invalid) {
183 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
184 size_t numCounterOffers = 0;
185 const NBAIO_Format offers[1] = {pipeFormat};
186 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
187 ALOG_ASSERT(index == 0);
188 PipeReader *pipeReader = new PipeReader(*pipe);
189 numCounterOffers = 0;
190 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
191 ALOG_ASSERT(index == 0);
192 mTeeSink = pipe;
193 mTeeSource = pipeReader;
194 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800195 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800196#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800197
Eric Laurent81784c32012-11-19 14:55:58 -0800198 }
199}
200
201AudioFlinger::ThreadBase::TrackBase::~TrackBase()
202{
Glenn Kasten46909e72013-02-26 09:20:22 -0800203#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800204 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800205#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800206 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
207 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800208 if (mCblk != NULL) {
209 if (mClient == 0) {
210 delete mCblk;
211 } else {
212 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
213 }
214 }
215 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
216 if (mClient != 0) {
217 // Client destructor must run with AudioFlinger mutex locked
218 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
219 // If the client's reference count drops to zero, the associated destructor
220 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
221 // relying on the automatic clear() at end of scope.
222 mClient.clear();
223 }
224}
225
226// AudioBufferProvider interface
227// getNextBuffer() = 0;
228// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
229void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
230{
Glenn Kasten46909e72013-02-26 09:20:22 -0800231#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800232 if (mTeeSink != 0) {
233 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
234 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800235#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800236
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800237 ServerProxy::Buffer buf;
238 buf.mFrameCount = buffer->frameCount;
239 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800240 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800241 buffer->raw = NULL;
242 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800243}
244
Eric Laurent81784c32012-11-19 14:55:58 -0800245status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
246{
247 mSyncEvents.add(event);
248 return NO_ERROR;
249}
250
251// ----------------------------------------------------------------------------
252// Playback
253// ----------------------------------------------------------------------------
254
255AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
256 : BnAudioTrack(),
257 mTrack(track)
258{
259}
260
261AudioFlinger::TrackHandle::~TrackHandle() {
262 // just stop the track on deletion, associated resources
263 // will be freed from the main thread once all pending buffers have
264 // been played. Unless it's not in the active track list, in which
265 // case we free everything now...
266 mTrack->destroy();
267}
268
269sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
270 return mTrack->getCblk();
271}
272
273status_t AudioFlinger::TrackHandle::start() {
274 return mTrack->start();
275}
276
277void AudioFlinger::TrackHandle::stop() {
278 mTrack->stop();
279}
280
281void AudioFlinger::TrackHandle::flush() {
282 mTrack->flush();
283}
284
Eric Laurent81784c32012-11-19 14:55:58 -0800285void AudioFlinger::TrackHandle::pause() {
286 mTrack->pause();
287}
288
289status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
290{
291 return mTrack->attachAuxEffect(EffectId);
292}
293
294status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
295 sp<IMemory>* buffer) {
296 if (!mTrack->isTimedTrack())
297 return INVALID_OPERATION;
298
299 PlaybackThread::TimedTrack* tt =
300 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
301 return tt->allocateTimedBuffer(size, buffer);
302}
303
304status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
305 int64_t pts) {
306 if (!mTrack->isTimedTrack())
307 return INVALID_OPERATION;
308
309 PlaybackThread::TimedTrack* tt =
310 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
311 return tt->queueTimedBuffer(buffer, pts);
312}
313
314status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
315 const LinearTransform& xform, int target) {
316
317 if (!mTrack->isTimedTrack())
318 return INVALID_OPERATION;
319
320 PlaybackThread::TimedTrack* tt =
321 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
322 return tt->setMediaTimeTransform(
323 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
324}
325
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700326status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
327 return mTrack->setParameters(keyValuePairs);
328}
329
Glenn Kasten53cec222013-08-29 09:01:02 -0700330status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
331{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700332 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700333}
334
Eric Laurent59fe0102013-09-27 18:48:26 -0700335
336void AudioFlinger::TrackHandle::signal()
337{
338 return mTrack->signal();
339}
340
Eric Laurent81784c32012-11-19 14:55:58 -0800341status_t AudioFlinger::TrackHandle::onTransact(
342 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
343{
344 return BnAudioTrack::onTransact(code, data, reply, flags);
345}
346
347// ----------------------------------------------------------------------------
348
349// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
350AudioFlinger::PlaybackThread::Track::Track(
351 PlaybackThread *thread,
352 const sp<Client>& client,
353 audio_stream_type_t streamType,
354 uint32_t sampleRate,
355 audio_format_t format,
356 audio_channel_mask_t channelMask,
357 size_t frameCount,
358 const sp<IMemory>& sharedBuffer,
359 int sessionId,
360 IAudioFlinger::track_flags_t flags)
Alok Kediya601e9b52013-09-27 11:55:10 +0530361 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
362 ((audio_stream_type_t)streamType == AUDIO_STREAM_VOICE_CALL)? IAudioFlinger::TRACK_VOICE_COMMUNICATION:0x0,
363 sharedBuffer, sessionId, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800364 mFillingUpStatus(FS_INVALID),
365 // mRetryCount initialized later when needed
366 mSharedBuffer(sharedBuffer),
367 mStreamType(streamType),
368 mName(-1), // see note below
369 mMainBuffer(thread->mixBuffer()),
370 mAuxBuffer(NULL),
371 mAuxEffectId(0), mHasVolumeController(false),
372 mPresentationCompleteFrames(0),
373 mFlags(flags),
374 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800375 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800376 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800377 mAudioTrackServerProxy(NULL),
378 mResumeToStopping(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800379{
380 if (mCblk != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800381 if (sharedBuffer == 0) {
382 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
383 mFrameSize);
384 } else {
385 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
386 mFrameSize);
387 }
388 mServerProxy = mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800389 // to avoid leaking a track name, do not allocate one unless there is an mCblk
390 mName = thread->getTrackName_l(channelMask, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800391 if (mName < 0) {
392 ALOGE("no more track names available");
393 return;
394 }
395 // only allocate a fast track index if we were able to allocate a normal track name
396 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800397 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Eric Laurent81784c32012-11-19 14:55:58 -0800398 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
399 int i = __builtin_ctz(thread->mFastTrackAvailMask);
400 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
401 // FIXME This is too eager. We allocate a fast track index before the
402 // fast track becomes active. Since fast tracks are a scarce resource,
403 // this means we are potentially denying other more important fast tracks from
404 // being created. It would be better to allocate the index dynamically.
405 mFastIndex = i;
Eric Laurent81784c32012-11-19 14:55:58 -0800406 // Read the initial underruns because this field is never cleared by the fast mixer
407 mObservedUnderruns = thread->getFastTrackUnderruns(i);
408 thread->mFastTrackAvailMask &= ~(1 << i);
409 }
410 }
411 ALOGV("Track constructor name %d, calling pid %d", mName,
412 IPCThreadState::self()->getCallingPid());
413}
414
415AudioFlinger::PlaybackThread::Track::~Track()
416{
417 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700418
419 // The destructor would clear mSharedBuffer,
420 // but it will not push the decremented reference count,
421 // leaving the client's IMemory dangling indefinitely.
422 // This prevents that leak.
423 if (mSharedBuffer != 0) {
424 mSharedBuffer.clear();
425 // flush the binder command buffer
426 IPCThreadState::self()->flushCommands();
427 }
Eric Laurent81784c32012-11-19 14:55:58 -0800428}
429
430void AudioFlinger::PlaybackThread::Track::destroy()
431{
432 // NOTE: destroyTrack_l() can remove a strong reference to this Track
433 // by removing it from mTracks vector, so there is a risk that this Tracks's
434 // destructor is called. As the destructor needs to lock mLock,
435 // we must acquire a strong reference on this Track before locking mLock
436 // here so that the destructor is called only when exiting this function.
437 // On the other hand, as long as Track::destroy() is only called by
438 // TrackHandle destructor, the TrackHandle still holds a strong ref on
439 // this Track with its member mTrack.
440 sp<Track> keep(this);
441 { // scope for mLock
442 sp<ThreadBase> thread = mThread.promote();
443 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800444 Mutex::Autolock _l(thread->mLock);
445 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800446 bool wasActive = playbackThread->destroyTrack_l(this);
447 if (!isOutputTrack() && !wasActive) {
448 AudioSystem::releaseOutput(thread->id());
449 }
Eric Laurent81784c32012-11-19 14:55:58 -0800450 }
451 }
452}
453
454/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
455{
Eric Laurent972a1732013-09-04 09:42:59 -0700456 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700457 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800458}
459
460void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
461{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800462 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800463 if (isFastTrack()) {
464 sprintf(buffer, " F %2d", mFastIndex);
465 } else {
466 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
467 }
468 track_state state = mState;
469 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800470 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800471 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800472 } else {
473 switch (state) {
474 case IDLE:
475 stateChar = 'I';
476 break;
477 case STOPPING_1:
478 stateChar = 's';
479 break;
480 case STOPPING_2:
481 stateChar = '5';
482 break;
483 case STOPPED:
484 stateChar = 'S';
485 break;
486 case RESUMING:
487 stateChar = 'R';
488 break;
489 case ACTIVE:
490 stateChar = 'A';
491 break;
492 case PAUSING:
493 stateChar = 'p';
494 break;
495 case PAUSED:
496 stateChar = 'P';
497 break;
498 case FLUSHED:
499 stateChar = 'F';
500 break;
501 default:
502 stateChar = '?';
503 break;
504 }
Eric Laurent81784c32012-11-19 14:55:58 -0800505 }
506 char nowInUnderrun;
507 switch (mObservedUnderruns.mBitFields.mMostRecent) {
508 case UNDERRUN_FULL:
509 nowInUnderrun = ' ';
510 break;
511 case UNDERRUN_PARTIAL:
512 nowInUnderrun = '<';
513 break;
514 case UNDERRUN_EMPTY:
515 nowInUnderrun = '*';
516 break;
517 default:
518 nowInUnderrun = '?';
519 break;
520 }
Eric Laurent972a1732013-09-04 09:42:59 -0700521 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 -0700522 "%08X %08X %08X 0x%03X %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800523 (mClient == 0) ? getpid_cached : mClient->pid(),
524 mStreamType,
525 mFormat,
526 mChannelMask,
527 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800528 mFrameCount,
529 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800530 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800531 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800532 20.0 * log10((vlr & 0xFFFF) / 4096.0),
533 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700534 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -0800535 (int)mMainBuffer,
536 (int)mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700537 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700538 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800539 nowInUnderrun);
540}
541
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800542uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
543 return mAudioTrackServerProxy->getSampleRate();
544}
545
Eric Laurent81784c32012-11-19 14:55:58 -0800546// AudioBufferProvider interface
547status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
548 AudioBufferProvider::Buffer* buffer, int64_t pts)
549{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800550 ServerProxy::Buffer buf;
551 size_t desiredFrames = buffer->frameCount;
552 buf.mFrameCount = desiredFrames;
553 status_t status = mServerProxy->obtainBuffer(&buf);
554 buffer->frameCount = buf.mFrameCount;
555 buffer->raw = buf.mRaw;
556 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700557 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800558 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800559 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800560}
561
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700562// releaseBuffer() is not overridden
563
564// ExtendedAudioBufferProvider interface
565
Eric Laurent81784c32012-11-19 14:55:58 -0800566// Note that framesReady() takes a mutex on the control block using tryLock().
567// This could result in priority inversion if framesReady() is called by the normal mixer,
568// as the normal mixer thread runs at lower
569// priority than the client's callback thread: there is a short window within framesReady()
570// during which the normal mixer could be preempted, and the client callback would block.
571// Another problem can occur if framesReady() is called by the fast mixer:
572// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
573// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
574size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800575 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800576}
577
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700578size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
579{
580 return mAudioTrackServerProxy->framesReleased();
581}
582
Eric Laurent81784c32012-11-19 14:55:58 -0800583// Don't call for fast tracks; the framesReady() could result in priority inversion
584bool AudioFlinger::PlaybackThread::Track::isReady() const {
585 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
586 return true;
587 }
588
589 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700590 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800591 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700592 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800593 return true;
594 }
595 return false;
596}
597
598status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
599 int triggerSession)
600{
601 status_t status = NO_ERROR;
602 ALOGV("start(%d), calling pid %d session %d",
603 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
604
605 sp<ThreadBase> thread = mThread.promote();
606 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700607 if (isOffloaded()) {
608 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
609 Mutex::Autolock _lth(thread->mLock);
610 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700611 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
612 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700613 invalidate();
614 return PERMISSION_DENIED;
615 }
616 }
617 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800618 track_state state = mState;
619 // here the track could be either new, or restarted
620 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800621
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800622 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800623 if (mResumeToStopping) {
624 // happened we need to resume to STOPPING_1
625 mState = TrackBase::STOPPING_1;
626 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
627 } else {
628 mState = TrackBase::RESUMING;
629 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
630 }
Eric Laurent81784c32012-11-19 14:55:58 -0800631 } else {
632 mState = TrackBase::ACTIVE;
633 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
634 }
635
Eric Laurentbfb1b832013-01-07 09:53:42 -0800636 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
637 status = playbackThread->addTrack_l(this);
638 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800639 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800640 // restore previous state if start was rejected by policy manager
641 if (status == PERMISSION_DENIED) {
642 mState = state;
643 }
644 }
645 // track was already in the active list, not a problem
646 if (status == ALREADY_EXISTS) {
647 status = NO_ERROR;
Glenn Kasten4ce5dd92013-10-17 11:32:39 -0700648 } else {
649 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
650 // It is usually unsafe to access the server proxy from a binder thread.
651 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
652 // isn't looking at this track yet: we still hold the normal mixer thread lock,
653 // and for fast tracks the track is not yet in the fast mixer thread's active set.
654 ServerProxy::Buffer buffer;
655 buffer.mFrameCount = 1;
Glenn Kastena6f2c7b2013-10-18 13:00:29 -0700656 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800657 }
658 } else {
659 status = BAD_VALUE;
660 }
661 return status;
662}
663
664void AudioFlinger::PlaybackThread::Track::stop()
665{
666 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
667 sp<ThreadBase> thread = mThread.promote();
668 if (thread != 0) {
669 Mutex::Autolock _l(thread->mLock);
670 track_state state = mState;
671 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
672 // If the track is not active (PAUSED and buffers full), flush buffers
673 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
674 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
675 reset();
676 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800677 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800678 mState = STOPPED;
679 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800680 // For fast tracks prepareTracks_l() will set state to STOPPING_2
681 // presentation is complete
682 // For an offloaded track this starts a drain and state will
683 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800684 mState = STOPPING_1;
685 }
686 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
687 playbackThread);
688 }
Eric Laurent81784c32012-11-19 14:55:58 -0800689 }
690}
691
692void AudioFlinger::PlaybackThread::Track::pause()
693{
694 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
695 sp<ThreadBase> thread = mThread.promote();
696 if (thread != 0) {
697 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800698 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
699 switch (mState) {
700 case STOPPING_1:
701 case STOPPING_2:
702 if (!isOffloaded()) {
703 /* nothing to do if track is not offloaded */
704 break;
705 }
706
707 // Offloaded track was draining, we need to carry on draining when resumed
708 mResumeToStopping = true;
709 // fall through...
710 case ACTIVE:
711 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800712 mState = PAUSING;
713 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700714 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800715 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800716
Eric Laurentbfb1b832013-01-07 09:53:42 -0800717 default:
718 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800719 }
720 }
721}
722
723void AudioFlinger::PlaybackThread::Track::flush()
724{
725 ALOGV("flush(%d)", mName);
726 sp<ThreadBase> thread = mThread.promote();
727 if (thread != 0) {
728 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800729 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800730
731 if (isOffloaded()) {
732 // If offloaded we allow flush during any state except terminated
733 // and keep the track active to avoid problems if user is seeking
734 // rapidly and underlying hardware has a significant delay handling
735 // a pause
736 if (isTerminated()) {
737 return;
738 }
739
740 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800741 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800742
743 if (mState == STOPPING_1 || mState == STOPPING_2) {
744 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
745 mState = ACTIVE;
746 }
747
748 if (mState == ACTIVE) {
749 ALOGV("flush called in active state, resetting buffer time out retry count");
750 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
751 }
752
753 mResumeToStopping = false;
754 } else {
755 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
756 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
757 return;
758 }
759 // No point remaining in PAUSED state after a flush => go to
760 // FLUSHED state
761 mState = FLUSHED;
762 // do not reset the track if it is still in the process of being stopped or paused.
763 // this will be done by prepareTracks_l() when the track is stopped.
764 // prepareTracks_l() will see mState == FLUSHED, then
765 // remove from active track list, reset(), and trigger presentation complete
766 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
767 reset();
768 }
Eric Laurent81784c32012-11-19 14:55:58 -0800769 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800770 // Prevent flush being lost if the track is flushed and then resumed
771 // before mixer thread can run. This is important when offloading
772 // because the hardware buffer could hold a large amount of audio
773 playbackThread->flushOutput_l();
Eric Laurentede6c3b2013-09-19 14:37:46 -0700774 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800775 }
776}
777
778void AudioFlinger::PlaybackThread::Track::reset()
779{
780 // Do not reset twice to avoid discarding data written just after a flush and before
781 // the audioflinger thread detects the track is stopped.
782 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800783 // Force underrun condition to avoid false underrun callback until first data is
784 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700785 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800786 mFillingUpStatus = FS_FILLING;
787 mResetDone = true;
788 if (mState == FLUSHED) {
789 mState = IDLE;
790 }
791 }
792}
793
Eric Laurentbfb1b832013-01-07 09:53:42 -0800794status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
795{
796 sp<ThreadBase> thread = mThread.promote();
797 if (thread == 0) {
798 ALOGE("thread is dead");
799 return FAILED_TRANSACTION;
800 } else if ((thread->type() == ThreadBase::DIRECT) ||
801 (thread->type() == ThreadBase::OFFLOAD)) {
802 return thread->setParameters(keyValuePairs);
803 } else {
804 return PERMISSION_DENIED;
805 }
806}
807
Glenn Kasten573d80a2013-08-26 09:36:23 -0700808status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
809{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700810 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
811 if (isFastTrack()) {
812 return INVALID_OPERATION;
813 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700814 sp<ThreadBase> thread = mThread.promote();
815 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700816 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700817 }
818 Mutex::Autolock _l(thread->mLock);
819 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700820 if (!isOffloaded()) {
821 if (!playbackThread->mLatchQValid) {
822 return INVALID_OPERATION;
823 }
824 uint32_t unpresentedFrames =
825 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
826 playbackThread->mSampleRate;
827 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
828 if (framesWritten < unpresentedFrames) {
829 return INVALID_OPERATION;
830 }
831 timestamp.mPosition = framesWritten - unpresentedFrames;
832 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
833 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700834 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700835
836 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700837}
838
Eric Laurent81784c32012-11-19 14:55:58 -0800839status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
840{
841 status_t status = DEAD_OBJECT;
842 sp<ThreadBase> thread = mThread.promote();
843 if (thread != 0) {
844 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
845 sp<AudioFlinger> af = mClient->audioFlinger();
846
847 Mutex::Autolock _l(af->mLock);
848
849 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
850
851 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
852 Mutex::Autolock _dl(playbackThread->mLock);
853 Mutex::Autolock _sl(srcThread->mLock);
854 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
855 if (chain == 0) {
856 return INVALID_OPERATION;
857 }
858
859 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
860 if (effect == 0) {
861 return INVALID_OPERATION;
862 }
863 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700864 status = playbackThread->addEffect_l(effect);
865 if (status != NO_ERROR) {
866 srcThread->addEffect_l(effect);
867 return INVALID_OPERATION;
868 }
Eric Laurent81784c32012-11-19 14:55:58 -0800869 // removeEffect_l() has stopped the effect if it was active so it must be restarted
870 if (effect->state() == EffectModule::ACTIVE ||
871 effect->state() == EffectModule::STOPPING) {
872 effect->start();
873 }
874
875 sp<EffectChain> dstChain = effect->chain().promote();
876 if (dstChain == 0) {
877 srcThread->addEffect_l(effect);
878 return INVALID_OPERATION;
879 }
880 AudioSystem::unregisterEffect(effect->id());
881 AudioSystem::registerEffect(&effect->desc(),
882 srcThread->id(),
883 dstChain->strategy(),
884 AUDIO_SESSION_OUTPUT_MIX,
885 effect->id());
886 }
887 status = playbackThread->attachAuxEffect(this, EffectId);
888 }
889 return status;
890}
891
892void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
893{
894 mAuxEffectId = EffectId;
895 mAuxBuffer = buffer;
896}
897
898bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
899 size_t audioHalFrames)
900{
901 // a track is considered presented when the total number of frames written to audio HAL
902 // corresponds to the number of frames written when presentationComplete() is called for the
903 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800904 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
905 // to detect when all frames have been played. In this case framesWritten isn't
906 // useful because it doesn't always reflect whether there is data in the h/w
907 // buffers, particularly if a track has been paused and resumed during draining
908 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
909 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 if (mPresentationCompleteFrames == 0) {
911 mPresentationCompleteFrames = framesWritten + audioHalFrames;
912 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
913 mPresentationCompleteFrames, audioHalFrames);
914 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800915
916 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800917 ALOGV("presentationComplete() session %d complete: framesWritten %d",
918 mSessionId, framesWritten);
919 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800920 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800921 return true;
922 }
923 return false;
924}
925
926void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
927{
928 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
929 if (mSyncEvents[i]->type() == type) {
930 mSyncEvents[i]->trigger();
931 mSyncEvents.removeAt(i);
932 i--;
933 }
934 }
935}
936
937// implement VolumeBufferProvider interface
938
939uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
940{
941 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
942 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800943 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800944 uint32_t vl = vlr & 0xFFFF;
945 uint32_t vr = vlr >> 16;
946 // track volumes come from shared memory, so can't be trusted and must be clamped
947 if (vl > MAX_GAIN_INT) {
948 vl = MAX_GAIN_INT;
949 }
950 if (vr > MAX_GAIN_INT) {
951 vr = MAX_GAIN_INT;
952 }
953 // now apply the cached master volume and stream type volume;
954 // this is trusted but lacks any synchronization or barrier so may be stale
955 float v = mCachedVolume;
956 vl *= v;
957 vr *= v;
958 // re-combine into U4.16
959 vlr = (vr << 16) | (vl & 0xFFFF);
960 // FIXME look at mute, pause, and stop flags
961 return vlr;
962}
963
964status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
965{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800966 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800967 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
968 (mState == STOPPED)))) {
969 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
970 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
971 event->cancel();
972 return INVALID_OPERATION;
973 }
974 (void) TrackBase::setSyncEvent(event);
975 return NO_ERROR;
976}
977
Glenn Kasten5736c352012-12-04 12:12:34 -0800978void AudioFlinger::PlaybackThread::Track::invalidate()
979{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800980 // FIXME should use proxy, and needs work
981 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700982 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800983 android_atomic_release_store(0x40000000, &cblk->mFutex);
984 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
985 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800986 mIsInvalid = true;
987}
988
Eric Laurent59fe0102013-09-27 18:48:26 -0700989void AudioFlinger::PlaybackThread::Track::signal()
990{
991 sp<ThreadBase> thread = mThread.promote();
992 if (thread != 0) {
993 PlaybackThread *t = (PlaybackThread *)thread.get();
994 Mutex::Autolock _l(t->mLock);
995 t->broadcast_l();
996 }
997}
998
Eric Laurent81784c32012-11-19 14:55:58 -0800999// ----------------------------------------------------------------------------
1000
1001sp<AudioFlinger::PlaybackThread::TimedTrack>
1002AudioFlinger::PlaybackThread::TimedTrack::create(
1003 PlaybackThread *thread,
1004 const sp<Client>& client,
1005 audio_stream_type_t streamType,
1006 uint32_t sampleRate,
1007 audio_format_t format,
1008 audio_channel_mask_t channelMask,
1009 size_t frameCount,
1010 const sp<IMemory>& sharedBuffer,
1011 int sessionId) {
1012 if (!client->reserveTimedTrack())
1013 return 0;
1014
1015 return new TimedTrack(
1016 thread, client, streamType, sampleRate, format, channelMask, frameCount,
1017 sharedBuffer, sessionId);
1018}
1019
1020AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1021 PlaybackThread *thread,
1022 const sp<Client>& client,
1023 audio_stream_type_t streamType,
1024 uint32_t sampleRate,
1025 audio_format_t format,
1026 audio_channel_mask_t channelMask,
1027 size_t frameCount,
1028 const sp<IMemory>& sharedBuffer,
1029 int sessionId)
1030 : Track(thread, client, streamType, sampleRate, format, channelMask,
1031 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
1032 mQueueHeadInFlight(false),
1033 mTrimQueueHeadOnRelease(false),
1034 mFramesPendingInQueue(0),
1035 mTimedSilenceBuffer(NULL),
1036 mTimedSilenceBufferSize(0),
1037 mTimedAudioOutputOnTime(false),
1038 mMediaTimeTransformValid(false)
1039{
1040 LocalClock lc;
1041 mLocalTimeFreq = lc.getLocalFreq();
1042
1043 mLocalTimeToSampleTransform.a_zero = 0;
1044 mLocalTimeToSampleTransform.b_zero = 0;
1045 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1046 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1047 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1048 &mLocalTimeToSampleTransform.a_to_b_denom);
1049
1050 mMediaTimeToSampleTransform.a_zero = 0;
1051 mMediaTimeToSampleTransform.b_zero = 0;
1052 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1053 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1054 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1055 &mMediaTimeToSampleTransform.a_to_b_denom);
1056}
1057
1058AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1059 mClient->releaseTimedTrack();
1060 delete [] mTimedSilenceBuffer;
1061}
1062
1063status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1064 size_t size, sp<IMemory>* buffer) {
1065
1066 Mutex::Autolock _l(mTimedBufferQueueLock);
1067
1068 trimTimedBufferQueue_l();
1069
1070 // lazily initialize the shared memory heap for timed buffers
1071 if (mTimedMemoryDealer == NULL) {
1072 const int kTimedBufferHeapSize = 512 << 10;
1073
1074 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1075 "AudioFlingerTimed");
1076 if (mTimedMemoryDealer == NULL)
1077 return NO_MEMORY;
1078 }
1079
1080 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
1081 if (newBuffer == NULL) {
1082 newBuffer = mTimedMemoryDealer->allocate(size);
1083 if (newBuffer == NULL)
1084 return NO_MEMORY;
1085 }
1086
1087 *buffer = newBuffer;
1088 return NO_ERROR;
1089}
1090
1091// caller must hold mTimedBufferQueueLock
1092void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1093 int64_t mediaTimeNow;
1094 {
1095 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1096 if (!mMediaTimeTransformValid)
1097 return;
1098
1099 int64_t targetTimeNow;
1100 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1101 ? mCCHelper.getCommonTime(&targetTimeNow)
1102 : mCCHelper.getLocalTime(&targetTimeNow);
1103
1104 if (OK != res)
1105 return;
1106
1107 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1108 &mediaTimeNow)) {
1109 return;
1110 }
1111 }
1112
1113 size_t trimEnd;
1114 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1115 int64_t bufEnd;
1116
1117 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1118 // We have a next buffer. Just use its PTS as the PTS of the frame
1119 // following the last frame in this buffer. If the stream is sparse
1120 // (ie, there are deliberate gaps left in the stream which should be
1121 // filled with silence by the TimedAudioTrack), then this can result
1122 // in one extra buffer being left un-trimmed when it could have
1123 // been. In general, this is not typical, and we would rather
1124 // optimized away the TS calculation below for the more common case
1125 // where PTSes are contiguous.
1126 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1127 } else {
1128 // We have no next buffer. Compute the PTS of the frame following
1129 // the last frame in this buffer by computing the duration of of
1130 // this frame in media time units and adding it to the PTS of the
1131 // buffer.
1132 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1133 / mFrameSize;
1134
1135 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1136 &bufEnd)) {
1137 ALOGE("Failed to convert frame count of %lld to media time"
1138 " duration" " (scale factor %d/%u) in %s",
1139 frameCount,
1140 mMediaTimeToSampleTransform.a_to_b_numer,
1141 mMediaTimeToSampleTransform.a_to_b_denom,
1142 __PRETTY_FUNCTION__);
1143 break;
1144 }
1145 bufEnd += mTimedBufferQueue[trimEnd].pts();
1146 }
1147
1148 if (bufEnd > mediaTimeNow)
1149 break;
1150
1151 // Is the buffer we want to use in the middle of a mix operation right
1152 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1153 // from the mixer which should be coming back shortly.
1154 if (!trimEnd && mQueueHeadInFlight) {
1155 mTrimQueueHeadOnRelease = true;
1156 }
1157 }
1158
1159 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1160 if (trimStart < trimEnd) {
1161 // Update the bookkeeping for framesReady()
1162 for (size_t i = trimStart; i < trimEnd; ++i) {
1163 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1164 }
1165
1166 // Now actually remove the buffers from the queue.
1167 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1168 }
1169}
1170
1171void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1172 const char* logTag) {
1173 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1174 "%s called (reason \"%s\"), but timed buffer queue has no"
1175 " elements to trim.", __FUNCTION__, logTag);
1176
1177 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1178 mTimedBufferQueue.removeAt(0);
1179}
1180
1181void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1182 const TimedBuffer& buf,
1183 const char* logTag) {
1184 uint32_t bufBytes = buf.buffer()->size();
1185 uint32_t consumedAlready = buf.position();
1186
1187 ALOG_ASSERT(consumedAlready <= bufBytes,
1188 "Bad bookkeeping while updating frames pending. Timed buffer is"
1189 " only %u bytes long, but claims to have consumed %u"
1190 " bytes. (update reason: \"%s\")",
1191 bufBytes, consumedAlready, logTag);
1192
1193 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1194 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1195 "Bad bookkeeping while updating frames pending. Should have at"
1196 " least %u queued frames, but we think we have only %u. (update"
1197 " reason: \"%s\")",
1198 bufFrames, mFramesPendingInQueue, logTag);
1199
1200 mFramesPendingInQueue -= bufFrames;
1201}
1202
1203status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1204 const sp<IMemory>& buffer, int64_t pts) {
1205
1206 {
1207 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1208 if (!mMediaTimeTransformValid)
1209 return INVALID_OPERATION;
1210 }
1211
1212 Mutex::Autolock _l(mTimedBufferQueueLock);
1213
1214 uint32_t bufFrames = buffer->size() / mFrameSize;
1215 mFramesPendingInQueue += bufFrames;
1216 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1217
1218 return NO_ERROR;
1219}
1220
1221status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1222 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1223
1224 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1225 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1226 target);
1227
1228 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1229 target == TimedAudioTrack::COMMON_TIME)) {
1230 return BAD_VALUE;
1231 }
1232
1233 Mutex::Autolock lock(mMediaTimeTransformLock);
1234 mMediaTimeTransform = xform;
1235 mMediaTimeTransformTarget = target;
1236 mMediaTimeTransformValid = true;
1237
1238 return NO_ERROR;
1239}
1240
1241#define min(a, b) ((a) < (b) ? (a) : (b))
1242
1243// implementation of getNextBuffer for tracks whose buffers have timestamps
1244status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1245 AudioBufferProvider::Buffer* buffer, int64_t pts)
1246{
1247 if (pts == AudioBufferProvider::kInvalidPTS) {
1248 buffer->raw = NULL;
1249 buffer->frameCount = 0;
1250 mTimedAudioOutputOnTime = false;
1251 return INVALID_OPERATION;
1252 }
1253
1254 Mutex::Autolock _l(mTimedBufferQueueLock);
1255
1256 ALOG_ASSERT(!mQueueHeadInFlight,
1257 "getNextBuffer called without releaseBuffer!");
1258
1259 while (true) {
1260
1261 // if we have no timed buffers, then fail
1262 if (mTimedBufferQueue.isEmpty()) {
1263 buffer->raw = NULL;
1264 buffer->frameCount = 0;
1265 return NOT_ENOUGH_DATA;
1266 }
1267
1268 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1269
1270 // calculate the PTS of the head of the timed buffer queue expressed in
1271 // local time
1272 int64_t headLocalPTS;
1273 {
1274 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1275
1276 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1277
1278 if (mMediaTimeTransform.a_to_b_denom == 0) {
1279 // the transform represents a pause, so yield silence
1280 timedYieldSilence_l(buffer->frameCount, buffer);
1281 return NO_ERROR;
1282 }
1283
1284 int64_t transformedPTS;
1285 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1286 &transformedPTS)) {
1287 // the transform failed. this shouldn't happen, but if it does
1288 // then just drop this buffer
1289 ALOGW("timedGetNextBuffer transform failed");
1290 buffer->raw = NULL;
1291 buffer->frameCount = 0;
1292 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1293 return NO_ERROR;
1294 }
1295
1296 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1297 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1298 &headLocalPTS)) {
1299 buffer->raw = NULL;
1300 buffer->frameCount = 0;
1301 return INVALID_OPERATION;
1302 }
1303 } else {
1304 headLocalPTS = transformedPTS;
1305 }
1306 }
1307
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001308 uint32_t sr = sampleRate();
1309
Eric Laurent81784c32012-11-19 14:55:58 -08001310 // adjust the head buffer's PTS to reflect the portion of the head buffer
1311 // that has already been consumed
1312 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001313 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001314
1315 // Calculate the delta in samples between the head of the input buffer
1316 // queue and the start of the next output buffer that will be written.
1317 // If the transformation fails because of over or underflow, it means
1318 // that the sample's position in the output stream is so far out of
1319 // whack that it should just be dropped.
1320 int64_t sampleDelta;
1321 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1322 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1323 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1324 " mix");
1325 continue;
1326 }
1327 if (!mLocalTimeToSampleTransform.doForwardTransform(
1328 (effectivePTS - pts) << 32, &sampleDelta)) {
1329 ALOGV("*** too late during sample rate transform: dropped buffer");
1330 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1331 continue;
1332 }
1333
1334 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1335 " sampleDelta=[%d.%08x]",
1336 head.pts(), head.position(), pts,
1337 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1338 + (sampleDelta >> 32)),
1339 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1340
1341 // if the delta between the ideal placement for the next input sample and
1342 // the current output position is within this threshold, then we will
1343 // concatenate the next input samples to the previous output
1344 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001345 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001346
1347 // if this is the first buffer of audio that we're emitting from this track
1348 // then it should be almost exactly on time.
1349 const int64_t kSampleStartupThreshold = 1LL << 32;
1350
1351 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1352 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1353 // the next input is close enough to being on time, so concatenate it
1354 // with the last output
1355 timedYieldSamples_l(buffer);
1356
1357 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1358 head.position(), buffer->frameCount);
1359 return NO_ERROR;
1360 }
1361
1362 // Looks like our output is not on time. Reset our on timed status.
1363 // Next time we mix samples from our input queue, then should be within
1364 // the StartupThreshold.
1365 mTimedAudioOutputOnTime = false;
1366 if (sampleDelta > 0) {
1367 // the gap between the current output position and the proper start of
1368 // the next input sample is too big, so fill it with silence
1369 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1370
1371 timedYieldSilence_l(framesUntilNextInput, buffer);
1372 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1373 return NO_ERROR;
1374 } else {
1375 // the next input sample is late
1376 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1377 size_t onTimeSamplePosition =
1378 head.position() + lateFrames * mFrameSize;
1379
1380 if (onTimeSamplePosition > head.buffer()->size()) {
1381 // all the remaining samples in the head are too late, so
1382 // drop it and move on
1383 ALOGV("*** too late: dropped buffer");
1384 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1385 continue;
1386 } else {
1387 // skip over the late samples
1388 head.setPosition(onTimeSamplePosition);
1389
1390 // yield the available samples
1391 timedYieldSamples_l(buffer);
1392
1393 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1394 return NO_ERROR;
1395 }
1396 }
1397 }
1398}
1399
1400// Yield samples from the timed buffer queue head up to the given output
1401// buffer's capacity.
1402//
1403// Caller must hold mTimedBufferQueueLock
1404void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1405 AudioBufferProvider::Buffer* buffer) {
1406
1407 const TimedBuffer& head = mTimedBufferQueue[0];
1408
1409 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1410 head.position());
1411
1412 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1413 mFrameSize);
1414 size_t framesRequested = buffer->frameCount;
1415 buffer->frameCount = min(framesLeftInHead, framesRequested);
1416
1417 mQueueHeadInFlight = true;
1418 mTimedAudioOutputOnTime = true;
1419}
1420
1421// Yield samples of silence up to the given output buffer's capacity
1422//
1423// Caller must hold mTimedBufferQueueLock
1424void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1425 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1426
1427 // lazily allocate a buffer filled with silence
1428 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1429 delete [] mTimedSilenceBuffer;
1430 mTimedSilenceBufferSize = numFrames * mFrameSize;
1431 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1432 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1433 }
1434
1435 buffer->raw = mTimedSilenceBuffer;
1436 size_t framesRequested = buffer->frameCount;
1437 buffer->frameCount = min(numFrames, framesRequested);
1438
1439 mTimedAudioOutputOnTime = false;
1440}
1441
1442// AudioBufferProvider interface
1443void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1444 AudioBufferProvider::Buffer* buffer) {
1445
1446 Mutex::Autolock _l(mTimedBufferQueueLock);
1447
1448 // If the buffer which was just released is part of the buffer at the head
1449 // of the queue, be sure to update the amt of the buffer which has been
1450 // consumed. If the buffer being returned is not part of the head of the
1451 // queue, its either because the buffer is part of the silence buffer, or
1452 // because the head of the timed queue was trimmed after the mixer called
1453 // getNextBuffer but before the mixer called releaseBuffer.
1454 if (buffer->raw == mTimedSilenceBuffer) {
1455 ALOG_ASSERT(!mQueueHeadInFlight,
1456 "Queue head in flight during release of silence buffer!");
1457 goto done;
1458 }
1459
1460 ALOG_ASSERT(mQueueHeadInFlight,
1461 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1462 " head in flight.");
1463
1464 if (mTimedBufferQueue.size()) {
1465 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1466
1467 void* start = head.buffer()->pointer();
1468 void* end = reinterpret_cast<void*>(
1469 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1470 + head.buffer()->size());
1471
1472 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1473 "released buffer not within the head of the timed buffer"
1474 " queue; qHead = [%p, %p], released buffer = %p",
1475 start, end, buffer->raw);
1476
1477 head.setPosition(head.position() +
1478 (buffer->frameCount * mFrameSize));
1479 mQueueHeadInFlight = false;
1480
1481 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1482 "Bad bookkeeping during releaseBuffer! Should have at"
1483 " least %u queued frames, but we think we have only %u",
1484 buffer->frameCount, mFramesPendingInQueue);
1485
1486 mFramesPendingInQueue -= buffer->frameCount;
1487
1488 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1489 || mTrimQueueHeadOnRelease) {
1490 trimTimedBufferQueueHead_l("releaseBuffer");
1491 mTrimQueueHeadOnRelease = false;
1492 }
1493 } else {
1494 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1495 " buffers in the timed buffer queue");
1496 }
1497
1498done:
1499 buffer->raw = 0;
1500 buffer->frameCount = 0;
1501}
1502
1503size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1504 Mutex::Autolock _l(mTimedBufferQueueLock);
1505 return mFramesPendingInQueue;
1506}
1507
1508AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1509 : mPTS(0), mPosition(0) {}
1510
1511AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1512 const sp<IMemory>& buffer, int64_t pts)
1513 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1514
1515
1516// ----------------------------------------------------------------------------
1517
1518AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1519 PlaybackThread *playbackThread,
1520 DuplicatingThread *sourceThread,
1521 uint32_t sampleRate,
1522 audio_format_t format,
1523 audio_channel_mask_t channelMask,
1524 size_t frameCount)
1525 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1526 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001527 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001528{
1529
1530 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001531 mOutBuffer.frameCount = 0;
1532 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001533 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001534 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001535 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001536 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001537 // since client and server are in the same process,
1538 // the buffer has the same virtual address on both sides
1539 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001540 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1541 mClientProxy->setSendLevel(0.0);
1542 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001543 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1544 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001545 } else {
1546 ALOGW("Error creating output track on thread %p", playbackThread);
1547 }
1548}
1549
1550AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1551{
1552 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001553 delete mClientProxy;
1554 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001555}
1556
1557status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1558 int triggerSession)
1559{
1560 status_t status = Track::start(event, triggerSession);
1561 if (status != NO_ERROR) {
1562 return status;
1563 }
1564
1565 mActive = true;
1566 mRetryCount = 127;
1567 return status;
1568}
1569
1570void AudioFlinger::PlaybackThread::OutputTrack::stop()
1571{
1572 Track::stop();
1573 clearBufferQueue();
1574 mOutBuffer.frameCount = 0;
1575 mActive = false;
1576}
1577
1578bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1579{
1580 Buffer *pInBuffer;
1581 Buffer inBuffer;
1582 uint32_t channelCount = mChannelCount;
1583 bool outputBufferFull = false;
1584 inBuffer.frameCount = frames;
1585 inBuffer.i16 = data;
1586
1587 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1588
1589 if (!mActive && frames != 0) {
1590 start();
1591 sp<ThreadBase> thread = mThread.promote();
1592 if (thread != 0) {
1593 MixerThread *mixerThread = (MixerThread *)thread.get();
1594 if (mFrameCount > frames) {
1595 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1596 uint32_t startFrames = (mFrameCount - frames);
1597 pInBuffer = new Buffer;
1598 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1599 pInBuffer->frameCount = startFrames;
1600 pInBuffer->i16 = pInBuffer->mBuffer;
1601 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1602 mBufferQueue.add(pInBuffer);
1603 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001604 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001605 }
1606 }
1607 }
1608 }
1609
1610 while (waitTimeLeftMs) {
1611 // First write pending buffers, then new data
1612 if (mBufferQueue.size()) {
1613 pInBuffer = mBufferQueue.itemAt(0);
1614 } else {
1615 pInBuffer = &inBuffer;
1616 }
1617
1618 if (pInBuffer->frameCount == 0) {
1619 break;
1620 }
1621
1622 if (mOutBuffer.frameCount == 0) {
1623 mOutBuffer.frameCount = pInBuffer->frameCount;
1624 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001625 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1626 if (status != NO_ERROR) {
1627 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1628 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001629 outputBufferFull = true;
1630 break;
1631 }
1632 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1633 if (waitTimeLeftMs >= waitTimeMs) {
1634 waitTimeLeftMs -= waitTimeMs;
1635 } else {
1636 waitTimeLeftMs = 0;
1637 }
1638 }
1639
1640 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1641 pInBuffer->frameCount;
1642 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001643 Proxy::Buffer buf;
1644 buf.mFrameCount = outFrames;
1645 buf.mRaw = NULL;
1646 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001647 pInBuffer->frameCount -= outFrames;
1648 pInBuffer->i16 += outFrames * channelCount;
1649 mOutBuffer.frameCount -= outFrames;
1650 mOutBuffer.i16 += outFrames * channelCount;
1651
1652 if (pInBuffer->frameCount == 0) {
1653 if (mBufferQueue.size()) {
1654 mBufferQueue.removeAt(0);
1655 delete [] pInBuffer->mBuffer;
1656 delete pInBuffer;
1657 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1658 mThread.unsafe_get(), mBufferQueue.size());
1659 } else {
1660 break;
1661 }
1662 }
1663 }
1664
1665 // If we could not write all frames, allocate a buffer and queue it for next time.
1666 if (inBuffer.frameCount) {
1667 sp<ThreadBase> thread = mThread.promote();
1668 if (thread != 0 && !thread->standby()) {
1669 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1670 pInBuffer = new Buffer;
1671 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1672 pInBuffer->frameCount = inBuffer.frameCount;
1673 pInBuffer->i16 = pInBuffer->mBuffer;
1674 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1675 sizeof(int16_t));
1676 mBufferQueue.add(pInBuffer);
1677 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1678 mThread.unsafe_get(), mBufferQueue.size());
1679 } else {
1680 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1681 mThread.unsafe_get(), this);
1682 }
1683 }
1684 }
1685
1686 // Calling write() with a 0 length buffer, means that no more data will be written:
1687 // If no more buffers are pending, fill output track buffer to make sure it is started
1688 // by output mixer.
1689 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001690 // FIXME borken, replace by getting framesReady() from proxy
1691 size_t user = 0; // was mCblk->user
1692 if (user < mFrameCount) {
1693 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001694 pInBuffer = new Buffer;
1695 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1696 pInBuffer->frameCount = frames;
1697 pInBuffer->i16 = pInBuffer->mBuffer;
1698 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1699 mBufferQueue.add(pInBuffer);
1700 } else if (mActive) {
1701 stop();
1702 }
1703 }
1704
1705 return outputBufferFull;
1706}
1707
1708status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1709 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1710{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001711 ClientProxy::Buffer buf;
1712 buf.mFrameCount = buffer->frameCount;
1713 struct timespec timeout;
1714 timeout.tv_sec = waitTimeMs / 1000;
1715 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1716 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1717 buffer->frameCount = buf.mFrameCount;
1718 buffer->raw = buf.mRaw;
1719 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001720}
1721
Eric Laurent81784c32012-11-19 14:55:58 -08001722void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1723{
1724 size_t size = mBufferQueue.size();
1725
1726 for (size_t i = 0; i < size; i++) {
1727 Buffer *pBuffer = mBufferQueue.itemAt(i);
1728 delete [] pBuffer->mBuffer;
1729 delete pBuffer;
1730 }
1731 mBufferQueue.clear();
1732}
1733
1734
1735// ----------------------------------------------------------------------------
1736// Record
1737// ----------------------------------------------------------------------------
1738
1739AudioFlinger::RecordHandle::RecordHandle(
1740 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1741 : BnAudioRecord(),
1742 mRecordTrack(recordTrack)
1743{
1744}
1745
1746AudioFlinger::RecordHandle::~RecordHandle() {
1747 stop_nonvirtual();
1748 mRecordTrack->destroy();
1749}
1750
1751sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1752 return mRecordTrack->getCblk();
1753}
1754
1755status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1756 int triggerSession) {
1757 ALOGV("RecordHandle::start()");
1758 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1759}
1760
1761void AudioFlinger::RecordHandle::stop() {
1762 stop_nonvirtual();
1763}
1764
1765void AudioFlinger::RecordHandle::stop_nonvirtual() {
1766 ALOGV("RecordHandle::stop()");
1767 mRecordTrack->stop();
1768}
1769
1770status_t AudioFlinger::RecordHandle::onTransact(
1771 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1772{
1773 return BnAudioRecord::onTransact(code, data, reply, flags);
1774}
1775
1776// ----------------------------------------------------------------------------
1777
1778// RecordTrack constructor must be called with AudioFlinger::mLock held
1779AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1780 RecordThread *thread,
1781 const sp<Client>& client,
1782 uint32_t sampleRate,
1783 audio_format_t format,
1784 audio_channel_mask_t channelMask,
1785 size_t frameCount,
Alok Kediya601e9b52013-09-27 11:55:10 +05301786 uint32_t flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001787 int sessionId)
Alok Kediya601e9b52013-09-27 11:55:10 +05301788 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
1789 flags, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001790 mOverflow(false)
1791{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001792 ALOGV("RecordTrack constructor");
Alok Kediya601e9b52013-09-27 11:55:10 +05301793 mFlags = flags;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001794 if (mCblk != NULL) {
1795 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1796 mFrameSize);
1797 mServerProxy = mAudioRecordServerProxy;
1798 }
Eric Laurent81784c32012-11-19 14:55:58 -08001799}
1800
1801AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1802{
1803 ALOGV("%s", __func__);
1804}
1805
1806// AudioBufferProvider interface
1807status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1808 int64_t pts)
1809{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001810 ServerProxy::Buffer buf;
1811 buf.mFrameCount = buffer->frameCount;
1812 status_t status = mServerProxy->obtainBuffer(&buf);
1813 buffer->frameCount = buf.mFrameCount;
1814 buffer->raw = buf.mRaw;
1815 if (buf.mFrameCount == 0) {
1816 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001817 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001818 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001819 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001820}
1821
1822status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1823 int triggerSession)
1824{
1825 sp<ThreadBase> thread = mThread.promote();
1826 if (thread != 0) {
1827 RecordThread *recordThread = (RecordThread *)thread.get();
1828 return recordThread->start(this, event, triggerSession);
1829 } else {
1830 return BAD_VALUE;
1831 }
1832}
1833
1834void AudioFlinger::RecordThread::RecordTrack::stop()
1835{
1836 sp<ThreadBase> thread = mThread.promote();
1837 if (thread != 0) {
1838 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001839 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001840 AudioSystem::stopInput(recordThread->id());
1841 }
1842 }
1843}
1844
1845void AudioFlinger::RecordThread::RecordTrack::destroy()
1846{
1847 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1848 sp<RecordTrack> keep(this);
1849 {
1850 sp<ThreadBase> thread = mThread.promote();
1851 if (thread != 0) {
1852 if (mState == ACTIVE || mState == RESUMING) {
1853 AudioSystem::stopInput(thread->id());
1854 }
1855 AudioSystem::releaseInput(thread->id());
1856 Mutex::Autolock _l(thread->mLock);
1857 RecordThread *recordThread = (RecordThread *) thread.get();
1858 recordThread->destroyTrack_l(this);
1859 }
1860 }
1861}
1862
Eric Laurent9a54bc22013-09-09 09:08:44 -07001863void AudioFlinger::RecordThread::RecordTrack::invalidate()
1864{
1865 // FIXME should use proxy, and needs work
1866 audio_track_cblk_t* cblk = mCblk;
1867 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1868 android_atomic_release_store(0x40000000, &cblk->mFutex);
1869 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1870 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1871}
1872
Eric Laurent81784c32012-11-19 14:55:58 -08001873
1874/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1875{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001876 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001877}
1878
1879void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1880{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001881 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001882 (mClient == 0) ? getpid_cached : mClient->pid(),
1883 mFormat,
1884 mChannelMask,
1885 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001886 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001887 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001888 mFrameCount);
1889}
1890
Eric Laurent81784c32012-11-19 14:55:58 -08001891}; // namespace android