blob: 2dc96f6a7690f26235bb18d132da8d429645bae5 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenad8510a2015-02-17 16:24:07 -080023#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070025#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080026#include <utils/Log.h>
27
28#include <private/media/AudioTrackShared.h>
29
30#include <common_time/cc_helper.h>
31#include <common_time/local_clock.h>
32
33#include "AudioMixer.h"
34#include "AudioFlinger.h"
35#include "ServiceUtilities.h"
36
Glenn Kastenda6ef132013-01-10 12:31:01 -080037#include <media/nbaio/Pipe.h>
38#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080040
Eric Laurent81784c32012-11-19 14:55:58 -080041// ----------------------------------------------------------------------------
42
43// Note: the following macro is used for extremely verbose logging message. In
44// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
45// 0; but one side effect of this is to turn all LOGV's as well. Some messages
46// are so verbose that we want to suppress them even when we have ALOG_ASSERT
47// turned on. Do not uncomment the #def below unless you really know what you
48// are doing and want to see all of the extremely verbose messages.
49//#define VERY_VERY_VERBOSE_LOGGING
50#ifdef VERY_VERY_VERBOSE_LOGGING
51#define ALOGVV ALOGV
52#else
53#define ALOGVV(a...) do { } while(0)
54#endif
55
56namespace android {
57
58// ----------------------------------------------------------------------------
59// TrackBase
60// ----------------------------------------------------------------------------
61
Glenn Kastenda6ef132013-01-10 12:31:01 -080062static volatile int32_t nextTrackId = 55;
63
Eric Laurent81784c32012-11-19 14:55:58 -080064// TrackBase constructor must be called with AudioFlinger::mLock held
65AudioFlinger::ThreadBase::TrackBase::TrackBase(
66 ThreadBase *thread,
67 const sp<Client>& client,
68 uint32_t sampleRate,
69 audio_format_t format,
70 audio_channel_mask_t channelMask,
71 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070072 void *buffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080073 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080074 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070075 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070076 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070077 alloc_type alloc,
78 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080079 : RefBase(),
80 mThread(thread),
81 mClient(client),
82 mCblk(NULL),
83 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080084 mState(IDLE),
85 mSampleRate(sampleRate),
86 mFormat(format),
87 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070088 mChannelCount(isOut ?
89 audio_channel_count_from_out_mask(channelMask) :
90 audio_channel_count_from_in_mask(channelMask)),
Eric Laurent81784c32012-11-19 14:55:58 -080091 mFrameSize(audio_is_linear_pcm(format) ?
92 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
93 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080094 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070095 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080096 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080097 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080098 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070099 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -0700100 mType(type),
101 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800102{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800103 // if the caller is us, trust the specified uid
104 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
105 int newclientUid = IPCThreadState::self()->getCallingUid();
106 if (clientUid != -1 && clientUid != newclientUid) {
107 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
108 }
109 clientUid = newclientUid;
110 }
111 // clientUid contains the uid of the app that is responsible for this track, so we can blame
112 // battery usage on it.
113 mUid = clientUid;
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hungeaa39692017-02-13 18:48:39 -0800116
117 size_t bufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
118 // check overflow when computing bufferSize due to multiplication by mFrameSize.
119 if (bufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
120 || mFrameSize == 0 // format needs to be correct
121 || bufferSize > SIZE_MAX / mFrameSize) {
122 android_errorWriteLog(0x534e4554, "34749571");
123 return;
124 }
125 bufferSize *= mFrameSize;
126
Eric Laurent81784c32012-11-19 14:55:58 -0800127 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700128 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hungeaa39692017-02-13 18:48:39 -0800129 // check overflow when computing allocation size for streaming tracks.
130 if (size > SIZE_MAX - bufferSize) {
131 android_errorWriteLog(0x534e4554, "34749571");
132 return;
133 }
Eric Laurent81784c32012-11-19 14:55:58 -0800134 size += bufferSize;
135 }
136
137 if (client != 0) {
138 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700139 if (mCblkMemory == 0 ||
140 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800141 ALOGE("not enough memory for AudioTrack size=%u", size);
142 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700143 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800144 return;
145 }
146 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800147 // this syntax avoids calling the audio_track_cblk_t constructor twice
148 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800149 // assume mCblk != NULL
150 }
151
152 // construct the shared structure in-place.
153 if (mCblk != NULL) {
154 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700155 switch (alloc) {
156 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700157 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
158 if (roHeap == 0 ||
159 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
160 (mBuffer = mBufferMemory->pointer()) == NULL) {
161 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
162 if (roHeap != 0) {
163 roHeap->dump("buffer");
164 }
165 mCblkMemory.clear();
166 mBufferMemory.clear();
167 return;
168 }
Eric Laurent81784c32012-11-19 14:55:58 -0800169 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700170 } break;
171 case ALLOC_PIPE:
172 mBufferMemory = thread->pipeMemory();
173 // mBuffer is the virtual address as seen from current process (mediaserver),
174 // and should normally be coming from mBufferMemory->pointer().
175 // However in this case the TrackBase does not reference the buffer directly.
176 // It should references the buffer via the pipe.
177 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
178 mBuffer = NULL;
179 break;
180 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700181 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700182 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700183 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
184 memset(mBuffer, 0, bufferSize);
185 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700186 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800187#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700188 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800189#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700190 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700191 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700192 case ALLOC_LOCAL:
193 mBuffer = calloc(1, bufferSize);
194 break;
195 case ALLOC_NONE:
196 mBuffer = buffer;
197 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800198 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199
Glenn Kasten46909e72013-02-26 09:20:22 -0800200#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700202 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800203 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800204 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
205 size_t numCounterOffers = 0;
206 const NBAIO_Format offers[1] = {pipeFormat};
207 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
208 ALOG_ASSERT(index == 0);
209 PipeReader *pipeReader = new PipeReader(*pipe);
210 numCounterOffers = 0;
211 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
212 ALOG_ASSERT(index == 0);
213 mTeeSink = pipe;
214 mTeeSource = pipeReader;
215 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800216 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800217#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800218
Eric Laurent81784c32012-11-19 14:55:58 -0800219 }
220}
221
Eric Laurent83b88082014-06-20 18:31:16 -0700222status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
223{
224 status_t status;
225 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
226 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
227 } else {
228 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
229 }
230 return status;
231}
232
Eric Laurent81784c32012-11-19 14:55:58 -0800233AudioFlinger::ThreadBase::TrackBase::~TrackBase()
234{
Glenn Kasten46909e72013-02-26 09:20:22 -0800235#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800236 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800237#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800238 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
239 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800240 if (mCblk != NULL) {
241 if (mClient == 0) {
242 delete mCblk;
243 } else {
244 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
245 }
246 }
247 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
248 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700249 // Client destructor must run with AudioFlinger client mutex locked
250 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800251 // If the client's reference count drops to zero, the associated destructor
252 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
253 // relying on the automatic clear() at end of scope.
254 mClient.clear();
255 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700256 // flush the binder command buffer
257 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800258}
259
260// AudioBufferProvider interface
261// getNextBuffer() = 0;
262// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
263void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
264{
Glenn Kasten46909e72013-02-26 09:20:22 -0800265#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800266 if (mTeeSink != 0) {
267 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
268 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800269#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800270
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800271 ServerProxy::Buffer buf;
272 buf.mFrameCount = buffer->frameCount;
273 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800274 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800275 buffer->raw = NULL;
276 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800277}
278
Eric Laurent81784c32012-11-19 14:55:58 -0800279status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
280{
281 mSyncEvents.add(event);
282 return NO_ERROR;
283}
284
285// ----------------------------------------------------------------------------
286// Playback
287// ----------------------------------------------------------------------------
288
289AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
290 : BnAudioTrack(),
291 mTrack(track)
292{
293}
294
295AudioFlinger::TrackHandle::~TrackHandle() {
296 // just stop the track on deletion, associated resources
297 // will be freed from the main thread once all pending buffers have
298 // been played. Unless it's not in the active track list, in which
299 // case we free everything now...
300 mTrack->destroy();
301}
302
303sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
304 return mTrack->getCblk();
305}
306
307status_t AudioFlinger::TrackHandle::start() {
308 return mTrack->start();
309}
310
311void AudioFlinger::TrackHandle::stop() {
312 mTrack->stop();
313}
314
315void AudioFlinger::TrackHandle::flush() {
316 mTrack->flush();
317}
318
Eric Laurent81784c32012-11-19 14:55:58 -0800319void AudioFlinger::TrackHandle::pause() {
320 mTrack->pause();
321}
322
323status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
324{
325 return mTrack->attachAuxEffect(EffectId);
326}
327
328status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
329 sp<IMemory>* buffer) {
330 if (!mTrack->isTimedTrack())
331 return INVALID_OPERATION;
332
333 PlaybackThread::TimedTrack* tt =
334 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
335 return tt->allocateTimedBuffer(size, buffer);
336}
337
338status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
339 int64_t pts) {
340 if (!mTrack->isTimedTrack())
341 return INVALID_OPERATION;
342
Glenn Kasten663c2242013-09-24 11:52:37 -0700343 if (buffer == 0 || buffer->pointer() == NULL) {
344 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
345 return BAD_VALUE;
346 }
347
Eric Laurent81784c32012-11-19 14:55:58 -0800348 PlaybackThread::TimedTrack* tt =
349 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
350 return tt->queueTimedBuffer(buffer, pts);
351}
352
353status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
354 const LinearTransform& xform, int target) {
355
356 if (!mTrack->isTimedTrack())
357 return INVALID_OPERATION;
358
359 PlaybackThread::TimedTrack* tt =
360 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
361 return tt->setMediaTimeTransform(
362 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
363}
364
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700365status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
366 return mTrack->setParameters(keyValuePairs);
367}
368
Glenn Kasten53cec222013-08-29 09:01:02 -0700369status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
370{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700371 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700372}
373
Eric Laurent59fe0102013-09-27 18:48:26 -0700374
375void AudioFlinger::TrackHandle::signal()
376{
377 return mTrack->signal();
378}
379
Eric Laurent81784c32012-11-19 14:55:58 -0800380status_t AudioFlinger::TrackHandle::onTransact(
381 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
382{
383 return BnAudioTrack::onTransact(code, data, reply, flags);
384}
385
386// ----------------------------------------------------------------------------
387
388// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
389AudioFlinger::PlaybackThread::Track::Track(
390 PlaybackThread *thread,
391 const sp<Client>& client,
392 audio_stream_type_t streamType,
393 uint32_t sampleRate,
394 audio_format_t format,
395 audio_channel_mask_t channelMask,
396 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700397 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800398 const sp<IMemory>& sharedBuffer,
399 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800400 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700401 IAudioFlinger::track_flags_t flags,
402 track_type type)
403 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
404 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
405 sessionId, uid, flags, true /*isOut*/,
406 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
407 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800408 mFillingUpStatus(FS_INVALID),
409 // mRetryCount initialized later when needed
410 mSharedBuffer(sharedBuffer),
411 mStreamType(streamType),
412 mName(-1), // see note below
413 mMainBuffer(thread->mixBuffer()),
414 mAuxBuffer(NULL),
415 mAuxEffectId(0), mHasVolumeController(false),
416 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800417 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800418 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800419 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800420 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800421 mResumeToStopping(false),
Phil Burk1b420972015-04-22 10:52:21 -0700422 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800423{
Eric Laurent83b88082014-06-20 18:31:16 -0700424 // client == 0 implies sharedBuffer == 0
425 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
426
427 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
428 sharedBuffer->size());
429
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700430 if (mCblk == NULL) {
431 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800432 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700433
434 if (sharedBuffer == 0) {
435 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700436 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700437 } else {
438 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
439 mFrameSize);
440 }
441 mServerProxy = mAudioTrackServerProxy;
442
Glenn Kastenc263ca02014-06-04 20:31:46 -0700443 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700444 if (mName < 0) {
445 ALOGE("no more track names available");
446 return;
447 }
448 // only allocate a fast track index if we were able to allocate a normal track name
449 if (flags & IAudioFlinger::TRACK_FAST) {
450 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
451 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
452 int i = __builtin_ctz(thread->mFastTrackAvailMask);
453 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
454 // FIXME This is too eager. We allocate a fast track index before the
455 // fast track becomes active. Since fast tracks are a scarce resource,
456 // this means we are potentially denying other more important fast tracks from
457 // being created. It would be better to allocate the index dynamically.
458 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700459 thread->mFastTrackAvailMask &= ~(1 << i);
460 }
Eric Laurent81784c32012-11-19 14:55:58 -0800461}
462
463AudioFlinger::PlaybackThread::Track::~Track()
464{
465 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700466
467 // The destructor would clear mSharedBuffer,
468 // but it will not push the decremented reference count,
469 // leaving the client's IMemory dangling indefinitely.
470 // This prevents that leak.
471 if (mSharedBuffer != 0) {
472 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700473 }
Eric Laurent81784c32012-11-19 14:55:58 -0800474}
475
Glenn Kasten03003332013-08-06 15:40:54 -0700476status_t AudioFlinger::PlaybackThread::Track::initCheck() const
477{
478 status_t status = TrackBase::initCheck();
479 if (status == NO_ERROR && mName < 0) {
480 status = NO_MEMORY;
481 }
482 return status;
483}
484
Eric Laurent81784c32012-11-19 14:55:58 -0800485void AudioFlinger::PlaybackThread::Track::destroy()
486{
487 // NOTE: destroyTrack_l() can remove a strong reference to this Track
488 // by removing it from mTracks vector, so there is a risk that this Tracks's
489 // destructor is called. As the destructor needs to lock mLock,
490 // we must acquire a strong reference on this Track before locking mLock
491 // here so that the destructor is called only when exiting this function.
492 // On the other hand, as long as Track::destroy() is only called by
493 // TrackHandle destructor, the TrackHandle still holds a strong ref on
494 // this Track with its member mTrack.
495 sp<Track> keep(this);
496 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700497 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800498 sp<ThreadBase> thread = mThread.promote();
499 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800500 Mutex::Autolock _l(thread->mLock);
501 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700502 wasActive = playbackThread->destroyTrack_l(this);
503 }
504 if (isExternalTrack() && !wasActive) {
Eric Laurente83b55d2014-11-14 10:06:21 -0800505 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800506 }
507 }
508}
509
510/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
511{
Marco Nelissenb2208842014-02-07 14:00:50 -0800512 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700513 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800514}
515
Marco Nelissenb2208842014-02-07 14:00:50 -0800516void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800517{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700518 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800519 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800520 sprintf(buffer, " F %2d", mFastIndex);
521 } else if (mName >= AudioMixer::TRACK0) {
522 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800523 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800524 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800525 }
526 track_state state = mState;
527 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800528 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800529 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800530 } else {
531 switch (state) {
532 case IDLE:
533 stateChar = 'I';
534 break;
535 case STOPPING_1:
536 stateChar = 's';
537 break;
538 case STOPPING_2:
539 stateChar = '5';
540 break;
541 case STOPPED:
542 stateChar = 'S';
543 break;
544 case RESUMING:
545 stateChar = 'R';
546 break;
547 case ACTIVE:
548 stateChar = 'A';
549 break;
550 case PAUSING:
551 stateChar = 'p';
552 break;
553 case PAUSED:
554 stateChar = 'P';
555 break;
556 case FLUSHED:
557 stateChar = 'F';
558 break;
559 default:
560 stateChar = '?';
561 break;
562 }
Eric Laurent81784c32012-11-19 14:55:58 -0800563 }
564 char nowInUnderrun;
565 switch (mObservedUnderruns.mBitFields.mMostRecent) {
566 case UNDERRUN_FULL:
567 nowInUnderrun = ' ';
568 break;
569 case UNDERRUN_PARTIAL:
570 nowInUnderrun = '<';
571 break;
572 case UNDERRUN_EMPTY:
573 nowInUnderrun = '*';
574 break;
575 default:
576 nowInUnderrun = '?';
577 break;
578 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000579 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 +0000580 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800581 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800582 (mClient == 0) ? getpid_cached : mClient->pid(),
583 mStreamType,
584 mFormat,
585 mChannelMask,
586 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800587 mFrameCount,
588 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800589 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800590 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700591 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
592 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700593 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000594 mMainBuffer,
595 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700596 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700597 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800598 nowInUnderrun);
599}
600
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800601uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
602 return mAudioTrackServerProxy->getSampleRate();
603}
604
Eric Laurent81784c32012-11-19 14:55:58 -0800605// AudioBufferProvider interface
606status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800607 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800608{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 ServerProxy::Buffer buf;
610 size_t desiredFrames = buffer->frameCount;
611 buf.mFrameCount = desiredFrames;
612 status_t status = mServerProxy->obtainBuffer(&buf);
613 buffer->frameCount = buf.mFrameCount;
614 buffer->raw = buf.mRaw;
615 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700616 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800617 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800618 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800619}
620
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700621// releaseBuffer() is not overridden
622
623// ExtendedAudioBufferProvider interface
624
Andy Hung27876c02014-09-09 18:07:55 -0700625// framesReady() may return an approximation of the number of frames if called
626// from a different thread than the one calling Proxy->obtainBuffer() and
627// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
628// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800629size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700630 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
631 // Static tracks return zero frames immediately upon stopping (for FastTracks).
632 // The remainder of the buffer is not drained.
633 return 0;
634 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800635 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800636}
637
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700638size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
639{
640 return mAudioTrackServerProxy->framesReleased();
641}
642
Eric Laurent81784c32012-11-19 14:55:58 -0800643// Don't call for fast tracks; the framesReady() could result in priority inversion
644bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800645 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
646 return true;
647 }
648
Eric Laurent16498512014-03-17 17:22:08 -0700649 if (isStopping()) {
650 if (framesReady() > 0) {
651 mFillingUpStatus = FS_FILLED;
652 }
Eric Laurent81784c32012-11-19 14:55:58 -0800653 return true;
654 }
655
656 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700657 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800658 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700659 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800660 return true;
661 }
662 return false;
663}
664
Glenn Kasten0f11b512014-01-31 16:18:54 -0800665status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
666 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800667{
668 status_t status = NO_ERROR;
669 ALOGV("start(%d), calling pid %d session %d",
670 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
671
672 sp<ThreadBase> thread = mThread.promote();
673 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700674 if (isOffloaded()) {
675 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
676 Mutex::Autolock _lth(thread->mLock);
677 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700678 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
679 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700680 invalidate();
681 return PERMISSION_DENIED;
682 }
683 }
684 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800685 track_state state = mState;
686 // here the track could be either new, or restarted
687 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800688
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800689 // initial state-stopping. next state-pausing.
690 // What if resume is called ?
691
692 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800693 if (mResumeToStopping) {
694 // happened we need to resume to STOPPING_1
695 mState = TrackBase::STOPPING_1;
696 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
697 } else {
698 mState = TrackBase::RESUMING;
699 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
700 }
Eric Laurent81784c32012-11-19 14:55:58 -0800701 } else {
702 mState = TrackBase::ACTIVE;
703 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
704 }
705
Eric Laurentbfb1b832013-01-07 09:53:42 -0800706 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700707 if (isFastTrack()) {
708 // refresh fast track underruns on start because that field is never cleared
709 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
710 // after stop.
711 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
712 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800713 status = playbackThread->addTrack_l(this);
714 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800715 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800716 // restore previous state if start was rejected by policy manager
717 if (status == PERMISSION_DENIED) {
718 mState = state;
719 }
720 }
721 // track was already in the active list, not a problem
722 if (status == ALREADY_EXISTS) {
723 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700724 } else {
725 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
726 // It is usually unsafe to access the server proxy from a binder thread.
727 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
728 // isn't looking at this track yet: we still hold the normal mixer thread lock,
729 // and for fast tracks the track is not yet in the fast mixer thread's active set.
730 ServerProxy::Buffer buffer;
731 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700732 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800733 }
734 } else {
735 status = BAD_VALUE;
736 }
737 return status;
738}
739
740void AudioFlinger::PlaybackThread::Track::stop()
741{
742 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
743 sp<ThreadBase> thread = mThread.promote();
744 if (thread != 0) {
745 Mutex::Autolock _l(thread->mLock);
746 track_state state = mState;
747 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
748 // If the track is not active (PAUSED and buffers full), flush buffers
749 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
750 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
751 reset();
752 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700753 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800754 mState = STOPPED;
755 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800756 // For fast tracks prepareTracks_l() will set state to STOPPING_2
757 // presentation is complete
758 // For an offloaded track this starts a drain and state will
759 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800760 mState = STOPPING_1;
761 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700762 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800763 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
764 playbackThread);
765 }
Eric Laurent81784c32012-11-19 14:55:58 -0800766 }
767}
768
769void AudioFlinger::PlaybackThread::Track::pause()
770{
771 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
772 sp<ThreadBase> thread = mThread.promote();
773 if (thread != 0) {
774 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800775 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
776 switch (mState) {
777 case STOPPING_1:
778 case STOPPING_2:
779 if (!isOffloaded()) {
780 /* nothing to do if track is not offloaded */
781 break;
782 }
783
784 // Offloaded track was draining, we need to carry on draining when resumed
785 mResumeToStopping = true;
786 // fall through...
787 case ACTIVE:
788 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800789 mState = PAUSING;
790 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700791 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800792 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800793
Eric Laurentbfb1b832013-01-07 09:53:42 -0800794 default:
795 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800796 }
797 }
798}
799
800void AudioFlinger::PlaybackThread::Track::flush()
801{
802 ALOGV("flush(%d)", mName);
803 sp<ThreadBase> thread = mThread.promote();
804 if (thread != 0) {
805 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800806 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800807
808 if (isOffloaded()) {
809 // If offloaded we allow flush during any state except terminated
810 // and keep the track active to avoid problems if user is seeking
811 // rapidly and underlying hardware has a significant delay handling
812 // a pause
813 if (isTerminated()) {
814 return;
815 }
816
817 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800818 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800819
820 if (mState == STOPPING_1 || mState == STOPPING_2) {
821 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
822 mState = ACTIVE;
823 }
824
825 if (mState == ACTIVE) {
826 ALOGV("flush called in active state, resetting buffer time out retry count");
827 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
828 }
829
Haynes Mathew George7844f672014-01-15 12:32:55 -0800830 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800831 mResumeToStopping = false;
832 } else {
833 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
834 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
835 return;
836 }
837 // No point remaining in PAUSED state after a flush => go to
838 // FLUSHED state
839 mState = FLUSHED;
840 // do not reset the track if it is still in the process of being stopped or paused.
841 // this will be done by prepareTracks_l() when the track is stopped.
842 // prepareTracks_l() will see mState == FLUSHED, then
843 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800844 if (isDirect()) {
845 mFlushHwPending = true;
846 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800847 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
848 reset();
849 }
Eric Laurent81784c32012-11-19 14:55:58 -0800850 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800851 // Prevent flush being lost if the track is flushed and then resumed
852 // before mixer thread can run. This is important when offloading
853 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700854 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800855 }
856}
857
Haynes Mathew George7844f672014-01-15 12:32:55 -0800858// must be called with thread lock held
859void AudioFlinger::PlaybackThread::Track::flushAck()
860{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800861 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800862 return;
863
864 mFlushHwPending = false;
865}
866
Eric Laurent81784c32012-11-19 14:55:58 -0800867void AudioFlinger::PlaybackThread::Track::reset()
868{
869 // Do not reset twice to avoid discarding data written just after a flush and before
870 // the audioflinger thread detects the track is stopped.
871 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800872 // Force underrun condition to avoid false underrun callback until first data is
873 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700874 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800875 mFillingUpStatus = FS_FILLING;
876 mResetDone = true;
877 if (mState == FLUSHED) {
878 mState = IDLE;
879 }
880 }
881}
882
Eric Laurentbfb1b832013-01-07 09:53:42 -0800883status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
884{
885 sp<ThreadBase> thread = mThread.promote();
886 if (thread == 0) {
887 ALOGE("thread is dead");
888 return FAILED_TRANSACTION;
889 } else if ((thread->type() == ThreadBase::DIRECT) ||
890 (thread->type() == ThreadBase::OFFLOAD)) {
891 return thread->setParameters(keyValuePairs);
892 } else {
893 return PERMISSION_DENIED;
894 }
895}
896
Glenn Kasten573d80a2013-08-26 09:36:23 -0700897status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
898{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700899 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
900 if (isFastTrack()) {
901 return INVALID_OPERATION;
902 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700903 sp<ThreadBase> thread = mThread.promote();
904 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700905 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700906 }
Phil Burk6140c792015-03-19 14:30:21 -0700907
Glenn Kasten573d80a2013-08-26 09:36:23 -0700908 Mutex::Autolock _l(thread->mLock);
909 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Phil Burk6140c792015-03-19 14:30:21 -0700910
911 status_t result = INVALID_OPERATION;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700912 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700913 if (!playbackThread->mLatchQValid) {
914 return INVALID_OPERATION;
915 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700916 // FIXME Not accurate under dynamic changes of sample rate and speed.
917 // Do not use track's mSampleRate as it is not current for mixer tracks.
918 uint32_t sampleRate = mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700919 AudioPlaybackRate playbackRate = mAudioTrackServerProxy->getPlaybackRate();
920 uint32_t unpresentedFrames = ((double) playbackThread->mLatchQ.mUnpresentedFrames *
921 sampleRate * playbackRate.mSpeed)/ playbackThread->mSampleRate;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700922 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
923 // for a brand new track to share the same address as a recently destroyed
924 // track, and thus for us to get the frames released of the wrong track.
925 // It is unlikely that we would be able to call getTimestamp() so quickly
926 // right after creating a new track. Nevertheless, the index here should
927 // be changed to something that is unique. Or use a completely different strategy.
928 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
929 uint32_t framesWritten = i >= 0 ?
930 playbackThread->mLatchQ.mFramesReleased[i] :
931 mAudioTrackServerProxy->framesReleased();
Phil Burk1b420972015-04-22 10:52:21 -0700932 if (framesWritten >= unpresentedFrames) {
Phil Burk6140c792015-03-19 14:30:21 -0700933 timestamp.mPosition = framesWritten - unpresentedFrames;
934 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
935 result = NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -0700936 }
Phil Burk6140c792015-03-19 14:30:21 -0700937 } else { // offloaded or direct
938 result = playbackThread->getTimestamp_l(timestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700939 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700940
Phil Burk6140c792015-03-19 14:30:21 -0700941 return result;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700942}
943
Eric Laurent81784c32012-11-19 14:55:58 -0800944status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
945{
946 status_t status = DEAD_OBJECT;
947 sp<ThreadBase> thread = mThread.promote();
948 if (thread != 0) {
949 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
950 sp<AudioFlinger> af = mClient->audioFlinger();
951
952 Mutex::Autolock _l(af->mLock);
953
954 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
955
956 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
957 Mutex::Autolock _dl(playbackThread->mLock);
958 Mutex::Autolock _sl(srcThread->mLock);
959 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
960 if (chain == 0) {
961 return INVALID_OPERATION;
962 }
963
964 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
965 if (effect == 0) {
966 return INVALID_OPERATION;
967 }
968 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700969 status = playbackThread->addEffect_l(effect);
970 if (status != NO_ERROR) {
971 srcThread->addEffect_l(effect);
972 return INVALID_OPERATION;
973 }
Eric Laurent81784c32012-11-19 14:55:58 -0800974 // removeEffect_l() has stopped the effect if it was active so it must be restarted
975 if (effect->state() == EffectModule::ACTIVE ||
976 effect->state() == EffectModule::STOPPING) {
977 effect->start();
978 }
979
980 sp<EffectChain> dstChain = effect->chain().promote();
981 if (dstChain == 0) {
982 srcThread->addEffect_l(effect);
983 return INVALID_OPERATION;
984 }
985 AudioSystem::unregisterEffect(effect->id());
986 AudioSystem::registerEffect(&effect->desc(),
987 srcThread->id(),
988 dstChain->strategy(),
989 AUDIO_SESSION_OUTPUT_MIX,
990 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700991 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800992 }
993 status = playbackThread->attachAuxEffect(this, EffectId);
994 }
995 return status;
996}
997
998void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
999{
1000 mAuxEffectId = EffectId;
1001 mAuxBuffer = buffer;
1002}
1003
1004bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
1005 size_t audioHalFrames)
1006{
1007 // a track is considered presented when the total number of frames written to audio HAL
1008 // corresponds to the number of frames written when presentationComplete() is called for the
1009 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001010 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1011 // to detect when all frames have been played. In this case framesWritten isn't
1012 // useful because it doesn't always reflect whether there is data in the h/w
1013 // buffers, particularly if a track has been paused and resumed during draining
1014 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1015 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001016 if (mPresentationCompleteFrames == 0) {
1017 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1018 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1019 mPresentationCompleteFrames, audioHalFrames);
1020 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001021
1022 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001023 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001024 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001025 return true;
1026 }
1027 return false;
1028}
1029
1030void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1031{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001032 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001033 if (mSyncEvents[i]->type() == type) {
1034 mSyncEvents[i]->trigger();
1035 mSyncEvents.removeAt(i);
1036 i--;
1037 }
1038 }
1039}
1040
1041// implement VolumeBufferProvider interface
1042
Glenn Kastenc56f3422014-03-21 17:53:17 -07001043gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001044{
1045 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1046 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001047 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1048 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1049 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001050 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001051 if (vl > GAIN_FLOAT_UNITY) {
1052 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001053 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001054 if (vr > GAIN_FLOAT_UNITY) {
1055 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001056 }
1057 // now apply the cached master volume and stream type volume;
1058 // this is trusted but lacks any synchronization or barrier so may be stale
1059 float v = mCachedVolume;
1060 vl *= v;
1061 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001062 // re-combine into packed minifloat
1063 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001064 // FIXME look at mute, pause, and stop flags
1065 return vlr;
1066}
1067
1068status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1069{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001070 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001071 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1072 (mState == STOPPED)))) {
1073 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1074 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1075 event->cancel();
1076 return INVALID_OPERATION;
1077 }
1078 (void) TrackBase::setSyncEvent(event);
1079 return NO_ERROR;
1080}
1081
Glenn Kasten5736c352012-12-04 12:12:34 -08001082void AudioFlinger::PlaybackThread::Track::invalidate()
1083{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001084 // FIXME should use proxy, and needs work
1085 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001086 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001087 android_atomic_release_store(0x40000000, &cblk->mFutex);
1088 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001089 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001090 mIsInvalid = true;
1091}
1092
Eric Laurent59fe0102013-09-27 18:48:26 -07001093void AudioFlinger::PlaybackThread::Track::signal()
1094{
1095 sp<ThreadBase> thread = mThread.promote();
1096 if (thread != 0) {
1097 PlaybackThread *t = (PlaybackThread *)thread.get();
1098 Mutex::Autolock _l(t->mLock);
1099 t->broadcast_l();
1100 }
1101}
1102
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001103//To be called with thread lock held
1104bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1105
1106 if (mState == RESUMING)
1107 return true;
1108 /* Resume is pending if track was stopping before pause was called */
1109 if (mState == STOPPING_1 &&
1110 mResumeToStopping)
1111 return true;
1112
1113 return false;
1114}
1115
1116//To be called with thread lock held
1117void AudioFlinger::PlaybackThread::Track::resumeAck() {
1118
1119
1120 if (mState == RESUMING)
1121 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001122
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001123 // Other possibility of pending resume is stopping_1 state
1124 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001125 // drain being called.
1126 if (mState == STOPPING_1) {
1127 mResumeToStopping = false;
1128 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001129}
Eric Laurent81784c32012-11-19 14:55:58 -08001130// ----------------------------------------------------------------------------
1131
1132sp<AudioFlinger::PlaybackThread::TimedTrack>
1133AudioFlinger::PlaybackThread::TimedTrack::create(
1134 PlaybackThread *thread,
1135 const sp<Client>& client,
1136 audio_stream_type_t streamType,
1137 uint32_t sampleRate,
1138 audio_format_t format,
1139 audio_channel_mask_t channelMask,
1140 size_t frameCount,
1141 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001142 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001143 int uid)
1144{
Eric Laurent81784c32012-11-19 14:55:58 -08001145 if (!client->reserveTimedTrack())
1146 return 0;
1147
1148 return new TimedTrack(
1149 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001150 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001151}
1152
1153AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1154 PlaybackThread *thread,
1155 const sp<Client>& client,
1156 audio_stream_type_t streamType,
1157 uint32_t sampleRate,
1158 audio_format_t format,
1159 audio_channel_mask_t channelMask,
1160 size_t frameCount,
1161 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001162 int sessionId,
1163 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001164 : Track(thread, client, streamType, sampleRate, format, channelMask,
Eric Laurent83b88082014-06-20 18:31:16 -07001165 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1166 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001167 mQueueHeadInFlight(false),
1168 mTrimQueueHeadOnRelease(false),
1169 mFramesPendingInQueue(0),
1170 mTimedSilenceBuffer(NULL),
1171 mTimedSilenceBufferSize(0),
1172 mTimedAudioOutputOnTime(false),
1173 mMediaTimeTransformValid(false)
1174{
1175 LocalClock lc;
1176 mLocalTimeFreq = lc.getLocalFreq();
1177
1178 mLocalTimeToSampleTransform.a_zero = 0;
1179 mLocalTimeToSampleTransform.b_zero = 0;
1180 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1181 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1182 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1183 &mLocalTimeToSampleTransform.a_to_b_denom);
1184
1185 mMediaTimeToSampleTransform.a_zero = 0;
1186 mMediaTimeToSampleTransform.b_zero = 0;
1187 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1188 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1189 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1190 &mMediaTimeToSampleTransform.a_to_b_denom);
1191}
1192
1193AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1194 mClient->releaseTimedTrack();
1195 delete [] mTimedSilenceBuffer;
1196}
1197
1198status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1199 size_t size, sp<IMemory>* buffer) {
1200
1201 Mutex::Autolock _l(mTimedBufferQueueLock);
1202
1203 trimTimedBufferQueue_l();
1204
1205 // lazily initialize the shared memory heap for timed buffers
1206 if (mTimedMemoryDealer == NULL) {
1207 const int kTimedBufferHeapSize = 512 << 10;
1208
1209 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1210 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001211 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001212 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001213 }
Eric Laurent81784c32012-11-19 14:55:58 -08001214 }
1215
1216 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001217 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001218 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001219 }
1220
1221 *buffer = newBuffer;
1222 return NO_ERROR;
1223}
1224
1225// caller must hold mTimedBufferQueueLock
1226void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1227 int64_t mediaTimeNow;
1228 {
1229 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1230 if (!mMediaTimeTransformValid)
1231 return;
1232
1233 int64_t targetTimeNow;
1234 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1235 ? mCCHelper.getCommonTime(&targetTimeNow)
1236 : mCCHelper.getLocalTime(&targetTimeNow);
1237
1238 if (OK != res)
1239 return;
1240
1241 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1242 &mediaTimeNow)) {
1243 return;
1244 }
1245 }
1246
1247 size_t trimEnd;
1248 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1249 int64_t bufEnd;
1250
1251 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1252 // We have a next buffer. Just use its PTS as the PTS of the frame
1253 // following the last frame in this buffer. If the stream is sparse
1254 // (ie, there are deliberate gaps left in the stream which should be
1255 // filled with silence by the TimedAudioTrack), then this can result
1256 // in one extra buffer being left un-trimmed when it could have
1257 // been. In general, this is not typical, and we would rather
1258 // optimized away the TS calculation below for the more common case
1259 // where PTSes are contiguous.
1260 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1261 } else {
1262 // We have no next buffer. Compute the PTS of the frame following
1263 // the last frame in this buffer by computing the duration of of
1264 // this frame in media time units and adding it to the PTS of the
1265 // buffer.
1266 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1267 / mFrameSize;
1268
1269 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1270 &bufEnd)) {
1271 ALOGE("Failed to convert frame count of %lld to media time"
1272 " duration" " (scale factor %d/%u) in %s",
1273 frameCount,
1274 mMediaTimeToSampleTransform.a_to_b_numer,
1275 mMediaTimeToSampleTransform.a_to_b_denom,
1276 __PRETTY_FUNCTION__);
1277 break;
1278 }
1279 bufEnd += mTimedBufferQueue[trimEnd].pts();
1280 }
1281
1282 if (bufEnd > mediaTimeNow)
1283 break;
1284
1285 // Is the buffer we want to use in the middle of a mix operation right
1286 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1287 // from the mixer which should be coming back shortly.
1288 if (!trimEnd && mQueueHeadInFlight) {
1289 mTrimQueueHeadOnRelease = true;
1290 }
1291 }
1292
1293 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1294 if (trimStart < trimEnd) {
1295 // Update the bookkeeping for framesReady()
1296 for (size_t i = trimStart; i < trimEnd; ++i) {
1297 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1298 }
1299
1300 // Now actually remove the buffers from the queue.
1301 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1302 }
1303}
1304
1305void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1306 const char* logTag) {
1307 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1308 "%s called (reason \"%s\"), but timed buffer queue has no"
1309 " elements to trim.", __FUNCTION__, logTag);
1310
1311 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1312 mTimedBufferQueue.removeAt(0);
1313}
1314
1315void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1316 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001317 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001318 uint32_t bufBytes = buf.buffer()->size();
1319 uint32_t consumedAlready = buf.position();
1320
1321 ALOG_ASSERT(consumedAlready <= bufBytes,
1322 "Bad bookkeeping while updating frames pending. Timed buffer is"
1323 " only %u bytes long, but claims to have consumed %u"
1324 " bytes. (update reason: \"%s\")",
1325 bufBytes, consumedAlready, logTag);
1326
1327 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1328 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1329 "Bad bookkeeping while updating frames pending. Should have at"
1330 " least %u queued frames, but we think we have only %u. (update"
1331 " reason: \"%s\")",
1332 bufFrames, mFramesPendingInQueue, logTag);
1333
1334 mFramesPendingInQueue -= bufFrames;
1335}
1336
1337status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1338 const sp<IMemory>& buffer, int64_t pts) {
1339
1340 {
1341 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1342 if (!mMediaTimeTransformValid)
1343 return INVALID_OPERATION;
1344 }
1345
1346 Mutex::Autolock _l(mTimedBufferQueueLock);
1347
1348 uint32_t bufFrames = buffer->size() / mFrameSize;
1349 mFramesPendingInQueue += bufFrames;
1350 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1351
1352 return NO_ERROR;
1353}
1354
1355status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1356 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1357
1358 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1359 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1360 target);
1361
1362 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1363 target == TimedAudioTrack::COMMON_TIME)) {
1364 return BAD_VALUE;
1365 }
1366
1367 Mutex::Autolock lock(mMediaTimeTransformLock);
1368 mMediaTimeTransform = xform;
1369 mMediaTimeTransformTarget = target;
1370 mMediaTimeTransformValid = true;
1371
1372 return NO_ERROR;
1373}
1374
1375#define min(a, b) ((a) < (b) ? (a) : (b))
1376
1377// implementation of getNextBuffer for tracks whose buffers have timestamps
1378status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1379 AudioBufferProvider::Buffer* buffer, int64_t pts)
1380{
1381 if (pts == AudioBufferProvider::kInvalidPTS) {
1382 buffer->raw = NULL;
1383 buffer->frameCount = 0;
1384 mTimedAudioOutputOnTime = false;
1385 return INVALID_OPERATION;
1386 }
1387
1388 Mutex::Autolock _l(mTimedBufferQueueLock);
1389
1390 ALOG_ASSERT(!mQueueHeadInFlight,
1391 "getNextBuffer called without releaseBuffer!");
1392
1393 while (true) {
1394
1395 // if we have no timed buffers, then fail
1396 if (mTimedBufferQueue.isEmpty()) {
1397 buffer->raw = NULL;
1398 buffer->frameCount = 0;
1399 return NOT_ENOUGH_DATA;
1400 }
1401
1402 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1403
1404 // calculate the PTS of the head of the timed buffer queue expressed in
1405 // local time
1406 int64_t headLocalPTS;
1407 {
1408 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1409
1410 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1411
1412 if (mMediaTimeTransform.a_to_b_denom == 0) {
1413 // the transform represents a pause, so yield silence
1414 timedYieldSilence_l(buffer->frameCount, buffer);
1415 return NO_ERROR;
1416 }
1417
1418 int64_t transformedPTS;
1419 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1420 &transformedPTS)) {
1421 // the transform failed. this shouldn't happen, but if it does
1422 // then just drop this buffer
1423 ALOGW("timedGetNextBuffer transform failed");
1424 buffer->raw = NULL;
1425 buffer->frameCount = 0;
1426 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1427 return NO_ERROR;
1428 }
1429
1430 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1431 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1432 &headLocalPTS)) {
1433 buffer->raw = NULL;
1434 buffer->frameCount = 0;
1435 return INVALID_OPERATION;
1436 }
1437 } else {
1438 headLocalPTS = transformedPTS;
1439 }
1440 }
1441
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001442 uint32_t sr = sampleRate();
1443
Eric Laurent81784c32012-11-19 14:55:58 -08001444 // adjust the head buffer's PTS to reflect the portion of the head buffer
1445 // that has already been consumed
1446 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001447 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001448
1449 // Calculate the delta in samples between the head of the input buffer
1450 // queue and the start of the next output buffer that will be written.
1451 // If the transformation fails because of over or underflow, it means
1452 // that the sample's position in the output stream is so far out of
1453 // whack that it should just be dropped.
1454 int64_t sampleDelta;
1455 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1456 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1457 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1458 " mix");
1459 continue;
1460 }
1461 if (!mLocalTimeToSampleTransform.doForwardTransform(
1462 (effectivePTS - pts) << 32, &sampleDelta)) {
1463 ALOGV("*** too late during sample rate transform: dropped buffer");
1464 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1465 continue;
1466 }
1467
1468 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1469 " sampleDelta=[%d.%08x]",
1470 head.pts(), head.position(), pts,
1471 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1472 + (sampleDelta >> 32)),
1473 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1474
1475 // if the delta between the ideal placement for the next input sample and
1476 // the current output position is within this threshold, then we will
1477 // concatenate the next input samples to the previous output
1478 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001479 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001480
1481 // if this is the first buffer of audio that we're emitting from this track
1482 // then it should be almost exactly on time.
1483 const int64_t kSampleStartupThreshold = 1LL << 32;
1484
1485 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1486 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1487 // the next input is close enough to being on time, so concatenate it
1488 // with the last output
1489 timedYieldSamples_l(buffer);
1490
1491 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1492 head.position(), buffer->frameCount);
1493 return NO_ERROR;
1494 }
1495
1496 // Looks like our output is not on time. Reset our on timed status.
1497 // Next time we mix samples from our input queue, then should be within
1498 // the StartupThreshold.
1499 mTimedAudioOutputOnTime = false;
1500 if (sampleDelta > 0) {
1501 // the gap between the current output position and the proper start of
1502 // the next input sample is too big, so fill it with silence
1503 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1504
1505 timedYieldSilence_l(framesUntilNextInput, buffer);
1506 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1507 return NO_ERROR;
1508 } else {
1509 // the next input sample is late
1510 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1511 size_t onTimeSamplePosition =
1512 head.position() + lateFrames * mFrameSize;
1513
1514 if (onTimeSamplePosition > head.buffer()->size()) {
1515 // all the remaining samples in the head are too late, so
1516 // drop it and move on
1517 ALOGV("*** too late: dropped buffer");
1518 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1519 continue;
1520 } else {
1521 // skip over the late samples
1522 head.setPosition(onTimeSamplePosition);
1523
1524 // yield the available samples
1525 timedYieldSamples_l(buffer);
1526
1527 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1528 return NO_ERROR;
1529 }
1530 }
1531 }
1532}
1533
1534// Yield samples from the timed buffer queue head up to the given output
1535// buffer's capacity.
1536//
1537// Caller must hold mTimedBufferQueueLock
1538void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1539 AudioBufferProvider::Buffer* buffer) {
1540
1541 const TimedBuffer& head = mTimedBufferQueue[0];
1542
1543 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1544 head.position());
1545
1546 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1547 mFrameSize);
1548 size_t framesRequested = buffer->frameCount;
1549 buffer->frameCount = min(framesLeftInHead, framesRequested);
1550
1551 mQueueHeadInFlight = true;
1552 mTimedAudioOutputOnTime = true;
1553}
1554
1555// Yield samples of silence up to the given output buffer's capacity
1556//
1557// Caller must hold mTimedBufferQueueLock
1558void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1559 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1560
1561 // lazily allocate a buffer filled with silence
1562 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1563 delete [] mTimedSilenceBuffer;
1564 mTimedSilenceBufferSize = numFrames * mFrameSize;
1565 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1566 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1567 }
1568
1569 buffer->raw = mTimedSilenceBuffer;
1570 size_t framesRequested = buffer->frameCount;
1571 buffer->frameCount = min(numFrames, framesRequested);
1572
1573 mTimedAudioOutputOnTime = false;
1574}
1575
1576// AudioBufferProvider interface
1577void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1578 AudioBufferProvider::Buffer* buffer) {
1579
1580 Mutex::Autolock _l(mTimedBufferQueueLock);
1581
1582 // If the buffer which was just released is part of the buffer at the head
1583 // of the queue, be sure to update the amt of the buffer which has been
1584 // consumed. If the buffer being returned is not part of the head of the
1585 // queue, its either because the buffer is part of the silence buffer, or
1586 // because the head of the timed queue was trimmed after the mixer called
1587 // getNextBuffer but before the mixer called releaseBuffer.
1588 if (buffer->raw == mTimedSilenceBuffer) {
1589 ALOG_ASSERT(!mQueueHeadInFlight,
1590 "Queue head in flight during release of silence buffer!");
1591 goto done;
1592 }
1593
1594 ALOG_ASSERT(mQueueHeadInFlight,
1595 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1596 " head in flight.");
1597
1598 if (mTimedBufferQueue.size()) {
1599 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1600
1601 void* start = head.buffer()->pointer();
1602 void* end = reinterpret_cast<void*>(
1603 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1604 + head.buffer()->size());
1605
1606 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1607 "released buffer not within the head of the timed buffer"
1608 " queue; qHead = [%p, %p], released buffer = %p",
1609 start, end, buffer->raw);
1610
1611 head.setPosition(head.position() +
1612 (buffer->frameCount * mFrameSize));
1613 mQueueHeadInFlight = false;
1614
1615 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1616 "Bad bookkeeping during releaseBuffer! Should have at"
1617 " least %u queued frames, but we think we have only %u",
1618 buffer->frameCount, mFramesPendingInQueue);
1619
1620 mFramesPendingInQueue -= buffer->frameCount;
1621
1622 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1623 || mTrimQueueHeadOnRelease) {
1624 trimTimedBufferQueueHead_l("releaseBuffer");
1625 mTrimQueueHeadOnRelease = false;
1626 }
1627 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001628 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001629 " buffers in the timed buffer queue");
1630 }
1631
1632done:
1633 buffer->raw = 0;
1634 buffer->frameCount = 0;
1635}
1636
1637size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1638 Mutex::Autolock _l(mTimedBufferQueueLock);
1639 return mFramesPendingInQueue;
1640}
1641
1642AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1643 : mPTS(0), mPosition(0) {}
1644
1645AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1646 const sp<IMemory>& buffer, int64_t pts)
1647 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1648
1649
1650// ----------------------------------------------------------------------------
1651
1652AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1653 PlaybackThread *playbackThread,
1654 DuplicatingThread *sourceThread,
1655 uint32_t sampleRate,
1656 audio_format_t format,
1657 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001658 size_t frameCount,
1659 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001660 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1661 sampleRate, format, channelMask, frameCount,
1662 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001663 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001664{
1665
1666 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001667 mOutBuffer.frameCount = 0;
1668 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001669 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001670 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001671 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001672 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001673 // since client and server are in the same process,
1674 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001675 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1676 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001677 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001678 mClientProxy->setSendLevel(0.0);
1679 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001680 } else {
1681 ALOGW("Error creating output track on thread %p", playbackThread);
1682 }
1683}
1684
1685AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1686{
1687 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001688 delete mClientProxy;
1689 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001690}
1691
1692status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1693 int triggerSession)
1694{
1695 status_t status = Track::start(event, triggerSession);
1696 if (status != NO_ERROR) {
1697 return status;
1698 }
1699
1700 mActive = true;
1701 mRetryCount = 127;
1702 return status;
1703}
1704
1705void AudioFlinger::PlaybackThread::OutputTrack::stop()
1706{
1707 Track::stop();
1708 clearBufferQueue();
1709 mOutBuffer.frameCount = 0;
1710 mActive = false;
1711}
1712
Andy Hungc25b84a2015-01-14 19:04:10 -08001713bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001714{
1715 Buffer *pInBuffer;
1716 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001717 bool outputBufferFull = false;
1718 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001719 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001720
1721 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1722
1723 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001724 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001725 }
1726
1727 while (waitTimeLeftMs) {
1728 // First write pending buffers, then new data
1729 if (mBufferQueue.size()) {
1730 pInBuffer = mBufferQueue.itemAt(0);
1731 } else {
1732 pInBuffer = &inBuffer;
1733 }
1734
1735 if (pInBuffer->frameCount == 0) {
1736 break;
1737 }
1738
1739 if (mOutBuffer.frameCount == 0) {
1740 mOutBuffer.frameCount = pInBuffer->frameCount;
1741 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001742 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1743 if (status != NO_ERROR) {
1744 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1745 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001746 outputBufferFull = true;
1747 break;
1748 }
1749 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1750 if (waitTimeLeftMs >= waitTimeMs) {
1751 waitTimeLeftMs -= waitTimeMs;
1752 } else {
1753 waitTimeLeftMs = 0;
1754 }
1755 }
1756
1757 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1758 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001759 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001760 Proxy::Buffer buf;
1761 buf.mFrameCount = outFrames;
1762 buf.mRaw = NULL;
1763 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001764 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001765 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001766 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001767 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001768
1769 if (pInBuffer->frameCount == 0) {
1770 if (mBufferQueue.size()) {
1771 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001772 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001773 delete pInBuffer;
1774 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1775 mThread.unsafe_get(), mBufferQueue.size());
1776 } else {
1777 break;
1778 }
1779 }
1780 }
1781
1782 // If we could not write all frames, allocate a buffer and queue it for next time.
1783 if (inBuffer.frameCount) {
1784 sp<ThreadBase> thread = mThread.promote();
1785 if (thread != 0 && !thread->standby()) {
1786 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1787 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001788 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001789 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001790 pInBuffer->raw = pInBuffer->mBuffer;
1791 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001792 mBufferQueue.add(pInBuffer);
1793 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1794 mThread.unsafe_get(), mBufferQueue.size());
1795 } else {
1796 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1797 mThread.unsafe_get(), this);
1798 }
1799 }
1800 }
1801
Andy Hungc25b84a2015-01-14 19:04:10 -08001802 // Calling write() with a 0 length buffer means that no more data will be written:
1803 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1804 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1805 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001806 }
1807
1808 return outputBufferFull;
1809}
1810
1811status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1812 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1813{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001814 ClientProxy::Buffer buf;
1815 buf.mFrameCount = buffer->frameCount;
1816 struct timespec timeout;
1817 timeout.tv_sec = waitTimeMs / 1000;
1818 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1819 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1820 buffer->frameCount = buf.mFrameCount;
1821 buffer->raw = buf.mRaw;
1822 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001823}
1824
Eric Laurent81784c32012-11-19 14:55:58 -08001825void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1826{
1827 size_t size = mBufferQueue.size();
1828
1829 for (size_t i = 0; i < size; i++) {
1830 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001831 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001832 delete pBuffer;
1833 }
1834 mBufferQueue.clear();
1835}
1836
1837
Eric Laurent83b88082014-06-20 18:31:16 -07001838AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001839 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001840 uint32_t sampleRate,
1841 audio_channel_mask_t channelMask,
1842 audio_format_t format,
1843 size_t frameCount,
1844 void *buffer,
1845 IAudioFlinger::track_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001846 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001847 sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001848 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1849 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1850{
1851 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1852 playbackThread->sampleRate();
1853 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1854 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1855
1856 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1857 this, sampleRate,
1858 (int)mPeerTimeout.tv_sec,
1859 (int)(mPeerTimeout.tv_nsec / 1000000));
1860}
1861
1862AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1863{
1864}
1865
1866// AudioBufferProvider interface
1867status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1868 AudioBufferProvider::Buffer* buffer, int64_t pts)
1869{
1870 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1871 Proxy::Buffer buf;
1872 buf.mFrameCount = buffer->frameCount;
1873 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1874 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001875 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001876 if (buf.mFrameCount == 0) {
1877 return WOULD_BLOCK;
1878 }
Eric Laurent83b88082014-06-20 18:31:16 -07001879 status = Track::getNextBuffer(buffer, pts);
1880 return status;
1881}
1882
1883void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1884{
1885 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1886 Proxy::Buffer buf;
1887 buf.mFrameCount = buffer->frameCount;
1888 buf.mRaw = buffer->raw;
1889 mPeerProxy->releaseBuffer(&buf);
1890 TrackBase::releaseBuffer(buffer);
1891}
1892
1893status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1894 const struct timespec *timeOut)
1895{
1896 return mProxy->obtainBuffer(buffer, timeOut);
1897}
1898
1899void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1900{
1901 mProxy->releaseBuffer(buffer);
1902 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1903 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1904 start();
1905 }
1906 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1907}
1908
Eric Laurent81784c32012-11-19 14:55:58 -08001909// ----------------------------------------------------------------------------
1910// Record
1911// ----------------------------------------------------------------------------
1912
1913AudioFlinger::RecordHandle::RecordHandle(
1914 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1915 : BnAudioRecord(),
1916 mRecordTrack(recordTrack)
1917{
1918}
1919
1920AudioFlinger::RecordHandle::~RecordHandle() {
1921 stop_nonvirtual();
1922 mRecordTrack->destroy();
1923}
1924
Eric Laurent81784c32012-11-19 14:55:58 -08001925status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1926 int triggerSession) {
1927 ALOGV("RecordHandle::start()");
1928 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1929}
1930
1931void AudioFlinger::RecordHandle::stop() {
1932 stop_nonvirtual();
1933}
1934
1935void AudioFlinger::RecordHandle::stop_nonvirtual() {
1936 ALOGV("RecordHandle::stop()");
1937 mRecordTrack->stop();
1938}
1939
1940status_t AudioFlinger::RecordHandle::onTransact(
1941 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1942{
1943 return BnAudioRecord::onTransact(code, data, reply, flags);
1944}
1945
1946// ----------------------------------------------------------------------------
1947
Glenn Kasten05997e22014-03-13 15:08:33 -07001948// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001949AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1950 RecordThread *thread,
1951 const sp<Client>& client,
1952 uint32_t sampleRate,
1953 audio_format_t format,
1954 audio_channel_mask_t channelMask,
1955 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001956 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001957 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001958 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001959 IAudioFlinger::track_flags_t flags,
1960 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001961 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001962 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001963 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001964 (type == TYPE_DEFAULT) ?
1965 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1966 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1967 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001968 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001969 mFramesToDrop(0),
1970 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1971 mRecordBufferConverter(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001972{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001973 if (mCblk == NULL) {
1974 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001975 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001976
Andy Hung97a893e2015-03-29 01:03:07 -07001977 mRecordBufferConverter = new RecordBufferConverter(
1978 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1979 channelMask, format, sampleRate);
1980 // Check if the RecordBufferConverter construction was successful.
1981 // If not, don't continue with construction.
1982 //
1983 // NOTE: It would be extremely rare that the record track cannot be created
1984 // for the current device, but a pending or future device change would make
1985 // the record track configuration valid.
1986 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1987 ALOGE("RecordTrack unable to create record buffer converter");
1988 return;
1989 }
1990
Eric Laurent83b88082014-06-20 18:31:16 -07001991 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1992 mFrameSize, !isExternalTrack());
Andy Hung97a893e2015-03-29 01:03:07 -07001993 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001994
1995 if (flags & IAudioFlinger::TRACK_FAST) {
1996 ALOG_ASSERT(thread->mFastTrackAvail);
1997 thread->mFastTrackAvail = false;
1998 }
Eric Laurent81784c32012-11-19 14:55:58 -08001999}
2000
2001AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
2002{
2003 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07002004 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002005 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08002006}
2007
Andy Hung97a893e2015-03-29 01:03:07 -07002008status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
2009{
2010 status_t status = TrackBase::initCheck();
2011 if (status == NO_ERROR && mServerProxy == 0) {
2012 status = BAD_VALUE;
2013 }
2014 return status;
2015}
2016
Eric Laurent81784c32012-11-19 14:55:58 -08002017// AudioBufferProvider interface
2018status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002019 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002020{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002021 ServerProxy::Buffer buf;
2022 buf.mFrameCount = buffer->frameCount;
2023 status_t status = mServerProxy->obtainBuffer(&buf);
2024 buffer->frameCount = buf.mFrameCount;
2025 buffer->raw = buf.mRaw;
2026 if (buf.mFrameCount == 0) {
2027 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002028 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002029 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002030 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002031}
2032
2033status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2034 int triggerSession)
2035{
2036 sp<ThreadBase> thread = mThread.promote();
2037 if (thread != 0) {
2038 RecordThread *recordThread = (RecordThread *)thread.get();
2039 return recordThread->start(this, event, triggerSession);
2040 } else {
2041 return BAD_VALUE;
2042 }
2043}
2044
2045void AudioFlinger::RecordThread::RecordTrack::stop()
2046{
2047 sp<ThreadBase> thread = mThread.promote();
2048 if (thread != 0) {
2049 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002050 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07002051 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002052 }
2053 }
2054}
2055
2056void AudioFlinger::RecordThread::RecordTrack::destroy()
2057{
2058 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2059 sp<RecordTrack> keep(this);
2060 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002061 if (isExternalTrack()) {
2062 if (mState == ACTIVE || mState == RESUMING) {
2063 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2064 }
2065 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
2066 }
Eric Laurent81784c32012-11-19 14:55:58 -08002067 sp<ThreadBase> thread = mThread.promote();
2068 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002069 Mutex::Autolock _l(thread->mLock);
2070 RecordThread *recordThread = (RecordThread *) thread.get();
2071 recordThread->destroyTrack_l(this);
2072 }
2073 }
2074}
2075
Eric Laurent9a54bc22013-09-09 09:08:44 -07002076void AudioFlinger::RecordThread::RecordTrack::invalidate()
2077{
2078 // FIXME should use proxy, and needs work
2079 audio_track_cblk_t* cblk = mCblk;
2080 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2081 android_atomic_release_store(0x40000000, &cblk->mFutex);
2082 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002083 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002084}
2085
Eric Laurent81784c32012-11-19 14:55:58 -08002086
2087/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2088{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002089 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002090}
2091
Marco Nelissenb2208842014-02-07 14:00:50 -08002092void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002093{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002094 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08002095 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08002096 (mClient == 0) ? getpid_cached : mClient->pid(),
2097 mFormat,
2098 mChannelMask,
2099 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002100 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002101 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002102 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002103 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002104
Eric Laurent81784c32012-11-19 14:55:58 -08002105}
2106
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002107void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2108{
2109 if (event == mSyncStartEvent) {
2110 ssize_t framesToDrop = 0;
2111 sp<ThreadBase> threadBase = mThread.promote();
2112 if (threadBase != 0) {
2113 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2114 // from audio HAL
2115 framesToDrop = threadBase->mFrameCount * 2;
2116 }
2117 mFramesToDrop = framesToDrop;
2118 }
2119}
2120
2121void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2122{
2123 if (mSyncStartEvent != 0) {
2124 mSyncStartEvent->cancel();
2125 mSyncStartEvent.clear();
2126 }
2127 mFramesToDrop = 0;
2128}
2129
Eric Laurent83b88082014-06-20 18:31:16 -07002130
2131AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2132 uint32_t sampleRate,
2133 audio_channel_mask_t channelMask,
2134 audio_format_t format,
2135 size_t frameCount,
2136 void *buffer,
2137 IAudioFlinger::track_flags_t flags)
2138 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2139 buffer, 0, getuid(), flags, TYPE_PATCH),
2140 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2141{
2142 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2143 recordThread->sampleRate();
2144 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2145 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2146
2147 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2148 this, sampleRate,
2149 (int)mPeerTimeout.tv_sec,
2150 (int)(mPeerTimeout.tv_nsec / 1000000));
2151}
2152
2153AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2154{
2155}
2156
2157// AudioBufferProvider interface
2158status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2159 AudioBufferProvider::Buffer* buffer, int64_t pts)
2160{
2161 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2162 Proxy::Buffer buf;
2163 buf.mFrameCount = buffer->frameCount;
2164 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2165 ALOGV_IF(status != NO_ERROR,
2166 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002167 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002168 if (buf.mFrameCount == 0) {
2169 return WOULD_BLOCK;
2170 }
Eric Laurent83b88082014-06-20 18:31:16 -07002171 status = RecordTrack::getNextBuffer(buffer, pts);
2172 return status;
2173}
2174
2175void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2176{
2177 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2178 Proxy::Buffer buf;
2179 buf.mFrameCount = buffer->frameCount;
2180 buf.mRaw = buffer->raw;
2181 mPeerProxy->releaseBuffer(&buf);
2182 TrackBase::releaseBuffer(buffer);
2183}
2184
2185status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2186 const struct timespec *timeOut)
2187{
2188 return mProxy->obtainBuffer(buffer, timeOut);
2189}
2190
2191void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2192{
2193 mProxy->releaseBuffer(buffer);
2194}
2195
Glenn Kasten63238ef2015-03-02 15:50:29 -08002196} // namespace android