blob: d1bcb0b878273dac37bdd8f18ddb89de2b35e1e3 [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 Nelissen9cae2172013-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 Nelissen9cae2172013-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);
Andy Hung64e843f2017-02-13 18:48:39 -0800111
112 size_t bufferSize = sharedBuffer == NULL ? roundup(frameCount) : frameCount;
113 // check overflow when computing bufferSize due to multiplication by mFrameSize.
114 if (bufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
115 || mFrameSize == 0 // format needs to be correct
116 || bufferSize > SIZE_MAX / mFrameSize) {
117 android_errorWriteLog(0x534e4554, "34749571");
118 return;
119 }
120 bufferSize *= mFrameSize;
121
Eric Laurent81784c32012-11-19 14:55:58 -0800122 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent81784c32012-11-19 14:55:58 -0800123 if (sharedBuffer == 0) {
Andy Hung64e843f2017-02-13 18:48:39 -0800124 // check overflow when computing allocation size for streaming tracks.
125 if (size > SIZE_MAX - bufferSize) {
126 android_errorWriteLog(0x534e4554, "34749571");
127 return;
128 }
Eric Laurent81784c32012-11-19 14:55:58 -0800129 size += bufferSize;
130 }
131
132 if (client != 0) {
133 mCblkMemory = client->heap()->allocate(size);
134 if (mCblkMemory != 0) {
135 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
136 // can't assume mCblk != NULL
137 } else {
138 ALOGE("not enough memory for AudioTrack size=%u", size);
139 client->heap()->dump("AudioTrack");
140 return;
141 }
142 } else {
Andy Hung1159ffd2017-02-13 18:50:48 -0800143 mCblk = (audio_track_cblk_t *) malloc(size);
144 if (mCblk == NULL) {
145 ALOGE("not enough memory for AudioTrack size=%zu", size);
146 return;
147 }
Eric Laurent81784c32012-11-19 14:55:58 -0800148 }
149
150 // construct the shared structure in-place.
151 if (mCblk != NULL) {
152 new(mCblk) audio_track_cblk_t();
153 // clear all buffers
154 mCblk->frameCount_ = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800155 if (sharedBuffer == 0) {
156 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
157 memset(mBuffer, 0, bufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -0800158 } else {
159 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800160#if 0
Glenn Kasten96f60d82013-07-12 10:21:18 -0700161 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800162#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800163 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800164
Glenn Kasten46909e72013-02-26 09:20:22 -0800165#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800166 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800167 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
168 if (pipeFormat != Format_Invalid) {
169 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
170 size_t numCounterOffers = 0;
171 const NBAIO_Format offers[1] = {pipeFormat};
172 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
173 ALOG_ASSERT(index == 0);
174 PipeReader *pipeReader = new PipeReader(*pipe);
175 numCounterOffers = 0;
176 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
177 ALOG_ASSERT(index == 0);
178 mTeeSink = pipe;
179 mTeeSource = pipeReader;
180 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800181 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800182#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800183
Eric Laurent81784c32012-11-19 14:55:58 -0800184 }
185}
186
187AudioFlinger::ThreadBase::TrackBase::~TrackBase()
188{
Glenn Kasten46909e72013-02-26 09:20:22 -0800189#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800190 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800191#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800192 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
193 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800194 if (mCblk != NULL) {
Andy Hung1159ffd2017-02-13 18:50:48 -0800195 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurent81784c32012-11-19 14:55:58 -0800196 if (mClient == 0) {
Andy Hung1159ffd2017-02-13 18:50:48 -0800197 free(mCblk);
Eric Laurent81784c32012-11-19 14:55:58 -0800198 }
199 }
200 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
201 if (mClient != 0) {
202 // Client destructor must run with AudioFlinger mutex locked
203 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
204 // If the client's reference count drops to zero, the associated destructor
205 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
206 // relying on the automatic clear() at end of scope.
207 mClient.clear();
208 }
209}
210
211// AudioBufferProvider interface
212// getNextBuffer() = 0;
213// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
214void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
215{
Glenn Kasten46909e72013-02-26 09:20:22 -0800216#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800217 if (mTeeSink != 0) {
218 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
219 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800220#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800221
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800222 ServerProxy::Buffer buf;
223 buf.mFrameCount = buffer->frameCount;
224 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800225 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800226 buffer->raw = NULL;
227 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800228}
229
Eric Laurent81784c32012-11-19 14:55:58 -0800230status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
231{
232 mSyncEvents.add(event);
233 return NO_ERROR;
234}
235
236// ----------------------------------------------------------------------------
237// Playback
238// ----------------------------------------------------------------------------
239
240AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
241 : BnAudioTrack(),
242 mTrack(track)
243{
244}
245
246AudioFlinger::TrackHandle::~TrackHandle() {
247 // just stop the track on deletion, associated resources
248 // will be freed from the main thread once all pending buffers have
249 // been played. Unless it's not in the active track list, in which
250 // case we free everything now...
251 mTrack->destroy();
252}
253
254sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
255 return mTrack->getCblk();
256}
257
258status_t AudioFlinger::TrackHandle::start() {
259 return mTrack->start();
260}
261
262void AudioFlinger::TrackHandle::stop() {
263 mTrack->stop();
264}
265
266void AudioFlinger::TrackHandle::flush() {
267 mTrack->flush();
268}
269
Eric Laurent81784c32012-11-19 14:55:58 -0800270void AudioFlinger::TrackHandle::pause() {
271 mTrack->pause();
272}
273
274status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
275{
276 return mTrack->attachAuxEffect(EffectId);
277}
278
279status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
280 sp<IMemory>* buffer) {
281 if (!mTrack->isTimedTrack())
282 return INVALID_OPERATION;
283
284 PlaybackThread::TimedTrack* tt =
285 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
286 return tt->allocateTimedBuffer(size, buffer);
287}
288
289status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
290 int64_t pts) {
291 if (!mTrack->isTimedTrack())
292 return INVALID_OPERATION;
293
294 PlaybackThread::TimedTrack* tt =
295 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
296 return tt->queueTimedBuffer(buffer, pts);
297}
298
299status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
300 const LinearTransform& xform, int target) {
301
302 if (!mTrack->isTimedTrack())
303 return INVALID_OPERATION;
304
305 PlaybackThread::TimedTrack* tt =
306 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
307 return tt->setMediaTimeTransform(
308 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
309}
310
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700311status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
312 return mTrack->setParameters(keyValuePairs);
313}
314
Glenn Kasten53cec222013-08-29 09:01:02 -0700315status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
316{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700317 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700318}
319
Eric Laurent59fe0102013-09-27 18:48:26 -0700320
321void AudioFlinger::TrackHandle::signal()
322{
323 return mTrack->signal();
324}
325
Eric Laurent81784c32012-11-19 14:55:58 -0800326status_t AudioFlinger::TrackHandle::onTransact(
327 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
328{
329 return BnAudioTrack::onTransact(code, data, reply, flags);
330}
331
332// ----------------------------------------------------------------------------
333
334// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
335AudioFlinger::PlaybackThread::Track::Track(
336 PlaybackThread *thread,
337 const sp<Client>& client,
338 audio_stream_type_t streamType,
339 uint32_t sampleRate,
340 audio_format_t format,
341 audio_channel_mask_t channelMask,
342 size_t frameCount,
343 const sp<IMemory>& sharedBuffer,
344 int sessionId,
Marco Nelissen9cae2172013-01-14 14:12:05 -0800345 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -0800346 IAudioFlinger::track_flags_t flags)
347 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Marco Nelissen9cae2172013-01-14 14:12:05 -0800348 sessionId, uid, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800349 mFillingUpStatus(FS_INVALID),
350 // mRetryCount initialized later when needed
351 mSharedBuffer(sharedBuffer),
352 mStreamType(streamType),
353 mName(-1), // see note below
354 mMainBuffer(thread->mixBuffer()),
355 mAuxBuffer(NULL),
356 mAuxEffectId(0), mHasVolumeController(false),
357 mPresentationCompleteFrames(0),
358 mFlags(flags),
359 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800360 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800361 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800362 mAudioTrackServerProxy(NULL),
363 mResumeToStopping(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800364{
365 if (mCblk != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800366 if (sharedBuffer == 0) {
367 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
368 mFrameSize);
369 } else {
370 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
371 mFrameSize);
372 }
373 mServerProxy = mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800374 // to avoid leaking a track name, do not allocate one unless there is an mCblk
375 mName = thread->getTrackName_l(channelMask, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800376 if (mName < 0) {
377 ALOGE("no more track names available");
378 return;
379 }
380 // only allocate a fast track index if we were able to allocate a normal track name
381 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800382 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Eric Laurent81784c32012-11-19 14:55:58 -0800383 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
384 int i = __builtin_ctz(thread->mFastTrackAvailMask);
385 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
386 // FIXME This is too eager. We allocate a fast track index before the
387 // fast track becomes active. Since fast tracks are a scarce resource,
388 // this means we are potentially denying other more important fast tracks from
389 // being created. It would be better to allocate the index dynamically.
390 mFastIndex = i;
Eric Laurent81784c32012-11-19 14:55:58 -0800391 // Read the initial underruns because this field is never cleared by the fast mixer
392 mObservedUnderruns = thread->getFastTrackUnderruns(i);
393 thread->mFastTrackAvailMask &= ~(1 << i);
394 }
395 }
396 ALOGV("Track constructor name %d, calling pid %d", mName,
397 IPCThreadState::self()->getCallingPid());
398}
399
400AudioFlinger::PlaybackThread::Track::~Track()
401{
402 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700403
404 // The destructor would clear mSharedBuffer,
405 // but it will not push the decremented reference count,
406 // leaving the client's IMemory dangling indefinitely.
407 // This prevents that leak.
408 if (mSharedBuffer != 0) {
409 mSharedBuffer.clear();
410 // flush the binder command buffer
411 IPCThreadState::self()->flushCommands();
412 }
Eric Laurent81784c32012-11-19 14:55:58 -0800413}
414
415void AudioFlinger::PlaybackThread::Track::destroy()
416{
417 // NOTE: destroyTrack_l() can remove a strong reference to this Track
418 // by removing it from mTracks vector, so there is a risk that this Tracks's
419 // destructor is called. As the destructor needs to lock mLock,
420 // we must acquire a strong reference on this Track before locking mLock
421 // here so that the destructor is called only when exiting this function.
422 // On the other hand, as long as Track::destroy() is only called by
423 // TrackHandle destructor, the TrackHandle still holds a strong ref on
424 // this Track with its member mTrack.
425 sp<Track> keep(this);
426 { // scope for mLock
427 sp<ThreadBase> thread = mThread.promote();
428 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800429 Mutex::Autolock _l(thread->mLock);
430 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800431 bool wasActive = playbackThread->destroyTrack_l(this);
432 if (!isOutputTrack() && !wasActive) {
433 AudioSystem::releaseOutput(thread->id());
434 }
Eric Laurent81784c32012-11-19 14:55:58 -0800435 }
436 }
437}
438
439/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
440{
Eric Laurent972a1732013-09-04 09:42:59 -0700441 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700442 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800443}
444
445void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
446{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800447 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800448 if (isFastTrack()) {
449 sprintf(buffer, " F %2d", mFastIndex);
450 } else {
451 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
452 }
453 track_state state = mState;
454 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800455 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800456 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800457 } else {
458 switch (state) {
459 case IDLE:
460 stateChar = 'I';
461 break;
462 case STOPPING_1:
463 stateChar = 's';
464 break;
465 case STOPPING_2:
466 stateChar = '5';
467 break;
468 case STOPPED:
469 stateChar = 'S';
470 break;
471 case RESUMING:
472 stateChar = 'R';
473 break;
474 case ACTIVE:
475 stateChar = 'A';
476 break;
477 case PAUSING:
478 stateChar = 'p';
479 break;
480 case PAUSED:
481 stateChar = 'P';
482 break;
483 case FLUSHED:
484 stateChar = 'F';
485 break;
486 default:
487 stateChar = '?';
488 break;
489 }
Eric Laurent81784c32012-11-19 14:55:58 -0800490 }
491 char nowInUnderrun;
492 switch (mObservedUnderruns.mBitFields.mMostRecent) {
493 case UNDERRUN_FULL:
494 nowInUnderrun = ' ';
495 break;
496 case UNDERRUN_PARTIAL:
497 nowInUnderrun = '<';
498 break;
499 case UNDERRUN_EMPTY:
500 nowInUnderrun = '*';
501 break;
502 default:
503 nowInUnderrun = '?';
504 break;
505 }
Eric Laurent972a1732013-09-04 09:42:59 -0700506 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 -0700507 "%08X %08X %08X 0x%03X %9u%c\n",
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,
Eric Laurent81784c32012-11-19 14:55:58 -0800520 (int)mMainBuffer,
521 (int)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(
533 AudioBufferProvider::Buffer* buffer, int64_t pts)
534{
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 Georgee0cd1052013-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
583status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
584 int triggerSession)
585{
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
738 mResumeToStopping = false;
739 } else {
740 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
741 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
742 return;
743 }
744 // No point remaining in PAUSED state after a flush => go to
745 // FLUSHED state
746 mState = FLUSHED;
747 // do not reset the track if it is still in the process of being stopped or paused.
748 // this will be done by prepareTracks_l() when the track is stopped.
749 // prepareTracks_l() will see mState == FLUSHED, then
750 // remove from active track list, reset(), and trigger presentation complete
751 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
752 reset();
753 }
Eric Laurent81784c32012-11-19 14:55:58 -0800754 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800755 // Prevent flush being lost if the track is flushed and then resumed
756 // before mixer thread can run. This is important when offloading
757 // because the hardware buffer could hold a large amount of audio
758 playbackThread->flushOutput_l();
Eric Laurentede6c3b2013-09-19 14:37:46 -0700759 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800760 }
761}
762
763void AudioFlinger::PlaybackThread::Track::reset()
764{
765 // Do not reset twice to avoid discarding data written just after a flush and before
766 // the audioflinger thread detects the track is stopped.
767 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800768 // Force underrun condition to avoid false underrun callback until first data is
769 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700770 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800771 mFillingUpStatus = FS_FILLING;
772 mResetDone = true;
773 if (mState == FLUSHED) {
774 mState = IDLE;
775 }
776 }
777}
778
Eric Laurentbfb1b832013-01-07 09:53:42 -0800779status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
780{
781 sp<ThreadBase> thread = mThread.promote();
782 if (thread == 0) {
783 ALOGE("thread is dead");
784 return FAILED_TRANSACTION;
785 } else if ((thread->type() == ThreadBase::DIRECT) ||
786 (thread->type() == ThreadBase::OFFLOAD)) {
787 return thread->setParameters(keyValuePairs);
788 } else {
789 return PERMISSION_DENIED;
790 }
791}
792
Glenn Kasten573d80a2013-08-26 09:36:23 -0700793status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
794{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700795 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
796 if (isFastTrack()) {
797 return INVALID_OPERATION;
798 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700799 sp<ThreadBase> thread = mThread.promote();
800 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700801 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700802 }
803 Mutex::Autolock _l(thread->mLock);
804 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700805 if (!isOffloaded()) {
806 if (!playbackThread->mLatchQValid) {
807 return INVALID_OPERATION;
808 }
809 uint32_t unpresentedFrames =
810 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
811 playbackThread->mSampleRate;
812 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
813 if (framesWritten < unpresentedFrames) {
814 return INVALID_OPERATION;
815 }
816 timestamp.mPosition = framesWritten - unpresentedFrames;
817 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
818 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700819 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700820
821 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700822}
823
Eric Laurent81784c32012-11-19 14:55:58 -0800824status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
825{
826 status_t status = DEAD_OBJECT;
827 sp<ThreadBase> thread = mThread.promote();
828 if (thread != 0) {
829 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
830 sp<AudioFlinger> af = mClient->audioFlinger();
831
832 Mutex::Autolock _l(af->mLock);
833
834 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
835
836 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
837 Mutex::Autolock _dl(playbackThread->mLock);
838 Mutex::Autolock _sl(srcThread->mLock);
839 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
840 if (chain == 0) {
841 return INVALID_OPERATION;
842 }
843
844 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
845 if (effect == 0) {
846 return INVALID_OPERATION;
847 }
848 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700849 status = playbackThread->addEffect_l(effect);
850 if (status != NO_ERROR) {
851 srcThread->addEffect_l(effect);
852 return INVALID_OPERATION;
853 }
Eric Laurent81784c32012-11-19 14:55:58 -0800854 // removeEffect_l() has stopped the effect if it was active so it must be restarted
855 if (effect->state() == EffectModule::ACTIVE ||
856 effect->state() == EffectModule::STOPPING) {
857 effect->start();
858 }
859
860 sp<EffectChain> dstChain = effect->chain().promote();
861 if (dstChain == 0) {
862 srcThread->addEffect_l(effect);
863 return INVALID_OPERATION;
864 }
865 AudioSystem::unregisterEffect(effect->id());
866 AudioSystem::registerEffect(&effect->desc(),
867 srcThread->id(),
868 dstChain->strategy(),
869 AUDIO_SESSION_OUTPUT_MIX,
870 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700871 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800872 }
873 status = playbackThread->attachAuxEffect(this, EffectId);
874 }
875 return status;
876}
877
878void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
879{
880 mAuxEffectId = EffectId;
881 mAuxBuffer = buffer;
882}
883
884bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
885 size_t audioHalFrames)
886{
887 // a track is considered presented when the total number of frames written to audio HAL
888 // corresponds to the number of frames written when presentationComplete() is called for the
889 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800890 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
891 // to detect when all frames have been played. In this case framesWritten isn't
892 // useful because it doesn't always reflect whether there is data in the h/w
893 // buffers, particularly if a track has been paused and resumed during draining
894 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
895 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800896 if (mPresentationCompleteFrames == 0) {
897 mPresentationCompleteFrames = framesWritten + audioHalFrames;
898 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
899 mPresentationCompleteFrames, audioHalFrames);
900 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800901
902 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800903 ALOGV("presentationComplete() session %d complete: framesWritten %d",
904 mSessionId, framesWritten);
905 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800906 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800907 return true;
908 }
909 return false;
910}
911
912void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
913{
914 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
915 if (mSyncEvents[i]->type() == type) {
916 mSyncEvents[i]->trigger();
917 mSyncEvents.removeAt(i);
918 i--;
919 }
920 }
921}
922
923// implement VolumeBufferProvider interface
924
925uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
926{
927 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
928 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800929 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800930 uint32_t vl = vlr & 0xFFFF;
931 uint32_t vr = vlr >> 16;
932 // track volumes come from shared memory, so can't be trusted and must be clamped
933 if (vl > MAX_GAIN_INT) {
934 vl = MAX_GAIN_INT;
935 }
936 if (vr > MAX_GAIN_INT) {
937 vr = MAX_GAIN_INT;
938 }
939 // now apply the cached master volume and stream type volume;
940 // this is trusted but lacks any synchronization or barrier so may be stale
941 float v = mCachedVolume;
942 vl *= v;
943 vr *= v;
944 // re-combine into U4.16
945 vlr = (vr << 16) | (vl & 0xFFFF);
946 // FIXME look at mute, pause, and stop flags
947 return vlr;
948}
949
950status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
951{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800952 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800953 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
954 (mState == STOPPED)))) {
955 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
956 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
957 event->cancel();
958 return INVALID_OPERATION;
959 }
960 (void) TrackBase::setSyncEvent(event);
961 return NO_ERROR;
962}
963
Glenn Kasten5736c352012-12-04 12:12:34 -0800964void AudioFlinger::PlaybackThread::Track::invalidate()
965{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800966 // FIXME should use proxy, and needs work
967 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700968 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800969 android_atomic_release_store(0x40000000, &cblk->mFutex);
970 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
971 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800972 mIsInvalid = true;
973}
974
Eric Laurent59fe0102013-09-27 18:48:26 -0700975void AudioFlinger::PlaybackThread::Track::signal()
976{
977 sp<ThreadBase> thread = mThread.promote();
978 if (thread != 0) {
979 PlaybackThread *t = (PlaybackThread *)thread.get();
980 Mutex::Autolock _l(t->mLock);
981 t->broadcast_l();
982 }
983}
984
Eric Laurent81784c32012-11-19 14:55:58 -0800985// ----------------------------------------------------------------------------
986
987sp<AudioFlinger::PlaybackThread::TimedTrack>
988AudioFlinger::PlaybackThread::TimedTrack::create(
989 PlaybackThread *thread,
990 const sp<Client>& client,
991 audio_stream_type_t streamType,
992 uint32_t sampleRate,
993 audio_format_t format,
994 audio_channel_mask_t channelMask,
995 size_t frameCount,
996 const sp<IMemory>& sharedBuffer,
Marco Nelissen9cae2172013-01-14 14:12:05 -0800997 int sessionId,
998 int uid) {
Eric Laurent81784c32012-11-19 14:55:58 -0800999 if (!client->reserveTimedTrack())
1000 return 0;
1001
1002 return new TimedTrack(
1003 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001004 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001005}
1006
1007AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1008 PlaybackThread *thread,
1009 const sp<Client>& client,
1010 audio_stream_type_t streamType,
1011 uint32_t sampleRate,
1012 audio_format_t format,
1013 audio_channel_mask_t channelMask,
1014 size_t frameCount,
1015 const sp<IMemory>& sharedBuffer,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001016 int sessionId,
1017 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001018 : Track(thread, client, streamType, sampleRate, format, channelMask,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001019 frameCount, sharedBuffer, sessionId, uid, IAudioFlinger::TRACK_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001020 mQueueHeadInFlight(false),
1021 mTrimQueueHeadOnRelease(false),
1022 mFramesPendingInQueue(0),
1023 mTimedSilenceBuffer(NULL),
1024 mTimedSilenceBufferSize(0),
1025 mTimedAudioOutputOnTime(false),
1026 mMediaTimeTransformValid(false)
1027{
1028 LocalClock lc;
1029 mLocalTimeFreq = lc.getLocalFreq();
1030
1031 mLocalTimeToSampleTransform.a_zero = 0;
1032 mLocalTimeToSampleTransform.b_zero = 0;
1033 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1034 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1035 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1036 &mLocalTimeToSampleTransform.a_to_b_denom);
1037
1038 mMediaTimeToSampleTransform.a_zero = 0;
1039 mMediaTimeToSampleTransform.b_zero = 0;
1040 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1041 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1042 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1043 &mMediaTimeToSampleTransform.a_to_b_denom);
1044}
1045
1046AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1047 mClient->releaseTimedTrack();
1048 delete [] mTimedSilenceBuffer;
1049}
1050
1051status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1052 size_t size, sp<IMemory>* buffer) {
1053
1054 Mutex::Autolock _l(mTimedBufferQueueLock);
1055
1056 trimTimedBufferQueue_l();
1057
1058 // lazily initialize the shared memory heap for timed buffers
1059 if (mTimedMemoryDealer == NULL) {
1060 const int kTimedBufferHeapSize = 512 << 10;
1061
1062 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1063 "AudioFlingerTimed");
1064 if (mTimedMemoryDealer == NULL)
1065 return NO_MEMORY;
1066 }
1067
1068 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
1069 if (newBuffer == NULL) {
1070 newBuffer = mTimedMemoryDealer->allocate(size);
1071 if (newBuffer == NULL)
1072 return NO_MEMORY;
1073 }
1074
1075 *buffer = newBuffer;
1076 return NO_ERROR;
1077}
1078
1079// caller must hold mTimedBufferQueueLock
1080void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1081 int64_t mediaTimeNow;
1082 {
1083 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1084 if (!mMediaTimeTransformValid)
1085 return;
1086
1087 int64_t targetTimeNow;
1088 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1089 ? mCCHelper.getCommonTime(&targetTimeNow)
1090 : mCCHelper.getLocalTime(&targetTimeNow);
1091
1092 if (OK != res)
1093 return;
1094
1095 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1096 &mediaTimeNow)) {
1097 return;
1098 }
1099 }
1100
1101 size_t trimEnd;
1102 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1103 int64_t bufEnd;
1104
1105 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1106 // We have a next buffer. Just use its PTS as the PTS of the frame
1107 // following the last frame in this buffer. If the stream is sparse
1108 // (ie, there are deliberate gaps left in the stream which should be
1109 // filled with silence by the TimedAudioTrack), then this can result
1110 // in one extra buffer being left un-trimmed when it could have
1111 // been. In general, this is not typical, and we would rather
1112 // optimized away the TS calculation below for the more common case
1113 // where PTSes are contiguous.
1114 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1115 } else {
1116 // We have no next buffer. Compute the PTS of the frame following
1117 // the last frame in this buffer by computing the duration of of
1118 // this frame in media time units and adding it to the PTS of the
1119 // buffer.
1120 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1121 / mFrameSize;
1122
1123 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1124 &bufEnd)) {
1125 ALOGE("Failed to convert frame count of %lld to media time"
1126 " duration" " (scale factor %d/%u) in %s",
1127 frameCount,
1128 mMediaTimeToSampleTransform.a_to_b_numer,
1129 mMediaTimeToSampleTransform.a_to_b_denom,
1130 __PRETTY_FUNCTION__);
1131 break;
1132 }
1133 bufEnd += mTimedBufferQueue[trimEnd].pts();
1134 }
1135
1136 if (bufEnd > mediaTimeNow)
1137 break;
1138
1139 // Is the buffer we want to use in the middle of a mix operation right
1140 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1141 // from the mixer which should be coming back shortly.
1142 if (!trimEnd && mQueueHeadInFlight) {
1143 mTrimQueueHeadOnRelease = true;
1144 }
1145 }
1146
1147 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1148 if (trimStart < trimEnd) {
1149 // Update the bookkeeping for framesReady()
1150 for (size_t i = trimStart; i < trimEnd; ++i) {
1151 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1152 }
1153
1154 // Now actually remove the buffers from the queue.
1155 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1156 }
1157}
1158
1159void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1160 const char* logTag) {
1161 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1162 "%s called (reason \"%s\"), but timed buffer queue has no"
1163 " elements to trim.", __FUNCTION__, logTag);
1164
1165 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1166 mTimedBufferQueue.removeAt(0);
1167}
1168
1169void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1170 const TimedBuffer& buf,
1171 const char* logTag) {
1172 uint32_t bufBytes = buf.buffer()->size();
1173 uint32_t consumedAlready = buf.position();
1174
1175 ALOG_ASSERT(consumedAlready <= bufBytes,
1176 "Bad bookkeeping while updating frames pending. Timed buffer is"
1177 " only %u bytes long, but claims to have consumed %u"
1178 " bytes. (update reason: \"%s\")",
1179 bufBytes, consumedAlready, logTag);
1180
1181 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1182 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1183 "Bad bookkeeping while updating frames pending. Should have at"
1184 " least %u queued frames, but we think we have only %u. (update"
1185 " reason: \"%s\")",
1186 bufFrames, mFramesPendingInQueue, logTag);
1187
1188 mFramesPendingInQueue -= bufFrames;
1189}
1190
1191status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1192 const sp<IMemory>& buffer, int64_t pts) {
1193
1194 {
1195 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1196 if (!mMediaTimeTransformValid)
1197 return INVALID_OPERATION;
1198 }
1199
1200 Mutex::Autolock _l(mTimedBufferQueueLock);
1201
1202 uint32_t bufFrames = buffer->size() / mFrameSize;
1203 mFramesPendingInQueue += bufFrames;
1204 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1205
1206 return NO_ERROR;
1207}
1208
1209status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1210 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1211
1212 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1213 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1214 target);
1215
1216 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1217 target == TimedAudioTrack::COMMON_TIME)) {
1218 return BAD_VALUE;
1219 }
1220
1221 Mutex::Autolock lock(mMediaTimeTransformLock);
1222 mMediaTimeTransform = xform;
1223 mMediaTimeTransformTarget = target;
1224 mMediaTimeTransformValid = true;
1225
1226 return NO_ERROR;
1227}
1228
1229#define min(a, b) ((a) < (b) ? (a) : (b))
1230
1231// implementation of getNextBuffer for tracks whose buffers have timestamps
1232status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1233 AudioBufferProvider::Buffer* buffer, int64_t pts)
1234{
1235 if (pts == AudioBufferProvider::kInvalidPTS) {
1236 buffer->raw = NULL;
1237 buffer->frameCount = 0;
1238 mTimedAudioOutputOnTime = false;
1239 return INVALID_OPERATION;
1240 }
1241
1242 Mutex::Autolock _l(mTimedBufferQueueLock);
1243
1244 ALOG_ASSERT(!mQueueHeadInFlight,
1245 "getNextBuffer called without releaseBuffer!");
1246
1247 while (true) {
1248
1249 // if we have no timed buffers, then fail
1250 if (mTimedBufferQueue.isEmpty()) {
1251 buffer->raw = NULL;
1252 buffer->frameCount = 0;
1253 return NOT_ENOUGH_DATA;
1254 }
1255
1256 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1257
1258 // calculate the PTS of the head of the timed buffer queue expressed in
1259 // local time
1260 int64_t headLocalPTS;
1261 {
1262 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1263
1264 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1265
1266 if (mMediaTimeTransform.a_to_b_denom == 0) {
1267 // the transform represents a pause, so yield silence
1268 timedYieldSilence_l(buffer->frameCount, buffer);
1269 return NO_ERROR;
1270 }
1271
1272 int64_t transformedPTS;
1273 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1274 &transformedPTS)) {
1275 // the transform failed. this shouldn't happen, but if it does
1276 // then just drop this buffer
1277 ALOGW("timedGetNextBuffer transform failed");
1278 buffer->raw = NULL;
1279 buffer->frameCount = 0;
1280 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1281 return NO_ERROR;
1282 }
1283
1284 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1285 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1286 &headLocalPTS)) {
1287 buffer->raw = NULL;
1288 buffer->frameCount = 0;
1289 return INVALID_OPERATION;
1290 }
1291 } else {
1292 headLocalPTS = transformedPTS;
1293 }
1294 }
1295
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001296 uint32_t sr = sampleRate();
1297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 // adjust the head buffer's PTS to reflect the portion of the head buffer
1299 // that has already been consumed
1300 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001301 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001302
1303 // Calculate the delta in samples between the head of the input buffer
1304 // queue and the start of the next output buffer that will be written.
1305 // If the transformation fails because of over or underflow, it means
1306 // that the sample's position in the output stream is so far out of
1307 // whack that it should just be dropped.
1308 int64_t sampleDelta;
1309 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1310 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1311 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1312 " mix");
1313 continue;
1314 }
1315 if (!mLocalTimeToSampleTransform.doForwardTransform(
1316 (effectivePTS - pts) << 32, &sampleDelta)) {
1317 ALOGV("*** too late during sample rate transform: dropped buffer");
1318 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1319 continue;
1320 }
1321
1322 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1323 " sampleDelta=[%d.%08x]",
1324 head.pts(), head.position(), pts,
1325 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1326 + (sampleDelta >> 32)),
1327 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1328
1329 // if the delta between the ideal placement for the next input sample and
1330 // the current output position is within this threshold, then we will
1331 // concatenate the next input samples to the previous output
1332 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001333 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001334
1335 // if this is the first buffer of audio that we're emitting from this track
1336 // then it should be almost exactly on time.
1337 const int64_t kSampleStartupThreshold = 1LL << 32;
1338
1339 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1340 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1341 // the next input is close enough to being on time, so concatenate it
1342 // with the last output
1343 timedYieldSamples_l(buffer);
1344
1345 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1346 head.position(), buffer->frameCount);
1347 return NO_ERROR;
1348 }
1349
1350 // Looks like our output is not on time. Reset our on timed status.
1351 // Next time we mix samples from our input queue, then should be within
1352 // the StartupThreshold.
1353 mTimedAudioOutputOnTime = false;
1354 if (sampleDelta > 0) {
1355 // the gap between the current output position and the proper start of
1356 // the next input sample is too big, so fill it with silence
1357 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1358
1359 timedYieldSilence_l(framesUntilNextInput, buffer);
1360 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1361 return NO_ERROR;
1362 } else {
1363 // the next input sample is late
1364 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1365 size_t onTimeSamplePosition =
1366 head.position() + lateFrames * mFrameSize;
1367
1368 if (onTimeSamplePosition > head.buffer()->size()) {
1369 // all the remaining samples in the head are too late, so
1370 // drop it and move on
1371 ALOGV("*** too late: dropped buffer");
1372 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1373 continue;
1374 } else {
1375 // skip over the late samples
1376 head.setPosition(onTimeSamplePosition);
1377
1378 // yield the available samples
1379 timedYieldSamples_l(buffer);
1380
1381 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1382 return NO_ERROR;
1383 }
1384 }
1385 }
1386}
1387
1388// Yield samples from the timed buffer queue head up to the given output
1389// buffer's capacity.
1390//
1391// Caller must hold mTimedBufferQueueLock
1392void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1393 AudioBufferProvider::Buffer* buffer) {
1394
1395 const TimedBuffer& head = mTimedBufferQueue[0];
1396
1397 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1398 head.position());
1399
1400 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1401 mFrameSize);
1402 size_t framesRequested = buffer->frameCount;
1403 buffer->frameCount = min(framesLeftInHead, framesRequested);
1404
1405 mQueueHeadInFlight = true;
1406 mTimedAudioOutputOnTime = true;
1407}
1408
1409// Yield samples of silence up to the given output buffer's capacity
1410//
1411// Caller must hold mTimedBufferQueueLock
1412void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1413 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1414
1415 // lazily allocate a buffer filled with silence
1416 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1417 delete [] mTimedSilenceBuffer;
1418 mTimedSilenceBufferSize = numFrames * mFrameSize;
1419 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1420 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1421 }
1422
1423 buffer->raw = mTimedSilenceBuffer;
1424 size_t framesRequested = buffer->frameCount;
1425 buffer->frameCount = min(numFrames, framesRequested);
1426
1427 mTimedAudioOutputOnTime = false;
1428}
1429
1430// AudioBufferProvider interface
1431void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1432 AudioBufferProvider::Buffer* buffer) {
1433
1434 Mutex::Autolock _l(mTimedBufferQueueLock);
1435
1436 // If the buffer which was just released is part of the buffer at the head
1437 // of the queue, be sure to update the amt of the buffer which has been
1438 // consumed. If the buffer being returned is not part of the head of the
1439 // queue, its either because the buffer is part of the silence buffer, or
1440 // because the head of the timed queue was trimmed after the mixer called
1441 // getNextBuffer but before the mixer called releaseBuffer.
1442 if (buffer->raw == mTimedSilenceBuffer) {
1443 ALOG_ASSERT(!mQueueHeadInFlight,
1444 "Queue head in flight during release of silence buffer!");
1445 goto done;
1446 }
1447
1448 ALOG_ASSERT(mQueueHeadInFlight,
1449 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1450 " head in flight.");
1451
1452 if (mTimedBufferQueue.size()) {
1453 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1454
1455 void* start = head.buffer()->pointer();
1456 void* end = reinterpret_cast<void*>(
1457 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1458 + head.buffer()->size());
1459
1460 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1461 "released buffer not within the head of the timed buffer"
1462 " queue; qHead = [%p, %p], released buffer = %p",
1463 start, end, buffer->raw);
1464
1465 head.setPosition(head.position() +
1466 (buffer->frameCount * mFrameSize));
1467 mQueueHeadInFlight = false;
1468
1469 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1470 "Bad bookkeeping during releaseBuffer! Should have at"
1471 " least %u queued frames, but we think we have only %u",
1472 buffer->frameCount, mFramesPendingInQueue);
1473
1474 mFramesPendingInQueue -= buffer->frameCount;
1475
1476 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1477 || mTrimQueueHeadOnRelease) {
1478 trimTimedBufferQueueHead_l("releaseBuffer");
1479 mTrimQueueHeadOnRelease = false;
1480 }
1481 } else {
1482 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1483 " buffers in the timed buffer queue");
1484 }
1485
1486done:
1487 buffer->raw = 0;
1488 buffer->frameCount = 0;
1489}
1490
1491size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1492 Mutex::Autolock _l(mTimedBufferQueueLock);
1493 return mFramesPendingInQueue;
1494}
1495
1496AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1497 : mPTS(0), mPosition(0) {}
1498
1499AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1500 const sp<IMemory>& buffer, int64_t pts)
1501 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1502
1503
1504// ----------------------------------------------------------------------------
1505
1506AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1507 PlaybackThread *playbackThread,
1508 DuplicatingThread *sourceThread,
1509 uint32_t sampleRate,
1510 audio_format_t format,
1511 audio_channel_mask_t channelMask,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001512 size_t frameCount,
1513 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001514 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001515 NULL, 0, uid, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001516 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001517{
1518
1519 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001520 mOutBuffer.frameCount = 0;
1521 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001522 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001523 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001524 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001525 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001526 // since client and server are in the same process,
1527 // the buffer has the same virtual address on both sides
1528 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001529 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1530 mClientProxy->setSendLevel(0.0);
1531 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001532 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1533 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001534 } else {
1535 ALOGW("Error creating output track on thread %p", playbackThread);
1536 }
1537}
1538
1539AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1540{
1541 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001542 delete mClientProxy;
1543 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001544}
1545
1546status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1547 int triggerSession)
1548{
1549 status_t status = Track::start(event, triggerSession);
1550 if (status != NO_ERROR) {
1551 return status;
1552 }
1553
1554 mActive = true;
1555 mRetryCount = 127;
1556 return status;
1557}
1558
1559void AudioFlinger::PlaybackThread::OutputTrack::stop()
1560{
1561 Track::stop();
1562 clearBufferQueue();
1563 mOutBuffer.frameCount = 0;
1564 mActive = false;
1565}
1566
1567bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1568{
1569 Buffer *pInBuffer;
1570 Buffer inBuffer;
1571 uint32_t channelCount = mChannelCount;
1572 bool outputBufferFull = false;
1573 inBuffer.frameCount = frames;
1574 inBuffer.i16 = data;
1575
1576 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1577
1578 if (!mActive && frames != 0) {
1579 start();
1580 sp<ThreadBase> thread = mThread.promote();
1581 if (thread != 0) {
1582 MixerThread *mixerThread = (MixerThread *)thread.get();
1583 if (mFrameCount > frames) {
1584 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1585 uint32_t startFrames = (mFrameCount - frames);
1586 pInBuffer = new Buffer;
1587 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1588 pInBuffer->frameCount = startFrames;
1589 pInBuffer->i16 = pInBuffer->mBuffer;
1590 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1591 mBufferQueue.add(pInBuffer);
1592 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001593 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001594 }
1595 }
1596 }
1597 }
1598
1599 while (waitTimeLeftMs) {
1600 // First write pending buffers, then new data
1601 if (mBufferQueue.size()) {
1602 pInBuffer = mBufferQueue.itemAt(0);
1603 } else {
1604 pInBuffer = &inBuffer;
1605 }
1606
1607 if (pInBuffer->frameCount == 0) {
1608 break;
1609 }
1610
1611 if (mOutBuffer.frameCount == 0) {
1612 mOutBuffer.frameCount = pInBuffer->frameCount;
1613 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001614 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1615 if (status != NO_ERROR) {
1616 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1617 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001618 outputBufferFull = true;
1619 break;
1620 }
1621 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1622 if (waitTimeLeftMs >= waitTimeMs) {
1623 waitTimeLeftMs -= waitTimeMs;
1624 } else {
1625 waitTimeLeftMs = 0;
1626 }
1627 }
1628
1629 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1630 pInBuffer->frameCount;
1631 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001632 Proxy::Buffer buf;
1633 buf.mFrameCount = outFrames;
1634 buf.mRaw = NULL;
1635 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001636 pInBuffer->frameCount -= outFrames;
1637 pInBuffer->i16 += outFrames * channelCount;
1638 mOutBuffer.frameCount -= outFrames;
1639 mOutBuffer.i16 += outFrames * channelCount;
1640
1641 if (pInBuffer->frameCount == 0) {
1642 if (mBufferQueue.size()) {
1643 mBufferQueue.removeAt(0);
1644 delete [] pInBuffer->mBuffer;
1645 delete pInBuffer;
1646 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1647 mThread.unsafe_get(), mBufferQueue.size());
1648 } else {
1649 break;
1650 }
1651 }
1652 }
1653
1654 // If we could not write all frames, allocate a buffer and queue it for next time.
1655 if (inBuffer.frameCount) {
1656 sp<ThreadBase> thread = mThread.promote();
1657 if (thread != 0 && !thread->standby()) {
1658 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1659 pInBuffer = new Buffer;
1660 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1661 pInBuffer->frameCount = inBuffer.frameCount;
1662 pInBuffer->i16 = pInBuffer->mBuffer;
1663 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1664 sizeof(int16_t));
1665 mBufferQueue.add(pInBuffer);
1666 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1667 mThread.unsafe_get(), mBufferQueue.size());
1668 } else {
1669 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1670 mThread.unsafe_get(), this);
1671 }
1672 }
1673 }
1674
1675 // Calling write() with a 0 length buffer, means that no more data will be written:
1676 // If no more buffers are pending, fill output track buffer to make sure it is started
1677 // by output mixer.
1678 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001679 // FIXME borken, replace by getting framesReady() from proxy
1680 size_t user = 0; // was mCblk->user
1681 if (user < mFrameCount) {
1682 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001683 pInBuffer = new Buffer;
1684 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1685 pInBuffer->frameCount = frames;
1686 pInBuffer->i16 = pInBuffer->mBuffer;
1687 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1688 mBufferQueue.add(pInBuffer);
1689 } else if (mActive) {
1690 stop();
1691 }
1692 }
1693
1694 return outputBufferFull;
1695}
1696
1697status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1698 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1699{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001700 ClientProxy::Buffer buf;
1701 buf.mFrameCount = buffer->frameCount;
1702 struct timespec timeout;
1703 timeout.tv_sec = waitTimeMs / 1000;
1704 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1705 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1706 buffer->frameCount = buf.mFrameCount;
1707 buffer->raw = buf.mRaw;
1708 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001709}
1710
Eric Laurent81784c32012-11-19 14:55:58 -08001711void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1712{
1713 size_t size = mBufferQueue.size();
1714
1715 for (size_t i = 0; i < size; i++) {
1716 Buffer *pBuffer = mBufferQueue.itemAt(i);
1717 delete [] pBuffer->mBuffer;
1718 delete pBuffer;
1719 }
1720 mBufferQueue.clear();
1721}
1722
1723
1724// ----------------------------------------------------------------------------
1725// Record
1726// ----------------------------------------------------------------------------
1727
1728AudioFlinger::RecordHandle::RecordHandle(
1729 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1730 : BnAudioRecord(),
1731 mRecordTrack(recordTrack)
1732{
1733}
1734
1735AudioFlinger::RecordHandle::~RecordHandle() {
1736 stop_nonvirtual();
1737 mRecordTrack->destroy();
1738}
1739
1740sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1741 return mRecordTrack->getCblk();
1742}
1743
1744status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1745 int triggerSession) {
1746 ALOGV("RecordHandle::start()");
1747 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1748}
1749
1750void AudioFlinger::RecordHandle::stop() {
1751 stop_nonvirtual();
1752}
1753
1754void AudioFlinger::RecordHandle::stop_nonvirtual() {
1755 ALOGV("RecordHandle::stop()");
1756 mRecordTrack->stop();
1757}
1758
1759status_t AudioFlinger::RecordHandle::onTransact(
1760 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1761{
1762 return BnAudioRecord::onTransact(code, data, reply, flags);
1763}
1764
1765// ----------------------------------------------------------------------------
1766
1767// RecordTrack constructor must be called with AudioFlinger::mLock held
1768AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1769 RecordThread *thread,
1770 const sp<Client>& client,
1771 uint32_t sampleRate,
1772 audio_format_t format,
1773 audio_channel_mask_t channelMask,
1774 size_t frameCount,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001775 int sessionId,
1776 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001777 : TrackBase(thread, client, sampleRate, format,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001778 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, uid, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001779 mOverflow(false)
1780{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001781 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001782 if (mCblk != NULL) {
1783 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1784 mFrameSize);
1785 mServerProxy = mAudioRecordServerProxy;
1786 }
Eric Laurent81784c32012-11-19 14:55:58 -08001787}
1788
1789AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1790{
1791 ALOGV("%s", __func__);
1792}
1793
1794// AudioBufferProvider interface
1795status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1796 int64_t pts)
1797{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001798 ServerProxy::Buffer buf;
1799 buf.mFrameCount = buffer->frameCount;
1800 status_t status = mServerProxy->obtainBuffer(&buf);
1801 buffer->frameCount = buf.mFrameCount;
1802 buffer->raw = buf.mRaw;
1803 if (buf.mFrameCount == 0) {
1804 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001805 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001806 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001807 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001808}
1809
1810status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1811 int triggerSession)
1812{
1813 sp<ThreadBase> thread = mThread.promote();
1814 if (thread != 0) {
1815 RecordThread *recordThread = (RecordThread *)thread.get();
1816 return recordThread->start(this, event, triggerSession);
1817 } else {
1818 return BAD_VALUE;
1819 }
1820}
1821
1822void AudioFlinger::RecordThread::RecordTrack::stop()
1823{
1824 sp<ThreadBase> thread = mThread.promote();
1825 if (thread != 0) {
1826 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001827 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001828 AudioSystem::stopInput(recordThread->id());
1829 }
1830 }
1831}
1832
1833void AudioFlinger::RecordThread::RecordTrack::destroy()
1834{
1835 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1836 sp<RecordTrack> keep(this);
1837 {
1838 sp<ThreadBase> thread = mThread.promote();
1839 if (thread != 0) {
1840 if (mState == ACTIVE || mState == RESUMING) {
1841 AudioSystem::stopInput(thread->id());
1842 }
1843 AudioSystem::releaseInput(thread->id());
1844 Mutex::Autolock _l(thread->mLock);
1845 RecordThread *recordThread = (RecordThread *) thread.get();
1846 recordThread->destroyTrack_l(this);
1847 }
1848 }
1849}
1850
Eric Laurent9a54bc22013-09-09 09:08:44 -07001851void AudioFlinger::RecordThread::RecordTrack::invalidate()
1852{
1853 // FIXME should use proxy, and needs work
1854 audio_track_cblk_t* cblk = mCblk;
1855 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1856 android_atomic_release_store(0x40000000, &cblk->mFutex);
1857 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1858 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1859}
1860
Eric Laurent81784c32012-11-19 14:55:58 -08001861
1862/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1863{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001864 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001865}
1866
1867void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1868{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001869 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001870 (mClient == 0) ? getpid_cached : mClient->pid(),
1871 mFormat,
1872 mChannelMask,
1873 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001874 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001875 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001876 mFrameCount);
1877}
1878
Eric Laurent81784c32012-11-19 14:55:58 -08001879}; // namespace android