blob: b6825177d39ba3143b158e92d33e2d88869ada57 [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{
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700505 result.append("T Name Active Client Session S Flags "
506 " Format Chn mask SRate "
507 "ST L dB R dB VS dB "
508 " Server FrmCnt FrmRdy F Underruns Flushed "
509 "Main Buf Aux Buf\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800510}
511
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700512void AudioFlinger::PlaybackThread::Track::appendDump(String8& result, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700514 char trackType;
515 switch (mType) {
516 case TYPE_DEFAULT:
517 case TYPE_OUTPUT:
518 if (mSharedBuffer.get() != nullptr) {
519 trackType = 'S'; // static
520 } else {
521 trackType = ' '; // normal
Eric Laurentbfb1b832013-01-07 09:53:42 -0800522 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700523 break;
524 case TYPE_PATCH:
525 trackType = 'P';
526 break;
527 default:
528 trackType = '?';
Eric Laurent81784c32012-11-19 14:55:58 -0800529 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700530
531 if (isFastTrack()) {
532 result.appendFormat("F%c %3d", trackType, mFastIndex);
533 } else if (mName >= AudioMixer::TRACK0) {
534 result.appendFormat("%c %4d", trackType, mName - AudioMixer::TRACK0);
535 } else {
536 result.appendFormat("%c none", trackType);
537 }
538
Eric Laurent81784c32012-11-19 14:55:58 -0800539 char nowInUnderrun;
540 switch (mObservedUnderruns.mBitFields.mMostRecent) {
541 case UNDERRUN_FULL:
542 nowInUnderrun = ' ';
543 break;
544 case UNDERRUN_PARTIAL:
545 nowInUnderrun = '<';
546 break;
547 case UNDERRUN_EMPTY:
548 nowInUnderrun = '*';
549 break;
550 default:
551 nowInUnderrun = '?';
552 break;
553 }
Andy Hungda540db2017-04-20 14:06:17 -0700554
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700555 char fillingStatus;
556 switch (mFillingUpStatus) {
557 case FS_INVALID:
558 fillingStatus = 'I';
559 break;
560 case FS_FILLING:
561 fillingStatus = 'f';
562 break;
563 case FS_FILLED:
564 fillingStatus = 'F';
565 break;
566 case FS_ACTIVE:
567 fillingStatus = 'A';
568 break;
569 default:
570 fillingStatus = '?';
571 break;
572 }
573
574 // clip framesReadySafe to max representation in dump
575 const size_t framesReadySafe =
576 std::min(mAudioTrackServerProxy->framesReadySafe(), (size_t)99999999);
577
578 // obtain volumes
579 const gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
580 const std::pair<float /* volume */, bool /* active */> vsVolume =
581 mVolumeHandler->getLastVolume();
582
583 // Our effective frame count is obtained by ServerProxy::getBufferSizeInFrames()
584 // as it may be reduced by the application.
585 const size_t bufferSizeInFrames = (size_t)mAudioTrackServerProxy->getBufferSizeInFrames();
586 // Check whether the buffer size has been modified by the app.
587 const char modifiedBufferChar = bufferSizeInFrames < mFrameCount
588 ? 'r' /* buffer reduced */: bufferSizeInFrames > mFrameCount
589 ? 'e' /* error */ : ' ' /* identical */;
590
591 result.appendFormat("%7s %6u %7u %2s 0x%03X "
592 "%08X %08X %6u "
593 "%2u %5.2g %5.2g %5.2g%c "
594 "%08X %6zu%c %6zu %c %9u%c %7u "
595 "%08zX %08zX\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800596 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800597 (mClient == 0) ? getpid_cached : mClient->pid(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700598 mSessionId,
599 getTrackStateString(),
600 mCblk->mFlags,
601
Eric Laurent81784c32012-11-19 14:55:58 -0800602 mFormat,
603 mChannelMask,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 mAudioTrackServerProxy->getSampleRate(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700605
606 mStreamType,
Glenn Kastenc56f3422014-03-21 17:53:17 -0700607 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
608 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Andy Hungda540db2017-04-20 14:06:17 -0700609 20.0 * log10(vsVolume.first), // VolumeShaper(s) total volume
610 vsVolume.second ? 'A' : ' ', // if any VolumeShapers active
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700611
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700612 mCblk->mServer,
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700613 bufferSizeInFrames,
614 modifiedBufferChar,
615 framesReadySafe,
616 fillingStatus,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700617 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -0800618 nowInUnderrun,
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700619 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000,
620
621 (size_t)mMainBuffer, // use %zX as %p appends 0x
622 (size_t)mAuxBuffer // use %zX as %p appends 0x
623 );
Eric Laurent81784c32012-11-19 14:55:58 -0800624}
625
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800626uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
627 return mAudioTrackServerProxy->getSampleRate();
628}
629
Eric Laurent81784c32012-11-19 14:55:58 -0800630// AudioBufferProvider interface
631status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800632 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800633{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800634 ServerProxy::Buffer buf;
635 size_t desiredFrames = buffer->frameCount;
636 buf.mFrameCount = desiredFrames;
637 status_t status = mServerProxy->obtainBuffer(&buf);
638 buffer->frameCount = buf.mFrameCount;
639 buffer->raw = buf.mRaw;
Mikhail Naganova66d3892017-05-03 16:50:56 -0700640 if (buf.mFrameCount == 0 && !isStopping() && !isStopped() && !isPaused()) {
641 ALOGV("underrun, framesReady(%zu) < framesDesired(%zd), state: %d",
642 buf.mFrameCount, desiredFrames, mState);
Glenn Kasten82aaf942013-07-17 16:05:07 -0700643 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800644 } else {
645 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800646 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800647
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800648 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800649}
650
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700651// releaseBuffer() is not overridden
652
653// ExtendedAudioBufferProvider interface
654
Andy Hung27876c02014-09-09 18:07:55 -0700655// framesReady() may return an approximation of the number of frames if called
656// from a different thread than the one calling Proxy->obtainBuffer() and
657// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
658// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800659size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700660 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
661 // Static tracks return zero frames immediately upon stopping (for FastTracks).
662 // The remainder of the buffer is not drained.
663 return 0;
664 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800665 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800666}
667
Andy Hung818e7a32016-02-16 18:08:07 -0800668int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700669{
670 return mAudioTrackServerProxy->framesReleased();
671}
672
Andy Hung818e7a32016-02-16 18:08:07 -0800673void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800674{
675 // This call comes from a FastTrack and should be kept lockless.
676 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800677 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800678
Andy Hung818e7a32016-02-16 18:08:07 -0800679 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hung6ae58432016-02-16 18:32:24 -0800680}
681
Eric Laurent81784c32012-11-19 14:55:58 -0800682// Don't call for fast tracks; the framesReady() could result in priority inversion
683bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800684 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
685 return true;
686 }
687
Eric Laurent16498512014-03-17 17:22:08 -0700688 if (isStopping()) {
689 if (framesReady() > 0) {
690 mFillingUpStatus = FS_FILLED;
691 }
Eric Laurent81784c32012-11-19 14:55:58 -0800692 return true;
693 }
694
Phil Burke8972b02016-03-04 11:29:57 -0800695 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700696 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800697 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700698 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800699 return true;
700 }
701 return false;
702}
703
Glenn Kasten0f11b512014-01-31 16:18:54 -0800704status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800705 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800706{
707 status_t status = NO_ERROR;
708 ALOGV("start(%d), calling pid %d session %d",
709 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
710
711 sp<ThreadBase> thread = mThread.promote();
712 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700713 if (isOffloaded()) {
714 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
715 Mutex::Autolock _lth(thread->mLock);
716 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700717 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
718 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700719 invalidate();
720 return PERMISSION_DENIED;
721 }
722 }
723 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800724 track_state state = mState;
725 // here the track could be either new, or restarted
726 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800727
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800728 // initial state-stopping. next state-pausing.
729 // What if resume is called ?
730
731 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800732 if (mResumeToStopping) {
733 // happened we need to resume to STOPPING_1
734 mState = TrackBase::STOPPING_1;
735 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
736 } else {
737 mState = TrackBase::RESUMING;
738 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
739 }
Eric Laurent81784c32012-11-19 14:55:58 -0800740 } else {
741 mState = TrackBase::ACTIVE;
742 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
743 }
744
Andy Hunge10393e2015-06-12 13:59:33 -0700745 // states to reset position info for non-offloaded/direct tracks
746 if (!isOffloaded() && !isDirect()
747 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
748 mFrameMap.reset();
749 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800750 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700751 if (isFastTrack()) {
752 // refresh fast track underruns on start because that field is never cleared
753 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
754 // after stop.
755 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
756 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800757 status = playbackThread->addTrack_l(this);
758 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800759 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800760 // restore previous state if start was rejected by policy manager
761 if (status == PERMISSION_DENIED) {
762 mState = state;
763 }
764 }
765 // track was already in the active list, not a problem
766 if (status == ALREADY_EXISTS) {
767 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700768 } else {
769 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
770 // It is usually unsafe to access the server proxy from a binder thread.
771 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
772 // isn't looking at this track yet: we still hold the normal mixer thread lock,
773 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700774 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700775 ServerProxy::Buffer buffer;
776 buffer.mFrameCount = 1;
777 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800778 }
779 } else {
780 status = BAD_VALUE;
781 }
782 return status;
783}
784
785void AudioFlinger::PlaybackThread::Track::stop()
786{
787 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
788 sp<ThreadBase> thread = mThread.promote();
789 if (thread != 0) {
790 Mutex::Autolock _l(thread->mLock);
791 track_state state = mState;
792 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
793 // If the track is not active (PAUSED and buffers full), flush buffers
794 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
795 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
796 reset();
797 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700798 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800799 mState = STOPPED;
800 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800801 // For fast tracks prepareTracks_l() will set state to STOPPING_2
802 // presentation is complete
803 // For an offloaded track this starts a drain and state will
804 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800805 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -0700806 if (isOffloaded()) {
807 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
808 }
Eric Laurent81784c32012-11-19 14:55:58 -0800809 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700810 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800811 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
812 playbackThread);
813 }
Eric Laurent81784c32012-11-19 14:55:58 -0800814 }
815}
816
817void AudioFlinger::PlaybackThread::Track::pause()
818{
819 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
820 sp<ThreadBase> thread = mThread.promote();
821 if (thread != 0) {
822 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800823 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
824 switch (mState) {
825 case STOPPING_1:
826 case STOPPING_2:
827 if (!isOffloaded()) {
828 /* nothing to do if track is not offloaded */
829 break;
830 }
831
832 // Offloaded track was draining, we need to carry on draining when resumed
833 mResumeToStopping = true;
834 // fall through...
835 case ACTIVE:
836 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800837 mState = PAUSING;
838 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700839 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800840 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800841
Eric Laurentbfb1b832013-01-07 09:53:42 -0800842 default:
843 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800844 }
845 }
846}
847
848void AudioFlinger::PlaybackThread::Track::flush()
849{
850 ALOGV("flush(%d)", mName);
851 sp<ThreadBase> thread = mThread.promote();
852 if (thread != 0) {
853 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800854 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800855
Phil Burk4bb650b2016-09-09 12:11:17 -0700856 // Flush the ring buffer now if the track is not active in the PlaybackThread.
857 // Otherwise the flush would not be done until the track is resumed.
858 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
859 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
860 (void)mServerProxy->flushBufferIfNeeded();
861 }
862
Eric Laurentbfb1b832013-01-07 09:53:42 -0800863 if (isOffloaded()) {
864 // If offloaded we allow flush during any state except terminated
865 // and keep the track active to avoid problems if user is seeking
866 // rapidly and underlying hardware has a significant delay handling
867 // a pause
868 if (isTerminated()) {
869 return;
870 }
871
872 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800873 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800874
875 if (mState == STOPPING_1 || mState == STOPPING_2) {
876 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
877 mState = ACTIVE;
878 }
879
Haynes Mathew George7844f672014-01-15 12:32:55 -0800880 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800881 mResumeToStopping = false;
882 } else {
883 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
884 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
885 return;
886 }
887 // No point remaining in PAUSED state after a flush => go to
888 // FLUSHED state
889 mState = FLUSHED;
890 // do not reset the track if it is still in the process of being stopped or paused.
891 // this will be done by prepareTracks_l() when the track is stopped.
892 // prepareTracks_l() will see mState == FLUSHED, then
893 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800894 if (isDirect()) {
895 mFlushHwPending = true;
896 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800897 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
898 reset();
899 }
Eric Laurent81784c32012-11-19 14:55:58 -0800900 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800901 // Prevent flush being lost if the track is flushed and then resumed
902 // before mixer thread can run. This is important when offloading
903 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700904 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800905 }
906}
907
Haynes Mathew George7844f672014-01-15 12:32:55 -0800908// must be called with thread lock held
909void AudioFlinger::PlaybackThread::Track::flushAck()
910{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800911 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800912 return;
913
Phil Burk4bb650b2016-09-09 12:11:17 -0700914 // Clear the client ring buffer so that the app can prime the buffer while paused.
915 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
916 mServerProxy->flushBufferIfNeeded();
917
Haynes Mathew George7844f672014-01-15 12:32:55 -0800918 mFlushHwPending = false;
919}
920
Eric Laurent81784c32012-11-19 14:55:58 -0800921void AudioFlinger::PlaybackThread::Track::reset()
922{
923 // Do not reset twice to avoid discarding data written just after a flush and before
924 // the audioflinger thread detects the track is stopped.
925 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800926 // Force underrun condition to avoid false underrun callback until first data is
927 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700928 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 mFillingUpStatus = FS_FILLING;
930 mResetDone = true;
931 if (mState == FLUSHED) {
932 mState = IDLE;
933 }
934 }
935}
936
Eric Laurentbfb1b832013-01-07 09:53:42 -0800937status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
938{
939 sp<ThreadBase> thread = mThread.promote();
940 if (thread == 0) {
941 ALOGE("thread is dead");
942 return FAILED_TRANSACTION;
943 } else if ((thread->type() == ThreadBase::DIRECT) ||
944 (thread->type() == ThreadBase::OFFLOAD)) {
945 return thread->setParameters(keyValuePairs);
946 } else {
947 return PERMISSION_DENIED;
948 }
949}
950
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800951VolumeShaper::Status AudioFlinger::PlaybackThread::Track::applyVolumeShaper(
952 const sp<VolumeShaper::Configuration>& configuration,
953 const sp<VolumeShaper::Operation>& operation)
954{
Andy Hung10cbff12017-02-21 17:30:14 -0800955 sp<VolumeShaper::Configuration> newConfiguration;
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800956
Andy Hung10cbff12017-02-21 17:30:14 -0800957 if (isOffloadedOrDirect()) {
958 const VolumeShaper::Configuration::OptionFlag optionFlag
959 = configuration->getOptionFlags();
960 if ((optionFlag & VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME) == 0) {
961 ALOGW("%s tracks do not support frame counted VolumeShaper,"
962 " using clock time instead", isOffloaded() ? "Offload" : "Direct");
963 newConfiguration = new VolumeShaper::Configuration(*configuration);
964 newConfiguration->setOptionFlags(
965 VolumeShaper::Configuration::OptionFlag(optionFlag
966 | VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME));
967 }
968 }
969
970 VolumeShaper::Status status = mVolumeHandler->applyVolumeShaper(
971 (newConfiguration.get() != nullptr ? newConfiguration : configuration), operation);
972
973 if (isOffloadedOrDirect()) {
974 // Signal thread to fetch new volume.
975 sp<ThreadBase> thread = mThread.promote();
976 if (thread != 0) {
977 Mutex::Autolock _l(thread->mLock);
978 thread->broadcast_l();
979 }
980 }
981 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800982}
983
984sp<VolumeShaper::State> AudioFlinger::PlaybackThread::Track::getVolumeShaperState(int id)
985{
986 // Note: We don't check if Thread exists.
987
988 // mVolumeHandler is thread safe.
989 return mVolumeHandler->getVolumeShaperState(id);
990}
991
Glenn Kasten573d80a2013-08-26 09:36:23 -0700992status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
993{
Andy Hung818e7a32016-02-16 18:08:07 -0800994 if (!isOffloaded() && !isDirect()) {
995 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700996 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700997 sp<ThreadBase> thread = mThread.promote();
998 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700999 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -07001000 }
Phil Burk6140c792015-03-19 14:30:21 -07001001
Glenn Kasten573d80a2013-08-26 09:36:23 -07001002 Mutex::Autolock _l(thread->mLock);
1003 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -08001004 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -07001005}
1006
Eric Laurent81784c32012-11-19 14:55:58 -08001007status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
1008{
1009 status_t status = DEAD_OBJECT;
1010 sp<ThreadBase> thread = mThread.promote();
1011 if (thread != 0) {
1012 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1013 sp<AudioFlinger> af = mClient->audioFlinger();
1014
1015 Mutex::Autolock _l(af->mLock);
1016
1017 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
1018
1019 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
1020 Mutex::Autolock _dl(playbackThread->mLock);
1021 Mutex::Autolock _sl(srcThread->mLock);
1022 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
1023 if (chain == 0) {
1024 return INVALID_OPERATION;
1025 }
1026
1027 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
1028 if (effect == 0) {
1029 return INVALID_OPERATION;
1030 }
1031 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001032 status = playbackThread->addEffect_l(effect);
1033 if (status != NO_ERROR) {
1034 srcThread->addEffect_l(effect);
1035 return INVALID_OPERATION;
1036 }
Eric Laurent81784c32012-11-19 14:55:58 -08001037 // removeEffect_l() has stopped the effect if it was active so it must be restarted
1038 if (effect->state() == EffectModule::ACTIVE ||
1039 effect->state() == EffectModule::STOPPING) {
1040 effect->start();
1041 }
1042
1043 sp<EffectChain> dstChain = effect->chain().promote();
1044 if (dstChain == 0) {
1045 srcThread->addEffect_l(effect);
1046 return INVALID_OPERATION;
1047 }
1048 AudioSystem::unregisterEffect(effect->id());
1049 AudioSystem::registerEffect(&effect->desc(),
1050 srcThread->id(),
1051 dstChain->strategy(),
1052 AUDIO_SESSION_OUTPUT_MIX,
1053 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07001054 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -08001055 }
1056 status = playbackThread->attachAuxEffect(this, EffectId);
1057 }
1058 return status;
1059}
1060
1061void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
1062{
1063 mAuxEffectId = EffectId;
1064 mAuxBuffer = buffer;
1065}
1066
Andy Hung818e7a32016-02-16 18:08:07 -08001067bool AudioFlinger::PlaybackThread::Track::presentationComplete(
1068 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001069{
Andy Hung818e7a32016-02-16 18:08:07 -08001070 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
1071 // This assists in proper timestamp computation as well as wakelock management.
1072
Eric Laurent81784c32012-11-19 14:55:58 -08001073 // a track is considered presented when the total number of frames written to audio HAL
1074 // corresponds to the number of frames written when presentationComplete() is called for the
1075 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001076 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1077 // to detect when all frames have been played. In this case framesWritten isn't
1078 // useful because it doesn't always reflect whether there is data in the h/w
1079 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung818e7a32016-02-16 18:08:07 -08001080 ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
1081 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001082 if (mPresentationCompleteFrames == 0) {
1083 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung818e7a32016-02-16 18:08:07 -08001084 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
1085 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08001086 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001087
Andy Hungc54b1ff2016-02-23 14:07:07 -08001088 bool complete;
1089 if (isOffloaded()) {
1090 complete = true;
1091 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001092 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -08001093 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001094 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -08001095 && mAudioTrackServerProxy->isDrained();
1096 }
1097
1098 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -08001099 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001100 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001101 return true;
1102 }
1103 return false;
1104}
1105
1106void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1107{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001108 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001109 if (mSyncEvents[i]->type() == type) {
1110 mSyncEvents[i]->trigger();
1111 mSyncEvents.removeAt(i);
1112 i--;
1113 }
1114 }
1115}
1116
1117// implement VolumeBufferProvider interface
1118
Glenn Kastenc56f3422014-03-21 17:53:17 -07001119gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001120{
1121 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1122 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001123 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1124 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1125 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001126 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001127 if (vl > GAIN_FLOAT_UNITY) {
1128 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001129 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001130 if (vr > GAIN_FLOAT_UNITY) {
1131 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001132 }
1133 // now apply the cached master volume and stream type volume;
1134 // this is trusted but lacks any synchronization or barrier so may be stale
1135 float v = mCachedVolume;
1136 vl *= v;
1137 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001138 // re-combine into packed minifloat
1139 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001140 // FIXME look at mute, pause, and stop flags
1141 return vlr;
1142}
1143
1144status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1145{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001146 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001147 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1148 (mState == STOPPED)))) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001149 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001150 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1151 event->cancel();
1152 return INVALID_OPERATION;
1153 }
1154 (void) TrackBase::setSyncEvent(event);
1155 return NO_ERROR;
1156}
1157
Glenn Kasten5736c352012-12-04 12:12:34 -08001158void AudioFlinger::PlaybackThread::Track::invalidate()
1159{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001160 TrackBase::invalidate();
Eric Laurent4d231dc2016-03-11 18:38:23 -08001161 signalClientFlag(CBLK_INVALID);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001162}
1163
1164void AudioFlinger::PlaybackThread::Track::disable()
1165{
1166 signalClientFlag(CBLK_DISABLED);
1167}
1168
1169void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1170{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001171 // FIXME should use proxy, and needs work
1172 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001173 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001174 android_atomic_release_store(0x40000000, &cblk->mFutex);
1175 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001176 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001177}
1178
Eric Laurent59fe0102013-09-27 18:48:26 -07001179void AudioFlinger::PlaybackThread::Track::signal()
1180{
1181 sp<ThreadBase> thread = mThread.promote();
1182 if (thread != 0) {
1183 PlaybackThread *t = (PlaybackThread *)thread.get();
1184 Mutex::Autolock _l(t->mLock);
1185 t->broadcast_l();
1186 }
1187}
1188
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001189//To be called with thread lock held
1190bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1191
1192 if (mState == RESUMING)
1193 return true;
1194 /* Resume is pending if track was stopping before pause was called */
1195 if (mState == STOPPING_1 &&
1196 mResumeToStopping)
1197 return true;
1198
1199 return false;
1200}
1201
1202//To be called with thread lock held
1203void AudioFlinger::PlaybackThread::Track::resumeAck() {
1204
1205
1206 if (mState == RESUMING)
1207 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001208
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001209 // Other possibility of pending resume is stopping_1 state
1210 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001211 // drain being called.
1212 if (mState == STOPPING_1) {
1213 mResumeToStopping = false;
1214 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001215}
Andy Hunge10393e2015-06-12 13:59:33 -07001216
1217//To be called with thread lock held
1218void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001219 int64_t trackFramesReleased, int64_t sinkFramesWritten,
1220 const ExtendedTimestamp &timeStamp) {
1221 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001222 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001223
1224 // adjust server times and set drained state.
1225 //
1226 // Our timestamps are only updated when the track is on the Thread active list.
1227 // We need to ensure that tracks are not removed before full drain.
1228 ExtendedTimestamp local = timeStamp;
1229 bool checked = false;
1230 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1231 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1232 // Lookup the track frame corresponding to the sink frame position.
1233 if (local.mTimeNs[i] > 0) {
1234 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1235 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001236 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hung818e7a32016-02-16 18:08:07 -08001237 mAudioTrackServerProxy->setDrained(
1238 local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1239 checked = true;
1240 }
1241 }
Andy Hunge10393e2015-06-12 13:59:33 -07001242 }
Andy Hung818e7a32016-02-16 18:08:07 -08001243 if (!checked) { // no server info, assume drained.
1244 mAudioTrackServerProxy->setDrained(true);
1245 }
Andy Hungea2b9c02016-02-12 17:06:53 -08001246 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001247 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001248 mServerProxy->setTimestamp(local);
Andy Hunge10393e2015-06-12 13:59:33 -07001249}
1250
Eric Laurent81784c32012-11-19 14:55:58 -08001251// ----------------------------------------------------------------------------
1252
Eric Laurent81784c32012-11-19 14:55:58 -08001253AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1254 PlaybackThread *playbackThread,
1255 DuplicatingThread *sourceThread,
1256 uint32_t sampleRate,
1257 audio_format_t format,
1258 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001259 size_t frameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001260 uid_t uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001261 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1262 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07001263 nullptr /* buffer */, (size_t)0 /* bufferSize */, nullptr /* sharedBuffer */,
1264 AUDIO_SESSION_NONE, uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001265 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07001266 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08001267{
1268
1269 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001270 mOutBuffer.frameCount = 0;
1271 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001272 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001273 "frameCount %zu, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001274 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001275 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001276 // since client and server are in the same process,
1277 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001278 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1279 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001280 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001281 mClientProxy->setSendLevel(0.0);
1282 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001283 } else {
1284 ALOGW("Error creating output track on thread %p", playbackThread);
1285 }
1286}
1287
1288AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1289{
1290 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001291 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001292}
1293
1294status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001295 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001296{
1297 status_t status = Track::start(event, triggerSession);
1298 if (status != NO_ERROR) {
1299 return status;
1300 }
1301
1302 mActive = true;
1303 mRetryCount = 127;
1304 return status;
1305}
1306
1307void AudioFlinger::PlaybackThread::OutputTrack::stop()
1308{
1309 Track::stop();
1310 clearBufferQueue();
1311 mOutBuffer.frameCount = 0;
1312 mActive = false;
1313}
1314
Andy Hungc25b84a2015-01-14 19:04:10 -08001315bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001316{
1317 Buffer *pInBuffer;
1318 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001319 bool outputBufferFull = false;
1320 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001321 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001322
1323 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1324
1325 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001326 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001327 }
1328
1329 while (waitTimeLeftMs) {
1330 // First write pending buffers, then new data
1331 if (mBufferQueue.size()) {
1332 pInBuffer = mBufferQueue.itemAt(0);
1333 } else {
1334 pInBuffer = &inBuffer;
1335 }
1336
1337 if (pInBuffer->frameCount == 0) {
1338 break;
1339 }
1340
1341 if (mOutBuffer.frameCount == 0) {
1342 mOutBuffer.frameCount = pInBuffer->frameCount;
1343 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001344 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001345 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001346 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1347 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001348 outputBufferFull = true;
1349 break;
1350 }
1351 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1352 if (waitTimeLeftMs >= waitTimeMs) {
1353 waitTimeLeftMs -= waitTimeMs;
1354 } else {
1355 waitTimeLeftMs = 0;
1356 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001357 if (status == NOT_ENOUGH_DATA) {
1358 restartIfDisabled();
1359 continue;
1360 }
Eric Laurent81784c32012-11-19 14:55:58 -08001361 }
1362
1363 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1364 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001365 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001366 Proxy::Buffer buf;
1367 buf.mFrameCount = outFrames;
1368 buf.mRaw = NULL;
1369 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001370 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001371 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001372 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001373 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001374 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001375
1376 if (pInBuffer->frameCount == 0) {
1377 if (mBufferQueue.size()) {
1378 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001379 free(pInBuffer->mBuffer);
Yunlian Jiang8adc8082017-06-06 15:59:44 -07001380 if (pInBuffer != &inBuffer) {
1381 delete pInBuffer;
1382 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001383 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001384 mThread.unsafe_get(), mBufferQueue.size());
1385 } else {
1386 break;
1387 }
1388 }
1389 }
1390
1391 // If we could not write all frames, allocate a buffer and queue it for next time.
1392 if (inBuffer.frameCount) {
1393 sp<ThreadBase> thread = mThread.promote();
1394 if (thread != 0 && !thread->standby()) {
1395 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1396 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001397 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001398 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001399 pInBuffer->raw = pInBuffer->mBuffer;
1400 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001401 mBufferQueue.add(pInBuffer);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001402 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001403 mThread.unsafe_get(), mBufferQueue.size());
1404 } else {
1405 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1406 mThread.unsafe_get(), this);
1407 }
1408 }
1409 }
1410
Andy Hungc25b84a2015-01-14 19:04:10 -08001411 // Calling write() with a 0 length buffer means that no more data will be written:
1412 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1413 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1414 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001415 }
1416
1417 return outputBufferFull;
1418}
1419
1420status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1421 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1422{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001423 ClientProxy::Buffer buf;
1424 buf.mFrameCount = buffer->frameCount;
1425 struct timespec timeout;
1426 timeout.tv_sec = waitTimeMs / 1000;
1427 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1428 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1429 buffer->frameCount = buf.mFrameCount;
1430 buffer->raw = buf.mRaw;
1431 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001432}
1433
Eric Laurent81784c32012-11-19 14:55:58 -08001434void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1435{
1436 size_t size = mBufferQueue.size();
1437
1438 for (size_t i = 0; i < size; i++) {
1439 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001440 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001441 delete pBuffer;
1442 }
1443 mBufferQueue.clear();
1444}
1445
Eric Laurent4d231dc2016-03-11 18:38:23 -08001446void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1447{
1448 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1449 if (mActive && (flags & CBLK_DISABLED)) {
1450 start();
1451 }
1452}
Eric Laurent81784c32012-11-19 14:55:58 -08001453
Eric Laurent83b88082014-06-20 18:31:16 -07001454AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001455 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001456 uint32_t sampleRate,
1457 audio_channel_mask_t channelMask,
1458 audio_format_t format,
1459 size_t frameCount,
1460 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07001461 size_t bufferSize,
Eric Laurent05067782016-06-01 18:27:28 -07001462 audio_output_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001463 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001464 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07001465 buffer, bufferSize, nullptr /* sharedBuffer */,
1466 AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001467 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1468{
1469 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1470 playbackThread->sampleRate();
1471 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1472 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1473
1474 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1475 this, sampleRate,
1476 (int)mPeerTimeout.tv_sec,
1477 (int)(mPeerTimeout.tv_nsec / 1000000));
1478}
1479
1480AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1481{
1482}
1483
Eric Laurent4d231dc2016-03-11 18:38:23 -08001484status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001485 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001486{
1487 status_t status = Track::start(event, triggerSession);
1488 if (status != NO_ERROR) {
1489 return status;
1490 }
1491 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1492 return status;
1493}
1494
Eric Laurent83b88082014-06-20 18:31:16 -07001495// AudioBufferProvider interface
1496status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001497 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001498{
1499 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1500 Proxy::Buffer buf;
1501 buf.mFrameCount = buffer->frameCount;
1502 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1503 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001504 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001505 if (buf.mFrameCount == 0) {
1506 return WOULD_BLOCK;
1507 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001508 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001509 return status;
1510}
1511
1512void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1513{
1514 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1515 Proxy::Buffer buf;
1516 buf.mFrameCount = buffer->frameCount;
1517 buf.mRaw = buffer->raw;
1518 mPeerProxy->releaseBuffer(&buf);
1519 TrackBase::releaseBuffer(buffer);
1520}
1521
1522status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1523 const struct timespec *timeOut)
1524{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001525 status_t status = NO_ERROR;
1526 static const int32_t kMaxTries = 5;
1527 int32_t tryCounter = kMaxTries;
1528 do {
1529 if (status == NOT_ENOUGH_DATA) {
1530 restartIfDisabled();
1531 }
1532 status = mProxy->obtainBuffer(buffer, timeOut);
1533 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1534 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001535}
1536
1537void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1538{
1539 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001540 restartIfDisabled();
1541 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1542}
1543
1544void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1545{
Eric Laurent83b88082014-06-20 18:31:16 -07001546 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1547 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1548 start();
1549 }
Eric Laurent83b88082014-06-20 18:31:16 -07001550}
1551
Eric Laurent81784c32012-11-19 14:55:58 -08001552// ----------------------------------------------------------------------------
1553// Record
1554// ----------------------------------------------------------------------------
1555
1556AudioFlinger::RecordHandle::RecordHandle(
1557 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1558 : BnAudioRecord(),
1559 mRecordTrack(recordTrack)
1560{
1561}
1562
1563AudioFlinger::RecordHandle::~RecordHandle() {
1564 stop_nonvirtual();
1565 mRecordTrack->destroy();
1566}
1567
Eric Laurent81784c32012-11-19 14:55:58 -08001568status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001569 audio_session_t triggerSession) {
Eric Laurent81784c32012-11-19 14:55:58 -08001570 ALOGV("RecordHandle::start()");
1571 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1572}
1573
1574void AudioFlinger::RecordHandle::stop() {
1575 stop_nonvirtual();
1576}
1577
1578void AudioFlinger::RecordHandle::stop_nonvirtual() {
1579 ALOGV("RecordHandle::stop()");
1580 mRecordTrack->stop();
1581}
1582
1583status_t AudioFlinger::RecordHandle::onTransact(
1584 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1585{
1586 return BnAudioRecord::onTransact(code, data, reply, flags);
1587}
1588
1589// ----------------------------------------------------------------------------
1590
Glenn Kasten05997e22014-03-13 15:08:33 -07001591// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001592AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1593 RecordThread *thread,
1594 const sp<Client>& client,
1595 uint32_t sampleRate,
1596 audio_format_t format,
1597 audio_channel_mask_t channelMask,
1598 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001599 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07001600 size_t bufferSize,
Glenn Kastend848eb42016-03-08 13:42:11 -08001601 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001602 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001603 audio_input_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001604 track_type type,
1605 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001606 : TrackBase(thread, client, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07001607 channelMask, frameCount, buffer, bufferSize, sessionId, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001608 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001609 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001610 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
Eric Laurent20b9ef02016-12-05 11:03:16 -08001611 type, portId),
Andy Hung97a893e2015-03-29 01:03:07 -07001612 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001613 mFramesToDrop(0),
1614 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001615 mRecordBufferConverter(NULL),
1616 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001617{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001618 if (mCblk == NULL) {
1619 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001620 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001621
Andy Hung97a893e2015-03-29 01:03:07 -07001622 mRecordBufferConverter = new RecordBufferConverter(
1623 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1624 channelMask, format, sampleRate);
1625 // Check if the RecordBufferConverter construction was successful.
1626 // If not, don't continue with construction.
1627 //
1628 // NOTE: It would be extremely rare that the record track cannot be created
1629 // for the current device, but a pending or future device change would make
1630 // the record track configuration valid.
1631 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1632 ALOGE("RecordTrack unable to create record buffer converter");
1633 return;
1634 }
1635
Andy Hung6ae58432016-02-16 18:32:24 -08001636 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001637 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001638
Andy Hung97a893e2015-03-29 01:03:07 -07001639 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001640
Eric Laurent05067782016-06-01 18:27:28 -07001641 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001642 ALOG_ASSERT(thread->mFastTrackAvail);
1643 thread->mFastTrackAvail = false;
1644 }
Eric Laurent81784c32012-11-19 14:55:58 -08001645}
1646
1647AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1648{
1649 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001650 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001651 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001652}
1653
Andy Hung97a893e2015-03-29 01:03:07 -07001654status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1655{
1656 status_t status = TrackBase::initCheck();
1657 if (status == NO_ERROR && mServerProxy == 0) {
1658 status = BAD_VALUE;
1659 }
1660 return status;
1661}
1662
Eric Laurent81784c32012-11-19 14:55:58 -08001663// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001664status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001665{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001666 ServerProxy::Buffer buf;
1667 buf.mFrameCount = buffer->frameCount;
1668 status_t status = mServerProxy->obtainBuffer(&buf);
1669 buffer->frameCount = buf.mFrameCount;
1670 buffer->raw = buf.mRaw;
1671 if (buf.mFrameCount == 0) {
1672 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001673 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001674 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001675 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001676}
1677
1678status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001679 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001680{
1681 sp<ThreadBase> thread = mThread.promote();
1682 if (thread != 0) {
1683 RecordThread *recordThread = (RecordThread *)thread.get();
1684 return recordThread->start(this, event, triggerSession);
1685 } else {
1686 return BAD_VALUE;
1687 }
1688}
1689
1690void AudioFlinger::RecordThread::RecordTrack::stop()
1691{
1692 sp<ThreadBase> thread = mThread.promote();
1693 if (thread != 0) {
1694 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001695 if (recordThread->stop(this) && isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001696 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001697 }
1698 }
1699}
1700
1701void AudioFlinger::RecordThread::RecordTrack::destroy()
1702{
1703 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1704 sp<RecordTrack> keep(this);
1705 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001706 if (isExternalTrack()) {
1707 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001708 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001709 }
Glenn Kastend848eb42016-03-08 13:42:11 -08001710 AudioSystem::releaseInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001711 }
Eric Laurent81784c32012-11-19 14:55:58 -08001712 sp<ThreadBase> thread = mThread.promote();
1713 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001714 Mutex::Autolock _l(thread->mLock);
1715 RecordThread *recordThread = (RecordThread *) thread.get();
1716 recordThread->destroyTrack_l(this);
1717 }
1718 }
1719}
1720
Eric Laurent9a54bc22013-09-09 09:08:44 -07001721void AudioFlinger::RecordThread::RecordTrack::invalidate()
1722{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001723 TrackBase::invalidate();
Eric Laurent9a54bc22013-09-09 09:08:44 -07001724 // FIXME should use proxy, and needs work
1725 audio_track_cblk_t* cblk = mCblk;
1726 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1727 android_atomic_release_store(0x40000000, &cblk->mFutex);
1728 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001729 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001730}
1731
Eric Laurent81784c32012-11-19 14:55:58 -08001732
1733/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1734{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001735 result.append("Active Client Session S Flags Format Chn mask SRate Server FrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001736}
1737
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001738void AudioFlinger::RecordThread::RecordTrack::appendDump(String8& result, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001739{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001740 result.appendFormat("%c%5s %6u %7u %2s 0x%03X "
1741 "%08X %08X %6u "
1742 "%08X %6zu\n",
1743 isFastTrack() ? 'F' : ' ',
Marco Nelissenb2208842014-02-07 14:00:50 -08001744 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001745 (mClient == 0) ? getpid_cached : mClient->pid(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001746 mSessionId,
1747 getTrackStateString(),
1748 mCblk->mFlags,
1749
Eric Laurent81784c32012-11-19 14:55:58 -08001750 mFormat,
1751 mChannelMask,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001752 mSampleRate,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001753
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001754 mCblk->mServer,
1755 mFrameCount
1756 );
Eric Laurent81784c32012-11-19 14:55:58 -08001757}
1758
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001759void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1760{
1761 if (event == mSyncStartEvent) {
1762 ssize_t framesToDrop = 0;
1763 sp<ThreadBase> threadBase = mThread.promote();
1764 if (threadBase != 0) {
1765 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1766 // from audio HAL
1767 framesToDrop = threadBase->mFrameCount * 2;
1768 }
1769 mFramesToDrop = framesToDrop;
1770 }
1771}
1772
1773void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1774{
1775 if (mSyncStartEvent != 0) {
1776 mSyncStartEvent->cancel();
1777 mSyncStartEvent.clear();
1778 }
1779 mFramesToDrop = 0;
1780}
1781
Andy Hung3f0c9022016-01-15 17:49:46 -08001782void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1783 int64_t trackFramesReleased, int64_t sourceFramesRead,
1784 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1785{
1786 ExtendedTimestamp local = timestamp;
1787
1788 // Convert HAL frames to server-side track frames at track sample rate.
1789 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1790 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1791 if (local.mTimeNs[i] != 0) {
1792 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1793 const int64_t relativeTrackFrames = relativeServerFrames
1794 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1795 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1796 }
1797 }
Andy Hung6ae58432016-02-16 18:32:24 -08001798 mServerProxy->setTimestamp(local);
Andy Hung3f0c9022016-01-15 17:49:46 -08001799}
Eric Laurent83b88082014-06-20 18:31:16 -07001800
1801AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1802 uint32_t sampleRate,
1803 audio_channel_mask_t channelMask,
1804 audio_format_t format,
1805 size_t frameCount,
1806 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07001807 size_t bufferSize,
Eric Laurent05067782016-06-01 18:27:28 -07001808 audio_input_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07001809 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07001810 buffer, bufferSize, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001811 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1812{
1813 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1814 recordThread->sampleRate();
1815 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1816 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1817
1818 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1819 this, sampleRate,
1820 (int)mPeerTimeout.tv_sec,
1821 (int)(mPeerTimeout.tv_nsec / 1000000));
1822}
1823
1824AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1825{
1826}
1827
1828// AudioBufferProvider interface
1829status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001830 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001831{
1832 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1833 Proxy::Buffer buf;
1834 buf.mFrameCount = buffer->frameCount;
1835 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1836 ALOGV_IF(status != NO_ERROR,
1837 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001838 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001839 if (buf.mFrameCount == 0) {
1840 return WOULD_BLOCK;
1841 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001842 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001843 return status;
1844}
1845
1846void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1847{
1848 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1849 Proxy::Buffer buf;
1850 buf.mFrameCount = buffer->frameCount;
1851 buf.mRaw = buffer->raw;
1852 mPeerProxy->releaseBuffer(&buf);
1853 TrackBase::releaseBuffer(buffer);
1854}
1855
1856status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1857 const struct timespec *timeOut)
1858{
1859 return mProxy->obtainBuffer(buffer, timeOut);
1860}
1861
1862void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1863{
1864 mProxy->releaseBuffer(buffer);
1865}
1866
Eric Laurent6acd1d42017-01-04 14:23:29 -08001867
1868
1869AudioFlinger::MmapThread::MmapTrack::MmapTrack(ThreadBase *thread,
1870 uint32_t sampleRate,
1871 audio_format_t format,
1872 audio_channel_mask_t channelMask,
1873 audio_session_t sessionId,
1874 uid_t uid,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001875 pid_t pid,
Eric Laurent6acd1d42017-01-04 14:23:29 -08001876 audio_port_handle_t portId)
1877 : TrackBase(thread, NULL, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07001878 channelMask, (size_t)0 /* frameCount */,
1879 nullptr /* buffer */, (size_t)0 /* bufferSize */,
1880 sessionId, uid, false /* isOut */,
Eric Laurent6acd1d42017-01-04 14:23:29 -08001881 ALLOC_NONE,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001882 TYPE_DEFAULT, portId),
1883 mPid(pid)
Eric Laurent6acd1d42017-01-04 14:23:29 -08001884{
1885}
1886
1887AudioFlinger::MmapThread::MmapTrack::~MmapTrack()
1888{
1889}
1890
1891status_t AudioFlinger::MmapThread::MmapTrack::initCheck() const
1892{
1893 return NO_ERROR;
1894}
1895
1896status_t AudioFlinger::MmapThread::MmapTrack::start(AudioSystem::sync_event_t event __unused,
1897 audio_session_t triggerSession __unused)
1898{
1899 return NO_ERROR;
1900}
1901
1902void AudioFlinger::MmapThread::MmapTrack::stop()
1903{
1904}
1905
1906// AudioBufferProvider interface
1907status_t AudioFlinger::MmapThread::MmapTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
1908{
1909 buffer->frameCount = 0;
1910 buffer->raw = nullptr;
1911 return INVALID_OPERATION;
1912}
1913
1914// ExtendedAudioBufferProvider interface
1915size_t AudioFlinger::MmapThread::MmapTrack::framesReady() const {
1916 return 0;
1917}
1918
1919int64_t AudioFlinger::MmapThread::MmapTrack::framesReleased() const
1920{
1921 return 0;
1922}
1923
1924void AudioFlinger::MmapThread::MmapTrack::onTimestamp(const ExtendedTimestamp &timestamp __unused)
1925{
1926}
1927
1928/*static*/ void AudioFlinger::MmapThread::MmapTrack::appendDumpHeader(String8& result)
1929{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001930 result.append("Client Session Format Chn mask SRate\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001931}
1932
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001933void AudioFlinger::MmapThread::MmapTrack::appendDump(String8& result, bool active __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08001934{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001935 result.appendFormat("%6u %7u %08X %08X %6u\n",
1936 mPid,
1937 mSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08001938 mFormat,
1939 mChannelMask,
1940 mSampleRate);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001941}
1942
Glenn Kasten63238ef2015-03-02 15:50:29 -08001943} // namespace android