blob: c753afded5764285271af0a4e98f8b28989a5ddd [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 Nelissendcb346b2015-09-09 10:47:29 -0700103 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
104 if (!isTrustedCallingUid(callingUid) || clientUid == -1) {
105 ALOGW_IF(clientUid != -1 && clientUid != (int)callingUid,
106 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
107 clientUid = (int)callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800108 }
109 // clientUid contains the uid of the app that is responsible for this track, so we can blame
110 // battery usage on it.
111 mUid = clientUid;
112
Eric Laurent81784c32012-11-19 14:55:58 -0800113 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
114 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700115 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
116 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800117 size += bufferSize;
118 }
119
120 if (client != 0) {
121 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700122 if (mCblkMemory == 0 ||
123 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800124 ALOGE("not enough memory for AudioTrack size=%u", size);
125 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700126 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800127 return;
128 }
129 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800130 // this syntax avoids calling the audio_track_cblk_t constructor twice
131 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800132 // assume mCblk != NULL
133 }
134
135 // construct the shared structure in-place.
136 if (mCblk != NULL) {
137 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700138 switch (alloc) {
139 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700140 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
141 if (roHeap == 0 ||
142 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
143 (mBuffer = mBufferMemory->pointer()) == NULL) {
144 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
145 if (roHeap != 0) {
146 roHeap->dump("buffer");
147 }
148 mCblkMemory.clear();
149 mBufferMemory.clear();
150 return;
151 }
Eric Laurent81784c32012-11-19 14:55:58 -0800152 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700153 } break;
154 case ALLOC_PIPE:
155 mBufferMemory = thread->pipeMemory();
156 // mBuffer is the virtual address as seen from current process (mediaserver),
157 // and should normally be coming from mBufferMemory->pointer().
158 // However in this case the TrackBase does not reference the buffer directly.
159 // It should references the buffer via the pipe.
160 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
161 mBuffer = NULL;
162 break;
163 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700164 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700165 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700166 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
167 memset(mBuffer, 0, bufferSize);
168 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700169 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700171 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800172#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700173 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700174 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700175 case ALLOC_LOCAL:
176 mBuffer = calloc(1, bufferSize);
177 break;
178 case ALLOC_NONE:
179 mBuffer = buffer;
180 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800181 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800182
Glenn Kasten46909e72013-02-26 09:20:22 -0800183#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800184 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700185 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800186 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800187 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
188 size_t numCounterOffers = 0;
189 const NBAIO_Format offers[1] = {pipeFormat};
190 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
191 ALOG_ASSERT(index == 0);
192 PipeReader *pipeReader = new PipeReader(*pipe);
193 numCounterOffers = 0;
194 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
195 ALOG_ASSERT(index == 0);
196 mTeeSink = pipe;
197 mTeeSource = pipeReader;
198 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800200#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201
Eric Laurent81784c32012-11-19 14:55:58 -0800202 }
203}
204
Eric Laurent83b88082014-06-20 18:31:16 -0700205status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
206{
207 status_t status;
208 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
209 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
210 } else {
211 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
212 }
213 return status;
214}
215
Eric Laurent81784c32012-11-19 14:55:58 -0800216AudioFlinger::ThreadBase::TrackBase::~TrackBase()
217{
Glenn Kasten46909e72013-02-26 09:20:22 -0800218#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800219 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800220#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800221 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
222 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800223 if (mCblk != NULL) {
224 if (mClient == 0) {
225 delete mCblk;
226 } else {
227 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
228 }
229 }
230 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
231 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700232 // Client destructor must run with AudioFlinger client mutex locked
233 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800234 // If the client's reference count drops to zero, the associated destructor
235 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
236 // relying on the automatic clear() at end of scope.
237 mClient.clear();
238 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700239 // flush the binder command buffer
240 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800241}
242
243// AudioBufferProvider interface
244// getNextBuffer() = 0;
245// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
246void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
247{
Glenn Kasten46909e72013-02-26 09:20:22 -0800248#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800249 if (mTeeSink != 0) {
250 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
251 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800252#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800253
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800254 ServerProxy::Buffer buf;
255 buf.mFrameCount = buffer->frameCount;
256 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800257 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800258 buffer->raw = NULL;
259 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800260}
261
Eric Laurent81784c32012-11-19 14:55:58 -0800262status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
263{
264 mSyncEvents.add(event);
265 return NO_ERROR;
266}
267
268// ----------------------------------------------------------------------------
269// Playback
270// ----------------------------------------------------------------------------
271
272AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
273 : BnAudioTrack(),
274 mTrack(track)
275{
276}
277
278AudioFlinger::TrackHandle::~TrackHandle() {
279 // just stop the track on deletion, associated resources
280 // will be freed from the main thread once all pending buffers have
281 // been played. Unless it's not in the active track list, in which
282 // case we free everything now...
283 mTrack->destroy();
284}
285
286sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
287 return mTrack->getCblk();
288}
289
290status_t AudioFlinger::TrackHandle::start() {
291 return mTrack->start();
292}
293
294void AudioFlinger::TrackHandle::stop() {
295 mTrack->stop();
296}
297
298void AudioFlinger::TrackHandle::flush() {
299 mTrack->flush();
300}
301
Eric Laurent81784c32012-11-19 14:55:58 -0800302void AudioFlinger::TrackHandle::pause() {
303 mTrack->pause();
304}
305
306status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
307{
308 return mTrack->attachAuxEffect(EffectId);
309}
310
311status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
312 sp<IMemory>* buffer) {
313 if (!mTrack->isTimedTrack())
314 return INVALID_OPERATION;
315
316 PlaybackThread::TimedTrack* tt =
317 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
318 return tt->allocateTimedBuffer(size, buffer);
319}
320
321status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
322 int64_t pts) {
323 if (!mTrack->isTimedTrack())
324 return INVALID_OPERATION;
325
Glenn Kasten663c2242013-09-24 11:52:37 -0700326 if (buffer == 0 || buffer->pointer() == NULL) {
327 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
328 return BAD_VALUE;
329 }
330
Eric Laurent81784c32012-11-19 14:55:58 -0800331 PlaybackThread::TimedTrack* tt =
332 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
333 return tt->queueTimedBuffer(buffer, pts);
334}
335
336status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
337 const LinearTransform& xform, int target) {
338
339 if (!mTrack->isTimedTrack())
340 return INVALID_OPERATION;
341
342 PlaybackThread::TimedTrack* tt =
343 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
344 return tt->setMediaTimeTransform(
345 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
346}
347
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700348status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
349 return mTrack->setParameters(keyValuePairs);
350}
351
Glenn Kasten53cec222013-08-29 09:01:02 -0700352status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
353{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700354 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700355}
356
Eric Laurent59fe0102013-09-27 18:48:26 -0700357
358void AudioFlinger::TrackHandle::signal()
359{
360 return mTrack->signal();
361}
362
Eric Laurent81784c32012-11-19 14:55:58 -0800363status_t AudioFlinger::TrackHandle::onTransact(
364 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
365{
366 return BnAudioTrack::onTransact(code, data, reply, flags);
367}
368
369// ----------------------------------------------------------------------------
370
371// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
372AudioFlinger::PlaybackThread::Track::Track(
373 PlaybackThread *thread,
374 const sp<Client>& client,
375 audio_stream_type_t streamType,
376 uint32_t sampleRate,
377 audio_format_t format,
378 audio_channel_mask_t channelMask,
379 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700380 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800381 const sp<IMemory>& sharedBuffer,
382 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800383 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700384 IAudioFlinger::track_flags_t flags,
385 track_type type)
386 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
387 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
388 sessionId, uid, flags, true /*isOut*/,
389 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
390 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800391 mFillingUpStatus(FS_INVALID),
392 // mRetryCount initialized later when needed
393 mSharedBuffer(sharedBuffer),
394 mStreamType(streamType),
395 mName(-1), // see note below
396 mMainBuffer(thread->mixBuffer()),
397 mAuxBuffer(NULL),
398 mAuxEffectId(0), mHasVolumeController(false),
399 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800400 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800401 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800402 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800403 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800404 mResumeToStopping(false),
Phil Burk1b420972015-04-22 10:52:21 -0700405 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800406{
Eric Laurent83b88082014-06-20 18:31:16 -0700407 // client == 0 implies sharedBuffer == 0
408 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
409
410 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
411 sharedBuffer->size());
412
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700413 if (mCblk == NULL) {
414 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800415 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700416
417 if (sharedBuffer == 0) {
418 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700419 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700420 } else {
421 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
422 mFrameSize);
423 }
424 mServerProxy = mAudioTrackServerProxy;
425
Glenn Kastenc263ca02014-06-04 20:31:46 -0700426 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700427 if (mName < 0) {
428 ALOGE("no more track names available");
429 return;
430 }
431 // only allocate a fast track index if we were able to allocate a normal track name
432 if (flags & IAudioFlinger::TRACK_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700433 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
434 // race with setSyncEvent(). However, if we call it, we cannot properly start
435 // static fast tracks (SoundPool) immediately after stopping.
436 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700437 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
438 int i = __builtin_ctz(thread->mFastTrackAvailMask);
439 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
440 // FIXME This is too eager. We allocate a fast track index before the
441 // fast track becomes active. Since fast tracks are a scarce resource,
442 // this means we are potentially denying other more important fast tracks from
443 // being created. It would be better to allocate the index dynamically.
444 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700445 thread->mFastTrackAvailMask &= ~(1 << i);
446 }
Eric Laurent81784c32012-11-19 14:55:58 -0800447}
448
449AudioFlinger::PlaybackThread::Track::~Track()
450{
451 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700452
453 // The destructor would clear mSharedBuffer,
454 // but it will not push the decremented reference count,
455 // leaving the client's IMemory dangling indefinitely.
456 // This prevents that leak.
457 if (mSharedBuffer != 0) {
458 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700459 }
Eric Laurent81784c32012-11-19 14:55:58 -0800460}
461
Glenn Kasten03003332013-08-06 15:40:54 -0700462status_t AudioFlinger::PlaybackThread::Track::initCheck() const
463{
464 status_t status = TrackBase::initCheck();
465 if (status == NO_ERROR && mName < 0) {
466 status = NO_MEMORY;
467 }
468 return status;
469}
470
Eric Laurent81784c32012-11-19 14:55:58 -0800471void AudioFlinger::PlaybackThread::Track::destroy()
472{
473 // NOTE: destroyTrack_l() can remove a strong reference to this Track
474 // by removing it from mTracks vector, so there is a risk that this Tracks's
475 // destructor is called. As the destructor needs to lock mLock,
476 // we must acquire a strong reference on this Track before locking mLock
477 // here so that the destructor is called only when exiting this function.
478 // On the other hand, as long as Track::destroy() is only called by
479 // TrackHandle destructor, the TrackHandle still holds a strong ref on
480 // this Track with its member mTrack.
481 sp<Track> keep(this);
482 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700483 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800484 sp<ThreadBase> thread = mThread.promote();
485 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800486 Mutex::Autolock _l(thread->mLock);
487 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700488 wasActive = playbackThread->destroyTrack_l(this);
489 }
490 if (isExternalTrack() && !wasActive) {
Eric Laurente83b55d2014-11-14 10:06:21 -0800491 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800492 }
493 }
494}
495
496/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
497{
Marco Nelissenb2208842014-02-07 14:00:50 -0800498 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700499 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800500}
501
Marco Nelissenb2208842014-02-07 14:00:50 -0800502void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800503{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700504 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800505 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800506 sprintf(buffer, " F %2d", mFastIndex);
507 } else if (mName >= AudioMixer::TRACK0) {
508 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800509 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800510 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800511 }
512 track_state state = mState;
513 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800514 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800515 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800516 } else {
517 switch (state) {
518 case IDLE:
519 stateChar = 'I';
520 break;
521 case STOPPING_1:
522 stateChar = 's';
523 break;
524 case STOPPING_2:
525 stateChar = '5';
526 break;
527 case STOPPED:
528 stateChar = 'S';
529 break;
530 case RESUMING:
531 stateChar = 'R';
532 break;
533 case ACTIVE:
534 stateChar = 'A';
535 break;
536 case PAUSING:
537 stateChar = 'p';
538 break;
539 case PAUSED:
540 stateChar = 'P';
541 break;
542 case FLUSHED:
543 stateChar = 'F';
544 break;
545 default:
546 stateChar = '?';
547 break;
548 }
Eric Laurent81784c32012-11-19 14:55:58 -0800549 }
550 char nowInUnderrun;
551 switch (mObservedUnderruns.mBitFields.mMostRecent) {
552 case UNDERRUN_FULL:
553 nowInUnderrun = ' ';
554 break;
555 case UNDERRUN_PARTIAL:
556 nowInUnderrun = '<';
557 break;
558 case UNDERRUN_EMPTY:
559 nowInUnderrun = '*';
560 break;
561 default:
562 nowInUnderrun = '?';
563 break;
564 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000565 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 +0000566 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800567 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800568 (mClient == 0) ? getpid_cached : mClient->pid(),
569 mStreamType,
570 mFormat,
571 mChannelMask,
572 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800573 mFrameCount,
574 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800575 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800576 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700577 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
578 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700579 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000580 mMainBuffer,
581 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700582 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700583 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800584 nowInUnderrun);
585}
586
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800587uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
588 return mAudioTrackServerProxy->getSampleRate();
589}
590
Eric Laurent81784c32012-11-19 14:55:58 -0800591// AudioBufferProvider interface
592status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800593 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800594{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800595 ServerProxy::Buffer buf;
596 size_t desiredFrames = buffer->frameCount;
597 buf.mFrameCount = desiredFrames;
598 status_t status = mServerProxy->obtainBuffer(&buf);
599 buffer->frameCount = buf.mFrameCount;
600 buffer->raw = buf.mRaw;
601 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700602 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800603 } else {
604 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800605 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800606
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800607 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800608}
609
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700610// releaseBuffer() is not overridden
611
612// ExtendedAudioBufferProvider interface
613
Andy Hung27876c02014-09-09 18:07:55 -0700614// framesReady() may return an approximation of the number of frames if called
615// from a different thread than the one calling Proxy->obtainBuffer() and
616// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
617// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800618size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700619 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
620 // Static tracks return zero frames immediately upon stopping (for FastTracks).
621 // The remainder of the buffer is not drained.
622 return 0;
623 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800624 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800625}
626
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700627size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
628{
629 return mAudioTrackServerProxy->framesReleased();
630}
631
Eric Laurent81784c32012-11-19 14:55:58 -0800632// Don't call for fast tracks; the framesReady() could result in priority inversion
633bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800634 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
635 return true;
636 }
637
Eric Laurent16498512014-03-17 17:22:08 -0700638 if (isStopping()) {
639 if (framesReady() > 0) {
640 mFillingUpStatus = FS_FILLED;
641 }
Eric Laurent81784c32012-11-19 14:55:58 -0800642 return true;
643 }
644
645 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700646 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800647 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700648 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800649 return true;
650 }
651 return false;
652}
653
Glenn Kasten0f11b512014-01-31 16:18:54 -0800654status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
655 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800656{
657 status_t status = NO_ERROR;
658 ALOGV("start(%d), calling pid %d session %d",
659 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
660
661 sp<ThreadBase> thread = mThread.promote();
662 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700663 if (isOffloaded()) {
664 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
665 Mutex::Autolock _lth(thread->mLock);
666 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700667 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
668 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700669 invalidate();
670 return PERMISSION_DENIED;
671 }
672 }
673 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800674 track_state state = mState;
675 // here the track could be either new, or restarted
676 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800677
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800678 // initial state-stopping. next state-pausing.
679 // What if resume is called ?
680
681 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800682 if (mResumeToStopping) {
683 // happened we need to resume to STOPPING_1
684 mState = TrackBase::STOPPING_1;
685 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
686 } else {
687 mState = TrackBase::RESUMING;
688 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
689 }
Eric Laurent81784c32012-11-19 14:55:58 -0800690 } else {
691 mState = TrackBase::ACTIVE;
692 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
693 }
694
Eric Laurentbfb1b832013-01-07 09:53:42 -0800695 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700696 if (isFastTrack()) {
697 // refresh fast track underruns on start because that field is never cleared
698 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
699 // after stop.
700 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
701 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800702 status = playbackThread->addTrack_l(this);
703 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800704 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800705 // restore previous state if start was rejected by policy manager
706 if (status == PERMISSION_DENIED) {
707 mState = state;
708 }
709 }
710 // track was already in the active list, not a problem
711 if (status == ALREADY_EXISTS) {
712 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700713 } else {
714 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
715 // It is usually unsafe to access the server proxy from a binder thread.
716 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
717 // isn't looking at this track yet: we still hold the normal mixer thread lock,
718 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700719 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700720 ServerProxy::Buffer buffer;
721 buffer.mFrameCount = 1;
722 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800723 }
724 } else {
725 status = BAD_VALUE;
726 }
727 return status;
728}
729
730void AudioFlinger::PlaybackThread::Track::stop()
731{
732 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
733 sp<ThreadBase> thread = mThread.promote();
734 if (thread != 0) {
735 Mutex::Autolock _l(thread->mLock);
736 track_state state = mState;
737 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
738 // If the track is not active (PAUSED and buffers full), flush buffers
739 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
740 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
741 reset();
742 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700743 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800744 mState = STOPPED;
745 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800746 // For fast tracks prepareTracks_l() will set state to STOPPING_2
747 // presentation is complete
748 // For an offloaded track this starts a drain and state will
749 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800750 mState = STOPPING_1;
751 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700752 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800753 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
754 playbackThread);
755 }
Eric Laurent81784c32012-11-19 14:55:58 -0800756 }
757}
758
759void AudioFlinger::PlaybackThread::Track::pause()
760{
761 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
762 sp<ThreadBase> thread = mThread.promote();
763 if (thread != 0) {
764 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800765 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
766 switch (mState) {
767 case STOPPING_1:
768 case STOPPING_2:
769 if (!isOffloaded()) {
770 /* nothing to do if track is not offloaded */
771 break;
772 }
773
774 // Offloaded track was draining, we need to carry on draining when resumed
775 mResumeToStopping = true;
776 // fall through...
777 case ACTIVE:
778 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800779 mState = PAUSING;
780 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700781 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800782 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800783
Eric Laurentbfb1b832013-01-07 09:53:42 -0800784 default:
785 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800786 }
787 }
788}
789
790void AudioFlinger::PlaybackThread::Track::flush()
791{
792 ALOGV("flush(%d)", mName);
793 sp<ThreadBase> thread = mThread.promote();
794 if (thread != 0) {
795 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800796 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800797
798 if (isOffloaded()) {
799 // If offloaded we allow flush during any state except terminated
800 // and keep the track active to avoid problems if user is seeking
801 // rapidly and underlying hardware has a significant delay handling
802 // a pause
803 if (isTerminated()) {
804 return;
805 }
806
807 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800808 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800809
810 if (mState == STOPPING_1 || mState == STOPPING_2) {
811 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
812 mState = ACTIVE;
813 }
814
815 if (mState == ACTIVE) {
816 ALOGV("flush called in active state, resetting buffer time out retry count");
817 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
818 }
819
Haynes Mathew George7844f672014-01-15 12:32:55 -0800820 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800821 mResumeToStopping = false;
822 } else {
823 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
824 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
825 return;
826 }
827 // No point remaining in PAUSED state after a flush => go to
828 // FLUSHED state
829 mState = FLUSHED;
830 // do not reset the track if it is still in the process of being stopped or paused.
831 // this will be done by prepareTracks_l() when the track is stopped.
832 // prepareTracks_l() will see mState == FLUSHED, then
833 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800834 if (isDirect()) {
835 mFlushHwPending = true;
836 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800837 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
838 reset();
839 }
Eric Laurent81784c32012-11-19 14:55:58 -0800840 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800841 // Prevent flush being lost if the track is flushed and then resumed
842 // before mixer thread can run. This is important when offloading
843 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700844 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800845 }
846}
847
Haynes Mathew George7844f672014-01-15 12:32:55 -0800848// must be called with thread lock held
849void AudioFlinger::PlaybackThread::Track::flushAck()
850{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800851 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800852 return;
853
854 mFlushHwPending = false;
855}
856
Eric Laurent81784c32012-11-19 14:55:58 -0800857void AudioFlinger::PlaybackThread::Track::reset()
858{
859 // Do not reset twice to avoid discarding data written just after a flush and before
860 // the audioflinger thread detects the track is stopped.
861 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800862 // Force underrun condition to avoid false underrun callback until first data is
863 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700864 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800865 mFillingUpStatus = FS_FILLING;
866 mResetDone = true;
867 if (mState == FLUSHED) {
868 mState = IDLE;
869 }
870 }
871}
872
Eric Laurentbfb1b832013-01-07 09:53:42 -0800873status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
874{
875 sp<ThreadBase> thread = mThread.promote();
876 if (thread == 0) {
877 ALOGE("thread is dead");
878 return FAILED_TRANSACTION;
879 } else if ((thread->type() == ThreadBase::DIRECT) ||
880 (thread->type() == ThreadBase::OFFLOAD)) {
881 return thread->setParameters(keyValuePairs);
882 } else {
883 return PERMISSION_DENIED;
884 }
885}
886
Glenn Kasten573d80a2013-08-26 09:36:23 -0700887status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
888{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700889 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
890 if (isFastTrack()) {
891 return INVALID_OPERATION;
892 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700893 sp<ThreadBase> thread = mThread.promote();
894 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700895 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700896 }
Phil Burk6140c792015-03-19 14:30:21 -0700897
Glenn Kasten573d80a2013-08-26 09:36:23 -0700898 Mutex::Autolock _l(thread->mLock);
899 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Phil Burk6140c792015-03-19 14:30:21 -0700900
901 status_t result = INVALID_OPERATION;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700902 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700903 if (!playbackThread->mLatchQValid) {
904 return INVALID_OPERATION;
905 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700906 // FIXME Not accurate under dynamic changes of sample rate and speed.
907 // Do not use track's mSampleRate as it is not current for mixer tracks.
908 uint32_t sampleRate = mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700909 AudioPlaybackRate playbackRate = mAudioTrackServerProxy->getPlaybackRate();
910 uint32_t unpresentedFrames = ((double) playbackThread->mLatchQ.mUnpresentedFrames *
911 sampleRate * playbackRate.mSpeed)/ playbackThread->mSampleRate;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700912 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
913 // for a brand new track to share the same address as a recently destroyed
914 // track, and thus for us to get the frames released of the wrong track.
915 // It is unlikely that we would be able to call getTimestamp() so quickly
916 // right after creating a new track. Nevertheless, the index here should
917 // be changed to something that is unique. Or use a completely different strategy.
918 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
919 uint32_t framesWritten = i >= 0 ?
920 playbackThread->mLatchQ.mFramesReleased[i] :
921 mAudioTrackServerProxy->framesReleased();
Phil Burk1b420972015-04-22 10:52:21 -0700922 if (framesWritten >= unpresentedFrames) {
Phil Burk6140c792015-03-19 14:30:21 -0700923 timestamp.mPosition = framesWritten - unpresentedFrames;
924 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
925 result = NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -0700926 }
Phil Burk6140c792015-03-19 14:30:21 -0700927 } else { // offloaded or direct
928 result = playbackThread->getTimestamp_l(timestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700929 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700930
Phil Burk6140c792015-03-19 14:30:21 -0700931 return result;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700932}
933
Eric Laurent81784c32012-11-19 14:55:58 -0800934status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
935{
936 status_t status = DEAD_OBJECT;
937 sp<ThreadBase> thread = mThread.promote();
938 if (thread != 0) {
939 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
940 sp<AudioFlinger> af = mClient->audioFlinger();
941
942 Mutex::Autolock _l(af->mLock);
943
944 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
945
946 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
947 Mutex::Autolock _dl(playbackThread->mLock);
948 Mutex::Autolock _sl(srcThread->mLock);
949 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
950 if (chain == 0) {
951 return INVALID_OPERATION;
952 }
953
954 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
955 if (effect == 0) {
956 return INVALID_OPERATION;
957 }
958 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700959 status = playbackThread->addEffect_l(effect);
960 if (status != NO_ERROR) {
961 srcThread->addEffect_l(effect);
962 return INVALID_OPERATION;
963 }
Eric Laurent81784c32012-11-19 14:55:58 -0800964 // removeEffect_l() has stopped the effect if it was active so it must be restarted
965 if (effect->state() == EffectModule::ACTIVE ||
966 effect->state() == EffectModule::STOPPING) {
967 effect->start();
968 }
969
970 sp<EffectChain> dstChain = effect->chain().promote();
971 if (dstChain == 0) {
972 srcThread->addEffect_l(effect);
973 return INVALID_OPERATION;
974 }
975 AudioSystem::unregisterEffect(effect->id());
976 AudioSystem::registerEffect(&effect->desc(),
977 srcThread->id(),
978 dstChain->strategy(),
979 AUDIO_SESSION_OUTPUT_MIX,
980 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700981 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800982 }
983 status = playbackThread->attachAuxEffect(this, EffectId);
984 }
985 return status;
986}
987
988void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
989{
990 mAuxEffectId = EffectId;
991 mAuxBuffer = buffer;
992}
993
994bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
995 size_t audioHalFrames)
996{
997 // a track is considered presented when the total number of frames written to audio HAL
998 // corresponds to the number of frames written when presentationComplete() is called for the
999 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001000 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1001 // to detect when all frames have been played. In this case framesWritten isn't
1002 // useful because it doesn't always reflect whether there is data in the h/w
1003 // buffers, particularly if a track has been paused and resumed during draining
1004 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1005 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001006 if (mPresentationCompleteFrames == 0) {
1007 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1008 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1009 mPresentationCompleteFrames, audioHalFrames);
1010 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001011
1012 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001013 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001014 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001015 return true;
1016 }
1017 return false;
1018}
1019
1020void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1021{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001022 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001023 if (mSyncEvents[i]->type() == type) {
1024 mSyncEvents[i]->trigger();
1025 mSyncEvents.removeAt(i);
1026 i--;
1027 }
1028 }
1029}
1030
1031// implement VolumeBufferProvider interface
1032
Glenn Kastenc56f3422014-03-21 17:53:17 -07001033gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001034{
1035 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1036 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001037 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1038 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1039 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001040 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001041 if (vl > GAIN_FLOAT_UNITY) {
1042 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001043 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001044 if (vr > GAIN_FLOAT_UNITY) {
1045 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001046 }
1047 // now apply the cached master volume and stream type volume;
1048 // this is trusted but lacks any synchronization or barrier so may be stale
1049 float v = mCachedVolume;
1050 vl *= v;
1051 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001052 // re-combine into packed minifloat
1053 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001054 // FIXME look at mute, pause, and stop flags
1055 return vlr;
1056}
1057
1058status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1059{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001060 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001061 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1062 (mState == STOPPED)))) {
1063 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1064 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1065 event->cancel();
1066 return INVALID_OPERATION;
1067 }
1068 (void) TrackBase::setSyncEvent(event);
1069 return NO_ERROR;
1070}
1071
Glenn Kasten5736c352012-12-04 12:12:34 -08001072void AudioFlinger::PlaybackThread::Track::invalidate()
1073{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001074 // FIXME should use proxy, and needs work
1075 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001076 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001077 android_atomic_release_store(0x40000000, &cblk->mFutex);
1078 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001079 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001080 mIsInvalid = true;
1081}
1082
Eric Laurent59fe0102013-09-27 18:48:26 -07001083void AudioFlinger::PlaybackThread::Track::signal()
1084{
1085 sp<ThreadBase> thread = mThread.promote();
1086 if (thread != 0) {
1087 PlaybackThread *t = (PlaybackThread *)thread.get();
1088 Mutex::Autolock _l(t->mLock);
1089 t->broadcast_l();
1090 }
1091}
1092
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001093//To be called with thread lock held
1094bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1095
1096 if (mState == RESUMING)
1097 return true;
1098 /* Resume is pending if track was stopping before pause was called */
1099 if (mState == STOPPING_1 &&
1100 mResumeToStopping)
1101 return true;
1102
1103 return false;
1104}
1105
1106//To be called with thread lock held
1107void AudioFlinger::PlaybackThread::Track::resumeAck() {
1108
1109
1110 if (mState == RESUMING)
1111 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001112
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001113 // Other possibility of pending resume is stopping_1 state
1114 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001115 // drain being called.
1116 if (mState == STOPPING_1) {
1117 mResumeToStopping = false;
1118 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001119}
Eric Laurent81784c32012-11-19 14:55:58 -08001120// ----------------------------------------------------------------------------
1121
1122sp<AudioFlinger::PlaybackThread::TimedTrack>
1123AudioFlinger::PlaybackThread::TimedTrack::create(
1124 PlaybackThread *thread,
1125 const sp<Client>& client,
1126 audio_stream_type_t streamType,
1127 uint32_t sampleRate,
1128 audio_format_t format,
1129 audio_channel_mask_t channelMask,
1130 size_t frameCount,
1131 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001132 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001133 int uid)
1134{
Eric Laurent81784c32012-11-19 14:55:58 -08001135 if (!client->reserveTimedTrack())
1136 return 0;
1137
1138 return new TimedTrack(
1139 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001140 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001141}
1142
1143AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1144 PlaybackThread *thread,
1145 const sp<Client>& client,
1146 audio_stream_type_t streamType,
1147 uint32_t sampleRate,
1148 audio_format_t format,
1149 audio_channel_mask_t channelMask,
1150 size_t frameCount,
1151 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001152 int sessionId,
1153 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001154 : Track(thread, client, streamType, sampleRate, format, channelMask,
Eric Laurent83b88082014-06-20 18:31:16 -07001155 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1156 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001157 mQueueHeadInFlight(false),
1158 mTrimQueueHeadOnRelease(false),
1159 mFramesPendingInQueue(0),
1160 mTimedSilenceBuffer(NULL),
1161 mTimedSilenceBufferSize(0),
1162 mTimedAudioOutputOnTime(false),
1163 mMediaTimeTransformValid(false)
1164{
1165 LocalClock lc;
1166 mLocalTimeFreq = lc.getLocalFreq();
1167
1168 mLocalTimeToSampleTransform.a_zero = 0;
1169 mLocalTimeToSampleTransform.b_zero = 0;
1170 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1171 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1172 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1173 &mLocalTimeToSampleTransform.a_to_b_denom);
1174
1175 mMediaTimeToSampleTransform.a_zero = 0;
1176 mMediaTimeToSampleTransform.b_zero = 0;
1177 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1178 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1179 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1180 &mMediaTimeToSampleTransform.a_to_b_denom);
1181}
1182
1183AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1184 mClient->releaseTimedTrack();
1185 delete [] mTimedSilenceBuffer;
1186}
1187
1188status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1189 size_t size, sp<IMemory>* buffer) {
1190
1191 Mutex::Autolock _l(mTimedBufferQueueLock);
1192
1193 trimTimedBufferQueue_l();
1194
1195 // lazily initialize the shared memory heap for timed buffers
1196 if (mTimedMemoryDealer == NULL) {
1197 const int kTimedBufferHeapSize = 512 << 10;
1198
1199 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1200 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001201 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001202 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001203 }
Eric Laurent81784c32012-11-19 14:55:58 -08001204 }
1205
1206 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001207 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001208 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001209 }
1210
1211 *buffer = newBuffer;
1212 return NO_ERROR;
1213}
1214
1215// caller must hold mTimedBufferQueueLock
1216void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1217 int64_t mediaTimeNow;
1218 {
1219 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1220 if (!mMediaTimeTransformValid)
1221 return;
1222
1223 int64_t targetTimeNow;
1224 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1225 ? mCCHelper.getCommonTime(&targetTimeNow)
1226 : mCCHelper.getLocalTime(&targetTimeNow);
1227
1228 if (OK != res)
1229 return;
1230
1231 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1232 &mediaTimeNow)) {
1233 return;
1234 }
1235 }
1236
1237 size_t trimEnd;
1238 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1239 int64_t bufEnd;
1240
1241 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1242 // We have a next buffer. Just use its PTS as the PTS of the frame
1243 // following the last frame in this buffer. If the stream is sparse
1244 // (ie, there are deliberate gaps left in the stream which should be
1245 // filled with silence by the TimedAudioTrack), then this can result
1246 // in one extra buffer being left un-trimmed when it could have
1247 // been. In general, this is not typical, and we would rather
1248 // optimized away the TS calculation below for the more common case
1249 // where PTSes are contiguous.
1250 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1251 } else {
1252 // We have no next buffer. Compute the PTS of the frame following
1253 // the last frame in this buffer by computing the duration of of
1254 // this frame in media time units and adding it to the PTS of the
1255 // buffer.
1256 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1257 / mFrameSize;
1258
1259 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1260 &bufEnd)) {
1261 ALOGE("Failed to convert frame count of %lld to media time"
1262 " duration" " (scale factor %d/%u) in %s",
1263 frameCount,
1264 mMediaTimeToSampleTransform.a_to_b_numer,
1265 mMediaTimeToSampleTransform.a_to_b_denom,
1266 __PRETTY_FUNCTION__);
1267 break;
1268 }
1269 bufEnd += mTimedBufferQueue[trimEnd].pts();
1270 }
1271
1272 if (bufEnd > mediaTimeNow)
1273 break;
1274
1275 // Is the buffer we want to use in the middle of a mix operation right
1276 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1277 // from the mixer which should be coming back shortly.
1278 if (!trimEnd && mQueueHeadInFlight) {
1279 mTrimQueueHeadOnRelease = true;
1280 }
1281 }
1282
1283 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1284 if (trimStart < trimEnd) {
1285 // Update the bookkeeping for framesReady()
1286 for (size_t i = trimStart; i < trimEnd; ++i) {
1287 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1288 }
1289
1290 // Now actually remove the buffers from the queue.
1291 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1292 }
1293}
1294
1295void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1296 const char* logTag) {
1297 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1298 "%s called (reason \"%s\"), but timed buffer queue has no"
1299 " elements to trim.", __FUNCTION__, logTag);
1300
1301 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1302 mTimedBufferQueue.removeAt(0);
1303}
1304
1305void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1306 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001307 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001308 uint32_t bufBytes = buf.buffer()->size();
1309 uint32_t consumedAlready = buf.position();
1310
1311 ALOG_ASSERT(consumedAlready <= bufBytes,
1312 "Bad bookkeeping while updating frames pending. Timed buffer is"
1313 " only %u bytes long, but claims to have consumed %u"
1314 " bytes. (update reason: \"%s\")",
1315 bufBytes, consumedAlready, logTag);
1316
1317 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1318 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1319 "Bad bookkeeping while updating frames pending. Should have at"
1320 " least %u queued frames, but we think we have only %u. (update"
1321 " reason: \"%s\")",
1322 bufFrames, mFramesPendingInQueue, logTag);
1323
1324 mFramesPendingInQueue -= bufFrames;
1325}
1326
1327status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1328 const sp<IMemory>& buffer, int64_t pts) {
1329
1330 {
1331 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1332 if (!mMediaTimeTransformValid)
1333 return INVALID_OPERATION;
1334 }
1335
1336 Mutex::Autolock _l(mTimedBufferQueueLock);
1337
1338 uint32_t bufFrames = buffer->size() / mFrameSize;
1339 mFramesPendingInQueue += bufFrames;
1340 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1341
1342 return NO_ERROR;
1343}
1344
1345status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1346 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1347
1348 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1349 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1350 target);
1351
1352 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1353 target == TimedAudioTrack::COMMON_TIME)) {
1354 return BAD_VALUE;
1355 }
1356
1357 Mutex::Autolock lock(mMediaTimeTransformLock);
1358 mMediaTimeTransform = xform;
1359 mMediaTimeTransformTarget = target;
1360 mMediaTimeTransformValid = true;
1361
1362 return NO_ERROR;
1363}
1364
1365#define min(a, b) ((a) < (b) ? (a) : (b))
1366
1367// implementation of getNextBuffer for tracks whose buffers have timestamps
1368status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1369 AudioBufferProvider::Buffer* buffer, int64_t pts)
1370{
1371 if (pts == AudioBufferProvider::kInvalidPTS) {
1372 buffer->raw = NULL;
1373 buffer->frameCount = 0;
1374 mTimedAudioOutputOnTime = false;
1375 return INVALID_OPERATION;
1376 }
1377
1378 Mutex::Autolock _l(mTimedBufferQueueLock);
1379
1380 ALOG_ASSERT(!mQueueHeadInFlight,
1381 "getNextBuffer called without releaseBuffer!");
1382
1383 while (true) {
1384
1385 // if we have no timed buffers, then fail
1386 if (mTimedBufferQueue.isEmpty()) {
1387 buffer->raw = NULL;
1388 buffer->frameCount = 0;
1389 return NOT_ENOUGH_DATA;
1390 }
1391
1392 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1393
1394 // calculate the PTS of the head of the timed buffer queue expressed in
1395 // local time
1396 int64_t headLocalPTS;
1397 {
1398 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1399
1400 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1401
1402 if (mMediaTimeTransform.a_to_b_denom == 0) {
1403 // the transform represents a pause, so yield silence
1404 timedYieldSilence_l(buffer->frameCount, buffer);
1405 return NO_ERROR;
1406 }
1407
1408 int64_t transformedPTS;
1409 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1410 &transformedPTS)) {
1411 // the transform failed. this shouldn't happen, but if it does
1412 // then just drop this buffer
1413 ALOGW("timedGetNextBuffer transform failed");
1414 buffer->raw = NULL;
1415 buffer->frameCount = 0;
1416 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1417 return NO_ERROR;
1418 }
1419
1420 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1421 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1422 &headLocalPTS)) {
1423 buffer->raw = NULL;
1424 buffer->frameCount = 0;
1425 return INVALID_OPERATION;
1426 }
1427 } else {
1428 headLocalPTS = transformedPTS;
1429 }
1430 }
1431
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001432 uint32_t sr = sampleRate();
1433
Eric Laurent81784c32012-11-19 14:55:58 -08001434 // adjust the head buffer's PTS to reflect the portion of the head buffer
1435 // that has already been consumed
1436 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001437 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001438
1439 // Calculate the delta in samples between the head of the input buffer
1440 // queue and the start of the next output buffer that will be written.
1441 // If the transformation fails because of over or underflow, it means
1442 // that the sample's position in the output stream is so far out of
1443 // whack that it should just be dropped.
1444 int64_t sampleDelta;
1445 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1446 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1447 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1448 " mix");
1449 continue;
1450 }
1451 if (!mLocalTimeToSampleTransform.doForwardTransform(
1452 (effectivePTS - pts) << 32, &sampleDelta)) {
1453 ALOGV("*** too late during sample rate transform: dropped buffer");
1454 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1455 continue;
1456 }
1457
1458 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1459 " sampleDelta=[%d.%08x]",
1460 head.pts(), head.position(), pts,
1461 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1462 + (sampleDelta >> 32)),
1463 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1464
1465 // if the delta between the ideal placement for the next input sample and
1466 // the current output position is within this threshold, then we will
1467 // concatenate the next input samples to the previous output
1468 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001469 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001470
1471 // if this is the first buffer of audio that we're emitting from this track
1472 // then it should be almost exactly on time.
1473 const int64_t kSampleStartupThreshold = 1LL << 32;
1474
1475 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1476 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1477 // the next input is close enough to being on time, so concatenate it
1478 // with the last output
1479 timedYieldSamples_l(buffer);
1480
1481 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1482 head.position(), buffer->frameCount);
1483 return NO_ERROR;
1484 }
1485
1486 // Looks like our output is not on time. Reset our on timed status.
1487 // Next time we mix samples from our input queue, then should be within
1488 // the StartupThreshold.
1489 mTimedAudioOutputOnTime = false;
1490 if (sampleDelta > 0) {
1491 // the gap between the current output position and the proper start of
1492 // the next input sample is too big, so fill it with silence
1493 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1494
1495 timedYieldSilence_l(framesUntilNextInput, buffer);
1496 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1497 return NO_ERROR;
1498 } else {
1499 // the next input sample is late
1500 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1501 size_t onTimeSamplePosition =
1502 head.position() + lateFrames * mFrameSize;
1503
1504 if (onTimeSamplePosition > head.buffer()->size()) {
1505 // all the remaining samples in the head are too late, so
1506 // drop it and move on
1507 ALOGV("*** too late: dropped buffer");
1508 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1509 continue;
1510 } else {
1511 // skip over the late samples
1512 head.setPosition(onTimeSamplePosition);
1513
1514 // yield the available samples
1515 timedYieldSamples_l(buffer);
1516
1517 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1518 return NO_ERROR;
1519 }
1520 }
1521 }
1522}
1523
1524// Yield samples from the timed buffer queue head up to the given output
1525// buffer's capacity.
1526//
1527// Caller must hold mTimedBufferQueueLock
1528void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1529 AudioBufferProvider::Buffer* buffer) {
1530
1531 const TimedBuffer& head = mTimedBufferQueue[0];
1532
1533 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1534 head.position());
1535
1536 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1537 mFrameSize);
1538 size_t framesRequested = buffer->frameCount;
1539 buffer->frameCount = min(framesLeftInHead, framesRequested);
1540
1541 mQueueHeadInFlight = true;
1542 mTimedAudioOutputOnTime = true;
1543}
1544
1545// Yield samples of silence up to the given output buffer's capacity
1546//
1547// Caller must hold mTimedBufferQueueLock
1548void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1549 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1550
1551 // lazily allocate a buffer filled with silence
1552 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1553 delete [] mTimedSilenceBuffer;
1554 mTimedSilenceBufferSize = numFrames * mFrameSize;
1555 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1556 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1557 }
1558
1559 buffer->raw = mTimedSilenceBuffer;
1560 size_t framesRequested = buffer->frameCount;
1561 buffer->frameCount = min(numFrames, framesRequested);
1562
1563 mTimedAudioOutputOnTime = false;
1564}
1565
1566// AudioBufferProvider interface
1567void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1568 AudioBufferProvider::Buffer* buffer) {
1569
1570 Mutex::Autolock _l(mTimedBufferQueueLock);
1571
1572 // If the buffer which was just released is part of the buffer at the head
1573 // of the queue, be sure to update the amt of the buffer which has been
1574 // consumed. If the buffer being returned is not part of the head of the
1575 // queue, its either because the buffer is part of the silence buffer, or
1576 // because the head of the timed queue was trimmed after the mixer called
1577 // getNextBuffer but before the mixer called releaseBuffer.
1578 if (buffer->raw == mTimedSilenceBuffer) {
1579 ALOG_ASSERT(!mQueueHeadInFlight,
1580 "Queue head in flight during release of silence buffer!");
1581 goto done;
1582 }
1583
1584 ALOG_ASSERT(mQueueHeadInFlight,
1585 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1586 " head in flight.");
1587
1588 if (mTimedBufferQueue.size()) {
1589 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1590
1591 void* start = head.buffer()->pointer();
1592 void* end = reinterpret_cast<void*>(
1593 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1594 + head.buffer()->size());
1595
1596 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1597 "released buffer not within the head of the timed buffer"
1598 " queue; qHead = [%p, %p], released buffer = %p",
1599 start, end, buffer->raw);
1600
1601 head.setPosition(head.position() +
1602 (buffer->frameCount * mFrameSize));
1603 mQueueHeadInFlight = false;
1604
1605 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1606 "Bad bookkeeping during releaseBuffer! Should have at"
1607 " least %u queued frames, but we think we have only %u",
1608 buffer->frameCount, mFramesPendingInQueue);
1609
1610 mFramesPendingInQueue -= buffer->frameCount;
1611
1612 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1613 || mTrimQueueHeadOnRelease) {
1614 trimTimedBufferQueueHead_l("releaseBuffer");
1615 mTrimQueueHeadOnRelease = false;
1616 }
1617 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001618 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001619 " buffers in the timed buffer queue");
1620 }
1621
1622done:
1623 buffer->raw = 0;
1624 buffer->frameCount = 0;
1625}
1626
1627size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1628 Mutex::Autolock _l(mTimedBufferQueueLock);
1629 return mFramesPendingInQueue;
1630}
1631
1632AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1633 : mPTS(0), mPosition(0) {}
1634
1635AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1636 const sp<IMemory>& buffer, int64_t pts)
1637 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1638
1639
1640// ----------------------------------------------------------------------------
1641
1642AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1643 PlaybackThread *playbackThread,
1644 DuplicatingThread *sourceThread,
1645 uint32_t sampleRate,
1646 audio_format_t format,
1647 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001648 size_t frameCount,
1649 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001650 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1651 sampleRate, format, channelMask, frameCount,
1652 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001653 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001654{
1655
1656 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001657 mOutBuffer.frameCount = 0;
1658 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001659 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001660 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001661 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001662 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001663 // since client and server are in the same process,
1664 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001665 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1666 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001667 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001668 mClientProxy->setSendLevel(0.0);
1669 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001670 } else {
1671 ALOGW("Error creating output track on thread %p", playbackThread);
1672 }
1673}
1674
1675AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1676{
1677 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001678 delete mClientProxy;
1679 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001680}
1681
1682status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1683 int triggerSession)
1684{
1685 status_t status = Track::start(event, triggerSession);
1686 if (status != NO_ERROR) {
1687 return status;
1688 }
1689
1690 mActive = true;
1691 mRetryCount = 127;
1692 return status;
1693}
1694
1695void AudioFlinger::PlaybackThread::OutputTrack::stop()
1696{
1697 Track::stop();
1698 clearBufferQueue();
1699 mOutBuffer.frameCount = 0;
1700 mActive = false;
1701}
1702
Andy Hungc25b84a2015-01-14 19:04:10 -08001703bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001704{
1705 Buffer *pInBuffer;
1706 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001707 bool outputBufferFull = false;
1708 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001709 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001710
1711 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1712
1713 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001714 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001715 }
1716
1717 while (waitTimeLeftMs) {
1718 // First write pending buffers, then new data
1719 if (mBufferQueue.size()) {
1720 pInBuffer = mBufferQueue.itemAt(0);
1721 } else {
1722 pInBuffer = &inBuffer;
1723 }
1724
1725 if (pInBuffer->frameCount == 0) {
1726 break;
1727 }
1728
1729 if (mOutBuffer.frameCount == 0) {
1730 mOutBuffer.frameCount = pInBuffer->frameCount;
1731 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001732 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1733 if (status != NO_ERROR) {
1734 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1735 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001736 outputBufferFull = true;
1737 break;
1738 }
1739 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1740 if (waitTimeLeftMs >= waitTimeMs) {
1741 waitTimeLeftMs -= waitTimeMs;
1742 } else {
1743 waitTimeLeftMs = 0;
1744 }
1745 }
1746
1747 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1748 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001749 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001750 Proxy::Buffer buf;
1751 buf.mFrameCount = outFrames;
1752 buf.mRaw = NULL;
1753 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001754 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001755 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001756 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001757 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001758
1759 if (pInBuffer->frameCount == 0) {
1760 if (mBufferQueue.size()) {
1761 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001762 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001763 delete pInBuffer;
1764 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1765 mThread.unsafe_get(), mBufferQueue.size());
1766 } else {
1767 break;
1768 }
1769 }
1770 }
1771
1772 // If we could not write all frames, allocate a buffer and queue it for next time.
1773 if (inBuffer.frameCount) {
1774 sp<ThreadBase> thread = mThread.promote();
1775 if (thread != 0 && !thread->standby()) {
1776 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1777 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001778 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001779 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001780 pInBuffer->raw = pInBuffer->mBuffer;
1781 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001782 mBufferQueue.add(pInBuffer);
1783 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1784 mThread.unsafe_get(), mBufferQueue.size());
1785 } else {
1786 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1787 mThread.unsafe_get(), this);
1788 }
1789 }
1790 }
1791
Andy Hungc25b84a2015-01-14 19:04:10 -08001792 // Calling write() with a 0 length buffer means that no more data will be written:
1793 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1794 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1795 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001796 }
1797
1798 return outputBufferFull;
1799}
1800
1801status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1802 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1803{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001804 ClientProxy::Buffer buf;
1805 buf.mFrameCount = buffer->frameCount;
1806 struct timespec timeout;
1807 timeout.tv_sec = waitTimeMs / 1000;
1808 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1809 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1810 buffer->frameCount = buf.mFrameCount;
1811 buffer->raw = buf.mRaw;
1812 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001813}
1814
Eric Laurent81784c32012-11-19 14:55:58 -08001815void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1816{
1817 size_t size = mBufferQueue.size();
1818
1819 for (size_t i = 0; i < size; i++) {
1820 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001821 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001822 delete pBuffer;
1823 }
1824 mBufferQueue.clear();
1825}
1826
1827
Eric Laurent83b88082014-06-20 18:31:16 -07001828AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001829 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001830 uint32_t sampleRate,
1831 audio_channel_mask_t channelMask,
1832 audio_format_t format,
1833 size_t frameCount,
1834 void *buffer,
1835 IAudioFlinger::track_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001836 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001837 sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001838 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1839 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1840{
1841 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1842 playbackThread->sampleRate();
1843 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1844 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1845
1846 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1847 this, sampleRate,
1848 (int)mPeerTimeout.tv_sec,
1849 (int)(mPeerTimeout.tv_nsec / 1000000));
1850}
1851
1852AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1853{
1854}
1855
1856// AudioBufferProvider interface
1857status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1858 AudioBufferProvider::Buffer* buffer, int64_t pts)
1859{
1860 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1861 Proxy::Buffer buf;
1862 buf.mFrameCount = buffer->frameCount;
1863 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1864 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001865 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001866 if (buf.mFrameCount == 0) {
1867 return WOULD_BLOCK;
1868 }
Eric Laurent83b88082014-06-20 18:31:16 -07001869 status = Track::getNextBuffer(buffer, pts);
1870 return status;
1871}
1872
1873void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1874{
1875 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1876 Proxy::Buffer buf;
1877 buf.mFrameCount = buffer->frameCount;
1878 buf.mRaw = buffer->raw;
1879 mPeerProxy->releaseBuffer(&buf);
1880 TrackBase::releaseBuffer(buffer);
1881}
1882
1883status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1884 const struct timespec *timeOut)
1885{
1886 return mProxy->obtainBuffer(buffer, timeOut);
1887}
1888
1889void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1890{
1891 mProxy->releaseBuffer(buffer);
1892 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1893 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1894 start();
1895 }
1896 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1897}
1898
Eric Laurent81784c32012-11-19 14:55:58 -08001899// ----------------------------------------------------------------------------
1900// Record
1901// ----------------------------------------------------------------------------
1902
1903AudioFlinger::RecordHandle::RecordHandle(
1904 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1905 : BnAudioRecord(),
1906 mRecordTrack(recordTrack)
1907{
1908}
1909
1910AudioFlinger::RecordHandle::~RecordHandle() {
1911 stop_nonvirtual();
1912 mRecordTrack->destroy();
1913}
1914
Eric Laurent81784c32012-11-19 14:55:58 -08001915status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1916 int triggerSession) {
1917 ALOGV("RecordHandle::start()");
1918 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1919}
1920
1921void AudioFlinger::RecordHandle::stop() {
1922 stop_nonvirtual();
1923}
1924
1925void AudioFlinger::RecordHandle::stop_nonvirtual() {
1926 ALOGV("RecordHandle::stop()");
1927 mRecordTrack->stop();
1928}
1929
1930status_t AudioFlinger::RecordHandle::onTransact(
1931 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1932{
1933 return BnAudioRecord::onTransact(code, data, reply, flags);
1934}
1935
1936// ----------------------------------------------------------------------------
1937
Glenn Kasten05997e22014-03-13 15:08:33 -07001938// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001939AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1940 RecordThread *thread,
1941 const sp<Client>& client,
1942 uint32_t sampleRate,
1943 audio_format_t format,
1944 audio_channel_mask_t channelMask,
1945 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001946 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001947 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001948 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001949 IAudioFlinger::track_flags_t flags,
1950 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001951 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001952 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001953 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001954 (type == TYPE_DEFAULT) ?
1955 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1956 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1957 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001958 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001959 mFramesToDrop(0),
1960 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1961 mRecordBufferConverter(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001962{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001963 if (mCblk == NULL) {
1964 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001965 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001966
Andy Hung97a893e2015-03-29 01:03:07 -07001967 mRecordBufferConverter = new RecordBufferConverter(
1968 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1969 channelMask, format, sampleRate);
1970 // Check if the RecordBufferConverter construction was successful.
1971 // If not, don't continue with construction.
1972 //
1973 // NOTE: It would be extremely rare that the record track cannot be created
1974 // for the current device, but a pending or future device change would make
1975 // the record track configuration valid.
1976 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1977 ALOGE("RecordTrack unable to create record buffer converter");
1978 return;
1979 }
1980
Eric Laurent83b88082014-06-20 18:31:16 -07001981 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1982 mFrameSize, !isExternalTrack());
Andy Hung97a893e2015-03-29 01:03:07 -07001983 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001984
1985 if (flags & IAudioFlinger::TRACK_FAST) {
1986 ALOG_ASSERT(thread->mFastTrackAvail);
1987 thread->mFastTrackAvail = false;
1988 }
Eric Laurent81784c32012-11-19 14:55:58 -08001989}
1990
1991AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1992{
1993 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001994 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001995 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001996}
1997
Andy Hung97a893e2015-03-29 01:03:07 -07001998status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1999{
2000 status_t status = TrackBase::initCheck();
2001 if (status == NO_ERROR && mServerProxy == 0) {
2002 status = BAD_VALUE;
2003 }
2004 return status;
2005}
2006
Eric Laurent81784c32012-11-19 14:55:58 -08002007// AudioBufferProvider interface
2008status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002009 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002010{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002011 ServerProxy::Buffer buf;
2012 buf.mFrameCount = buffer->frameCount;
2013 status_t status = mServerProxy->obtainBuffer(&buf);
2014 buffer->frameCount = buf.mFrameCount;
2015 buffer->raw = buf.mRaw;
2016 if (buf.mFrameCount == 0) {
2017 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002018 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002019 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002020 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002021}
2022
2023status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2024 int triggerSession)
2025{
2026 sp<ThreadBase> thread = mThread.promote();
2027 if (thread != 0) {
2028 RecordThread *recordThread = (RecordThread *)thread.get();
2029 return recordThread->start(this, event, triggerSession);
2030 } else {
2031 return BAD_VALUE;
2032 }
2033}
2034
2035void AudioFlinger::RecordThread::RecordTrack::stop()
2036{
2037 sp<ThreadBase> thread = mThread.promote();
2038 if (thread != 0) {
2039 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002040 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07002041 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002042 }
2043 }
2044}
2045
2046void AudioFlinger::RecordThread::RecordTrack::destroy()
2047{
2048 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2049 sp<RecordTrack> keep(this);
2050 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002051 if (isExternalTrack()) {
2052 if (mState == ACTIVE || mState == RESUMING) {
2053 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2054 }
2055 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
2056 }
Eric Laurent81784c32012-11-19 14:55:58 -08002057 sp<ThreadBase> thread = mThread.promote();
2058 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002059 Mutex::Autolock _l(thread->mLock);
2060 RecordThread *recordThread = (RecordThread *) thread.get();
2061 recordThread->destroyTrack_l(this);
2062 }
2063 }
2064}
2065
Eric Laurent9a54bc22013-09-09 09:08:44 -07002066void AudioFlinger::RecordThread::RecordTrack::invalidate()
2067{
2068 // FIXME should use proxy, and needs work
2069 audio_track_cblk_t* cblk = mCblk;
2070 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2071 android_atomic_release_store(0x40000000, &cblk->mFutex);
2072 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002073 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002074}
2075
Eric Laurent81784c32012-11-19 14:55:58 -08002076
2077/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2078{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002079 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002080}
2081
Marco Nelissenb2208842014-02-07 14:00:50 -08002082void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002083{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002084 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08002085 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08002086 (mClient == 0) ? getpid_cached : mClient->pid(),
2087 mFormat,
2088 mChannelMask,
2089 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002090 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002091 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002092 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002093 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002094
Eric Laurent81784c32012-11-19 14:55:58 -08002095}
2096
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002097void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2098{
2099 if (event == mSyncStartEvent) {
2100 ssize_t framesToDrop = 0;
2101 sp<ThreadBase> threadBase = mThread.promote();
2102 if (threadBase != 0) {
2103 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2104 // from audio HAL
2105 framesToDrop = threadBase->mFrameCount * 2;
2106 }
2107 mFramesToDrop = framesToDrop;
2108 }
2109}
2110
2111void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2112{
2113 if (mSyncStartEvent != 0) {
2114 mSyncStartEvent->cancel();
2115 mSyncStartEvent.clear();
2116 }
2117 mFramesToDrop = 0;
2118}
2119
Eric Laurent83b88082014-06-20 18:31:16 -07002120
2121AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2122 uint32_t sampleRate,
2123 audio_channel_mask_t channelMask,
2124 audio_format_t format,
2125 size_t frameCount,
2126 void *buffer,
2127 IAudioFlinger::track_flags_t flags)
2128 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2129 buffer, 0, getuid(), flags, TYPE_PATCH),
2130 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2131{
2132 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2133 recordThread->sampleRate();
2134 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2135 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2136
2137 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2138 this, sampleRate,
2139 (int)mPeerTimeout.tv_sec,
2140 (int)(mPeerTimeout.tv_nsec / 1000000));
2141}
2142
2143AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2144{
2145}
2146
2147// AudioBufferProvider interface
2148status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2149 AudioBufferProvider::Buffer* buffer, int64_t pts)
2150{
2151 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2152 Proxy::Buffer buf;
2153 buf.mFrameCount = buffer->frameCount;
2154 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2155 ALOGV_IF(status != NO_ERROR,
2156 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002157 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002158 if (buf.mFrameCount == 0) {
2159 return WOULD_BLOCK;
2160 }
Eric Laurent83b88082014-06-20 18:31:16 -07002161 status = RecordTrack::getNextBuffer(buffer, pts);
2162 return status;
2163}
2164
2165void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2166{
2167 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2168 Proxy::Buffer buf;
2169 buf.mFrameCount = buffer->frameCount;
2170 buf.mRaw = buffer->raw;
2171 mPeerProxy->releaseBuffer(&buf);
2172 TrackBase::releaseBuffer(buffer);
2173}
2174
2175status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2176 const struct timespec *timeOut)
2177{
2178 return mProxy->obtainBuffer(buffer, timeOut);
2179}
2180
2181void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2182{
2183 mProxy->releaseBuffer(buffer);
2184}
2185
Glenn Kasten63238ef2015-03-02 15:50:29 -08002186} // namespace android