blob: 6cbb9321ef64742a0267d48cf45fdb913ec499ca [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) {
Andy Hunga5427822015-09-11 16:15:35 -0700466 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
467 // race with setSyncEvent(). However, if we call it, we cannot properly start
468 // static fast tracks (SoundPool) immediately after stopping.
469 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700470 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
471 int i = __builtin_ctz(thread->mFastTrackAvailMask);
472 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
473 // FIXME This is too eager. We allocate a fast track index before the
474 // fast track becomes active. Since fast tracks are a scarce resource,
475 // this means we are potentially denying other more important fast tracks from
476 // being created. It would be better to allocate the index dynamically.
477 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700478 thread->mFastTrackAvailMask &= ~(1 << i);
479 }
Eric Laurent81784c32012-11-19 14:55:58 -0800480}
481
482AudioFlinger::PlaybackThread::Track::~Track()
483{
484 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700485
486 // The destructor would clear mSharedBuffer,
487 // but it will not push the decremented reference count,
488 // leaving the client's IMemory dangling indefinitely.
489 // This prevents that leak.
490 if (mSharedBuffer != 0) {
491 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700492 }
Eric Laurent81784c32012-11-19 14:55:58 -0800493}
494
Glenn Kasten03003332013-08-06 15:40:54 -0700495status_t AudioFlinger::PlaybackThread::Track::initCheck() const
496{
497 status_t status = TrackBase::initCheck();
498 if (status == NO_ERROR && mName < 0) {
499 status = NO_MEMORY;
500 }
501 return status;
502}
503
Eric Laurent81784c32012-11-19 14:55:58 -0800504void AudioFlinger::PlaybackThread::Track::destroy()
505{
506 // NOTE: destroyTrack_l() can remove a strong reference to this Track
507 // by removing it from mTracks vector, so there is a risk that this Tracks's
508 // destructor is called. As the destructor needs to lock mLock,
509 // we must acquire a strong reference on this Track before locking mLock
510 // here so that the destructor is called only when exiting this function.
511 // On the other hand, as long as Track::destroy() is only called by
512 // TrackHandle destructor, the TrackHandle still holds a strong ref on
513 // this Track with its member mTrack.
514 sp<Track> keep(this);
515 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700516 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800517 sp<ThreadBase> thread = mThread.promote();
518 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800519 Mutex::Autolock _l(thread->mLock);
520 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700521 wasActive = playbackThread->destroyTrack_l(this);
522 }
523 if (isExternalTrack() && !wasActive) {
Eric Laurente83b55d2014-11-14 10:06:21 -0800524 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800525 }
526 }
527}
528
529/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
530{
Marco Nelissenb2208842014-02-07 14:00:50 -0800531 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700532 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800533}
534
Marco Nelissenb2208842014-02-07 14:00:50 -0800535void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800536{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700537 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800538 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800539 sprintf(buffer, " F %2d", mFastIndex);
540 } else if (mName >= AudioMixer::TRACK0) {
541 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800542 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800543 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800544 }
545 track_state state = mState;
546 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800547 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800548 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800549 } else {
550 switch (state) {
551 case IDLE:
552 stateChar = 'I';
553 break;
554 case STOPPING_1:
555 stateChar = 's';
556 break;
557 case STOPPING_2:
558 stateChar = '5';
559 break;
560 case STOPPED:
561 stateChar = 'S';
562 break;
563 case RESUMING:
564 stateChar = 'R';
565 break;
566 case ACTIVE:
567 stateChar = 'A';
568 break;
569 case PAUSING:
570 stateChar = 'p';
571 break;
572 case PAUSED:
573 stateChar = 'P';
574 break;
575 case FLUSHED:
576 stateChar = 'F';
577 break;
578 default:
579 stateChar = '?';
580 break;
581 }
Eric Laurent81784c32012-11-19 14:55:58 -0800582 }
583 char nowInUnderrun;
584 switch (mObservedUnderruns.mBitFields.mMostRecent) {
585 case UNDERRUN_FULL:
586 nowInUnderrun = ' ';
587 break;
588 case UNDERRUN_PARTIAL:
589 nowInUnderrun = '<';
590 break;
591 case UNDERRUN_EMPTY:
592 nowInUnderrun = '*';
593 break;
594 default:
595 nowInUnderrun = '?';
596 break;
597 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000598 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 +0000599 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800600 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800601 (mClient == 0) ? getpid_cached : mClient->pid(),
602 mStreamType,
603 mFormat,
604 mChannelMask,
605 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800606 mFrameCount,
607 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800608 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700610 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
611 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700612 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000613 mMainBuffer,
614 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700615 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700616 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800617 nowInUnderrun);
618}
619
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800620uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
621 return mAudioTrackServerProxy->getSampleRate();
622}
623
Eric Laurent81784c32012-11-19 14:55:58 -0800624// AudioBufferProvider interface
625status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800626 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800627{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800628 ServerProxy::Buffer buf;
629 size_t desiredFrames = buffer->frameCount;
630 buf.mFrameCount = desiredFrames;
631 status_t status = mServerProxy->obtainBuffer(&buf);
632 buffer->frameCount = buf.mFrameCount;
633 buffer->raw = buf.mRaw;
634 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700635 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800636 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800637 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800638}
639
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700640// releaseBuffer() is not overridden
641
642// ExtendedAudioBufferProvider interface
643
Andy Hung27876c02014-09-09 18:07:55 -0700644// framesReady() may return an approximation of the number of frames if called
645// from a different thread than the one calling Proxy->obtainBuffer() and
646// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
647// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800648size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700649 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
650 // Static tracks return zero frames immediately upon stopping (for FastTracks).
651 // The remainder of the buffer is not drained.
652 return 0;
653 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800654 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800655}
656
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700657size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
658{
659 return mAudioTrackServerProxy->framesReleased();
660}
661
Eric Laurent81784c32012-11-19 14:55:58 -0800662// Don't call for fast tracks; the framesReady() could result in priority inversion
663bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800664 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
665 return true;
666 }
667
Eric Laurent16498512014-03-17 17:22:08 -0700668 if (isStopping()) {
669 if (framesReady() > 0) {
670 mFillingUpStatus = FS_FILLED;
671 }
Eric Laurent81784c32012-11-19 14:55:58 -0800672 return true;
673 }
674
675 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700676 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800677 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700678 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800679 return true;
680 }
681 return false;
682}
683
Glenn Kasten0f11b512014-01-31 16:18:54 -0800684status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
685 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800686{
687 status_t status = NO_ERROR;
688 ALOGV("start(%d), calling pid %d session %d",
689 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
690
691 sp<ThreadBase> thread = mThread.promote();
692 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700693 if (isOffloaded()) {
694 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
695 Mutex::Autolock _lth(thread->mLock);
696 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700697 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
698 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700699 invalidate();
700 return PERMISSION_DENIED;
701 }
702 }
703 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800704 track_state state = mState;
705 // here the track could be either new, or restarted
706 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800707
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800708 // initial state-stopping. next state-pausing.
709 // What if resume is called ?
710
711 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800712 if (mResumeToStopping) {
713 // happened we need to resume to STOPPING_1
714 mState = TrackBase::STOPPING_1;
715 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
716 } else {
717 mState = TrackBase::RESUMING;
718 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
719 }
Eric Laurent81784c32012-11-19 14:55:58 -0800720 } else {
721 mState = TrackBase::ACTIVE;
722 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
723 }
724
Eric Laurentbfb1b832013-01-07 09:53:42 -0800725 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700726 if (isFastTrack()) {
727 // refresh fast track underruns on start because that field is never cleared
728 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
729 // after stop.
730 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
731 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800732 status = playbackThread->addTrack_l(this);
733 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800734 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800735 // restore previous state if start was rejected by policy manager
736 if (status == PERMISSION_DENIED) {
737 mState = state;
738 }
739 }
740 // track was already in the active list, not a problem
741 if (status == ALREADY_EXISTS) {
742 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700743 } else {
744 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
745 // It is usually unsafe to access the server proxy from a binder thread.
746 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
747 // isn't looking at this track yet: we still hold the normal mixer thread lock,
748 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hung954ca452015-09-09 14:39:02 -0700749 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700750 ServerProxy::Buffer buffer;
751 buffer.mFrameCount = 1;
752 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800753 }
754 } else {
755 status = BAD_VALUE;
756 }
757 return status;
758}
759
760void AudioFlinger::PlaybackThread::Track::stop()
761{
762 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
763 sp<ThreadBase> thread = mThread.promote();
764 if (thread != 0) {
765 Mutex::Autolock _l(thread->mLock);
766 track_state state = mState;
767 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
768 // If the track is not active (PAUSED and buffers full), flush buffers
769 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
770 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
771 reset();
772 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700773 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800774 mState = STOPPED;
775 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800776 // For fast tracks prepareTracks_l() will set state to STOPPING_2
777 // presentation is complete
778 // For an offloaded track this starts a drain and state will
779 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800780 mState = STOPPING_1;
781 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700782 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800783 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
784 playbackThread);
785 }
Eric Laurent81784c32012-11-19 14:55:58 -0800786 }
787}
788
789void AudioFlinger::PlaybackThread::Track::pause()
790{
791 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
792 sp<ThreadBase> thread = mThread.promote();
793 if (thread != 0) {
794 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800795 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
796 switch (mState) {
797 case STOPPING_1:
798 case STOPPING_2:
799 if (!isOffloaded()) {
800 /* nothing to do if track is not offloaded */
801 break;
802 }
803
804 // Offloaded track was draining, we need to carry on draining when resumed
805 mResumeToStopping = true;
806 // fall through...
807 case ACTIVE:
808 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800809 mState = PAUSING;
810 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700811 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800812 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800813
Eric Laurentbfb1b832013-01-07 09:53:42 -0800814 default:
815 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800816 }
817 }
818}
819
820void AudioFlinger::PlaybackThread::Track::flush()
821{
822 ALOGV("flush(%d)", mName);
823 sp<ThreadBase> thread = mThread.promote();
824 if (thread != 0) {
825 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800826 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800827
828 if (isOffloaded()) {
829 // If offloaded we allow flush during any state except terminated
830 // and keep the track active to avoid problems if user is seeking
831 // rapidly and underlying hardware has a significant delay handling
832 // a pause
833 if (isTerminated()) {
834 return;
835 }
836
837 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800838 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800839
840 if (mState == STOPPING_1 || mState == STOPPING_2) {
841 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
842 mState = ACTIVE;
843 }
844
845 if (mState == ACTIVE) {
846 ALOGV("flush called in active state, resetting buffer time out retry count");
847 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
848 }
849
Haynes Mathew George7844f672014-01-15 12:32:55 -0800850 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800851 mResumeToStopping = false;
852 } else {
853 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
854 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
855 return;
856 }
857 // No point remaining in PAUSED state after a flush => go to
858 // FLUSHED state
859 mState = FLUSHED;
860 // do not reset the track if it is still in the process of being stopped or paused.
861 // this will be done by prepareTracks_l() when the track is stopped.
862 // prepareTracks_l() will see mState == FLUSHED, then
863 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800864 if (isDirect()) {
865 mFlushHwPending = true;
866 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800867 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
868 reset();
869 }
Eric Laurent81784c32012-11-19 14:55:58 -0800870 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800871 // Prevent flush being lost if the track is flushed and then resumed
872 // before mixer thread can run. This is important when offloading
873 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700874 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800875 }
876}
877
Haynes Mathew George7844f672014-01-15 12:32:55 -0800878// must be called with thread lock held
879void AudioFlinger::PlaybackThread::Track::flushAck()
880{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800881 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800882 return;
883
884 mFlushHwPending = false;
885}
886
Eric Laurent81784c32012-11-19 14:55:58 -0800887void AudioFlinger::PlaybackThread::Track::reset()
888{
889 // Do not reset twice to avoid discarding data written just after a flush and before
890 // the audioflinger thread detects the track is stopped.
891 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800892 // Force underrun condition to avoid false underrun callback until first data is
893 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700894 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800895 mFillingUpStatus = FS_FILLING;
896 mResetDone = true;
897 if (mState == FLUSHED) {
898 mState = IDLE;
899 }
900 }
901}
902
Eric Laurentbfb1b832013-01-07 09:53:42 -0800903status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
904{
905 sp<ThreadBase> thread = mThread.promote();
906 if (thread == 0) {
907 ALOGE("thread is dead");
908 return FAILED_TRANSACTION;
909 } else if ((thread->type() == ThreadBase::DIRECT) ||
910 (thread->type() == ThreadBase::OFFLOAD)) {
911 return thread->setParameters(keyValuePairs);
912 } else {
913 return PERMISSION_DENIED;
914 }
915}
916
Glenn Kasten573d80a2013-08-26 09:36:23 -0700917status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
918{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700919 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
920 if (isFastTrack()) {
921 return INVALID_OPERATION;
922 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700923 sp<ThreadBase> thread = mThread.promote();
924 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700925 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700926 }
Phil Burk6140c792015-03-19 14:30:21 -0700927
Glenn Kasten573d80a2013-08-26 09:36:23 -0700928 Mutex::Autolock _l(thread->mLock);
929 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Phil Burk6140c792015-03-19 14:30:21 -0700930
931 status_t result = INVALID_OPERATION;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700932 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700933 if (!playbackThread->mLatchQValid) {
934 return INVALID_OPERATION;
935 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700936 // FIXME Not accurate under dynamic changes of sample rate and speed.
937 // Do not use track's mSampleRate as it is not current for mixer tracks.
938 uint32_t sampleRate = mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700939 AudioPlaybackRate playbackRate = mAudioTrackServerProxy->getPlaybackRate();
940 uint32_t unpresentedFrames = ((double) playbackThread->mLatchQ.mUnpresentedFrames *
941 sampleRate * playbackRate.mSpeed)/ playbackThread->mSampleRate;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700942 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
943 // for a brand new track to share the same address as a recently destroyed
944 // track, and thus for us to get the frames released of the wrong track.
945 // It is unlikely that we would be able to call getTimestamp() so quickly
946 // right after creating a new track. Nevertheless, the index here should
947 // be changed to something that is unique. Or use a completely different strategy.
948 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
949 uint32_t framesWritten = i >= 0 ?
950 playbackThread->mLatchQ.mFramesReleased[i] :
951 mAudioTrackServerProxy->framesReleased();
Phil Burk1b420972015-04-22 10:52:21 -0700952 if (framesWritten >= unpresentedFrames) {
Phil Burk6140c792015-03-19 14:30:21 -0700953 timestamp.mPosition = framesWritten - unpresentedFrames;
954 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
955 result = NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -0700956 }
Phil Burk6140c792015-03-19 14:30:21 -0700957 } else { // offloaded or direct
958 result = playbackThread->getTimestamp_l(timestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700959 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700960
Phil Burk6140c792015-03-19 14:30:21 -0700961 return result;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700962}
963
Eric Laurent81784c32012-11-19 14:55:58 -0800964status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
965{
966 status_t status = DEAD_OBJECT;
967 sp<ThreadBase> thread = mThread.promote();
968 if (thread != 0) {
969 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
970 sp<AudioFlinger> af = mClient->audioFlinger();
971
972 Mutex::Autolock _l(af->mLock);
973
974 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
975
976 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
977 Mutex::Autolock _dl(playbackThread->mLock);
978 Mutex::Autolock _sl(srcThread->mLock);
979 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
980 if (chain == 0) {
981 return INVALID_OPERATION;
982 }
983
984 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
985 if (effect == 0) {
986 return INVALID_OPERATION;
987 }
988 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700989 status = playbackThread->addEffect_l(effect);
990 if (status != NO_ERROR) {
991 srcThread->addEffect_l(effect);
992 return INVALID_OPERATION;
993 }
Eric Laurent81784c32012-11-19 14:55:58 -0800994 // removeEffect_l() has stopped the effect if it was active so it must be restarted
995 if (effect->state() == EffectModule::ACTIVE ||
996 effect->state() == EffectModule::STOPPING) {
997 effect->start();
998 }
999
1000 sp<EffectChain> dstChain = effect->chain().promote();
1001 if (dstChain == 0) {
1002 srcThread->addEffect_l(effect);
1003 return INVALID_OPERATION;
1004 }
1005 AudioSystem::unregisterEffect(effect->id());
1006 AudioSystem::registerEffect(&effect->desc(),
1007 srcThread->id(),
1008 dstChain->strategy(),
1009 AUDIO_SESSION_OUTPUT_MIX,
1010 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07001011 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -08001012 }
1013 status = playbackThread->attachAuxEffect(this, EffectId);
1014 }
1015 return status;
1016}
1017
1018void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
1019{
1020 mAuxEffectId = EffectId;
1021 mAuxBuffer = buffer;
1022}
1023
1024bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
1025 size_t audioHalFrames)
1026{
1027 // a track is considered presented when the total number of frames written to audio HAL
1028 // corresponds to the number of frames written when presentationComplete() is called for the
1029 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001030 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1031 // to detect when all frames have been played. In this case framesWritten isn't
1032 // useful because it doesn't always reflect whether there is data in the h/w
1033 // buffers, particularly if a track has been paused and resumed during draining
1034 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1035 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001036 if (mPresentationCompleteFrames == 0) {
1037 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1038 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1039 mPresentationCompleteFrames, audioHalFrames);
1040 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001041
1042 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001043 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001044 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001045 return true;
1046 }
1047 return false;
1048}
1049
1050void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1051{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001052 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001053 if (mSyncEvents[i]->type() == type) {
1054 mSyncEvents[i]->trigger();
1055 mSyncEvents.removeAt(i);
1056 i--;
1057 }
1058 }
1059}
1060
1061// implement VolumeBufferProvider interface
1062
Glenn Kastenc56f3422014-03-21 17:53:17 -07001063gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001064{
1065 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1066 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001067 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1068 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1069 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001070 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001071 if (vl > GAIN_FLOAT_UNITY) {
1072 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001073 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001074 if (vr > GAIN_FLOAT_UNITY) {
1075 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001076 }
1077 // now apply the cached master volume and stream type volume;
1078 // this is trusted but lacks any synchronization or barrier so may be stale
1079 float v = mCachedVolume;
1080 vl *= v;
1081 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001082 // re-combine into packed minifloat
1083 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001084 // FIXME look at mute, pause, and stop flags
1085 return vlr;
1086}
1087
1088status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1089{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001090 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001091 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1092 (mState == STOPPED)))) {
1093 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1094 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1095 event->cancel();
1096 return INVALID_OPERATION;
1097 }
1098 (void) TrackBase::setSyncEvent(event);
1099 return NO_ERROR;
1100}
1101
Glenn Kasten5736c352012-12-04 12:12:34 -08001102void AudioFlinger::PlaybackThread::Track::invalidate()
1103{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001104 // FIXME should use proxy, and needs work
1105 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001106 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001107 android_atomic_release_store(0x40000000, &cblk->mFutex);
1108 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001109 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001110 mIsInvalid = true;
1111}
1112
Eric Laurent59fe0102013-09-27 18:48:26 -07001113void AudioFlinger::PlaybackThread::Track::signal()
1114{
1115 sp<ThreadBase> thread = mThread.promote();
1116 if (thread != 0) {
1117 PlaybackThread *t = (PlaybackThread *)thread.get();
1118 Mutex::Autolock _l(t->mLock);
1119 t->broadcast_l();
1120 }
1121}
1122
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001123//To be called with thread lock held
1124bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1125
1126 if (mState == RESUMING)
1127 return true;
1128 /* Resume is pending if track was stopping before pause was called */
1129 if (mState == STOPPING_1 &&
1130 mResumeToStopping)
1131 return true;
1132
1133 return false;
1134}
1135
1136//To be called with thread lock held
1137void AudioFlinger::PlaybackThread::Track::resumeAck() {
1138
1139
1140 if (mState == RESUMING)
1141 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001142
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001143 // Other possibility of pending resume is stopping_1 state
1144 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001145 // drain being called.
1146 if (mState == STOPPING_1) {
1147 mResumeToStopping = false;
1148 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001149}
Eric Laurent81784c32012-11-19 14:55:58 -08001150// ----------------------------------------------------------------------------
1151
1152sp<AudioFlinger::PlaybackThread::TimedTrack>
1153AudioFlinger::PlaybackThread::TimedTrack::create(
1154 PlaybackThread *thread,
1155 const sp<Client>& client,
1156 audio_stream_type_t streamType,
1157 uint32_t sampleRate,
1158 audio_format_t format,
1159 audio_channel_mask_t channelMask,
1160 size_t frameCount,
1161 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001162 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001163 int uid)
1164{
Eric Laurent81784c32012-11-19 14:55:58 -08001165 if (!client->reserveTimedTrack())
1166 return 0;
1167
1168 return new TimedTrack(
1169 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001170 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001171}
1172
1173AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1174 PlaybackThread *thread,
1175 const sp<Client>& client,
1176 audio_stream_type_t streamType,
1177 uint32_t sampleRate,
1178 audio_format_t format,
1179 audio_channel_mask_t channelMask,
1180 size_t frameCount,
1181 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001182 int sessionId,
1183 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001184 : Track(thread, client, streamType, sampleRate, format, channelMask,
Eric Laurent83b88082014-06-20 18:31:16 -07001185 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1186 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001187 mQueueHeadInFlight(false),
1188 mTrimQueueHeadOnRelease(false),
1189 mFramesPendingInQueue(0),
1190 mTimedSilenceBuffer(NULL),
1191 mTimedSilenceBufferSize(0),
1192 mTimedAudioOutputOnTime(false),
1193 mMediaTimeTransformValid(false)
1194{
1195 LocalClock lc;
1196 mLocalTimeFreq = lc.getLocalFreq();
1197
1198 mLocalTimeToSampleTransform.a_zero = 0;
1199 mLocalTimeToSampleTransform.b_zero = 0;
1200 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1201 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1202 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1203 &mLocalTimeToSampleTransform.a_to_b_denom);
1204
1205 mMediaTimeToSampleTransform.a_zero = 0;
1206 mMediaTimeToSampleTransform.b_zero = 0;
1207 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1208 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1209 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1210 &mMediaTimeToSampleTransform.a_to_b_denom);
1211}
1212
1213AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1214 mClient->releaseTimedTrack();
1215 delete [] mTimedSilenceBuffer;
1216}
1217
1218status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1219 size_t size, sp<IMemory>* buffer) {
1220
1221 Mutex::Autolock _l(mTimedBufferQueueLock);
1222
1223 trimTimedBufferQueue_l();
1224
1225 // lazily initialize the shared memory heap for timed buffers
1226 if (mTimedMemoryDealer == NULL) {
1227 const int kTimedBufferHeapSize = 512 << 10;
1228
1229 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1230 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001231 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001232 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001233 }
Eric Laurent81784c32012-11-19 14:55:58 -08001234 }
1235
1236 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001237 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001238 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001239 }
1240
1241 *buffer = newBuffer;
1242 return NO_ERROR;
1243}
1244
1245// caller must hold mTimedBufferQueueLock
1246void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1247 int64_t mediaTimeNow;
1248 {
1249 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1250 if (!mMediaTimeTransformValid)
1251 return;
1252
1253 int64_t targetTimeNow;
1254 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1255 ? mCCHelper.getCommonTime(&targetTimeNow)
1256 : mCCHelper.getLocalTime(&targetTimeNow);
1257
1258 if (OK != res)
1259 return;
1260
1261 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1262 &mediaTimeNow)) {
1263 return;
1264 }
1265 }
1266
1267 size_t trimEnd;
1268 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1269 int64_t bufEnd;
1270
1271 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1272 // We have a next buffer. Just use its PTS as the PTS of the frame
1273 // following the last frame in this buffer. If the stream is sparse
1274 // (ie, there are deliberate gaps left in the stream which should be
1275 // filled with silence by the TimedAudioTrack), then this can result
1276 // in one extra buffer being left un-trimmed when it could have
1277 // been. In general, this is not typical, and we would rather
1278 // optimized away the TS calculation below for the more common case
1279 // where PTSes are contiguous.
1280 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1281 } else {
1282 // We have no next buffer. Compute the PTS of the frame following
1283 // the last frame in this buffer by computing the duration of of
1284 // this frame in media time units and adding it to the PTS of the
1285 // buffer.
1286 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1287 / mFrameSize;
1288
1289 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1290 &bufEnd)) {
1291 ALOGE("Failed to convert frame count of %lld to media time"
1292 " duration" " (scale factor %d/%u) in %s",
1293 frameCount,
1294 mMediaTimeToSampleTransform.a_to_b_numer,
1295 mMediaTimeToSampleTransform.a_to_b_denom,
1296 __PRETTY_FUNCTION__);
1297 break;
1298 }
1299 bufEnd += mTimedBufferQueue[trimEnd].pts();
1300 }
1301
1302 if (bufEnd > mediaTimeNow)
1303 break;
1304
1305 // Is the buffer we want to use in the middle of a mix operation right
1306 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1307 // from the mixer which should be coming back shortly.
1308 if (!trimEnd && mQueueHeadInFlight) {
1309 mTrimQueueHeadOnRelease = true;
1310 }
1311 }
1312
1313 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1314 if (trimStart < trimEnd) {
1315 // Update the bookkeeping for framesReady()
1316 for (size_t i = trimStart; i < trimEnd; ++i) {
1317 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1318 }
1319
1320 // Now actually remove the buffers from the queue.
1321 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1322 }
1323}
1324
1325void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1326 const char* logTag) {
1327 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1328 "%s called (reason \"%s\"), but timed buffer queue has no"
1329 " elements to trim.", __FUNCTION__, logTag);
1330
1331 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1332 mTimedBufferQueue.removeAt(0);
1333}
1334
1335void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1336 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001337 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001338 uint32_t bufBytes = buf.buffer()->size();
1339 uint32_t consumedAlready = buf.position();
1340
1341 ALOG_ASSERT(consumedAlready <= bufBytes,
1342 "Bad bookkeeping while updating frames pending. Timed buffer is"
1343 " only %u bytes long, but claims to have consumed %u"
1344 " bytes. (update reason: \"%s\")",
1345 bufBytes, consumedAlready, logTag);
1346
1347 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1348 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1349 "Bad bookkeeping while updating frames pending. Should have at"
1350 " least %u queued frames, but we think we have only %u. (update"
1351 " reason: \"%s\")",
1352 bufFrames, mFramesPendingInQueue, logTag);
1353
1354 mFramesPendingInQueue -= bufFrames;
1355}
1356
1357status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1358 const sp<IMemory>& buffer, int64_t pts) {
1359
1360 {
1361 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1362 if (!mMediaTimeTransformValid)
1363 return INVALID_OPERATION;
1364 }
1365
1366 Mutex::Autolock _l(mTimedBufferQueueLock);
1367
1368 uint32_t bufFrames = buffer->size() / mFrameSize;
1369 mFramesPendingInQueue += bufFrames;
1370 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1371
1372 return NO_ERROR;
1373}
1374
1375status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1376 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1377
1378 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1379 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1380 target);
1381
1382 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1383 target == TimedAudioTrack::COMMON_TIME)) {
1384 return BAD_VALUE;
1385 }
1386
1387 Mutex::Autolock lock(mMediaTimeTransformLock);
1388 mMediaTimeTransform = xform;
1389 mMediaTimeTransformTarget = target;
1390 mMediaTimeTransformValid = true;
1391
1392 return NO_ERROR;
1393}
1394
1395#define min(a, b) ((a) < (b) ? (a) : (b))
1396
1397// implementation of getNextBuffer for tracks whose buffers have timestamps
1398status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1399 AudioBufferProvider::Buffer* buffer, int64_t pts)
1400{
1401 if (pts == AudioBufferProvider::kInvalidPTS) {
1402 buffer->raw = NULL;
1403 buffer->frameCount = 0;
1404 mTimedAudioOutputOnTime = false;
1405 return INVALID_OPERATION;
1406 }
1407
1408 Mutex::Autolock _l(mTimedBufferQueueLock);
1409
1410 ALOG_ASSERT(!mQueueHeadInFlight,
1411 "getNextBuffer called without releaseBuffer!");
1412
1413 while (true) {
1414
1415 // if we have no timed buffers, then fail
1416 if (mTimedBufferQueue.isEmpty()) {
1417 buffer->raw = NULL;
1418 buffer->frameCount = 0;
1419 return NOT_ENOUGH_DATA;
1420 }
1421
1422 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1423
1424 // calculate the PTS of the head of the timed buffer queue expressed in
1425 // local time
1426 int64_t headLocalPTS;
1427 {
1428 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1429
1430 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1431
1432 if (mMediaTimeTransform.a_to_b_denom == 0) {
1433 // the transform represents a pause, so yield silence
1434 timedYieldSilence_l(buffer->frameCount, buffer);
1435 return NO_ERROR;
1436 }
1437
1438 int64_t transformedPTS;
1439 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1440 &transformedPTS)) {
1441 // the transform failed. this shouldn't happen, but if it does
1442 // then just drop this buffer
1443 ALOGW("timedGetNextBuffer transform failed");
1444 buffer->raw = NULL;
1445 buffer->frameCount = 0;
1446 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1447 return NO_ERROR;
1448 }
1449
1450 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1451 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1452 &headLocalPTS)) {
1453 buffer->raw = NULL;
1454 buffer->frameCount = 0;
1455 return INVALID_OPERATION;
1456 }
1457 } else {
1458 headLocalPTS = transformedPTS;
1459 }
1460 }
1461
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001462 uint32_t sr = sampleRate();
1463
Eric Laurent81784c32012-11-19 14:55:58 -08001464 // adjust the head buffer's PTS to reflect the portion of the head buffer
1465 // that has already been consumed
1466 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001467 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001468
1469 // Calculate the delta in samples between the head of the input buffer
1470 // queue and the start of the next output buffer that will be written.
1471 // If the transformation fails because of over or underflow, it means
1472 // that the sample's position in the output stream is so far out of
1473 // whack that it should just be dropped.
1474 int64_t sampleDelta;
1475 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1476 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1477 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1478 " mix");
1479 continue;
1480 }
1481 if (!mLocalTimeToSampleTransform.doForwardTransform(
1482 (effectivePTS - pts) << 32, &sampleDelta)) {
1483 ALOGV("*** too late during sample rate transform: dropped buffer");
1484 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1485 continue;
1486 }
1487
1488 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1489 " sampleDelta=[%d.%08x]",
1490 head.pts(), head.position(), pts,
1491 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1492 + (sampleDelta >> 32)),
1493 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1494
1495 // if the delta between the ideal placement for the next input sample and
1496 // the current output position is within this threshold, then we will
1497 // concatenate the next input samples to the previous output
1498 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001499 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001500
1501 // if this is the first buffer of audio that we're emitting from this track
1502 // then it should be almost exactly on time.
1503 const int64_t kSampleStartupThreshold = 1LL << 32;
1504
1505 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1506 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1507 // the next input is close enough to being on time, so concatenate it
1508 // with the last output
1509 timedYieldSamples_l(buffer);
1510
1511 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1512 head.position(), buffer->frameCount);
1513 return NO_ERROR;
1514 }
1515
1516 // Looks like our output is not on time. Reset our on timed status.
1517 // Next time we mix samples from our input queue, then should be within
1518 // the StartupThreshold.
1519 mTimedAudioOutputOnTime = false;
1520 if (sampleDelta > 0) {
1521 // the gap between the current output position and the proper start of
1522 // the next input sample is too big, so fill it with silence
1523 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1524
1525 timedYieldSilence_l(framesUntilNextInput, buffer);
1526 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1527 return NO_ERROR;
1528 } else {
1529 // the next input sample is late
1530 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1531 size_t onTimeSamplePosition =
1532 head.position() + lateFrames * mFrameSize;
1533
1534 if (onTimeSamplePosition > head.buffer()->size()) {
1535 // all the remaining samples in the head are too late, so
1536 // drop it and move on
1537 ALOGV("*** too late: dropped buffer");
1538 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1539 continue;
1540 } else {
1541 // skip over the late samples
1542 head.setPosition(onTimeSamplePosition);
1543
1544 // yield the available samples
1545 timedYieldSamples_l(buffer);
1546
1547 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1548 return NO_ERROR;
1549 }
1550 }
1551 }
1552}
1553
1554// Yield samples from the timed buffer queue head up to the given output
1555// buffer's capacity.
1556//
1557// Caller must hold mTimedBufferQueueLock
1558void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1559 AudioBufferProvider::Buffer* buffer) {
1560
1561 const TimedBuffer& head = mTimedBufferQueue[0];
1562
1563 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1564 head.position());
1565
1566 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1567 mFrameSize);
1568 size_t framesRequested = buffer->frameCount;
1569 buffer->frameCount = min(framesLeftInHead, framesRequested);
1570
1571 mQueueHeadInFlight = true;
1572 mTimedAudioOutputOnTime = true;
1573}
1574
1575// Yield samples of silence up to the given output buffer's capacity
1576//
1577// Caller must hold mTimedBufferQueueLock
1578void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1579 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1580
1581 // lazily allocate a buffer filled with silence
1582 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1583 delete [] mTimedSilenceBuffer;
1584 mTimedSilenceBufferSize = numFrames * mFrameSize;
1585 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1586 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1587 }
1588
1589 buffer->raw = mTimedSilenceBuffer;
1590 size_t framesRequested = buffer->frameCount;
1591 buffer->frameCount = min(numFrames, framesRequested);
1592
1593 mTimedAudioOutputOnTime = false;
1594}
1595
1596// AudioBufferProvider interface
1597void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1598 AudioBufferProvider::Buffer* buffer) {
1599
1600 Mutex::Autolock _l(mTimedBufferQueueLock);
1601
1602 // If the buffer which was just released is part of the buffer at the head
1603 // of the queue, be sure to update the amt of the buffer which has been
1604 // consumed. If the buffer being returned is not part of the head of the
1605 // queue, its either because the buffer is part of the silence buffer, or
1606 // because the head of the timed queue was trimmed after the mixer called
1607 // getNextBuffer but before the mixer called releaseBuffer.
1608 if (buffer->raw == mTimedSilenceBuffer) {
1609 ALOG_ASSERT(!mQueueHeadInFlight,
1610 "Queue head in flight during release of silence buffer!");
1611 goto done;
1612 }
1613
1614 ALOG_ASSERT(mQueueHeadInFlight,
1615 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1616 " head in flight.");
1617
1618 if (mTimedBufferQueue.size()) {
1619 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1620
1621 void* start = head.buffer()->pointer();
1622 void* end = reinterpret_cast<void*>(
1623 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1624 + head.buffer()->size());
1625
1626 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1627 "released buffer not within the head of the timed buffer"
1628 " queue; qHead = [%p, %p], released buffer = %p",
1629 start, end, buffer->raw);
1630
1631 head.setPosition(head.position() +
1632 (buffer->frameCount * mFrameSize));
1633 mQueueHeadInFlight = false;
1634
1635 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1636 "Bad bookkeeping during releaseBuffer! Should have at"
1637 " least %u queued frames, but we think we have only %u",
1638 buffer->frameCount, mFramesPendingInQueue);
1639
1640 mFramesPendingInQueue -= buffer->frameCount;
1641
1642 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1643 || mTrimQueueHeadOnRelease) {
1644 trimTimedBufferQueueHead_l("releaseBuffer");
1645 mTrimQueueHeadOnRelease = false;
1646 }
1647 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001648 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001649 " buffers in the timed buffer queue");
1650 }
1651
1652done:
1653 buffer->raw = 0;
1654 buffer->frameCount = 0;
1655}
1656
1657size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1658 Mutex::Autolock _l(mTimedBufferQueueLock);
1659 return mFramesPendingInQueue;
1660}
1661
1662AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1663 : mPTS(0), mPosition(0) {}
1664
1665AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1666 const sp<IMemory>& buffer, int64_t pts)
1667 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1668
1669
1670// ----------------------------------------------------------------------------
1671
1672AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1673 PlaybackThread *playbackThread,
1674 DuplicatingThread *sourceThread,
1675 uint32_t sampleRate,
1676 audio_format_t format,
1677 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001678 size_t frameCount,
1679 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001680 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1681 sampleRate, format, channelMask, frameCount,
1682 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001683 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001684{
1685
1686 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001687 mOutBuffer.frameCount = 0;
1688 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001689 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001690 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001691 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001692 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001693 // since client and server are in the same process,
1694 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001695 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1696 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001697 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001698 mClientProxy->setSendLevel(0.0);
1699 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001700 } else {
1701 ALOGW("Error creating output track on thread %p", playbackThread);
1702 }
1703}
1704
1705AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1706{
1707 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001708 delete mClientProxy;
1709 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001710}
1711
1712status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1713 int triggerSession)
1714{
1715 status_t status = Track::start(event, triggerSession);
1716 if (status != NO_ERROR) {
1717 return status;
1718 }
1719
1720 mActive = true;
1721 mRetryCount = 127;
1722 return status;
1723}
1724
1725void AudioFlinger::PlaybackThread::OutputTrack::stop()
1726{
1727 Track::stop();
1728 clearBufferQueue();
1729 mOutBuffer.frameCount = 0;
1730 mActive = false;
1731}
1732
Andy Hungc25b84a2015-01-14 19:04:10 -08001733bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001734{
1735 Buffer *pInBuffer;
1736 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001737 bool outputBufferFull = false;
1738 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001739 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001740
1741 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1742
1743 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001744 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001745 }
1746
1747 while (waitTimeLeftMs) {
1748 // First write pending buffers, then new data
1749 if (mBufferQueue.size()) {
1750 pInBuffer = mBufferQueue.itemAt(0);
1751 } else {
1752 pInBuffer = &inBuffer;
1753 }
1754
1755 if (pInBuffer->frameCount == 0) {
1756 break;
1757 }
1758
1759 if (mOutBuffer.frameCount == 0) {
1760 mOutBuffer.frameCount = pInBuffer->frameCount;
1761 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001762 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1763 if (status != NO_ERROR) {
1764 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1765 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001766 outputBufferFull = true;
1767 break;
1768 }
1769 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1770 if (waitTimeLeftMs >= waitTimeMs) {
1771 waitTimeLeftMs -= waitTimeMs;
1772 } else {
1773 waitTimeLeftMs = 0;
1774 }
1775 }
1776
1777 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1778 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001779 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001780 Proxy::Buffer buf;
1781 buf.mFrameCount = outFrames;
1782 buf.mRaw = NULL;
1783 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001784 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001785 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001786 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001787 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001788
1789 if (pInBuffer->frameCount == 0) {
1790 if (mBufferQueue.size()) {
1791 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001792 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001793 delete pInBuffer;
1794 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1795 mThread.unsafe_get(), mBufferQueue.size());
1796 } else {
1797 break;
1798 }
1799 }
1800 }
1801
1802 // If we could not write all frames, allocate a buffer and queue it for next time.
1803 if (inBuffer.frameCount) {
1804 sp<ThreadBase> thread = mThread.promote();
1805 if (thread != 0 && !thread->standby()) {
1806 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1807 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001808 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001809 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001810 pInBuffer->raw = pInBuffer->mBuffer;
1811 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001812 mBufferQueue.add(pInBuffer);
1813 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1814 mThread.unsafe_get(), mBufferQueue.size());
1815 } else {
1816 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1817 mThread.unsafe_get(), this);
1818 }
1819 }
1820 }
1821
Andy Hungc25b84a2015-01-14 19:04:10 -08001822 // Calling write() with a 0 length buffer means that no more data will be written:
1823 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1824 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1825 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001826 }
1827
1828 return outputBufferFull;
1829}
1830
1831status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1832 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1833{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001834 ClientProxy::Buffer buf;
1835 buf.mFrameCount = buffer->frameCount;
1836 struct timespec timeout;
1837 timeout.tv_sec = waitTimeMs / 1000;
1838 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1839 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1840 buffer->frameCount = buf.mFrameCount;
1841 buffer->raw = buf.mRaw;
1842 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001843}
1844
Eric Laurent81784c32012-11-19 14:55:58 -08001845void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1846{
1847 size_t size = mBufferQueue.size();
1848
1849 for (size_t i = 0; i < size; i++) {
1850 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001851 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001852 delete pBuffer;
1853 }
1854 mBufferQueue.clear();
1855}
1856
1857
Eric Laurent83b88082014-06-20 18:31:16 -07001858AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001859 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001860 uint32_t sampleRate,
1861 audio_channel_mask_t channelMask,
1862 audio_format_t format,
1863 size_t frameCount,
1864 void *buffer,
1865 IAudioFlinger::track_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001866 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001867 sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001868 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1869 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1870{
1871 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1872 playbackThread->sampleRate();
1873 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1874 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1875
1876 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1877 this, sampleRate,
1878 (int)mPeerTimeout.tv_sec,
1879 (int)(mPeerTimeout.tv_nsec / 1000000));
1880}
1881
1882AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1883{
1884}
1885
1886// AudioBufferProvider interface
1887status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1888 AudioBufferProvider::Buffer* buffer, int64_t pts)
1889{
1890 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1891 Proxy::Buffer buf;
1892 buf.mFrameCount = buffer->frameCount;
1893 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1894 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001895 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001896 if (buf.mFrameCount == 0) {
1897 return WOULD_BLOCK;
1898 }
Eric Laurent83b88082014-06-20 18:31:16 -07001899 status = Track::getNextBuffer(buffer, pts);
1900 return status;
1901}
1902
1903void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1904{
1905 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1906 Proxy::Buffer buf;
1907 buf.mFrameCount = buffer->frameCount;
1908 buf.mRaw = buffer->raw;
1909 mPeerProxy->releaseBuffer(&buf);
1910 TrackBase::releaseBuffer(buffer);
1911}
1912
1913status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1914 const struct timespec *timeOut)
1915{
1916 return mProxy->obtainBuffer(buffer, timeOut);
1917}
1918
1919void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1920{
1921 mProxy->releaseBuffer(buffer);
1922 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1923 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1924 start();
1925 }
1926 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1927}
1928
Eric Laurent81784c32012-11-19 14:55:58 -08001929// ----------------------------------------------------------------------------
1930// Record
1931// ----------------------------------------------------------------------------
1932
1933AudioFlinger::RecordHandle::RecordHandle(
1934 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1935 : BnAudioRecord(),
1936 mRecordTrack(recordTrack)
1937{
1938}
1939
1940AudioFlinger::RecordHandle::~RecordHandle() {
1941 stop_nonvirtual();
1942 mRecordTrack->destroy();
1943}
1944
Eric Laurent81784c32012-11-19 14:55:58 -08001945status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1946 int triggerSession) {
1947 ALOGV("RecordHandle::start()");
1948 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1949}
1950
1951void AudioFlinger::RecordHandle::stop() {
1952 stop_nonvirtual();
1953}
1954
1955void AudioFlinger::RecordHandle::stop_nonvirtual() {
1956 ALOGV("RecordHandle::stop()");
1957 mRecordTrack->stop();
1958}
1959
1960status_t AudioFlinger::RecordHandle::onTransact(
1961 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1962{
1963 return BnAudioRecord::onTransact(code, data, reply, flags);
1964}
1965
1966// ----------------------------------------------------------------------------
1967
Glenn Kasten05997e22014-03-13 15:08:33 -07001968// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001969AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1970 RecordThread *thread,
1971 const sp<Client>& client,
1972 uint32_t sampleRate,
1973 audio_format_t format,
1974 audio_channel_mask_t channelMask,
1975 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001976 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001977 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001978 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001979 IAudioFlinger::track_flags_t flags,
1980 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001981 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001982 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001983 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001984 (type == TYPE_DEFAULT) ?
1985 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1986 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1987 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001988 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001989 mFramesToDrop(0),
1990 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1991 mRecordBufferConverter(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001992{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001993 if (mCblk == NULL) {
1994 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001995 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001996
Andy Hung97a893e2015-03-29 01:03:07 -07001997 mRecordBufferConverter = new RecordBufferConverter(
1998 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1999 channelMask, format, sampleRate);
2000 // Check if the RecordBufferConverter construction was successful.
2001 // If not, don't continue with construction.
2002 //
2003 // NOTE: It would be extremely rare that the record track cannot be created
2004 // for the current device, but a pending or future device change would make
2005 // the record track configuration valid.
2006 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
2007 ALOGE("RecordTrack unable to create record buffer converter");
2008 return;
2009 }
2010
Eric Laurent83b88082014-06-20 18:31:16 -07002011 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
2012 mFrameSize, !isExternalTrack());
Andy Hung97a893e2015-03-29 01:03:07 -07002013 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07002014
2015 if (flags & IAudioFlinger::TRACK_FAST) {
2016 ALOG_ASSERT(thread->mFastTrackAvail);
2017 thread->mFastTrackAvail = false;
2018 }
Eric Laurent81784c32012-11-19 14:55:58 -08002019}
2020
2021AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
2022{
2023 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07002024 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002025 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08002026}
2027
Andy Hung97a893e2015-03-29 01:03:07 -07002028status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
2029{
2030 status_t status = TrackBase::initCheck();
2031 if (status == NO_ERROR && mServerProxy == 0) {
2032 status = BAD_VALUE;
2033 }
2034 return status;
2035}
2036
Eric Laurent81784c32012-11-19 14:55:58 -08002037// AudioBufferProvider interface
2038status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002039 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002040{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002041 ServerProxy::Buffer buf;
2042 buf.mFrameCount = buffer->frameCount;
2043 status_t status = mServerProxy->obtainBuffer(&buf);
2044 buffer->frameCount = buf.mFrameCount;
2045 buffer->raw = buf.mRaw;
2046 if (buf.mFrameCount == 0) {
2047 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002048 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002049 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002050 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002051}
2052
2053status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2054 int triggerSession)
2055{
2056 sp<ThreadBase> thread = mThread.promote();
2057 if (thread != 0) {
2058 RecordThread *recordThread = (RecordThread *)thread.get();
2059 return recordThread->start(this, event, triggerSession);
2060 } else {
2061 return BAD_VALUE;
2062 }
2063}
2064
2065void AudioFlinger::RecordThread::RecordTrack::stop()
2066{
2067 sp<ThreadBase> thread = mThread.promote();
2068 if (thread != 0) {
2069 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002070 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07002071 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002072 }
2073 }
2074}
2075
2076void AudioFlinger::RecordThread::RecordTrack::destroy()
2077{
2078 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2079 sp<RecordTrack> keep(this);
2080 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002081 if (isExternalTrack()) {
2082 if (mState == ACTIVE || mState == RESUMING) {
2083 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2084 }
2085 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
2086 }
Eric Laurent81784c32012-11-19 14:55:58 -08002087 sp<ThreadBase> thread = mThread.promote();
2088 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002089 Mutex::Autolock _l(thread->mLock);
2090 RecordThread *recordThread = (RecordThread *) thread.get();
2091 recordThread->destroyTrack_l(this);
2092 }
2093 }
2094}
2095
Eric Laurent9a54bc22013-09-09 09:08:44 -07002096void AudioFlinger::RecordThread::RecordTrack::invalidate()
2097{
2098 // FIXME should use proxy, and needs work
2099 audio_track_cblk_t* cblk = mCblk;
2100 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2101 android_atomic_release_store(0x40000000, &cblk->mFutex);
2102 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002103 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002104}
2105
Eric Laurent81784c32012-11-19 14:55:58 -08002106
2107/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2108{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002109 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002110}
2111
Marco Nelissenb2208842014-02-07 14:00:50 -08002112void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002113{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002114 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08002115 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08002116 (mClient == 0) ? getpid_cached : mClient->pid(),
2117 mFormat,
2118 mChannelMask,
2119 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002120 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002121 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002122 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002123 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002124
Eric Laurent81784c32012-11-19 14:55:58 -08002125}
2126
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002127void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2128{
2129 if (event == mSyncStartEvent) {
2130 ssize_t framesToDrop = 0;
2131 sp<ThreadBase> threadBase = mThread.promote();
2132 if (threadBase != 0) {
2133 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2134 // from audio HAL
2135 framesToDrop = threadBase->mFrameCount * 2;
2136 }
2137 mFramesToDrop = framesToDrop;
2138 }
2139}
2140
2141void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2142{
2143 if (mSyncStartEvent != 0) {
2144 mSyncStartEvent->cancel();
2145 mSyncStartEvent.clear();
2146 }
2147 mFramesToDrop = 0;
2148}
2149
Eric Laurent83b88082014-06-20 18:31:16 -07002150
2151AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2152 uint32_t sampleRate,
2153 audio_channel_mask_t channelMask,
2154 audio_format_t format,
2155 size_t frameCount,
2156 void *buffer,
2157 IAudioFlinger::track_flags_t flags)
2158 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2159 buffer, 0, getuid(), flags, TYPE_PATCH),
2160 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2161{
2162 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2163 recordThread->sampleRate();
2164 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2165 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2166
2167 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2168 this, sampleRate,
2169 (int)mPeerTimeout.tv_sec,
2170 (int)(mPeerTimeout.tv_nsec / 1000000));
2171}
2172
2173AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2174{
2175}
2176
2177// AudioBufferProvider interface
2178status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2179 AudioBufferProvider::Buffer* buffer, int64_t pts)
2180{
2181 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2182 Proxy::Buffer buf;
2183 buf.mFrameCount = buffer->frameCount;
2184 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2185 ALOGV_IF(status != NO_ERROR,
2186 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002187 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002188 if (buf.mFrameCount == 0) {
2189 return WOULD_BLOCK;
2190 }
Eric Laurent83b88082014-06-20 18:31:16 -07002191 status = RecordTrack::getNextBuffer(buffer, pts);
2192 return status;
2193}
2194
2195void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2196{
2197 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2198 Proxy::Buffer buf;
2199 buf.mFrameCount = buffer->frameCount;
2200 buf.mRaw = buffer->raw;
2201 mPeerProxy->releaseBuffer(&buf);
2202 TrackBase::releaseBuffer(buffer);
2203}
2204
2205status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2206 const struct timespec *timeOut)
2207{
2208 return mProxy->obtainBuffer(buffer, timeOut);
2209}
2210
2211void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2212{
2213 mProxy->releaseBuffer(buffer);
2214}
2215
Glenn Kasten63238ef2015-03-02 15:50:29 -08002216} // namespace android