blob: b4c1fdde2183d0ef9f45f0ad94de3e69d7c27af0 [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
Eric Laurent81784c32012-11-19 14:55:58 -0800592// Don't call for fast tracks; the framesReady() could result in priority inversion
593bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800594 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
595 return true;
596 }
597
Eric Laurent16498512014-03-17 17:22:08 -0700598 if (isStopping()) {
599 if (framesReady() > 0) {
600 mFillingUpStatus = FS_FILLED;
601 }
Eric Laurent81784c32012-11-19 14:55:58 -0800602 return true;
603 }
604
605 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700606 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800607 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700608 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800609 return true;
610 }
611 return false;
612}
613
Glenn Kasten0f11b512014-01-31 16:18:54 -0800614status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
615 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800616{
617 status_t status = NO_ERROR;
618 ALOGV("start(%d), calling pid %d session %d",
619 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
620
621 sp<ThreadBase> thread = mThread.promote();
622 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700623 if (isOffloaded()) {
624 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
625 Mutex::Autolock _lth(thread->mLock);
626 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700627 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
628 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700629 invalidate();
630 return PERMISSION_DENIED;
631 }
632 }
633 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800634 track_state state = mState;
635 // here the track could be either new, or restarted
636 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800637
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800638 // initial state-stopping. next state-pausing.
639 // What if resume is called ?
640
641 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800642 if (mResumeToStopping) {
643 // happened we need to resume to STOPPING_1
644 mState = TrackBase::STOPPING_1;
645 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
646 } else {
647 mState = TrackBase::RESUMING;
648 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
649 }
Eric Laurent81784c32012-11-19 14:55:58 -0800650 } else {
651 mState = TrackBase::ACTIVE;
652 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
653 }
654
Eric Laurentbfb1b832013-01-07 09:53:42 -0800655 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700656 if (isFastTrack()) {
657 // refresh fast track underruns on start because that field is never cleared
658 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
659 // after stop.
660 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
661 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800662 status = playbackThread->addTrack_l(this);
663 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800664 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800665 // restore previous state if start was rejected by policy manager
666 if (status == PERMISSION_DENIED) {
667 mState = state;
668 }
669 }
670 // track was already in the active list, not a problem
671 if (status == ALREADY_EXISTS) {
672 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700673 } else {
674 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
675 // It is usually unsafe to access the server proxy from a binder thread.
676 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
677 // isn't looking at this track yet: we still hold the normal mixer thread lock,
678 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700679 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700680 ServerProxy::Buffer buffer;
681 buffer.mFrameCount = 1;
682 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800683 }
684 } else {
685 status = BAD_VALUE;
686 }
687 return status;
688}
689
690void AudioFlinger::PlaybackThread::Track::stop()
691{
692 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
693 sp<ThreadBase> thread = mThread.promote();
694 if (thread != 0) {
695 Mutex::Autolock _l(thread->mLock);
696 track_state state = mState;
697 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
698 // If the track is not active (PAUSED and buffers full), flush buffers
699 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
700 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
701 reset();
702 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700703 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800704 mState = STOPPED;
705 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800706 // For fast tracks prepareTracks_l() will set state to STOPPING_2
707 // presentation is complete
708 // For an offloaded track this starts a drain and state will
709 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800710 mState = STOPPING_1;
711 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700712 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800713 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
714 playbackThread);
715 }
Eric Laurent81784c32012-11-19 14:55:58 -0800716 }
717}
718
719void AudioFlinger::PlaybackThread::Track::pause()
720{
721 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
722 sp<ThreadBase> thread = mThread.promote();
723 if (thread != 0) {
724 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800725 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
726 switch (mState) {
727 case STOPPING_1:
728 case STOPPING_2:
729 if (!isOffloaded()) {
730 /* nothing to do if track is not offloaded */
731 break;
732 }
733
734 // Offloaded track was draining, we need to carry on draining when resumed
735 mResumeToStopping = true;
736 // fall through...
737 case ACTIVE:
738 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800739 mState = PAUSING;
740 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700741 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800742 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800743
Eric Laurentbfb1b832013-01-07 09:53:42 -0800744 default:
745 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800746 }
747 }
748}
749
750void AudioFlinger::PlaybackThread::Track::flush()
751{
752 ALOGV("flush(%d)", mName);
753 sp<ThreadBase> thread = mThread.promote();
754 if (thread != 0) {
755 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800756 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800757
758 if (isOffloaded()) {
759 // If offloaded we allow flush during any state except terminated
760 // and keep the track active to avoid problems if user is seeking
761 // rapidly and underlying hardware has a significant delay handling
762 // a pause
763 if (isTerminated()) {
764 return;
765 }
766
767 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800768 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800769
770 if (mState == STOPPING_1 || mState == STOPPING_2) {
771 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
772 mState = ACTIVE;
773 }
774
775 if (mState == ACTIVE) {
776 ALOGV("flush called in active state, resetting buffer time out retry count");
777 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
778 }
779
Haynes Mathew George7844f672014-01-15 12:32:55 -0800780 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800781 mResumeToStopping = false;
782 } else {
783 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
784 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
785 return;
786 }
787 // No point remaining in PAUSED state after a flush => go to
788 // FLUSHED state
789 mState = FLUSHED;
790 // do not reset the track if it is still in the process of being stopped or paused.
791 // this will be done by prepareTracks_l() when the track is stopped.
792 // prepareTracks_l() will see mState == FLUSHED, then
793 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800794 if (isDirect()) {
795 mFlushHwPending = true;
796 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800797 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
798 reset();
799 }
Eric Laurent81784c32012-11-19 14:55:58 -0800800 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800801 // Prevent flush being lost if the track is flushed and then resumed
802 // before mixer thread can run. This is important when offloading
803 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700804 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800805 }
806}
807
Haynes Mathew George7844f672014-01-15 12:32:55 -0800808// must be called with thread lock held
809void AudioFlinger::PlaybackThread::Track::flushAck()
810{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800811 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800812 return;
813
814 mFlushHwPending = false;
815}
816
Eric Laurent81784c32012-11-19 14:55:58 -0800817void AudioFlinger::PlaybackThread::Track::reset()
818{
819 // Do not reset twice to avoid discarding data written just after a flush and before
820 // the audioflinger thread detects the track is stopped.
821 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800822 // Force underrun condition to avoid false underrun callback until first data is
823 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700824 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800825 mFillingUpStatus = FS_FILLING;
826 mResetDone = true;
827 if (mState == FLUSHED) {
828 mState = IDLE;
829 }
830 }
831}
832
Eric Laurentbfb1b832013-01-07 09:53:42 -0800833status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
834{
835 sp<ThreadBase> thread = mThread.promote();
836 if (thread == 0) {
837 ALOGE("thread is dead");
838 return FAILED_TRANSACTION;
839 } else if ((thread->type() == ThreadBase::DIRECT) ||
840 (thread->type() == ThreadBase::OFFLOAD)) {
841 return thread->setParameters(keyValuePairs);
842 } else {
843 return PERMISSION_DENIED;
844 }
845}
846
Glenn Kasten573d80a2013-08-26 09:36:23 -0700847status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
848{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700849 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
850 if (isFastTrack()) {
851 return INVALID_OPERATION;
852 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700853 sp<ThreadBase> thread = mThread.promote();
854 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700855 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700856 }
Phil Burk6140c792015-03-19 14:30:21 -0700857
Glenn Kasten573d80a2013-08-26 09:36:23 -0700858 Mutex::Autolock _l(thread->mLock);
859 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Phil Burk6140c792015-03-19 14:30:21 -0700860
861 status_t result = INVALID_OPERATION;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700862 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700863 if (!playbackThread->mLatchQValid) {
864 return INVALID_OPERATION;
865 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700866 // FIXME Not accurate under dynamic changes of sample rate and speed.
867 // Do not use track's mSampleRate as it is not current for mixer tracks.
868 uint32_t sampleRate = mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700869 AudioPlaybackRate playbackRate = mAudioTrackServerProxy->getPlaybackRate();
870 uint32_t unpresentedFrames = ((double) playbackThread->mLatchQ.mUnpresentedFrames *
871 sampleRate * playbackRate.mSpeed)/ playbackThread->mSampleRate;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700872 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
873 // for a brand new track to share the same address as a recently destroyed
874 // track, and thus for us to get the frames released of the wrong track.
875 // It is unlikely that we would be able to call getTimestamp() so quickly
876 // right after creating a new track. Nevertheless, the index here should
877 // be changed to something that is unique. Or use a completely different strategy.
878 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
879 uint32_t framesWritten = i >= 0 ?
880 playbackThread->mLatchQ.mFramesReleased[i] :
881 mAudioTrackServerProxy->framesReleased();
Phil Burk1b420972015-04-22 10:52:21 -0700882 if (framesWritten >= unpresentedFrames) {
Phil Burk6140c792015-03-19 14:30:21 -0700883 timestamp.mPosition = framesWritten - unpresentedFrames;
884 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
885 result = NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -0700886 }
Phil Burk6140c792015-03-19 14:30:21 -0700887 } else { // offloaded or direct
888 result = playbackThread->getTimestamp_l(timestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700889 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700890
Phil Burk6140c792015-03-19 14:30:21 -0700891 return result;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700892}
893
Eric Laurent81784c32012-11-19 14:55:58 -0800894status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
895{
896 status_t status = DEAD_OBJECT;
897 sp<ThreadBase> thread = mThread.promote();
898 if (thread != 0) {
899 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
900 sp<AudioFlinger> af = mClient->audioFlinger();
901
902 Mutex::Autolock _l(af->mLock);
903
904 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
905
906 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
907 Mutex::Autolock _dl(playbackThread->mLock);
908 Mutex::Autolock _sl(srcThread->mLock);
909 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
910 if (chain == 0) {
911 return INVALID_OPERATION;
912 }
913
914 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
915 if (effect == 0) {
916 return INVALID_OPERATION;
917 }
918 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700919 status = playbackThread->addEffect_l(effect);
920 if (status != NO_ERROR) {
921 srcThread->addEffect_l(effect);
922 return INVALID_OPERATION;
923 }
Eric Laurent81784c32012-11-19 14:55:58 -0800924 // removeEffect_l() has stopped the effect if it was active so it must be restarted
925 if (effect->state() == EffectModule::ACTIVE ||
926 effect->state() == EffectModule::STOPPING) {
927 effect->start();
928 }
929
930 sp<EffectChain> dstChain = effect->chain().promote();
931 if (dstChain == 0) {
932 srcThread->addEffect_l(effect);
933 return INVALID_OPERATION;
934 }
935 AudioSystem::unregisterEffect(effect->id());
936 AudioSystem::registerEffect(&effect->desc(),
937 srcThread->id(),
938 dstChain->strategy(),
939 AUDIO_SESSION_OUTPUT_MIX,
940 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700941 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800942 }
943 status = playbackThread->attachAuxEffect(this, EffectId);
944 }
945 return status;
946}
947
948void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
949{
950 mAuxEffectId = EffectId;
951 mAuxBuffer = buffer;
952}
953
954bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
955 size_t audioHalFrames)
956{
957 // a track is considered presented when the total number of frames written to audio HAL
958 // corresponds to the number of frames written when presentationComplete() is called for the
959 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800960 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
961 // to detect when all frames have been played. In this case framesWritten isn't
962 // useful because it doesn't always reflect whether there is data in the h/w
963 // buffers, particularly if a track has been paused and resumed during draining
964 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
965 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800966 if (mPresentationCompleteFrames == 0) {
967 mPresentationCompleteFrames = framesWritten + audioHalFrames;
968 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
969 mPresentationCompleteFrames, audioHalFrames);
970 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800971
972 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800973 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800974 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800975 return true;
976 }
977 return false;
978}
979
980void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
981{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700982 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800983 if (mSyncEvents[i]->type() == type) {
984 mSyncEvents[i]->trigger();
985 mSyncEvents.removeAt(i);
986 i--;
987 }
988 }
989}
990
991// implement VolumeBufferProvider interface
992
Glenn Kastenc56f3422014-03-21 17:53:17 -0700993gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -0800994{
995 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
996 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -0700997 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
998 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
999 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001000 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001001 if (vl > GAIN_FLOAT_UNITY) {
1002 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001003 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001004 if (vr > GAIN_FLOAT_UNITY) {
1005 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001006 }
1007 // now apply the cached master volume and stream type volume;
1008 // this is trusted but lacks any synchronization or barrier so may be stale
1009 float v = mCachedVolume;
1010 vl *= v;
1011 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001012 // re-combine into packed minifloat
1013 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001014 // FIXME look at mute, pause, and stop flags
1015 return vlr;
1016}
1017
1018status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1019{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001020 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001021 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1022 (mState == STOPPED)))) {
1023 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1024 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1025 event->cancel();
1026 return INVALID_OPERATION;
1027 }
1028 (void) TrackBase::setSyncEvent(event);
1029 return NO_ERROR;
1030}
1031
Glenn Kasten5736c352012-12-04 12:12:34 -08001032void AudioFlinger::PlaybackThread::Track::invalidate()
1033{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001034 // FIXME should use proxy, and needs work
1035 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001036 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001037 android_atomic_release_store(0x40000000, &cblk->mFutex);
1038 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001039 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001040 mIsInvalid = true;
1041}
1042
Eric Laurent59fe0102013-09-27 18:48:26 -07001043void AudioFlinger::PlaybackThread::Track::signal()
1044{
1045 sp<ThreadBase> thread = mThread.promote();
1046 if (thread != 0) {
1047 PlaybackThread *t = (PlaybackThread *)thread.get();
1048 Mutex::Autolock _l(t->mLock);
1049 t->broadcast_l();
1050 }
1051}
1052
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001053//To be called with thread lock held
1054bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1055
1056 if (mState == RESUMING)
1057 return true;
1058 /* Resume is pending if track was stopping before pause was called */
1059 if (mState == STOPPING_1 &&
1060 mResumeToStopping)
1061 return true;
1062
1063 return false;
1064}
1065
1066//To be called with thread lock held
1067void AudioFlinger::PlaybackThread::Track::resumeAck() {
1068
1069
1070 if (mState == RESUMING)
1071 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001072
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001073 // Other possibility of pending resume is stopping_1 state
1074 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001075 // drain being called.
1076 if (mState == STOPPING_1) {
1077 mResumeToStopping = false;
1078 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001079}
Eric Laurent81784c32012-11-19 14:55:58 -08001080// ----------------------------------------------------------------------------
1081
Eric Laurent81784c32012-11-19 14:55:58 -08001082AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1083 PlaybackThread *playbackThread,
1084 DuplicatingThread *sourceThread,
1085 uint32_t sampleRate,
1086 audio_format_t format,
1087 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001088 size_t frameCount,
1089 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001090 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1091 sampleRate, format, channelMask, frameCount,
1092 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001093 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001094{
1095
1096 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001097 mOutBuffer.frameCount = 0;
1098 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001099 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001100 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001101 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001102 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001103 // since client and server are in the same process,
1104 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001105 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1106 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001107 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001108 mClientProxy->setSendLevel(0.0);
1109 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001110 } else {
1111 ALOGW("Error creating output track on thread %p", playbackThread);
1112 }
1113}
1114
1115AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1116{
1117 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001118 delete mClientProxy;
1119 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001120}
1121
1122status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1123 int triggerSession)
1124{
1125 status_t status = Track::start(event, triggerSession);
1126 if (status != NO_ERROR) {
1127 return status;
1128 }
1129
1130 mActive = true;
1131 mRetryCount = 127;
1132 return status;
1133}
1134
1135void AudioFlinger::PlaybackThread::OutputTrack::stop()
1136{
1137 Track::stop();
1138 clearBufferQueue();
1139 mOutBuffer.frameCount = 0;
1140 mActive = false;
1141}
1142
Andy Hungc25b84a2015-01-14 19:04:10 -08001143bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001144{
1145 Buffer *pInBuffer;
1146 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001147 bool outputBufferFull = false;
1148 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001149 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001150
1151 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1152
1153 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001154 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001155 }
1156
1157 while (waitTimeLeftMs) {
1158 // First write pending buffers, then new data
1159 if (mBufferQueue.size()) {
1160 pInBuffer = mBufferQueue.itemAt(0);
1161 } else {
1162 pInBuffer = &inBuffer;
1163 }
1164
1165 if (pInBuffer->frameCount == 0) {
1166 break;
1167 }
1168
1169 if (mOutBuffer.frameCount == 0) {
1170 mOutBuffer.frameCount = pInBuffer->frameCount;
1171 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001172 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1173 if (status != NO_ERROR) {
1174 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1175 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001176 outputBufferFull = true;
1177 break;
1178 }
1179 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1180 if (waitTimeLeftMs >= waitTimeMs) {
1181 waitTimeLeftMs -= waitTimeMs;
1182 } else {
1183 waitTimeLeftMs = 0;
1184 }
1185 }
1186
1187 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1188 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001189 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001190 Proxy::Buffer buf;
1191 buf.mFrameCount = outFrames;
1192 buf.mRaw = NULL;
1193 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001194 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001195 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001196 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001197 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001198
1199 if (pInBuffer->frameCount == 0) {
1200 if (mBufferQueue.size()) {
1201 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001202 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001203 delete pInBuffer;
1204 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1205 mThread.unsafe_get(), mBufferQueue.size());
1206 } else {
1207 break;
1208 }
1209 }
1210 }
1211
1212 // If we could not write all frames, allocate a buffer and queue it for next time.
1213 if (inBuffer.frameCount) {
1214 sp<ThreadBase> thread = mThread.promote();
1215 if (thread != 0 && !thread->standby()) {
1216 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1217 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001218 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001219 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001220 pInBuffer->raw = pInBuffer->mBuffer;
1221 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001222 mBufferQueue.add(pInBuffer);
1223 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1224 mThread.unsafe_get(), mBufferQueue.size());
1225 } else {
1226 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1227 mThread.unsafe_get(), this);
1228 }
1229 }
1230 }
1231
Andy Hungc25b84a2015-01-14 19:04:10 -08001232 // Calling write() with a 0 length buffer means that no more data will be written:
1233 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1234 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1235 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001236 }
1237
1238 return outputBufferFull;
1239}
1240
1241status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1242 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1243{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001244 ClientProxy::Buffer buf;
1245 buf.mFrameCount = buffer->frameCount;
1246 struct timespec timeout;
1247 timeout.tv_sec = waitTimeMs / 1000;
1248 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1249 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1250 buffer->frameCount = buf.mFrameCount;
1251 buffer->raw = buf.mRaw;
1252 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001253}
1254
Eric Laurent81784c32012-11-19 14:55:58 -08001255void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1256{
1257 size_t size = mBufferQueue.size();
1258
1259 for (size_t i = 0; i < size; i++) {
1260 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001261 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001262 delete pBuffer;
1263 }
1264 mBufferQueue.clear();
1265}
1266
1267
Eric Laurent83b88082014-06-20 18:31:16 -07001268AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001269 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001270 uint32_t sampleRate,
1271 audio_channel_mask_t channelMask,
1272 audio_format_t format,
1273 size_t frameCount,
1274 void *buffer,
1275 IAudioFlinger::track_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001276 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001277 sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001278 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1279 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1280{
1281 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1282 playbackThread->sampleRate();
1283 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1284 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1285
1286 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1287 this, sampleRate,
1288 (int)mPeerTimeout.tv_sec,
1289 (int)(mPeerTimeout.tv_nsec / 1000000));
1290}
1291
1292AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1293{
1294}
1295
1296// AudioBufferProvider interface
1297status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001298 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001299{
1300 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1301 Proxy::Buffer buf;
1302 buf.mFrameCount = buffer->frameCount;
1303 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1304 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001305 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001306 if (buf.mFrameCount == 0) {
1307 return WOULD_BLOCK;
1308 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001309 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001310 return status;
1311}
1312
1313void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1314{
1315 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1316 Proxy::Buffer buf;
1317 buf.mFrameCount = buffer->frameCount;
1318 buf.mRaw = buffer->raw;
1319 mPeerProxy->releaseBuffer(&buf);
1320 TrackBase::releaseBuffer(buffer);
1321}
1322
1323status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1324 const struct timespec *timeOut)
1325{
1326 return mProxy->obtainBuffer(buffer, timeOut);
1327}
1328
1329void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1330{
1331 mProxy->releaseBuffer(buffer);
1332 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1333 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1334 start();
1335 }
1336 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1337}
1338
Eric Laurent81784c32012-11-19 14:55:58 -08001339// ----------------------------------------------------------------------------
1340// Record
1341// ----------------------------------------------------------------------------
1342
1343AudioFlinger::RecordHandle::RecordHandle(
1344 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1345 : BnAudioRecord(),
1346 mRecordTrack(recordTrack)
1347{
1348}
1349
1350AudioFlinger::RecordHandle::~RecordHandle() {
1351 stop_nonvirtual();
1352 mRecordTrack->destroy();
1353}
1354
Eric Laurent81784c32012-11-19 14:55:58 -08001355status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1356 int triggerSession) {
1357 ALOGV("RecordHandle::start()");
1358 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1359}
1360
1361void AudioFlinger::RecordHandle::stop() {
1362 stop_nonvirtual();
1363}
1364
1365void AudioFlinger::RecordHandle::stop_nonvirtual() {
1366 ALOGV("RecordHandle::stop()");
1367 mRecordTrack->stop();
1368}
1369
1370status_t AudioFlinger::RecordHandle::onTransact(
1371 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1372{
1373 return BnAudioRecord::onTransact(code, data, reply, flags);
1374}
1375
1376// ----------------------------------------------------------------------------
1377
Glenn Kasten05997e22014-03-13 15:08:33 -07001378// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001379AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1380 RecordThread *thread,
1381 const sp<Client>& client,
1382 uint32_t sampleRate,
1383 audio_format_t format,
1384 audio_channel_mask_t channelMask,
1385 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001386 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001387 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001388 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001389 IAudioFlinger::track_flags_t flags,
1390 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001391 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001392 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001393 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001394 (type == TYPE_DEFAULT) ?
1395 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1396 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1397 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001398 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001399 mFramesToDrop(0),
1400 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1401 mRecordBufferConverter(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001402{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001403 if (mCblk == NULL) {
1404 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001405 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001406
Andy Hung97a893e2015-03-29 01:03:07 -07001407 mRecordBufferConverter = new RecordBufferConverter(
1408 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1409 channelMask, format, sampleRate);
1410 // Check if the RecordBufferConverter construction was successful.
1411 // If not, don't continue with construction.
1412 //
1413 // NOTE: It would be extremely rare that the record track cannot be created
1414 // for the current device, but a pending or future device change would make
1415 // the record track configuration valid.
1416 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1417 ALOGE("RecordTrack unable to create record buffer converter");
1418 return;
1419 }
1420
Andy Hung3f0c9022016-01-15 17:49:46 -08001421 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1422 mFrameSize, !isExternalTrack());
1423 mServerProxy = mAudioRecordServerProxy;
1424
Andy Hung97a893e2015-03-29 01:03:07 -07001425 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001426
1427 if (flags & IAudioFlinger::TRACK_FAST) {
1428 ALOG_ASSERT(thread->mFastTrackAvail);
1429 thread->mFastTrackAvail = false;
1430 }
Eric Laurent81784c32012-11-19 14:55:58 -08001431}
1432
1433AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1434{
1435 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001436 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001437 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001438}
1439
Andy Hung97a893e2015-03-29 01:03:07 -07001440status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1441{
1442 status_t status = TrackBase::initCheck();
1443 if (status == NO_ERROR && mServerProxy == 0) {
1444 status = BAD_VALUE;
1445 }
1446 return status;
1447}
1448
Eric Laurent81784c32012-11-19 14:55:58 -08001449// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001450status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001451{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001452 ServerProxy::Buffer buf;
1453 buf.mFrameCount = buffer->frameCount;
1454 status_t status = mServerProxy->obtainBuffer(&buf);
1455 buffer->frameCount = buf.mFrameCount;
1456 buffer->raw = buf.mRaw;
1457 if (buf.mFrameCount == 0) {
1458 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001459 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001460 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001461 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001462}
1463
1464status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1465 int triggerSession)
1466{
1467 sp<ThreadBase> thread = mThread.promote();
1468 if (thread != 0) {
1469 RecordThread *recordThread = (RecordThread *)thread.get();
1470 return recordThread->start(this, event, triggerSession);
1471 } else {
1472 return BAD_VALUE;
1473 }
1474}
1475
1476void AudioFlinger::RecordThread::RecordTrack::stop()
1477{
1478 sp<ThreadBase> thread = mThread.promote();
1479 if (thread != 0) {
1480 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001481 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07001482 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001483 }
1484 }
1485}
1486
1487void AudioFlinger::RecordThread::RecordTrack::destroy()
1488{
1489 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1490 sp<RecordTrack> keep(this);
1491 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001492 if (isExternalTrack()) {
1493 if (mState == ACTIVE || mState == RESUMING) {
1494 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
1495 }
1496 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
1497 }
Eric Laurent81784c32012-11-19 14:55:58 -08001498 sp<ThreadBase> thread = mThread.promote();
1499 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001500 Mutex::Autolock _l(thread->mLock);
1501 RecordThread *recordThread = (RecordThread *) thread.get();
1502 recordThread->destroyTrack_l(this);
1503 }
1504 }
1505}
1506
Eric Laurent9a54bc22013-09-09 09:08:44 -07001507void AudioFlinger::RecordThread::RecordTrack::invalidate()
1508{
1509 // FIXME should use proxy, and needs work
1510 audio_track_cblk_t* cblk = mCblk;
1511 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1512 android_atomic_release_store(0x40000000, &cblk->mFutex);
1513 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001514 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001515}
1516
Eric Laurent81784c32012-11-19 14:55:58 -08001517
1518/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1519{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001520 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001521}
1522
Marco Nelissenb2208842014-02-07 14:00:50 -08001523void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001524{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001525 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001526 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001527 (mClient == 0) ? getpid_cached : mClient->pid(),
1528 mFormat,
1529 mChannelMask,
1530 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001531 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001532 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001533 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001534 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001535
Eric Laurent81784c32012-11-19 14:55:58 -08001536}
1537
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001538void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1539{
1540 if (event == mSyncStartEvent) {
1541 ssize_t framesToDrop = 0;
1542 sp<ThreadBase> threadBase = mThread.promote();
1543 if (threadBase != 0) {
1544 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1545 // from audio HAL
1546 framesToDrop = threadBase->mFrameCount * 2;
1547 }
1548 mFramesToDrop = framesToDrop;
1549 }
1550}
1551
1552void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1553{
1554 if (mSyncStartEvent != 0) {
1555 mSyncStartEvent->cancel();
1556 mSyncStartEvent.clear();
1557 }
1558 mFramesToDrop = 0;
1559}
1560
Andy Hung3f0c9022016-01-15 17:49:46 -08001561void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1562 int64_t trackFramesReleased, int64_t sourceFramesRead,
1563 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1564{
1565 ExtendedTimestamp local = timestamp;
1566
1567 // Convert HAL frames to server-side track frames at track sample rate.
1568 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1569 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1570 if (local.mTimeNs[i] != 0) {
1571 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1572 const int64_t relativeTrackFrames = relativeServerFrames
1573 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1574 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1575 }
1576 }
1577 mAudioRecordServerProxy->setExtendedTimestamp(local);
1578}
Eric Laurent83b88082014-06-20 18:31:16 -07001579
1580AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1581 uint32_t sampleRate,
1582 audio_channel_mask_t channelMask,
1583 audio_format_t format,
1584 size_t frameCount,
1585 void *buffer,
1586 IAudioFlinger::track_flags_t flags)
1587 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
1588 buffer, 0, getuid(), flags, TYPE_PATCH),
1589 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1590{
1591 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1592 recordThread->sampleRate();
1593 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1594 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1595
1596 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1597 this, sampleRate,
1598 (int)mPeerTimeout.tv_sec,
1599 (int)(mPeerTimeout.tv_nsec / 1000000));
1600}
1601
1602AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1603{
1604}
1605
1606// AudioBufferProvider interface
1607status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001608 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001609{
1610 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1611 Proxy::Buffer buf;
1612 buf.mFrameCount = buffer->frameCount;
1613 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1614 ALOGV_IF(status != NO_ERROR,
1615 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001616 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001617 if (buf.mFrameCount == 0) {
1618 return WOULD_BLOCK;
1619 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001620 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001621 return status;
1622}
1623
1624void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1625{
1626 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1627 Proxy::Buffer buf;
1628 buf.mFrameCount = buffer->frameCount;
1629 buf.mRaw = buffer->raw;
1630 mPeerProxy->releaseBuffer(&buf);
1631 TrackBase::releaseBuffer(buffer);
1632}
1633
1634status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1635 const struct timespec *timeOut)
1636{
1637 return mProxy->obtainBuffer(buffer, timeOut);
1638}
1639
1640void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1641{
1642 mProxy->releaseBuffer(buffer);
1643}
1644
Glenn Kasten63238ef2015-03-02 15:50:29 -08001645} // namespace android