blob: f9f51c8ce4e91a183b3f099afb9214cdb3cc9e92 [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"
Glenn Kastenad8510a2015-02-17 16:24:07 -080023#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070025#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080026#include <utils/Log.h>
27
28#include <private/media/AudioTrackShared.h>
29
30#include <common_time/cc_helper.h>
31#include <common_time/local_clock.h>
32
33#include "AudioMixer.h"
34#include "AudioFlinger.h"
35#include "ServiceUtilities.h"
36
Glenn Kastenda6ef132013-01-10 12:31:01 -080037#include <media/nbaio/Pipe.h>
38#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080040
Eric Laurent81784c32012-11-19 14:55:58 -080041// ----------------------------------------------------------------------------
42
43// Note: the following macro is used for extremely verbose logging message. In
44// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
45// 0; but one side effect of this is to turn all LOGV's as well. Some messages
46// are so verbose that we want to suppress them even when we have ALOG_ASSERT
47// turned on. Do not uncomment the #def below unless you really know what you
48// are doing and want to see all of the extremely verbose messages.
49//#define VERY_VERY_VERBOSE_LOGGING
50#ifdef VERY_VERY_VERBOSE_LOGGING
51#define ALOGVV ALOGV
52#else
53#define ALOGVV(a...) do { } while(0)
54#endif
55
56namespace android {
57
58// ----------------------------------------------------------------------------
59// TrackBase
60// ----------------------------------------------------------------------------
61
Glenn Kastenda6ef132013-01-10 12:31:01 -080062static volatile int32_t nextTrackId = 55;
63
Eric Laurent81784c32012-11-19 14:55:58 -080064// TrackBase constructor must be called with AudioFlinger::mLock held
65AudioFlinger::ThreadBase::TrackBase::TrackBase(
66 ThreadBase *thread,
67 const sp<Client>& client,
68 uint32_t sampleRate,
69 audio_format_t format,
70 audio_channel_mask_t channelMask,
71 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070072 void *buffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080073 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080074 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070075 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070076 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070077 alloc_type alloc,
78 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080079 : RefBase(),
80 mThread(thread),
81 mClient(client),
82 mCblk(NULL),
83 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080084 mState(IDLE),
85 mSampleRate(sampleRate),
86 mFormat(format),
87 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070088 mChannelCount(isOut ?
89 audio_channel_count_from_out_mask(channelMask) :
90 audio_channel_count_from_in_mask(channelMask)),
Eric Laurent81784c32012-11-19 14:55:58 -080091 mFrameSize(audio_is_linear_pcm(format) ?
92 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
93 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080094 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070095 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080096 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080097 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080098 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070099 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -0700100 mType(type),
101 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800102{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800103 // if the caller is us, trust the specified uid
104 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
105 int newclientUid = IPCThreadState::self()->getCallingUid();
106 if (clientUid != -1 && clientUid != newclientUid) {
107 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
108 }
109 clientUid = newclientUid;
110 }
111 // clientUid contains the uid of the app that is responsible for this track, so we can blame
112 // battery usage on it.
113 mUid = clientUid;
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hungeaa39692017-02-13 18:48:39 -0800116
117 size_t bufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
118 // check overflow when computing bufferSize due to multiplication by mFrameSize.
119 if (bufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
120 || mFrameSize == 0 // format needs to be correct
121 || bufferSize > SIZE_MAX / mFrameSize) {
122 android_errorWriteLog(0x534e4554, "34749571");
123 return;
124 }
125 bufferSize *= mFrameSize;
126
Eric Laurent81784c32012-11-19 14:55:58 -0800127 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700128 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hungeaa39692017-02-13 18:48:39 -0800129 // check overflow when computing allocation size for streaming tracks.
130 if (size > SIZE_MAX - bufferSize) {
131 android_errorWriteLog(0x534e4554, "34749571");
132 return;
133 }
Eric Laurent81784c32012-11-19 14:55:58 -0800134 size += bufferSize;
135 }
136
137 if (client != 0) {
138 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700139 if (mCblkMemory == 0 ||
140 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800141 ALOGE("not enough memory for AudioTrack size=%u", size);
142 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700143 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800144 return;
145 }
146 } else {
Andy Hung1159ffd2017-02-13 18:50:48 -0800147 mCblk = (audio_track_cblk_t *) malloc(size);
148 if (mCblk == NULL) {
149 ALOGE("not enough memory for AudioTrack size=%zu", size);
150 return;
151 }
Eric Laurent81784c32012-11-19 14:55:58 -0800152 }
153
154 // construct the shared structure in-place.
155 if (mCblk != NULL) {
156 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700157 switch (alloc) {
158 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700159 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
160 if (roHeap == 0 ||
161 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
162 (mBuffer = mBufferMemory->pointer()) == NULL) {
163 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
164 if (roHeap != 0) {
165 roHeap->dump("buffer");
166 }
167 mCblkMemory.clear();
168 mBufferMemory.clear();
169 return;
170 }
Eric Laurent81784c32012-11-19 14:55:58 -0800171 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700172 } break;
173 case ALLOC_PIPE:
174 mBufferMemory = thread->pipeMemory();
175 // mBuffer is the virtual address as seen from current process (mediaserver),
176 // and should normally be coming from mBufferMemory->pointer().
177 // However in this case the TrackBase does not reference the buffer directly.
178 // It should references the buffer via the pipe.
179 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
180 mBuffer = NULL;
181 break;
182 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700183 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700184 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700185 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
186 memset(mBuffer, 0, bufferSize);
187 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700188 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800189#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700190 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800191#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700192 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700193 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700194 case ALLOC_LOCAL:
195 mBuffer = calloc(1, bufferSize);
196 break;
197 case ALLOC_NONE:
198 mBuffer = buffer;
199 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800200 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201
Glenn Kasten46909e72013-02-26 09:20:22 -0800202#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800203 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700204 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800205 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800206 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
207 size_t numCounterOffers = 0;
208 const NBAIO_Format offers[1] = {pipeFormat};
209 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
210 ALOG_ASSERT(index == 0);
211 PipeReader *pipeReader = new PipeReader(*pipe);
212 numCounterOffers = 0;
213 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
214 ALOG_ASSERT(index == 0);
215 mTeeSink = pipe;
216 mTeeSource = pipeReader;
217 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800218 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800219#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800220
Eric Laurent81784c32012-11-19 14:55:58 -0800221 }
222}
223
Eric Laurent83b88082014-06-20 18:31:16 -0700224status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
225{
226 status_t status;
227 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
228 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
229 } else {
230 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
231 }
232 return status;
233}
234
Eric Laurent81784c32012-11-19 14:55:58 -0800235AudioFlinger::ThreadBase::TrackBase::~TrackBase()
236{
Glenn Kasten46909e72013-02-26 09:20:22 -0800237#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800238 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800239#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800240 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
241 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800242 if (mCblk != NULL) {
Andy Hung1159ffd2017-02-13 18:50:48 -0800243 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurent81784c32012-11-19 14:55:58 -0800244 if (mClient == 0) {
Andy Hung1159ffd2017-02-13 18:50:48 -0800245 free(mCblk);
Eric Laurent81784c32012-11-19 14:55:58 -0800246 }
247 }
248 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
249 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700250 // Client destructor must run with AudioFlinger client mutex locked
251 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800252 // If the client's reference count drops to zero, the associated destructor
253 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
254 // relying on the automatic clear() at end of scope.
255 mClient.clear();
256 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700257 // flush the binder command buffer
258 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800259}
260
261// AudioBufferProvider interface
262// getNextBuffer() = 0;
263// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
264void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
265{
Glenn Kasten46909e72013-02-26 09:20:22 -0800266#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800267 if (mTeeSink != 0) {
268 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
269 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800270#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800271
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800272 ServerProxy::Buffer buf;
273 buf.mFrameCount = buffer->frameCount;
274 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800275 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800276 buffer->raw = NULL;
277 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800278}
279
Eric Laurent81784c32012-11-19 14:55:58 -0800280status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
281{
282 mSyncEvents.add(event);
283 return NO_ERROR;
284}
285
286// ----------------------------------------------------------------------------
287// Playback
288// ----------------------------------------------------------------------------
289
290AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
291 : BnAudioTrack(),
292 mTrack(track)
293{
294}
295
296AudioFlinger::TrackHandle::~TrackHandle() {
297 // just stop the track on deletion, associated resources
298 // will be freed from the main thread once all pending buffers have
299 // been played. Unless it's not in the active track list, in which
300 // case we free everything now...
301 mTrack->destroy();
302}
303
304sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
305 return mTrack->getCblk();
306}
307
308status_t AudioFlinger::TrackHandle::start() {
309 return mTrack->start();
310}
311
312void AudioFlinger::TrackHandle::stop() {
313 mTrack->stop();
314}
315
316void AudioFlinger::TrackHandle::flush() {
317 mTrack->flush();
318}
319
Eric Laurent81784c32012-11-19 14:55:58 -0800320void AudioFlinger::TrackHandle::pause() {
321 mTrack->pause();
322}
323
324status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
325{
326 return mTrack->attachAuxEffect(EffectId);
327}
328
329status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
330 sp<IMemory>* buffer) {
331 if (!mTrack->isTimedTrack())
332 return INVALID_OPERATION;
333
334 PlaybackThread::TimedTrack* tt =
335 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
336 return tt->allocateTimedBuffer(size, buffer);
337}
338
339status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
340 int64_t pts) {
341 if (!mTrack->isTimedTrack())
342 return INVALID_OPERATION;
343
Glenn Kasten663c2242013-09-24 11:52:37 -0700344 if (buffer == 0 || buffer->pointer() == NULL) {
345 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
346 return BAD_VALUE;
347 }
348
Eric Laurent81784c32012-11-19 14:55:58 -0800349 PlaybackThread::TimedTrack* tt =
350 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
351 return tt->queueTimedBuffer(buffer, pts);
352}
353
354status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
355 const LinearTransform& xform, int target) {
356
357 if (!mTrack->isTimedTrack())
358 return INVALID_OPERATION;
359
360 PlaybackThread::TimedTrack* tt =
361 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
362 return tt->setMediaTimeTransform(
363 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
364}
365
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700366status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
367 return mTrack->setParameters(keyValuePairs);
368}
369
Glenn Kasten53cec222013-08-29 09:01:02 -0700370status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
371{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700372 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700373}
374
Eric Laurent59fe0102013-09-27 18:48:26 -0700375
376void AudioFlinger::TrackHandle::signal()
377{
378 return mTrack->signal();
379}
380
Eric Laurent81784c32012-11-19 14:55:58 -0800381status_t AudioFlinger::TrackHandle::onTransact(
382 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
383{
384 return BnAudioTrack::onTransact(code, data, reply, flags);
385}
386
387// ----------------------------------------------------------------------------
388
389// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
390AudioFlinger::PlaybackThread::Track::Track(
391 PlaybackThread *thread,
392 const sp<Client>& client,
393 audio_stream_type_t streamType,
394 uint32_t sampleRate,
395 audio_format_t format,
396 audio_channel_mask_t channelMask,
397 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700398 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800399 const sp<IMemory>& sharedBuffer,
400 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800401 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700402 IAudioFlinger::track_flags_t flags,
403 track_type type)
404 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
405 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
406 sessionId, uid, flags, true /*isOut*/,
407 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
408 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800409 mFillingUpStatus(FS_INVALID),
410 // mRetryCount initialized later when needed
411 mSharedBuffer(sharedBuffer),
412 mStreamType(streamType),
413 mName(-1), // see note below
414 mMainBuffer(thread->mixBuffer()),
415 mAuxBuffer(NULL),
416 mAuxEffectId(0), mHasVolumeController(false),
417 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800418 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800419 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800420 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800421 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800422 mResumeToStopping(false),
Phil Burk1b420972015-04-22 10:52:21 -0700423 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800424{
Eric Laurent83b88082014-06-20 18:31:16 -0700425 // client == 0 implies sharedBuffer == 0
426 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
427
428 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
429 sharedBuffer->size());
430
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700431 if (mCblk == NULL) {
432 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800433 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700434
435 if (sharedBuffer == 0) {
436 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700437 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700438 } else {
Andy Hungf4aeab22017-06-12 17:22:46 -0700439 // Is the shared buffer of sufficient size?
440 // (frameCount * mFrameSize) is <= SIZE_MAX, checked in TrackBase.
441 if (sharedBuffer->size() < frameCount * mFrameSize) {
442 // Workaround: clear out mCblk to indicate track hasn't been properly created.
443 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
444 if (mClient == 0) {
445 free(mCblk);
446 }
447 mCblk = NULL;
448
449 mSharedBuffer.clear(); // release shared buffer early
450 android_errorWriteLog(0x534e4554, "38340117");
451 return;
452 }
453
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700454 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
455 mFrameSize);
456 }
457 mServerProxy = mAudioTrackServerProxy;
458
Glenn Kastenc263ca02014-06-04 20:31:46 -0700459 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700460 if (mName < 0) {
461 ALOGE("no more track names available");
462 return;
463 }
464 // only allocate a fast track index if we were able to allocate a normal track name
465 if (flags & IAudioFlinger::TRACK_FAST) {
466 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
467 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
468 int i = __builtin_ctz(thread->mFastTrackAvailMask);
469 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
470 // FIXME This is too eager. We allocate a fast track index before the
471 // fast track becomes active. Since fast tracks are a scarce resource,
472 // this means we are potentially denying other more important fast tracks from
473 // being created. It would be better to allocate the index dynamically.
474 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700475 thread->mFastTrackAvailMask &= ~(1 << i);
476 }
Eric Laurent81784c32012-11-19 14:55:58 -0800477}
478
479AudioFlinger::PlaybackThread::Track::~Track()
480{
481 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700482
483 // The destructor would clear mSharedBuffer,
484 // but it will not push the decremented reference count,
485 // leaving the client's IMemory dangling indefinitely.
486 // This prevents that leak.
487 if (mSharedBuffer != 0) {
488 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700489 }
Eric Laurent81784c32012-11-19 14:55:58 -0800490}
491
Glenn Kasten03003332013-08-06 15:40:54 -0700492status_t AudioFlinger::PlaybackThread::Track::initCheck() const
493{
494 status_t status = TrackBase::initCheck();
495 if (status == NO_ERROR && mName < 0) {
496 status = NO_MEMORY;
497 }
498 return status;
499}
500
Eric Laurent81784c32012-11-19 14:55:58 -0800501void AudioFlinger::PlaybackThread::Track::destroy()
502{
503 // NOTE: destroyTrack_l() can remove a strong reference to this Track
504 // by removing it from mTracks vector, so there is a risk that this Tracks's
505 // destructor is called. As the destructor needs to lock mLock,
506 // we must acquire a strong reference on this Track before locking mLock
507 // here so that the destructor is called only when exiting this function.
508 // On the other hand, as long as Track::destroy() is only called by
509 // TrackHandle destructor, the TrackHandle still holds a strong ref on
510 // this Track with its member mTrack.
511 sp<Track> keep(this);
512 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700513 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800514 sp<ThreadBase> thread = mThread.promote();
515 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800516 Mutex::Autolock _l(thread->mLock);
517 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700518 wasActive = playbackThread->destroyTrack_l(this);
519 }
520 if (isExternalTrack() && !wasActive) {
Eric Laurente83b55d2014-11-14 10:06:21 -0800521 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800522 }
523 }
524}
525
526/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
527{
Marco Nelissenb2208842014-02-07 14:00:50 -0800528 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700529 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800530}
531
Marco Nelissenb2208842014-02-07 14:00:50 -0800532void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800533{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700534 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800535 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800536 sprintf(buffer, " F %2d", mFastIndex);
537 } else if (mName >= AudioMixer::TRACK0) {
538 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800539 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800540 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800541 }
542 track_state state = mState;
543 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800544 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800545 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800546 } else {
547 switch (state) {
548 case IDLE:
549 stateChar = 'I';
550 break;
551 case STOPPING_1:
552 stateChar = 's';
553 break;
554 case STOPPING_2:
555 stateChar = '5';
556 break;
557 case STOPPED:
558 stateChar = 'S';
559 break;
560 case RESUMING:
561 stateChar = 'R';
562 break;
563 case ACTIVE:
564 stateChar = 'A';
565 break;
566 case PAUSING:
567 stateChar = 'p';
568 break;
569 case PAUSED:
570 stateChar = 'P';
571 break;
572 case FLUSHED:
573 stateChar = 'F';
574 break;
575 default:
576 stateChar = '?';
577 break;
578 }
Eric Laurent81784c32012-11-19 14:55:58 -0800579 }
580 char nowInUnderrun;
581 switch (mObservedUnderruns.mBitFields.mMostRecent) {
582 case UNDERRUN_FULL:
583 nowInUnderrun = ' ';
584 break;
585 case UNDERRUN_PARTIAL:
586 nowInUnderrun = '<';
587 break;
588 case UNDERRUN_EMPTY:
589 nowInUnderrun = '*';
590 break;
591 default:
592 nowInUnderrun = '?';
593 break;
594 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000595 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 +0000596 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800597 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800598 (mClient == 0) ? getpid_cached : mClient->pid(),
599 mStreamType,
600 mFormat,
601 mChannelMask,
602 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800603 mFrameCount,
604 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800605 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800606 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700607 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
608 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700609 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000610 mMainBuffer,
611 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700612 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700613 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800614 nowInUnderrun);
615}
616
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
618 return mAudioTrackServerProxy->getSampleRate();
619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// AudioBufferProvider interface
622status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800623 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800624{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800625 ServerProxy::Buffer buf;
626 size_t desiredFrames = buffer->frameCount;
627 buf.mFrameCount = desiredFrames;
628 status_t status = mServerProxy->obtainBuffer(&buf);
629 buffer->frameCount = buf.mFrameCount;
630 buffer->raw = buf.mRaw;
631 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700632 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800633 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800634 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800635}
636
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700637// releaseBuffer() is not overridden
638
639// ExtendedAudioBufferProvider interface
640
Andy Hung27876c02014-09-09 18:07:55 -0700641// framesReady() may return an approximation of the number of frames if called
642// from a different thread than the one calling Proxy->obtainBuffer() and
643// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
644// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800645size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700646 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
647 // Static tracks return zero frames immediately upon stopping (for FastTracks).
648 // The remainder of the buffer is not drained.
649 return 0;
650 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800651 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700654size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
655{
656 return mAudioTrackServerProxy->framesReleased();
657}
658
Eric Laurent81784c32012-11-19 14:55:58 -0800659// Don't call for fast tracks; the framesReady() could result in priority inversion
660bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800661 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
662 return true;
663 }
664
Eric Laurent16498512014-03-17 17:22:08 -0700665 if (isStopping()) {
666 if (framesReady() > 0) {
667 mFillingUpStatus = FS_FILLED;
668 }
Eric Laurent81784c32012-11-19 14:55:58 -0800669 return true;
670 }
671
672 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700673 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800674 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700675 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800676 return true;
677 }
678 return false;
679}
680
Glenn Kasten0f11b512014-01-31 16:18:54 -0800681status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
682 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800683{
684 status_t status = NO_ERROR;
685 ALOGV("start(%d), calling pid %d session %d",
686 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
687
688 sp<ThreadBase> thread = mThread.promote();
689 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700690 if (isOffloaded()) {
691 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
692 Mutex::Autolock _lth(thread->mLock);
693 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700694 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
695 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700696 invalidate();
697 return PERMISSION_DENIED;
698 }
699 }
700 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800701 track_state state = mState;
702 // here the track could be either new, or restarted
703 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800704
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800705 // initial state-stopping. next state-pausing.
706 // What if resume is called ?
707
708 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800709 if (mResumeToStopping) {
710 // happened we need to resume to STOPPING_1
711 mState = TrackBase::STOPPING_1;
712 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
713 } else {
714 mState = TrackBase::RESUMING;
715 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
716 }
Eric Laurent81784c32012-11-19 14:55:58 -0800717 } else {
718 mState = TrackBase::ACTIVE;
719 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
720 }
721
Eric Laurentbfb1b832013-01-07 09:53:42 -0800722 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700723 if (isFastTrack()) {
724 // refresh fast track underruns on start because that field is never cleared
725 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
726 // after stop.
727 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
728 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800729 status = playbackThread->addTrack_l(this);
730 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800731 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800732 // restore previous state if start was rejected by policy manager
733 if (status == PERMISSION_DENIED) {
734 mState = state;
735 }
736 }
737 // track was already in the active list, not a problem
738 if (status == ALREADY_EXISTS) {
739 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700740 } else {
741 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
742 // It is usually unsafe to access the server proxy from a binder thread.
743 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
744 // isn't looking at this track yet: we still hold the normal mixer thread lock,
745 // and for fast tracks the track is not yet in the fast mixer thread's active set.
746 ServerProxy::Buffer buffer;
747 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700748 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800749 }
750 } else {
751 status = BAD_VALUE;
752 }
753 return status;
754}
755
756void AudioFlinger::PlaybackThread::Track::stop()
757{
758 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
759 sp<ThreadBase> thread = mThread.promote();
760 if (thread != 0) {
761 Mutex::Autolock _l(thread->mLock);
762 track_state state = mState;
763 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
764 // If the track is not active (PAUSED and buffers full), flush buffers
765 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
766 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
767 reset();
768 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700769 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800770 mState = STOPPED;
771 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800772 // For fast tracks prepareTracks_l() will set state to STOPPING_2
773 // presentation is complete
774 // For an offloaded track this starts a drain and state will
775 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800776 mState = STOPPING_1;
777 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700778 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800779 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
780 playbackThread);
781 }
Eric Laurent81784c32012-11-19 14:55:58 -0800782 }
783}
784
785void AudioFlinger::PlaybackThread::Track::pause()
786{
787 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
788 sp<ThreadBase> thread = mThread.promote();
789 if (thread != 0) {
790 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800791 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
792 switch (mState) {
793 case STOPPING_1:
794 case STOPPING_2:
795 if (!isOffloaded()) {
796 /* nothing to do if track is not offloaded */
797 break;
798 }
799
800 // Offloaded track was draining, we need to carry on draining when resumed
801 mResumeToStopping = true;
802 // fall through...
803 case ACTIVE:
804 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800805 mState = PAUSING;
806 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700807 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800808 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800809
Eric Laurentbfb1b832013-01-07 09:53:42 -0800810 default:
811 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800812 }
813 }
814}
815
816void AudioFlinger::PlaybackThread::Track::flush()
817{
818 ALOGV("flush(%d)", mName);
819 sp<ThreadBase> thread = mThread.promote();
820 if (thread != 0) {
821 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800822 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800823
824 if (isOffloaded()) {
825 // If offloaded we allow flush during any state except terminated
826 // and keep the track active to avoid problems if user is seeking
827 // rapidly and underlying hardware has a significant delay handling
828 // a pause
829 if (isTerminated()) {
830 return;
831 }
832
833 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800834 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800835
836 if (mState == STOPPING_1 || mState == STOPPING_2) {
837 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
838 mState = ACTIVE;
839 }
840
841 if (mState == ACTIVE) {
842 ALOGV("flush called in active state, resetting buffer time out retry count");
843 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
844 }
845
Haynes Mathew George7844f672014-01-15 12:32:55 -0800846 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800847 mResumeToStopping = false;
848 } else {
849 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
850 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
851 return;
852 }
853 // No point remaining in PAUSED state after a flush => go to
854 // FLUSHED state
855 mState = FLUSHED;
856 // do not reset the track if it is still in the process of being stopped or paused.
857 // this will be done by prepareTracks_l() when the track is stopped.
858 // prepareTracks_l() will see mState == FLUSHED, then
859 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800860 if (isDirect()) {
861 mFlushHwPending = true;
862 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800863 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
864 reset();
865 }
Eric Laurent81784c32012-11-19 14:55:58 -0800866 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800867 // Prevent flush being lost if the track is flushed and then resumed
868 // before mixer thread can run. This is important when offloading
869 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700870 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800871 }
872}
873
Haynes Mathew George7844f672014-01-15 12:32:55 -0800874// must be called with thread lock held
875void AudioFlinger::PlaybackThread::Track::flushAck()
876{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800877 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800878 return;
879
880 mFlushHwPending = false;
881}
882
Eric Laurent81784c32012-11-19 14:55:58 -0800883void AudioFlinger::PlaybackThread::Track::reset()
884{
885 // Do not reset twice to avoid discarding data written just after a flush and before
886 // the audioflinger thread detects the track is stopped.
887 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800888 // Force underrun condition to avoid false underrun callback until first data is
889 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700890 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800891 mFillingUpStatus = FS_FILLING;
892 mResetDone = true;
893 if (mState == FLUSHED) {
894 mState = IDLE;
895 }
896 }
897}
898
Eric Laurentbfb1b832013-01-07 09:53:42 -0800899status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
900{
901 sp<ThreadBase> thread = mThread.promote();
902 if (thread == 0) {
903 ALOGE("thread is dead");
904 return FAILED_TRANSACTION;
905 } else if ((thread->type() == ThreadBase::DIRECT) ||
906 (thread->type() == ThreadBase::OFFLOAD)) {
907 return thread->setParameters(keyValuePairs);
908 } else {
909 return PERMISSION_DENIED;
910 }
911}
912
Glenn Kasten573d80a2013-08-26 09:36:23 -0700913status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
914{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700915 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
916 if (isFastTrack()) {
917 return INVALID_OPERATION;
918 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700919 sp<ThreadBase> thread = mThread.promote();
920 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700921 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700922 }
Phil Burk6140c792015-03-19 14:30:21 -0700923
Glenn Kasten573d80a2013-08-26 09:36:23 -0700924 Mutex::Autolock _l(thread->mLock);
925 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Phil Burk6140c792015-03-19 14:30:21 -0700926
927 status_t result = INVALID_OPERATION;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700928 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700929 if (!playbackThread->mLatchQValid) {
930 return INVALID_OPERATION;
931 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700932 // FIXME Not accurate under dynamic changes of sample rate and speed.
933 // Do not use track's mSampleRate as it is not current for mixer tracks.
934 uint32_t sampleRate = mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700935 AudioPlaybackRate playbackRate = mAudioTrackServerProxy->getPlaybackRate();
936 uint32_t unpresentedFrames = ((double) playbackThread->mLatchQ.mUnpresentedFrames *
937 sampleRate * playbackRate.mSpeed)/ playbackThread->mSampleRate;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700938 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
939 // for a brand new track to share the same address as a recently destroyed
940 // track, and thus for us to get the frames released of the wrong track.
941 // It is unlikely that we would be able to call getTimestamp() so quickly
942 // right after creating a new track. Nevertheless, the index here should
943 // be changed to something that is unique. Or use a completely different strategy.
944 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
945 uint32_t framesWritten = i >= 0 ?
946 playbackThread->mLatchQ.mFramesReleased[i] :
947 mAudioTrackServerProxy->framesReleased();
Phil Burk1b420972015-04-22 10:52:21 -0700948 if (framesWritten >= unpresentedFrames) {
Phil Burk6140c792015-03-19 14:30:21 -0700949 timestamp.mPosition = framesWritten - unpresentedFrames;
950 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
951 result = NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -0700952 }
Phil Burk6140c792015-03-19 14:30:21 -0700953 } else { // offloaded or direct
954 result = playbackThread->getTimestamp_l(timestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700955 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700956
Phil Burk6140c792015-03-19 14:30:21 -0700957 return result;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700958}
959
Eric Laurent81784c32012-11-19 14:55:58 -0800960status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
961{
962 status_t status = DEAD_OBJECT;
963 sp<ThreadBase> thread = mThread.promote();
964 if (thread != 0) {
965 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
966 sp<AudioFlinger> af = mClient->audioFlinger();
967
968 Mutex::Autolock _l(af->mLock);
969
970 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
971
972 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
973 Mutex::Autolock _dl(playbackThread->mLock);
974 Mutex::Autolock _sl(srcThread->mLock);
975 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
976 if (chain == 0) {
977 return INVALID_OPERATION;
978 }
979
980 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
981 if (effect == 0) {
982 return INVALID_OPERATION;
983 }
984 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700985 status = playbackThread->addEffect_l(effect);
986 if (status != NO_ERROR) {
987 srcThread->addEffect_l(effect);
988 return INVALID_OPERATION;
989 }
Eric Laurent81784c32012-11-19 14:55:58 -0800990 // removeEffect_l() has stopped the effect if it was active so it must be restarted
991 if (effect->state() == EffectModule::ACTIVE ||
992 effect->state() == EffectModule::STOPPING) {
993 effect->start();
994 }
995
996 sp<EffectChain> dstChain = effect->chain().promote();
997 if (dstChain == 0) {
998 srcThread->addEffect_l(effect);
999 return INVALID_OPERATION;
1000 }
1001 AudioSystem::unregisterEffect(effect->id());
1002 AudioSystem::registerEffect(&effect->desc(),
1003 srcThread->id(),
1004 dstChain->strategy(),
1005 AUDIO_SESSION_OUTPUT_MIX,
1006 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07001007 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -08001008 }
1009 status = playbackThread->attachAuxEffect(this, EffectId);
1010 }
1011 return status;
1012}
1013
1014void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
1015{
1016 mAuxEffectId = EffectId;
1017 mAuxBuffer = buffer;
1018}
1019
1020bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
1021 size_t audioHalFrames)
1022{
1023 // a track is considered presented when the total number of frames written to audio HAL
1024 // corresponds to the number of frames written when presentationComplete() is called for the
1025 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001026 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1027 // to detect when all frames have been played. In this case framesWritten isn't
1028 // useful because it doesn't always reflect whether there is data in the h/w
1029 // buffers, particularly if a track has been paused and resumed during draining
1030 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1031 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001032 if (mPresentationCompleteFrames == 0) {
1033 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1034 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1035 mPresentationCompleteFrames, audioHalFrames);
1036 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001037
1038 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001039 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001040 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001041 return true;
1042 }
1043 return false;
1044}
1045
1046void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1047{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001048 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001049 if (mSyncEvents[i]->type() == type) {
1050 mSyncEvents[i]->trigger();
1051 mSyncEvents.removeAt(i);
1052 i--;
1053 }
1054 }
1055}
1056
1057// implement VolumeBufferProvider interface
1058
Glenn Kastenc56f3422014-03-21 17:53:17 -07001059gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001060{
1061 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1062 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001063 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1064 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1065 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001066 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001067 if (vl > GAIN_FLOAT_UNITY) {
1068 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001069 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001070 if (vr > GAIN_FLOAT_UNITY) {
1071 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001072 }
1073 // now apply the cached master volume and stream type volume;
1074 // this is trusted but lacks any synchronization or barrier so may be stale
1075 float v = mCachedVolume;
1076 vl *= v;
1077 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001078 // re-combine into packed minifloat
1079 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001080 // FIXME look at mute, pause, and stop flags
1081 return vlr;
1082}
1083
1084status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1085{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001086 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001087 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1088 (mState == STOPPED)))) {
1089 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1090 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1091 event->cancel();
1092 return INVALID_OPERATION;
1093 }
1094 (void) TrackBase::setSyncEvent(event);
1095 return NO_ERROR;
1096}
1097
Glenn Kasten5736c352012-12-04 12:12:34 -08001098void AudioFlinger::PlaybackThread::Track::invalidate()
1099{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001100 // FIXME should use proxy, and needs work
1101 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001102 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001103 android_atomic_release_store(0x40000000, &cblk->mFutex);
1104 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001105 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001106 mIsInvalid = true;
1107}
1108
Eric Laurent59fe0102013-09-27 18:48:26 -07001109void AudioFlinger::PlaybackThread::Track::signal()
1110{
1111 sp<ThreadBase> thread = mThread.promote();
1112 if (thread != 0) {
1113 PlaybackThread *t = (PlaybackThread *)thread.get();
1114 Mutex::Autolock _l(t->mLock);
1115 t->broadcast_l();
1116 }
1117}
1118
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001119//To be called with thread lock held
1120bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1121
1122 if (mState == RESUMING)
1123 return true;
1124 /* Resume is pending if track was stopping before pause was called */
1125 if (mState == STOPPING_1 &&
1126 mResumeToStopping)
1127 return true;
1128
1129 return false;
1130}
1131
1132//To be called with thread lock held
1133void AudioFlinger::PlaybackThread::Track::resumeAck() {
1134
1135
1136 if (mState == RESUMING)
1137 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001138
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001139 // Other possibility of pending resume is stopping_1 state
1140 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001141 // drain being called.
1142 if (mState == STOPPING_1) {
1143 mResumeToStopping = false;
1144 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001145}
Eric Laurent81784c32012-11-19 14:55:58 -08001146// ----------------------------------------------------------------------------
1147
1148sp<AudioFlinger::PlaybackThread::TimedTrack>
1149AudioFlinger::PlaybackThread::TimedTrack::create(
1150 PlaybackThread *thread,
1151 const sp<Client>& client,
1152 audio_stream_type_t streamType,
1153 uint32_t sampleRate,
1154 audio_format_t format,
1155 audio_channel_mask_t channelMask,
1156 size_t frameCount,
1157 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001158 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001159 int uid)
1160{
Eric Laurent81784c32012-11-19 14:55:58 -08001161 if (!client->reserveTimedTrack())
1162 return 0;
1163
1164 return new TimedTrack(
1165 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001166 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001167}
1168
1169AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1170 PlaybackThread *thread,
1171 const sp<Client>& client,
1172 audio_stream_type_t streamType,
1173 uint32_t sampleRate,
1174 audio_format_t format,
1175 audio_channel_mask_t channelMask,
1176 size_t frameCount,
1177 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001178 int sessionId,
1179 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001180 : Track(thread, client, streamType, sampleRate, format, channelMask,
Eric Laurent83b88082014-06-20 18:31:16 -07001181 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1182 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001183 mQueueHeadInFlight(false),
1184 mTrimQueueHeadOnRelease(false),
1185 mFramesPendingInQueue(0),
1186 mTimedSilenceBuffer(NULL),
1187 mTimedSilenceBufferSize(0),
1188 mTimedAudioOutputOnTime(false),
1189 mMediaTimeTransformValid(false)
1190{
1191 LocalClock lc;
1192 mLocalTimeFreq = lc.getLocalFreq();
1193
1194 mLocalTimeToSampleTransform.a_zero = 0;
1195 mLocalTimeToSampleTransform.b_zero = 0;
1196 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1197 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1198 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1199 &mLocalTimeToSampleTransform.a_to_b_denom);
1200
1201 mMediaTimeToSampleTransform.a_zero = 0;
1202 mMediaTimeToSampleTransform.b_zero = 0;
1203 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1204 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1205 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1206 &mMediaTimeToSampleTransform.a_to_b_denom);
1207}
1208
1209AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1210 mClient->releaseTimedTrack();
1211 delete [] mTimedSilenceBuffer;
1212}
1213
1214status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1215 size_t size, sp<IMemory>* buffer) {
1216
1217 Mutex::Autolock _l(mTimedBufferQueueLock);
1218
1219 trimTimedBufferQueue_l();
1220
1221 // lazily initialize the shared memory heap for timed buffers
1222 if (mTimedMemoryDealer == NULL) {
1223 const int kTimedBufferHeapSize = 512 << 10;
1224
1225 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1226 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001227 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001228 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001229 }
Eric Laurent81784c32012-11-19 14:55:58 -08001230 }
1231
1232 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001233 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001234 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001235 }
1236
1237 *buffer = newBuffer;
1238 return NO_ERROR;
1239}
1240
1241// caller must hold mTimedBufferQueueLock
1242void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1243 int64_t mediaTimeNow;
1244 {
1245 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1246 if (!mMediaTimeTransformValid)
1247 return;
1248
1249 int64_t targetTimeNow;
1250 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1251 ? mCCHelper.getCommonTime(&targetTimeNow)
1252 : mCCHelper.getLocalTime(&targetTimeNow);
1253
1254 if (OK != res)
1255 return;
1256
1257 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1258 &mediaTimeNow)) {
1259 return;
1260 }
1261 }
1262
1263 size_t trimEnd;
1264 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1265 int64_t bufEnd;
1266
1267 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1268 // We have a next buffer. Just use its PTS as the PTS of the frame
1269 // following the last frame in this buffer. If the stream is sparse
1270 // (ie, there are deliberate gaps left in the stream which should be
1271 // filled with silence by the TimedAudioTrack), then this can result
1272 // in one extra buffer being left un-trimmed when it could have
1273 // been. In general, this is not typical, and we would rather
1274 // optimized away the TS calculation below for the more common case
1275 // where PTSes are contiguous.
1276 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1277 } else {
1278 // We have no next buffer. Compute the PTS of the frame following
1279 // the last frame in this buffer by computing the duration of of
1280 // this frame in media time units and adding it to the PTS of the
1281 // buffer.
1282 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1283 / mFrameSize;
1284
1285 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1286 &bufEnd)) {
1287 ALOGE("Failed to convert frame count of %lld to media time"
1288 " duration" " (scale factor %d/%u) in %s",
1289 frameCount,
1290 mMediaTimeToSampleTransform.a_to_b_numer,
1291 mMediaTimeToSampleTransform.a_to_b_denom,
1292 __PRETTY_FUNCTION__);
1293 break;
1294 }
1295 bufEnd += mTimedBufferQueue[trimEnd].pts();
1296 }
1297
1298 if (bufEnd > mediaTimeNow)
1299 break;
1300
1301 // Is the buffer we want to use in the middle of a mix operation right
1302 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1303 // from the mixer which should be coming back shortly.
1304 if (!trimEnd && mQueueHeadInFlight) {
1305 mTrimQueueHeadOnRelease = true;
1306 }
1307 }
1308
1309 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1310 if (trimStart < trimEnd) {
1311 // Update the bookkeeping for framesReady()
1312 for (size_t i = trimStart; i < trimEnd; ++i) {
1313 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1314 }
1315
1316 // Now actually remove the buffers from the queue.
1317 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1318 }
1319}
1320
1321void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1322 const char* logTag) {
1323 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1324 "%s called (reason \"%s\"), but timed buffer queue has no"
1325 " elements to trim.", __FUNCTION__, logTag);
1326
1327 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1328 mTimedBufferQueue.removeAt(0);
1329}
1330
1331void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1332 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001333 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001334 uint32_t bufBytes = buf.buffer()->size();
1335 uint32_t consumedAlready = buf.position();
1336
1337 ALOG_ASSERT(consumedAlready <= bufBytes,
1338 "Bad bookkeeping while updating frames pending. Timed buffer is"
1339 " only %u bytes long, but claims to have consumed %u"
1340 " bytes. (update reason: \"%s\")",
1341 bufBytes, consumedAlready, logTag);
1342
1343 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1344 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1345 "Bad bookkeeping while updating frames pending. Should have at"
1346 " least %u queued frames, but we think we have only %u. (update"
1347 " reason: \"%s\")",
1348 bufFrames, mFramesPendingInQueue, logTag);
1349
1350 mFramesPendingInQueue -= bufFrames;
1351}
1352
1353status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1354 const sp<IMemory>& buffer, int64_t pts) {
1355
1356 {
1357 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1358 if (!mMediaTimeTransformValid)
1359 return INVALID_OPERATION;
1360 }
1361
1362 Mutex::Autolock _l(mTimedBufferQueueLock);
1363
1364 uint32_t bufFrames = buffer->size() / mFrameSize;
1365 mFramesPendingInQueue += bufFrames;
1366 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1367
1368 return NO_ERROR;
1369}
1370
1371status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1372 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1373
1374 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1375 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1376 target);
1377
1378 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1379 target == TimedAudioTrack::COMMON_TIME)) {
1380 return BAD_VALUE;
1381 }
1382
1383 Mutex::Autolock lock(mMediaTimeTransformLock);
1384 mMediaTimeTransform = xform;
1385 mMediaTimeTransformTarget = target;
1386 mMediaTimeTransformValid = true;
1387
1388 return NO_ERROR;
1389}
1390
1391#define min(a, b) ((a) < (b) ? (a) : (b))
1392
1393// implementation of getNextBuffer for tracks whose buffers have timestamps
1394status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1395 AudioBufferProvider::Buffer* buffer, int64_t pts)
1396{
1397 if (pts == AudioBufferProvider::kInvalidPTS) {
1398 buffer->raw = NULL;
1399 buffer->frameCount = 0;
1400 mTimedAudioOutputOnTime = false;
1401 return INVALID_OPERATION;
1402 }
1403
1404 Mutex::Autolock _l(mTimedBufferQueueLock);
1405
1406 ALOG_ASSERT(!mQueueHeadInFlight,
1407 "getNextBuffer called without releaseBuffer!");
1408
1409 while (true) {
1410
1411 // if we have no timed buffers, then fail
1412 if (mTimedBufferQueue.isEmpty()) {
1413 buffer->raw = NULL;
1414 buffer->frameCount = 0;
1415 return NOT_ENOUGH_DATA;
1416 }
1417
1418 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1419
1420 // calculate the PTS of the head of the timed buffer queue expressed in
1421 // local time
1422 int64_t headLocalPTS;
1423 {
1424 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1425
1426 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1427
1428 if (mMediaTimeTransform.a_to_b_denom == 0) {
1429 // the transform represents a pause, so yield silence
1430 timedYieldSilence_l(buffer->frameCount, buffer);
1431 return NO_ERROR;
1432 }
1433
1434 int64_t transformedPTS;
1435 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1436 &transformedPTS)) {
1437 // the transform failed. this shouldn't happen, but if it does
1438 // then just drop this buffer
1439 ALOGW("timedGetNextBuffer transform failed");
1440 buffer->raw = NULL;
1441 buffer->frameCount = 0;
1442 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1443 return NO_ERROR;
1444 }
1445
1446 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1447 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1448 &headLocalPTS)) {
1449 buffer->raw = NULL;
1450 buffer->frameCount = 0;
1451 return INVALID_OPERATION;
1452 }
1453 } else {
1454 headLocalPTS = transformedPTS;
1455 }
1456 }
1457
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001458 uint32_t sr = sampleRate();
1459
Eric Laurent81784c32012-11-19 14:55:58 -08001460 // adjust the head buffer's PTS to reflect the portion of the head buffer
1461 // that has already been consumed
1462 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001463 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001464
1465 // Calculate the delta in samples between the head of the input buffer
1466 // queue and the start of the next output buffer that will be written.
1467 // If the transformation fails because of over or underflow, it means
1468 // that the sample's position in the output stream is so far out of
1469 // whack that it should just be dropped.
1470 int64_t sampleDelta;
1471 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1472 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1473 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1474 " mix");
1475 continue;
1476 }
1477 if (!mLocalTimeToSampleTransform.doForwardTransform(
1478 (effectivePTS - pts) << 32, &sampleDelta)) {
1479 ALOGV("*** too late during sample rate transform: dropped buffer");
1480 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1481 continue;
1482 }
1483
1484 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1485 " sampleDelta=[%d.%08x]",
1486 head.pts(), head.position(), pts,
1487 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1488 + (sampleDelta >> 32)),
1489 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1490
1491 // if the delta between the ideal placement for the next input sample and
1492 // the current output position is within this threshold, then we will
1493 // concatenate the next input samples to the previous output
1494 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001495 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001496
1497 // if this is the first buffer of audio that we're emitting from this track
1498 // then it should be almost exactly on time.
1499 const int64_t kSampleStartupThreshold = 1LL << 32;
1500
1501 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1502 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1503 // the next input is close enough to being on time, so concatenate it
1504 // with the last output
1505 timedYieldSamples_l(buffer);
1506
1507 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1508 head.position(), buffer->frameCount);
1509 return NO_ERROR;
1510 }
1511
1512 // Looks like our output is not on time. Reset our on timed status.
1513 // Next time we mix samples from our input queue, then should be within
1514 // the StartupThreshold.
1515 mTimedAudioOutputOnTime = false;
1516 if (sampleDelta > 0) {
1517 // the gap between the current output position and the proper start of
1518 // the next input sample is too big, so fill it with silence
1519 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1520
1521 timedYieldSilence_l(framesUntilNextInput, buffer);
1522 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1523 return NO_ERROR;
1524 } else {
1525 // the next input sample is late
1526 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1527 size_t onTimeSamplePosition =
1528 head.position() + lateFrames * mFrameSize;
1529
1530 if (onTimeSamplePosition > head.buffer()->size()) {
1531 // all the remaining samples in the head are too late, so
1532 // drop it and move on
1533 ALOGV("*** too late: dropped buffer");
1534 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1535 continue;
1536 } else {
1537 // skip over the late samples
1538 head.setPosition(onTimeSamplePosition);
1539
1540 // yield the available samples
1541 timedYieldSamples_l(buffer);
1542
1543 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1544 return NO_ERROR;
1545 }
1546 }
1547 }
1548}
1549
1550// Yield samples from the timed buffer queue head up to the given output
1551// buffer's capacity.
1552//
1553// Caller must hold mTimedBufferQueueLock
1554void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1555 AudioBufferProvider::Buffer* buffer) {
1556
1557 const TimedBuffer& head = mTimedBufferQueue[0];
1558
1559 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1560 head.position());
1561
1562 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1563 mFrameSize);
1564 size_t framesRequested = buffer->frameCount;
1565 buffer->frameCount = min(framesLeftInHead, framesRequested);
1566
1567 mQueueHeadInFlight = true;
1568 mTimedAudioOutputOnTime = true;
1569}
1570
1571// Yield samples of silence up to the given output buffer's capacity
1572//
1573// Caller must hold mTimedBufferQueueLock
1574void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1575 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1576
1577 // lazily allocate a buffer filled with silence
1578 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1579 delete [] mTimedSilenceBuffer;
1580 mTimedSilenceBufferSize = numFrames * mFrameSize;
1581 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1582 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1583 }
1584
1585 buffer->raw = mTimedSilenceBuffer;
1586 size_t framesRequested = buffer->frameCount;
1587 buffer->frameCount = min(numFrames, framesRequested);
1588
1589 mTimedAudioOutputOnTime = false;
1590}
1591
1592// AudioBufferProvider interface
1593void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1594 AudioBufferProvider::Buffer* buffer) {
1595
1596 Mutex::Autolock _l(mTimedBufferQueueLock);
1597
1598 // If the buffer which was just released is part of the buffer at the head
1599 // of the queue, be sure to update the amt of the buffer which has been
1600 // consumed. If the buffer being returned is not part of the head of the
1601 // queue, its either because the buffer is part of the silence buffer, or
1602 // because the head of the timed queue was trimmed after the mixer called
1603 // getNextBuffer but before the mixer called releaseBuffer.
1604 if (buffer->raw == mTimedSilenceBuffer) {
1605 ALOG_ASSERT(!mQueueHeadInFlight,
1606 "Queue head in flight during release of silence buffer!");
1607 goto done;
1608 }
1609
1610 ALOG_ASSERT(mQueueHeadInFlight,
1611 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1612 " head in flight.");
1613
1614 if (mTimedBufferQueue.size()) {
1615 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1616
1617 void* start = head.buffer()->pointer();
1618 void* end = reinterpret_cast<void*>(
1619 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1620 + head.buffer()->size());
1621
1622 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1623 "released buffer not within the head of the timed buffer"
1624 " queue; qHead = [%p, %p], released buffer = %p",
1625 start, end, buffer->raw);
1626
1627 head.setPosition(head.position() +
1628 (buffer->frameCount * mFrameSize));
1629 mQueueHeadInFlight = false;
1630
1631 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1632 "Bad bookkeeping during releaseBuffer! Should have at"
1633 " least %u queued frames, but we think we have only %u",
1634 buffer->frameCount, mFramesPendingInQueue);
1635
1636 mFramesPendingInQueue -= buffer->frameCount;
1637
1638 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1639 || mTrimQueueHeadOnRelease) {
1640 trimTimedBufferQueueHead_l("releaseBuffer");
1641 mTrimQueueHeadOnRelease = false;
1642 }
1643 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001644 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001645 " buffers in the timed buffer queue");
1646 }
1647
1648done:
1649 buffer->raw = 0;
1650 buffer->frameCount = 0;
1651}
1652
1653size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1654 Mutex::Autolock _l(mTimedBufferQueueLock);
1655 return mFramesPendingInQueue;
1656}
1657
1658AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1659 : mPTS(0), mPosition(0) {}
1660
1661AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1662 const sp<IMemory>& buffer, int64_t pts)
1663 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1664
1665
1666// ----------------------------------------------------------------------------
1667
1668AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1669 PlaybackThread *playbackThread,
1670 DuplicatingThread *sourceThread,
1671 uint32_t sampleRate,
1672 audio_format_t format,
1673 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001674 size_t frameCount,
1675 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001676 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1677 sampleRate, format, channelMask, frameCount,
1678 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001679 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001680{
1681
1682 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001683 mOutBuffer.frameCount = 0;
1684 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001685 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001686 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001687 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001688 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001689 // since client and server are in the same process,
1690 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001691 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1692 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001693 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001694 mClientProxy->setSendLevel(0.0);
1695 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001696 } else {
1697 ALOGW("Error creating output track on thread %p", playbackThread);
1698 }
1699}
1700
1701AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1702{
1703 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001704 delete mClientProxy;
1705 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001706}
1707
1708status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1709 int triggerSession)
1710{
1711 status_t status = Track::start(event, triggerSession);
1712 if (status != NO_ERROR) {
1713 return status;
1714 }
1715
1716 mActive = true;
1717 mRetryCount = 127;
1718 return status;
1719}
1720
1721void AudioFlinger::PlaybackThread::OutputTrack::stop()
1722{
1723 Track::stop();
1724 clearBufferQueue();
1725 mOutBuffer.frameCount = 0;
1726 mActive = false;
1727}
1728
Andy Hungc25b84a2015-01-14 19:04:10 -08001729bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001730{
1731 Buffer *pInBuffer;
1732 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001733 bool outputBufferFull = false;
1734 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001735 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001736
1737 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1738
1739 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001740 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001741 }
1742
1743 while (waitTimeLeftMs) {
1744 // First write pending buffers, then new data
1745 if (mBufferQueue.size()) {
1746 pInBuffer = mBufferQueue.itemAt(0);
1747 } else {
1748 pInBuffer = &inBuffer;
1749 }
1750
1751 if (pInBuffer->frameCount == 0) {
1752 break;
1753 }
1754
1755 if (mOutBuffer.frameCount == 0) {
1756 mOutBuffer.frameCount = pInBuffer->frameCount;
1757 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001758 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1759 if (status != NO_ERROR) {
1760 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1761 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001762 outputBufferFull = true;
1763 break;
1764 }
1765 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1766 if (waitTimeLeftMs >= waitTimeMs) {
1767 waitTimeLeftMs -= waitTimeMs;
1768 } else {
1769 waitTimeLeftMs = 0;
1770 }
1771 }
1772
1773 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1774 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001775 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001776 Proxy::Buffer buf;
1777 buf.mFrameCount = outFrames;
1778 buf.mRaw = NULL;
1779 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001780 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001781 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001782 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001783 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001784
1785 if (pInBuffer->frameCount == 0) {
1786 if (mBufferQueue.size()) {
1787 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001788 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001789 delete pInBuffer;
1790 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1791 mThread.unsafe_get(), mBufferQueue.size());
1792 } else {
1793 break;
1794 }
1795 }
1796 }
1797
1798 // If we could not write all frames, allocate a buffer and queue it for next time.
1799 if (inBuffer.frameCount) {
1800 sp<ThreadBase> thread = mThread.promote();
1801 if (thread != 0 && !thread->standby()) {
1802 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1803 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001804 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001805 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001806 pInBuffer->raw = pInBuffer->mBuffer;
1807 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001808 mBufferQueue.add(pInBuffer);
1809 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1810 mThread.unsafe_get(), mBufferQueue.size());
1811 } else {
1812 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1813 mThread.unsafe_get(), this);
1814 }
1815 }
1816 }
1817
Andy Hungc25b84a2015-01-14 19:04:10 -08001818 // Calling write() with a 0 length buffer means that no more data will be written:
1819 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1820 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1821 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001822 }
1823
1824 return outputBufferFull;
1825}
1826
1827status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1828 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1829{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001830 ClientProxy::Buffer buf;
1831 buf.mFrameCount = buffer->frameCount;
1832 struct timespec timeout;
1833 timeout.tv_sec = waitTimeMs / 1000;
1834 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1835 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1836 buffer->frameCount = buf.mFrameCount;
1837 buffer->raw = buf.mRaw;
1838 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001839}
1840
Eric Laurent81784c32012-11-19 14:55:58 -08001841void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1842{
1843 size_t size = mBufferQueue.size();
1844
1845 for (size_t i = 0; i < size; i++) {
1846 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001847 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001848 delete pBuffer;
1849 }
1850 mBufferQueue.clear();
1851}
1852
1853
Eric Laurent83b88082014-06-20 18:31:16 -07001854AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001855 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001856 uint32_t sampleRate,
1857 audio_channel_mask_t channelMask,
1858 audio_format_t format,
1859 size_t frameCount,
1860 void *buffer,
1861 IAudioFlinger::track_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001862 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001863 sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001864 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1865 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1866{
1867 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1868 playbackThread->sampleRate();
1869 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1870 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1871
1872 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1873 this, sampleRate,
1874 (int)mPeerTimeout.tv_sec,
1875 (int)(mPeerTimeout.tv_nsec / 1000000));
1876}
1877
1878AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1879{
1880}
1881
1882// AudioBufferProvider interface
1883status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1884 AudioBufferProvider::Buffer* buffer, int64_t pts)
1885{
1886 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1887 Proxy::Buffer buf;
1888 buf.mFrameCount = buffer->frameCount;
1889 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1890 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001891 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001892 if (buf.mFrameCount == 0) {
1893 return WOULD_BLOCK;
1894 }
Eric Laurent83b88082014-06-20 18:31:16 -07001895 status = Track::getNextBuffer(buffer, pts);
1896 return status;
1897}
1898
1899void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1900{
1901 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1902 Proxy::Buffer buf;
1903 buf.mFrameCount = buffer->frameCount;
1904 buf.mRaw = buffer->raw;
1905 mPeerProxy->releaseBuffer(&buf);
1906 TrackBase::releaseBuffer(buffer);
1907}
1908
1909status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1910 const struct timespec *timeOut)
1911{
1912 return mProxy->obtainBuffer(buffer, timeOut);
1913}
1914
1915void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1916{
1917 mProxy->releaseBuffer(buffer);
1918 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1919 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1920 start();
1921 }
1922 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1923}
1924
Eric Laurent81784c32012-11-19 14:55:58 -08001925// ----------------------------------------------------------------------------
1926// Record
1927// ----------------------------------------------------------------------------
1928
1929AudioFlinger::RecordHandle::RecordHandle(
1930 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1931 : BnAudioRecord(),
1932 mRecordTrack(recordTrack)
1933{
1934}
1935
1936AudioFlinger::RecordHandle::~RecordHandle() {
1937 stop_nonvirtual();
1938 mRecordTrack->destroy();
1939}
1940
Eric Laurent81784c32012-11-19 14:55:58 -08001941status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1942 int triggerSession) {
1943 ALOGV("RecordHandle::start()");
1944 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1945}
1946
1947void AudioFlinger::RecordHandle::stop() {
1948 stop_nonvirtual();
1949}
1950
1951void AudioFlinger::RecordHandle::stop_nonvirtual() {
1952 ALOGV("RecordHandle::stop()");
1953 mRecordTrack->stop();
1954}
1955
1956status_t AudioFlinger::RecordHandle::onTransact(
1957 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1958{
1959 return BnAudioRecord::onTransact(code, data, reply, flags);
1960}
1961
1962// ----------------------------------------------------------------------------
1963
Glenn Kasten05997e22014-03-13 15:08:33 -07001964// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001965AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1966 RecordThread *thread,
1967 const sp<Client>& client,
1968 uint32_t sampleRate,
1969 audio_format_t format,
1970 audio_channel_mask_t channelMask,
1971 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001972 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001973 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001974 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001975 IAudioFlinger::track_flags_t flags,
1976 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001977 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001978 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001979 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001980 (type == TYPE_DEFAULT) ?
1981 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1982 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1983 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001984 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001985 mFramesToDrop(0),
1986 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1987 mRecordBufferConverter(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001988{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001989 if (mCblk == NULL) {
1990 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001991 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001992
Andy Hung97a893e2015-03-29 01:03:07 -07001993 mRecordBufferConverter = new RecordBufferConverter(
1994 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1995 channelMask, format, sampleRate);
1996 // Check if the RecordBufferConverter construction was successful.
1997 // If not, don't continue with construction.
1998 //
1999 // NOTE: It would be extremely rare that the record track cannot be created
2000 // for the current device, but a pending or future device change would make
2001 // the record track configuration valid.
2002 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
2003 ALOGE("RecordTrack unable to create record buffer converter");
2004 return;
2005 }
2006
Eric Laurent83b88082014-06-20 18:31:16 -07002007 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
2008 mFrameSize, !isExternalTrack());
Andy Hung97a893e2015-03-29 01:03:07 -07002009 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07002010
2011 if (flags & IAudioFlinger::TRACK_FAST) {
2012 ALOG_ASSERT(thread->mFastTrackAvail);
2013 thread->mFastTrackAvail = false;
2014 }
Eric Laurent81784c32012-11-19 14:55:58 -08002015}
2016
2017AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
2018{
2019 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07002020 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002021 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08002022}
2023
Andy Hung97a893e2015-03-29 01:03:07 -07002024status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
2025{
2026 status_t status = TrackBase::initCheck();
2027 if (status == NO_ERROR && mServerProxy == 0) {
2028 status = BAD_VALUE;
2029 }
2030 return status;
2031}
2032
Eric Laurent81784c32012-11-19 14:55:58 -08002033// AudioBufferProvider interface
2034status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002035 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002036{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002037 ServerProxy::Buffer buf;
2038 buf.mFrameCount = buffer->frameCount;
2039 status_t status = mServerProxy->obtainBuffer(&buf);
2040 buffer->frameCount = buf.mFrameCount;
2041 buffer->raw = buf.mRaw;
2042 if (buf.mFrameCount == 0) {
2043 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002044 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002045 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002046 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002047}
2048
2049status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2050 int triggerSession)
2051{
2052 sp<ThreadBase> thread = mThread.promote();
2053 if (thread != 0) {
2054 RecordThread *recordThread = (RecordThread *)thread.get();
2055 return recordThread->start(this, event, triggerSession);
2056 } else {
2057 return BAD_VALUE;
2058 }
2059}
2060
2061void AudioFlinger::RecordThread::RecordTrack::stop()
2062{
2063 sp<ThreadBase> thread = mThread.promote();
2064 if (thread != 0) {
2065 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002066 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07002067 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002068 }
2069 }
2070}
2071
2072void AudioFlinger::RecordThread::RecordTrack::destroy()
2073{
2074 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2075 sp<RecordTrack> keep(this);
2076 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002077 if (isExternalTrack()) {
2078 if (mState == ACTIVE || mState == RESUMING) {
2079 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2080 }
2081 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
2082 }
Eric Laurent81784c32012-11-19 14:55:58 -08002083 sp<ThreadBase> thread = mThread.promote();
2084 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002085 Mutex::Autolock _l(thread->mLock);
2086 RecordThread *recordThread = (RecordThread *) thread.get();
2087 recordThread->destroyTrack_l(this);
2088 }
2089 }
2090}
2091
Eric Laurent9a54bc22013-09-09 09:08:44 -07002092void AudioFlinger::RecordThread::RecordTrack::invalidate()
2093{
2094 // FIXME should use proxy, and needs work
2095 audio_track_cblk_t* cblk = mCblk;
2096 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2097 android_atomic_release_store(0x40000000, &cblk->mFutex);
2098 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002099 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002100}
2101
Eric Laurent81784c32012-11-19 14:55:58 -08002102
2103/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2104{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002105 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002106}
2107
Marco Nelissenb2208842014-02-07 14:00:50 -08002108void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002109{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002110 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08002111 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08002112 (mClient == 0) ? getpid_cached : mClient->pid(),
2113 mFormat,
2114 mChannelMask,
2115 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002116 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002117 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002118 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002119 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002120
Eric Laurent81784c32012-11-19 14:55:58 -08002121}
2122
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002123void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2124{
2125 if (event == mSyncStartEvent) {
2126 ssize_t framesToDrop = 0;
2127 sp<ThreadBase> threadBase = mThread.promote();
2128 if (threadBase != 0) {
2129 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2130 // from audio HAL
2131 framesToDrop = threadBase->mFrameCount * 2;
2132 }
2133 mFramesToDrop = framesToDrop;
2134 }
2135}
2136
2137void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2138{
2139 if (mSyncStartEvent != 0) {
2140 mSyncStartEvent->cancel();
2141 mSyncStartEvent.clear();
2142 }
2143 mFramesToDrop = 0;
2144}
2145
Eric Laurent83b88082014-06-20 18:31:16 -07002146
2147AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2148 uint32_t sampleRate,
2149 audio_channel_mask_t channelMask,
2150 audio_format_t format,
2151 size_t frameCount,
2152 void *buffer,
2153 IAudioFlinger::track_flags_t flags)
2154 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2155 buffer, 0, getuid(), flags, TYPE_PATCH),
2156 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2157{
2158 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2159 recordThread->sampleRate();
2160 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2161 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2162
2163 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2164 this, sampleRate,
2165 (int)mPeerTimeout.tv_sec,
2166 (int)(mPeerTimeout.tv_nsec / 1000000));
2167}
2168
2169AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2170{
2171}
2172
2173// AudioBufferProvider interface
2174status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2175 AudioBufferProvider::Buffer* buffer, int64_t pts)
2176{
2177 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2178 Proxy::Buffer buf;
2179 buf.mFrameCount = buffer->frameCount;
2180 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2181 ALOGV_IF(status != NO_ERROR,
2182 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002183 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002184 if (buf.mFrameCount == 0) {
2185 return WOULD_BLOCK;
2186 }
Eric Laurent83b88082014-06-20 18:31:16 -07002187 status = RecordTrack::getNextBuffer(buffer, pts);
2188 return status;
2189}
2190
2191void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2192{
2193 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2194 Proxy::Buffer buf;
2195 buf.mFrameCount = buffer->frameCount;
2196 buf.mRaw = buffer->raw;
2197 mPeerProxy->releaseBuffer(&buf);
2198 TrackBase::releaseBuffer(buffer);
2199}
2200
2201status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2202 const struct timespec *timeOut)
2203{
2204 return mProxy->obtainBuffer(buffer, timeOut);
2205}
2206
2207void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2208{
2209 mProxy->releaseBuffer(buffer);
2210}
2211
Glenn Kasten63238ef2015-03-02 15:50:29 -08002212} // namespace android