blob: f2dd8848ccbcbe7f3b1990a14ae8a5b881ffc056 [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 "AudioFlinger.h"
31#include "ServiceUtilities.h"
32
Glenn Kastenda6ef132013-01-10 12:31:01 -080033#include <media/nbaio/Pipe.h>
34#include <media/nbaio/PipeReader.h>
Andy Hung89816052017-01-11 17:08:23 -080035#include <media/RecordBufferConverter.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
Chih-Hung Hsieh9a3fbd92016-06-03 15:09:07 -070055#define TIME_TO_NANOS(time) ((uint64_t)(time).tv_sec * NANOS_PER_SECOND + (time).tv_nsec)
Andy Hunge10393e2015-06-12 13:59:33 -070056
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,
Andy Hung1f12a8a2016-11-07 16:10:30 -080075 uid_t clientUid,
Glenn Kastend776ac62014-05-07 09:16:09 -070076 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070077 alloc_type alloc,
Eric Laurent20b9ef02016-12-05 11:03:16 -080078 track_type type,
79 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -080080 : RefBase(),
81 mThread(thread),
82 mClient(client),
83 mCblk(NULL),
84 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080085 mState(IDLE),
86 mSampleRate(sampleRate),
87 mFormat(format),
88 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070089 mChannelCount(isOut ?
90 audio_channel_count_from_out_mask(channelMask) :
91 audio_channel_count_from_in_mask(channelMask)),
Phil Burkfdb3c072016-02-09 10:47:02 -080092 mFrameSize(audio_has_proportional_frames(format) ?
Eric Laurent81784c32012-11-19 14:55:58 -080093 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
94 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080095 mSessionId(sessionId),
96 mIsOut(isOut),
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),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800100 mThreadIoHandle(thread->id()),
101 mPortId(portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800102{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700103 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung1f12a8a2016-11-07 16:10:30 -0800104 if (!isTrustedCallingUid(callingUid) || clientUid == AUDIO_UID_INVALID) {
105 ALOGW_IF(clientUid != AUDIO_UID_INVALID && clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -0700106 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
Andy Hung1f12a8a2016-11-07 16:10:30 -0800107 clientUid = callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800108 }
109 // clientUid contains the uid of the app that is responsible for this track, so we can blame
110 // battery usage on it.
111 mUid = clientUid;
112
Eric Laurent81784c32012-11-19 14:55:58 -0800113 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
114 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700115 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
116 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800117 size += bufferSize;
118 }
119
120 if (client != 0) {
121 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700122 if (mCblkMemory == 0 ||
123 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700124 ALOGE("not enough memory for AudioTrack size=%zu", size);
Eric Laurent81784c32012-11-19 14:55:58 -0800125 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700126 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800127 return;
128 }
129 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800130 // this syntax avoids calling the audio_track_cblk_t constructor twice
131 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800132 // assume mCblk != NULL
133 }
134
135 // construct the shared structure in-place.
136 if (mCblk != NULL) {
137 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700138 switch (alloc) {
139 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700140 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
141 if (roHeap == 0 ||
142 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
143 (mBuffer = mBufferMemory->pointer()) == NULL) {
144 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
145 if (roHeap != 0) {
146 roHeap->dump("buffer");
147 }
148 mCblkMemory.clear();
149 mBufferMemory.clear();
150 return;
151 }
Eric Laurent81784c32012-11-19 14:55:58 -0800152 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700153 } break;
154 case ALLOC_PIPE:
155 mBufferMemory = thread->pipeMemory();
156 // mBuffer is the virtual address as seen from current process (mediaserver),
157 // and should normally be coming from mBufferMemory->pointer().
158 // However in this case the TrackBase does not reference the buffer directly.
159 // It should references the buffer via the pipe.
160 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
161 mBuffer = NULL;
162 break;
163 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700164 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700165 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700166 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
167 memset(mBuffer, 0, bufferSize);
168 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700169 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700171 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800172#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700173 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700174 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700175 case ALLOC_LOCAL:
176 mBuffer = calloc(1, bufferSize);
177 break;
178 case ALLOC_NONE:
179 mBuffer = buffer;
180 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800181 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800182
Glenn Kasten46909e72013-02-26 09:20:22 -0800183#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800184 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700185 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800186 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800187 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
188 size_t numCounterOffers = 0;
189 const NBAIO_Format offers[1] = {pipeFormat};
190 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
191 ALOG_ASSERT(index == 0);
192 PipeReader *pipeReader = new PipeReader(*pipe);
193 numCounterOffers = 0;
194 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
195 ALOG_ASSERT(index == 0);
196 mTeeSink = pipe;
197 mTeeSource = pipeReader;
198 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800200#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201
Eric Laurent81784c32012-11-19 14:55:58 -0800202 }
203}
204
Eric Laurent83b88082014-06-20 18:31:16 -0700205status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
206{
207 status_t status;
208 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
209 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
210 } else {
211 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
212 }
213 return status;
214}
215
Eric Laurent81784c32012-11-19 14:55:58 -0800216AudioFlinger::ThreadBase::TrackBase::~TrackBase()
217{
Glenn Kasten46909e72013-02-26 09:20:22 -0800218#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800219 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800220#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800221 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
Eric Laurent5bba2f62016-03-18 11:14:14 -0700222 mServerProxy.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800223 if (mCblk != NULL) {
224 if (mClient == 0) {
225 delete mCblk;
226 } else {
227 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
228 }
229 }
230 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
231 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700232 // Client destructor must run with AudioFlinger client mutex locked
233 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800234 // If the client's reference count drops to zero, the associated destructor
235 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
236 // relying on the automatic clear() at end of scope.
237 mClient.clear();
238 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700239 // flush the binder command buffer
240 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800241}
242
243// AudioBufferProvider interface
244// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800245// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800246void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
247{
Glenn Kasten46909e72013-02-26 09:20:22 -0800248#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800249 if (mTeeSink != 0) {
250 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
251 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800252#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800253
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800254 ServerProxy::Buffer buf;
255 buf.mFrameCount = buffer->frameCount;
256 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800257 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800258 buffer->raw = NULL;
259 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800260}
261
Eric Laurent81784c32012-11-19 14:55:58 -0800262status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
263{
264 mSyncEvents.add(event);
265 return NO_ERROR;
266}
267
268// ----------------------------------------------------------------------------
269// Playback
270// ----------------------------------------------------------------------------
271
272AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
273 : BnAudioTrack(),
274 mTrack(track)
275{
276}
277
278AudioFlinger::TrackHandle::~TrackHandle() {
279 // just stop the track on deletion, associated resources
280 // will be freed from the main thread once all pending buffers have
281 // been played. Unless it's not in the active track list, in which
282 // case we free everything now...
283 mTrack->destroy();
284}
285
286sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
287 return mTrack->getCblk();
288}
289
290status_t AudioFlinger::TrackHandle::start() {
291 return mTrack->start();
292}
293
294void AudioFlinger::TrackHandle::stop() {
295 mTrack->stop();
296}
297
298void AudioFlinger::TrackHandle::flush() {
299 mTrack->flush();
300}
301
Eric Laurent81784c32012-11-19 14:55:58 -0800302void AudioFlinger::TrackHandle::pause() {
303 mTrack->pause();
304}
305
306status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
307{
308 return mTrack->attachAuxEffect(EffectId);
309}
310
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700311status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
312 return mTrack->setParameters(keyValuePairs);
313}
314
Glenn Kasten53cec222013-08-29 09:01:02 -0700315status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
316{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700317 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700318}
319
Eric Laurent59fe0102013-09-27 18:48:26 -0700320
321void AudioFlinger::TrackHandle::signal()
322{
323 return mTrack->signal();
324}
325
Eric Laurent81784c32012-11-19 14:55:58 -0800326status_t AudioFlinger::TrackHandle::onTransact(
327 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
328{
329 return BnAudioTrack::onTransact(code, data, reply, flags);
330}
331
332// ----------------------------------------------------------------------------
333
334// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
335AudioFlinger::PlaybackThread::Track::Track(
336 PlaybackThread *thread,
337 const sp<Client>& client,
338 audio_stream_type_t streamType,
339 uint32_t sampleRate,
340 audio_format_t format,
341 audio_channel_mask_t channelMask,
342 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700343 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800344 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800345 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800346 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -0700347 audio_output_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800348 track_type type,
349 audio_port_handle_t portId)
Eric Laurent83b88082014-06-20 18:31:16 -0700350 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
351 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
Eric Laurent05067782016-06-01 18:27:28 -0700352 sessionId, uid, true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700353 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800354 type, portId),
Eric Laurent81784c32012-11-19 14:55:58 -0800355 mFillingUpStatus(FS_INVALID),
356 // mRetryCount initialized later when needed
357 mSharedBuffer(sharedBuffer),
358 mStreamType(streamType),
359 mName(-1), // see note below
360 mMainBuffer(thread->mixBuffer()),
361 mAuxBuffer(NULL),
362 mAuxEffectId(0), mHasVolumeController(false),
363 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700364 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Andy Hunge10393e2015-06-12 13:59:33 -0700365 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800366 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800367 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800368 mIsInvalid(false),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800369 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700370 mFlushHwPending(false),
371 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -0800372{
Eric Laurent83b88082014-06-20 18:31:16 -0700373 // client == 0 implies sharedBuffer == 0
374 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
375
Eric Laurente93cc032016-05-05 10:15:10 -0700376 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Eric Laurent83b88082014-06-20 18:31:16 -0700377 sharedBuffer->size());
378
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700379 if (mCblk == NULL) {
380 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800381 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700382
383 if (sharedBuffer == 0) {
384 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700385 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700386 } else {
387 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
388 mFrameSize);
389 }
390 mServerProxy = mAudioTrackServerProxy;
391
Eric Laurentad7dd962016-09-22 12:38:37 -0700392 mName = thread->getTrackName_l(channelMask, format, sessionId, uid);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700393 if (mName < 0) {
394 ALOGE("no more track names available");
395 return;
396 }
397 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700398 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700399 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
400 // race with setSyncEvent(). However, if we call it, we cannot properly start
401 // static fast tracks (SoundPool) immediately after stopping.
402 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700403 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
404 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700405 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700406 // FIXME This is too eager. We allocate a fast track index before the
407 // fast track becomes active. Since fast tracks are a scarce resource,
408 // this means we are potentially denying other more important fast tracks from
409 // being created. It would be better to allocate the index dynamically.
410 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700411 thread->mFastTrackAvailMask &= ~(1 << i);
412 }
Eric Laurent81784c32012-11-19 14:55:58 -0800413}
414
415AudioFlinger::PlaybackThread::Track::~Track()
416{
417 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700418
419 // The destructor would clear mSharedBuffer,
420 // but it will not push the decremented reference count,
421 // leaving the client's IMemory dangling indefinitely.
422 // This prevents that leak.
423 if (mSharedBuffer != 0) {
424 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700425 }
Eric Laurent81784c32012-11-19 14:55:58 -0800426}
427
Glenn Kasten03003332013-08-06 15:40:54 -0700428status_t AudioFlinger::PlaybackThread::Track::initCheck() const
429{
430 status_t status = TrackBase::initCheck();
431 if (status == NO_ERROR && mName < 0) {
432 status = NO_MEMORY;
433 }
434 return status;
435}
436
Eric Laurent81784c32012-11-19 14:55:58 -0800437void AudioFlinger::PlaybackThread::Track::destroy()
438{
439 // NOTE: destroyTrack_l() can remove a strong reference to this Track
440 // by removing it from mTracks vector, so there is a risk that this Tracks's
441 // destructor is called. As the destructor needs to lock mLock,
442 // we must acquire a strong reference on this Track before locking mLock
443 // here so that the destructor is called only when exiting this function.
444 // On the other hand, as long as Track::destroy() is only called by
445 // TrackHandle destructor, the TrackHandle still holds a strong ref on
446 // this Track with its member mTrack.
447 sp<Track> keep(this);
448 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700449 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800450 sp<ThreadBase> thread = mThread.promote();
451 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800452 Mutex::Autolock _l(thread->mLock);
453 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700454 wasActive = playbackThread->destroyTrack_l(this);
455 }
456 if (isExternalTrack() && !wasActive) {
Glenn Kastend848eb42016-03-08 13:42:11 -0800457 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800458 }
459 }
460}
461
462/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
463{
Marco Nelissenb2208842014-02-07 14:00:50 -0800464 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Andy Hung2148bf02016-11-28 19:01:02 -0800465 "L dB R dB Server Main buf Aux buf Flags UndFrmCnt Flushed\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800466}
467
Marco Nelissenb2208842014-02-07 14:00:50 -0800468void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800469{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700470 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800471 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800472 sprintf(buffer, " F %2d", mFastIndex);
473 } else if (mName >= AudioMixer::TRACK0) {
474 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800475 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800476 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800477 }
478 track_state state = mState;
479 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800480 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800481 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800482 } else {
483 switch (state) {
484 case IDLE:
485 stateChar = 'I';
486 break;
487 case STOPPING_1:
488 stateChar = 's';
489 break;
490 case STOPPING_2:
491 stateChar = '5';
492 break;
493 case STOPPED:
494 stateChar = 'S';
495 break;
496 case RESUMING:
497 stateChar = 'R';
498 break;
499 case ACTIVE:
500 stateChar = 'A';
501 break;
502 case PAUSING:
503 stateChar = 'p';
504 break;
505 case PAUSED:
506 stateChar = 'P';
507 break;
508 case FLUSHED:
509 stateChar = 'F';
510 break;
511 default:
512 stateChar = '?';
513 break;
514 }
Eric Laurent81784c32012-11-19 14:55:58 -0800515 }
516 char nowInUnderrun;
517 switch (mObservedUnderruns.mBitFields.mMostRecent) {
518 case UNDERRUN_FULL:
519 nowInUnderrun = ' ';
520 break;
521 case UNDERRUN_PARTIAL:
522 nowInUnderrun = '<';
523 break;
524 case UNDERRUN_EMPTY:
525 nowInUnderrun = '*';
526 break;
527 default:
528 nowInUnderrun = '?';
529 break;
530 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000531 snprintf(&buffer[8], size-8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u %5.2g %5.2g "
Andy Hung2148bf02016-11-28 19:01:02 -0800532 "%08X %08zX %08zX 0x%03X %9u%c %7u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800533 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800534 (mClient == 0) ? getpid_cached : mClient->pid(),
535 mStreamType,
536 mFormat,
537 mChannelMask,
538 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800539 mFrameCount,
540 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800541 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800542 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700543 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
544 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700545 mCblk->mServer,
Andy Hung2148bf02016-11-28 19:01:02 -0800546 (size_t)mMainBuffer, // use %zX as %p appends 0x
547 (size_t)mAuxBuffer, // use %zX as %p appends 0x
Glenn Kasten96f60d82013-07-12 10:21:18 -0700548 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700549 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -0800550 nowInUnderrun,
551 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000); // 7 digits
Eric Laurent81784c32012-11-19 14:55:58 -0800552}
553
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800554uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
555 return mAudioTrackServerProxy->getSampleRate();
556}
557
Eric Laurent81784c32012-11-19 14:55:58 -0800558// AudioBufferProvider interface
559status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800560 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800561{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800562 ServerProxy::Buffer buf;
563 size_t desiredFrames = buffer->frameCount;
564 buf.mFrameCount = desiredFrames;
565 status_t status = mServerProxy->obtainBuffer(&buf);
566 buffer->frameCount = buf.mFrameCount;
567 buffer->raw = buf.mRaw;
568 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700569 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800570 } else {
571 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800572 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800573
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800574 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800575}
576
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700577// releaseBuffer() is not overridden
578
579// ExtendedAudioBufferProvider interface
580
Andy Hung27876c02014-09-09 18:07:55 -0700581// framesReady() may return an approximation of the number of frames if called
582// from a different thread than the one calling Proxy->obtainBuffer() and
583// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
584// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800585size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700586 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
587 // Static tracks return zero frames immediately upon stopping (for FastTracks).
588 // The remainder of the buffer is not drained.
589 return 0;
590 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800591 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800592}
593
Andy Hung818e7a32016-02-16 18:08:07 -0800594int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700595{
596 return mAudioTrackServerProxy->framesReleased();
597}
598
Andy Hung818e7a32016-02-16 18:08:07 -0800599void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800600{
601 // This call comes from a FastTrack and should be kept lockless.
602 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800603 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800604
Andy Hung818e7a32016-02-16 18:08:07 -0800605 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hung6ae58432016-02-16 18:32:24 -0800606}
607
Eric Laurent81784c32012-11-19 14:55:58 -0800608// Don't call for fast tracks; the framesReady() could result in priority inversion
609bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800610 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
611 return true;
612 }
613
Eric Laurent16498512014-03-17 17:22:08 -0700614 if (isStopping()) {
615 if (framesReady() > 0) {
616 mFillingUpStatus = FS_FILLED;
617 }
Eric Laurent81784c32012-11-19 14:55:58 -0800618 return true;
619 }
620
Phil Burke8972b02016-03-04 11:29:57 -0800621 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700622 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800623 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700624 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800625 return true;
626 }
627 return false;
628}
629
Glenn Kasten0f11b512014-01-31 16:18:54 -0800630status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800631 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800632{
633 status_t status = NO_ERROR;
634 ALOGV("start(%d), calling pid %d session %d",
635 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
636
637 sp<ThreadBase> thread = mThread.promote();
638 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700639 if (isOffloaded()) {
640 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
641 Mutex::Autolock _lth(thread->mLock);
642 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700643 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
644 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700645 invalidate();
646 return PERMISSION_DENIED;
647 }
648 }
649 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800650 track_state state = mState;
651 // here the track could be either new, or restarted
652 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800653
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800654 // initial state-stopping. next state-pausing.
655 // What if resume is called ?
656
657 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800658 if (mResumeToStopping) {
659 // happened we need to resume to STOPPING_1
660 mState = TrackBase::STOPPING_1;
661 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
662 } else {
663 mState = TrackBase::RESUMING;
664 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
665 }
Eric Laurent81784c32012-11-19 14:55:58 -0800666 } else {
667 mState = TrackBase::ACTIVE;
668 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
669 }
670
Andy Hunge10393e2015-06-12 13:59:33 -0700671 // states to reset position info for non-offloaded/direct tracks
672 if (!isOffloaded() && !isDirect()
673 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
674 mFrameMap.reset();
675 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800676 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700677 if (isFastTrack()) {
678 // refresh fast track underruns on start because that field is never cleared
679 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
680 // after stop.
681 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
682 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800683 status = playbackThread->addTrack_l(this);
684 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800685 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800686 // restore previous state if start was rejected by policy manager
687 if (status == PERMISSION_DENIED) {
688 mState = state;
689 }
690 }
691 // track was already in the active list, not a problem
692 if (status == ALREADY_EXISTS) {
693 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700694 } else {
695 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
696 // It is usually unsafe to access the server proxy from a binder thread.
697 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
698 // isn't looking at this track yet: we still hold the normal mixer thread lock,
699 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700700 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700701 ServerProxy::Buffer buffer;
702 buffer.mFrameCount = 1;
703 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800704 }
705 } else {
706 status = BAD_VALUE;
707 }
708 return status;
709}
710
711void AudioFlinger::PlaybackThread::Track::stop()
712{
713 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
714 sp<ThreadBase> thread = mThread.promote();
715 if (thread != 0) {
716 Mutex::Autolock _l(thread->mLock);
717 track_state state = mState;
718 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
719 // If the track is not active (PAUSED and buffers full), flush buffers
720 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
721 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
722 reset();
723 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700724 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800725 mState = STOPPED;
726 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800727 // For fast tracks prepareTracks_l() will set state to STOPPING_2
728 // presentation is complete
729 // For an offloaded track this starts a drain and state will
730 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800731 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -0700732 if (isOffloaded()) {
733 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
734 }
Eric Laurent81784c32012-11-19 14:55:58 -0800735 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700736 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800737 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
738 playbackThread);
739 }
Eric Laurent81784c32012-11-19 14:55:58 -0800740 }
741}
742
743void AudioFlinger::PlaybackThread::Track::pause()
744{
745 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
746 sp<ThreadBase> thread = mThread.promote();
747 if (thread != 0) {
748 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800749 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
750 switch (mState) {
751 case STOPPING_1:
752 case STOPPING_2:
753 if (!isOffloaded()) {
754 /* nothing to do if track is not offloaded */
755 break;
756 }
757
758 // Offloaded track was draining, we need to carry on draining when resumed
759 mResumeToStopping = true;
760 // fall through...
761 case ACTIVE:
762 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800763 mState = PAUSING;
764 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700765 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800766 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800767
Eric Laurentbfb1b832013-01-07 09:53:42 -0800768 default:
769 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800770 }
771 }
772}
773
774void AudioFlinger::PlaybackThread::Track::flush()
775{
776 ALOGV("flush(%d)", mName);
777 sp<ThreadBase> thread = mThread.promote();
778 if (thread != 0) {
779 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800780 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800781
Phil Burk4bb650b2016-09-09 12:11:17 -0700782 // Flush the ring buffer now if the track is not active in the PlaybackThread.
783 // Otherwise the flush would not be done until the track is resumed.
784 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
785 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
786 (void)mServerProxy->flushBufferIfNeeded();
787 }
788
Eric Laurentbfb1b832013-01-07 09:53:42 -0800789 if (isOffloaded()) {
790 // If offloaded we allow flush during any state except terminated
791 // and keep the track active to avoid problems if user is seeking
792 // rapidly and underlying hardware has a significant delay handling
793 // a pause
794 if (isTerminated()) {
795 return;
796 }
797
798 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800799 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800800
801 if (mState == STOPPING_1 || mState == STOPPING_2) {
802 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
803 mState = ACTIVE;
804 }
805
Haynes Mathew George7844f672014-01-15 12:32:55 -0800806 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800807 mResumeToStopping = false;
808 } else {
809 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
810 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
811 return;
812 }
813 // No point remaining in PAUSED state after a flush => go to
814 // FLUSHED state
815 mState = FLUSHED;
816 // do not reset the track if it is still in the process of being stopped or paused.
817 // this will be done by prepareTracks_l() when the track is stopped.
818 // prepareTracks_l() will see mState == FLUSHED, then
819 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800820 if (isDirect()) {
821 mFlushHwPending = true;
822 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800823 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
824 reset();
825 }
Eric Laurent81784c32012-11-19 14:55:58 -0800826 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800827 // Prevent flush being lost if the track is flushed and then resumed
828 // before mixer thread can run. This is important when offloading
829 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700830 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800831 }
832}
833
Haynes Mathew George7844f672014-01-15 12:32:55 -0800834// must be called with thread lock held
835void AudioFlinger::PlaybackThread::Track::flushAck()
836{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800837 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800838 return;
839
Phil Burk4bb650b2016-09-09 12:11:17 -0700840 // Clear the client ring buffer so that the app can prime the buffer while paused.
841 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
842 mServerProxy->flushBufferIfNeeded();
843
Haynes Mathew George7844f672014-01-15 12:32:55 -0800844 mFlushHwPending = false;
845}
846
Eric Laurent81784c32012-11-19 14:55:58 -0800847void AudioFlinger::PlaybackThread::Track::reset()
848{
849 // Do not reset twice to avoid discarding data written just after a flush and before
850 // the audioflinger thread detects the track is stopped.
851 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800852 // Force underrun condition to avoid false underrun callback until first data is
853 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700854 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800855 mFillingUpStatus = FS_FILLING;
856 mResetDone = true;
857 if (mState == FLUSHED) {
858 mState = IDLE;
859 }
860 }
861}
862
Eric Laurentbfb1b832013-01-07 09:53:42 -0800863status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
864{
865 sp<ThreadBase> thread = mThread.promote();
866 if (thread == 0) {
867 ALOGE("thread is dead");
868 return FAILED_TRANSACTION;
869 } else if ((thread->type() == ThreadBase::DIRECT) ||
870 (thread->type() == ThreadBase::OFFLOAD)) {
871 return thread->setParameters(keyValuePairs);
872 } else {
873 return PERMISSION_DENIED;
874 }
875}
876
Glenn Kasten573d80a2013-08-26 09:36:23 -0700877status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
878{
Andy Hung818e7a32016-02-16 18:08:07 -0800879 if (!isOffloaded() && !isDirect()) {
880 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700881 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700882 sp<ThreadBase> thread = mThread.promote();
883 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700884 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700885 }
Phil Burk6140c792015-03-19 14:30:21 -0700886
Glenn Kasten573d80a2013-08-26 09:36:23 -0700887 Mutex::Autolock _l(thread->mLock);
888 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -0800889 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700890}
891
Eric Laurent81784c32012-11-19 14:55:58 -0800892status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
893{
894 status_t status = DEAD_OBJECT;
895 sp<ThreadBase> thread = mThread.promote();
896 if (thread != 0) {
897 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
898 sp<AudioFlinger> af = mClient->audioFlinger();
899
900 Mutex::Autolock _l(af->mLock);
901
902 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
903
904 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
905 Mutex::Autolock _dl(playbackThread->mLock);
906 Mutex::Autolock _sl(srcThread->mLock);
907 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
908 if (chain == 0) {
909 return INVALID_OPERATION;
910 }
911
912 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
913 if (effect == 0) {
914 return INVALID_OPERATION;
915 }
916 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700917 status = playbackThread->addEffect_l(effect);
918 if (status != NO_ERROR) {
919 srcThread->addEffect_l(effect);
920 return INVALID_OPERATION;
921 }
Eric Laurent81784c32012-11-19 14:55:58 -0800922 // removeEffect_l() has stopped the effect if it was active so it must be restarted
923 if (effect->state() == EffectModule::ACTIVE ||
924 effect->state() == EffectModule::STOPPING) {
925 effect->start();
926 }
927
928 sp<EffectChain> dstChain = effect->chain().promote();
929 if (dstChain == 0) {
930 srcThread->addEffect_l(effect);
931 return INVALID_OPERATION;
932 }
933 AudioSystem::unregisterEffect(effect->id());
934 AudioSystem::registerEffect(&effect->desc(),
935 srcThread->id(),
936 dstChain->strategy(),
937 AUDIO_SESSION_OUTPUT_MIX,
938 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700939 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800940 }
941 status = playbackThread->attachAuxEffect(this, EffectId);
942 }
943 return status;
944}
945
946void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
947{
948 mAuxEffectId = EffectId;
949 mAuxBuffer = buffer;
950}
951
Andy Hung818e7a32016-02-16 18:08:07 -0800952bool AudioFlinger::PlaybackThread::Track::presentationComplete(
953 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -0800954{
Andy Hung818e7a32016-02-16 18:08:07 -0800955 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
956 // This assists in proper timestamp computation as well as wakelock management.
957
Eric Laurent81784c32012-11-19 14:55:58 -0800958 // a track is considered presented when the total number of frames written to audio HAL
959 // corresponds to the number of frames written when presentationComplete() is called for the
960 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800961 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
962 // to detect when all frames have been played. In this case framesWritten isn't
963 // useful because it doesn't always reflect whether there is data in the h/w
964 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung818e7a32016-02-16 18:08:07 -0800965 ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
966 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800967 if (mPresentationCompleteFrames == 0) {
968 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung818e7a32016-02-16 18:08:07 -0800969 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
970 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800971 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800972
Andy Hungc54b1ff2016-02-23 14:07:07 -0800973 bool complete;
974 if (isOffloaded()) {
975 complete = true;
976 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700977 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -0800978 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700979 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -0800980 && mAudioTrackServerProxy->isDrained();
981 }
982
983 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -0800984 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800985 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800986 return true;
987 }
988 return false;
989}
990
991void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
992{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700993 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800994 if (mSyncEvents[i]->type() == type) {
995 mSyncEvents[i]->trigger();
996 mSyncEvents.removeAt(i);
997 i--;
998 }
999 }
1000}
1001
1002// implement VolumeBufferProvider interface
1003
Glenn Kastenc56f3422014-03-21 17:53:17 -07001004gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001005{
1006 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1007 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001008 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1009 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1010 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001011 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001012 if (vl > GAIN_FLOAT_UNITY) {
1013 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001014 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001015 if (vr > GAIN_FLOAT_UNITY) {
1016 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001017 }
1018 // now apply the cached master volume and stream type volume;
1019 // this is trusted but lacks any synchronization or barrier so may be stale
1020 float v = mCachedVolume;
1021 vl *= v;
1022 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001023 // re-combine into packed minifloat
1024 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001025 // FIXME look at mute, pause, and stop flags
1026 return vlr;
1027}
1028
1029status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1030{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001031 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001032 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1033 (mState == STOPPED)))) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001034 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001035 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1036 event->cancel();
1037 return INVALID_OPERATION;
1038 }
1039 (void) TrackBase::setSyncEvent(event);
1040 return NO_ERROR;
1041}
1042
Glenn Kasten5736c352012-12-04 12:12:34 -08001043void AudioFlinger::PlaybackThread::Track::invalidate()
1044{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001045 signalClientFlag(CBLK_INVALID);
1046 mIsInvalid = true;
1047}
1048
1049void AudioFlinger::PlaybackThread::Track::disable()
1050{
1051 signalClientFlag(CBLK_DISABLED);
1052}
1053
1054void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1055{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001056 // FIXME should use proxy, and needs work
1057 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001058 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001059 android_atomic_release_store(0x40000000, &cblk->mFutex);
1060 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001061 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001062}
1063
Eric Laurent59fe0102013-09-27 18:48:26 -07001064void AudioFlinger::PlaybackThread::Track::signal()
1065{
1066 sp<ThreadBase> thread = mThread.promote();
1067 if (thread != 0) {
1068 PlaybackThread *t = (PlaybackThread *)thread.get();
1069 Mutex::Autolock _l(t->mLock);
1070 t->broadcast_l();
1071 }
1072}
1073
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001074//To be called with thread lock held
1075bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1076
1077 if (mState == RESUMING)
1078 return true;
1079 /* Resume is pending if track was stopping before pause was called */
1080 if (mState == STOPPING_1 &&
1081 mResumeToStopping)
1082 return true;
1083
1084 return false;
1085}
1086
1087//To be called with thread lock held
1088void AudioFlinger::PlaybackThread::Track::resumeAck() {
1089
1090
1091 if (mState == RESUMING)
1092 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001093
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001094 // Other possibility of pending resume is stopping_1 state
1095 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001096 // drain being called.
1097 if (mState == STOPPING_1) {
1098 mResumeToStopping = false;
1099 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001100}
Andy Hunge10393e2015-06-12 13:59:33 -07001101
1102//To be called with thread lock held
1103void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001104 int64_t trackFramesReleased, int64_t sinkFramesWritten,
1105 const ExtendedTimestamp &timeStamp) {
1106 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001107 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001108
1109 // adjust server times and set drained state.
1110 //
1111 // Our timestamps are only updated when the track is on the Thread active list.
1112 // We need to ensure that tracks are not removed before full drain.
1113 ExtendedTimestamp local = timeStamp;
1114 bool checked = false;
1115 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1116 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1117 // Lookup the track frame corresponding to the sink frame position.
1118 if (local.mTimeNs[i] > 0) {
1119 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1120 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001121 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hung818e7a32016-02-16 18:08:07 -08001122 mAudioTrackServerProxy->setDrained(
1123 local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1124 checked = true;
1125 }
1126 }
Andy Hunge10393e2015-06-12 13:59:33 -07001127 }
Andy Hung818e7a32016-02-16 18:08:07 -08001128 if (!checked) { // no server info, assume drained.
1129 mAudioTrackServerProxy->setDrained(true);
1130 }
Andy Hungea2b9c02016-02-12 17:06:53 -08001131 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001132 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001133 mServerProxy->setTimestamp(local);
Andy Hunge10393e2015-06-12 13:59:33 -07001134}
1135
Eric Laurent81784c32012-11-19 14:55:58 -08001136// ----------------------------------------------------------------------------
1137
Eric Laurent81784c32012-11-19 14:55:58 -08001138AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1139 PlaybackThread *playbackThread,
1140 DuplicatingThread *sourceThread,
1141 uint32_t sampleRate,
1142 audio_format_t format,
1143 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001144 size_t frameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001145 uid_t uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001146 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1147 sampleRate, format, channelMask, frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001148 NULL, 0, AUDIO_SESSION_NONE, uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001149 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07001150 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08001151{
1152
1153 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001154 mOutBuffer.frameCount = 0;
1155 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001156 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001157 "frameCount %zu, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001158 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001159 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001160 // since client and server are in the same process,
1161 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001162 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1163 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001164 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001165 mClientProxy->setSendLevel(0.0);
1166 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001167 } else {
1168 ALOGW("Error creating output track on thread %p", playbackThread);
1169 }
1170}
1171
1172AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1173{
1174 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001175 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001176}
1177
1178status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001179 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001180{
1181 status_t status = Track::start(event, triggerSession);
1182 if (status != NO_ERROR) {
1183 return status;
1184 }
1185
1186 mActive = true;
1187 mRetryCount = 127;
1188 return status;
1189}
1190
1191void AudioFlinger::PlaybackThread::OutputTrack::stop()
1192{
1193 Track::stop();
1194 clearBufferQueue();
1195 mOutBuffer.frameCount = 0;
1196 mActive = false;
1197}
1198
Andy Hungc25b84a2015-01-14 19:04:10 -08001199bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001200{
1201 Buffer *pInBuffer;
1202 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001203 bool outputBufferFull = false;
1204 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001205 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001206
1207 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1208
1209 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001210 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001211 }
1212
1213 while (waitTimeLeftMs) {
1214 // First write pending buffers, then new data
1215 if (mBufferQueue.size()) {
1216 pInBuffer = mBufferQueue.itemAt(0);
1217 } else {
1218 pInBuffer = &inBuffer;
1219 }
1220
1221 if (pInBuffer->frameCount == 0) {
1222 break;
1223 }
1224
1225 if (mOutBuffer.frameCount == 0) {
1226 mOutBuffer.frameCount = pInBuffer->frameCount;
1227 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001228 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001229 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001230 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1231 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001232 outputBufferFull = true;
1233 break;
1234 }
1235 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1236 if (waitTimeLeftMs >= waitTimeMs) {
1237 waitTimeLeftMs -= waitTimeMs;
1238 } else {
1239 waitTimeLeftMs = 0;
1240 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001241 if (status == NOT_ENOUGH_DATA) {
1242 restartIfDisabled();
1243 continue;
1244 }
Eric Laurent81784c32012-11-19 14:55:58 -08001245 }
1246
1247 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1248 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001249 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001250 Proxy::Buffer buf;
1251 buf.mFrameCount = outFrames;
1252 buf.mRaw = NULL;
1253 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001254 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001255 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001256 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001257 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001258 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001259
1260 if (pInBuffer->frameCount == 0) {
1261 if (mBufferQueue.size()) {
1262 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001263 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001264 delete pInBuffer;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001265 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001266 mThread.unsafe_get(), mBufferQueue.size());
1267 } else {
1268 break;
1269 }
1270 }
1271 }
1272
1273 // If we could not write all frames, allocate a buffer and queue it for next time.
1274 if (inBuffer.frameCount) {
1275 sp<ThreadBase> thread = mThread.promote();
1276 if (thread != 0 && !thread->standby()) {
1277 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1278 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001279 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001280 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001281 pInBuffer->raw = pInBuffer->mBuffer;
1282 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001283 mBufferQueue.add(pInBuffer);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001284 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001285 mThread.unsafe_get(), mBufferQueue.size());
1286 } else {
1287 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1288 mThread.unsafe_get(), this);
1289 }
1290 }
1291 }
1292
Andy Hungc25b84a2015-01-14 19:04:10 -08001293 // Calling write() with a 0 length buffer means that no more data will be written:
1294 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1295 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1296 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001297 }
1298
1299 return outputBufferFull;
1300}
1301
1302status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1303 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1304{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001305 ClientProxy::Buffer buf;
1306 buf.mFrameCount = buffer->frameCount;
1307 struct timespec timeout;
1308 timeout.tv_sec = waitTimeMs / 1000;
1309 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1310 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1311 buffer->frameCount = buf.mFrameCount;
1312 buffer->raw = buf.mRaw;
1313 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001314}
1315
Eric Laurent81784c32012-11-19 14:55:58 -08001316void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1317{
1318 size_t size = mBufferQueue.size();
1319
1320 for (size_t i = 0; i < size; i++) {
1321 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001322 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001323 delete pBuffer;
1324 }
1325 mBufferQueue.clear();
1326}
1327
Eric Laurent4d231dc2016-03-11 18:38:23 -08001328void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1329{
1330 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1331 if (mActive && (flags & CBLK_DISABLED)) {
1332 start();
1333 }
1334}
Eric Laurent81784c32012-11-19 14:55:58 -08001335
Eric Laurent83b88082014-06-20 18:31:16 -07001336AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001337 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001338 uint32_t sampleRate,
1339 audio_channel_mask_t channelMask,
1340 audio_format_t format,
1341 size_t frameCount,
1342 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001343 audio_output_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001344 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001345 sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001346 buffer, 0, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001347 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1348{
1349 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1350 playbackThread->sampleRate();
1351 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1352 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1353
1354 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1355 this, sampleRate,
1356 (int)mPeerTimeout.tv_sec,
1357 (int)(mPeerTimeout.tv_nsec / 1000000));
1358}
1359
1360AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1361{
1362}
1363
Eric Laurent4d231dc2016-03-11 18:38:23 -08001364status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001365 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001366{
1367 status_t status = Track::start(event, triggerSession);
1368 if (status != NO_ERROR) {
1369 return status;
1370 }
1371 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1372 return status;
1373}
1374
Eric Laurent83b88082014-06-20 18:31:16 -07001375// AudioBufferProvider interface
1376status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001377 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001378{
1379 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1380 Proxy::Buffer buf;
1381 buf.mFrameCount = buffer->frameCount;
1382 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1383 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001384 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001385 if (buf.mFrameCount == 0) {
1386 return WOULD_BLOCK;
1387 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001388 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001389 return status;
1390}
1391
1392void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1393{
1394 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1395 Proxy::Buffer buf;
1396 buf.mFrameCount = buffer->frameCount;
1397 buf.mRaw = buffer->raw;
1398 mPeerProxy->releaseBuffer(&buf);
1399 TrackBase::releaseBuffer(buffer);
1400}
1401
1402status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1403 const struct timespec *timeOut)
1404{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001405 status_t status = NO_ERROR;
1406 static const int32_t kMaxTries = 5;
1407 int32_t tryCounter = kMaxTries;
1408 do {
1409 if (status == NOT_ENOUGH_DATA) {
1410 restartIfDisabled();
1411 }
1412 status = mProxy->obtainBuffer(buffer, timeOut);
1413 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1414 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001415}
1416
1417void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1418{
1419 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001420 restartIfDisabled();
1421 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1422}
1423
1424void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1425{
Eric Laurent83b88082014-06-20 18:31:16 -07001426 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1427 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1428 start();
1429 }
Eric Laurent83b88082014-06-20 18:31:16 -07001430}
1431
Eric Laurent81784c32012-11-19 14:55:58 -08001432// ----------------------------------------------------------------------------
1433// Record
1434// ----------------------------------------------------------------------------
1435
1436AudioFlinger::RecordHandle::RecordHandle(
1437 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1438 : BnAudioRecord(),
1439 mRecordTrack(recordTrack)
1440{
1441}
1442
1443AudioFlinger::RecordHandle::~RecordHandle() {
1444 stop_nonvirtual();
1445 mRecordTrack->destroy();
1446}
1447
Eric Laurent81784c32012-11-19 14:55:58 -08001448status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001449 audio_session_t triggerSession) {
Eric Laurent81784c32012-11-19 14:55:58 -08001450 ALOGV("RecordHandle::start()");
1451 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1452}
1453
1454void AudioFlinger::RecordHandle::stop() {
1455 stop_nonvirtual();
1456}
1457
1458void AudioFlinger::RecordHandle::stop_nonvirtual() {
1459 ALOGV("RecordHandle::stop()");
1460 mRecordTrack->stop();
1461}
1462
1463status_t AudioFlinger::RecordHandle::onTransact(
1464 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1465{
1466 return BnAudioRecord::onTransact(code, data, reply, flags);
1467}
1468
1469// ----------------------------------------------------------------------------
1470
Glenn Kasten05997e22014-03-13 15:08:33 -07001471// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001472AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1473 RecordThread *thread,
1474 const sp<Client>& client,
1475 uint32_t sampleRate,
1476 audio_format_t format,
1477 audio_channel_mask_t channelMask,
1478 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001479 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001480 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001481 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001482 audio_input_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001483 track_type type,
1484 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001485 : TrackBase(thread, client, sampleRate, format,
Eric Laurent05067782016-06-01 18:27:28 -07001486 channelMask, frameCount, buffer, sessionId, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001487 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001488 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001489 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
Eric Laurent20b9ef02016-12-05 11:03:16 -08001490 type, portId),
Andy Hung97a893e2015-03-29 01:03:07 -07001491 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001492 mFramesToDrop(0),
1493 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001494 mRecordBufferConverter(NULL),
1495 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001496{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001497 if (mCblk == NULL) {
1498 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001499 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001500
Andy Hung97a893e2015-03-29 01:03:07 -07001501 mRecordBufferConverter = new RecordBufferConverter(
1502 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1503 channelMask, format, sampleRate);
1504 // Check if the RecordBufferConverter construction was successful.
1505 // If not, don't continue with construction.
1506 //
1507 // NOTE: It would be extremely rare that the record track cannot be created
1508 // for the current device, but a pending or future device change would make
1509 // the record track configuration valid.
1510 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1511 ALOGE("RecordTrack unable to create record buffer converter");
1512 return;
1513 }
1514
Andy Hung6ae58432016-02-16 18:32:24 -08001515 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001516 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001517
Andy Hung97a893e2015-03-29 01:03:07 -07001518 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001519
Eric Laurent05067782016-06-01 18:27:28 -07001520 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001521 ALOG_ASSERT(thread->mFastTrackAvail);
1522 thread->mFastTrackAvail = false;
1523 }
Eric Laurent81784c32012-11-19 14:55:58 -08001524}
1525
1526AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1527{
1528 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001529 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001530 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001531}
1532
Andy Hung97a893e2015-03-29 01:03:07 -07001533status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1534{
1535 status_t status = TrackBase::initCheck();
1536 if (status == NO_ERROR && mServerProxy == 0) {
1537 status = BAD_VALUE;
1538 }
1539 return status;
1540}
1541
Eric Laurent81784c32012-11-19 14:55:58 -08001542// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001543status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001544{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001545 ServerProxy::Buffer buf;
1546 buf.mFrameCount = buffer->frameCount;
1547 status_t status = mServerProxy->obtainBuffer(&buf);
1548 buffer->frameCount = buf.mFrameCount;
1549 buffer->raw = buf.mRaw;
1550 if (buf.mFrameCount == 0) {
1551 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001552 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001553 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001554 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001555}
1556
1557status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001558 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001559{
1560 sp<ThreadBase> thread = mThread.promote();
1561 if (thread != 0) {
1562 RecordThread *recordThread = (RecordThread *)thread.get();
1563 return recordThread->start(this, event, triggerSession);
1564 } else {
1565 return BAD_VALUE;
1566 }
1567}
1568
1569void AudioFlinger::RecordThread::RecordTrack::stop()
1570{
1571 sp<ThreadBase> thread = mThread.promote();
1572 if (thread != 0) {
1573 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001574 if (recordThread->stop(this) && isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001575 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001576 }
1577 }
1578}
1579
1580void AudioFlinger::RecordThread::RecordTrack::destroy()
1581{
1582 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1583 sp<RecordTrack> keep(this);
1584 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001585 if (isExternalTrack()) {
1586 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001587 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001588 }
Glenn Kastend848eb42016-03-08 13:42:11 -08001589 AudioSystem::releaseInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001590 }
Eric Laurent81784c32012-11-19 14:55:58 -08001591 sp<ThreadBase> thread = mThread.promote();
1592 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001593 Mutex::Autolock _l(thread->mLock);
1594 RecordThread *recordThread = (RecordThread *) thread.get();
1595 recordThread->destroyTrack_l(this);
1596 }
1597 }
1598}
1599
Eric Laurent9a54bc22013-09-09 09:08:44 -07001600void AudioFlinger::RecordThread::RecordTrack::invalidate()
1601{
1602 // FIXME should use proxy, and needs work
1603 audio_track_cblk_t* cblk = mCblk;
1604 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1605 android_atomic_release_store(0x40000000, &cblk->mFutex);
1606 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001607 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001608}
1609
Eric Laurent81784c32012-11-19 14:55:58 -08001610
1611/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1612{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001613 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001614}
1615
Marco Nelissenb2208842014-02-07 14:00:50 -08001616void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001617{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001618 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001619 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001620 (mClient == 0) ? getpid_cached : mClient->pid(),
1621 mFormat,
1622 mChannelMask,
1623 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001624 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001625 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001626 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001627 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001628
Eric Laurent81784c32012-11-19 14:55:58 -08001629}
1630
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001631void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1632{
1633 if (event == mSyncStartEvent) {
1634 ssize_t framesToDrop = 0;
1635 sp<ThreadBase> threadBase = mThread.promote();
1636 if (threadBase != 0) {
1637 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1638 // from audio HAL
1639 framesToDrop = threadBase->mFrameCount * 2;
1640 }
1641 mFramesToDrop = framesToDrop;
1642 }
1643}
1644
1645void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1646{
1647 if (mSyncStartEvent != 0) {
1648 mSyncStartEvent->cancel();
1649 mSyncStartEvent.clear();
1650 }
1651 mFramesToDrop = 0;
1652}
1653
Andy Hung3f0c9022016-01-15 17:49:46 -08001654void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1655 int64_t trackFramesReleased, int64_t sourceFramesRead,
1656 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1657{
1658 ExtendedTimestamp local = timestamp;
1659
1660 // Convert HAL frames to server-side track frames at track sample rate.
1661 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1662 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1663 if (local.mTimeNs[i] != 0) {
1664 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1665 const int64_t relativeTrackFrames = relativeServerFrames
1666 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1667 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1668 }
1669 }
Andy Hung6ae58432016-02-16 18:32:24 -08001670 mServerProxy->setTimestamp(local);
Andy Hung3f0c9022016-01-15 17:49:46 -08001671}
Eric Laurent83b88082014-06-20 18:31:16 -07001672
1673AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1674 uint32_t sampleRate,
1675 audio_channel_mask_t channelMask,
1676 audio_format_t format,
1677 size_t frameCount,
1678 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001679 audio_input_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07001680 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001681 buffer, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001682 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1683{
1684 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1685 recordThread->sampleRate();
1686 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1687 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1688
1689 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1690 this, sampleRate,
1691 (int)mPeerTimeout.tv_sec,
1692 (int)(mPeerTimeout.tv_nsec / 1000000));
1693}
1694
1695AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1696{
1697}
1698
1699// AudioBufferProvider interface
1700status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001701 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001702{
1703 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1704 Proxy::Buffer buf;
1705 buf.mFrameCount = buffer->frameCount;
1706 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1707 ALOGV_IF(status != NO_ERROR,
1708 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001709 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001710 if (buf.mFrameCount == 0) {
1711 return WOULD_BLOCK;
1712 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001713 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001714 return status;
1715}
1716
1717void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1718{
1719 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1720 Proxy::Buffer buf;
1721 buf.mFrameCount = buffer->frameCount;
1722 buf.mRaw = buffer->raw;
1723 mPeerProxy->releaseBuffer(&buf);
1724 TrackBase::releaseBuffer(buffer);
1725}
1726
1727status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1728 const struct timespec *timeOut)
1729{
1730 return mProxy->obtainBuffer(buffer, timeOut);
1731}
1732
1733void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1734{
1735 mProxy->releaseBuffer(buffer);
1736}
1737
Glenn Kasten63238ef2015-03-02 15:50:29 -08001738} // namespace android