blob: 72b22529ba13eaf63c9100de501b186d6324519b [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
Andy Hunge10393e2015-06-12 13:59:33 -070053// TODO move to a common header (Also shared with AudioTrack.cpp)
54#define NANOS_PER_SECOND 1000000000
55#define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * NANOS_PER_SECOND + time.tv_nsec)
56
Eric Laurent81784c32012-11-19 14:55:58 -080057namespace android {
58
59// ----------------------------------------------------------------------------
60// TrackBase
61// ----------------------------------------------------------------------------
62
Glenn Kastenda6ef132013-01-10 12:31:01 -080063static volatile int32_t nextTrackId = 55;
64
Eric Laurent81784c32012-11-19 14:55:58 -080065// TrackBase constructor must be called with AudioFlinger::mLock held
66AudioFlinger::ThreadBase::TrackBase::TrackBase(
67 ThreadBase *thread,
68 const sp<Client>& client,
69 uint32_t sampleRate,
70 audio_format_t format,
71 audio_channel_mask_t channelMask,
72 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070073 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -080074 audio_session_t sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080075 int clientUid,
Glenn Kastend776ac62014-05-07 09:16:09 -070076 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070077 alloc_type alloc,
78 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080079 : RefBase(),
80 mThread(thread),
81 mClient(client),
82 mCblk(NULL),
83 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080084 mState(IDLE),
85 mSampleRate(sampleRate),
86 mFormat(format),
87 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070088 mChannelCount(isOut ?
89 audio_channel_count_from_out_mask(channelMask) :
90 audio_channel_count_from_in_mask(channelMask)),
Phil Burkfdb3c072016-02-09 10:47:02 -080091 mFrameSize(audio_has_proportional_frames(format) ?
Eric Laurent81784c32012-11-19 14:55:58 -080092 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
93 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080094 mSessionId(sessionId),
95 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080096 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080097 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070098 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -070099 mType(type),
100 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800101{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700102 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
103 if (!isTrustedCallingUid(callingUid) || clientUid == -1) {
104 ALOGW_IF(clientUid != -1 && clientUid != (int)callingUid,
105 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
106 clientUid = (int)callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800107 }
108 // clientUid contains the uid of the app that is responsible for this track, so we can blame
109 // battery usage on it.
110 mUid = clientUid;
111
Eric Laurent81784c32012-11-19 14:55:58 -0800112 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hungeaa39692017-02-13 18:48:39 -0800113
114 size_t bufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
115 // check overflow when computing bufferSize due to multiplication by mFrameSize.
116 if (bufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
117 || mFrameSize == 0 // format needs to be correct
118 || bufferSize > SIZE_MAX / mFrameSize) {
119 android_errorWriteLog(0x534e4554, "34749571");
120 return;
121 }
122 bufferSize *= mFrameSize;
123
Eric Laurent81784c32012-11-19 14:55:58 -0800124 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700125 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hungeaa39692017-02-13 18:48:39 -0800126 // check overflow when computing allocation size for streaming tracks.
127 if (size > SIZE_MAX - bufferSize) {
128 android_errorWriteLog(0x534e4554, "34749571");
129 return;
130 }
Eric Laurent81784c32012-11-19 14:55:58 -0800131 size += bufferSize;
132 }
133
134 if (client != 0) {
135 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700136 if (mCblkMemory == 0 ||
137 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700138 ALOGE("not enough memory for AudioTrack size=%zu", size);
Eric Laurent81784c32012-11-19 14:55:58 -0800139 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700140 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800141 return;
142 }
143 } else {
Andy Hung1159ffd2017-02-13 18:50:48 -0800144 mCblk = (audio_track_cblk_t *) malloc(size);
145 if (mCblk == NULL) {
146 ALOGE("not enough memory for AudioTrack size=%zu", size);
147 return;
148 }
Eric Laurent81784c32012-11-19 14:55:58 -0800149 }
150
151 // construct the shared structure in-place.
152 if (mCblk != NULL) {
153 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700154 switch (alloc) {
155 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700156 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
157 if (roHeap == 0 ||
158 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
159 (mBuffer = mBufferMemory->pointer()) == NULL) {
160 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
161 if (roHeap != 0) {
162 roHeap->dump("buffer");
163 }
164 mCblkMemory.clear();
165 mBufferMemory.clear();
166 return;
167 }
Eric Laurent81784c32012-11-19 14:55:58 -0800168 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700169 } break;
170 case ALLOC_PIPE:
171 mBufferMemory = thread->pipeMemory();
172 // mBuffer is the virtual address as seen from current process (mediaserver),
173 // and should normally be coming from mBufferMemory->pointer().
174 // However in this case the TrackBase does not reference the buffer directly.
175 // It should references the buffer via the pipe.
176 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
177 mBuffer = NULL;
178 break;
179 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700180 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700181 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700182 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
183 memset(mBuffer, 0, bufferSize);
184 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700185 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800186#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700187 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800188#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700189 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700190 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700191 case ALLOC_LOCAL:
192 mBuffer = calloc(1, bufferSize);
193 break;
194 case ALLOC_NONE:
195 mBuffer = buffer;
196 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800197 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800198
Glenn Kasten46909e72013-02-26 09:20:22 -0800199#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800200 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700201 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800202 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800203 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
204 size_t numCounterOffers = 0;
205 const NBAIO_Format offers[1] = {pipeFormat};
206 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
207 ALOG_ASSERT(index == 0);
208 PipeReader *pipeReader = new PipeReader(*pipe);
209 numCounterOffers = 0;
210 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
211 ALOG_ASSERT(index == 0);
212 mTeeSink = pipe;
213 mTeeSource = pipeReader;
214 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800215 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800216#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800217
Eric Laurent81784c32012-11-19 14:55:58 -0800218 }
219}
220
Eric Laurent83b88082014-06-20 18:31:16 -0700221status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
222{
223 status_t status;
224 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
225 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
226 } else {
227 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
228 }
229 return status;
230}
231
Eric Laurent81784c32012-11-19 14:55:58 -0800232AudioFlinger::ThreadBase::TrackBase::~TrackBase()
233{
Glenn Kasten46909e72013-02-26 09:20:22 -0800234#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800235 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800236#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800237 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
238 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800239 if (mCblk != NULL) {
Andy Hung1159ffd2017-02-13 18:50:48 -0800240 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurent81784c32012-11-19 14:55:58 -0800241 if (mClient == 0) {
Andy Hung1159ffd2017-02-13 18:50:48 -0800242 free(mCblk);
Eric Laurent81784c32012-11-19 14:55:58 -0800243 }
244 }
245 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
246 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700247 // Client destructor must run with AudioFlinger client mutex locked
248 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800249 // If the client's reference count drops to zero, the associated destructor
250 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
251 // relying on the automatic clear() at end of scope.
252 mClient.clear();
253 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700254 // flush the binder command buffer
255 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800256}
257
258// AudioBufferProvider interface
259// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800260// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800261void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
262{
Glenn Kasten46909e72013-02-26 09:20:22 -0800263#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800264 if (mTeeSink != 0) {
265 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
266 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800267#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800268
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800269 ServerProxy::Buffer buf;
270 buf.mFrameCount = buffer->frameCount;
271 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800272 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800273 buffer->raw = NULL;
274 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800275}
276
Eric Laurent81784c32012-11-19 14:55:58 -0800277status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
278{
279 mSyncEvents.add(event);
280 return NO_ERROR;
281}
282
283// ----------------------------------------------------------------------------
284// Playback
285// ----------------------------------------------------------------------------
286
287AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
288 : BnAudioTrack(),
289 mTrack(track)
290{
291}
292
293AudioFlinger::TrackHandle::~TrackHandle() {
294 // just stop the track on deletion, associated resources
295 // will be freed from the main thread once all pending buffers have
296 // been played. Unless it's not in the active track list, in which
297 // case we free everything now...
298 mTrack->destroy();
299}
300
301sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
302 return mTrack->getCblk();
303}
304
305status_t AudioFlinger::TrackHandle::start() {
306 return mTrack->start();
307}
308
309void AudioFlinger::TrackHandle::stop() {
310 mTrack->stop();
311}
312
313void AudioFlinger::TrackHandle::flush() {
314 mTrack->flush();
315}
316
Eric Laurent81784c32012-11-19 14:55:58 -0800317void AudioFlinger::TrackHandle::pause() {
318 mTrack->pause();
319}
320
321status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
322{
323 return mTrack->attachAuxEffect(EffectId);
324}
325
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700326status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
327 return mTrack->setParameters(keyValuePairs);
328}
329
Glenn Kasten53cec222013-08-29 09:01:02 -0700330status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
331{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700332 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700333}
334
Eric Laurent59fe0102013-09-27 18:48:26 -0700335
336void AudioFlinger::TrackHandle::signal()
337{
338 return mTrack->signal();
339}
340
Eric Laurent81784c32012-11-19 14:55:58 -0800341status_t AudioFlinger::TrackHandle::onTransact(
342 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
343{
344 return BnAudioTrack::onTransact(code, data, reply, flags);
345}
346
347// ----------------------------------------------------------------------------
348
349// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
350AudioFlinger::PlaybackThread::Track::Track(
351 PlaybackThread *thread,
352 const sp<Client>& client,
353 audio_stream_type_t streamType,
354 uint32_t sampleRate,
355 audio_format_t format,
356 audio_channel_mask_t channelMask,
357 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700358 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800359 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800360 audio_session_t sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800361 int uid,
Eric Laurent05067782016-06-01 18:27:28 -0700362 audio_output_flags_t flags,
Eric Laurent83b88082014-06-20 18:31:16 -0700363 track_type type)
364 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
365 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
Eric Laurent05067782016-06-01 18:27:28 -0700366 sessionId, uid, true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700367 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
368 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800369 mFillingUpStatus(FS_INVALID),
370 // mRetryCount initialized later when needed
371 mSharedBuffer(sharedBuffer),
372 mStreamType(streamType),
373 mName(-1), // see note below
374 mMainBuffer(thread->mixBuffer()),
375 mAuxBuffer(NULL),
376 mAuxEffectId(0), mHasVolumeController(false),
377 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700378 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Andy Hunge10393e2015-06-12 13:59:33 -0700379 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800380 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800381 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800382 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800383 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800384 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700385 mFlushHwPending(false),
386 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -0800387{
Eric Laurent83b88082014-06-20 18:31:16 -0700388 // client == 0 implies sharedBuffer == 0
389 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
390
Eric Laurente93cc032016-05-05 10:15:10 -0700391 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Eric Laurent83b88082014-06-20 18:31:16 -0700392 sharedBuffer->size());
393
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700394 if (mCblk == NULL) {
395 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800396 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700397
398 if (sharedBuffer == 0) {
399 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700400 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700401 } else {
Andy Hungf4aeab22017-06-12 17:22:46 -0700402 // Is the shared buffer of sufficient size?
403 // (frameCount * mFrameSize) is <= SIZE_MAX, checked in TrackBase.
404 if (sharedBuffer->size() < frameCount * mFrameSize) {
405 // Workaround: clear out mCblk to indicate track hasn't been properly created.
406 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
407 if (mClient == 0) {
408 free(mCblk);
409 }
410 mCblk = NULL;
411
412 mSharedBuffer.clear(); // release shared buffer early
413 android_errorWriteLog(0x534e4554, "38340117");
414 return;
415 }
416
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700417 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
418 mFrameSize);
419 }
420 mServerProxy = mAudioTrackServerProxy;
421
Glenn Kastenc263ca02014-06-04 20:31:46 -0700422 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700423 if (mName < 0) {
424 ALOGE("no more track names available");
425 return;
426 }
427 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700428 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700429 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
430 // race with setSyncEvent(). However, if we call it, we cannot properly start
431 // static fast tracks (SoundPool) immediately after stopping.
432 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700433 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
434 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700435 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700436 // FIXME This is too eager. We allocate a fast track index before the
437 // fast track becomes active. Since fast tracks are a scarce resource,
438 // this means we are potentially denying other more important fast tracks from
439 // being created. It would be better to allocate the index dynamically.
440 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700441 thread->mFastTrackAvailMask &= ~(1 << i);
442 }
Eric Laurent81784c32012-11-19 14:55:58 -0800443}
444
445AudioFlinger::PlaybackThread::Track::~Track()
446{
447 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700448
449 // The destructor would clear mSharedBuffer,
450 // but it will not push the decremented reference count,
451 // leaving the client's IMemory dangling indefinitely.
452 // This prevents that leak.
453 if (mSharedBuffer != 0) {
454 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700455 }
Eric Laurent81784c32012-11-19 14:55:58 -0800456}
457
Glenn Kasten03003332013-08-06 15:40:54 -0700458status_t AudioFlinger::PlaybackThread::Track::initCheck() const
459{
460 status_t status = TrackBase::initCheck();
461 if (status == NO_ERROR && mName < 0) {
462 status = NO_MEMORY;
463 }
464 return status;
465}
466
Eric Laurent81784c32012-11-19 14:55:58 -0800467void AudioFlinger::PlaybackThread::Track::destroy()
468{
469 // NOTE: destroyTrack_l() can remove a strong reference to this Track
470 // by removing it from mTracks vector, so there is a risk that this Tracks's
471 // destructor is called. As the destructor needs to lock mLock,
472 // we must acquire a strong reference on this Track before locking mLock
473 // here so that the destructor is called only when exiting this function.
474 // On the other hand, as long as Track::destroy() is only called by
475 // TrackHandle destructor, the TrackHandle still holds a strong ref on
476 // this Track with its member mTrack.
477 sp<Track> keep(this);
478 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700479 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800480 sp<ThreadBase> thread = mThread.promote();
481 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800482 Mutex::Autolock _l(thread->mLock);
483 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700484 wasActive = playbackThread->destroyTrack_l(this);
485 }
486 if (isExternalTrack() && !wasActive) {
Glenn Kastend848eb42016-03-08 13:42:11 -0800487 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800488 }
489 }
490}
491
492/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
493{
Marco Nelissenb2208842014-02-07 14:00:50 -0800494 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700495 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800496}
497
Marco Nelissenb2208842014-02-07 14:00:50 -0800498void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800499{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700500 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800501 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800502 sprintf(buffer, " F %2d", mFastIndex);
503 } else if (mName >= AudioMixer::TRACK0) {
504 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800505 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800506 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800507 }
508 track_state state = mState;
509 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800510 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800511 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800512 } else {
513 switch (state) {
514 case IDLE:
515 stateChar = 'I';
516 break;
517 case STOPPING_1:
518 stateChar = 's';
519 break;
520 case STOPPING_2:
521 stateChar = '5';
522 break;
523 case STOPPED:
524 stateChar = 'S';
525 break;
526 case RESUMING:
527 stateChar = 'R';
528 break;
529 case ACTIVE:
530 stateChar = 'A';
531 break;
532 case PAUSING:
533 stateChar = 'p';
534 break;
535 case PAUSED:
536 stateChar = 'P';
537 break;
538 case FLUSHED:
539 stateChar = 'F';
540 break;
541 default:
542 stateChar = '?';
543 break;
544 }
Eric Laurent81784c32012-11-19 14:55:58 -0800545 }
546 char nowInUnderrun;
547 switch (mObservedUnderruns.mBitFields.mMostRecent) {
548 case UNDERRUN_FULL:
549 nowInUnderrun = ' ';
550 break;
551 case UNDERRUN_PARTIAL:
552 nowInUnderrun = '<';
553 break;
554 case UNDERRUN_EMPTY:
555 nowInUnderrun = '*';
556 break;
557 default:
558 nowInUnderrun = '?';
559 break;
560 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000561 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 +0000562 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800563 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800564 (mClient == 0) ? getpid_cached : mClient->pid(),
565 mStreamType,
566 mFormat,
567 mChannelMask,
568 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800569 mFrameCount,
570 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800571 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800572 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700573 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
574 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700575 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000576 mMainBuffer,
577 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700578 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700579 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800580 nowInUnderrun);
581}
582
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800583uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
584 return mAudioTrackServerProxy->getSampleRate();
585}
586
Eric Laurent81784c32012-11-19 14:55:58 -0800587// AudioBufferProvider interface
588status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800589 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800590{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800591 ServerProxy::Buffer buf;
592 size_t desiredFrames = buffer->frameCount;
593 buf.mFrameCount = desiredFrames;
594 status_t status = mServerProxy->obtainBuffer(&buf);
595 buffer->frameCount = buf.mFrameCount;
596 buffer->raw = buf.mRaw;
597 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700598 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800599 } else {
600 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800601 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800602
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800603 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800604}
605
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700606// releaseBuffer() is not overridden
607
608// ExtendedAudioBufferProvider interface
609
Andy Hung27876c02014-09-09 18:07:55 -0700610// framesReady() may return an approximation of the number of frames if called
611// from a different thread than the one calling Proxy->obtainBuffer() and
612// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
613// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800614size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700615 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
616 // Static tracks return zero frames immediately upon stopping (for FastTracks).
617 // The remainder of the buffer is not drained.
618 return 0;
619 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800620 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800621}
622
Andy Hung818e7a32016-02-16 18:08:07 -0800623int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700624{
625 return mAudioTrackServerProxy->framesReleased();
626}
627
Andy Hung818e7a32016-02-16 18:08:07 -0800628void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800629{
630 // This call comes from a FastTrack and should be kept lockless.
631 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800632 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800633
Andy Hung818e7a32016-02-16 18:08:07 -0800634 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hung6ae58432016-02-16 18:32:24 -0800635}
636
Eric Laurent81784c32012-11-19 14:55:58 -0800637// Don't call for fast tracks; the framesReady() could result in priority inversion
638bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800639 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
640 return true;
641 }
642
Eric Laurent16498512014-03-17 17:22:08 -0700643 if (isStopping()) {
644 if (framesReady() > 0) {
645 mFillingUpStatus = FS_FILLED;
646 }
Eric Laurent81784c32012-11-19 14:55:58 -0800647 return true;
648 }
649
Phil Burke8972b02016-03-04 11:29:57 -0800650 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700651 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800652 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700653 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800654 return true;
655 }
656 return false;
657}
658
Glenn Kasten0f11b512014-01-31 16:18:54 -0800659status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800660 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800661{
662 status_t status = NO_ERROR;
663 ALOGV("start(%d), calling pid %d session %d",
664 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
665
666 sp<ThreadBase> thread = mThread.promote();
667 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700668 if (isOffloaded()) {
669 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
670 Mutex::Autolock _lth(thread->mLock);
671 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700672 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
673 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700674 invalidate();
675 return PERMISSION_DENIED;
676 }
677 }
678 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800679 track_state state = mState;
680 // here the track could be either new, or restarted
681 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800682
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800683 // initial state-stopping. next state-pausing.
684 // What if resume is called ?
685
686 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800687 if (mResumeToStopping) {
688 // happened we need to resume to STOPPING_1
689 mState = TrackBase::STOPPING_1;
690 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
691 } else {
692 mState = TrackBase::RESUMING;
693 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
694 }
Eric Laurent81784c32012-11-19 14:55:58 -0800695 } else {
696 mState = TrackBase::ACTIVE;
697 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
698 }
699
Andy Hunge10393e2015-06-12 13:59:33 -0700700 // states to reset position info for non-offloaded/direct tracks
701 if (!isOffloaded() && !isDirect()
702 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
703 mFrameMap.reset();
704 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800705 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700706 if (isFastTrack()) {
707 // refresh fast track underruns on start because that field is never cleared
708 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
709 // after stop.
710 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
711 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800712 status = playbackThread->addTrack_l(this);
713 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800714 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800715 // restore previous state if start was rejected by policy manager
716 if (status == PERMISSION_DENIED) {
717 mState = state;
718 }
719 }
720 // track was already in the active list, not a problem
721 if (status == ALREADY_EXISTS) {
722 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700723 } else {
724 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
725 // It is usually unsafe to access the server proxy from a binder thread.
726 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
727 // isn't looking at this track yet: we still hold the normal mixer thread lock,
728 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700729 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700730 ServerProxy::Buffer buffer;
731 buffer.mFrameCount = 1;
732 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800733 }
734 } else {
735 status = BAD_VALUE;
736 }
737 return status;
738}
739
740void AudioFlinger::PlaybackThread::Track::stop()
741{
742 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
743 sp<ThreadBase> thread = mThread.promote();
744 if (thread != 0) {
745 Mutex::Autolock _l(thread->mLock);
746 track_state state = mState;
747 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
748 // If the track is not active (PAUSED and buffers full), flush buffers
749 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
750 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
751 reset();
752 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700753 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800754 mState = STOPPED;
755 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800756 // For fast tracks prepareTracks_l() will set state to STOPPING_2
757 // presentation is complete
758 // For an offloaded track this starts a drain and state will
759 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800760 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -0700761 if (isOffloaded()) {
762 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
763 }
Eric Laurent81784c32012-11-19 14:55:58 -0800764 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700765 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800766 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
767 playbackThread);
768 }
Eric Laurent81784c32012-11-19 14:55:58 -0800769 }
770}
771
772void AudioFlinger::PlaybackThread::Track::pause()
773{
774 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
775 sp<ThreadBase> thread = mThread.promote();
776 if (thread != 0) {
777 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800778 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
779 switch (mState) {
780 case STOPPING_1:
781 case STOPPING_2:
782 if (!isOffloaded()) {
783 /* nothing to do if track is not offloaded */
784 break;
785 }
786
787 // Offloaded track was draining, we need to carry on draining when resumed
788 mResumeToStopping = true;
789 // fall through...
790 case ACTIVE:
791 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800792 mState = PAUSING;
793 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700794 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800795 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800796
Eric Laurentbfb1b832013-01-07 09:53:42 -0800797 default:
798 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800799 }
800 }
801}
802
803void AudioFlinger::PlaybackThread::Track::flush()
804{
805 ALOGV("flush(%d)", mName);
806 sp<ThreadBase> thread = mThread.promote();
807 if (thread != 0) {
808 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800809 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800810
811 if (isOffloaded()) {
812 // If offloaded we allow flush during any state except terminated
813 // and keep the track active to avoid problems if user is seeking
814 // rapidly and underlying hardware has a significant delay handling
815 // a pause
816 if (isTerminated()) {
817 return;
818 }
819
820 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800821 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800822
823 if (mState == STOPPING_1 || mState == STOPPING_2) {
824 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
825 mState = ACTIVE;
826 }
827
Haynes Mathew George7844f672014-01-15 12:32:55 -0800828 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800829 mResumeToStopping = false;
830 } else {
831 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
832 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
833 return;
834 }
835 // No point remaining in PAUSED state after a flush => go to
836 // FLUSHED state
837 mState = FLUSHED;
838 // do not reset the track if it is still in the process of being stopped or paused.
839 // this will be done by prepareTracks_l() when the track is stopped.
840 // prepareTracks_l() will see mState == FLUSHED, then
841 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800842 if (isDirect()) {
843 mFlushHwPending = true;
844 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800845 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
846 reset();
847 }
Eric Laurent81784c32012-11-19 14:55:58 -0800848 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800849 // Prevent flush being lost if the track is flushed and then resumed
850 // before mixer thread can run. This is important when offloading
851 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700852 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800853 }
854}
855
Haynes Mathew George7844f672014-01-15 12:32:55 -0800856// must be called with thread lock held
857void AudioFlinger::PlaybackThread::Track::flushAck()
858{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800859 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800860 return;
861
862 mFlushHwPending = false;
863}
864
Eric Laurent81784c32012-11-19 14:55:58 -0800865void AudioFlinger::PlaybackThread::Track::reset()
866{
867 // Do not reset twice to avoid discarding data written just after a flush and before
868 // the audioflinger thread detects the track is stopped.
869 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800870 // Force underrun condition to avoid false underrun callback until first data is
871 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700872 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800873 mFillingUpStatus = FS_FILLING;
874 mResetDone = true;
875 if (mState == FLUSHED) {
876 mState = IDLE;
877 }
878 }
879}
880
Eric Laurentbfb1b832013-01-07 09:53:42 -0800881status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
882{
883 sp<ThreadBase> thread = mThread.promote();
884 if (thread == 0) {
885 ALOGE("thread is dead");
886 return FAILED_TRANSACTION;
887 } else if ((thread->type() == ThreadBase::DIRECT) ||
888 (thread->type() == ThreadBase::OFFLOAD)) {
889 return thread->setParameters(keyValuePairs);
890 } else {
891 return PERMISSION_DENIED;
892 }
893}
894
Glenn Kasten573d80a2013-08-26 09:36:23 -0700895status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
896{
Andy Hung818e7a32016-02-16 18:08:07 -0800897 if (!isOffloaded() && !isDirect()) {
898 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700899 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700900 sp<ThreadBase> thread = mThread.promote();
901 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700902 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700903 }
Phil Burk6140c792015-03-19 14:30:21 -0700904
Glenn Kasten573d80a2013-08-26 09:36:23 -0700905 Mutex::Autolock _l(thread->mLock);
906 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -0800907 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700908}
909
Eric Laurent81784c32012-11-19 14:55:58 -0800910status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
911{
912 status_t status = DEAD_OBJECT;
913 sp<ThreadBase> thread = mThread.promote();
914 if (thread != 0) {
915 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
916 sp<AudioFlinger> af = mClient->audioFlinger();
917
918 Mutex::Autolock _l(af->mLock);
919
920 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
921
922 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
923 Mutex::Autolock _dl(playbackThread->mLock);
924 Mutex::Autolock _sl(srcThread->mLock);
925 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
926 if (chain == 0) {
927 return INVALID_OPERATION;
928 }
929
930 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
931 if (effect == 0) {
932 return INVALID_OPERATION;
933 }
934 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700935 status = playbackThread->addEffect_l(effect);
936 if (status != NO_ERROR) {
937 srcThread->addEffect_l(effect);
938 return INVALID_OPERATION;
939 }
Eric Laurent81784c32012-11-19 14:55:58 -0800940 // removeEffect_l() has stopped the effect if it was active so it must be restarted
941 if (effect->state() == EffectModule::ACTIVE ||
942 effect->state() == EffectModule::STOPPING) {
943 effect->start();
944 }
945
946 sp<EffectChain> dstChain = effect->chain().promote();
947 if (dstChain == 0) {
948 srcThread->addEffect_l(effect);
949 return INVALID_OPERATION;
950 }
951 AudioSystem::unregisterEffect(effect->id());
952 AudioSystem::registerEffect(&effect->desc(),
953 srcThread->id(),
954 dstChain->strategy(),
955 AUDIO_SESSION_OUTPUT_MIX,
956 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700957 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800958 }
959 status = playbackThread->attachAuxEffect(this, EffectId);
960 }
961 return status;
962}
963
964void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
965{
966 mAuxEffectId = EffectId;
967 mAuxBuffer = buffer;
968}
969
Andy Hung818e7a32016-02-16 18:08:07 -0800970bool AudioFlinger::PlaybackThread::Track::presentationComplete(
971 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -0800972{
Andy Hung818e7a32016-02-16 18:08:07 -0800973 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
974 // This assists in proper timestamp computation as well as wakelock management.
975
Eric Laurent81784c32012-11-19 14:55:58 -0800976 // a track is considered presented when the total number of frames written to audio HAL
977 // corresponds to the number of frames written when presentationComplete() is called for the
978 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800979 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
980 // to detect when all frames have been played. In this case framesWritten isn't
981 // useful because it doesn't always reflect whether there is data in the h/w
982 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung818e7a32016-02-16 18:08:07 -0800983 ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
984 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800985 if (mPresentationCompleteFrames == 0) {
986 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung818e7a32016-02-16 18:08:07 -0800987 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
988 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800989 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800990
Andy Hungc54b1ff2016-02-23 14:07:07 -0800991 bool complete;
992 if (isOffloaded()) {
993 complete = true;
994 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700995 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -0800996 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700997 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -0800998 && mAudioTrackServerProxy->isDrained();
999 }
1000
1001 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -08001002 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001003 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001004 return true;
1005 }
1006 return false;
1007}
1008
1009void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1010{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001011 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001012 if (mSyncEvents[i]->type() == type) {
1013 mSyncEvents[i]->trigger();
1014 mSyncEvents.removeAt(i);
1015 i--;
1016 }
1017 }
1018}
1019
1020// implement VolumeBufferProvider interface
1021
Glenn Kastenc56f3422014-03-21 17:53:17 -07001022gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001023{
1024 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1025 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001026 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1027 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1028 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001029 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001030 if (vl > GAIN_FLOAT_UNITY) {
1031 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001032 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001033 if (vr > GAIN_FLOAT_UNITY) {
1034 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001035 }
1036 // now apply the cached master volume and stream type volume;
1037 // this is trusted but lacks any synchronization or barrier so may be stale
1038 float v = mCachedVolume;
1039 vl *= v;
1040 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001041 // re-combine into packed minifloat
1042 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001043 // FIXME look at mute, pause, and stop flags
1044 return vlr;
1045}
1046
1047status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1048{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001049 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001050 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1051 (mState == STOPPED)))) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001052 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001053 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1054 event->cancel();
1055 return INVALID_OPERATION;
1056 }
1057 (void) TrackBase::setSyncEvent(event);
1058 return NO_ERROR;
1059}
1060
Glenn Kasten5736c352012-12-04 12:12:34 -08001061void AudioFlinger::PlaybackThread::Track::invalidate()
1062{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001063 signalClientFlag(CBLK_INVALID);
1064 mIsInvalid = true;
1065}
1066
1067void AudioFlinger::PlaybackThread::Track::disable()
1068{
1069 signalClientFlag(CBLK_DISABLED);
1070}
1071
1072void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1073{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001074 // FIXME should use proxy, and needs work
1075 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001076 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001077 android_atomic_release_store(0x40000000, &cblk->mFutex);
1078 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001079 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001080}
1081
Eric Laurent59fe0102013-09-27 18:48:26 -07001082void AudioFlinger::PlaybackThread::Track::signal()
1083{
1084 sp<ThreadBase> thread = mThread.promote();
1085 if (thread != 0) {
1086 PlaybackThread *t = (PlaybackThread *)thread.get();
1087 Mutex::Autolock _l(t->mLock);
1088 t->broadcast_l();
1089 }
1090}
1091
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001092//To be called with thread lock held
1093bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1094
1095 if (mState == RESUMING)
1096 return true;
1097 /* Resume is pending if track was stopping before pause was called */
1098 if (mState == STOPPING_1 &&
1099 mResumeToStopping)
1100 return true;
1101
1102 return false;
1103}
1104
1105//To be called with thread lock held
1106void AudioFlinger::PlaybackThread::Track::resumeAck() {
1107
1108
1109 if (mState == RESUMING)
1110 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001111
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001112 // Other possibility of pending resume is stopping_1 state
1113 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001114 // drain being called.
1115 if (mState == STOPPING_1) {
1116 mResumeToStopping = false;
1117 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001118}
Andy Hunge10393e2015-06-12 13:59:33 -07001119
1120//To be called with thread lock held
1121void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001122 int64_t trackFramesReleased, int64_t sinkFramesWritten,
1123 const ExtendedTimestamp &timeStamp) {
1124 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001125 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001126
1127 // adjust server times and set drained state.
1128 //
1129 // Our timestamps are only updated when the track is on the Thread active list.
1130 // We need to ensure that tracks are not removed before full drain.
1131 ExtendedTimestamp local = timeStamp;
1132 bool checked = false;
1133 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1134 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1135 // Lookup the track frame corresponding to the sink frame position.
1136 if (local.mTimeNs[i] > 0) {
1137 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1138 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001139 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hung818e7a32016-02-16 18:08:07 -08001140 mAudioTrackServerProxy->setDrained(
1141 local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1142 checked = true;
1143 }
1144 }
Andy Hunge10393e2015-06-12 13:59:33 -07001145 }
Andy Hung818e7a32016-02-16 18:08:07 -08001146 if (!checked) { // no server info, assume drained.
1147 mAudioTrackServerProxy->setDrained(true);
1148 }
Andy Hungea2b9c02016-02-12 17:06:53 -08001149 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001150 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001151 mServerProxy->setTimestamp(local);
Andy Hunge10393e2015-06-12 13:59:33 -07001152}
1153
Eric Laurent81784c32012-11-19 14:55:58 -08001154// ----------------------------------------------------------------------------
1155
Eric Laurent81784c32012-11-19 14:55:58 -08001156AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1157 PlaybackThread *playbackThread,
1158 DuplicatingThread *sourceThread,
1159 uint32_t sampleRate,
1160 audio_format_t format,
1161 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001162 size_t frameCount,
1163 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001164 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1165 sampleRate, format, channelMask, frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001166 NULL, 0, AUDIO_SESSION_NONE, uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001167 TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001168 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001169{
1170
1171 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001172 mOutBuffer.frameCount = 0;
1173 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001174 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001175 "frameCount %zu, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001176 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001177 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001178 // since client and server are in the same process,
1179 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001180 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1181 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001182 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001183 mClientProxy->setSendLevel(0.0);
1184 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001185 } else {
1186 ALOGW("Error creating output track on thread %p", playbackThread);
1187 }
1188}
1189
1190AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1191{
1192 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001193 delete mClientProxy;
1194 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001195}
1196
1197status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001198 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001199{
1200 status_t status = Track::start(event, triggerSession);
1201 if (status != NO_ERROR) {
1202 return status;
1203 }
1204
1205 mActive = true;
1206 mRetryCount = 127;
1207 return status;
1208}
1209
1210void AudioFlinger::PlaybackThread::OutputTrack::stop()
1211{
1212 Track::stop();
1213 clearBufferQueue();
1214 mOutBuffer.frameCount = 0;
1215 mActive = false;
1216}
1217
Andy Hungc25b84a2015-01-14 19:04:10 -08001218bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001219{
1220 Buffer *pInBuffer;
1221 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001222 bool outputBufferFull = false;
1223 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001224 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001225
1226 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1227
1228 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001229 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001230 }
1231
1232 while (waitTimeLeftMs) {
1233 // First write pending buffers, then new data
1234 if (mBufferQueue.size()) {
1235 pInBuffer = mBufferQueue.itemAt(0);
1236 } else {
1237 pInBuffer = &inBuffer;
1238 }
1239
1240 if (pInBuffer->frameCount == 0) {
1241 break;
1242 }
1243
1244 if (mOutBuffer.frameCount == 0) {
1245 mOutBuffer.frameCount = pInBuffer->frameCount;
1246 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001247 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001248 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1250 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001251 outputBufferFull = true;
1252 break;
1253 }
1254 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1255 if (waitTimeLeftMs >= waitTimeMs) {
1256 waitTimeLeftMs -= waitTimeMs;
1257 } else {
1258 waitTimeLeftMs = 0;
1259 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001260 if (status == NOT_ENOUGH_DATA) {
1261 restartIfDisabled();
1262 continue;
1263 }
Eric Laurent81784c32012-11-19 14:55:58 -08001264 }
1265
1266 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1267 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001268 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001269 Proxy::Buffer buf;
1270 buf.mFrameCount = outFrames;
1271 buf.mRaw = NULL;
1272 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001273 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001274 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001275 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001276 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001277 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001278
1279 if (pInBuffer->frameCount == 0) {
1280 if (mBufferQueue.size()) {
1281 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001282 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001283 delete pInBuffer;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001284 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001285 mThread.unsafe_get(), mBufferQueue.size());
1286 } else {
1287 break;
1288 }
1289 }
1290 }
1291
1292 // If we could not write all frames, allocate a buffer and queue it for next time.
1293 if (inBuffer.frameCount) {
1294 sp<ThreadBase> thread = mThread.promote();
1295 if (thread != 0 && !thread->standby()) {
1296 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1297 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001298 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001299 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001300 pInBuffer->raw = pInBuffer->mBuffer;
1301 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001302 mBufferQueue.add(pInBuffer);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001303 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001304 mThread.unsafe_get(), mBufferQueue.size());
1305 } else {
1306 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1307 mThread.unsafe_get(), this);
1308 }
1309 }
1310 }
1311
Andy Hungc25b84a2015-01-14 19:04:10 -08001312 // Calling write() with a 0 length buffer means that no more data will be written:
1313 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1314 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1315 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001316 }
1317
1318 return outputBufferFull;
1319}
1320
1321status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1322 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1323{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001324 ClientProxy::Buffer buf;
1325 buf.mFrameCount = buffer->frameCount;
1326 struct timespec timeout;
1327 timeout.tv_sec = waitTimeMs / 1000;
1328 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1329 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1330 buffer->frameCount = buf.mFrameCount;
1331 buffer->raw = buf.mRaw;
1332 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001333}
1334
Eric Laurent81784c32012-11-19 14:55:58 -08001335void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1336{
1337 size_t size = mBufferQueue.size();
1338
1339 for (size_t i = 0; i < size; i++) {
1340 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001341 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001342 delete pBuffer;
1343 }
1344 mBufferQueue.clear();
1345}
1346
Eric Laurent4d231dc2016-03-11 18:38:23 -08001347void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1348{
1349 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1350 if (mActive && (flags & CBLK_DISABLED)) {
1351 start();
1352 }
1353}
Eric Laurent81784c32012-11-19 14:55:58 -08001354
Eric Laurent83b88082014-06-20 18:31:16 -07001355AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001356 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001357 uint32_t sampleRate,
1358 audio_channel_mask_t channelMask,
1359 audio_format_t format,
1360 size_t frameCount,
1361 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001362 audio_output_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001363 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001364 sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001365 buffer, 0, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001366 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1367{
1368 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1369 playbackThread->sampleRate();
1370 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1371 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1372
1373 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1374 this, sampleRate,
1375 (int)mPeerTimeout.tv_sec,
1376 (int)(mPeerTimeout.tv_nsec / 1000000));
1377}
1378
1379AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1380{
1381}
1382
Eric Laurent4d231dc2016-03-11 18:38:23 -08001383status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001384 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001385{
1386 status_t status = Track::start(event, triggerSession);
1387 if (status != NO_ERROR) {
1388 return status;
1389 }
1390 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1391 return status;
1392}
1393
Eric Laurent83b88082014-06-20 18:31:16 -07001394// AudioBufferProvider interface
1395status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001396 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001397{
1398 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1399 Proxy::Buffer buf;
1400 buf.mFrameCount = buffer->frameCount;
1401 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1402 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001403 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001404 if (buf.mFrameCount == 0) {
1405 return WOULD_BLOCK;
1406 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001407 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001408 return status;
1409}
1410
1411void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1412{
1413 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1414 Proxy::Buffer buf;
1415 buf.mFrameCount = buffer->frameCount;
1416 buf.mRaw = buffer->raw;
1417 mPeerProxy->releaseBuffer(&buf);
1418 TrackBase::releaseBuffer(buffer);
1419}
1420
1421status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1422 const struct timespec *timeOut)
1423{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001424 status_t status = NO_ERROR;
1425 static const int32_t kMaxTries = 5;
1426 int32_t tryCounter = kMaxTries;
1427 do {
1428 if (status == NOT_ENOUGH_DATA) {
1429 restartIfDisabled();
1430 }
1431 status = mProxy->obtainBuffer(buffer, timeOut);
1432 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1433 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001434}
1435
1436void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1437{
1438 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001439 restartIfDisabled();
1440 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1441}
1442
1443void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1444{
Eric Laurent83b88082014-06-20 18:31:16 -07001445 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1446 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1447 start();
1448 }
Eric Laurent83b88082014-06-20 18:31:16 -07001449}
1450
Eric Laurent81784c32012-11-19 14:55:58 -08001451// ----------------------------------------------------------------------------
1452// Record
1453// ----------------------------------------------------------------------------
1454
1455AudioFlinger::RecordHandle::RecordHandle(
1456 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1457 : BnAudioRecord(),
1458 mRecordTrack(recordTrack)
1459{
1460}
1461
1462AudioFlinger::RecordHandle::~RecordHandle() {
1463 stop_nonvirtual();
1464 mRecordTrack->destroy();
1465}
1466
Eric Laurent81784c32012-11-19 14:55:58 -08001467status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001468 audio_session_t triggerSession) {
Eric Laurent81784c32012-11-19 14:55:58 -08001469 ALOGV("RecordHandle::start()");
1470 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1471}
1472
1473void AudioFlinger::RecordHandle::stop() {
1474 stop_nonvirtual();
1475}
1476
1477void AudioFlinger::RecordHandle::stop_nonvirtual() {
1478 ALOGV("RecordHandle::stop()");
1479 mRecordTrack->stop();
1480}
1481
1482status_t AudioFlinger::RecordHandle::onTransact(
1483 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1484{
1485 return BnAudioRecord::onTransact(code, data, reply, flags);
1486}
1487
1488// ----------------------------------------------------------------------------
1489
Glenn Kasten05997e22014-03-13 15:08:33 -07001490// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001491AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1492 RecordThread *thread,
1493 const sp<Client>& client,
1494 uint32_t sampleRate,
1495 audio_format_t format,
1496 audio_channel_mask_t channelMask,
1497 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001498 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001499 audio_session_t sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001500 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07001501 audio_input_flags_t flags,
Eric Laurent83b88082014-06-20 18:31:16 -07001502 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001503 : TrackBase(thread, client, sampleRate, format,
Eric Laurent05067782016-06-01 18:27:28 -07001504 channelMask, frameCount, buffer, sessionId, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001505 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001506 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001507 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1508 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001509 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001510 mFramesToDrop(0),
1511 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001512 mRecordBufferConverter(NULL),
1513 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001514{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001515 if (mCblk == NULL) {
1516 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001517 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001518
Andy Hung97a893e2015-03-29 01:03:07 -07001519 mRecordBufferConverter = new RecordBufferConverter(
1520 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1521 channelMask, format, sampleRate);
1522 // Check if the RecordBufferConverter construction was successful.
1523 // If not, don't continue with construction.
1524 //
1525 // NOTE: It would be extremely rare that the record track cannot be created
1526 // for the current device, but a pending or future device change would make
1527 // the record track configuration valid.
1528 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1529 ALOGE("RecordTrack unable to create record buffer converter");
1530 return;
1531 }
1532
Andy Hung6ae58432016-02-16 18:32:24 -08001533 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001534 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001535
Andy Hung97a893e2015-03-29 01:03:07 -07001536 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001537
Eric Laurent05067782016-06-01 18:27:28 -07001538 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001539 ALOG_ASSERT(thread->mFastTrackAvail);
1540 thread->mFastTrackAvail = false;
1541 }
Eric Laurent81784c32012-11-19 14:55:58 -08001542}
1543
1544AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1545{
1546 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001547 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001548 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001549}
1550
Andy Hung97a893e2015-03-29 01:03:07 -07001551status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1552{
1553 status_t status = TrackBase::initCheck();
1554 if (status == NO_ERROR && mServerProxy == 0) {
1555 status = BAD_VALUE;
1556 }
1557 return status;
1558}
1559
Eric Laurent81784c32012-11-19 14:55:58 -08001560// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001561status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001562{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001563 ServerProxy::Buffer buf;
1564 buf.mFrameCount = buffer->frameCount;
1565 status_t status = mServerProxy->obtainBuffer(&buf);
1566 buffer->frameCount = buf.mFrameCount;
1567 buffer->raw = buf.mRaw;
1568 if (buf.mFrameCount == 0) {
1569 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001570 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001571 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001572 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001573}
1574
1575status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001576 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001577{
1578 sp<ThreadBase> thread = mThread.promote();
1579 if (thread != 0) {
1580 RecordThread *recordThread = (RecordThread *)thread.get();
1581 return recordThread->start(this, event, triggerSession);
1582 } else {
1583 return BAD_VALUE;
1584 }
1585}
1586
1587void AudioFlinger::RecordThread::RecordTrack::stop()
1588{
1589 sp<ThreadBase> thread = mThread.promote();
1590 if (thread != 0) {
1591 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001592 if (recordThread->stop(this) && isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001593 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001594 }
1595 }
1596}
1597
1598void AudioFlinger::RecordThread::RecordTrack::destroy()
1599{
1600 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1601 sp<RecordTrack> keep(this);
1602 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001603 if (isExternalTrack()) {
1604 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001605 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001606 }
Glenn Kastend848eb42016-03-08 13:42:11 -08001607 AudioSystem::releaseInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001608 }
Eric Laurent81784c32012-11-19 14:55:58 -08001609 sp<ThreadBase> thread = mThread.promote();
1610 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001611 Mutex::Autolock _l(thread->mLock);
1612 RecordThread *recordThread = (RecordThread *) thread.get();
1613 recordThread->destroyTrack_l(this);
1614 }
1615 }
1616}
1617
Eric Laurent9a54bc22013-09-09 09:08:44 -07001618void AudioFlinger::RecordThread::RecordTrack::invalidate()
1619{
1620 // FIXME should use proxy, and needs work
1621 audio_track_cblk_t* cblk = mCblk;
1622 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1623 android_atomic_release_store(0x40000000, &cblk->mFutex);
1624 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001625 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001626}
1627
Eric Laurent81784c32012-11-19 14:55:58 -08001628
1629/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1630{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001631 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001632}
1633
Marco Nelissenb2208842014-02-07 14:00:50 -08001634void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001635{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001636 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001637 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001638 (mClient == 0) ? getpid_cached : mClient->pid(),
1639 mFormat,
1640 mChannelMask,
1641 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001642 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001643 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001644 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001645 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001646
Eric Laurent81784c32012-11-19 14:55:58 -08001647}
1648
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001649void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1650{
1651 if (event == mSyncStartEvent) {
1652 ssize_t framesToDrop = 0;
1653 sp<ThreadBase> threadBase = mThread.promote();
1654 if (threadBase != 0) {
1655 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1656 // from audio HAL
1657 framesToDrop = threadBase->mFrameCount * 2;
1658 }
1659 mFramesToDrop = framesToDrop;
1660 }
1661}
1662
1663void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1664{
1665 if (mSyncStartEvent != 0) {
1666 mSyncStartEvent->cancel();
1667 mSyncStartEvent.clear();
1668 }
1669 mFramesToDrop = 0;
1670}
1671
Andy Hung3f0c9022016-01-15 17:49:46 -08001672void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1673 int64_t trackFramesReleased, int64_t sourceFramesRead,
1674 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1675{
1676 ExtendedTimestamp local = timestamp;
1677
1678 // Convert HAL frames to server-side track frames at track sample rate.
1679 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1680 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1681 if (local.mTimeNs[i] != 0) {
1682 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1683 const int64_t relativeTrackFrames = relativeServerFrames
1684 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1685 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1686 }
1687 }
Andy Hung6ae58432016-02-16 18:32:24 -08001688 mServerProxy->setTimestamp(local);
Andy Hung3f0c9022016-01-15 17:49:46 -08001689}
Eric Laurent83b88082014-06-20 18:31:16 -07001690
1691AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1692 uint32_t sampleRate,
1693 audio_channel_mask_t channelMask,
1694 audio_format_t format,
1695 size_t frameCount,
1696 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001697 audio_input_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07001698 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001699 buffer, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001700 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1701{
1702 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1703 recordThread->sampleRate();
1704 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1705 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1706
1707 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1708 this, sampleRate,
1709 (int)mPeerTimeout.tv_sec,
1710 (int)(mPeerTimeout.tv_nsec / 1000000));
1711}
1712
1713AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1714{
1715}
1716
1717// AudioBufferProvider interface
1718status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001719 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001720{
1721 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1722 Proxy::Buffer buf;
1723 buf.mFrameCount = buffer->frameCount;
1724 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1725 ALOGV_IF(status != NO_ERROR,
1726 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001727 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001728 if (buf.mFrameCount == 0) {
1729 return WOULD_BLOCK;
1730 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001731 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001732 return status;
1733}
1734
1735void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1736{
1737 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1738 Proxy::Buffer buf;
1739 buf.mFrameCount = buffer->frameCount;
1740 buf.mRaw = buffer->raw;
1741 mPeerProxy->releaseBuffer(&buf);
1742 TrackBase::releaseBuffer(buffer);
1743}
1744
1745status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1746 const struct timespec *timeOut)
1747{
1748 return mProxy->obtainBuffer(buffer, timeOut);
1749}
1750
1751void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1752{
1753 mProxy->releaseBuffer(buffer);
1754}
1755
Glenn Kasten63238ef2015-03-02 15:50:29 -08001756} // namespace android