blob: 92ed46a5a5756095f6e874675687d5be33fadad2 [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,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080071 int clientUid,
Glenn Kastene3aa6592012-12-04 12:22:46 -080072 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)),
83 mFrameSize(audio_is_linear_pcm(format) ?
84 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
85 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080086 mSessionId(sessionId),
87 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080088 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080089 mId(android_atomic_inc(&nextTrackId)),
90 mTerminated(false)
Eric Laurent81784c32012-11-19 14:55:58 -080091{
Marco Nelissen462fd2f2013-01-14 14:12:05 -080092 // if the caller is us, trust the specified uid
93 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
94 int newclientUid = IPCThreadState::self()->getCallingUid();
95 if (clientUid != -1 && clientUid != newclientUid) {
96 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
97 }
98 clientUid = newclientUid;
99 }
100 // clientUid contains the uid of the app that is responsible for this track, so we can blame
101 // battery usage on it.
102 mUid = clientUid;
103
Eric Laurent81784c32012-11-19 14:55:58 -0800104 // client == 0 implies sharedBuffer == 0
105 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
106
107 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
108 sharedBuffer->size());
109
110 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
111 size_t size = sizeof(audio_track_cblk_t);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800112 size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -0800113 if (sharedBuffer == 0) {
114 size += bufferSize;
115 }
116
117 if (client != 0) {
118 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700119 if (mCblkMemory == 0 ||
120 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800121 ALOGE("not enough memory for AudioTrack size=%u", size);
122 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700123 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800124 return;
125 }
126 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800127 // this syntax avoids calling the audio_track_cblk_t constructor twice
128 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800129 // assume mCblk != NULL
130 }
131
132 // construct the shared structure in-place.
133 if (mCblk != NULL) {
134 new(mCblk) audio_track_cblk_t();
135 // clear all buffers
Eric Laurent81784c32012-11-19 14:55:58 -0800136 if (sharedBuffer == 0) {
137 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
138 memset(mBuffer, 0, bufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -0800139 } else {
140 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800141#if 0
Glenn Kasten96f60d82013-07-12 10:21:18 -0700142 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800143#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800144 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800145
Glenn Kasten46909e72013-02-26 09:20:22 -0800146#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800147 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800148 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800149 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800150 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
151 size_t numCounterOffers = 0;
152 const NBAIO_Format offers[1] = {pipeFormat};
153 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
154 ALOG_ASSERT(index == 0);
155 PipeReader *pipeReader = new PipeReader(*pipe);
156 numCounterOffers = 0;
157 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
158 ALOG_ASSERT(index == 0);
159 mTeeSink = pipe;
160 mTeeSource = pipeReader;
161 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800162 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800163#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800164
Eric Laurent81784c32012-11-19 14:55:58 -0800165 }
166}
167
168AudioFlinger::ThreadBase::TrackBase::~TrackBase()
169{
Glenn Kasten46909e72013-02-26 09:20:22 -0800170#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800171 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800172#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800173 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
174 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800175 if (mCblk != NULL) {
176 if (mClient == 0) {
177 delete mCblk;
178 } else {
179 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
180 }
181 }
182 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
183 if (mClient != 0) {
184 // Client destructor must run with AudioFlinger mutex locked
185 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
186 // If the client's reference count drops to zero, the associated destructor
187 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
188 // relying on the automatic clear() at end of scope.
189 mClient.clear();
190 }
191}
192
193// AudioBufferProvider interface
194// getNextBuffer() = 0;
195// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
196void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
197{
Glenn Kasten46909e72013-02-26 09:20:22 -0800198#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199 if (mTeeSink != 0) {
200 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
201 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800202#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800203
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800204 ServerProxy::Buffer buf;
205 buf.mFrameCount = buffer->frameCount;
206 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800207 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800208 buffer->raw = NULL;
209 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800210}
211
Eric Laurent81784c32012-11-19 14:55:58 -0800212status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
213{
214 mSyncEvents.add(event);
215 return NO_ERROR;
216}
217
218// ----------------------------------------------------------------------------
219// Playback
220// ----------------------------------------------------------------------------
221
222AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
223 : BnAudioTrack(),
224 mTrack(track)
225{
226}
227
228AudioFlinger::TrackHandle::~TrackHandle() {
229 // just stop the track on deletion, associated resources
230 // will be freed from the main thread once all pending buffers have
231 // been played. Unless it's not in the active track list, in which
232 // case we free everything now...
233 mTrack->destroy();
234}
235
236sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
237 return mTrack->getCblk();
238}
239
240status_t AudioFlinger::TrackHandle::start() {
241 return mTrack->start();
242}
243
244void AudioFlinger::TrackHandle::stop() {
245 mTrack->stop();
246}
247
248void AudioFlinger::TrackHandle::flush() {
249 mTrack->flush();
250}
251
Eric Laurent81784c32012-11-19 14:55:58 -0800252void AudioFlinger::TrackHandle::pause() {
253 mTrack->pause();
254}
255
256status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
257{
258 return mTrack->attachAuxEffect(EffectId);
259}
260
261status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
262 sp<IMemory>* buffer) {
263 if (!mTrack->isTimedTrack())
264 return INVALID_OPERATION;
265
266 PlaybackThread::TimedTrack* tt =
267 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
268 return tt->allocateTimedBuffer(size, buffer);
269}
270
271status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
272 int64_t pts) {
273 if (!mTrack->isTimedTrack())
274 return INVALID_OPERATION;
275
Glenn Kasten663c2242013-09-24 11:52:37 -0700276 if (buffer == 0 || buffer->pointer() == NULL) {
277 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
278 return BAD_VALUE;
279 }
280
Eric Laurent81784c32012-11-19 14:55:58 -0800281 PlaybackThread::TimedTrack* tt =
282 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
283 return tt->queueTimedBuffer(buffer, pts);
284}
285
286status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
287 const LinearTransform& xform, int target) {
288
289 if (!mTrack->isTimedTrack())
290 return INVALID_OPERATION;
291
292 PlaybackThread::TimedTrack* tt =
293 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
294 return tt->setMediaTimeTransform(
295 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
296}
297
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700298status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
299 return mTrack->setParameters(keyValuePairs);
300}
301
Glenn Kasten53cec222013-08-29 09:01:02 -0700302status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
303{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700304 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700305}
306
Eric Laurent59fe0102013-09-27 18:48:26 -0700307
308void AudioFlinger::TrackHandle::signal()
309{
310 return mTrack->signal();
311}
312
Eric Laurent81784c32012-11-19 14:55:58 -0800313status_t AudioFlinger::TrackHandle::onTransact(
314 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
315{
316 return BnAudioTrack::onTransact(code, data, reply, flags);
317}
318
319// ----------------------------------------------------------------------------
320
321// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
322AudioFlinger::PlaybackThread::Track::Track(
323 PlaybackThread *thread,
324 const sp<Client>& client,
325 audio_stream_type_t streamType,
326 uint32_t sampleRate,
327 audio_format_t format,
328 audio_channel_mask_t channelMask,
329 size_t frameCount,
330 const sp<IMemory>& sharedBuffer,
331 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800332 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -0800333 IAudioFlinger::track_flags_t flags)
334 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800335 sessionId, uid, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800336 mFillingUpStatus(FS_INVALID),
337 // mRetryCount initialized later when needed
338 mSharedBuffer(sharedBuffer),
339 mStreamType(streamType),
340 mName(-1), // see note below
341 mMainBuffer(thread->mixBuffer()),
342 mAuxBuffer(NULL),
343 mAuxEffectId(0), mHasVolumeController(false),
344 mPresentationCompleteFrames(0),
345 mFlags(flags),
346 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800347 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800348 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800349 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800350 mResumeToStopping(false),
351 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800352{
353 if (mCblk != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800354 if (sharedBuffer == 0) {
355 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
356 mFrameSize);
357 } else {
358 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
359 mFrameSize);
360 }
361 mServerProxy = mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800362 // to avoid leaking a track name, do not allocate one unless there is an mCblk
363 mName = thread->getTrackName_l(channelMask, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800364 if (mName < 0) {
365 ALOGE("no more track names available");
366 return;
367 }
368 // only allocate a fast track index if we were able to allocate a normal track name
369 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800370 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Eric Laurent81784c32012-11-19 14:55:58 -0800371 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
372 int i = __builtin_ctz(thread->mFastTrackAvailMask);
373 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
374 // FIXME This is too eager. We allocate a fast track index before the
375 // fast track becomes active. Since fast tracks are a scarce resource,
376 // this means we are potentially denying other more important fast tracks from
377 // being created. It would be better to allocate the index dynamically.
378 mFastIndex = i;
Eric Laurent81784c32012-11-19 14:55:58 -0800379 // Read the initial underruns because this field is never cleared by the fast mixer
380 mObservedUnderruns = thread->getFastTrackUnderruns(i);
381 thread->mFastTrackAvailMask &= ~(1 << i);
382 }
383 }
384 ALOGV("Track constructor name %d, calling pid %d", mName,
385 IPCThreadState::self()->getCallingPid());
386}
387
388AudioFlinger::PlaybackThread::Track::~Track()
389{
390 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700391
392 // The destructor would clear mSharedBuffer,
393 // but it will not push the decremented reference count,
394 // leaving the client's IMemory dangling indefinitely.
395 // This prevents that leak.
396 if (mSharedBuffer != 0) {
397 mSharedBuffer.clear();
398 // flush the binder command buffer
399 IPCThreadState::self()->flushCommands();
400 }
Eric Laurent81784c32012-11-19 14:55:58 -0800401}
402
Glenn Kasten03003332013-08-06 15:40:54 -0700403status_t AudioFlinger::PlaybackThread::Track::initCheck() const
404{
405 status_t status = TrackBase::initCheck();
406 if (status == NO_ERROR && mName < 0) {
407 status = NO_MEMORY;
408 }
409 return status;
410}
411
Eric Laurent81784c32012-11-19 14:55:58 -0800412void AudioFlinger::PlaybackThread::Track::destroy()
413{
414 // NOTE: destroyTrack_l() can remove a strong reference to this Track
415 // by removing it from mTracks vector, so there is a risk that this Tracks's
416 // destructor is called. As the destructor needs to lock mLock,
417 // we must acquire a strong reference on this Track before locking mLock
418 // here so that the destructor is called only when exiting this function.
419 // On the other hand, as long as Track::destroy() is only called by
420 // TrackHandle destructor, the TrackHandle still holds a strong ref on
421 // this Track with its member mTrack.
422 sp<Track> keep(this);
423 { // scope for mLock
424 sp<ThreadBase> thread = mThread.promote();
425 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800426 Mutex::Autolock _l(thread->mLock);
427 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800428 bool wasActive = playbackThread->destroyTrack_l(this);
429 if (!isOutputTrack() && !wasActive) {
430 AudioSystem::releaseOutput(thread->id());
431 }
Eric Laurent81784c32012-11-19 14:55:58 -0800432 }
433 }
434}
435
436/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
437{
Marco Nelissenb2208842014-02-07 14:00:50 -0800438 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700439 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800440}
441
Marco Nelissenb2208842014-02-07 14:00:50 -0800442void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800443{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800444 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800445 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800446 sprintf(buffer, " F %2d", mFastIndex);
447 } else if (mName >= AudioMixer::TRACK0) {
448 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800449 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800450 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800451 }
452 track_state state = mState;
453 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800454 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800455 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800456 } else {
457 switch (state) {
458 case IDLE:
459 stateChar = 'I';
460 break;
461 case STOPPING_1:
462 stateChar = 's';
463 break;
464 case STOPPING_2:
465 stateChar = '5';
466 break;
467 case STOPPED:
468 stateChar = 'S';
469 break;
470 case RESUMING:
471 stateChar = 'R';
472 break;
473 case ACTIVE:
474 stateChar = 'A';
475 break;
476 case PAUSING:
477 stateChar = 'p';
478 break;
479 case PAUSED:
480 stateChar = 'P';
481 break;
482 case FLUSHED:
483 stateChar = 'F';
484 break;
485 default:
486 stateChar = '?';
487 break;
488 }
Eric Laurent81784c32012-11-19 14:55:58 -0800489 }
490 char nowInUnderrun;
491 switch (mObservedUnderruns.mBitFields.mMostRecent) {
492 case UNDERRUN_FULL:
493 nowInUnderrun = ' ';
494 break;
495 case UNDERRUN_PARTIAL:
496 nowInUnderrun = '<';
497 break;
498 case UNDERRUN_EMPTY:
499 nowInUnderrun = '*';
500 break;
501 default:
502 nowInUnderrun = '?';
503 break;
504 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000505 snprintf(&buffer[8], size-8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u %5.2g %5.2g "
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000506 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800507 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800508 (mClient == 0) ? getpid_cached : mClient->pid(),
509 mStreamType,
510 mFormat,
511 mChannelMask,
512 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800513 mFrameCount,
514 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800515 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800516 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800517 20.0 * log10((vlr & 0xFFFF) / 4096.0),
518 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700519 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000520 mMainBuffer,
521 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700522 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700523 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800524 nowInUnderrun);
525}
526
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800527uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
528 return mAudioTrackServerProxy->getSampleRate();
529}
530
Eric Laurent81784c32012-11-19 14:55:58 -0800531// AudioBufferProvider interface
532status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800533 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800534{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800535 ServerProxy::Buffer buf;
536 size_t desiredFrames = buffer->frameCount;
537 buf.mFrameCount = desiredFrames;
538 status_t status = mServerProxy->obtainBuffer(&buf);
539 buffer->frameCount = buf.mFrameCount;
540 buffer->raw = buf.mRaw;
541 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700542 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800543 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800544 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800545}
546
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700547// releaseBuffer() is not overridden
548
549// ExtendedAudioBufferProvider interface
550
Eric Laurent81784c32012-11-19 14:55:58 -0800551// Note that framesReady() takes a mutex on the control block using tryLock().
552// This could result in priority inversion if framesReady() is called by the normal mixer,
553// as the normal mixer thread runs at lower
554// priority than the client's callback thread: there is a short window within framesReady()
555// during which the normal mixer could be preempted, and the client callback would block.
556// Another problem can occur if framesReady() is called by the fast mixer:
557// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
558// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
559size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800560 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800561}
562
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700563size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
564{
565 return mAudioTrackServerProxy->framesReleased();
566}
567
Eric Laurent81784c32012-11-19 14:55:58 -0800568// Don't call for fast tracks; the framesReady() could result in priority inversion
569bool AudioFlinger::PlaybackThread::Track::isReady() const {
Haynes Mathew George0bcfa882013-12-27 16:09:28 -0800570 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing() || isStopping()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800571 return true;
572 }
573
574 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700575 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800576 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700577 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800578 return true;
579 }
580 return false;
581}
582
Glenn Kasten0f11b512014-01-31 16:18:54 -0800583status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
584 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800585{
586 status_t status = NO_ERROR;
587 ALOGV("start(%d), calling pid %d session %d",
588 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
589
590 sp<ThreadBase> thread = mThread.promote();
591 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700592 if (isOffloaded()) {
593 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
594 Mutex::Autolock _lth(thread->mLock);
595 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700596 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
597 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700598 invalidate();
599 return PERMISSION_DENIED;
600 }
601 }
602 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800603 track_state state = mState;
604 // here the track could be either new, or restarted
605 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800606
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800607 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800608 if (mResumeToStopping) {
609 // happened we need to resume to STOPPING_1
610 mState = TrackBase::STOPPING_1;
611 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
612 } else {
613 mState = TrackBase::RESUMING;
614 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
615 }
Eric Laurent81784c32012-11-19 14:55:58 -0800616 } else {
617 mState = TrackBase::ACTIVE;
618 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
619 }
620
Eric Laurentbfb1b832013-01-07 09:53:42 -0800621 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
622 status = playbackThread->addTrack_l(this);
623 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800624 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800625 // restore previous state if start was rejected by policy manager
626 if (status == PERMISSION_DENIED) {
627 mState = state;
628 }
629 }
630 // track was already in the active list, not a problem
631 if (status == ALREADY_EXISTS) {
632 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700633 } else {
634 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
635 // It is usually unsafe to access the server proxy from a binder thread.
636 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
637 // isn't looking at this track yet: we still hold the normal mixer thread lock,
638 // and for fast tracks the track is not yet in the fast mixer thread's active set.
639 ServerProxy::Buffer buffer;
640 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700641 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800642 }
643 } else {
644 status = BAD_VALUE;
645 }
646 return status;
647}
648
649void AudioFlinger::PlaybackThread::Track::stop()
650{
651 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
652 sp<ThreadBase> thread = mThread.promote();
653 if (thread != 0) {
654 Mutex::Autolock _l(thread->mLock);
655 track_state state = mState;
656 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
657 // If the track is not active (PAUSED and buffers full), flush buffers
658 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
659 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
660 reset();
661 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800662 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800663 mState = STOPPED;
664 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800665 // For fast tracks prepareTracks_l() will set state to STOPPING_2
666 // presentation is complete
667 // For an offloaded track this starts a drain and state will
668 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800669 mState = STOPPING_1;
670 }
671 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
672 playbackThread);
673 }
Eric Laurent81784c32012-11-19 14:55:58 -0800674 }
675}
676
677void AudioFlinger::PlaybackThread::Track::pause()
678{
679 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
680 sp<ThreadBase> thread = mThread.promote();
681 if (thread != 0) {
682 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800683 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
684 switch (mState) {
685 case STOPPING_1:
686 case STOPPING_2:
687 if (!isOffloaded()) {
688 /* nothing to do if track is not offloaded */
689 break;
690 }
691
692 // Offloaded track was draining, we need to carry on draining when resumed
693 mResumeToStopping = true;
694 // fall through...
695 case ACTIVE:
696 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800697 mState = PAUSING;
698 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700699 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800700 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800701
Eric Laurentbfb1b832013-01-07 09:53:42 -0800702 default:
703 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800704 }
705 }
706}
707
708void AudioFlinger::PlaybackThread::Track::flush()
709{
710 ALOGV("flush(%d)", mName);
711 sp<ThreadBase> thread = mThread.promote();
712 if (thread != 0) {
713 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800714 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800715
716 if (isOffloaded()) {
717 // If offloaded we allow flush during any state except terminated
718 // and keep the track active to avoid problems if user is seeking
719 // rapidly and underlying hardware has a significant delay handling
720 // a pause
721 if (isTerminated()) {
722 return;
723 }
724
725 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800726 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800727
728 if (mState == STOPPING_1 || mState == STOPPING_2) {
729 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
730 mState = ACTIVE;
731 }
732
733 if (mState == ACTIVE) {
734 ALOGV("flush called in active state, resetting buffer time out retry count");
735 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
736 }
737
Haynes Mathew George7844f672014-01-15 12:32:55 -0800738 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800739 mResumeToStopping = false;
740 } else {
741 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
742 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
743 return;
744 }
745 // No point remaining in PAUSED state after a flush => go to
746 // FLUSHED state
747 mState = FLUSHED;
748 // do not reset the track if it is still in the process of being stopped or paused.
749 // this will be done by prepareTracks_l() when the track is stopped.
750 // prepareTracks_l() will see mState == FLUSHED, then
751 // remove from active track list, reset(), and trigger presentation complete
752 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
753 reset();
754 }
Eric Laurent81784c32012-11-19 14:55:58 -0800755 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800756 // Prevent flush being lost if the track is flushed and then resumed
757 // before mixer thread can run. This is important when offloading
758 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700759 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800760 }
761}
762
Haynes Mathew George7844f672014-01-15 12:32:55 -0800763// must be called with thread lock held
764void AudioFlinger::PlaybackThread::Track::flushAck()
765{
766 if (!isOffloaded())
767 return;
768
769 mFlushHwPending = false;
770}
771
Eric Laurent81784c32012-11-19 14:55:58 -0800772void AudioFlinger::PlaybackThread::Track::reset()
773{
774 // Do not reset twice to avoid discarding data written just after a flush and before
775 // the audioflinger thread detects the track is stopped.
776 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800777 // Force underrun condition to avoid false underrun callback until first data is
778 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700779 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800780 mFillingUpStatus = FS_FILLING;
781 mResetDone = true;
782 if (mState == FLUSHED) {
783 mState = IDLE;
784 }
785 }
786}
787
Eric Laurentbfb1b832013-01-07 09:53:42 -0800788status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
789{
790 sp<ThreadBase> thread = mThread.promote();
791 if (thread == 0) {
792 ALOGE("thread is dead");
793 return FAILED_TRANSACTION;
794 } else if ((thread->type() == ThreadBase::DIRECT) ||
795 (thread->type() == ThreadBase::OFFLOAD)) {
796 return thread->setParameters(keyValuePairs);
797 } else {
798 return PERMISSION_DENIED;
799 }
800}
801
Glenn Kasten573d80a2013-08-26 09:36:23 -0700802status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
803{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700804 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
805 if (isFastTrack()) {
806 return INVALID_OPERATION;
807 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700808 sp<ThreadBase> thread = mThread.promote();
809 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700810 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700811 }
812 Mutex::Autolock _l(thread->mLock);
813 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700814 if (!isOffloaded()) {
815 if (!playbackThread->mLatchQValid) {
816 return INVALID_OPERATION;
817 }
818 uint32_t unpresentedFrames =
819 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
820 playbackThread->mSampleRate;
821 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
822 if (framesWritten < unpresentedFrames) {
823 return INVALID_OPERATION;
824 }
825 timestamp.mPosition = framesWritten - unpresentedFrames;
826 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
827 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700828 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700829
830 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700831}
832
Eric Laurent81784c32012-11-19 14:55:58 -0800833status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
834{
835 status_t status = DEAD_OBJECT;
836 sp<ThreadBase> thread = mThread.promote();
837 if (thread != 0) {
838 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
839 sp<AudioFlinger> af = mClient->audioFlinger();
840
841 Mutex::Autolock _l(af->mLock);
842
843 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
844
845 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
846 Mutex::Autolock _dl(playbackThread->mLock);
847 Mutex::Autolock _sl(srcThread->mLock);
848 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
849 if (chain == 0) {
850 return INVALID_OPERATION;
851 }
852
853 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
854 if (effect == 0) {
855 return INVALID_OPERATION;
856 }
857 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700858 status = playbackThread->addEffect_l(effect);
859 if (status != NO_ERROR) {
860 srcThread->addEffect_l(effect);
861 return INVALID_OPERATION;
862 }
Eric Laurent81784c32012-11-19 14:55:58 -0800863 // removeEffect_l() has stopped the effect if it was active so it must be restarted
864 if (effect->state() == EffectModule::ACTIVE ||
865 effect->state() == EffectModule::STOPPING) {
866 effect->start();
867 }
868
869 sp<EffectChain> dstChain = effect->chain().promote();
870 if (dstChain == 0) {
871 srcThread->addEffect_l(effect);
872 return INVALID_OPERATION;
873 }
874 AudioSystem::unregisterEffect(effect->id());
875 AudioSystem::registerEffect(&effect->desc(),
876 srcThread->id(),
877 dstChain->strategy(),
878 AUDIO_SESSION_OUTPUT_MIX,
879 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700880 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800881 }
882 status = playbackThread->attachAuxEffect(this, EffectId);
883 }
884 return status;
885}
886
887void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
888{
889 mAuxEffectId = EffectId;
890 mAuxBuffer = buffer;
891}
892
893bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
894 size_t audioHalFrames)
895{
896 // a track is considered presented when the total number of frames written to audio HAL
897 // corresponds to the number of frames written when presentationComplete() is called for the
898 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800899 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
900 // to detect when all frames have been played. In this case framesWritten isn't
901 // useful because it doesn't always reflect whether there is data in the h/w
902 // buffers, particularly if a track has been paused and resumed during draining
903 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
904 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800905 if (mPresentationCompleteFrames == 0) {
906 mPresentationCompleteFrames = framesWritten + audioHalFrames;
907 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
908 mPresentationCompleteFrames, audioHalFrames);
909 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800910
911 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800912 ALOGV("presentationComplete() session %d complete: framesWritten %d",
913 mSessionId, framesWritten);
914 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800915 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800916 return true;
917 }
918 return false;
919}
920
921void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
922{
923 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
924 if (mSyncEvents[i]->type() == type) {
925 mSyncEvents[i]->trigger();
926 mSyncEvents.removeAt(i);
927 i--;
928 }
929 }
930}
931
932// implement VolumeBufferProvider interface
933
934uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
935{
936 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
937 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800938 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800939 uint32_t vl = vlr & 0xFFFF;
940 uint32_t vr = vlr >> 16;
941 // track volumes come from shared memory, so can't be trusted and must be clamped
942 if (vl > MAX_GAIN_INT) {
943 vl = MAX_GAIN_INT;
944 }
945 if (vr > MAX_GAIN_INT) {
946 vr = MAX_GAIN_INT;
947 }
948 // now apply the cached master volume and stream type volume;
949 // this is trusted but lacks any synchronization or barrier so may be stale
950 float v = mCachedVolume;
951 vl *= v;
952 vr *= v;
953 // re-combine into U4.16
954 vlr = (vr << 16) | (vl & 0xFFFF);
955 // FIXME look at mute, pause, and stop flags
956 return vlr;
957}
958
959status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
960{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800961 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800962 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
963 (mState == STOPPED)))) {
964 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
965 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
966 event->cancel();
967 return INVALID_OPERATION;
968 }
969 (void) TrackBase::setSyncEvent(event);
970 return NO_ERROR;
971}
972
Glenn Kasten5736c352012-12-04 12:12:34 -0800973void AudioFlinger::PlaybackThread::Track::invalidate()
974{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800975 // FIXME should use proxy, and needs work
976 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700977 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800978 android_atomic_release_store(0x40000000, &cblk->mFutex);
979 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
980 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800981 mIsInvalid = true;
982}
983
Eric Laurent59fe0102013-09-27 18:48:26 -0700984void AudioFlinger::PlaybackThread::Track::signal()
985{
986 sp<ThreadBase> thread = mThread.promote();
987 if (thread != 0) {
988 PlaybackThread *t = (PlaybackThread *)thread.get();
989 Mutex::Autolock _l(t->mLock);
990 t->broadcast_l();
991 }
992}
993
Eric Laurent81784c32012-11-19 14:55:58 -0800994// ----------------------------------------------------------------------------
995
996sp<AudioFlinger::PlaybackThread::TimedTrack>
997AudioFlinger::PlaybackThread::TimedTrack::create(
998 PlaybackThread *thread,
999 const sp<Client>& client,
1000 audio_stream_type_t streamType,
1001 uint32_t sampleRate,
1002 audio_format_t format,
1003 audio_channel_mask_t channelMask,
1004 size_t frameCount,
1005 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001006 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001007 int uid)
1008{
Eric Laurent81784c32012-11-19 14:55:58 -08001009 if (!client->reserveTimedTrack())
1010 return 0;
1011
1012 return new TimedTrack(
1013 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001014 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001015}
1016
1017AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1018 PlaybackThread *thread,
1019 const sp<Client>& client,
1020 audio_stream_type_t streamType,
1021 uint32_t sampleRate,
1022 audio_format_t format,
1023 audio_channel_mask_t channelMask,
1024 size_t frameCount,
1025 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001026 int sessionId,
1027 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001028 : Track(thread, client, streamType, sampleRate, format, channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001029 frameCount, sharedBuffer, sessionId, uid, IAudioFlinger::TRACK_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001030 mQueueHeadInFlight(false),
1031 mTrimQueueHeadOnRelease(false),
1032 mFramesPendingInQueue(0),
1033 mTimedSilenceBuffer(NULL),
1034 mTimedSilenceBufferSize(0),
1035 mTimedAudioOutputOnTime(false),
1036 mMediaTimeTransformValid(false)
1037{
1038 LocalClock lc;
1039 mLocalTimeFreq = lc.getLocalFreq();
1040
1041 mLocalTimeToSampleTransform.a_zero = 0;
1042 mLocalTimeToSampleTransform.b_zero = 0;
1043 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1044 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1045 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1046 &mLocalTimeToSampleTransform.a_to_b_denom);
1047
1048 mMediaTimeToSampleTransform.a_zero = 0;
1049 mMediaTimeToSampleTransform.b_zero = 0;
1050 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1051 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1052 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1053 &mMediaTimeToSampleTransform.a_to_b_denom);
1054}
1055
1056AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1057 mClient->releaseTimedTrack();
1058 delete [] mTimedSilenceBuffer;
1059}
1060
1061status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1062 size_t size, sp<IMemory>* buffer) {
1063
1064 Mutex::Autolock _l(mTimedBufferQueueLock);
1065
1066 trimTimedBufferQueue_l();
1067
1068 // lazily initialize the shared memory heap for timed buffers
1069 if (mTimedMemoryDealer == NULL) {
1070 const int kTimedBufferHeapSize = 512 << 10;
1071
1072 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1073 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001074 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001075 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001076 }
Eric Laurent81784c32012-11-19 14:55:58 -08001077 }
1078
1079 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001080 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001081 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001082 }
1083
1084 *buffer = newBuffer;
1085 return NO_ERROR;
1086}
1087
1088// caller must hold mTimedBufferQueueLock
1089void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1090 int64_t mediaTimeNow;
1091 {
1092 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1093 if (!mMediaTimeTransformValid)
1094 return;
1095
1096 int64_t targetTimeNow;
1097 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1098 ? mCCHelper.getCommonTime(&targetTimeNow)
1099 : mCCHelper.getLocalTime(&targetTimeNow);
1100
1101 if (OK != res)
1102 return;
1103
1104 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1105 &mediaTimeNow)) {
1106 return;
1107 }
1108 }
1109
1110 size_t trimEnd;
1111 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1112 int64_t bufEnd;
1113
1114 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1115 // We have a next buffer. Just use its PTS as the PTS of the frame
1116 // following the last frame in this buffer. If the stream is sparse
1117 // (ie, there are deliberate gaps left in the stream which should be
1118 // filled with silence by the TimedAudioTrack), then this can result
1119 // in one extra buffer being left un-trimmed when it could have
1120 // been. In general, this is not typical, and we would rather
1121 // optimized away the TS calculation below for the more common case
1122 // where PTSes are contiguous.
1123 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1124 } else {
1125 // We have no next buffer. Compute the PTS of the frame following
1126 // the last frame in this buffer by computing the duration of of
1127 // this frame in media time units and adding it to the PTS of the
1128 // buffer.
1129 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1130 / mFrameSize;
1131
1132 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1133 &bufEnd)) {
1134 ALOGE("Failed to convert frame count of %lld to media time"
1135 " duration" " (scale factor %d/%u) in %s",
1136 frameCount,
1137 mMediaTimeToSampleTransform.a_to_b_numer,
1138 mMediaTimeToSampleTransform.a_to_b_denom,
1139 __PRETTY_FUNCTION__);
1140 break;
1141 }
1142 bufEnd += mTimedBufferQueue[trimEnd].pts();
1143 }
1144
1145 if (bufEnd > mediaTimeNow)
1146 break;
1147
1148 // Is the buffer we want to use in the middle of a mix operation right
1149 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1150 // from the mixer which should be coming back shortly.
1151 if (!trimEnd && mQueueHeadInFlight) {
1152 mTrimQueueHeadOnRelease = true;
1153 }
1154 }
1155
1156 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1157 if (trimStart < trimEnd) {
1158 // Update the bookkeeping for framesReady()
1159 for (size_t i = trimStart; i < trimEnd; ++i) {
1160 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1161 }
1162
1163 // Now actually remove the buffers from the queue.
1164 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1165 }
1166}
1167
1168void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1169 const char* logTag) {
1170 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1171 "%s called (reason \"%s\"), but timed buffer queue has no"
1172 " elements to trim.", __FUNCTION__, logTag);
1173
1174 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1175 mTimedBufferQueue.removeAt(0);
1176}
1177
1178void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1179 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001180 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001181 uint32_t bufBytes = buf.buffer()->size();
1182 uint32_t consumedAlready = buf.position();
1183
1184 ALOG_ASSERT(consumedAlready <= bufBytes,
1185 "Bad bookkeeping while updating frames pending. Timed buffer is"
1186 " only %u bytes long, but claims to have consumed %u"
1187 " bytes. (update reason: \"%s\")",
1188 bufBytes, consumedAlready, logTag);
1189
1190 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1191 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1192 "Bad bookkeeping while updating frames pending. Should have at"
1193 " least %u queued frames, but we think we have only %u. (update"
1194 " reason: \"%s\")",
1195 bufFrames, mFramesPendingInQueue, logTag);
1196
1197 mFramesPendingInQueue -= bufFrames;
1198}
1199
1200status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1201 const sp<IMemory>& buffer, int64_t pts) {
1202
1203 {
1204 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1205 if (!mMediaTimeTransformValid)
1206 return INVALID_OPERATION;
1207 }
1208
1209 Mutex::Autolock _l(mTimedBufferQueueLock);
1210
1211 uint32_t bufFrames = buffer->size() / mFrameSize;
1212 mFramesPendingInQueue += bufFrames;
1213 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1214
1215 return NO_ERROR;
1216}
1217
1218status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1219 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1220
1221 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1222 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1223 target);
1224
1225 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1226 target == TimedAudioTrack::COMMON_TIME)) {
1227 return BAD_VALUE;
1228 }
1229
1230 Mutex::Autolock lock(mMediaTimeTransformLock);
1231 mMediaTimeTransform = xform;
1232 mMediaTimeTransformTarget = target;
1233 mMediaTimeTransformValid = true;
1234
1235 return NO_ERROR;
1236}
1237
1238#define min(a, b) ((a) < (b) ? (a) : (b))
1239
1240// implementation of getNextBuffer for tracks whose buffers have timestamps
1241status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1242 AudioBufferProvider::Buffer* buffer, int64_t pts)
1243{
1244 if (pts == AudioBufferProvider::kInvalidPTS) {
1245 buffer->raw = NULL;
1246 buffer->frameCount = 0;
1247 mTimedAudioOutputOnTime = false;
1248 return INVALID_OPERATION;
1249 }
1250
1251 Mutex::Autolock _l(mTimedBufferQueueLock);
1252
1253 ALOG_ASSERT(!mQueueHeadInFlight,
1254 "getNextBuffer called without releaseBuffer!");
1255
1256 while (true) {
1257
1258 // if we have no timed buffers, then fail
1259 if (mTimedBufferQueue.isEmpty()) {
1260 buffer->raw = NULL;
1261 buffer->frameCount = 0;
1262 return NOT_ENOUGH_DATA;
1263 }
1264
1265 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1266
1267 // calculate the PTS of the head of the timed buffer queue expressed in
1268 // local time
1269 int64_t headLocalPTS;
1270 {
1271 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1272
1273 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1274
1275 if (mMediaTimeTransform.a_to_b_denom == 0) {
1276 // the transform represents a pause, so yield silence
1277 timedYieldSilence_l(buffer->frameCount, buffer);
1278 return NO_ERROR;
1279 }
1280
1281 int64_t transformedPTS;
1282 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1283 &transformedPTS)) {
1284 // the transform failed. this shouldn't happen, but if it does
1285 // then just drop this buffer
1286 ALOGW("timedGetNextBuffer transform failed");
1287 buffer->raw = NULL;
1288 buffer->frameCount = 0;
1289 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1290 return NO_ERROR;
1291 }
1292
1293 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1294 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1295 &headLocalPTS)) {
1296 buffer->raw = NULL;
1297 buffer->frameCount = 0;
1298 return INVALID_OPERATION;
1299 }
1300 } else {
1301 headLocalPTS = transformedPTS;
1302 }
1303 }
1304
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001305 uint32_t sr = sampleRate();
1306
Eric Laurent81784c32012-11-19 14:55:58 -08001307 // adjust the head buffer's PTS to reflect the portion of the head buffer
1308 // that has already been consumed
1309 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001310 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001311
1312 // Calculate the delta in samples between the head of the input buffer
1313 // queue and the start of the next output buffer that will be written.
1314 // If the transformation fails because of over or underflow, it means
1315 // that the sample's position in the output stream is so far out of
1316 // whack that it should just be dropped.
1317 int64_t sampleDelta;
1318 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1319 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1320 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1321 " mix");
1322 continue;
1323 }
1324 if (!mLocalTimeToSampleTransform.doForwardTransform(
1325 (effectivePTS - pts) << 32, &sampleDelta)) {
1326 ALOGV("*** too late during sample rate transform: dropped buffer");
1327 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1328 continue;
1329 }
1330
1331 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1332 " sampleDelta=[%d.%08x]",
1333 head.pts(), head.position(), pts,
1334 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1335 + (sampleDelta >> 32)),
1336 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1337
1338 // if the delta between the ideal placement for the next input sample and
1339 // the current output position is within this threshold, then we will
1340 // concatenate the next input samples to the previous output
1341 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001342 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001343
1344 // if this is the first buffer of audio that we're emitting from this track
1345 // then it should be almost exactly on time.
1346 const int64_t kSampleStartupThreshold = 1LL << 32;
1347
1348 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1349 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1350 // the next input is close enough to being on time, so concatenate it
1351 // with the last output
1352 timedYieldSamples_l(buffer);
1353
1354 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1355 head.position(), buffer->frameCount);
1356 return NO_ERROR;
1357 }
1358
1359 // Looks like our output is not on time. Reset our on timed status.
1360 // Next time we mix samples from our input queue, then should be within
1361 // the StartupThreshold.
1362 mTimedAudioOutputOnTime = false;
1363 if (sampleDelta > 0) {
1364 // the gap between the current output position and the proper start of
1365 // the next input sample is too big, so fill it with silence
1366 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1367
1368 timedYieldSilence_l(framesUntilNextInput, buffer);
1369 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1370 return NO_ERROR;
1371 } else {
1372 // the next input sample is late
1373 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1374 size_t onTimeSamplePosition =
1375 head.position() + lateFrames * mFrameSize;
1376
1377 if (onTimeSamplePosition > head.buffer()->size()) {
1378 // all the remaining samples in the head are too late, so
1379 // drop it and move on
1380 ALOGV("*** too late: dropped buffer");
1381 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1382 continue;
1383 } else {
1384 // skip over the late samples
1385 head.setPosition(onTimeSamplePosition);
1386
1387 // yield the available samples
1388 timedYieldSamples_l(buffer);
1389
1390 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1391 return NO_ERROR;
1392 }
1393 }
1394 }
1395}
1396
1397// Yield samples from the timed buffer queue head up to the given output
1398// buffer's capacity.
1399//
1400// Caller must hold mTimedBufferQueueLock
1401void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1402 AudioBufferProvider::Buffer* buffer) {
1403
1404 const TimedBuffer& head = mTimedBufferQueue[0];
1405
1406 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1407 head.position());
1408
1409 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1410 mFrameSize);
1411 size_t framesRequested = buffer->frameCount;
1412 buffer->frameCount = min(framesLeftInHead, framesRequested);
1413
1414 mQueueHeadInFlight = true;
1415 mTimedAudioOutputOnTime = true;
1416}
1417
1418// Yield samples of silence up to the given output buffer's capacity
1419//
1420// Caller must hold mTimedBufferQueueLock
1421void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1422 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1423
1424 // lazily allocate a buffer filled with silence
1425 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1426 delete [] mTimedSilenceBuffer;
1427 mTimedSilenceBufferSize = numFrames * mFrameSize;
1428 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1429 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1430 }
1431
1432 buffer->raw = mTimedSilenceBuffer;
1433 size_t framesRequested = buffer->frameCount;
1434 buffer->frameCount = min(numFrames, framesRequested);
1435
1436 mTimedAudioOutputOnTime = false;
1437}
1438
1439// AudioBufferProvider interface
1440void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1441 AudioBufferProvider::Buffer* buffer) {
1442
1443 Mutex::Autolock _l(mTimedBufferQueueLock);
1444
1445 // If the buffer which was just released is part of the buffer at the head
1446 // of the queue, be sure to update the amt of the buffer which has been
1447 // consumed. If the buffer being returned is not part of the head of the
1448 // queue, its either because the buffer is part of the silence buffer, or
1449 // because the head of the timed queue was trimmed after the mixer called
1450 // getNextBuffer but before the mixer called releaseBuffer.
1451 if (buffer->raw == mTimedSilenceBuffer) {
1452 ALOG_ASSERT(!mQueueHeadInFlight,
1453 "Queue head in flight during release of silence buffer!");
1454 goto done;
1455 }
1456
1457 ALOG_ASSERT(mQueueHeadInFlight,
1458 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1459 " head in flight.");
1460
1461 if (mTimedBufferQueue.size()) {
1462 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1463
1464 void* start = head.buffer()->pointer();
1465 void* end = reinterpret_cast<void*>(
1466 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1467 + head.buffer()->size());
1468
1469 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1470 "released buffer not within the head of the timed buffer"
1471 " queue; qHead = [%p, %p], released buffer = %p",
1472 start, end, buffer->raw);
1473
1474 head.setPosition(head.position() +
1475 (buffer->frameCount * mFrameSize));
1476 mQueueHeadInFlight = false;
1477
1478 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1479 "Bad bookkeeping during releaseBuffer! Should have at"
1480 " least %u queued frames, but we think we have only %u",
1481 buffer->frameCount, mFramesPendingInQueue);
1482
1483 mFramesPendingInQueue -= buffer->frameCount;
1484
1485 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1486 || mTrimQueueHeadOnRelease) {
1487 trimTimedBufferQueueHead_l("releaseBuffer");
1488 mTrimQueueHeadOnRelease = false;
1489 }
1490 } else {
1491 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1492 " buffers in the timed buffer queue");
1493 }
1494
1495done:
1496 buffer->raw = 0;
1497 buffer->frameCount = 0;
1498}
1499
1500size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1501 Mutex::Autolock _l(mTimedBufferQueueLock);
1502 return mFramesPendingInQueue;
1503}
1504
1505AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1506 : mPTS(0), mPosition(0) {}
1507
1508AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1509 const sp<IMemory>& buffer, int64_t pts)
1510 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1511
1512
1513// ----------------------------------------------------------------------------
1514
1515AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1516 PlaybackThread *playbackThread,
1517 DuplicatingThread *sourceThread,
1518 uint32_t sampleRate,
1519 audio_format_t format,
1520 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001521 size_t frameCount,
1522 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001523 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001524 NULL, 0, uid, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001525 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001526{
1527
1528 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001529 mOutBuffer.frameCount = 0;
1530 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001531 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001532 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001533 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001534 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001535 // since client and server are in the same process,
1536 // the buffer has the same virtual address on both sides
1537 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001538 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1539 mClientProxy->setSendLevel(0.0);
1540 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001541 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1542 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001543 } else {
1544 ALOGW("Error creating output track on thread %p", playbackThread);
1545 }
1546}
1547
1548AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1549{
1550 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001551 delete mClientProxy;
1552 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001553}
1554
1555status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1556 int triggerSession)
1557{
1558 status_t status = Track::start(event, triggerSession);
1559 if (status != NO_ERROR) {
1560 return status;
1561 }
1562
1563 mActive = true;
1564 mRetryCount = 127;
1565 return status;
1566}
1567
1568void AudioFlinger::PlaybackThread::OutputTrack::stop()
1569{
1570 Track::stop();
1571 clearBufferQueue();
1572 mOutBuffer.frameCount = 0;
1573 mActive = false;
1574}
1575
1576bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1577{
1578 Buffer *pInBuffer;
1579 Buffer inBuffer;
1580 uint32_t channelCount = mChannelCount;
1581 bool outputBufferFull = false;
1582 inBuffer.frameCount = frames;
1583 inBuffer.i16 = data;
1584
1585 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1586
1587 if (!mActive && frames != 0) {
1588 start();
1589 sp<ThreadBase> thread = mThread.promote();
1590 if (thread != 0) {
1591 MixerThread *mixerThread = (MixerThread *)thread.get();
1592 if (mFrameCount > frames) {
1593 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1594 uint32_t startFrames = (mFrameCount - frames);
1595 pInBuffer = new Buffer;
1596 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1597 pInBuffer->frameCount = startFrames;
1598 pInBuffer->i16 = pInBuffer->mBuffer;
1599 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1600 mBufferQueue.add(pInBuffer);
1601 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001602 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001603 }
1604 }
1605 }
1606 }
1607
1608 while (waitTimeLeftMs) {
1609 // First write pending buffers, then new data
1610 if (mBufferQueue.size()) {
1611 pInBuffer = mBufferQueue.itemAt(0);
1612 } else {
1613 pInBuffer = &inBuffer;
1614 }
1615
1616 if (pInBuffer->frameCount == 0) {
1617 break;
1618 }
1619
1620 if (mOutBuffer.frameCount == 0) {
1621 mOutBuffer.frameCount = pInBuffer->frameCount;
1622 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001623 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1624 if (status != NO_ERROR) {
1625 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1626 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001627 outputBufferFull = true;
1628 break;
1629 }
1630 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1631 if (waitTimeLeftMs >= waitTimeMs) {
1632 waitTimeLeftMs -= waitTimeMs;
1633 } else {
1634 waitTimeLeftMs = 0;
1635 }
1636 }
1637
1638 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1639 pInBuffer->frameCount;
1640 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001641 Proxy::Buffer buf;
1642 buf.mFrameCount = outFrames;
1643 buf.mRaw = NULL;
1644 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001645 pInBuffer->frameCount -= outFrames;
1646 pInBuffer->i16 += outFrames * channelCount;
1647 mOutBuffer.frameCount -= outFrames;
1648 mOutBuffer.i16 += outFrames * channelCount;
1649
1650 if (pInBuffer->frameCount == 0) {
1651 if (mBufferQueue.size()) {
1652 mBufferQueue.removeAt(0);
1653 delete [] pInBuffer->mBuffer;
1654 delete pInBuffer;
1655 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1656 mThread.unsafe_get(), mBufferQueue.size());
1657 } else {
1658 break;
1659 }
1660 }
1661 }
1662
1663 // If we could not write all frames, allocate a buffer and queue it for next time.
1664 if (inBuffer.frameCount) {
1665 sp<ThreadBase> thread = mThread.promote();
1666 if (thread != 0 && !thread->standby()) {
1667 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1668 pInBuffer = new Buffer;
1669 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1670 pInBuffer->frameCount = inBuffer.frameCount;
1671 pInBuffer->i16 = pInBuffer->mBuffer;
1672 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1673 sizeof(int16_t));
1674 mBufferQueue.add(pInBuffer);
1675 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1676 mThread.unsafe_get(), mBufferQueue.size());
1677 } else {
1678 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1679 mThread.unsafe_get(), this);
1680 }
1681 }
1682 }
1683
1684 // Calling write() with a 0 length buffer, means that no more data will be written:
1685 // If no more buffers are pending, fill output track buffer to make sure it is started
1686 // by output mixer.
1687 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001688 // FIXME borken, replace by getting framesReady() from proxy
1689 size_t user = 0; // was mCblk->user
1690 if (user < mFrameCount) {
1691 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001692 pInBuffer = new Buffer;
1693 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1694 pInBuffer->frameCount = frames;
1695 pInBuffer->i16 = pInBuffer->mBuffer;
1696 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1697 mBufferQueue.add(pInBuffer);
1698 } else if (mActive) {
1699 stop();
1700 }
1701 }
1702
1703 return outputBufferFull;
1704}
1705
1706status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1707 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1708{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001709 ClientProxy::Buffer buf;
1710 buf.mFrameCount = buffer->frameCount;
1711 struct timespec timeout;
1712 timeout.tv_sec = waitTimeMs / 1000;
1713 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1714 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1715 buffer->frameCount = buf.mFrameCount;
1716 buffer->raw = buf.mRaw;
1717 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001718}
1719
Eric Laurent81784c32012-11-19 14:55:58 -08001720void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1721{
1722 size_t size = mBufferQueue.size();
1723
1724 for (size_t i = 0; i < size; i++) {
1725 Buffer *pBuffer = mBufferQueue.itemAt(i);
1726 delete [] pBuffer->mBuffer;
1727 delete pBuffer;
1728 }
1729 mBufferQueue.clear();
1730}
1731
1732
1733// ----------------------------------------------------------------------------
1734// Record
1735// ----------------------------------------------------------------------------
1736
1737AudioFlinger::RecordHandle::RecordHandle(
1738 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1739 : BnAudioRecord(),
1740 mRecordTrack(recordTrack)
1741{
1742}
1743
1744AudioFlinger::RecordHandle::~RecordHandle() {
1745 stop_nonvirtual();
1746 mRecordTrack->destroy();
1747}
1748
1749sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1750 return mRecordTrack->getCblk();
1751}
1752
1753status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1754 int triggerSession) {
1755 ALOGV("RecordHandle::start()");
1756 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1757}
1758
1759void AudioFlinger::RecordHandle::stop() {
1760 stop_nonvirtual();
1761}
1762
1763void AudioFlinger::RecordHandle::stop_nonvirtual() {
1764 ALOGV("RecordHandle::stop()");
1765 mRecordTrack->stop();
1766}
1767
1768status_t AudioFlinger::RecordHandle::onTransact(
1769 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1770{
1771 return BnAudioRecord::onTransact(code, data, reply, flags);
1772}
1773
1774// ----------------------------------------------------------------------------
1775
1776// RecordTrack constructor must be called with AudioFlinger::mLock held
1777AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1778 RecordThread *thread,
1779 const sp<Client>& client,
1780 uint32_t sampleRate,
1781 audio_format_t format,
1782 audio_channel_mask_t channelMask,
1783 size_t frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001784 int sessionId,
1785 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001786 : TrackBase(thread, client, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001787 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, uid, false /*isOut*/),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001788 mOverflow(false), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0),
1789 // See real initialization of mRsmpInFront at RecordThread::start()
1790 mRsmpInUnrel(0), mRsmpInFront(0), mFramesToDrop(0), mResamplerBufferProvider(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001791{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001792 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001793 if (mCblk != NULL) {
Glenn Kasten6ae6b812013-08-05 15:16:21 -07001794 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001795 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001796
1797 uint32_t channelCount = popcount(channelMask);
1798 // FIXME I don't understand either of the channel count checks
1799 if (thread->mSampleRate != sampleRate && thread->mChannelCount <= FCC_2 &&
1800 channelCount <= FCC_2) {
1801 // sink SR
1802 mResampler = AudioResampler::create(16, thread->mChannelCount, sampleRate);
1803 // source SR
1804 mResampler->setSampleRate(thread->mSampleRate);
1805 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
1806 mResamplerBufferProvider = new ResamplerBufferProvider(this);
1807 }
Eric Laurent81784c32012-11-19 14:55:58 -08001808}
1809
1810AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1811{
1812 ALOGV("%s", __func__);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001813 delete mResampler;
1814 delete[] mRsmpOutBuffer;
1815 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001816}
1817
1818// AudioBufferProvider interface
1819status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001820 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001821{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001822 ServerProxy::Buffer buf;
1823 buf.mFrameCount = buffer->frameCount;
1824 status_t status = mServerProxy->obtainBuffer(&buf);
1825 buffer->frameCount = buf.mFrameCount;
1826 buffer->raw = buf.mRaw;
1827 if (buf.mFrameCount == 0) {
1828 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001829 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001830 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001831 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001832}
1833
1834status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1835 int triggerSession)
1836{
1837 sp<ThreadBase> thread = mThread.promote();
1838 if (thread != 0) {
1839 RecordThread *recordThread = (RecordThread *)thread.get();
1840 return recordThread->start(this, event, triggerSession);
1841 } else {
1842 return BAD_VALUE;
1843 }
1844}
1845
1846void AudioFlinger::RecordThread::RecordTrack::stop()
1847{
1848 sp<ThreadBase> thread = mThread.promote();
1849 if (thread != 0) {
1850 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001851 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001852 AudioSystem::stopInput(recordThread->id());
1853 }
1854 }
1855}
1856
1857void AudioFlinger::RecordThread::RecordTrack::destroy()
1858{
1859 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1860 sp<RecordTrack> keep(this);
1861 {
1862 sp<ThreadBase> thread = mThread.promote();
1863 if (thread != 0) {
1864 if (mState == ACTIVE || mState == RESUMING) {
1865 AudioSystem::stopInput(thread->id());
1866 }
1867 AudioSystem::releaseInput(thread->id());
1868 Mutex::Autolock _l(thread->mLock);
1869 RecordThread *recordThread = (RecordThread *) thread.get();
1870 recordThread->destroyTrack_l(this);
1871 }
1872 }
1873}
1874
Eric Laurent9a54bc22013-09-09 09:08:44 -07001875void AudioFlinger::RecordThread::RecordTrack::invalidate()
1876{
1877 // FIXME should use proxy, and needs work
1878 audio_track_cblk_t* cblk = mCblk;
1879 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1880 android_atomic_release_store(0x40000000, &cblk->mFutex);
1881 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1882 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1883}
1884
Eric Laurent81784c32012-11-19 14:55:58 -08001885
1886/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1887{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001888 result.append(" Active Client Fmt Chn mask Session S Server fCount Resampling\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001889}
1890
Marco Nelissenb2208842014-02-07 14:00:50 -08001891void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001892{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001893 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %10d\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001894 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001895 (mClient == 0) ? getpid_cached : mClient->pid(),
1896 mFormat,
1897 mChannelMask,
1898 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001899 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001900 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001901 mFrameCount,
1902 mResampler != NULL);
1903
Eric Laurent81784c32012-11-19 14:55:58 -08001904}
1905
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001906void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1907{
1908 if (event == mSyncStartEvent) {
1909 ssize_t framesToDrop = 0;
1910 sp<ThreadBase> threadBase = mThread.promote();
1911 if (threadBase != 0) {
1912 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1913 // from audio HAL
1914 framesToDrop = threadBase->mFrameCount * 2;
1915 }
1916 mFramesToDrop = framesToDrop;
1917 }
1918}
1919
1920void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1921{
1922 if (mSyncStartEvent != 0) {
1923 mSyncStartEvent->cancel();
1924 mSyncStartEvent.clear();
1925 }
1926 mFramesToDrop = 0;
1927}
1928
Eric Laurent81784c32012-11-19 14:55:58 -08001929}; // namespace android