blob: b5db9fb3afc89d8932334ecd45b9ad7c4dc2c929 [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
Eric Laurent81784c32012-11-19 14:55:58 -080030#include "AudioMixer.h"
31#include "AudioFlinger.h"
32#include "ServiceUtilities.h"
33
Glenn Kastenda6ef132013-01-10 12:31:01 -080034#include <media/nbaio/Pipe.h>
35#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070036#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080037
Eric Laurent81784c32012-11-19 14:55:58 -080038// ----------------------------------------------------------------------------
39
40// Note: the following macro is used for extremely verbose logging message. In
41// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
42// 0; but one side effect of this is to turn all LOGV's as well. Some messages
43// are so verbose that we want to suppress them even when we have ALOG_ASSERT
44// turned on. Do not uncomment the #def below unless you really know what you
45// are doing and want to see all of the extremely verbose messages.
46//#define VERY_VERY_VERBOSE_LOGGING
47#ifdef VERY_VERY_VERBOSE_LOGGING
48#define ALOGVV ALOGV
49#else
50#define ALOGVV(a...) do { } while(0)
51#endif
52
53namespace android {
54
55// ----------------------------------------------------------------------------
56// TrackBase
57// ----------------------------------------------------------------------------
58
Glenn Kastenda6ef132013-01-10 12:31:01 -080059static volatile int32_t nextTrackId = 55;
60
Eric Laurent81784c32012-11-19 14:55:58 -080061// TrackBase constructor must be called with AudioFlinger::mLock held
62AudioFlinger::ThreadBase::TrackBase::TrackBase(
63 ThreadBase *thread,
64 const sp<Client>& client,
65 uint32_t sampleRate,
66 audio_format_t format,
67 audio_channel_mask_t channelMask,
68 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070069 void *buffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080070 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080071 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070072 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070073 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070074 alloc_type alloc,
75 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080076 : RefBase(),
77 mThread(thread),
78 mClient(client),
79 mCblk(NULL),
80 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080081 mState(IDLE),
82 mSampleRate(sampleRate),
83 mFormat(format),
84 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070085 mChannelCount(isOut ?
86 audio_channel_count_from_out_mask(channelMask) :
87 audio_channel_count_from_in_mask(channelMask)),
Eric Laurent81784c32012-11-19 14:55:58 -080088 mFrameSize(audio_is_linear_pcm(format) ?
89 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
90 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080091 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070092 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080093 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080094 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080095 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070096 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -070097 mType(type),
98 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -080099{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700100 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
101 if (!isTrustedCallingUid(callingUid) || clientUid == -1) {
102 ALOGW_IF(clientUid != -1 && clientUid != (int)callingUid,
103 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
104 clientUid = (int)callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800105 }
106 // clientUid contains the uid of the app that is responsible for this track, so we can blame
107 // battery usage on it.
108 mUid = clientUid;
109
Eric Laurent81784c32012-11-19 14:55:58 -0800110 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
111 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700112 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
113 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800114 size += bufferSize;
115 }
116
117 if (client != 0) {
118 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700119 if (mCblkMemory == 0 ||
120 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800121 ALOGE("not enough memory for AudioTrack size=%u", size);
122 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700123 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800124 return;
125 }
126 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800127 // this syntax avoids calling the audio_track_cblk_t constructor twice
128 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800129 // assume mCblk != NULL
130 }
131
132 // construct the shared structure in-place.
133 if (mCblk != NULL) {
134 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700135 switch (alloc) {
136 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700137 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
138 if (roHeap == 0 ||
139 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
140 (mBuffer = mBufferMemory->pointer()) == NULL) {
141 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
142 if (roHeap != 0) {
143 roHeap->dump("buffer");
144 }
145 mCblkMemory.clear();
146 mBufferMemory.clear();
147 return;
148 }
Eric Laurent81784c32012-11-19 14:55:58 -0800149 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700150 } break;
151 case ALLOC_PIPE:
152 mBufferMemory = thread->pipeMemory();
153 // mBuffer is the virtual address as seen from current process (mediaserver),
154 // and should normally be coming from mBufferMemory->pointer().
155 // However in this case the TrackBase does not reference the buffer directly.
156 // It should references the buffer via the pipe.
157 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
158 mBuffer = NULL;
159 break;
160 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700161 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700162 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700163 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
164 memset(mBuffer, 0, bufferSize);
165 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700166 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800167#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700168 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800169#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700170 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700171 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700172 case ALLOC_LOCAL:
173 mBuffer = calloc(1, bufferSize);
174 break;
175 case ALLOC_NONE:
176 mBuffer = buffer;
177 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800178 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800179
Glenn Kasten46909e72013-02-26 09:20:22 -0800180#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800181 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700182 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800183 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800184 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
185 size_t numCounterOffers = 0;
186 const NBAIO_Format offers[1] = {pipeFormat};
187 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
188 ALOG_ASSERT(index == 0);
189 PipeReader *pipeReader = new PipeReader(*pipe);
190 numCounterOffers = 0;
191 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
192 ALOG_ASSERT(index == 0);
193 mTeeSink = pipe;
194 mTeeSource = pipeReader;
195 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800196 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800197#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800198
Eric Laurent81784c32012-11-19 14:55:58 -0800199 }
200}
201
Eric Laurent83b88082014-06-20 18:31:16 -0700202status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
203{
204 status_t status;
205 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
206 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
207 } else {
208 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
209 }
210 return status;
211}
212
Eric Laurent81784c32012-11-19 14:55:58 -0800213AudioFlinger::ThreadBase::TrackBase::~TrackBase()
214{
Glenn Kasten46909e72013-02-26 09:20:22 -0800215#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800216 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800217#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800218 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
219 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800220 if (mCblk != NULL) {
221 if (mClient == 0) {
222 delete mCblk;
223 } else {
224 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
225 }
226 }
227 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
228 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700229 // Client destructor must run with AudioFlinger client mutex locked
230 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800231 // If the client's reference count drops to zero, the associated destructor
232 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
233 // relying on the automatic clear() at end of scope.
234 mClient.clear();
235 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700236 // flush the binder command buffer
237 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800238}
239
240// AudioBufferProvider interface
241// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800242// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800243void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
244{
Glenn Kasten46909e72013-02-26 09:20:22 -0800245#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800246 if (mTeeSink != 0) {
247 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
248 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800249#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800250
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800251 ServerProxy::Buffer buf;
252 buf.mFrameCount = buffer->frameCount;
253 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800254 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800255 buffer->raw = NULL;
256 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800257}
258
Eric Laurent81784c32012-11-19 14:55:58 -0800259status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
260{
261 mSyncEvents.add(event);
262 return NO_ERROR;
263}
264
265// ----------------------------------------------------------------------------
266// Playback
267// ----------------------------------------------------------------------------
268
269AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
270 : BnAudioTrack(),
271 mTrack(track)
272{
273}
274
275AudioFlinger::TrackHandle::~TrackHandle() {
276 // just stop the track on deletion, associated resources
277 // will be freed from the main thread once all pending buffers have
278 // been played. Unless it's not in the active track list, in which
279 // case we free everything now...
280 mTrack->destroy();
281}
282
283sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
284 return mTrack->getCblk();
285}
286
287status_t AudioFlinger::TrackHandle::start() {
288 return mTrack->start();
289}
290
291void AudioFlinger::TrackHandle::stop() {
292 mTrack->stop();
293}
294
295void AudioFlinger::TrackHandle::flush() {
296 mTrack->flush();
297}
298
Eric Laurent81784c32012-11-19 14:55:58 -0800299void AudioFlinger::TrackHandle::pause() {
300 mTrack->pause();
301}
302
303status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
304{
305 return mTrack->attachAuxEffect(EffectId);
306}
307
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700308status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
309 return mTrack->setParameters(keyValuePairs);
310}
311
Glenn Kasten53cec222013-08-29 09:01:02 -0700312status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
313{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700314 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700315}
316
Eric Laurent59fe0102013-09-27 18:48:26 -0700317
318void AudioFlinger::TrackHandle::signal()
319{
320 return mTrack->signal();
321}
322
Eric Laurent81784c32012-11-19 14:55:58 -0800323status_t AudioFlinger::TrackHandle::onTransact(
324 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
325{
326 return BnAudioTrack::onTransact(code, data, reply, flags);
327}
328
329// ----------------------------------------------------------------------------
330
331// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
332AudioFlinger::PlaybackThread::Track::Track(
333 PlaybackThread *thread,
334 const sp<Client>& client,
335 audio_stream_type_t streamType,
336 uint32_t sampleRate,
337 audio_format_t format,
338 audio_channel_mask_t channelMask,
339 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700340 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800341 const sp<IMemory>& sharedBuffer,
342 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800343 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700344 IAudioFlinger::track_flags_t flags,
345 track_type type)
346 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
347 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
348 sessionId, uid, flags, true /*isOut*/,
349 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
350 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800351 mFillingUpStatus(FS_INVALID),
352 // mRetryCount initialized later when needed
353 mSharedBuffer(sharedBuffer),
354 mStreamType(streamType),
355 mName(-1), // see note below
356 mMainBuffer(thread->mixBuffer()),
357 mAuxBuffer(NULL),
358 mAuxEffectId(0), mHasVolumeController(false),
359 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800360 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800361 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800362 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800363 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800364 mResumeToStopping(false),
Phil Burk1b420972015-04-22 10:52:21 -0700365 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800366{
Eric Laurent83b88082014-06-20 18:31:16 -0700367 // client == 0 implies sharedBuffer == 0
368 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
369
370 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
371 sharedBuffer->size());
372
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700373 if (mCblk == NULL) {
374 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800375 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700376
377 if (sharedBuffer == 0) {
378 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700379 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700380 } else {
381 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
382 mFrameSize);
383 }
384 mServerProxy = mAudioTrackServerProxy;
385
Glenn Kastenc263ca02014-06-04 20:31:46 -0700386 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700387 if (mName < 0) {
388 ALOGE("no more track names available");
389 return;
390 }
391 // only allocate a fast track index if we were able to allocate a normal track name
392 if (flags & IAudioFlinger::TRACK_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700393 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
394 // race with setSyncEvent(). However, if we call it, we cannot properly start
395 // static fast tracks (SoundPool) immediately after stopping.
396 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700397 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
398 int i = __builtin_ctz(thread->mFastTrackAvailMask);
399 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
400 // FIXME This is too eager. We allocate a fast track index before the
401 // fast track becomes active. Since fast tracks are a scarce resource,
402 // this means we are potentially denying other more important fast tracks from
403 // being created. It would be better to allocate the index dynamically.
404 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700405 thread->mFastTrackAvailMask &= ~(1 << i);
406 }
Eric Laurent81784c32012-11-19 14:55:58 -0800407}
408
409AudioFlinger::PlaybackThread::Track::~Track()
410{
411 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700412
413 // The destructor would clear mSharedBuffer,
414 // but it will not push the decremented reference count,
415 // leaving the client's IMemory dangling indefinitely.
416 // This prevents that leak.
417 if (mSharedBuffer != 0) {
418 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700419 }
Eric Laurent81784c32012-11-19 14:55:58 -0800420}
421
Glenn Kasten03003332013-08-06 15:40:54 -0700422status_t AudioFlinger::PlaybackThread::Track::initCheck() const
423{
424 status_t status = TrackBase::initCheck();
425 if (status == NO_ERROR && mName < 0) {
426 status = NO_MEMORY;
427 }
428 return status;
429}
430
Eric Laurent81784c32012-11-19 14:55:58 -0800431void AudioFlinger::PlaybackThread::Track::destroy()
432{
433 // NOTE: destroyTrack_l() can remove a strong reference to this Track
434 // by removing it from mTracks vector, so there is a risk that this Tracks's
435 // destructor is called. As the destructor needs to lock mLock,
436 // we must acquire a strong reference on this Track before locking mLock
437 // here so that the destructor is called only when exiting this function.
438 // On the other hand, as long as Track::destroy() is only called by
439 // TrackHandle destructor, the TrackHandle still holds a strong ref on
440 // this Track with its member mTrack.
441 sp<Track> keep(this);
442 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700443 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800444 sp<ThreadBase> thread = mThread.promote();
445 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800446 Mutex::Autolock _l(thread->mLock);
447 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700448 wasActive = playbackThread->destroyTrack_l(this);
449 }
450 if (isExternalTrack() && !wasActive) {
Eric Laurente83b55d2014-11-14 10:06:21 -0800451 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800452 }
453 }
454}
455
456/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
457{
Marco Nelissenb2208842014-02-07 14:00:50 -0800458 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700459 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800460}
461
Marco Nelissenb2208842014-02-07 14:00:50 -0800462void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800463{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700464 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800465 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800466 sprintf(buffer, " F %2d", mFastIndex);
467 } else if (mName >= AudioMixer::TRACK0) {
468 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800469 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800470 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800471 }
472 track_state state = mState;
473 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800474 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800475 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800476 } else {
477 switch (state) {
478 case IDLE:
479 stateChar = 'I';
480 break;
481 case STOPPING_1:
482 stateChar = 's';
483 break;
484 case STOPPING_2:
485 stateChar = '5';
486 break;
487 case STOPPED:
488 stateChar = 'S';
489 break;
490 case RESUMING:
491 stateChar = 'R';
492 break;
493 case ACTIVE:
494 stateChar = 'A';
495 break;
496 case PAUSING:
497 stateChar = 'p';
498 break;
499 case PAUSED:
500 stateChar = 'P';
501 break;
502 case FLUSHED:
503 stateChar = 'F';
504 break;
505 default:
506 stateChar = '?';
507 break;
508 }
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
510 char nowInUnderrun;
511 switch (mObservedUnderruns.mBitFields.mMostRecent) {
512 case UNDERRUN_FULL:
513 nowInUnderrun = ' ';
514 break;
515 case UNDERRUN_PARTIAL:
516 nowInUnderrun = '<';
517 break;
518 case UNDERRUN_EMPTY:
519 nowInUnderrun = '*';
520 break;
521 default:
522 nowInUnderrun = '?';
523 break;
524 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000525 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 +0000526 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800527 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800528 (mClient == 0) ? getpid_cached : mClient->pid(),
529 mStreamType,
530 mFormat,
531 mChannelMask,
532 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800533 mFrameCount,
534 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800535 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800536 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700537 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
538 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700539 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000540 mMainBuffer,
541 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700542 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700543 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800544 nowInUnderrun);
545}
546
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800547uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
548 return mAudioTrackServerProxy->getSampleRate();
549}
550
Eric Laurent81784c32012-11-19 14:55:58 -0800551// AudioBufferProvider interface
552status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800553 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800554{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800555 ServerProxy::Buffer buf;
556 size_t desiredFrames = buffer->frameCount;
557 buf.mFrameCount = desiredFrames;
558 status_t status = mServerProxy->obtainBuffer(&buf);
559 buffer->frameCount = buf.mFrameCount;
560 buffer->raw = buf.mRaw;
561 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700562 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800563 } else {
564 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800565 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800566
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800568}
569
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700570// releaseBuffer() is not overridden
571
572// ExtendedAudioBufferProvider interface
573
Andy Hung27876c02014-09-09 18:07:55 -0700574// framesReady() may return an approximation of the number of frames if called
575// from a different thread than the one calling Proxy->obtainBuffer() and
576// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
577// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800578size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700579 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
580 // Static tracks return zero frames immediately upon stopping (for FastTracks).
581 // The remainder of the buffer is not drained.
582 return 0;
583 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800584 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800585}
586
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700587size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
588{
589 return mAudioTrackServerProxy->framesReleased();
590}
591
Andy Hungb3a486f2015-08-04 15:17:58 -0700592void AudioFlinger::PlaybackThread::Track::onTimestamp(const AudioTimestamp &timestamp)
593{
594 mAudioTrackServerProxy->setTimestamp(timestamp);
595}
596
Eric Laurent81784c32012-11-19 14:55:58 -0800597// Don't call for fast tracks; the framesReady() could result in priority inversion
598bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800599 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
600 return true;
601 }
602
Eric Laurent16498512014-03-17 17:22:08 -0700603 if (isStopping()) {
604 if (framesReady() > 0) {
605 mFillingUpStatus = FS_FILLED;
606 }
Eric Laurent81784c32012-11-19 14:55:58 -0800607 return true;
608 }
609
610 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700611 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800612 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700613 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800614 return true;
615 }
616 return false;
617}
618
Glenn Kasten0f11b512014-01-31 16:18:54 -0800619status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
620 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800621{
622 status_t status = NO_ERROR;
623 ALOGV("start(%d), calling pid %d session %d",
624 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
625
626 sp<ThreadBase> thread = mThread.promote();
627 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700628 if (isOffloaded()) {
629 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
630 Mutex::Autolock _lth(thread->mLock);
631 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700632 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
633 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700634 invalidate();
635 return PERMISSION_DENIED;
636 }
637 }
638 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800639 track_state state = mState;
640 // here the track could be either new, or restarted
641 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800642
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800643 // initial state-stopping. next state-pausing.
644 // What if resume is called ?
645
646 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800647 if (mResumeToStopping) {
648 // happened we need to resume to STOPPING_1
649 mState = TrackBase::STOPPING_1;
650 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
651 } else {
652 mState = TrackBase::RESUMING;
653 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
654 }
Eric Laurent81784c32012-11-19 14:55:58 -0800655 } else {
656 mState = TrackBase::ACTIVE;
657 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
658 }
659
Eric Laurentbfb1b832013-01-07 09:53:42 -0800660 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700661 if (isFastTrack()) {
662 // refresh fast track underruns on start because that field is never cleared
663 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
664 // after stop.
665 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
666 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800667 status = playbackThread->addTrack_l(this);
668 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800669 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800670 // restore previous state if start was rejected by policy manager
671 if (status == PERMISSION_DENIED) {
672 mState = state;
673 }
674 }
675 // track was already in the active list, not a problem
676 if (status == ALREADY_EXISTS) {
677 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700678 } else {
679 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
680 // It is usually unsafe to access the server proxy from a binder thread.
681 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
682 // isn't looking at this track yet: we still hold the normal mixer thread lock,
683 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700684 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700685 ServerProxy::Buffer buffer;
686 buffer.mFrameCount = 1;
687 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800688 }
689 } else {
690 status = BAD_VALUE;
691 }
692 return status;
693}
694
695void AudioFlinger::PlaybackThread::Track::stop()
696{
697 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
698 sp<ThreadBase> thread = mThread.promote();
699 if (thread != 0) {
700 Mutex::Autolock _l(thread->mLock);
701 track_state state = mState;
702 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
703 // If the track is not active (PAUSED and buffers full), flush buffers
704 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
705 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
706 reset();
707 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700708 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800709 mState = STOPPED;
710 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800711 // For fast tracks prepareTracks_l() will set state to STOPPING_2
712 // presentation is complete
713 // For an offloaded track this starts a drain and state will
714 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800715 mState = STOPPING_1;
716 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700717 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800718 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
719 playbackThread);
720 }
Eric Laurent81784c32012-11-19 14:55:58 -0800721 }
722}
723
724void AudioFlinger::PlaybackThread::Track::pause()
725{
726 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
727 sp<ThreadBase> thread = mThread.promote();
728 if (thread != 0) {
729 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800730 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
731 switch (mState) {
732 case STOPPING_1:
733 case STOPPING_2:
734 if (!isOffloaded()) {
735 /* nothing to do if track is not offloaded */
736 break;
737 }
738
739 // Offloaded track was draining, we need to carry on draining when resumed
740 mResumeToStopping = true;
741 // fall through...
742 case ACTIVE:
743 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800744 mState = PAUSING;
745 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700746 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800747 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800748
Eric Laurentbfb1b832013-01-07 09:53:42 -0800749 default:
750 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800751 }
752 }
753}
754
755void AudioFlinger::PlaybackThread::Track::flush()
756{
757 ALOGV("flush(%d)", mName);
758 sp<ThreadBase> thread = mThread.promote();
759 if (thread != 0) {
760 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800761 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800762
763 if (isOffloaded()) {
764 // If offloaded we allow flush during any state except terminated
765 // and keep the track active to avoid problems if user is seeking
766 // rapidly and underlying hardware has a significant delay handling
767 // a pause
768 if (isTerminated()) {
769 return;
770 }
771
772 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800773 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800774
775 if (mState == STOPPING_1 || mState == STOPPING_2) {
776 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
777 mState = ACTIVE;
778 }
779
780 if (mState == ACTIVE) {
781 ALOGV("flush called in active state, resetting buffer time out retry count");
782 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
783 }
784
Haynes Mathew George7844f672014-01-15 12:32:55 -0800785 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800786 mResumeToStopping = false;
787 } else {
788 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
789 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
790 return;
791 }
792 // No point remaining in PAUSED state after a flush => go to
793 // FLUSHED state
794 mState = FLUSHED;
795 // do not reset the track if it is still in the process of being stopped or paused.
796 // this will be done by prepareTracks_l() when the track is stopped.
797 // prepareTracks_l() will see mState == FLUSHED, then
798 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800799 if (isDirect()) {
800 mFlushHwPending = true;
801 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800802 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
803 reset();
804 }
Eric Laurent81784c32012-11-19 14:55:58 -0800805 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800806 // Prevent flush being lost if the track is flushed and then resumed
807 // before mixer thread can run. This is important when offloading
808 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700809 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800810 }
811}
812
Haynes Mathew George7844f672014-01-15 12:32:55 -0800813// must be called with thread lock held
814void AudioFlinger::PlaybackThread::Track::flushAck()
815{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800816 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800817 return;
818
819 mFlushHwPending = false;
820}
821
Eric Laurent81784c32012-11-19 14:55:58 -0800822void AudioFlinger::PlaybackThread::Track::reset()
823{
824 // Do not reset twice to avoid discarding data written just after a flush and before
825 // the audioflinger thread detects the track is stopped.
826 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800827 // Force underrun condition to avoid false underrun callback until first data is
828 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700829 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800830 mFillingUpStatus = FS_FILLING;
831 mResetDone = true;
832 if (mState == FLUSHED) {
833 mState = IDLE;
834 }
835 }
836}
837
Eric Laurentbfb1b832013-01-07 09:53:42 -0800838status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
839{
840 sp<ThreadBase> thread = mThread.promote();
841 if (thread == 0) {
842 ALOGE("thread is dead");
843 return FAILED_TRANSACTION;
844 } else if ((thread->type() == ThreadBase::DIRECT) ||
845 (thread->type() == ThreadBase::OFFLOAD)) {
846 return thread->setParameters(keyValuePairs);
847 } else {
848 return PERMISSION_DENIED;
849 }
850}
851
Glenn Kasten573d80a2013-08-26 09:36:23 -0700852status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
853{
Andy Hungb3a486f2015-08-04 15:17:58 -0700854 // FastTrack timestamps are read through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700855 if (isFastTrack()) {
856 return INVALID_OPERATION;
857 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700858 sp<ThreadBase> thread = mThread.promote();
859 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700860 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700861 }
Phil Burk6140c792015-03-19 14:30:21 -0700862
Glenn Kasten573d80a2013-08-26 09:36:23 -0700863 Mutex::Autolock _l(thread->mLock);
864 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Phil Burk6140c792015-03-19 14:30:21 -0700865
866 status_t result = INVALID_OPERATION;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700867 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700868 if (!playbackThread->mLatchQValid) {
869 return INVALID_OPERATION;
870 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700871 // FIXME Not accurate under dynamic changes of sample rate and speed.
872 // Do not use track's mSampleRate as it is not current for mixer tracks.
873 uint32_t sampleRate = mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700874 AudioPlaybackRate playbackRate = mAudioTrackServerProxy->getPlaybackRate();
875 uint32_t unpresentedFrames = ((double) playbackThread->mLatchQ.mUnpresentedFrames *
876 sampleRate * playbackRate.mSpeed)/ playbackThread->mSampleRate;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700877 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
878 // for a brand new track to share the same address as a recently destroyed
879 // track, and thus for us to get the frames released of the wrong track.
880 // It is unlikely that we would be able to call getTimestamp() so quickly
881 // right after creating a new track. Nevertheless, the index here should
882 // be changed to something that is unique. Or use a completely different strategy.
883 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
884 uint32_t framesWritten = i >= 0 ?
885 playbackThread->mLatchQ.mFramesReleased[i] :
886 mAudioTrackServerProxy->framesReleased();
Phil Burk1b420972015-04-22 10:52:21 -0700887 if (framesWritten >= unpresentedFrames) {
Phil Burk6140c792015-03-19 14:30:21 -0700888 timestamp.mPosition = framesWritten - unpresentedFrames;
889 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
890 result = NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -0700891 }
Phil Burk6140c792015-03-19 14:30:21 -0700892 } else { // offloaded or direct
893 result = playbackThread->getTimestamp_l(timestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700894 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700895
Phil Burk6140c792015-03-19 14:30:21 -0700896 return result;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700897}
898
Eric Laurent81784c32012-11-19 14:55:58 -0800899status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
900{
901 status_t status = DEAD_OBJECT;
902 sp<ThreadBase> thread = mThread.promote();
903 if (thread != 0) {
904 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
905 sp<AudioFlinger> af = mClient->audioFlinger();
906
907 Mutex::Autolock _l(af->mLock);
908
909 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
910
911 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
912 Mutex::Autolock _dl(playbackThread->mLock);
913 Mutex::Autolock _sl(srcThread->mLock);
914 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
915 if (chain == 0) {
916 return INVALID_OPERATION;
917 }
918
919 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
920 if (effect == 0) {
921 return INVALID_OPERATION;
922 }
923 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700924 status = playbackThread->addEffect_l(effect);
925 if (status != NO_ERROR) {
926 srcThread->addEffect_l(effect);
927 return INVALID_OPERATION;
928 }
Eric Laurent81784c32012-11-19 14:55:58 -0800929 // removeEffect_l() has stopped the effect if it was active so it must be restarted
930 if (effect->state() == EffectModule::ACTIVE ||
931 effect->state() == EffectModule::STOPPING) {
932 effect->start();
933 }
934
935 sp<EffectChain> dstChain = effect->chain().promote();
936 if (dstChain == 0) {
937 srcThread->addEffect_l(effect);
938 return INVALID_OPERATION;
939 }
940 AudioSystem::unregisterEffect(effect->id());
941 AudioSystem::registerEffect(&effect->desc(),
942 srcThread->id(),
943 dstChain->strategy(),
944 AUDIO_SESSION_OUTPUT_MIX,
945 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700946 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800947 }
948 status = playbackThread->attachAuxEffect(this, EffectId);
949 }
950 return status;
951}
952
953void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
954{
955 mAuxEffectId = EffectId;
956 mAuxBuffer = buffer;
957}
958
959bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
960 size_t audioHalFrames)
961{
962 // a track is considered presented when the total number of frames written to audio HAL
963 // corresponds to the number of frames written when presentationComplete() is called for the
964 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800965 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
966 // to detect when all frames have been played. In this case framesWritten isn't
967 // useful because it doesn't always reflect whether there is data in the h/w
968 // buffers, particularly if a track has been paused and resumed during draining
969 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
970 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800971 if (mPresentationCompleteFrames == 0) {
972 mPresentationCompleteFrames = framesWritten + audioHalFrames;
973 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
974 mPresentationCompleteFrames, audioHalFrames);
975 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800976
977 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800978 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800979 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800980 return true;
981 }
982 return false;
983}
984
985void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
986{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700987 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800988 if (mSyncEvents[i]->type() == type) {
989 mSyncEvents[i]->trigger();
990 mSyncEvents.removeAt(i);
991 i--;
992 }
993 }
994}
995
996// implement VolumeBufferProvider interface
997
Glenn Kastenc56f3422014-03-21 17:53:17 -0700998gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -0800999{
1000 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1001 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001002 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1003 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1004 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001005 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001006 if (vl > GAIN_FLOAT_UNITY) {
1007 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001008 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001009 if (vr > GAIN_FLOAT_UNITY) {
1010 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001011 }
1012 // now apply the cached master volume and stream type volume;
1013 // this is trusted but lacks any synchronization or barrier so may be stale
1014 float v = mCachedVolume;
1015 vl *= v;
1016 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001017 // re-combine into packed minifloat
1018 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001019 // FIXME look at mute, pause, and stop flags
1020 return vlr;
1021}
1022
1023status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1024{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001025 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001026 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1027 (mState == STOPPED)))) {
1028 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1029 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1030 event->cancel();
1031 return INVALID_OPERATION;
1032 }
1033 (void) TrackBase::setSyncEvent(event);
1034 return NO_ERROR;
1035}
1036
Glenn Kasten5736c352012-12-04 12:12:34 -08001037void AudioFlinger::PlaybackThread::Track::invalidate()
1038{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001039 // FIXME should use proxy, and needs work
1040 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001041 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001042 android_atomic_release_store(0x40000000, &cblk->mFutex);
1043 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001044 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001045 mIsInvalid = true;
1046}
1047
Eric Laurent59fe0102013-09-27 18:48:26 -07001048void AudioFlinger::PlaybackThread::Track::signal()
1049{
1050 sp<ThreadBase> thread = mThread.promote();
1051 if (thread != 0) {
1052 PlaybackThread *t = (PlaybackThread *)thread.get();
1053 Mutex::Autolock _l(t->mLock);
1054 t->broadcast_l();
1055 }
1056}
1057
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001058//To be called with thread lock held
1059bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1060
1061 if (mState == RESUMING)
1062 return true;
1063 /* Resume is pending if track was stopping before pause was called */
1064 if (mState == STOPPING_1 &&
1065 mResumeToStopping)
1066 return true;
1067
1068 return false;
1069}
1070
1071//To be called with thread lock held
1072void AudioFlinger::PlaybackThread::Track::resumeAck() {
1073
1074
1075 if (mState == RESUMING)
1076 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001077
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001078 // Other possibility of pending resume is stopping_1 state
1079 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001080 // drain being called.
1081 if (mState == STOPPING_1) {
1082 mResumeToStopping = false;
1083 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001084}
Eric Laurent81784c32012-11-19 14:55:58 -08001085// ----------------------------------------------------------------------------
1086
Eric Laurent81784c32012-11-19 14:55:58 -08001087AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1088 PlaybackThread *playbackThread,
1089 DuplicatingThread *sourceThread,
1090 uint32_t sampleRate,
1091 audio_format_t format,
1092 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001093 size_t frameCount,
1094 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001095 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1096 sampleRate, format, channelMask, frameCount,
1097 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001098 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001099{
1100
1101 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001102 mOutBuffer.frameCount = 0;
1103 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001104 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001105 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001106 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001107 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001108 // since client and server are in the same process,
1109 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001110 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1111 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001112 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001113 mClientProxy->setSendLevel(0.0);
1114 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001115 } else {
1116 ALOGW("Error creating output track on thread %p", playbackThread);
1117 }
1118}
1119
1120AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1121{
1122 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001123 delete mClientProxy;
1124 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001125}
1126
1127status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1128 int triggerSession)
1129{
1130 status_t status = Track::start(event, triggerSession);
1131 if (status != NO_ERROR) {
1132 return status;
1133 }
1134
1135 mActive = true;
1136 mRetryCount = 127;
1137 return status;
1138}
1139
1140void AudioFlinger::PlaybackThread::OutputTrack::stop()
1141{
1142 Track::stop();
1143 clearBufferQueue();
1144 mOutBuffer.frameCount = 0;
1145 mActive = false;
1146}
1147
Andy Hungc25b84a2015-01-14 19:04:10 -08001148bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001149{
1150 Buffer *pInBuffer;
1151 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001152 bool outputBufferFull = false;
1153 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001154 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001155
1156 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1157
1158 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001159 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001160 }
1161
1162 while (waitTimeLeftMs) {
1163 // First write pending buffers, then new data
1164 if (mBufferQueue.size()) {
1165 pInBuffer = mBufferQueue.itemAt(0);
1166 } else {
1167 pInBuffer = &inBuffer;
1168 }
1169
1170 if (pInBuffer->frameCount == 0) {
1171 break;
1172 }
1173
1174 if (mOutBuffer.frameCount == 0) {
1175 mOutBuffer.frameCount = pInBuffer->frameCount;
1176 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001177 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1178 if (status != NO_ERROR) {
1179 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1180 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001181 outputBufferFull = true;
1182 break;
1183 }
1184 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1185 if (waitTimeLeftMs >= waitTimeMs) {
1186 waitTimeLeftMs -= waitTimeMs;
1187 } else {
1188 waitTimeLeftMs = 0;
1189 }
1190 }
1191
1192 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1193 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001194 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001195 Proxy::Buffer buf;
1196 buf.mFrameCount = outFrames;
1197 buf.mRaw = NULL;
1198 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001199 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001200 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001201 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001202 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001203
1204 if (pInBuffer->frameCount == 0) {
1205 if (mBufferQueue.size()) {
1206 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001207 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001208 delete pInBuffer;
1209 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1210 mThread.unsafe_get(), mBufferQueue.size());
1211 } else {
1212 break;
1213 }
1214 }
1215 }
1216
1217 // If we could not write all frames, allocate a buffer and queue it for next time.
1218 if (inBuffer.frameCount) {
1219 sp<ThreadBase> thread = mThread.promote();
1220 if (thread != 0 && !thread->standby()) {
1221 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1222 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001223 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001224 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001225 pInBuffer->raw = pInBuffer->mBuffer;
1226 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001227 mBufferQueue.add(pInBuffer);
1228 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1229 mThread.unsafe_get(), mBufferQueue.size());
1230 } else {
1231 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1232 mThread.unsafe_get(), this);
1233 }
1234 }
1235 }
1236
Andy Hungc25b84a2015-01-14 19:04:10 -08001237 // Calling write() with a 0 length buffer means that no more data will be written:
1238 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1239 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1240 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001241 }
1242
1243 return outputBufferFull;
1244}
1245
1246status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1247 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1248{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 ClientProxy::Buffer buf;
1250 buf.mFrameCount = buffer->frameCount;
1251 struct timespec timeout;
1252 timeout.tv_sec = waitTimeMs / 1000;
1253 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1254 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1255 buffer->frameCount = buf.mFrameCount;
1256 buffer->raw = buf.mRaw;
1257 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001258}
1259
Eric Laurent81784c32012-11-19 14:55:58 -08001260void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1261{
1262 size_t size = mBufferQueue.size();
1263
1264 for (size_t i = 0; i < size; i++) {
1265 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001266 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001267 delete pBuffer;
1268 }
1269 mBufferQueue.clear();
1270}
1271
1272
Eric Laurent83b88082014-06-20 18:31:16 -07001273AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001274 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001275 uint32_t sampleRate,
1276 audio_channel_mask_t channelMask,
1277 audio_format_t format,
1278 size_t frameCount,
1279 void *buffer,
1280 IAudioFlinger::track_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001281 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001282 sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001283 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1284 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1285{
1286 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1287 playbackThread->sampleRate();
1288 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1289 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1290
1291 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1292 this, sampleRate,
1293 (int)mPeerTimeout.tv_sec,
1294 (int)(mPeerTimeout.tv_nsec / 1000000));
1295}
1296
1297AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1298{
1299}
1300
1301// AudioBufferProvider interface
1302status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001303 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001304{
1305 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1306 Proxy::Buffer buf;
1307 buf.mFrameCount = buffer->frameCount;
1308 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1309 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001310 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001311 if (buf.mFrameCount == 0) {
1312 return WOULD_BLOCK;
1313 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001314 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001315 return status;
1316}
1317
1318void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1319{
1320 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1321 Proxy::Buffer buf;
1322 buf.mFrameCount = buffer->frameCount;
1323 buf.mRaw = buffer->raw;
1324 mPeerProxy->releaseBuffer(&buf);
1325 TrackBase::releaseBuffer(buffer);
1326}
1327
1328status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1329 const struct timespec *timeOut)
1330{
1331 return mProxy->obtainBuffer(buffer, timeOut);
1332}
1333
1334void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1335{
1336 mProxy->releaseBuffer(buffer);
1337 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1338 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1339 start();
1340 }
1341 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1342}
1343
Eric Laurent81784c32012-11-19 14:55:58 -08001344// ----------------------------------------------------------------------------
1345// Record
1346// ----------------------------------------------------------------------------
1347
1348AudioFlinger::RecordHandle::RecordHandle(
1349 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1350 : BnAudioRecord(),
1351 mRecordTrack(recordTrack)
1352{
1353}
1354
1355AudioFlinger::RecordHandle::~RecordHandle() {
1356 stop_nonvirtual();
1357 mRecordTrack->destroy();
1358}
1359
Eric Laurent81784c32012-11-19 14:55:58 -08001360status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1361 int triggerSession) {
1362 ALOGV("RecordHandle::start()");
1363 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1364}
1365
1366void AudioFlinger::RecordHandle::stop() {
1367 stop_nonvirtual();
1368}
1369
1370void AudioFlinger::RecordHandle::stop_nonvirtual() {
1371 ALOGV("RecordHandle::stop()");
1372 mRecordTrack->stop();
1373}
1374
1375status_t AudioFlinger::RecordHandle::onTransact(
1376 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1377{
1378 return BnAudioRecord::onTransact(code, data, reply, flags);
1379}
1380
1381// ----------------------------------------------------------------------------
1382
Glenn Kasten05997e22014-03-13 15:08:33 -07001383// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001384AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1385 RecordThread *thread,
1386 const sp<Client>& client,
1387 uint32_t sampleRate,
1388 audio_format_t format,
1389 audio_channel_mask_t channelMask,
1390 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001391 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001392 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001393 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001394 IAudioFlinger::track_flags_t flags,
1395 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001396 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001397 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001398 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001399 (type == TYPE_DEFAULT) ?
1400 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1401 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1402 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001403 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001404 mFramesToDrop(0),
1405 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1406 mRecordBufferConverter(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001407{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001408 if (mCblk == NULL) {
1409 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001410 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001411
Andy Hung97a893e2015-03-29 01:03:07 -07001412 mRecordBufferConverter = new RecordBufferConverter(
1413 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1414 channelMask, format, sampleRate);
1415 // Check if the RecordBufferConverter construction was successful.
1416 // If not, don't continue with construction.
1417 //
1418 // NOTE: It would be extremely rare that the record track cannot be created
1419 // for the current device, but a pending or future device change would make
1420 // the record track configuration valid.
1421 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1422 ALOGE("RecordTrack unable to create record buffer converter");
1423 return;
1424 }
1425
Andy Hung3f0c9022016-01-15 17:49:46 -08001426 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1427 mFrameSize, !isExternalTrack());
1428 mServerProxy = mAudioRecordServerProxy;
1429
Andy Hung97a893e2015-03-29 01:03:07 -07001430 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001431
1432 if (flags & IAudioFlinger::TRACK_FAST) {
1433 ALOG_ASSERT(thread->mFastTrackAvail);
1434 thread->mFastTrackAvail = false;
1435 }
Eric Laurent81784c32012-11-19 14:55:58 -08001436}
1437
1438AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1439{
1440 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001441 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001442 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001443}
1444
Andy Hung97a893e2015-03-29 01:03:07 -07001445status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1446{
1447 status_t status = TrackBase::initCheck();
1448 if (status == NO_ERROR && mServerProxy == 0) {
1449 status = BAD_VALUE;
1450 }
1451 return status;
1452}
1453
Eric Laurent81784c32012-11-19 14:55:58 -08001454// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001455status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001456{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001457 ServerProxy::Buffer buf;
1458 buf.mFrameCount = buffer->frameCount;
1459 status_t status = mServerProxy->obtainBuffer(&buf);
1460 buffer->frameCount = buf.mFrameCount;
1461 buffer->raw = buf.mRaw;
1462 if (buf.mFrameCount == 0) {
1463 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001464 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001465 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001466 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001467}
1468
1469status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1470 int triggerSession)
1471{
1472 sp<ThreadBase> thread = mThread.promote();
1473 if (thread != 0) {
1474 RecordThread *recordThread = (RecordThread *)thread.get();
1475 return recordThread->start(this, event, triggerSession);
1476 } else {
1477 return BAD_VALUE;
1478 }
1479}
1480
1481void AudioFlinger::RecordThread::RecordTrack::stop()
1482{
1483 sp<ThreadBase> thread = mThread.promote();
1484 if (thread != 0) {
1485 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001486 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07001487 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001488 }
1489 }
1490}
1491
1492void AudioFlinger::RecordThread::RecordTrack::destroy()
1493{
1494 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1495 sp<RecordTrack> keep(this);
1496 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001497 if (isExternalTrack()) {
1498 if (mState == ACTIVE || mState == RESUMING) {
1499 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
1500 }
1501 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
1502 }
Eric Laurent81784c32012-11-19 14:55:58 -08001503 sp<ThreadBase> thread = mThread.promote();
1504 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001505 Mutex::Autolock _l(thread->mLock);
1506 RecordThread *recordThread = (RecordThread *) thread.get();
1507 recordThread->destroyTrack_l(this);
1508 }
1509 }
1510}
1511
Eric Laurent9a54bc22013-09-09 09:08:44 -07001512void AudioFlinger::RecordThread::RecordTrack::invalidate()
1513{
1514 // FIXME should use proxy, and needs work
1515 audio_track_cblk_t* cblk = mCblk;
1516 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1517 android_atomic_release_store(0x40000000, &cblk->mFutex);
1518 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001519 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001520}
1521
Eric Laurent81784c32012-11-19 14:55:58 -08001522
1523/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1524{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001525 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001526}
1527
Marco Nelissenb2208842014-02-07 14:00:50 -08001528void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001529{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001530 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001531 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001532 (mClient == 0) ? getpid_cached : mClient->pid(),
1533 mFormat,
1534 mChannelMask,
1535 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001536 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001537 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001538 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001539 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001540
Eric Laurent81784c32012-11-19 14:55:58 -08001541}
1542
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001543void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1544{
1545 if (event == mSyncStartEvent) {
1546 ssize_t framesToDrop = 0;
1547 sp<ThreadBase> threadBase = mThread.promote();
1548 if (threadBase != 0) {
1549 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1550 // from audio HAL
1551 framesToDrop = threadBase->mFrameCount * 2;
1552 }
1553 mFramesToDrop = framesToDrop;
1554 }
1555}
1556
1557void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1558{
1559 if (mSyncStartEvent != 0) {
1560 mSyncStartEvent->cancel();
1561 mSyncStartEvent.clear();
1562 }
1563 mFramesToDrop = 0;
1564}
1565
Andy Hung3f0c9022016-01-15 17:49:46 -08001566void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1567 int64_t trackFramesReleased, int64_t sourceFramesRead,
1568 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1569{
1570 ExtendedTimestamp local = timestamp;
1571
1572 // Convert HAL frames to server-side track frames at track sample rate.
1573 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1574 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1575 if (local.mTimeNs[i] != 0) {
1576 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1577 const int64_t relativeTrackFrames = relativeServerFrames
1578 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1579 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1580 }
1581 }
1582 mAudioRecordServerProxy->setExtendedTimestamp(local);
1583}
Eric Laurent83b88082014-06-20 18:31:16 -07001584
1585AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1586 uint32_t sampleRate,
1587 audio_channel_mask_t channelMask,
1588 audio_format_t format,
1589 size_t frameCount,
1590 void *buffer,
1591 IAudioFlinger::track_flags_t flags)
1592 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
1593 buffer, 0, getuid(), flags, TYPE_PATCH),
1594 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1595{
1596 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1597 recordThread->sampleRate();
1598 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1599 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1600
1601 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1602 this, sampleRate,
1603 (int)mPeerTimeout.tv_sec,
1604 (int)(mPeerTimeout.tv_nsec / 1000000));
1605}
1606
1607AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1608{
1609}
1610
1611// AudioBufferProvider interface
1612status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001613 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001614{
1615 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1616 Proxy::Buffer buf;
1617 buf.mFrameCount = buffer->frameCount;
1618 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1619 ALOGV_IF(status != NO_ERROR,
1620 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001621 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001622 if (buf.mFrameCount == 0) {
1623 return WOULD_BLOCK;
1624 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001625 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001626 return status;
1627}
1628
1629void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1630{
1631 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1632 Proxy::Buffer buf;
1633 buf.mFrameCount = buffer->frameCount;
1634 buf.mRaw = buffer->raw;
1635 mPeerProxy->releaseBuffer(&buf);
1636 TrackBase::releaseBuffer(buffer);
1637}
1638
1639status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1640 const struct timespec *timeOut)
1641{
1642 return mProxy->obtainBuffer(buffer, timeOut);
1643}
1644
1645void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1646{
1647 mProxy->releaseBuffer(buffer);
1648}
1649
Glenn Kasten63238ef2015-03-02 15:50:29 -08001650} // namespace android