blob: 6dc7f30ff0d41decaad5084f805d7a42f82f63fc [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 Kasten755b0a62014-05-13 11:30:28 -070072 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070073 bool isOut,
74 bool useReadOnlyHeap)
Eric Laurent81784c32012-11-19 14:55:58 -080075 : RefBase(),
76 mThread(thread),
77 mClient(client),
78 mCblk(NULL),
79 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080080 mState(IDLE),
81 mSampleRate(sampleRate),
82 mFormat(format),
83 mChannelMask(channelMask),
84 mChannelCount(popcount(channelMask)),
85 mFrameSize(audio_is_linear_pcm(format) ?
86 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
87 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080088 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070089 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080090 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080091 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080092 mId(android_atomic_inc(&nextTrackId)),
93 mTerminated(false)
Eric Laurent81784c32012-11-19 14:55:58 -080094{
Marco Nelissen462fd2f2013-01-14 14:12:05 -080095 // if the caller is us, trust the specified uid
96 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
97 int newclientUid = IPCThreadState::self()->getCallingUid();
98 if (clientUid != -1 && clientUid != newclientUid) {
99 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
100 }
101 clientUid = newclientUid;
102 }
103 // clientUid contains the uid of the app that is responsible for this track, so we can blame
104 // battery usage on it.
105 mUid = clientUid;
106
Eric Laurent81784c32012-11-19 14:55:58 -0800107 // client == 0 implies sharedBuffer == 0
108 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
109
110 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
111 sharedBuffer->size());
112
113 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
114 size_t size = sizeof(audio_track_cblk_t);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800115 size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize;
Glenn Kastend776ac62014-05-07 09:16:09 -0700116 if (sharedBuffer == 0 && !useReadOnlyHeap) {
Eric Laurent81784c32012-11-19 14:55:58 -0800117 size += bufferSize;
118 }
119
120 if (client != 0) {
121 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700122 if (mCblkMemory == 0 ||
123 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800124 ALOGE("not enough memory for AudioTrack size=%u", size);
125 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700126 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800127 return;
128 }
129 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800130 // this syntax avoids calling the audio_track_cblk_t constructor twice
131 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800132 // assume mCblk != NULL
133 }
134
135 // construct the shared structure in-place.
136 if (mCblk != NULL) {
137 new(mCblk) audio_track_cblk_t();
Glenn Kastend776ac62014-05-07 09:16:09 -0700138 if (useReadOnlyHeap) {
139 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
140 if (roHeap == 0 ||
141 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
142 (mBuffer = mBufferMemory->pointer()) == NULL) {
143 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
144 if (roHeap != 0) {
145 roHeap->dump("buffer");
146 }
147 mCblkMemory.clear();
148 mBufferMemory.clear();
149 return;
150 }
Eric Laurent81784c32012-11-19 14:55:58 -0800151 memset(mBuffer, 0, bufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -0800152 } else {
Glenn Kastend776ac62014-05-07 09:16:09 -0700153 // clear all buffers
154 if (sharedBuffer == 0) {
155 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
156 memset(mBuffer, 0, bufferSize);
157 } else {
158 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800159#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700160 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800161#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700162 }
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);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800168 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800169 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) {
195 if (mClient == 0) {
196 delete mCblk;
197 } else {
198 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
199 }
200 }
201 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
202 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700203 // Client destructor must run with AudioFlinger client mutex locked
204 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800205 // If the client's reference count drops to zero, the associated destructor
206 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
207 // relying on the automatic clear() at end of scope.
208 mClient.clear();
209 }
210}
211
212// AudioBufferProvider interface
213// getNextBuffer() = 0;
214// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
215void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
216{
Glenn Kasten46909e72013-02-26 09:20:22 -0800217#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800218 if (mTeeSink != 0) {
219 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
220 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800221#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800222
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800223 ServerProxy::Buffer buf;
224 buf.mFrameCount = buffer->frameCount;
225 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800226 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800227 buffer->raw = NULL;
228 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800229}
230
Eric Laurent81784c32012-11-19 14:55:58 -0800231status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
232{
233 mSyncEvents.add(event);
234 return NO_ERROR;
235}
236
237// ----------------------------------------------------------------------------
238// Playback
239// ----------------------------------------------------------------------------
240
241AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
242 : BnAudioTrack(),
243 mTrack(track)
244{
245}
246
247AudioFlinger::TrackHandle::~TrackHandle() {
248 // just stop the track on deletion, associated resources
249 // will be freed from the main thread once all pending buffers have
250 // been played. Unless it's not in the active track list, in which
251 // case we free everything now...
252 mTrack->destroy();
253}
254
255sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
256 return mTrack->getCblk();
257}
258
259status_t AudioFlinger::TrackHandle::start() {
260 return mTrack->start();
261}
262
263void AudioFlinger::TrackHandle::stop() {
264 mTrack->stop();
265}
266
267void AudioFlinger::TrackHandle::flush() {
268 mTrack->flush();
269}
270
Eric Laurent81784c32012-11-19 14:55:58 -0800271void AudioFlinger::TrackHandle::pause() {
272 mTrack->pause();
273}
274
275status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
276{
277 return mTrack->attachAuxEffect(EffectId);
278}
279
280status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
281 sp<IMemory>* buffer) {
282 if (!mTrack->isTimedTrack())
283 return INVALID_OPERATION;
284
285 PlaybackThread::TimedTrack* tt =
286 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
287 return tt->allocateTimedBuffer(size, buffer);
288}
289
290status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
291 int64_t pts) {
292 if (!mTrack->isTimedTrack())
293 return INVALID_OPERATION;
294
Glenn Kasten663c2242013-09-24 11:52:37 -0700295 if (buffer == 0 || buffer->pointer() == NULL) {
296 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
297 return BAD_VALUE;
298 }
299
Eric Laurent81784c32012-11-19 14:55:58 -0800300 PlaybackThread::TimedTrack* tt =
301 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
302 return tt->queueTimedBuffer(buffer, pts);
303}
304
305status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
306 const LinearTransform& xform, int target) {
307
308 if (!mTrack->isTimedTrack())
309 return INVALID_OPERATION;
310
311 PlaybackThread::TimedTrack* tt =
312 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
313 return tt->setMediaTimeTransform(
314 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
315}
316
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700317status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
318 return mTrack->setParameters(keyValuePairs);
319}
320
Glenn Kasten53cec222013-08-29 09:01:02 -0700321status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
322{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700323 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700324}
325
Eric Laurent59fe0102013-09-27 18:48:26 -0700326
327void AudioFlinger::TrackHandle::signal()
328{
329 return mTrack->signal();
330}
331
Eric Laurent81784c32012-11-19 14:55:58 -0800332status_t AudioFlinger::TrackHandle::onTransact(
333 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
334{
335 return BnAudioTrack::onTransact(code, data, reply, flags);
336}
337
338// ----------------------------------------------------------------------------
339
340// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
341AudioFlinger::PlaybackThread::Track::Track(
342 PlaybackThread *thread,
343 const sp<Client>& client,
344 audio_stream_type_t streamType,
345 uint32_t sampleRate,
346 audio_format_t format,
347 audio_channel_mask_t channelMask,
348 size_t frameCount,
349 const sp<IMemory>& sharedBuffer,
350 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800351 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -0800352 IAudioFlinger::track_flags_t flags)
353 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kasten755b0a62014-05-13 11:30:28 -0700354 sessionId, uid, flags, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800355 mFillingUpStatus(FS_INVALID),
356 // mRetryCount initialized later when needed
357 mSharedBuffer(sharedBuffer),
358 mStreamType(streamType),
359 mName(-1), // see note below
360 mMainBuffer(thread->mixBuffer()),
361 mAuxBuffer(NULL),
362 mAuxEffectId(0), mHasVolumeController(false),
363 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800364 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800365 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800366 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800367 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800368 mResumeToStopping(false),
369 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800370{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700371 if (mCblk == NULL) {
372 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800373 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700374
375 if (sharedBuffer == 0) {
376 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
377 mFrameSize);
378 } else {
379 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
380 mFrameSize);
381 }
382 mServerProxy = mAudioTrackServerProxy;
383
384 mName = thread->getTrackName_l(channelMask, sessionId);
385 if (mName < 0) {
386 ALOGE("no more track names available");
387 return;
388 }
389 // only allocate a fast track index if we were able to allocate a normal track name
390 if (flags & IAudioFlinger::TRACK_FAST) {
391 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
392 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
393 int i = __builtin_ctz(thread->mFastTrackAvailMask);
394 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
395 // FIXME This is too eager. We allocate a fast track index before the
396 // fast track becomes active. Since fast tracks are a scarce resource,
397 // this means we are potentially denying other more important fast tracks from
398 // being created. It would be better to allocate the index dynamically.
399 mFastIndex = i;
400 // Read the initial underruns because this field is never cleared by the fast mixer
401 mObservedUnderruns = thread->getFastTrackUnderruns(i);
402 thread->mFastTrackAvailMask &= ~(1 << i);
403 }
Eric Laurent81784c32012-11-19 14:55:58 -0800404}
405
406AudioFlinger::PlaybackThread::Track::~Track()
407{
408 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700409
410 // The destructor would clear mSharedBuffer,
411 // but it will not push the decremented reference count,
412 // leaving the client's IMemory dangling indefinitely.
413 // This prevents that leak.
414 if (mSharedBuffer != 0) {
415 mSharedBuffer.clear();
416 // flush the binder command buffer
417 IPCThreadState::self()->flushCommands();
418 }
Eric Laurent81784c32012-11-19 14:55:58 -0800419}
420
Glenn Kasten03003332013-08-06 15:40:54 -0700421status_t AudioFlinger::PlaybackThread::Track::initCheck() const
422{
423 status_t status = TrackBase::initCheck();
424 if (status == NO_ERROR && mName < 0) {
425 status = NO_MEMORY;
426 }
427 return status;
428}
429
Eric Laurent81784c32012-11-19 14:55:58 -0800430void AudioFlinger::PlaybackThread::Track::destroy()
431{
432 // NOTE: destroyTrack_l() can remove a strong reference to this Track
433 // by removing it from mTracks vector, so there is a risk that this Tracks's
434 // destructor is called. As the destructor needs to lock mLock,
435 // we must acquire a strong reference on this Track before locking mLock
436 // here so that the destructor is called only when exiting this function.
437 // On the other hand, as long as Track::destroy() is only called by
438 // TrackHandle destructor, the TrackHandle still holds a strong ref on
439 // this Track with its member mTrack.
440 sp<Track> keep(this);
441 { // scope for mLock
442 sp<ThreadBase> thread = mThread.promote();
443 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800444 Mutex::Autolock _l(thread->mLock);
445 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800446 bool wasActive = playbackThread->destroyTrack_l(this);
447 if (!isOutputTrack() && !wasActive) {
448 AudioSystem::releaseOutput(thread->id());
449 }
Eric Laurent81784c32012-11-19 14:55:58 -0800450 }
451 }
452}
453
454/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
455{
Marco Nelissenb2208842014-02-07 14:00:50 -0800456 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700457 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800458}
459
Marco Nelissenb2208842014-02-07 14:00:50 -0800460void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800461{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800462 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800463 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800464 sprintf(buffer, " F %2d", mFastIndex);
465 } else if (mName >= AudioMixer::TRACK0) {
466 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800467 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800468 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800469 }
470 track_state state = mState;
471 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800472 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800473 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800474 } else {
475 switch (state) {
476 case IDLE:
477 stateChar = 'I';
478 break;
479 case STOPPING_1:
480 stateChar = 's';
481 break;
482 case STOPPING_2:
483 stateChar = '5';
484 break;
485 case STOPPED:
486 stateChar = 'S';
487 break;
488 case RESUMING:
489 stateChar = 'R';
490 break;
491 case ACTIVE:
492 stateChar = 'A';
493 break;
494 case PAUSING:
495 stateChar = 'p';
496 break;
497 case PAUSED:
498 stateChar = 'P';
499 break;
500 case FLUSHED:
501 stateChar = 'F';
502 break;
503 default:
504 stateChar = '?';
505 break;
506 }
Eric Laurent81784c32012-11-19 14:55:58 -0800507 }
508 char nowInUnderrun;
509 switch (mObservedUnderruns.mBitFields.mMostRecent) {
510 case UNDERRUN_FULL:
511 nowInUnderrun = ' ';
512 break;
513 case UNDERRUN_PARTIAL:
514 nowInUnderrun = '<';
515 break;
516 case UNDERRUN_EMPTY:
517 nowInUnderrun = '*';
518 break;
519 default:
520 nowInUnderrun = '?';
521 break;
522 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000523 snprintf(&buffer[8], size-8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u %5.2g %5.2g "
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000524 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800525 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800526 (mClient == 0) ? getpid_cached : mClient->pid(),
527 mStreamType,
528 mFormat,
529 mChannelMask,
530 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800531 mFrameCount,
532 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800533 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800534 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800535 20.0 * log10((vlr & 0xFFFF) / 4096.0),
536 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700537 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000538 mMainBuffer,
539 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700540 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700541 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800542 nowInUnderrun);
543}
544
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800545uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
546 return mAudioTrackServerProxy->getSampleRate();
547}
548
Eric Laurent81784c32012-11-19 14:55:58 -0800549// AudioBufferProvider interface
550status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800551 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800552{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 ServerProxy::Buffer buf;
554 size_t desiredFrames = buffer->frameCount;
555 buf.mFrameCount = desiredFrames;
556 status_t status = mServerProxy->obtainBuffer(&buf);
557 buffer->frameCount = buf.mFrameCount;
558 buffer->raw = buf.mRaw;
559 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700560 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800561 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800562 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800563}
564
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700565// releaseBuffer() is not overridden
566
567// ExtendedAudioBufferProvider interface
568
Eric Laurent81784c32012-11-19 14:55:58 -0800569// Note that framesReady() takes a mutex on the control block using tryLock().
570// This could result in priority inversion if framesReady() is called by the normal mixer,
571// as the normal mixer thread runs at lower
572// priority than the client's callback thread: there is a short window within framesReady()
573// during which the normal mixer could be preempted, and the client callback would block.
574// Another problem can occur if framesReady() is called by the fast mixer:
575// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
576// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
577size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800578 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800579}
580
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700581size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
582{
583 return mAudioTrackServerProxy->framesReleased();
584}
585
Eric Laurent81784c32012-11-19 14:55:58 -0800586// Don't call for fast tracks; the framesReady() could result in priority inversion
587bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800588 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
589 return true;
590 }
591
Eric Laurent16498512014-03-17 17:22:08 -0700592 if (isStopping()) {
593 if (framesReady() > 0) {
594 mFillingUpStatus = FS_FILLED;
595 }
Eric Laurent81784c32012-11-19 14:55:58 -0800596 return true;
597 }
598
599 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700600 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800601 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700602 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800603 return true;
604 }
605 return false;
606}
607
Glenn Kasten0f11b512014-01-31 16:18:54 -0800608status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
609 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
611 status_t status = NO_ERROR;
612 ALOGV("start(%d), calling pid %d session %d",
613 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
614
615 sp<ThreadBase> thread = mThread.promote();
616 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700617 if (isOffloaded()) {
618 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
619 Mutex::Autolock _lth(thread->mLock);
620 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700621 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
622 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700623 invalidate();
624 return PERMISSION_DENIED;
625 }
626 }
627 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800628 track_state state = mState;
629 // here the track could be either new, or restarted
630 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800631
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800632 // initial state-stopping. next state-pausing.
633 // What if resume is called ?
634
635 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800636 if (mResumeToStopping) {
637 // happened we need to resume to STOPPING_1
638 mState = TrackBase::STOPPING_1;
639 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
640 } else {
641 mState = TrackBase::RESUMING;
642 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
643 }
Eric Laurent81784c32012-11-19 14:55:58 -0800644 } else {
645 mState = TrackBase::ACTIVE;
646 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
647 }
648
Eric Laurentbfb1b832013-01-07 09:53:42 -0800649 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
650 status = playbackThread->addTrack_l(this);
651 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800652 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800653 // restore previous state if start was rejected by policy manager
654 if (status == PERMISSION_DENIED) {
655 mState = state;
656 }
657 }
658 // track was already in the active list, not a problem
659 if (status == ALREADY_EXISTS) {
660 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700661 } else {
662 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
663 // It is usually unsafe to access the server proxy from a binder thread.
664 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
665 // isn't looking at this track yet: we still hold the normal mixer thread lock,
666 // and for fast tracks the track is not yet in the fast mixer thread's active set.
667 ServerProxy::Buffer buffer;
668 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700669 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800670 }
671 } else {
672 status = BAD_VALUE;
673 }
674 return status;
675}
676
677void AudioFlinger::PlaybackThread::Track::stop()
678{
679 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
680 sp<ThreadBase> thread = mThread.promote();
681 if (thread != 0) {
682 Mutex::Autolock _l(thread->mLock);
683 track_state state = mState;
684 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
685 // If the track is not active (PAUSED and buffers full), flush buffers
686 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
687 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
688 reset();
689 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800690 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800691 mState = STOPPED;
692 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800693 // For fast tracks prepareTracks_l() will set state to STOPPING_2
694 // presentation is complete
695 // For an offloaded track this starts a drain and state will
696 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800697 mState = STOPPING_1;
698 }
699 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
700 playbackThread);
701 }
Eric Laurent81784c32012-11-19 14:55:58 -0800702 }
703}
704
705void AudioFlinger::PlaybackThread::Track::pause()
706{
707 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
708 sp<ThreadBase> thread = mThread.promote();
709 if (thread != 0) {
710 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800711 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
712 switch (mState) {
713 case STOPPING_1:
714 case STOPPING_2:
715 if (!isOffloaded()) {
716 /* nothing to do if track is not offloaded */
717 break;
718 }
719
720 // Offloaded track was draining, we need to carry on draining when resumed
721 mResumeToStopping = true;
722 // fall through...
723 case ACTIVE:
724 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800725 mState = PAUSING;
726 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700727 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800728 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800729
Eric Laurentbfb1b832013-01-07 09:53:42 -0800730 default:
731 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800732 }
733 }
734}
735
736void AudioFlinger::PlaybackThread::Track::flush()
737{
738 ALOGV("flush(%d)", mName);
739 sp<ThreadBase> thread = mThread.promote();
740 if (thread != 0) {
741 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800742 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800743
744 if (isOffloaded()) {
745 // If offloaded we allow flush during any state except terminated
746 // and keep the track active to avoid problems if user is seeking
747 // rapidly and underlying hardware has a significant delay handling
748 // a pause
749 if (isTerminated()) {
750 return;
751 }
752
753 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800754 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800755
756 if (mState == STOPPING_1 || mState == STOPPING_2) {
757 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
758 mState = ACTIVE;
759 }
760
761 if (mState == ACTIVE) {
762 ALOGV("flush called in active state, resetting buffer time out retry count");
763 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
764 }
765
Haynes Mathew George7844f672014-01-15 12:32:55 -0800766 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800767 mResumeToStopping = false;
768 } else {
769 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
770 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
771 return;
772 }
773 // No point remaining in PAUSED state after a flush => go to
774 // FLUSHED state
775 mState = FLUSHED;
776 // do not reset the track if it is still in the process of being stopped or paused.
777 // this will be done by prepareTracks_l() when the track is stopped.
778 // prepareTracks_l() will see mState == FLUSHED, then
779 // remove from active track list, reset(), and trigger presentation complete
780 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
781 reset();
782 }
Eric Laurent81784c32012-11-19 14:55:58 -0800783 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800784 // Prevent flush being lost if the track is flushed and then resumed
785 // before mixer thread can run. This is important when offloading
786 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700787 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800788 }
789}
790
Haynes Mathew George7844f672014-01-15 12:32:55 -0800791// must be called with thread lock held
792void AudioFlinger::PlaybackThread::Track::flushAck()
793{
794 if (!isOffloaded())
795 return;
796
797 mFlushHwPending = false;
798}
799
Eric Laurent81784c32012-11-19 14:55:58 -0800800void AudioFlinger::PlaybackThread::Track::reset()
801{
802 // Do not reset twice to avoid discarding data written just after a flush and before
803 // the audioflinger thread detects the track is stopped.
804 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800805 // Force underrun condition to avoid false underrun callback until first data is
806 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700807 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800808 mFillingUpStatus = FS_FILLING;
809 mResetDone = true;
810 if (mState == FLUSHED) {
811 mState = IDLE;
812 }
813 }
814}
815
Eric Laurentbfb1b832013-01-07 09:53:42 -0800816status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
817{
818 sp<ThreadBase> thread = mThread.promote();
819 if (thread == 0) {
820 ALOGE("thread is dead");
821 return FAILED_TRANSACTION;
822 } else if ((thread->type() == ThreadBase::DIRECT) ||
823 (thread->type() == ThreadBase::OFFLOAD)) {
824 return thread->setParameters(keyValuePairs);
825 } else {
826 return PERMISSION_DENIED;
827 }
828}
829
Glenn Kasten573d80a2013-08-26 09:36:23 -0700830status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
831{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700832 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
833 if (isFastTrack()) {
834 return INVALID_OPERATION;
835 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700836 sp<ThreadBase> thread = mThread.promote();
837 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700838 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700839 }
840 Mutex::Autolock _l(thread->mLock);
841 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700842 if (!isOffloaded()) {
843 if (!playbackThread->mLatchQValid) {
844 return INVALID_OPERATION;
845 }
846 uint32_t unpresentedFrames =
847 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
848 playbackThread->mSampleRate;
849 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
850 if (framesWritten < unpresentedFrames) {
851 return INVALID_OPERATION;
852 }
853 timestamp.mPosition = framesWritten - unpresentedFrames;
854 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
855 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700856 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700857
858 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700859}
860
Eric Laurent81784c32012-11-19 14:55:58 -0800861status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
862{
863 status_t status = DEAD_OBJECT;
864 sp<ThreadBase> thread = mThread.promote();
865 if (thread != 0) {
866 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
867 sp<AudioFlinger> af = mClient->audioFlinger();
868
869 Mutex::Autolock _l(af->mLock);
870
871 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
872
873 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
874 Mutex::Autolock _dl(playbackThread->mLock);
875 Mutex::Autolock _sl(srcThread->mLock);
876 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
877 if (chain == 0) {
878 return INVALID_OPERATION;
879 }
880
881 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
882 if (effect == 0) {
883 return INVALID_OPERATION;
884 }
885 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700886 status = playbackThread->addEffect_l(effect);
887 if (status != NO_ERROR) {
888 srcThread->addEffect_l(effect);
889 return INVALID_OPERATION;
890 }
Eric Laurent81784c32012-11-19 14:55:58 -0800891 // removeEffect_l() has stopped the effect if it was active so it must be restarted
892 if (effect->state() == EffectModule::ACTIVE ||
893 effect->state() == EffectModule::STOPPING) {
894 effect->start();
895 }
896
897 sp<EffectChain> dstChain = effect->chain().promote();
898 if (dstChain == 0) {
899 srcThread->addEffect_l(effect);
900 return INVALID_OPERATION;
901 }
902 AudioSystem::unregisterEffect(effect->id());
903 AudioSystem::registerEffect(&effect->desc(),
904 srcThread->id(),
905 dstChain->strategy(),
906 AUDIO_SESSION_OUTPUT_MIX,
907 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700908 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800909 }
910 status = playbackThread->attachAuxEffect(this, EffectId);
911 }
912 return status;
913}
914
915void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
916{
917 mAuxEffectId = EffectId;
918 mAuxBuffer = buffer;
919}
920
921bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
922 size_t audioHalFrames)
923{
924 // a track is considered presented when the total number of frames written to audio HAL
925 // corresponds to the number of frames written when presentationComplete() is called for the
926 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800927 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
928 // to detect when all frames have been played. In this case framesWritten isn't
929 // useful because it doesn't always reflect whether there is data in the h/w
930 // buffers, particularly if a track has been paused and resumed during draining
931 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
932 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800933 if (mPresentationCompleteFrames == 0) {
934 mPresentationCompleteFrames = framesWritten + audioHalFrames;
935 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
936 mPresentationCompleteFrames, audioHalFrames);
937 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800938
939 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800940 ALOGV("presentationComplete() session %d complete: framesWritten %d",
941 mSessionId, framesWritten);
942 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800943 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800944 return true;
945 }
946 return false;
947}
948
949void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
950{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700951 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800952 if (mSyncEvents[i]->type() == type) {
953 mSyncEvents[i]->trigger();
954 mSyncEvents.removeAt(i);
955 i--;
956 }
957 }
958}
959
960// implement VolumeBufferProvider interface
961
962uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
963{
964 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
965 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800966 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800967 uint32_t vl = vlr & 0xFFFF;
968 uint32_t vr = vlr >> 16;
969 // track volumes come from shared memory, so can't be trusted and must be clamped
970 if (vl > MAX_GAIN_INT) {
971 vl = MAX_GAIN_INT;
972 }
973 if (vr > MAX_GAIN_INT) {
974 vr = MAX_GAIN_INT;
975 }
976 // now apply the cached master volume and stream type volume;
977 // this is trusted but lacks any synchronization or barrier so may be stale
978 float v = mCachedVolume;
979 vl *= v;
980 vr *= v;
981 // re-combine into U4.16
982 vlr = (vr << 16) | (vl & 0xFFFF);
983 // FIXME look at mute, pause, and stop flags
984 return vlr;
985}
986
987status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
988{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800989 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800990 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
991 (mState == STOPPED)))) {
992 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
993 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
994 event->cancel();
995 return INVALID_OPERATION;
996 }
997 (void) TrackBase::setSyncEvent(event);
998 return NO_ERROR;
999}
1000
Glenn Kasten5736c352012-12-04 12:12:34 -08001001void AudioFlinger::PlaybackThread::Track::invalidate()
1002{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001003 // FIXME should use proxy, and needs work
1004 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001005 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001006 android_atomic_release_store(0x40000000, &cblk->mFutex);
1007 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1008 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001009 mIsInvalid = true;
1010}
1011
Eric Laurent59fe0102013-09-27 18:48:26 -07001012void AudioFlinger::PlaybackThread::Track::signal()
1013{
1014 sp<ThreadBase> thread = mThread.promote();
1015 if (thread != 0) {
1016 PlaybackThread *t = (PlaybackThread *)thread.get();
1017 Mutex::Autolock _l(t->mLock);
1018 t->broadcast_l();
1019 }
1020}
1021
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001022//To be called with thread lock held
1023bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1024
1025 if (mState == RESUMING)
1026 return true;
1027 /* Resume is pending if track was stopping before pause was called */
1028 if (mState == STOPPING_1 &&
1029 mResumeToStopping)
1030 return true;
1031
1032 return false;
1033}
1034
1035//To be called with thread lock held
1036void AudioFlinger::PlaybackThread::Track::resumeAck() {
1037
1038
1039 if (mState == RESUMING)
1040 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001041
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001042 // Other possibility of pending resume is stopping_1 state
1043 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001044 // drain being called.
1045 if (mState == STOPPING_1) {
1046 mResumeToStopping = false;
1047 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001048}
Eric Laurent81784c32012-11-19 14:55:58 -08001049// ----------------------------------------------------------------------------
1050
1051sp<AudioFlinger::PlaybackThread::TimedTrack>
1052AudioFlinger::PlaybackThread::TimedTrack::create(
1053 PlaybackThread *thread,
1054 const sp<Client>& client,
1055 audio_stream_type_t streamType,
1056 uint32_t sampleRate,
1057 audio_format_t format,
1058 audio_channel_mask_t channelMask,
1059 size_t frameCount,
1060 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001061 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001062 int uid)
1063{
Eric Laurent81784c32012-11-19 14:55:58 -08001064 if (!client->reserveTimedTrack())
1065 return 0;
1066
1067 return new TimedTrack(
1068 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001069 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001070}
1071
1072AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1073 PlaybackThread *thread,
1074 const sp<Client>& client,
1075 audio_stream_type_t streamType,
1076 uint32_t sampleRate,
1077 audio_format_t format,
1078 audio_channel_mask_t channelMask,
1079 size_t frameCount,
1080 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001081 int sessionId,
1082 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001083 : Track(thread, client, streamType, sampleRate, format, channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001084 frameCount, sharedBuffer, sessionId, uid, IAudioFlinger::TRACK_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001085 mQueueHeadInFlight(false),
1086 mTrimQueueHeadOnRelease(false),
1087 mFramesPendingInQueue(0),
1088 mTimedSilenceBuffer(NULL),
1089 mTimedSilenceBufferSize(0),
1090 mTimedAudioOutputOnTime(false),
1091 mMediaTimeTransformValid(false)
1092{
1093 LocalClock lc;
1094 mLocalTimeFreq = lc.getLocalFreq();
1095
1096 mLocalTimeToSampleTransform.a_zero = 0;
1097 mLocalTimeToSampleTransform.b_zero = 0;
1098 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1099 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1100 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1101 &mLocalTimeToSampleTransform.a_to_b_denom);
1102
1103 mMediaTimeToSampleTransform.a_zero = 0;
1104 mMediaTimeToSampleTransform.b_zero = 0;
1105 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1106 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1107 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1108 &mMediaTimeToSampleTransform.a_to_b_denom);
1109}
1110
1111AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1112 mClient->releaseTimedTrack();
1113 delete [] mTimedSilenceBuffer;
1114}
1115
1116status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1117 size_t size, sp<IMemory>* buffer) {
1118
1119 Mutex::Autolock _l(mTimedBufferQueueLock);
1120
1121 trimTimedBufferQueue_l();
1122
1123 // lazily initialize the shared memory heap for timed buffers
1124 if (mTimedMemoryDealer == NULL) {
1125 const int kTimedBufferHeapSize = 512 << 10;
1126
1127 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1128 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001129 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001130 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001131 }
Eric Laurent81784c32012-11-19 14:55:58 -08001132 }
1133
1134 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001135 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001136 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001137 }
1138
1139 *buffer = newBuffer;
1140 return NO_ERROR;
1141}
1142
1143// caller must hold mTimedBufferQueueLock
1144void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1145 int64_t mediaTimeNow;
1146 {
1147 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1148 if (!mMediaTimeTransformValid)
1149 return;
1150
1151 int64_t targetTimeNow;
1152 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1153 ? mCCHelper.getCommonTime(&targetTimeNow)
1154 : mCCHelper.getLocalTime(&targetTimeNow);
1155
1156 if (OK != res)
1157 return;
1158
1159 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1160 &mediaTimeNow)) {
1161 return;
1162 }
1163 }
1164
1165 size_t trimEnd;
1166 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1167 int64_t bufEnd;
1168
1169 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1170 // We have a next buffer. Just use its PTS as the PTS of the frame
1171 // following the last frame in this buffer. If the stream is sparse
1172 // (ie, there are deliberate gaps left in the stream which should be
1173 // filled with silence by the TimedAudioTrack), then this can result
1174 // in one extra buffer being left un-trimmed when it could have
1175 // been. In general, this is not typical, and we would rather
1176 // optimized away the TS calculation below for the more common case
1177 // where PTSes are contiguous.
1178 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1179 } else {
1180 // We have no next buffer. Compute the PTS of the frame following
1181 // the last frame in this buffer by computing the duration of of
1182 // this frame in media time units and adding it to the PTS of the
1183 // buffer.
1184 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1185 / mFrameSize;
1186
1187 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1188 &bufEnd)) {
1189 ALOGE("Failed to convert frame count of %lld to media time"
1190 " duration" " (scale factor %d/%u) in %s",
1191 frameCount,
1192 mMediaTimeToSampleTransform.a_to_b_numer,
1193 mMediaTimeToSampleTransform.a_to_b_denom,
1194 __PRETTY_FUNCTION__);
1195 break;
1196 }
1197 bufEnd += mTimedBufferQueue[trimEnd].pts();
1198 }
1199
1200 if (bufEnd > mediaTimeNow)
1201 break;
1202
1203 // Is the buffer we want to use in the middle of a mix operation right
1204 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1205 // from the mixer which should be coming back shortly.
1206 if (!trimEnd && mQueueHeadInFlight) {
1207 mTrimQueueHeadOnRelease = true;
1208 }
1209 }
1210
1211 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1212 if (trimStart < trimEnd) {
1213 // Update the bookkeeping for framesReady()
1214 for (size_t i = trimStart; i < trimEnd; ++i) {
1215 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1216 }
1217
1218 // Now actually remove the buffers from the queue.
1219 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1220 }
1221}
1222
1223void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1224 const char* logTag) {
1225 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1226 "%s called (reason \"%s\"), but timed buffer queue has no"
1227 " elements to trim.", __FUNCTION__, logTag);
1228
1229 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1230 mTimedBufferQueue.removeAt(0);
1231}
1232
1233void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1234 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001235 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001236 uint32_t bufBytes = buf.buffer()->size();
1237 uint32_t consumedAlready = buf.position();
1238
1239 ALOG_ASSERT(consumedAlready <= bufBytes,
1240 "Bad bookkeeping while updating frames pending. Timed buffer is"
1241 " only %u bytes long, but claims to have consumed %u"
1242 " bytes. (update reason: \"%s\")",
1243 bufBytes, consumedAlready, logTag);
1244
1245 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1246 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1247 "Bad bookkeeping while updating frames pending. Should have at"
1248 " least %u queued frames, but we think we have only %u. (update"
1249 " reason: \"%s\")",
1250 bufFrames, mFramesPendingInQueue, logTag);
1251
1252 mFramesPendingInQueue -= bufFrames;
1253}
1254
1255status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1256 const sp<IMemory>& buffer, int64_t pts) {
1257
1258 {
1259 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1260 if (!mMediaTimeTransformValid)
1261 return INVALID_OPERATION;
1262 }
1263
1264 Mutex::Autolock _l(mTimedBufferQueueLock);
1265
1266 uint32_t bufFrames = buffer->size() / mFrameSize;
1267 mFramesPendingInQueue += bufFrames;
1268 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1269
1270 return NO_ERROR;
1271}
1272
1273status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1274 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1275
1276 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1277 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1278 target);
1279
1280 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1281 target == TimedAudioTrack::COMMON_TIME)) {
1282 return BAD_VALUE;
1283 }
1284
1285 Mutex::Autolock lock(mMediaTimeTransformLock);
1286 mMediaTimeTransform = xform;
1287 mMediaTimeTransformTarget = target;
1288 mMediaTimeTransformValid = true;
1289
1290 return NO_ERROR;
1291}
1292
1293#define min(a, b) ((a) < (b) ? (a) : (b))
1294
1295// implementation of getNextBuffer for tracks whose buffers have timestamps
1296status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1297 AudioBufferProvider::Buffer* buffer, int64_t pts)
1298{
1299 if (pts == AudioBufferProvider::kInvalidPTS) {
1300 buffer->raw = NULL;
1301 buffer->frameCount = 0;
1302 mTimedAudioOutputOnTime = false;
1303 return INVALID_OPERATION;
1304 }
1305
1306 Mutex::Autolock _l(mTimedBufferQueueLock);
1307
1308 ALOG_ASSERT(!mQueueHeadInFlight,
1309 "getNextBuffer called without releaseBuffer!");
1310
1311 while (true) {
1312
1313 // if we have no timed buffers, then fail
1314 if (mTimedBufferQueue.isEmpty()) {
1315 buffer->raw = NULL;
1316 buffer->frameCount = 0;
1317 return NOT_ENOUGH_DATA;
1318 }
1319
1320 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1321
1322 // calculate the PTS of the head of the timed buffer queue expressed in
1323 // local time
1324 int64_t headLocalPTS;
1325 {
1326 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1327
1328 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1329
1330 if (mMediaTimeTransform.a_to_b_denom == 0) {
1331 // the transform represents a pause, so yield silence
1332 timedYieldSilence_l(buffer->frameCount, buffer);
1333 return NO_ERROR;
1334 }
1335
1336 int64_t transformedPTS;
1337 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1338 &transformedPTS)) {
1339 // the transform failed. this shouldn't happen, but if it does
1340 // then just drop this buffer
1341 ALOGW("timedGetNextBuffer transform failed");
1342 buffer->raw = NULL;
1343 buffer->frameCount = 0;
1344 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1345 return NO_ERROR;
1346 }
1347
1348 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1349 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1350 &headLocalPTS)) {
1351 buffer->raw = NULL;
1352 buffer->frameCount = 0;
1353 return INVALID_OPERATION;
1354 }
1355 } else {
1356 headLocalPTS = transformedPTS;
1357 }
1358 }
1359
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001360 uint32_t sr = sampleRate();
1361
Eric Laurent81784c32012-11-19 14:55:58 -08001362 // adjust the head buffer's PTS to reflect the portion of the head buffer
1363 // that has already been consumed
1364 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001365 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001366
1367 // Calculate the delta in samples between the head of the input buffer
1368 // queue and the start of the next output buffer that will be written.
1369 // If the transformation fails because of over or underflow, it means
1370 // that the sample's position in the output stream is so far out of
1371 // whack that it should just be dropped.
1372 int64_t sampleDelta;
1373 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1374 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1375 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1376 " mix");
1377 continue;
1378 }
1379 if (!mLocalTimeToSampleTransform.doForwardTransform(
1380 (effectivePTS - pts) << 32, &sampleDelta)) {
1381 ALOGV("*** too late during sample rate transform: dropped buffer");
1382 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1383 continue;
1384 }
1385
1386 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1387 " sampleDelta=[%d.%08x]",
1388 head.pts(), head.position(), pts,
1389 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1390 + (sampleDelta >> 32)),
1391 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1392
1393 // if the delta between the ideal placement for the next input sample and
1394 // the current output position is within this threshold, then we will
1395 // concatenate the next input samples to the previous output
1396 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001397 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001398
1399 // if this is the first buffer of audio that we're emitting from this track
1400 // then it should be almost exactly on time.
1401 const int64_t kSampleStartupThreshold = 1LL << 32;
1402
1403 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1404 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1405 // the next input is close enough to being on time, so concatenate it
1406 // with the last output
1407 timedYieldSamples_l(buffer);
1408
1409 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1410 head.position(), buffer->frameCount);
1411 return NO_ERROR;
1412 }
1413
1414 // Looks like our output is not on time. Reset our on timed status.
1415 // Next time we mix samples from our input queue, then should be within
1416 // the StartupThreshold.
1417 mTimedAudioOutputOnTime = false;
1418 if (sampleDelta > 0) {
1419 // the gap between the current output position and the proper start of
1420 // the next input sample is too big, so fill it with silence
1421 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1422
1423 timedYieldSilence_l(framesUntilNextInput, buffer);
1424 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1425 return NO_ERROR;
1426 } else {
1427 // the next input sample is late
1428 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1429 size_t onTimeSamplePosition =
1430 head.position() + lateFrames * mFrameSize;
1431
1432 if (onTimeSamplePosition > head.buffer()->size()) {
1433 // all the remaining samples in the head are too late, so
1434 // drop it and move on
1435 ALOGV("*** too late: dropped buffer");
1436 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1437 continue;
1438 } else {
1439 // skip over the late samples
1440 head.setPosition(onTimeSamplePosition);
1441
1442 // yield the available samples
1443 timedYieldSamples_l(buffer);
1444
1445 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1446 return NO_ERROR;
1447 }
1448 }
1449 }
1450}
1451
1452// Yield samples from the timed buffer queue head up to the given output
1453// buffer's capacity.
1454//
1455// Caller must hold mTimedBufferQueueLock
1456void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1457 AudioBufferProvider::Buffer* buffer) {
1458
1459 const TimedBuffer& head = mTimedBufferQueue[0];
1460
1461 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1462 head.position());
1463
1464 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1465 mFrameSize);
1466 size_t framesRequested = buffer->frameCount;
1467 buffer->frameCount = min(framesLeftInHead, framesRequested);
1468
1469 mQueueHeadInFlight = true;
1470 mTimedAudioOutputOnTime = true;
1471}
1472
1473// Yield samples of silence up to the given output buffer's capacity
1474//
1475// Caller must hold mTimedBufferQueueLock
1476void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1477 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1478
1479 // lazily allocate a buffer filled with silence
1480 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1481 delete [] mTimedSilenceBuffer;
1482 mTimedSilenceBufferSize = numFrames * mFrameSize;
1483 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1484 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1485 }
1486
1487 buffer->raw = mTimedSilenceBuffer;
1488 size_t framesRequested = buffer->frameCount;
1489 buffer->frameCount = min(numFrames, framesRequested);
1490
1491 mTimedAudioOutputOnTime = false;
1492}
1493
1494// AudioBufferProvider interface
1495void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1496 AudioBufferProvider::Buffer* buffer) {
1497
1498 Mutex::Autolock _l(mTimedBufferQueueLock);
1499
1500 // If the buffer which was just released is part of the buffer at the head
1501 // of the queue, be sure to update the amt of the buffer which has been
1502 // consumed. If the buffer being returned is not part of the head of the
1503 // queue, its either because the buffer is part of the silence buffer, or
1504 // because the head of the timed queue was trimmed after the mixer called
1505 // getNextBuffer but before the mixer called releaseBuffer.
1506 if (buffer->raw == mTimedSilenceBuffer) {
1507 ALOG_ASSERT(!mQueueHeadInFlight,
1508 "Queue head in flight during release of silence buffer!");
1509 goto done;
1510 }
1511
1512 ALOG_ASSERT(mQueueHeadInFlight,
1513 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1514 " head in flight.");
1515
1516 if (mTimedBufferQueue.size()) {
1517 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1518
1519 void* start = head.buffer()->pointer();
1520 void* end = reinterpret_cast<void*>(
1521 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1522 + head.buffer()->size());
1523
1524 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1525 "released buffer not within the head of the timed buffer"
1526 " queue; qHead = [%p, %p], released buffer = %p",
1527 start, end, buffer->raw);
1528
1529 head.setPosition(head.position() +
1530 (buffer->frameCount * mFrameSize));
1531 mQueueHeadInFlight = false;
1532
1533 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1534 "Bad bookkeeping during releaseBuffer! Should have at"
1535 " least %u queued frames, but we think we have only %u",
1536 buffer->frameCount, mFramesPendingInQueue);
1537
1538 mFramesPendingInQueue -= buffer->frameCount;
1539
1540 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1541 || mTrimQueueHeadOnRelease) {
1542 trimTimedBufferQueueHead_l("releaseBuffer");
1543 mTrimQueueHeadOnRelease = false;
1544 }
1545 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001546 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001547 " buffers in the timed buffer queue");
1548 }
1549
1550done:
1551 buffer->raw = 0;
1552 buffer->frameCount = 0;
1553}
1554
1555size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1556 Mutex::Autolock _l(mTimedBufferQueueLock);
1557 return mFramesPendingInQueue;
1558}
1559
1560AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1561 : mPTS(0), mPosition(0) {}
1562
1563AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1564 const sp<IMemory>& buffer, int64_t pts)
1565 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1566
1567
1568// ----------------------------------------------------------------------------
1569
1570AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1571 PlaybackThread *playbackThread,
1572 DuplicatingThread *sourceThread,
1573 uint32_t sampleRate,
1574 audio_format_t format,
1575 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001576 size_t frameCount,
1577 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001578 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001579 NULL, 0, uid, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001580 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001581{
1582
1583 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001584 mOutBuffer.frameCount = 0;
1585 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001586 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001587 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001588 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001589 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001590 // since client and server are in the same process,
1591 // the buffer has the same virtual address on both sides
1592 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001593 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1594 mClientProxy->setSendLevel(0.0);
1595 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001596 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1597 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001598 } else {
1599 ALOGW("Error creating output track on thread %p", playbackThread);
1600 }
1601}
1602
1603AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1604{
1605 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001606 delete mClientProxy;
1607 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001608}
1609
1610status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1611 int triggerSession)
1612{
1613 status_t status = Track::start(event, triggerSession);
1614 if (status != NO_ERROR) {
1615 return status;
1616 }
1617
1618 mActive = true;
1619 mRetryCount = 127;
1620 return status;
1621}
1622
1623void AudioFlinger::PlaybackThread::OutputTrack::stop()
1624{
1625 Track::stop();
1626 clearBufferQueue();
1627 mOutBuffer.frameCount = 0;
1628 mActive = false;
1629}
1630
1631bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1632{
1633 Buffer *pInBuffer;
1634 Buffer inBuffer;
1635 uint32_t channelCount = mChannelCount;
1636 bool outputBufferFull = false;
1637 inBuffer.frameCount = frames;
1638 inBuffer.i16 = data;
1639
1640 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1641
1642 if (!mActive && frames != 0) {
1643 start();
1644 sp<ThreadBase> thread = mThread.promote();
1645 if (thread != 0) {
1646 MixerThread *mixerThread = (MixerThread *)thread.get();
1647 if (mFrameCount > frames) {
1648 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1649 uint32_t startFrames = (mFrameCount - frames);
1650 pInBuffer = new Buffer;
1651 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1652 pInBuffer->frameCount = startFrames;
1653 pInBuffer->i16 = pInBuffer->mBuffer;
1654 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1655 mBufferQueue.add(pInBuffer);
1656 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001657 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001658 }
1659 }
1660 }
1661 }
1662
1663 while (waitTimeLeftMs) {
1664 // First write pending buffers, then new data
1665 if (mBufferQueue.size()) {
1666 pInBuffer = mBufferQueue.itemAt(0);
1667 } else {
1668 pInBuffer = &inBuffer;
1669 }
1670
1671 if (pInBuffer->frameCount == 0) {
1672 break;
1673 }
1674
1675 if (mOutBuffer.frameCount == 0) {
1676 mOutBuffer.frameCount = pInBuffer->frameCount;
1677 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001678 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1679 if (status != NO_ERROR) {
1680 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1681 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001682 outputBufferFull = true;
1683 break;
1684 }
1685 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1686 if (waitTimeLeftMs >= waitTimeMs) {
1687 waitTimeLeftMs -= waitTimeMs;
1688 } else {
1689 waitTimeLeftMs = 0;
1690 }
1691 }
1692
1693 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1694 pInBuffer->frameCount;
1695 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001696 Proxy::Buffer buf;
1697 buf.mFrameCount = outFrames;
1698 buf.mRaw = NULL;
1699 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001700 pInBuffer->frameCount -= outFrames;
1701 pInBuffer->i16 += outFrames * channelCount;
1702 mOutBuffer.frameCount -= outFrames;
1703 mOutBuffer.i16 += outFrames * channelCount;
1704
1705 if (pInBuffer->frameCount == 0) {
1706 if (mBufferQueue.size()) {
1707 mBufferQueue.removeAt(0);
1708 delete [] pInBuffer->mBuffer;
1709 delete pInBuffer;
1710 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1711 mThread.unsafe_get(), mBufferQueue.size());
1712 } else {
1713 break;
1714 }
1715 }
1716 }
1717
1718 // If we could not write all frames, allocate a buffer and queue it for next time.
1719 if (inBuffer.frameCount) {
1720 sp<ThreadBase> thread = mThread.promote();
1721 if (thread != 0 && !thread->standby()) {
1722 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1723 pInBuffer = new Buffer;
1724 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1725 pInBuffer->frameCount = inBuffer.frameCount;
1726 pInBuffer->i16 = pInBuffer->mBuffer;
1727 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1728 sizeof(int16_t));
1729 mBufferQueue.add(pInBuffer);
1730 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1731 mThread.unsafe_get(), mBufferQueue.size());
1732 } else {
1733 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1734 mThread.unsafe_get(), this);
1735 }
1736 }
1737 }
1738
1739 // Calling write() with a 0 length buffer, means that no more data will be written:
1740 // If no more buffers are pending, fill output track buffer to make sure it is started
1741 // by output mixer.
1742 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001743 // FIXME borken, replace by getting framesReady() from proxy
1744 size_t user = 0; // was mCblk->user
1745 if (user < mFrameCount) {
1746 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001747 pInBuffer = new Buffer;
1748 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1749 pInBuffer->frameCount = frames;
1750 pInBuffer->i16 = pInBuffer->mBuffer;
1751 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1752 mBufferQueue.add(pInBuffer);
1753 } else if (mActive) {
1754 stop();
1755 }
1756 }
1757
1758 return outputBufferFull;
1759}
1760
1761status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1762 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1763{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001764 ClientProxy::Buffer buf;
1765 buf.mFrameCount = buffer->frameCount;
1766 struct timespec timeout;
1767 timeout.tv_sec = waitTimeMs / 1000;
1768 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1769 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1770 buffer->frameCount = buf.mFrameCount;
1771 buffer->raw = buf.mRaw;
1772 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001773}
1774
Eric Laurent81784c32012-11-19 14:55:58 -08001775void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1776{
1777 size_t size = mBufferQueue.size();
1778
1779 for (size_t i = 0; i < size; i++) {
1780 Buffer *pBuffer = mBufferQueue.itemAt(i);
1781 delete [] pBuffer->mBuffer;
1782 delete pBuffer;
1783 }
1784 mBufferQueue.clear();
1785}
1786
1787
1788// ----------------------------------------------------------------------------
1789// Record
1790// ----------------------------------------------------------------------------
1791
1792AudioFlinger::RecordHandle::RecordHandle(
1793 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1794 : BnAudioRecord(),
1795 mRecordTrack(recordTrack)
1796{
1797}
1798
1799AudioFlinger::RecordHandle::~RecordHandle() {
1800 stop_nonvirtual();
1801 mRecordTrack->destroy();
1802}
1803
Eric Laurent81784c32012-11-19 14:55:58 -08001804status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1805 int triggerSession) {
1806 ALOGV("RecordHandle::start()");
1807 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1808}
1809
1810void AudioFlinger::RecordHandle::stop() {
1811 stop_nonvirtual();
1812}
1813
1814void AudioFlinger::RecordHandle::stop_nonvirtual() {
1815 ALOGV("RecordHandle::stop()");
1816 mRecordTrack->stop();
1817}
1818
1819status_t AudioFlinger::RecordHandle::onTransact(
1820 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1821{
1822 return BnAudioRecord::onTransact(code, data, reply, flags);
1823}
1824
1825// ----------------------------------------------------------------------------
1826
Glenn Kasten05997e22014-03-13 15:08:33 -07001827// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001828AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1829 RecordThread *thread,
1830 const sp<Client>& client,
1831 uint32_t sampleRate,
1832 audio_format_t format,
1833 audio_channel_mask_t channelMask,
1834 size_t frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001835 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001836 int uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001837 IAudioFlinger::track_flags_t flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001838 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001839 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, uid,
1840 flags, false /*isOut*/,
1841 (flags & IAudioFlinger::TRACK_FAST) != 0 /*useReadOnlyHeap*/),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001842 mOverflow(false), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0),
1843 // See real initialization of mRsmpInFront at RecordThread::start()
1844 mRsmpInUnrel(0), mRsmpInFront(0), mFramesToDrop(0), mResamplerBufferProvider(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001845{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001846 if (mCblk == NULL) {
1847 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001848 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001849
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001850 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, mFrameSize);
1851
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001852 uint32_t channelCount = popcount(channelMask);
1853 // FIXME I don't understand either of the channel count checks
1854 if (thread->mSampleRate != sampleRate && thread->mChannelCount <= FCC_2 &&
1855 channelCount <= FCC_2) {
1856 // sink SR
1857 mResampler = AudioResampler::create(16, thread->mChannelCount, sampleRate);
1858 // source SR
1859 mResampler->setSampleRate(thread->mSampleRate);
1860 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
1861 mResamplerBufferProvider = new ResamplerBufferProvider(this);
1862 }
Eric Laurent81784c32012-11-19 14:55:58 -08001863}
1864
1865AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1866{
1867 ALOGV("%s", __func__);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001868 delete mResampler;
1869 delete[] mRsmpOutBuffer;
1870 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001871}
1872
1873// AudioBufferProvider interface
1874status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001875 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001876{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001877 ServerProxy::Buffer buf;
1878 buf.mFrameCount = buffer->frameCount;
1879 status_t status = mServerProxy->obtainBuffer(&buf);
1880 buffer->frameCount = buf.mFrameCount;
1881 buffer->raw = buf.mRaw;
1882 if (buf.mFrameCount == 0) {
1883 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001884 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001885 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001886 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001887}
1888
1889status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1890 int triggerSession)
1891{
1892 sp<ThreadBase> thread = mThread.promote();
1893 if (thread != 0) {
1894 RecordThread *recordThread = (RecordThread *)thread.get();
1895 return recordThread->start(this, event, triggerSession);
1896 } else {
1897 return BAD_VALUE;
1898 }
1899}
1900
1901void AudioFlinger::RecordThread::RecordTrack::stop()
1902{
1903 sp<ThreadBase> thread = mThread.promote();
1904 if (thread != 0) {
1905 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001906 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001907 AudioSystem::stopInput(recordThread->id());
1908 }
1909 }
1910}
1911
1912void AudioFlinger::RecordThread::RecordTrack::destroy()
1913{
1914 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1915 sp<RecordTrack> keep(this);
1916 {
1917 sp<ThreadBase> thread = mThread.promote();
1918 if (thread != 0) {
1919 if (mState == ACTIVE || mState == RESUMING) {
1920 AudioSystem::stopInput(thread->id());
1921 }
1922 AudioSystem::releaseInput(thread->id());
1923 Mutex::Autolock _l(thread->mLock);
1924 RecordThread *recordThread = (RecordThread *) thread.get();
1925 recordThread->destroyTrack_l(this);
1926 }
1927 }
1928}
1929
Eric Laurent9a54bc22013-09-09 09:08:44 -07001930void AudioFlinger::RecordThread::RecordTrack::invalidate()
1931{
1932 // FIXME should use proxy, and needs work
1933 audio_track_cblk_t* cblk = mCblk;
1934 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1935 android_atomic_release_store(0x40000000, &cblk->mFutex);
1936 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1937 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1938}
1939
Eric Laurent81784c32012-11-19 14:55:58 -08001940
1941/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1942{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001943 result.append(" Active Client Fmt Chn mask Session S Server fCount Resampling\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001944}
1945
Marco Nelissenb2208842014-02-07 14:00:50 -08001946void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001947{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001948 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %10d\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001949 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001950 (mClient == 0) ? getpid_cached : mClient->pid(),
1951 mFormat,
1952 mChannelMask,
1953 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001954 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001955 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001956 mFrameCount,
1957 mResampler != NULL);
1958
Eric Laurent81784c32012-11-19 14:55:58 -08001959}
1960
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001961void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1962{
1963 if (event == mSyncStartEvent) {
1964 ssize_t framesToDrop = 0;
1965 sp<ThreadBase> threadBase = mThread.promote();
1966 if (threadBase != 0) {
1967 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1968 // from audio HAL
1969 framesToDrop = threadBase->mFrameCount * 2;
1970 }
1971 mFramesToDrop = framesToDrop;
1972 }
1973}
1974
1975void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1976{
1977 if (mSyncStartEvent != 0) {
1978 mSyncStartEvent->cancel();
1979 mSyncStartEvent.clear();
1980 }
1981 mFramesToDrop = 0;
1982}
1983
Eric Laurent81784c32012-11-19 14:55:58 -08001984}; // namespace android