blob: 8ffa43ed7cd97f5e74830529845532b58a7f28a4 [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);
149 if (pipeFormat != Format_Invalid) {
150 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{
Eric Laurent972a1732013-09-04 09:42:59 -0700438 result.append(" Name 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
442void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
443{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800444 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800445 if (isFastTrack()) {
446 sprintf(buffer, " F %2d", mFastIndex);
447 } else {
448 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
449 }
450 track_state state = mState;
451 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800452 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800453 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800454 } else {
455 switch (state) {
456 case IDLE:
457 stateChar = 'I';
458 break;
459 case STOPPING_1:
460 stateChar = 's';
461 break;
462 case STOPPING_2:
463 stateChar = '5';
464 break;
465 case STOPPED:
466 stateChar = 'S';
467 break;
468 case RESUMING:
469 stateChar = 'R';
470 break;
471 case ACTIVE:
472 stateChar = 'A';
473 break;
474 case PAUSING:
475 stateChar = 'p';
476 break;
477 case PAUSED:
478 stateChar = 'P';
479 break;
480 case FLUSHED:
481 stateChar = 'F';
482 break;
483 default:
484 stateChar = '?';
485 break;
486 }
Eric Laurent81784c32012-11-19 14:55:58 -0800487 }
488 char nowInUnderrun;
489 switch (mObservedUnderruns.mBitFields.mMostRecent) {
490 case UNDERRUN_FULL:
491 nowInUnderrun = ' ';
492 break;
493 case UNDERRUN_PARTIAL:
494 nowInUnderrun = '<';
495 break;
496 case UNDERRUN_EMPTY:
497 nowInUnderrun = '*';
498 break;
499 default:
500 nowInUnderrun = '?';
501 break;
502 }
Eric Laurent972a1732013-09-04 09:42:59 -0700503 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 -0700504 "%08X %08X %08X 0x%03X %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800505 (mClient == 0) ? getpid_cached : mClient->pid(),
506 mStreamType,
507 mFormat,
508 mChannelMask,
509 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800510 mFrameCount,
511 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800512 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800513 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800514 20.0 * log10((vlr & 0xFFFF) / 4096.0),
515 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700516 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -0800517 (int)mMainBuffer,
518 (int)mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700519 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700520 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800521 nowInUnderrun);
522}
523
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800524uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
525 return mAudioTrackServerProxy->getSampleRate();
526}
527
Eric Laurent81784c32012-11-19 14:55:58 -0800528// AudioBufferProvider interface
529status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800530 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800531{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800532 ServerProxy::Buffer buf;
533 size_t desiredFrames = buffer->frameCount;
534 buf.mFrameCount = desiredFrames;
535 status_t status = mServerProxy->obtainBuffer(&buf);
536 buffer->frameCount = buf.mFrameCount;
537 buffer->raw = buf.mRaw;
538 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700539 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800540 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800541 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800542}
543
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700544// releaseBuffer() is not overridden
545
546// ExtendedAudioBufferProvider interface
547
Eric Laurent81784c32012-11-19 14:55:58 -0800548// Note that framesReady() takes a mutex on the control block using tryLock().
549// This could result in priority inversion if framesReady() is called by the normal mixer,
550// as the normal mixer thread runs at lower
551// priority than the client's callback thread: there is a short window within framesReady()
552// during which the normal mixer could be preempted, and the client callback would block.
553// Another problem can occur if framesReady() is called by the fast mixer:
554// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
555// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
556size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800557 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800558}
559
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700560size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
561{
562 return mAudioTrackServerProxy->framesReleased();
563}
564
Eric Laurent81784c32012-11-19 14:55:58 -0800565// Don't call for fast tracks; the framesReady() could result in priority inversion
566bool AudioFlinger::PlaybackThread::Track::isReady() const {
Haynes Mathew George0bcfa882013-12-27 16:09:28 -0800567 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing() || isStopping()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800568 return true;
569 }
570
571 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700572 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800573 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700574 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800575 return true;
576 }
577 return false;
578}
579
Glenn Kasten0f11b512014-01-31 16:18:54 -0800580status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
581 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800582{
583 status_t status = NO_ERROR;
584 ALOGV("start(%d), calling pid %d session %d",
585 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
586
587 sp<ThreadBase> thread = mThread.promote();
588 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700589 if (isOffloaded()) {
590 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
591 Mutex::Autolock _lth(thread->mLock);
592 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700593 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
594 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700595 invalidate();
596 return PERMISSION_DENIED;
597 }
598 }
599 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800600 track_state state = mState;
601 // here the track could be either new, or restarted
602 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800603
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800604 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800605 if (mResumeToStopping) {
606 // happened we need to resume to STOPPING_1
607 mState = TrackBase::STOPPING_1;
608 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
609 } else {
610 mState = TrackBase::RESUMING;
611 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
612 }
Eric Laurent81784c32012-11-19 14:55:58 -0800613 } else {
614 mState = TrackBase::ACTIVE;
615 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
616 }
617
Eric Laurentbfb1b832013-01-07 09:53:42 -0800618 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
619 status = playbackThread->addTrack_l(this);
620 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800621 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800622 // restore previous state if start was rejected by policy manager
623 if (status == PERMISSION_DENIED) {
624 mState = state;
625 }
626 }
627 // track was already in the active list, not a problem
628 if (status == ALREADY_EXISTS) {
629 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700630 } else {
631 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
632 // It is usually unsafe to access the server proxy from a binder thread.
633 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
634 // isn't looking at this track yet: we still hold the normal mixer thread lock,
635 // and for fast tracks the track is not yet in the fast mixer thread's active set.
636 ServerProxy::Buffer buffer;
637 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700638 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800639 }
640 } else {
641 status = BAD_VALUE;
642 }
643 return status;
644}
645
646void AudioFlinger::PlaybackThread::Track::stop()
647{
648 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
649 sp<ThreadBase> thread = mThread.promote();
650 if (thread != 0) {
651 Mutex::Autolock _l(thread->mLock);
652 track_state state = mState;
653 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
654 // If the track is not active (PAUSED and buffers full), flush buffers
655 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
656 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
657 reset();
658 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800659 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800660 mState = STOPPED;
661 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800662 // For fast tracks prepareTracks_l() will set state to STOPPING_2
663 // presentation is complete
664 // For an offloaded track this starts a drain and state will
665 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800666 mState = STOPPING_1;
667 }
668 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
669 playbackThread);
670 }
Eric Laurent81784c32012-11-19 14:55:58 -0800671 }
672}
673
674void AudioFlinger::PlaybackThread::Track::pause()
675{
676 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
677 sp<ThreadBase> thread = mThread.promote();
678 if (thread != 0) {
679 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800680 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
681 switch (mState) {
682 case STOPPING_1:
683 case STOPPING_2:
684 if (!isOffloaded()) {
685 /* nothing to do if track is not offloaded */
686 break;
687 }
688
689 // Offloaded track was draining, we need to carry on draining when resumed
690 mResumeToStopping = true;
691 // fall through...
692 case ACTIVE:
693 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800694 mState = PAUSING;
695 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700696 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800697 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800698
Eric Laurentbfb1b832013-01-07 09:53:42 -0800699 default:
700 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800701 }
702 }
703}
704
705void AudioFlinger::PlaybackThread::Track::flush()
706{
707 ALOGV("flush(%d)", mName);
708 sp<ThreadBase> thread = mThread.promote();
709 if (thread != 0) {
710 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800711 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800712
713 if (isOffloaded()) {
714 // If offloaded we allow flush during any state except terminated
715 // and keep the track active to avoid problems if user is seeking
716 // rapidly and underlying hardware has a significant delay handling
717 // a pause
718 if (isTerminated()) {
719 return;
720 }
721
722 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800723 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800724
725 if (mState == STOPPING_1 || mState == STOPPING_2) {
726 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
727 mState = ACTIVE;
728 }
729
730 if (mState == ACTIVE) {
731 ALOGV("flush called in active state, resetting buffer time out retry count");
732 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
733 }
734
Haynes Mathew George7844f672014-01-15 12:32:55 -0800735 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800736 mResumeToStopping = false;
737 } else {
738 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
739 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
740 return;
741 }
742 // No point remaining in PAUSED state after a flush => go to
743 // FLUSHED state
744 mState = FLUSHED;
745 // do not reset the track if it is still in the process of being stopped or paused.
746 // this will be done by prepareTracks_l() when the track is stopped.
747 // prepareTracks_l() will see mState == FLUSHED, then
748 // remove from active track list, reset(), and trigger presentation complete
749 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
750 reset();
751 }
Eric Laurent81784c32012-11-19 14:55:58 -0800752 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800753 // Prevent flush being lost if the track is flushed and then resumed
754 // before mixer thread can run. This is important when offloading
755 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700756 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800757 }
758}
759
Haynes Mathew George7844f672014-01-15 12:32:55 -0800760// must be called with thread lock held
761void AudioFlinger::PlaybackThread::Track::flushAck()
762{
763 if (!isOffloaded())
764 return;
765
766 mFlushHwPending = false;
767}
768
Eric Laurent81784c32012-11-19 14:55:58 -0800769void AudioFlinger::PlaybackThread::Track::reset()
770{
771 // Do not reset twice to avoid discarding data written just after a flush and before
772 // the audioflinger thread detects the track is stopped.
773 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800774 // Force underrun condition to avoid false underrun callback until first data is
775 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700776 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800777 mFillingUpStatus = FS_FILLING;
778 mResetDone = true;
779 if (mState == FLUSHED) {
780 mState = IDLE;
781 }
782 }
783}
784
Eric Laurentbfb1b832013-01-07 09:53:42 -0800785status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
786{
787 sp<ThreadBase> thread = mThread.promote();
788 if (thread == 0) {
789 ALOGE("thread is dead");
790 return FAILED_TRANSACTION;
791 } else if ((thread->type() == ThreadBase::DIRECT) ||
792 (thread->type() == ThreadBase::OFFLOAD)) {
793 return thread->setParameters(keyValuePairs);
794 } else {
795 return PERMISSION_DENIED;
796 }
797}
798
Glenn Kasten573d80a2013-08-26 09:36:23 -0700799status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
800{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700801 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
802 if (isFastTrack()) {
803 return INVALID_OPERATION;
804 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700805 sp<ThreadBase> thread = mThread.promote();
806 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700807 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700808 }
809 Mutex::Autolock _l(thread->mLock);
810 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700811 if (!isOffloaded()) {
812 if (!playbackThread->mLatchQValid) {
813 return INVALID_OPERATION;
814 }
815 uint32_t unpresentedFrames =
816 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
817 playbackThread->mSampleRate;
818 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
819 if (framesWritten < unpresentedFrames) {
820 return INVALID_OPERATION;
821 }
822 timestamp.mPosition = framesWritten - unpresentedFrames;
823 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
824 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700825 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700826
827 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700828}
829
Eric Laurent81784c32012-11-19 14:55:58 -0800830status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
831{
832 status_t status = DEAD_OBJECT;
833 sp<ThreadBase> thread = mThread.promote();
834 if (thread != 0) {
835 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
836 sp<AudioFlinger> af = mClient->audioFlinger();
837
838 Mutex::Autolock _l(af->mLock);
839
840 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
841
842 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
843 Mutex::Autolock _dl(playbackThread->mLock);
844 Mutex::Autolock _sl(srcThread->mLock);
845 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
846 if (chain == 0) {
847 return INVALID_OPERATION;
848 }
849
850 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
851 if (effect == 0) {
852 return INVALID_OPERATION;
853 }
854 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700855 status = playbackThread->addEffect_l(effect);
856 if (status != NO_ERROR) {
857 srcThread->addEffect_l(effect);
858 return INVALID_OPERATION;
859 }
Eric Laurent81784c32012-11-19 14:55:58 -0800860 // removeEffect_l() has stopped the effect if it was active so it must be restarted
861 if (effect->state() == EffectModule::ACTIVE ||
862 effect->state() == EffectModule::STOPPING) {
863 effect->start();
864 }
865
866 sp<EffectChain> dstChain = effect->chain().promote();
867 if (dstChain == 0) {
868 srcThread->addEffect_l(effect);
869 return INVALID_OPERATION;
870 }
871 AudioSystem::unregisterEffect(effect->id());
872 AudioSystem::registerEffect(&effect->desc(),
873 srcThread->id(),
874 dstChain->strategy(),
875 AUDIO_SESSION_OUTPUT_MIX,
876 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700877 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800878 }
879 status = playbackThread->attachAuxEffect(this, EffectId);
880 }
881 return status;
882}
883
884void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
885{
886 mAuxEffectId = EffectId;
887 mAuxBuffer = buffer;
888}
889
890bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
891 size_t audioHalFrames)
892{
893 // a track is considered presented when the total number of frames written to audio HAL
894 // corresponds to the number of frames written when presentationComplete() is called for the
895 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800896 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
897 // to detect when all frames have been played. In this case framesWritten isn't
898 // useful because it doesn't always reflect whether there is data in the h/w
899 // buffers, particularly if a track has been paused and resumed during draining
900 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
901 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800902 if (mPresentationCompleteFrames == 0) {
903 mPresentationCompleteFrames = framesWritten + audioHalFrames;
904 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
905 mPresentationCompleteFrames, audioHalFrames);
906 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800907
908 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800909 ALOGV("presentationComplete() session %d complete: framesWritten %d",
910 mSessionId, framesWritten);
911 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800912 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800913 return true;
914 }
915 return false;
916}
917
918void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
919{
920 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
921 if (mSyncEvents[i]->type() == type) {
922 mSyncEvents[i]->trigger();
923 mSyncEvents.removeAt(i);
924 i--;
925 }
926 }
927}
928
929// implement VolumeBufferProvider interface
930
931uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
932{
933 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
934 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800935 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800936 uint32_t vl = vlr & 0xFFFF;
937 uint32_t vr = vlr >> 16;
938 // track volumes come from shared memory, so can't be trusted and must be clamped
939 if (vl > MAX_GAIN_INT) {
940 vl = MAX_GAIN_INT;
941 }
942 if (vr > MAX_GAIN_INT) {
943 vr = MAX_GAIN_INT;
944 }
945 // now apply the cached master volume and stream type volume;
946 // this is trusted but lacks any synchronization or barrier so may be stale
947 float v = mCachedVolume;
948 vl *= v;
949 vr *= v;
950 // re-combine into U4.16
951 vlr = (vr << 16) | (vl & 0xFFFF);
952 // FIXME look at mute, pause, and stop flags
953 return vlr;
954}
955
956status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
957{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800958 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800959 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
960 (mState == STOPPED)))) {
961 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
962 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
963 event->cancel();
964 return INVALID_OPERATION;
965 }
966 (void) TrackBase::setSyncEvent(event);
967 return NO_ERROR;
968}
969
Glenn Kasten5736c352012-12-04 12:12:34 -0800970void AudioFlinger::PlaybackThread::Track::invalidate()
971{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800972 // FIXME should use proxy, and needs work
973 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700974 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800975 android_atomic_release_store(0x40000000, &cblk->mFutex);
976 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
977 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800978 mIsInvalid = true;
979}
980
Eric Laurent59fe0102013-09-27 18:48:26 -0700981void AudioFlinger::PlaybackThread::Track::signal()
982{
983 sp<ThreadBase> thread = mThread.promote();
984 if (thread != 0) {
985 PlaybackThread *t = (PlaybackThread *)thread.get();
986 Mutex::Autolock _l(t->mLock);
987 t->broadcast_l();
988 }
989}
990
Eric Laurent81784c32012-11-19 14:55:58 -0800991// ----------------------------------------------------------------------------
992
993sp<AudioFlinger::PlaybackThread::TimedTrack>
994AudioFlinger::PlaybackThread::TimedTrack::create(
995 PlaybackThread *thread,
996 const sp<Client>& client,
997 audio_stream_type_t streamType,
998 uint32_t sampleRate,
999 audio_format_t format,
1000 audio_channel_mask_t channelMask,
1001 size_t frameCount,
1002 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001003 int sessionId,
1004 int uid) {
Eric Laurent81784c32012-11-19 14:55:58 -08001005 if (!client->reserveTimedTrack())
1006 return 0;
1007
1008 return new TimedTrack(
1009 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001010 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001011}
1012
1013AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1014 PlaybackThread *thread,
1015 const sp<Client>& client,
1016 audio_stream_type_t streamType,
1017 uint32_t sampleRate,
1018 audio_format_t format,
1019 audio_channel_mask_t channelMask,
1020 size_t frameCount,
1021 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001022 int sessionId,
1023 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001024 : Track(thread, client, streamType, sampleRate, format, channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001025 frameCount, sharedBuffer, sessionId, uid, IAudioFlinger::TRACK_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001026 mQueueHeadInFlight(false),
1027 mTrimQueueHeadOnRelease(false),
1028 mFramesPendingInQueue(0),
1029 mTimedSilenceBuffer(NULL),
1030 mTimedSilenceBufferSize(0),
1031 mTimedAudioOutputOnTime(false),
1032 mMediaTimeTransformValid(false)
1033{
1034 LocalClock lc;
1035 mLocalTimeFreq = lc.getLocalFreq();
1036
1037 mLocalTimeToSampleTransform.a_zero = 0;
1038 mLocalTimeToSampleTransform.b_zero = 0;
1039 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1040 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1041 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1042 &mLocalTimeToSampleTransform.a_to_b_denom);
1043
1044 mMediaTimeToSampleTransform.a_zero = 0;
1045 mMediaTimeToSampleTransform.b_zero = 0;
1046 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1047 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1048 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1049 &mMediaTimeToSampleTransform.a_to_b_denom);
1050}
1051
1052AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1053 mClient->releaseTimedTrack();
1054 delete [] mTimedSilenceBuffer;
1055}
1056
1057status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1058 size_t size, sp<IMemory>* buffer) {
1059
1060 Mutex::Autolock _l(mTimedBufferQueueLock);
1061
1062 trimTimedBufferQueue_l();
1063
1064 // lazily initialize the shared memory heap for timed buffers
1065 if (mTimedMemoryDealer == NULL) {
1066 const int kTimedBufferHeapSize = 512 << 10;
1067
1068 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1069 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001070 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001071 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001072 }
Eric Laurent81784c32012-11-19 14:55:58 -08001073 }
1074
1075 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001076 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001077 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001078 }
1079
1080 *buffer = newBuffer;
1081 return NO_ERROR;
1082}
1083
1084// caller must hold mTimedBufferQueueLock
1085void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1086 int64_t mediaTimeNow;
1087 {
1088 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1089 if (!mMediaTimeTransformValid)
1090 return;
1091
1092 int64_t targetTimeNow;
1093 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1094 ? mCCHelper.getCommonTime(&targetTimeNow)
1095 : mCCHelper.getLocalTime(&targetTimeNow);
1096
1097 if (OK != res)
1098 return;
1099
1100 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1101 &mediaTimeNow)) {
1102 return;
1103 }
1104 }
1105
1106 size_t trimEnd;
1107 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1108 int64_t bufEnd;
1109
1110 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1111 // We have a next buffer. Just use its PTS as the PTS of the frame
1112 // following the last frame in this buffer. If the stream is sparse
1113 // (ie, there are deliberate gaps left in the stream which should be
1114 // filled with silence by the TimedAudioTrack), then this can result
1115 // in one extra buffer being left un-trimmed when it could have
1116 // been. In general, this is not typical, and we would rather
1117 // optimized away the TS calculation below for the more common case
1118 // where PTSes are contiguous.
1119 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1120 } else {
1121 // We have no next buffer. Compute the PTS of the frame following
1122 // the last frame in this buffer by computing the duration of of
1123 // this frame in media time units and adding it to the PTS of the
1124 // buffer.
1125 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1126 / mFrameSize;
1127
1128 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1129 &bufEnd)) {
1130 ALOGE("Failed to convert frame count of %lld to media time"
1131 " duration" " (scale factor %d/%u) in %s",
1132 frameCount,
1133 mMediaTimeToSampleTransform.a_to_b_numer,
1134 mMediaTimeToSampleTransform.a_to_b_denom,
1135 __PRETTY_FUNCTION__);
1136 break;
1137 }
1138 bufEnd += mTimedBufferQueue[trimEnd].pts();
1139 }
1140
1141 if (bufEnd > mediaTimeNow)
1142 break;
1143
1144 // Is the buffer we want to use in the middle of a mix operation right
1145 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1146 // from the mixer which should be coming back shortly.
1147 if (!trimEnd && mQueueHeadInFlight) {
1148 mTrimQueueHeadOnRelease = true;
1149 }
1150 }
1151
1152 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1153 if (trimStart < trimEnd) {
1154 // Update the bookkeeping for framesReady()
1155 for (size_t i = trimStart; i < trimEnd; ++i) {
1156 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1157 }
1158
1159 // Now actually remove the buffers from the queue.
1160 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1161 }
1162}
1163
1164void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1165 const char* logTag) {
1166 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1167 "%s called (reason \"%s\"), but timed buffer queue has no"
1168 " elements to trim.", __FUNCTION__, logTag);
1169
1170 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1171 mTimedBufferQueue.removeAt(0);
1172}
1173
1174void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1175 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001176 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001177 uint32_t bufBytes = buf.buffer()->size();
1178 uint32_t consumedAlready = buf.position();
1179
1180 ALOG_ASSERT(consumedAlready <= bufBytes,
1181 "Bad bookkeeping while updating frames pending. Timed buffer is"
1182 " only %u bytes long, but claims to have consumed %u"
1183 " bytes. (update reason: \"%s\")",
1184 bufBytes, consumedAlready, logTag);
1185
1186 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1187 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1188 "Bad bookkeeping while updating frames pending. Should have at"
1189 " least %u queued frames, but we think we have only %u. (update"
1190 " reason: \"%s\")",
1191 bufFrames, mFramesPendingInQueue, logTag);
1192
1193 mFramesPendingInQueue -= bufFrames;
1194}
1195
1196status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1197 const sp<IMemory>& buffer, int64_t pts) {
1198
1199 {
1200 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1201 if (!mMediaTimeTransformValid)
1202 return INVALID_OPERATION;
1203 }
1204
1205 Mutex::Autolock _l(mTimedBufferQueueLock);
1206
1207 uint32_t bufFrames = buffer->size() / mFrameSize;
1208 mFramesPendingInQueue += bufFrames;
1209 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1210
1211 return NO_ERROR;
1212}
1213
1214status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1215 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1216
1217 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1218 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1219 target);
1220
1221 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1222 target == TimedAudioTrack::COMMON_TIME)) {
1223 return BAD_VALUE;
1224 }
1225
1226 Mutex::Autolock lock(mMediaTimeTransformLock);
1227 mMediaTimeTransform = xform;
1228 mMediaTimeTransformTarget = target;
1229 mMediaTimeTransformValid = true;
1230
1231 return NO_ERROR;
1232}
1233
1234#define min(a, b) ((a) < (b) ? (a) : (b))
1235
1236// implementation of getNextBuffer for tracks whose buffers have timestamps
1237status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1238 AudioBufferProvider::Buffer* buffer, int64_t pts)
1239{
1240 if (pts == AudioBufferProvider::kInvalidPTS) {
1241 buffer->raw = NULL;
1242 buffer->frameCount = 0;
1243 mTimedAudioOutputOnTime = false;
1244 return INVALID_OPERATION;
1245 }
1246
1247 Mutex::Autolock _l(mTimedBufferQueueLock);
1248
1249 ALOG_ASSERT(!mQueueHeadInFlight,
1250 "getNextBuffer called without releaseBuffer!");
1251
1252 while (true) {
1253
1254 // if we have no timed buffers, then fail
1255 if (mTimedBufferQueue.isEmpty()) {
1256 buffer->raw = NULL;
1257 buffer->frameCount = 0;
1258 return NOT_ENOUGH_DATA;
1259 }
1260
1261 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1262
1263 // calculate the PTS of the head of the timed buffer queue expressed in
1264 // local time
1265 int64_t headLocalPTS;
1266 {
1267 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1268
1269 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1270
1271 if (mMediaTimeTransform.a_to_b_denom == 0) {
1272 // the transform represents a pause, so yield silence
1273 timedYieldSilence_l(buffer->frameCount, buffer);
1274 return NO_ERROR;
1275 }
1276
1277 int64_t transformedPTS;
1278 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1279 &transformedPTS)) {
1280 // the transform failed. this shouldn't happen, but if it does
1281 // then just drop this buffer
1282 ALOGW("timedGetNextBuffer transform failed");
1283 buffer->raw = NULL;
1284 buffer->frameCount = 0;
1285 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1286 return NO_ERROR;
1287 }
1288
1289 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1290 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1291 &headLocalPTS)) {
1292 buffer->raw = NULL;
1293 buffer->frameCount = 0;
1294 return INVALID_OPERATION;
1295 }
1296 } else {
1297 headLocalPTS = transformedPTS;
1298 }
1299 }
1300
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001301 uint32_t sr = sampleRate();
1302
Eric Laurent81784c32012-11-19 14:55:58 -08001303 // adjust the head buffer's PTS to reflect the portion of the head buffer
1304 // that has already been consumed
1305 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001306 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001307
1308 // Calculate the delta in samples between the head of the input buffer
1309 // queue and the start of the next output buffer that will be written.
1310 // If the transformation fails because of over or underflow, it means
1311 // that the sample's position in the output stream is so far out of
1312 // whack that it should just be dropped.
1313 int64_t sampleDelta;
1314 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1315 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1316 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1317 " mix");
1318 continue;
1319 }
1320 if (!mLocalTimeToSampleTransform.doForwardTransform(
1321 (effectivePTS - pts) << 32, &sampleDelta)) {
1322 ALOGV("*** too late during sample rate transform: dropped buffer");
1323 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1324 continue;
1325 }
1326
1327 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1328 " sampleDelta=[%d.%08x]",
1329 head.pts(), head.position(), pts,
1330 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1331 + (sampleDelta >> 32)),
1332 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1333
1334 // if the delta between the ideal placement for the next input sample and
1335 // the current output position is within this threshold, then we will
1336 // concatenate the next input samples to the previous output
1337 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001338 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001339
1340 // if this is the first buffer of audio that we're emitting from this track
1341 // then it should be almost exactly on time.
1342 const int64_t kSampleStartupThreshold = 1LL << 32;
1343
1344 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1345 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1346 // the next input is close enough to being on time, so concatenate it
1347 // with the last output
1348 timedYieldSamples_l(buffer);
1349
1350 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1351 head.position(), buffer->frameCount);
1352 return NO_ERROR;
1353 }
1354
1355 // Looks like our output is not on time. Reset our on timed status.
1356 // Next time we mix samples from our input queue, then should be within
1357 // the StartupThreshold.
1358 mTimedAudioOutputOnTime = false;
1359 if (sampleDelta > 0) {
1360 // the gap between the current output position and the proper start of
1361 // the next input sample is too big, so fill it with silence
1362 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1363
1364 timedYieldSilence_l(framesUntilNextInput, buffer);
1365 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1366 return NO_ERROR;
1367 } else {
1368 // the next input sample is late
1369 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1370 size_t onTimeSamplePosition =
1371 head.position() + lateFrames * mFrameSize;
1372
1373 if (onTimeSamplePosition > head.buffer()->size()) {
1374 // all the remaining samples in the head are too late, so
1375 // drop it and move on
1376 ALOGV("*** too late: dropped buffer");
1377 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1378 continue;
1379 } else {
1380 // skip over the late samples
1381 head.setPosition(onTimeSamplePosition);
1382
1383 // yield the available samples
1384 timedYieldSamples_l(buffer);
1385
1386 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1387 return NO_ERROR;
1388 }
1389 }
1390 }
1391}
1392
1393// Yield samples from the timed buffer queue head up to the given output
1394// buffer's capacity.
1395//
1396// Caller must hold mTimedBufferQueueLock
1397void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1398 AudioBufferProvider::Buffer* buffer) {
1399
1400 const TimedBuffer& head = mTimedBufferQueue[0];
1401
1402 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1403 head.position());
1404
1405 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1406 mFrameSize);
1407 size_t framesRequested = buffer->frameCount;
1408 buffer->frameCount = min(framesLeftInHead, framesRequested);
1409
1410 mQueueHeadInFlight = true;
1411 mTimedAudioOutputOnTime = true;
1412}
1413
1414// Yield samples of silence up to the given output buffer's capacity
1415//
1416// Caller must hold mTimedBufferQueueLock
1417void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1418 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1419
1420 // lazily allocate a buffer filled with silence
1421 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1422 delete [] mTimedSilenceBuffer;
1423 mTimedSilenceBufferSize = numFrames * mFrameSize;
1424 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1425 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1426 }
1427
1428 buffer->raw = mTimedSilenceBuffer;
1429 size_t framesRequested = buffer->frameCount;
1430 buffer->frameCount = min(numFrames, framesRequested);
1431
1432 mTimedAudioOutputOnTime = false;
1433}
1434
1435// AudioBufferProvider interface
1436void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1437 AudioBufferProvider::Buffer* buffer) {
1438
1439 Mutex::Autolock _l(mTimedBufferQueueLock);
1440
1441 // If the buffer which was just released is part of the buffer at the head
1442 // of the queue, be sure to update the amt of the buffer which has been
1443 // consumed. If the buffer being returned is not part of the head of the
1444 // queue, its either because the buffer is part of the silence buffer, or
1445 // because the head of the timed queue was trimmed after the mixer called
1446 // getNextBuffer but before the mixer called releaseBuffer.
1447 if (buffer->raw == mTimedSilenceBuffer) {
1448 ALOG_ASSERT(!mQueueHeadInFlight,
1449 "Queue head in flight during release of silence buffer!");
1450 goto done;
1451 }
1452
1453 ALOG_ASSERT(mQueueHeadInFlight,
1454 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1455 " head in flight.");
1456
1457 if (mTimedBufferQueue.size()) {
1458 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1459
1460 void* start = head.buffer()->pointer();
1461 void* end = reinterpret_cast<void*>(
1462 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1463 + head.buffer()->size());
1464
1465 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1466 "released buffer not within the head of the timed buffer"
1467 " queue; qHead = [%p, %p], released buffer = %p",
1468 start, end, buffer->raw);
1469
1470 head.setPosition(head.position() +
1471 (buffer->frameCount * mFrameSize));
1472 mQueueHeadInFlight = false;
1473
1474 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1475 "Bad bookkeeping during releaseBuffer! Should have at"
1476 " least %u queued frames, but we think we have only %u",
1477 buffer->frameCount, mFramesPendingInQueue);
1478
1479 mFramesPendingInQueue -= buffer->frameCount;
1480
1481 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1482 || mTrimQueueHeadOnRelease) {
1483 trimTimedBufferQueueHead_l("releaseBuffer");
1484 mTrimQueueHeadOnRelease = false;
1485 }
1486 } else {
1487 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1488 " buffers in the timed buffer queue");
1489 }
1490
1491done:
1492 buffer->raw = 0;
1493 buffer->frameCount = 0;
1494}
1495
1496size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1497 Mutex::Autolock _l(mTimedBufferQueueLock);
1498 return mFramesPendingInQueue;
1499}
1500
1501AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1502 : mPTS(0), mPosition(0) {}
1503
1504AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1505 const sp<IMemory>& buffer, int64_t pts)
1506 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1507
1508
1509// ----------------------------------------------------------------------------
1510
1511AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1512 PlaybackThread *playbackThread,
1513 DuplicatingThread *sourceThread,
1514 uint32_t sampleRate,
1515 audio_format_t format,
1516 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001517 size_t frameCount,
1518 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001519 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001520 NULL, 0, uid, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001521 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001522{
1523
1524 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001525 mOutBuffer.frameCount = 0;
1526 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001527 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001528 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001529 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001530 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001531 // since client and server are in the same process,
1532 // the buffer has the same virtual address on both sides
1533 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001534 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1535 mClientProxy->setSendLevel(0.0);
1536 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001537 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1538 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001539 } else {
1540 ALOGW("Error creating output track on thread %p", playbackThread);
1541 }
1542}
1543
1544AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1545{
1546 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001547 delete mClientProxy;
1548 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001549}
1550
1551status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1552 int triggerSession)
1553{
1554 status_t status = Track::start(event, triggerSession);
1555 if (status != NO_ERROR) {
1556 return status;
1557 }
1558
1559 mActive = true;
1560 mRetryCount = 127;
1561 return status;
1562}
1563
1564void AudioFlinger::PlaybackThread::OutputTrack::stop()
1565{
1566 Track::stop();
1567 clearBufferQueue();
1568 mOutBuffer.frameCount = 0;
1569 mActive = false;
1570}
1571
1572bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1573{
1574 Buffer *pInBuffer;
1575 Buffer inBuffer;
1576 uint32_t channelCount = mChannelCount;
1577 bool outputBufferFull = false;
1578 inBuffer.frameCount = frames;
1579 inBuffer.i16 = data;
1580
1581 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1582
1583 if (!mActive && frames != 0) {
1584 start();
1585 sp<ThreadBase> thread = mThread.promote();
1586 if (thread != 0) {
1587 MixerThread *mixerThread = (MixerThread *)thread.get();
1588 if (mFrameCount > frames) {
1589 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1590 uint32_t startFrames = (mFrameCount - frames);
1591 pInBuffer = new Buffer;
1592 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1593 pInBuffer->frameCount = startFrames;
1594 pInBuffer->i16 = pInBuffer->mBuffer;
1595 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1596 mBufferQueue.add(pInBuffer);
1597 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001598 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001599 }
1600 }
1601 }
1602 }
1603
1604 while (waitTimeLeftMs) {
1605 // First write pending buffers, then new data
1606 if (mBufferQueue.size()) {
1607 pInBuffer = mBufferQueue.itemAt(0);
1608 } else {
1609 pInBuffer = &inBuffer;
1610 }
1611
1612 if (pInBuffer->frameCount == 0) {
1613 break;
1614 }
1615
1616 if (mOutBuffer.frameCount == 0) {
1617 mOutBuffer.frameCount = pInBuffer->frameCount;
1618 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001619 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1620 if (status != NO_ERROR) {
1621 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1622 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001623 outputBufferFull = true;
1624 break;
1625 }
1626 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1627 if (waitTimeLeftMs >= waitTimeMs) {
1628 waitTimeLeftMs -= waitTimeMs;
1629 } else {
1630 waitTimeLeftMs = 0;
1631 }
1632 }
1633
1634 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1635 pInBuffer->frameCount;
1636 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001637 Proxy::Buffer buf;
1638 buf.mFrameCount = outFrames;
1639 buf.mRaw = NULL;
1640 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001641 pInBuffer->frameCount -= outFrames;
1642 pInBuffer->i16 += outFrames * channelCount;
1643 mOutBuffer.frameCount -= outFrames;
1644 mOutBuffer.i16 += outFrames * channelCount;
1645
1646 if (pInBuffer->frameCount == 0) {
1647 if (mBufferQueue.size()) {
1648 mBufferQueue.removeAt(0);
1649 delete [] pInBuffer->mBuffer;
1650 delete pInBuffer;
1651 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1652 mThread.unsafe_get(), mBufferQueue.size());
1653 } else {
1654 break;
1655 }
1656 }
1657 }
1658
1659 // If we could not write all frames, allocate a buffer and queue it for next time.
1660 if (inBuffer.frameCount) {
1661 sp<ThreadBase> thread = mThread.promote();
1662 if (thread != 0 && !thread->standby()) {
1663 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1664 pInBuffer = new Buffer;
1665 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1666 pInBuffer->frameCount = inBuffer.frameCount;
1667 pInBuffer->i16 = pInBuffer->mBuffer;
1668 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1669 sizeof(int16_t));
1670 mBufferQueue.add(pInBuffer);
1671 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1672 mThread.unsafe_get(), mBufferQueue.size());
1673 } else {
1674 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1675 mThread.unsafe_get(), this);
1676 }
1677 }
1678 }
1679
1680 // Calling write() with a 0 length buffer, means that no more data will be written:
1681 // If no more buffers are pending, fill output track buffer to make sure it is started
1682 // by output mixer.
1683 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001684 // FIXME borken, replace by getting framesReady() from proxy
1685 size_t user = 0; // was mCblk->user
1686 if (user < mFrameCount) {
1687 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001688 pInBuffer = new Buffer;
1689 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1690 pInBuffer->frameCount = frames;
1691 pInBuffer->i16 = pInBuffer->mBuffer;
1692 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1693 mBufferQueue.add(pInBuffer);
1694 } else if (mActive) {
1695 stop();
1696 }
1697 }
1698
1699 return outputBufferFull;
1700}
1701
1702status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1703 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1704{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001705 ClientProxy::Buffer buf;
1706 buf.mFrameCount = buffer->frameCount;
1707 struct timespec timeout;
1708 timeout.tv_sec = waitTimeMs / 1000;
1709 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1710 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1711 buffer->frameCount = buf.mFrameCount;
1712 buffer->raw = buf.mRaw;
1713 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001714}
1715
Eric Laurent81784c32012-11-19 14:55:58 -08001716void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1717{
1718 size_t size = mBufferQueue.size();
1719
1720 for (size_t i = 0; i < size; i++) {
1721 Buffer *pBuffer = mBufferQueue.itemAt(i);
1722 delete [] pBuffer->mBuffer;
1723 delete pBuffer;
1724 }
1725 mBufferQueue.clear();
1726}
1727
1728
1729// ----------------------------------------------------------------------------
1730// Record
1731// ----------------------------------------------------------------------------
1732
1733AudioFlinger::RecordHandle::RecordHandle(
1734 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1735 : BnAudioRecord(),
1736 mRecordTrack(recordTrack)
1737{
1738}
1739
1740AudioFlinger::RecordHandle::~RecordHandle() {
1741 stop_nonvirtual();
1742 mRecordTrack->destroy();
1743}
1744
1745sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1746 return mRecordTrack->getCblk();
1747}
1748
1749status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1750 int triggerSession) {
1751 ALOGV("RecordHandle::start()");
1752 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1753}
1754
1755void AudioFlinger::RecordHandle::stop() {
1756 stop_nonvirtual();
1757}
1758
1759void AudioFlinger::RecordHandle::stop_nonvirtual() {
1760 ALOGV("RecordHandle::stop()");
1761 mRecordTrack->stop();
1762}
1763
1764status_t AudioFlinger::RecordHandle::onTransact(
1765 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1766{
1767 return BnAudioRecord::onTransact(code, data, reply, flags);
1768}
1769
1770// ----------------------------------------------------------------------------
1771
1772// RecordTrack constructor must be called with AudioFlinger::mLock held
1773AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1774 RecordThread *thread,
1775 const sp<Client>& client,
1776 uint32_t sampleRate,
1777 audio_format_t format,
1778 audio_channel_mask_t channelMask,
1779 size_t frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001780 int sessionId,
1781 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001782 : TrackBase(thread, client, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001783 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, uid, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001784 mOverflow(false)
1785{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001786 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001787 if (mCblk != NULL) {
Glenn Kasten6ae6b812013-08-05 15:16:21 -07001788 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001789 }
Eric Laurent81784c32012-11-19 14:55:58 -08001790}
1791
1792AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1793{
1794 ALOGV("%s", __func__);
1795}
1796
1797// AudioBufferProvider interface
1798status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001799 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001800{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001801 ServerProxy::Buffer buf;
1802 buf.mFrameCount = buffer->frameCount;
1803 status_t status = mServerProxy->obtainBuffer(&buf);
1804 buffer->frameCount = buf.mFrameCount;
1805 buffer->raw = buf.mRaw;
1806 if (buf.mFrameCount == 0) {
1807 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001808 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001809 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001810 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001811}
1812
1813status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1814 int triggerSession)
1815{
1816 sp<ThreadBase> thread = mThread.promote();
1817 if (thread != 0) {
1818 RecordThread *recordThread = (RecordThread *)thread.get();
1819 return recordThread->start(this, event, triggerSession);
1820 } else {
1821 return BAD_VALUE;
1822 }
1823}
1824
1825void AudioFlinger::RecordThread::RecordTrack::stop()
1826{
1827 sp<ThreadBase> thread = mThread.promote();
1828 if (thread != 0) {
1829 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001830 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001831 AudioSystem::stopInput(recordThread->id());
1832 }
1833 }
1834}
1835
1836void AudioFlinger::RecordThread::RecordTrack::destroy()
1837{
1838 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1839 sp<RecordTrack> keep(this);
1840 {
1841 sp<ThreadBase> thread = mThread.promote();
1842 if (thread != 0) {
1843 if (mState == ACTIVE || mState == RESUMING) {
1844 AudioSystem::stopInput(thread->id());
1845 }
1846 AudioSystem::releaseInput(thread->id());
1847 Mutex::Autolock _l(thread->mLock);
1848 RecordThread *recordThread = (RecordThread *) thread.get();
1849 recordThread->destroyTrack_l(this);
1850 }
1851 }
1852}
1853
Eric Laurent9a54bc22013-09-09 09:08:44 -07001854void AudioFlinger::RecordThread::RecordTrack::invalidate()
1855{
1856 // FIXME should use proxy, and needs work
1857 audio_track_cblk_t* cblk = mCblk;
1858 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1859 android_atomic_release_store(0x40000000, &cblk->mFutex);
1860 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1861 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1862}
1863
Eric Laurent81784c32012-11-19 14:55:58 -08001864
1865/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1866{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001867 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001868}
1869
1870void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1871{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001872 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001873 (mClient == 0) ? getpid_cached : mClient->pid(),
1874 mFormat,
1875 mChannelMask,
1876 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001877 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001878 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001879 mFrameCount);
1880}
1881
Eric Laurent81784c32012-11-19 14:55:58 -08001882}; // namespace android