blob: 37c5764961092e5ec5a4d2cce38fb1915278551a [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,
Andy Hung8fe68032017-06-05 16:17:51 -070074 size_t bufferSize,
Glenn Kastend848eb42016-03-08 13:42:11 -080075 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -080076 uid_t clientUid,
Glenn Kastend776ac62014-05-07 09:16:09 -070077 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070078 alloc_type alloc,
Eric Laurent20b9ef02016-12-05 11:03:16 -080079 track_type type,
80 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -080081 : RefBase(),
82 mThread(thread),
83 mClient(client),
84 mCblk(NULL),
Andy Hung8fe68032017-06-05 16:17:51 -070085 // mBuffer, mBufferSize
Eric Laurent81784c32012-11-19 14:55:58 -080086 mState(IDLE),
87 mSampleRate(sampleRate),
88 mFormat(format),
89 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070090 mChannelCount(isOut ?
91 audio_channel_count_from_out_mask(channelMask) :
92 audio_channel_count_from_in_mask(channelMask)),
Phil Burkfdb3c072016-02-09 10:47:02 -080093 mFrameSize(audio_has_proportional_frames(format) ?
Eric Laurent81784c32012-11-19 14:55:58 -080094 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
95 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080096 mSessionId(sessionId),
97 mIsOut(isOut),
Eric Laurentbfb1b832013-01-07 09:53:42 -080098 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070099 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -0700100 mType(type),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800101 mThreadIoHandle(thread->id()),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800102 mPortId(portId),
103 mIsInvalid(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800104{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700105 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung1f12a8a2016-11-07 16:10:30 -0800106 if (!isTrustedCallingUid(callingUid) || clientUid == AUDIO_UID_INVALID) {
107 ALOGW_IF(clientUid != AUDIO_UID_INVALID && clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -0700108 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
Andy Hung1f12a8a2016-11-07 16:10:30 -0800109 clientUid = callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800110 }
111 // clientUid contains the uid of the app that is responsible for this track, so we can blame
112 // battery usage on it.
113 mUid = clientUid;
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hung1883f692017-02-13 18:48:39 -0800116
Andy Hung8fe68032017-06-05 16:17:51 -0700117 size_t minBufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
Andy Hung1883f692017-02-13 18:48:39 -0800118 // check overflow when computing bufferSize due to multiplication by mFrameSize.
Andy Hung8fe68032017-06-05 16:17:51 -0700119 if (minBufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
Andy Hung1883f692017-02-13 18:48:39 -0800120 || mFrameSize == 0 // format needs to be correct
Andy Hung8fe68032017-06-05 16:17:51 -0700121 || minBufferSize > SIZE_MAX / mFrameSize) {
Andy Hung1883f692017-02-13 18:48:39 -0800122 android_errorWriteLog(0x534e4554, "34749571");
123 return;
124 }
Andy Hung8fe68032017-06-05 16:17:51 -0700125 minBufferSize *= mFrameSize;
126
127 if (buffer == nullptr) {
128 bufferSize = minBufferSize; // allocated here.
129 } else if (minBufferSize > bufferSize) {
130 android_errorWriteLog(0x534e4554, "38340117");
131 return;
132 }
Andy Hung1883f692017-02-13 18:48:39 -0800133
Eric Laurent81784c32012-11-19 14:55:58 -0800134 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700135 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hung1883f692017-02-13 18:48:39 -0800136 // check overflow when computing allocation size for streaming tracks.
137 if (size > SIZE_MAX - bufferSize) {
138 android_errorWriteLog(0x534e4554, "34749571");
139 return;
140 }
Eric Laurent81784c32012-11-19 14:55:58 -0800141 size += bufferSize;
142 }
143
144 if (client != 0) {
145 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700146 if (mCblkMemory == 0 ||
147 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700148 ALOGE("not enough memory for AudioTrack size=%zu", size);
Eric Laurent81784c32012-11-19 14:55:58 -0800149 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700150 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800151 return;
152 }
153 } else {
Andy Hungafb31482017-02-13 18:50:48 -0800154 mCblk = (audio_track_cblk_t *) malloc(size);
155 if (mCblk == NULL) {
156 ALOGE("not enough memory for AudioTrack size=%zu", size);
157 return;
158 }
Eric Laurent81784c32012-11-19 14:55:58 -0800159 }
160
161 // construct the shared structure in-place.
162 if (mCblk != NULL) {
163 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700164 switch (alloc) {
165 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700166 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
167 if (roHeap == 0 ||
168 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
169 (mBuffer = mBufferMemory->pointer()) == NULL) {
170 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
171 if (roHeap != 0) {
172 roHeap->dump("buffer");
173 }
174 mCblkMemory.clear();
175 mBufferMemory.clear();
176 return;
177 }
Eric Laurent81784c32012-11-19 14:55:58 -0800178 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700179 } break;
180 case ALLOC_PIPE:
181 mBufferMemory = thread->pipeMemory();
182 // mBuffer is the virtual address as seen from current process (mediaserver),
183 // and should normally be coming from mBufferMemory->pointer().
184 // However in this case the TrackBase does not reference the buffer directly.
185 // It should references the buffer via the pipe.
186 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
187 mBuffer = NULL;
Andy Hung8fe68032017-06-05 16:17:51 -0700188 bufferSize = 0;
Glenn Kastenc263ca02014-06-04 20:31:46 -0700189 break;
190 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700191 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700192 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700193 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
194 memset(mBuffer, 0, bufferSize);
195 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700196 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800197#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700198 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800199#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700200 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700201 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700202 case ALLOC_LOCAL:
203 mBuffer = calloc(1, bufferSize);
204 break;
205 case ALLOC_NONE:
206 mBuffer = buffer;
207 break;
Andy Hung8fe68032017-06-05 16:17:51 -0700208 default:
209 LOG_ALWAYS_FATAL("invalid allocation type: %d", (int)alloc);
Eric Laurent81784c32012-11-19 14:55:58 -0800210 }
Andy Hung8fe68032017-06-05 16:17:51 -0700211 mBufferSize = bufferSize;
Glenn Kastenda6ef132013-01-10 12:31:01 -0800212
Glenn Kasten46909e72013-02-26 09:20:22 -0800213#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800214 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700215 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800216 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800217 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
218 size_t numCounterOffers = 0;
219 const NBAIO_Format offers[1] = {pipeFormat};
220 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
221 ALOG_ASSERT(index == 0);
222 PipeReader *pipeReader = new PipeReader(*pipe);
223 numCounterOffers = 0;
224 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
225 ALOG_ASSERT(index == 0);
226 mTeeSink = pipe;
227 mTeeSource = pipeReader;
228 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800229 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800230#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800231
Eric Laurent81784c32012-11-19 14:55:58 -0800232 }
233}
234
Eric Laurent83b88082014-06-20 18:31:16 -0700235status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
236{
237 status_t status;
238 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
239 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
240 } else {
241 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
242 }
243 return status;
244}
245
Eric Laurent81784c32012-11-19 14:55:58 -0800246AudioFlinger::ThreadBase::TrackBase::~TrackBase()
247{
Glenn Kasten46909e72013-02-26 09:20:22 -0800248#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700249 dumpTee(-1, mTeeSource, mId, 'T');
Glenn Kasten46909e72013-02-26 09:20:22 -0800250#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800251 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
Eric Laurent5bba2f62016-03-18 11:14:14 -0700252 mServerProxy.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800253 if (mCblk != NULL) {
Andy Hungafb31482017-02-13 18:50:48 -0800254 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurent81784c32012-11-19 14:55:58 -0800255 if (mClient == 0) {
Andy Hungafb31482017-02-13 18:50:48 -0800256 free(mCblk);
Eric Laurent81784c32012-11-19 14:55:58 -0800257 }
258 }
259 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
260 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700261 // Client destructor must run with AudioFlinger client mutex locked
262 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800263 // If the client's reference count drops to zero, the associated destructor
264 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
265 // relying on the automatic clear() at end of scope.
266 mClient.clear();
267 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700268 // flush the binder command buffer
269 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800270}
271
272// AudioBufferProvider interface
273// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800274// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800275void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
276{
Glenn Kasten46909e72013-02-26 09:20:22 -0800277#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800278 if (mTeeSink != 0) {
279 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
280 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800281#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800282
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800283 ServerProxy::Buffer buf;
284 buf.mFrameCount = buffer->frameCount;
285 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800286 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800287 buffer->raw = NULL;
288 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800289}
290
Eric Laurent81784c32012-11-19 14:55:58 -0800291status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
292{
293 mSyncEvents.add(event);
294 return NO_ERROR;
295}
296
297// ----------------------------------------------------------------------------
298// Playback
299// ----------------------------------------------------------------------------
300
301AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
302 : BnAudioTrack(),
303 mTrack(track)
304{
305}
306
307AudioFlinger::TrackHandle::~TrackHandle() {
308 // just stop the track on deletion, associated resources
309 // will be freed from the main thread once all pending buffers have
310 // been played. Unless it's not in the active track list, in which
311 // case we free everything now...
312 mTrack->destroy();
313}
314
315sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
316 return mTrack->getCblk();
317}
318
319status_t AudioFlinger::TrackHandle::start() {
320 return mTrack->start();
321}
322
323void AudioFlinger::TrackHandle::stop() {
324 mTrack->stop();
325}
326
327void AudioFlinger::TrackHandle::flush() {
328 mTrack->flush();
329}
330
Eric Laurent81784c32012-11-19 14:55:58 -0800331void AudioFlinger::TrackHandle::pause() {
332 mTrack->pause();
333}
334
335status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
336{
337 return mTrack->attachAuxEffect(EffectId);
338}
339
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700340status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
341 return mTrack->setParameters(keyValuePairs);
342}
343
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800344VolumeShaper::Status AudioFlinger::TrackHandle::applyVolumeShaper(
345 const sp<VolumeShaper::Configuration>& configuration,
346 const sp<VolumeShaper::Operation>& operation) {
347 return mTrack->applyVolumeShaper(configuration, operation);
348}
349
350sp<VolumeShaper::State> AudioFlinger::TrackHandle::getVolumeShaperState(int id) {
351 return mTrack->getVolumeShaperState(id);
352}
353
Glenn Kasten53cec222013-08-29 09:01:02 -0700354status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
355{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700356 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700357}
358
Eric Laurent59fe0102013-09-27 18:48:26 -0700359
360void AudioFlinger::TrackHandle::signal()
361{
362 return mTrack->signal();
363}
364
Eric Laurent81784c32012-11-19 14:55:58 -0800365status_t AudioFlinger::TrackHandle::onTransact(
366 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
367{
368 return BnAudioTrack::onTransact(code, data, reply, flags);
369}
370
371// ----------------------------------------------------------------------------
372
373// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
374AudioFlinger::PlaybackThread::Track::Track(
375 PlaybackThread *thread,
376 const sp<Client>& client,
377 audio_stream_type_t streamType,
378 uint32_t sampleRate,
379 audio_format_t format,
380 audio_channel_mask_t channelMask,
381 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700382 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -0700383 size_t bufferSize,
Eric Laurent81784c32012-11-19 14:55:58 -0800384 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800385 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800386 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -0700387 audio_output_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800388 track_type type,
389 audio_port_handle_t portId)
Eric Laurent83b88082014-06-20 18:31:16 -0700390 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
391 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
Andy Hung8fe68032017-06-05 16:17:51 -0700392 (sharedBuffer != 0) ? sharedBuffer->size() : bufferSize,
Eric Laurent05067782016-06-01 18:27:28 -0700393 sessionId, uid, true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700394 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800395 type, portId),
Eric Laurent81784c32012-11-19 14:55:58 -0800396 mFillingUpStatus(FS_INVALID),
397 // mRetryCount initialized later when needed
398 mSharedBuffer(sharedBuffer),
399 mStreamType(streamType),
400 mName(-1), // see note below
401 mMainBuffer(thread->mixBuffer()),
402 mAuxBuffer(NULL),
403 mAuxEffectId(0), mHasVolumeController(false),
404 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700405 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800406 mVolumeHandler(new VolumeHandler(sampleRate)),
Andy Hunge10393e2015-06-12 13:59:33 -0700407 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800408 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800409 mCachedVolume(1.0),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800410 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700411 mFlushHwPending(false),
412 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -0800413{
Eric Laurent83b88082014-06-20 18:31:16 -0700414 // client == 0 implies sharedBuffer == 0
415 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
416
Eric Laurente93cc032016-05-05 10:15:10 -0700417 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Eric Laurent83b88082014-06-20 18:31:16 -0700418 sharedBuffer->size());
419
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700420 if (mCblk == NULL) {
421 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800422 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700423
424 if (sharedBuffer == 0) {
425 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700426 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700427 } else {
428 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
429 mFrameSize);
430 }
431 mServerProxy = mAudioTrackServerProxy;
432
Eric Laurentad7dd962016-09-22 12:38:37 -0700433 mName = thread->getTrackName_l(channelMask, format, sessionId, uid);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700434 if (mName < 0) {
435 ALOGE("no more track names available");
436 return;
437 }
438 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700439 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700440 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
441 // race with setSyncEvent(). However, if we call it, we cannot properly start
442 // static fast tracks (SoundPool) immediately after stopping.
443 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700444 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
445 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700446 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700447 // FIXME This is too eager. We allocate a fast track index before the
448 // fast track becomes active. Since fast tracks are a scarce resource,
449 // this means we are potentially denying other more important fast tracks from
450 // being created. It would be better to allocate the index dynamically.
451 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700452 thread->mFastTrackAvailMask &= ~(1 << i);
453 }
Eric Laurent81784c32012-11-19 14:55:58 -0800454}
455
456AudioFlinger::PlaybackThread::Track::~Track()
457{
458 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700459
460 // The destructor would clear mSharedBuffer,
461 // but it will not push the decremented reference count,
462 // leaving the client's IMemory dangling indefinitely.
463 // This prevents that leak.
464 if (mSharedBuffer != 0) {
465 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700466 }
Eric Laurent81784c32012-11-19 14:55:58 -0800467}
468
Glenn Kasten03003332013-08-06 15:40:54 -0700469status_t AudioFlinger::PlaybackThread::Track::initCheck() const
470{
471 status_t status = TrackBase::initCheck();
472 if (status == NO_ERROR && mName < 0) {
473 status = NO_MEMORY;
474 }
475 return status;
476}
477
Eric Laurent81784c32012-11-19 14:55:58 -0800478void AudioFlinger::PlaybackThread::Track::destroy()
479{
480 // NOTE: destroyTrack_l() can remove a strong reference to this Track
481 // by removing it from mTracks vector, so there is a risk that this Tracks's
482 // destructor is called. As the destructor needs to lock mLock,
483 // we must acquire a strong reference on this Track before locking mLock
484 // here so that the destructor is called only when exiting this function.
485 // On the other hand, as long as Track::destroy() is only called by
486 // TrackHandle destructor, the TrackHandle still holds a strong ref on
487 // this Track with its member mTrack.
488 sp<Track> keep(this);
489 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700490 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800491 sp<ThreadBase> thread = mThread.promote();
492 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800493 Mutex::Autolock _l(thread->mLock);
494 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700495 wasActive = playbackThread->destroyTrack_l(this);
496 }
497 if (isExternalTrack() && !wasActive) {
Glenn Kastend848eb42016-03-08 13:42:11 -0800498 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800499 }
500 }
501}
502
503/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
504{
Marco Nelissenb2208842014-02-07 14:00:50 -0800505 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Andy Hungda540db2017-04-20 14:06:17 -0700506 "L dB R dB VS dB Server Main buf Aux buf Flags UndFrmCnt Flushed\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800507}
508
Marco Nelissenb2208842014-02-07 14:00:50 -0800509void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800510{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700511 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800512 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800513 sprintf(buffer, " F %2d", mFastIndex);
514 } else if (mName >= AudioMixer::TRACK0) {
515 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800516 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800517 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800518 }
519 track_state state = mState;
520 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800521 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800522 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800523 } else {
524 switch (state) {
525 case IDLE:
526 stateChar = 'I';
527 break;
528 case STOPPING_1:
529 stateChar = 's';
530 break;
531 case STOPPING_2:
532 stateChar = '5';
533 break;
534 case STOPPED:
535 stateChar = 'S';
536 break;
537 case RESUMING:
538 stateChar = 'R';
539 break;
540 case ACTIVE:
541 stateChar = 'A';
542 break;
543 case PAUSING:
544 stateChar = 'p';
545 break;
546 case PAUSED:
547 stateChar = 'P';
548 break;
549 case FLUSHED:
550 stateChar = 'F';
551 break;
552 default:
553 stateChar = '?';
554 break;
555 }
Eric Laurent81784c32012-11-19 14:55:58 -0800556 }
557 char nowInUnderrun;
558 switch (mObservedUnderruns.mBitFields.mMostRecent) {
559 case UNDERRUN_FULL:
560 nowInUnderrun = ' ';
561 break;
562 case UNDERRUN_PARTIAL:
563 nowInUnderrun = '<';
564 break;
565 case UNDERRUN_EMPTY:
566 nowInUnderrun = '*';
567 break;
568 default:
569 nowInUnderrun = '?';
570 break;
571 }
Andy Hungda540db2017-04-20 14:06:17 -0700572
573 std::pair<float /* volume */, bool /* active */> vsVolume = mVolumeHandler->getLastVolume();
574 snprintf(&buffer[8], size - 8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u "
575 "%5.2g %5.2g %5.2g%c "
576 "%08X %08zX %08zX 0x%03X %9u%c %7u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800577 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800578 (mClient == 0) ? getpid_cached : mClient->pid(),
579 mStreamType,
580 mFormat,
581 mChannelMask,
582 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800583 mFrameCount,
584 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800585 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800586 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700587 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
588 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Andy Hungda540db2017-04-20 14:06:17 -0700589 20.0 * log10(vsVolume.first), // VolumeShaper(s) total volume
590 vsVolume.second ? 'A' : ' ', // if any VolumeShapers active
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700591 mCblk->mServer,
Andy Hung2148bf02016-11-28 19:01:02 -0800592 (size_t)mMainBuffer, // use %zX as %p appends 0x
593 (size_t)mAuxBuffer, // use %zX as %p appends 0x
Glenn Kasten96f60d82013-07-12 10:21:18 -0700594 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700595 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -0800596 nowInUnderrun,
597 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000); // 7 digits
Eric Laurent81784c32012-11-19 14:55:58 -0800598}
599
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
601 return mAudioTrackServerProxy->getSampleRate();
602}
603
Eric Laurent81784c32012-11-19 14:55:58 -0800604// AudioBufferProvider interface
605status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800606 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800607{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800608 ServerProxy::Buffer buf;
609 size_t desiredFrames = buffer->frameCount;
610 buf.mFrameCount = desiredFrames;
611 status_t status = mServerProxy->obtainBuffer(&buf);
612 buffer->frameCount = buf.mFrameCount;
613 buffer->raw = buf.mRaw;
Mikhail Naganova66d3892017-05-03 16:50:56 -0700614 if (buf.mFrameCount == 0 && !isStopping() && !isStopped() && !isPaused()) {
615 ALOGV("underrun, framesReady(%zu) < framesDesired(%zd), state: %d",
616 buf.mFrameCount, desiredFrames, mState);
Glenn Kasten82aaf942013-07-17 16:05:07 -0700617 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800618 } else {
619 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800620 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800621
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800622 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800623}
624
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700625// releaseBuffer() is not overridden
626
627// ExtendedAudioBufferProvider interface
628
Andy Hung27876c02014-09-09 18:07:55 -0700629// framesReady() may return an approximation of the number of frames if called
630// from a different thread than the one calling Proxy->obtainBuffer() and
631// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
632// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800633size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700634 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
635 // Static tracks return zero frames immediately upon stopping (for FastTracks).
636 // The remainder of the buffer is not drained.
637 return 0;
638 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800639 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800640}
641
Andy Hung818e7a32016-02-16 18:08:07 -0800642int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700643{
644 return mAudioTrackServerProxy->framesReleased();
645}
646
Andy Hung818e7a32016-02-16 18:08:07 -0800647void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800648{
649 // This call comes from a FastTrack and should be kept lockless.
650 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800651 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800652
Andy Hung818e7a32016-02-16 18:08:07 -0800653 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hung6ae58432016-02-16 18:32:24 -0800654}
655
Eric Laurent81784c32012-11-19 14:55:58 -0800656// Don't call for fast tracks; the framesReady() could result in priority inversion
657bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800658 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
659 return true;
660 }
661
Eric Laurent16498512014-03-17 17:22:08 -0700662 if (isStopping()) {
663 if (framesReady() > 0) {
664 mFillingUpStatus = FS_FILLED;
665 }
Eric Laurent81784c32012-11-19 14:55:58 -0800666 return true;
667 }
668
Phil Burke8972b02016-03-04 11:29:57 -0800669 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700670 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800671 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700672 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800673 return true;
674 }
675 return false;
676}
677
Glenn Kasten0f11b512014-01-31 16:18:54 -0800678status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800679 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800680{
681 status_t status = NO_ERROR;
682 ALOGV("start(%d), calling pid %d session %d",
683 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
684
685 sp<ThreadBase> thread = mThread.promote();
686 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700687 if (isOffloaded()) {
688 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
689 Mutex::Autolock _lth(thread->mLock);
690 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700691 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
692 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700693 invalidate();
694 return PERMISSION_DENIED;
695 }
696 }
697 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800698 track_state state = mState;
699 // here the track could be either new, or restarted
700 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800701
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800702 // initial state-stopping. next state-pausing.
703 // What if resume is called ?
704
705 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800706 if (mResumeToStopping) {
707 // happened we need to resume to STOPPING_1
708 mState = TrackBase::STOPPING_1;
709 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
710 } else {
711 mState = TrackBase::RESUMING;
712 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
713 }
Eric Laurent81784c32012-11-19 14:55:58 -0800714 } else {
715 mState = TrackBase::ACTIVE;
716 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
717 }
718
Andy Hunge10393e2015-06-12 13:59:33 -0700719 // states to reset position info for non-offloaded/direct tracks
720 if (!isOffloaded() && !isDirect()
721 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
722 mFrameMap.reset();
723 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800724 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700725 if (isFastTrack()) {
726 // refresh fast track underruns on start because that field is never cleared
727 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
728 // after stop.
729 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
730 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800731 status = playbackThread->addTrack_l(this);
732 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800733 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800734 // restore previous state if start was rejected by policy manager
735 if (status == PERMISSION_DENIED) {
736 mState = state;
737 }
738 }
739 // track was already in the active list, not a problem
740 if (status == ALREADY_EXISTS) {
741 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700742 } else {
743 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
744 // It is usually unsafe to access the server proxy from a binder thread.
745 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
746 // isn't looking at this track yet: we still hold the normal mixer thread lock,
747 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700748 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700749 ServerProxy::Buffer buffer;
750 buffer.mFrameCount = 1;
751 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800752 }
753 } else {
754 status = BAD_VALUE;
755 }
756 return status;
757}
758
759void AudioFlinger::PlaybackThread::Track::stop()
760{
761 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
762 sp<ThreadBase> thread = mThread.promote();
763 if (thread != 0) {
764 Mutex::Autolock _l(thread->mLock);
765 track_state state = mState;
766 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
767 // If the track is not active (PAUSED and buffers full), flush buffers
768 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
769 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
770 reset();
771 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700772 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800773 mState = STOPPED;
774 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800775 // For fast tracks prepareTracks_l() will set state to STOPPING_2
776 // presentation is complete
777 // For an offloaded track this starts a drain and state will
778 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800779 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -0700780 if (isOffloaded()) {
781 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
782 }
Eric Laurent81784c32012-11-19 14:55:58 -0800783 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700784 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800785 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
786 playbackThread);
787 }
Eric Laurent81784c32012-11-19 14:55:58 -0800788 }
789}
790
791void AudioFlinger::PlaybackThread::Track::pause()
792{
793 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
794 sp<ThreadBase> thread = mThread.promote();
795 if (thread != 0) {
796 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800797 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
798 switch (mState) {
799 case STOPPING_1:
800 case STOPPING_2:
801 if (!isOffloaded()) {
802 /* nothing to do if track is not offloaded */
803 break;
804 }
805
806 // Offloaded track was draining, we need to carry on draining when resumed
807 mResumeToStopping = true;
808 // fall through...
809 case ACTIVE:
810 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800811 mState = PAUSING;
812 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700813 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800814 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800815
Eric Laurentbfb1b832013-01-07 09:53:42 -0800816 default:
817 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800818 }
819 }
820}
821
822void AudioFlinger::PlaybackThread::Track::flush()
823{
824 ALOGV("flush(%d)", mName);
825 sp<ThreadBase> thread = mThread.promote();
826 if (thread != 0) {
827 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800828 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800829
Phil Burk4bb650b2016-09-09 12:11:17 -0700830 // Flush the ring buffer now if the track is not active in the PlaybackThread.
831 // Otherwise the flush would not be done until the track is resumed.
832 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
833 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
834 (void)mServerProxy->flushBufferIfNeeded();
835 }
836
Eric Laurentbfb1b832013-01-07 09:53:42 -0800837 if (isOffloaded()) {
838 // If offloaded we allow flush during any state except terminated
839 // and keep the track active to avoid problems if user is seeking
840 // rapidly and underlying hardware has a significant delay handling
841 // a pause
842 if (isTerminated()) {
843 return;
844 }
845
846 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800847 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800848
849 if (mState == STOPPING_1 || mState == STOPPING_2) {
850 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
851 mState = ACTIVE;
852 }
853
Haynes Mathew George7844f672014-01-15 12:32:55 -0800854 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800855 mResumeToStopping = false;
856 } else {
857 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
858 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
859 return;
860 }
861 // No point remaining in PAUSED state after a flush => go to
862 // FLUSHED state
863 mState = FLUSHED;
864 // do not reset the track if it is still in the process of being stopped or paused.
865 // this will be done by prepareTracks_l() when the track is stopped.
866 // prepareTracks_l() will see mState == FLUSHED, then
867 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800868 if (isDirect()) {
869 mFlushHwPending = true;
870 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800871 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
872 reset();
873 }
Eric Laurent81784c32012-11-19 14:55:58 -0800874 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800875 // Prevent flush being lost if the track is flushed and then resumed
876 // before mixer thread can run. This is important when offloading
877 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700878 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800879 }
880}
881
Haynes Mathew George7844f672014-01-15 12:32:55 -0800882// must be called with thread lock held
883void AudioFlinger::PlaybackThread::Track::flushAck()
884{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800885 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800886 return;
887
Phil Burk4bb650b2016-09-09 12:11:17 -0700888 // Clear the client ring buffer so that the app can prime the buffer while paused.
889 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
890 mServerProxy->flushBufferIfNeeded();
891
Haynes Mathew George7844f672014-01-15 12:32:55 -0800892 mFlushHwPending = false;
893}
894
Eric Laurent81784c32012-11-19 14:55:58 -0800895void AudioFlinger::PlaybackThread::Track::reset()
896{
897 // Do not reset twice to avoid discarding data written just after a flush and before
898 // the audioflinger thread detects the track is stopped.
899 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800900 // Force underrun condition to avoid false underrun callback until first data is
901 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700902 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800903 mFillingUpStatus = FS_FILLING;
904 mResetDone = true;
905 if (mState == FLUSHED) {
906 mState = IDLE;
907 }
908 }
909}
910
Eric Laurentbfb1b832013-01-07 09:53:42 -0800911status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
912{
913 sp<ThreadBase> thread = mThread.promote();
914 if (thread == 0) {
915 ALOGE("thread is dead");
916 return FAILED_TRANSACTION;
917 } else if ((thread->type() == ThreadBase::DIRECT) ||
918 (thread->type() == ThreadBase::OFFLOAD)) {
919 return thread->setParameters(keyValuePairs);
920 } else {
921 return PERMISSION_DENIED;
922 }
923}
924
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800925VolumeShaper::Status AudioFlinger::PlaybackThread::Track::applyVolumeShaper(
926 const sp<VolumeShaper::Configuration>& configuration,
927 const sp<VolumeShaper::Operation>& operation)
928{
Andy Hung10cbff12017-02-21 17:30:14 -0800929 sp<VolumeShaper::Configuration> newConfiguration;
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800930
Andy Hung10cbff12017-02-21 17:30:14 -0800931 if (isOffloadedOrDirect()) {
932 const VolumeShaper::Configuration::OptionFlag optionFlag
933 = configuration->getOptionFlags();
934 if ((optionFlag & VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME) == 0) {
935 ALOGW("%s tracks do not support frame counted VolumeShaper,"
936 " using clock time instead", isOffloaded() ? "Offload" : "Direct");
937 newConfiguration = new VolumeShaper::Configuration(*configuration);
938 newConfiguration->setOptionFlags(
939 VolumeShaper::Configuration::OptionFlag(optionFlag
940 | VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME));
941 }
942 }
943
944 VolumeShaper::Status status = mVolumeHandler->applyVolumeShaper(
945 (newConfiguration.get() != nullptr ? newConfiguration : configuration), operation);
946
947 if (isOffloadedOrDirect()) {
948 // Signal thread to fetch new volume.
949 sp<ThreadBase> thread = mThread.promote();
950 if (thread != 0) {
951 Mutex::Autolock _l(thread->mLock);
952 thread->broadcast_l();
953 }
954 }
955 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800956}
957
958sp<VolumeShaper::State> AudioFlinger::PlaybackThread::Track::getVolumeShaperState(int id)
959{
960 // Note: We don't check if Thread exists.
961
962 // mVolumeHandler is thread safe.
963 return mVolumeHandler->getVolumeShaperState(id);
964}
965
Glenn Kasten573d80a2013-08-26 09:36:23 -0700966status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
967{
Andy Hung818e7a32016-02-16 18:08:07 -0800968 if (!isOffloaded() && !isDirect()) {
969 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700970 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700971 sp<ThreadBase> thread = mThread.promote();
972 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700973 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700974 }
Phil Burk6140c792015-03-19 14:30:21 -0700975
Glenn Kasten573d80a2013-08-26 09:36:23 -0700976 Mutex::Autolock _l(thread->mLock);
977 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -0800978 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700979}
980
Eric Laurent81784c32012-11-19 14:55:58 -0800981status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
982{
983 status_t status = DEAD_OBJECT;
984 sp<ThreadBase> thread = mThread.promote();
985 if (thread != 0) {
986 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
987 sp<AudioFlinger> af = mClient->audioFlinger();
988
989 Mutex::Autolock _l(af->mLock);
990
991 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
992
993 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
994 Mutex::Autolock _dl(playbackThread->mLock);
995 Mutex::Autolock _sl(srcThread->mLock);
996 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
997 if (chain == 0) {
998 return INVALID_OPERATION;
999 }
1000
1001 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
1002 if (effect == 0) {
1003 return INVALID_OPERATION;
1004 }
1005 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001006 status = playbackThread->addEffect_l(effect);
1007 if (status != NO_ERROR) {
1008 srcThread->addEffect_l(effect);
1009 return INVALID_OPERATION;
1010 }
Eric Laurent81784c32012-11-19 14:55:58 -08001011 // removeEffect_l() has stopped the effect if it was active so it must be restarted
1012 if (effect->state() == EffectModule::ACTIVE ||
1013 effect->state() == EffectModule::STOPPING) {
1014 effect->start();
1015 }
1016
1017 sp<EffectChain> dstChain = effect->chain().promote();
1018 if (dstChain == 0) {
1019 srcThread->addEffect_l(effect);
1020 return INVALID_OPERATION;
1021 }
1022 AudioSystem::unregisterEffect(effect->id());
1023 AudioSystem::registerEffect(&effect->desc(),
1024 srcThread->id(),
1025 dstChain->strategy(),
1026 AUDIO_SESSION_OUTPUT_MIX,
1027 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07001028 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -08001029 }
1030 status = playbackThread->attachAuxEffect(this, EffectId);
1031 }
1032 return status;
1033}
1034
1035void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
1036{
1037 mAuxEffectId = EffectId;
1038 mAuxBuffer = buffer;
1039}
1040
Andy Hung818e7a32016-02-16 18:08:07 -08001041bool AudioFlinger::PlaybackThread::Track::presentationComplete(
1042 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001043{
Andy Hung818e7a32016-02-16 18:08:07 -08001044 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
1045 // This assists in proper timestamp computation as well as wakelock management.
1046
Eric Laurent81784c32012-11-19 14:55:58 -08001047 // a track is considered presented when the total number of frames written to audio HAL
1048 // corresponds to the number of frames written when presentationComplete() is called for the
1049 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001050 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1051 // to detect when all frames have been played. In this case framesWritten isn't
1052 // useful because it doesn't always reflect whether there is data in the h/w
1053 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung818e7a32016-02-16 18:08:07 -08001054 ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
1055 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001056 if (mPresentationCompleteFrames == 0) {
1057 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung818e7a32016-02-16 18:08:07 -08001058 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
1059 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08001060 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001061
Andy Hungc54b1ff2016-02-23 14:07:07 -08001062 bool complete;
1063 if (isOffloaded()) {
1064 complete = true;
1065 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001066 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -08001067 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001068 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -08001069 && mAudioTrackServerProxy->isDrained();
1070 }
1071
1072 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -08001073 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001074 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001075 return true;
1076 }
1077 return false;
1078}
1079
1080void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1081{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001082 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001083 if (mSyncEvents[i]->type() == type) {
1084 mSyncEvents[i]->trigger();
1085 mSyncEvents.removeAt(i);
1086 i--;
1087 }
1088 }
1089}
1090
1091// implement VolumeBufferProvider interface
1092
Glenn Kastenc56f3422014-03-21 17:53:17 -07001093gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001094{
1095 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1096 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001097 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1098 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1099 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001100 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001101 if (vl > GAIN_FLOAT_UNITY) {
1102 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001103 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001104 if (vr > GAIN_FLOAT_UNITY) {
1105 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001106 }
1107 // now apply the cached master volume and stream type volume;
1108 // this is trusted but lacks any synchronization or barrier so may be stale
1109 float v = mCachedVolume;
1110 vl *= v;
1111 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001112 // re-combine into packed minifloat
1113 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001114 // FIXME look at mute, pause, and stop flags
1115 return vlr;
1116}
1117
1118status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1119{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001120 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001121 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1122 (mState == STOPPED)))) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001123 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001124 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1125 event->cancel();
1126 return INVALID_OPERATION;
1127 }
1128 (void) TrackBase::setSyncEvent(event);
1129 return NO_ERROR;
1130}
1131
Glenn Kasten5736c352012-12-04 12:12:34 -08001132void AudioFlinger::PlaybackThread::Track::invalidate()
1133{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001134 TrackBase::invalidate();
Eric Laurent4d231dc2016-03-11 18:38:23 -08001135 signalClientFlag(CBLK_INVALID);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001136}
1137
1138void AudioFlinger::PlaybackThread::Track::disable()
1139{
1140 signalClientFlag(CBLK_DISABLED);
1141}
1142
1143void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1144{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001145 // FIXME should use proxy, and needs work
1146 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001147 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001148 android_atomic_release_store(0x40000000, &cblk->mFutex);
1149 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001150 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001151}
1152
Eric Laurent59fe0102013-09-27 18:48:26 -07001153void AudioFlinger::PlaybackThread::Track::signal()
1154{
1155 sp<ThreadBase> thread = mThread.promote();
1156 if (thread != 0) {
1157 PlaybackThread *t = (PlaybackThread *)thread.get();
1158 Mutex::Autolock _l(t->mLock);
1159 t->broadcast_l();
1160 }
1161}
1162
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001163//To be called with thread lock held
1164bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1165
1166 if (mState == RESUMING)
1167 return true;
1168 /* Resume is pending if track was stopping before pause was called */
1169 if (mState == STOPPING_1 &&
1170 mResumeToStopping)
1171 return true;
1172
1173 return false;
1174}
1175
1176//To be called with thread lock held
1177void AudioFlinger::PlaybackThread::Track::resumeAck() {
1178
1179
1180 if (mState == RESUMING)
1181 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001182
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001183 // Other possibility of pending resume is stopping_1 state
1184 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001185 // drain being called.
1186 if (mState == STOPPING_1) {
1187 mResumeToStopping = false;
1188 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001189}
Andy Hunge10393e2015-06-12 13:59:33 -07001190
1191//To be called with thread lock held
1192void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001193 int64_t trackFramesReleased, int64_t sinkFramesWritten,
1194 const ExtendedTimestamp &timeStamp) {
1195 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001196 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001197
1198 // adjust server times and set drained state.
1199 //
1200 // Our timestamps are only updated when the track is on the Thread active list.
1201 // We need to ensure that tracks are not removed before full drain.
1202 ExtendedTimestamp local = timeStamp;
1203 bool checked = false;
1204 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1205 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1206 // Lookup the track frame corresponding to the sink frame position.
1207 if (local.mTimeNs[i] > 0) {
1208 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1209 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001210 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hung818e7a32016-02-16 18:08:07 -08001211 mAudioTrackServerProxy->setDrained(
1212 local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1213 checked = true;
1214 }
1215 }
Andy Hunge10393e2015-06-12 13:59:33 -07001216 }
Andy Hung818e7a32016-02-16 18:08:07 -08001217 if (!checked) { // no server info, assume drained.
1218 mAudioTrackServerProxy->setDrained(true);
1219 }
Andy Hungea2b9c02016-02-12 17:06:53 -08001220 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001221 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001222 mServerProxy->setTimestamp(local);
Andy Hunge10393e2015-06-12 13:59:33 -07001223}
1224
Eric Laurent81784c32012-11-19 14:55:58 -08001225// ----------------------------------------------------------------------------
1226
Eric Laurent81784c32012-11-19 14:55:58 -08001227AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1228 PlaybackThread *playbackThread,
1229 DuplicatingThread *sourceThread,
1230 uint32_t sampleRate,
1231 audio_format_t format,
1232 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001233 size_t frameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001234 uid_t uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001235 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1236 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07001237 nullptr /* buffer */, (size_t)0 /* bufferSize */, nullptr /* sharedBuffer */,
1238 AUDIO_SESSION_NONE, uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001239 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07001240 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08001241{
1242
1243 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001244 mOutBuffer.frameCount = 0;
1245 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001246 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001247 "frameCount %zu, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001248 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001249 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001250 // since client and server are in the same process,
1251 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001252 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1253 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001254 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001255 mClientProxy->setSendLevel(0.0);
1256 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001257 } else {
1258 ALOGW("Error creating output track on thread %p", playbackThread);
1259 }
1260}
1261
1262AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1263{
1264 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001265 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001266}
1267
1268status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001269 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001270{
1271 status_t status = Track::start(event, triggerSession);
1272 if (status != NO_ERROR) {
1273 return status;
1274 }
1275
1276 mActive = true;
1277 mRetryCount = 127;
1278 return status;
1279}
1280
1281void AudioFlinger::PlaybackThread::OutputTrack::stop()
1282{
1283 Track::stop();
1284 clearBufferQueue();
1285 mOutBuffer.frameCount = 0;
1286 mActive = false;
1287}
1288
Andy Hungc25b84a2015-01-14 19:04:10 -08001289bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001290{
1291 Buffer *pInBuffer;
1292 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001293 bool outputBufferFull = false;
1294 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001295 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001296
1297 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1298
1299 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001300 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001301 }
1302
1303 while (waitTimeLeftMs) {
1304 // First write pending buffers, then new data
1305 if (mBufferQueue.size()) {
1306 pInBuffer = mBufferQueue.itemAt(0);
1307 } else {
1308 pInBuffer = &inBuffer;
1309 }
1310
1311 if (pInBuffer->frameCount == 0) {
1312 break;
1313 }
1314
1315 if (mOutBuffer.frameCount == 0) {
1316 mOutBuffer.frameCount = pInBuffer->frameCount;
1317 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001318 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001319 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001320 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1321 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001322 outputBufferFull = true;
1323 break;
1324 }
1325 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1326 if (waitTimeLeftMs >= waitTimeMs) {
1327 waitTimeLeftMs -= waitTimeMs;
1328 } else {
1329 waitTimeLeftMs = 0;
1330 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001331 if (status == NOT_ENOUGH_DATA) {
1332 restartIfDisabled();
1333 continue;
1334 }
Eric Laurent81784c32012-11-19 14:55:58 -08001335 }
1336
1337 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1338 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001339 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001340 Proxy::Buffer buf;
1341 buf.mFrameCount = outFrames;
1342 buf.mRaw = NULL;
1343 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001344 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001345 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001346 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001347 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001348 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001349
1350 if (pInBuffer->frameCount == 0) {
1351 if (mBufferQueue.size()) {
1352 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001353 free(pInBuffer->mBuffer);
Yunlian Jiang8adc8082017-06-06 15:59:44 -07001354 if (pInBuffer != &inBuffer) {
1355 delete pInBuffer;
1356 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001357 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001358 mThread.unsafe_get(), mBufferQueue.size());
1359 } else {
1360 break;
1361 }
1362 }
1363 }
1364
1365 // If we could not write all frames, allocate a buffer and queue it for next time.
1366 if (inBuffer.frameCount) {
1367 sp<ThreadBase> thread = mThread.promote();
1368 if (thread != 0 && !thread->standby()) {
1369 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1370 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001371 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001372 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001373 pInBuffer->raw = pInBuffer->mBuffer;
1374 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001375 mBufferQueue.add(pInBuffer);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001376 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001377 mThread.unsafe_get(), mBufferQueue.size());
1378 } else {
1379 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1380 mThread.unsafe_get(), this);
1381 }
1382 }
1383 }
1384
Andy Hungc25b84a2015-01-14 19:04:10 -08001385 // Calling write() with a 0 length buffer means that no more data will be written:
1386 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1387 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1388 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001389 }
1390
1391 return outputBufferFull;
1392}
1393
1394status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1395 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1396{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001397 ClientProxy::Buffer buf;
1398 buf.mFrameCount = buffer->frameCount;
1399 struct timespec timeout;
1400 timeout.tv_sec = waitTimeMs / 1000;
1401 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1402 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1403 buffer->frameCount = buf.mFrameCount;
1404 buffer->raw = buf.mRaw;
1405 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001406}
1407
Eric Laurent81784c32012-11-19 14:55:58 -08001408void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1409{
1410 size_t size = mBufferQueue.size();
1411
1412 for (size_t i = 0; i < size; i++) {
1413 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001414 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001415 delete pBuffer;
1416 }
1417 mBufferQueue.clear();
1418}
1419
Eric Laurent4d231dc2016-03-11 18:38:23 -08001420void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1421{
1422 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1423 if (mActive && (flags & CBLK_DISABLED)) {
1424 start();
1425 }
1426}
Eric Laurent81784c32012-11-19 14:55:58 -08001427
Eric Laurent83b88082014-06-20 18:31:16 -07001428AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001429 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001430 uint32_t sampleRate,
1431 audio_channel_mask_t channelMask,
1432 audio_format_t format,
1433 size_t frameCount,
1434 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07001435 size_t bufferSize,
Eric Laurent05067782016-06-01 18:27:28 -07001436 audio_output_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001437 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001438 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07001439 buffer, bufferSize, nullptr /* sharedBuffer */,
1440 AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001441 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1442{
1443 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1444 playbackThread->sampleRate();
1445 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1446 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1447
1448 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1449 this, sampleRate,
1450 (int)mPeerTimeout.tv_sec,
1451 (int)(mPeerTimeout.tv_nsec / 1000000));
1452}
1453
1454AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1455{
1456}
1457
Eric Laurent4d231dc2016-03-11 18:38:23 -08001458status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001459 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001460{
1461 status_t status = Track::start(event, triggerSession);
1462 if (status != NO_ERROR) {
1463 return status;
1464 }
1465 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1466 return status;
1467}
1468
Eric Laurent83b88082014-06-20 18:31:16 -07001469// AudioBufferProvider interface
1470status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001471 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001472{
1473 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1474 Proxy::Buffer buf;
1475 buf.mFrameCount = buffer->frameCount;
1476 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1477 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001478 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001479 if (buf.mFrameCount == 0) {
1480 return WOULD_BLOCK;
1481 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001482 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001483 return status;
1484}
1485
1486void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1487{
1488 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1489 Proxy::Buffer buf;
1490 buf.mFrameCount = buffer->frameCount;
1491 buf.mRaw = buffer->raw;
1492 mPeerProxy->releaseBuffer(&buf);
1493 TrackBase::releaseBuffer(buffer);
1494}
1495
1496status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1497 const struct timespec *timeOut)
1498{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001499 status_t status = NO_ERROR;
1500 static const int32_t kMaxTries = 5;
1501 int32_t tryCounter = kMaxTries;
1502 do {
1503 if (status == NOT_ENOUGH_DATA) {
1504 restartIfDisabled();
1505 }
1506 status = mProxy->obtainBuffer(buffer, timeOut);
1507 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1508 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001509}
1510
1511void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1512{
1513 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001514 restartIfDisabled();
1515 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1516}
1517
1518void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1519{
Eric Laurent83b88082014-06-20 18:31:16 -07001520 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1521 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1522 start();
1523 }
Eric Laurent83b88082014-06-20 18:31:16 -07001524}
1525
Eric Laurent81784c32012-11-19 14:55:58 -08001526// ----------------------------------------------------------------------------
1527// Record
1528// ----------------------------------------------------------------------------
1529
1530AudioFlinger::RecordHandle::RecordHandle(
1531 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1532 : BnAudioRecord(),
1533 mRecordTrack(recordTrack)
1534{
1535}
1536
1537AudioFlinger::RecordHandle::~RecordHandle() {
1538 stop_nonvirtual();
1539 mRecordTrack->destroy();
1540}
1541
Eric Laurent81784c32012-11-19 14:55:58 -08001542status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001543 audio_session_t triggerSession) {
Eric Laurent81784c32012-11-19 14:55:58 -08001544 ALOGV("RecordHandle::start()");
1545 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1546}
1547
1548void AudioFlinger::RecordHandle::stop() {
1549 stop_nonvirtual();
1550}
1551
1552void AudioFlinger::RecordHandle::stop_nonvirtual() {
1553 ALOGV("RecordHandle::stop()");
1554 mRecordTrack->stop();
1555}
1556
1557status_t AudioFlinger::RecordHandle::onTransact(
1558 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1559{
1560 return BnAudioRecord::onTransact(code, data, reply, flags);
1561}
1562
1563// ----------------------------------------------------------------------------
1564
Glenn Kasten05997e22014-03-13 15:08:33 -07001565// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001566AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1567 RecordThread *thread,
1568 const sp<Client>& client,
1569 uint32_t sampleRate,
1570 audio_format_t format,
1571 audio_channel_mask_t channelMask,
1572 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001573 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07001574 size_t bufferSize,
Glenn Kastend848eb42016-03-08 13:42:11 -08001575 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001576 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001577 audio_input_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001578 track_type type,
1579 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001580 : TrackBase(thread, client, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07001581 channelMask, frameCount, buffer, bufferSize, sessionId, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001582 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001583 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001584 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
Eric Laurent20b9ef02016-12-05 11:03:16 -08001585 type, portId),
Andy Hung97a893e2015-03-29 01:03:07 -07001586 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001587 mFramesToDrop(0),
1588 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001589 mRecordBufferConverter(NULL),
1590 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001591{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001592 if (mCblk == NULL) {
1593 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001594 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001595
Andy Hung97a893e2015-03-29 01:03:07 -07001596 mRecordBufferConverter = new RecordBufferConverter(
1597 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1598 channelMask, format, sampleRate);
1599 // Check if the RecordBufferConverter construction was successful.
1600 // If not, don't continue with construction.
1601 //
1602 // NOTE: It would be extremely rare that the record track cannot be created
1603 // for the current device, but a pending or future device change would make
1604 // the record track configuration valid.
1605 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1606 ALOGE("RecordTrack unable to create record buffer converter");
1607 return;
1608 }
1609
Andy Hung6ae58432016-02-16 18:32:24 -08001610 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001611 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001612
Andy Hung97a893e2015-03-29 01:03:07 -07001613 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001614
Eric Laurent05067782016-06-01 18:27:28 -07001615 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001616 ALOG_ASSERT(thread->mFastTrackAvail);
1617 thread->mFastTrackAvail = false;
1618 }
Eric Laurent81784c32012-11-19 14:55:58 -08001619}
1620
1621AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1622{
1623 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001624 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001625 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001626}
1627
Andy Hung97a893e2015-03-29 01:03:07 -07001628status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1629{
1630 status_t status = TrackBase::initCheck();
1631 if (status == NO_ERROR && mServerProxy == 0) {
1632 status = BAD_VALUE;
1633 }
1634 return status;
1635}
1636
Eric Laurent81784c32012-11-19 14:55:58 -08001637// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001638status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001639{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001640 ServerProxy::Buffer buf;
1641 buf.mFrameCount = buffer->frameCount;
1642 status_t status = mServerProxy->obtainBuffer(&buf);
1643 buffer->frameCount = buf.mFrameCount;
1644 buffer->raw = buf.mRaw;
1645 if (buf.mFrameCount == 0) {
1646 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001647 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001648 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001649 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001650}
1651
1652status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001653 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001654{
1655 sp<ThreadBase> thread = mThread.promote();
1656 if (thread != 0) {
1657 RecordThread *recordThread = (RecordThread *)thread.get();
1658 return recordThread->start(this, event, triggerSession);
1659 } else {
1660 return BAD_VALUE;
1661 }
1662}
1663
1664void AudioFlinger::RecordThread::RecordTrack::stop()
1665{
1666 sp<ThreadBase> thread = mThread.promote();
1667 if (thread != 0) {
1668 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001669 if (recordThread->stop(this) && isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001670 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001671 }
1672 }
1673}
1674
1675void AudioFlinger::RecordThread::RecordTrack::destroy()
1676{
1677 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1678 sp<RecordTrack> keep(this);
1679 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001680 if (isExternalTrack()) {
1681 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001682 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001683 }
Glenn Kastend848eb42016-03-08 13:42:11 -08001684 AudioSystem::releaseInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001685 }
Eric Laurent81784c32012-11-19 14:55:58 -08001686 sp<ThreadBase> thread = mThread.promote();
1687 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001688 Mutex::Autolock _l(thread->mLock);
1689 RecordThread *recordThread = (RecordThread *) thread.get();
1690 recordThread->destroyTrack_l(this);
1691 }
1692 }
1693}
1694
Eric Laurent9a54bc22013-09-09 09:08:44 -07001695void AudioFlinger::RecordThread::RecordTrack::invalidate()
1696{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001697 TrackBase::invalidate();
Eric Laurent9a54bc22013-09-09 09:08:44 -07001698 // FIXME should use proxy, and needs work
1699 audio_track_cblk_t* cblk = mCblk;
1700 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1701 android_atomic_release_store(0x40000000, &cblk->mFutex);
1702 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001703 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001704}
1705
Eric Laurent81784c32012-11-19 14:55:58 -08001706
1707/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1708{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001709 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001710}
1711
Marco Nelissenb2208842014-02-07 14:00:50 -08001712void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001713{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001714 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001715 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001716 (mClient == 0) ? getpid_cached : mClient->pid(),
1717 mFormat,
1718 mChannelMask,
1719 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001720 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001721 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001722 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001723 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001724
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001727void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1728{
1729 if (event == mSyncStartEvent) {
1730 ssize_t framesToDrop = 0;
1731 sp<ThreadBase> threadBase = mThread.promote();
1732 if (threadBase != 0) {
1733 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1734 // from audio HAL
1735 framesToDrop = threadBase->mFrameCount * 2;
1736 }
1737 mFramesToDrop = framesToDrop;
1738 }
1739}
1740
1741void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1742{
1743 if (mSyncStartEvent != 0) {
1744 mSyncStartEvent->cancel();
1745 mSyncStartEvent.clear();
1746 }
1747 mFramesToDrop = 0;
1748}
1749
Andy Hung3f0c9022016-01-15 17:49:46 -08001750void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1751 int64_t trackFramesReleased, int64_t sourceFramesRead,
1752 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1753{
1754 ExtendedTimestamp local = timestamp;
1755
1756 // Convert HAL frames to server-side track frames at track sample rate.
1757 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1758 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1759 if (local.mTimeNs[i] != 0) {
1760 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1761 const int64_t relativeTrackFrames = relativeServerFrames
1762 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1763 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1764 }
1765 }
Andy Hung6ae58432016-02-16 18:32:24 -08001766 mServerProxy->setTimestamp(local);
Andy Hung3f0c9022016-01-15 17:49:46 -08001767}
Eric Laurent83b88082014-06-20 18:31:16 -07001768
1769AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1770 uint32_t sampleRate,
1771 audio_channel_mask_t channelMask,
1772 audio_format_t format,
1773 size_t frameCount,
1774 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07001775 size_t bufferSize,
Eric Laurent05067782016-06-01 18:27:28 -07001776 audio_input_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07001777 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07001778 buffer, bufferSize, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001779 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1780{
1781 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1782 recordThread->sampleRate();
1783 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1784 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1785
1786 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1787 this, sampleRate,
1788 (int)mPeerTimeout.tv_sec,
1789 (int)(mPeerTimeout.tv_nsec / 1000000));
1790}
1791
1792AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1793{
1794}
1795
1796// AudioBufferProvider interface
1797status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001798 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001799{
1800 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1801 Proxy::Buffer buf;
1802 buf.mFrameCount = buffer->frameCount;
1803 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1804 ALOGV_IF(status != NO_ERROR,
1805 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001806 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001807 if (buf.mFrameCount == 0) {
1808 return WOULD_BLOCK;
1809 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001810 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001811 return status;
1812}
1813
1814void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1815{
1816 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1817 Proxy::Buffer buf;
1818 buf.mFrameCount = buffer->frameCount;
1819 buf.mRaw = buffer->raw;
1820 mPeerProxy->releaseBuffer(&buf);
1821 TrackBase::releaseBuffer(buffer);
1822}
1823
1824status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1825 const struct timespec *timeOut)
1826{
1827 return mProxy->obtainBuffer(buffer, timeOut);
1828}
1829
1830void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1831{
1832 mProxy->releaseBuffer(buffer);
1833}
1834
Eric Laurent6acd1d42017-01-04 14:23:29 -08001835
1836
1837AudioFlinger::MmapThread::MmapTrack::MmapTrack(ThreadBase *thread,
1838 uint32_t sampleRate,
1839 audio_format_t format,
1840 audio_channel_mask_t channelMask,
1841 audio_session_t sessionId,
1842 uid_t uid,
1843 audio_port_handle_t portId)
1844 : TrackBase(thread, NULL, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07001845 channelMask, (size_t)0 /* frameCount */,
1846 nullptr /* buffer */, (size_t)0 /* bufferSize */,
1847 sessionId, uid, false /* isOut */,
Eric Laurent6acd1d42017-01-04 14:23:29 -08001848 ALLOC_NONE,
1849 TYPE_DEFAULT, portId)
1850{
1851}
1852
1853AudioFlinger::MmapThread::MmapTrack::~MmapTrack()
1854{
1855}
1856
1857status_t AudioFlinger::MmapThread::MmapTrack::initCheck() const
1858{
1859 return NO_ERROR;
1860}
1861
1862status_t AudioFlinger::MmapThread::MmapTrack::start(AudioSystem::sync_event_t event __unused,
1863 audio_session_t triggerSession __unused)
1864{
1865 return NO_ERROR;
1866}
1867
1868void AudioFlinger::MmapThread::MmapTrack::stop()
1869{
1870}
1871
1872// AudioBufferProvider interface
1873status_t AudioFlinger::MmapThread::MmapTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
1874{
1875 buffer->frameCount = 0;
1876 buffer->raw = nullptr;
1877 return INVALID_OPERATION;
1878}
1879
1880// ExtendedAudioBufferProvider interface
1881size_t AudioFlinger::MmapThread::MmapTrack::framesReady() const {
1882 return 0;
1883}
1884
1885int64_t AudioFlinger::MmapThread::MmapTrack::framesReleased() const
1886{
1887 return 0;
1888}
1889
1890void AudioFlinger::MmapThread::MmapTrack::onTimestamp(const ExtendedTimestamp &timestamp __unused)
1891{
1892}
1893
1894/*static*/ void AudioFlinger::MmapThread::MmapTrack::appendDumpHeader(String8& result)
1895{
1896 result.append(" Client Fmt Chn mask SRate\n");
1897}
1898
1899void AudioFlinger::MmapThread::MmapTrack::dump(char* buffer, size_t size)
1900{
1901 snprintf(buffer, size, " %6u %3u %08X %5u\n",
1902 mUid,
1903 mFormat,
1904 mChannelMask,
1905 mSampleRate);
1906
1907}
1908
Glenn Kasten63238ef2015-03-02 15:50:29 -08001909} // namespace android