blob: edf41fd3605071ea2587173e731606c1d42f736f [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenad8510a2015-02-17 16:24:07 -080023#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070025#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080026#include <utils/Log.h>
27
28#include <private/media/AudioTrackShared.h>
29
Eric Laurent81784c32012-11-19 14:55:58 -080030#include "AudioFlinger.h"
31#include "ServiceUtilities.h"
32
Glenn Kastenda6ef132013-01-10 12:31:01 -080033#include <media/nbaio/Pipe.h>
34#include <media/nbaio/PipeReader.h>
Andy Hung89816052017-01-11 17:08:23 -080035#include <media/RecordBufferConverter.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070036#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080037
Eric Laurent81784c32012-11-19 14:55:58 -080038// ----------------------------------------------------------------------------
39
40// Note: the following macro is used for extremely verbose logging message. In
41// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
42// 0; but one side effect of this is to turn all LOGV's as well. Some messages
43// are so verbose that we want to suppress them even when we have ALOG_ASSERT
44// turned on. Do not uncomment the #def below unless you really know what you
45// are doing and want to see all of the extremely verbose messages.
46//#define VERY_VERY_VERBOSE_LOGGING
47#ifdef VERY_VERY_VERBOSE_LOGGING
48#define ALOGVV ALOGV
49#else
50#define ALOGVV(a...) do { } while(0)
51#endif
52
Andy Hunge10393e2015-06-12 13:59:33 -070053// TODO move to a common header (Also shared with AudioTrack.cpp)
54#define NANOS_PER_SECOND 1000000000
Chih-Hung Hsieh9a3fbd92016-06-03 15:09:07 -070055#define TIME_TO_NANOS(time) ((uint64_t)(time).tv_sec * NANOS_PER_SECOND + (time).tv_nsec)
Andy Hunge10393e2015-06-12 13:59:33 -070056
Eric Laurent81784c32012-11-19 14:55:58 -080057namespace android {
58
59// ----------------------------------------------------------------------------
60// TrackBase
61// ----------------------------------------------------------------------------
62
Glenn Kastenda6ef132013-01-10 12:31:01 -080063static volatile int32_t nextTrackId = 55;
64
Eric Laurent81784c32012-11-19 14:55:58 -080065// TrackBase constructor must be called with AudioFlinger::mLock held
66AudioFlinger::ThreadBase::TrackBase::TrackBase(
67 ThreadBase *thread,
68 const sp<Client>& client,
69 uint32_t sampleRate,
70 audio_format_t format,
71 audio_channel_mask_t channelMask,
72 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070073 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -080074 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -080075 uid_t clientUid,
Glenn Kastend776ac62014-05-07 09:16:09 -070076 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070077 alloc_type alloc,
Eric Laurent20b9ef02016-12-05 11:03:16 -080078 track_type type,
79 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -080080 : RefBase(),
81 mThread(thread),
82 mClient(client),
83 mCblk(NULL),
84 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080085 mState(IDLE),
86 mSampleRate(sampleRate),
87 mFormat(format),
88 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070089 mChannelCount(isOut ?
90 audio_channel_count_from_out_mask(channelMask) :
91 audio_channel_count_from_in_mask(channelMask)),
Phil Burkfdb3c072016-02-09 10:47:02 -080092 mFrameSize(audio_has_proportional_frames(format) ?
Eric Laurent81784c32012-11-19 14:55:58 -080093 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
94 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080095 mSessionId(sessionId),
96 mIsOut(isOut),
Eric Laurentbfb1b832013-01-07 09:53:42 -080097 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070098 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -070099 mType(type),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800100 mThreadIoHandle(thread->id()),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800101 mPortId(portId),
102 mIsInvalid(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800103{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700104 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung1f12a8a2016-11-07 16:10:30 -0800105 if (!isTrustedCallingUid(callingUid) || clientUid == AUDIO_UID_INVALID) {
106 ALOGW_IF(clientUid != AUDIO_UID_INVALID && clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -0700107 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
Andy Hung1f12a8a2016-11-07 16:10:30 -0800108 clientUid = callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800109 }
110 // clientUid contains the uid of the app that is responsible for this track, so we can blame
111 // battery usage on it.
112 mUid = clientUid;
113
Eric Laurent81784c32012-11-19 14:55:58 -0800114 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hung1883f692017-02-13 18:48:39 -0800115
116 size_t bufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
117 // check overflow when computing bufferSize due to multiplication by mFrameSize.
118 if (bufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
119 || mFrameSize == 0 // format needs to be correct
120 || bufferSize > SIZE_MAX / mFrameSize) {
121 android_errorWriteLog(0x534e4554, "34749571");
122 return;
123 }
124 bufferSize *= mFrameSize;
125
Eric Laurent81784c32012-11-19 14:55:58 -0800126 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700127 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hung1883f692017-02-13 18:48:39 -0800128 // check overflow when computing allocation size for streaming tracks.
129 if (size > SIZE_MAX - bufferSize) {
130 android_errorWriteLog(0x534e4554, "34749571");
131 return;
132 }
Eric Laurent81784c32012-11-19 14:55:58 -0800133 size += bufferSize;
134 }
135
136 if (client != 0) {
137 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700138 if (mCblkMemory == 0 ||
139 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700140 ALOGE("not enough memory for AudioTrack size=%zu", size);
Eric Laurent81784c32012-11-19 14:55:58 -0800141 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700142 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800143 return;
144 }
145 } else {
Andy Hungafb31482017-02-13 18:50:48 -0800146 mCblk = (audio_track_cblk_t *) malloc(size);
147 if (mCblk == NULL) {
148 ALOGE("not enough memory for AudioTrack size=%zu", size);
149 return;
150 }
Eric Laurent81784c32012-11-19 14:55:58 -0800151 }
152
153 // construct the shared structure in-place.
154 if (mCblk != NULL) {
155 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700156 switch (alloc) {
157 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700158 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
159 if (roHeap == 0 ||
160 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
161 (mBuffer = mBufferMemory->pointer()) == NULL) {
162 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
163 if (roHeap != 0) {
164 roHeap->dump("buffer");
165 }
166 mCblkMemory.clear();
167 mBufferMemory.clear();
168 return;
169 }
Eric Laurent81784c32012-11-19 14:55:58 -0800170 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700171 } break;
172 case ALLOC_PIPE:
173 mBufferMemory = thread->pipeMemory();
174 // mBuffer is the virtual address as seen from current process (mediaserver),
175 // and should normally be coming from mBufferMemory->pointer().
176 // However in this case the TrackBase does not reference the buffer directly.
177 // It should references the buffer via the pipe.
178 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
179 mBuffer = NULL;
180 break;
181 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700182 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700183 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700184 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
185 memset(mBuffer, 0, bufferSize);
186 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700187 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800188#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700189 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800190#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700191 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700192 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700193 case ALLOC_LOCAL:
194 mBuffer = calloc(1, bufferSize);
195 break;
196 case ALLOC_NONE:
197 mBuffer = buffer;
198 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800199 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800200
Glenn Kasten46909e72013-02-26 09:20:22 -0800201#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800202 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700203 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800204 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800205 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
206 size_t numCounterOffers = 0;
207 const NBAIO_Format offers[1] = {pipeFormat};
208 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
209 ALOG_ASSERT(index == 0);
210 PipeReader *pipeReader = new PipeReader(*pipe);
211 numCounterOffers = 0;
212 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
213 ALOG_ASSERT(index == 0);
214 mTeeSink = pipe;
215 mTeeSource = pipeReader;
216 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800217 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800218#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800219
Eric Laurent81784c32012-11-19 14:55:58 -0800220 }
221}
222
Eric Laurent83b88082014-06-20 18:31:16 -0700223status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
224{
225 status_t status;
226 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
227 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
228 } else {
229 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
230 }
231 return status;
232}
233
Eric Laurent81784c32012-11-19 14:55:58 -0800234AudioFlinger::ThreadBase::TrackBase::~TrackBase()
235{
Glenn Kasten46909e72013-02-26 09:20:22 -0800236#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800237 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800238#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800239 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
Eric Laurent5bba2f62016-03-18 11:14:14 -0700240 mServerProxy.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800241 if (mCblk != NULL) {
Andy Hungafb31482017-02-13 18:50:48 -0800242 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurent81784c32012-11-19 14:55:58 -0800243 if (mClient == 0) {
Andy Hungafb31482017-02-13 18:50:48 -0800244 free(mCblk);
Eric Laurent81784c32012-11-19 14:55:58 -0800245 }
246 }
247 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
248 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700249 // Client destructor must run with AudioFlinger client mutex locked
250 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800251 // If the client's reference count drops to zero, the associated destructor
252 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
253 // relying on the automatic clear() at end of scope.
254 mClient.clear();
255 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700256 // flush the binder command buffer
257 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800258}
259
260// AudioBufferProvider interface
261// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800262// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800263void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
264{
Glenn Kasten46909e72013-02-26 09:20:22 -0800265#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800266 if (mTeeSink != 0) {
267 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
268 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800269#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800270
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800271 ServerProxy::Buffer buf;
272 buf.mFrameCount = buffer->frameCount;
273 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800274 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800275 buffer->raw = NULL;
276 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800277}
278
Eric Laurent81784c32012-11-19 14:55:58 -0800279status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
280{
281 mSyncEvents.add(event);
282 return NO_ERROR;
283}
284
285// ----------------------------------------------------------------------------
286// Playback
287// ----------------------------------------------------------------------------
288
289AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
290 : BnAudioTrack(),
291 mTrack(track)
292{
293}
294
295AudioFlinger::TrackHandle::~TrackHandle() {
296 // just stop the track on deletion, associated resources
297 // will be freed from the main thread once all pending buffers have
298 // been played. Unless it's not in the active track list, in which
299 // case we free everything now...
300 mTrack->destroy();
301}
302
303sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
304 return mTrack->getCblk();
305}
306
307status_t AudioFlinger::TrackHandle::start() {
308 return mTrack->start();
309}
310
311void AudioFlinger::TrackHandle::stop() {
312 mTrack->stop();
313}
314
315void AudioFlinger::TrackHandle::flush() {
316 mTrack->flush();
317}
318
Eric Laurent81784c32012-11-19 14:55:58 -0800319void AudioFlinger::TrackHandle::pause() {
320 mTrack->pause();
321}
322
323status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
324{
325 return mTrack->attachAuxEffect(EffectId);
326}
327
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700328status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
329 return mTrack->setParameters(keyValuePairs);
330}
331
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800332VolumeShaper::Status AudioFlinger::TrackHandle::applyVolumeShaper(
333 const sp<VolumeShaper::Configuration>& configuration,
334 const sp<VolumeShaper::Operation>& operation) {
335 return mTrack->applyVolumeShaper(configuration, operation);
336}
337
338sp<VolumeShaper::State> AudioFlinger::TrackHandle::getVolumeShaperState(int id) {
339 return mTrack->getVolumeShaperState(id);
340}
341
Glenn Kasten53cec222013-08-29 09:01:02 -0700342status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
343{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700344 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700345}
346
Eric Laurent59fe0102013-09-27 18:48:26 -0700347
348void AudioFlinger::TrackHandle::signal()
349{
350 return mTrack->signal();
351}
352
Eric Laurent81784c32012-11-19 14:55:58 -0800353status_t AudioFlinger::TrackHandle::onTransact(
354 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
355{
356 return BnAudioTrack::onTransact(code, data, reply, flags);
357}
358
359// ----------------------------------------------------------------------------
360
361// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
362AudioFlinger::PlaybackThread::Track::Track(
363 PlaybackThread *thread,
364 const sp<Client>& client,
365 audio_stream_type_t streamType,
366 uint32_t sampleRate,
367 audio_format_t format,
368 audio_channel_mask_t channelMask,
369 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700370 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800371 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800372 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800373 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -0700374 audio_output_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800375 track_type type,
376 audio_port_handle_t portId)
Eric Laurent83b88082014-06-20 18:31:16 -0700377 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
378 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
Eric Laurent05067782016-06-01 18:27:28 -0700379 sessionId, uid, true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700380 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800381 type, portId),
Eric Laurent81784c32012-11-19 14:55:58 -0800382 mFillingUpStatus(FS_INVALID),
383 // mRetryCount initialized later when needed
384 mSharedBuffer(sharedBuffer),
385 mStreamType(streamType),
386 mName(-1), // see note below
387 mMainBuffer(thread->mixBuffer()),
388 mAuxBuffer(NULL),
389 mAuxEffectId(0), mHasVolumeController(false),
390 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700391 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800392 mVolumeHandler(new VolumeHandler(sampleRate)),
Andy Hunge10393e2015-06-12 13:59:33 -0700393 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800394 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800395 mCachedVolume(1.0),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800396 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700397 mFlushHwPending(false),
398 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -0800399{
Eric Laurent83b88082014-06-20 18:31:16 -0700400 // client == 0 implies sharedBuffer == 0
401 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
402
Eric Laurente93cc032016-05-05 10:15:10 -0700403 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Eric Laurent83b88082014-06-20 18:31:16 -0700404 sharedBuffer->size());
405
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700406 if (mCblk == NULL) {
407 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800408 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700409
410 if (sharedBuffer == 0) {
411 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700412 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700413 } else {
414 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
415 mFrameSize);
416 }
417 mServerProxy = mAudioTrackServerProxy;
418
Eric Laurentad7dd962016-09-22 12:38:37 -0700419 mName = thread->getTrackName_l(channelMask, format, sessionId, uid);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700420 if (mName < 0) {
421 ALOGE("no more track names available");
422 return;
423 }
424 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700425 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700426 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
427 // race with setSyncEvent(). However, if we call it, we cannot properly start
428 // static fast tracks (SoundPool) immediately after stopping.
429 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700430 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
431 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700432 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700433 // FIXME This is too eager. We allocate a fast track index before the
434 // fast track becomes active. Since fast tracks are a scarce resource,
435 // this means we are potentially denying other more important fast tracks from
436 // being created. It would be better to allocate the index dynamically.
437 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700438 thread->mFastTrackAvailMask &= ~(1 << i);
439 }
Eric Laurent81784c32012-11-19 14:55:58 -0800440}
441
442AudioFlinger::PlaybackThread::Track::~Track()
443{
444 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700445
446 // The destructor would clear mSharedBuffer,
447 // but it will not push the decremented reference count,
448 // leaving the client's IMemory dangling indefinitely.
449 // This prevents that leak.
450 if (mSharedBuffer != 0) {
451 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700452 }
Eric Laurent81784c32012-11-19 14:55:58 -0800453}
454
Glenn Kasten03003332013-08-06 15:40:54 -0700455status_t AudioFlinger::PlaybackThread::Track::initCheck() const
456{
457 status_t status = TrackBase::initCheck();
458 if (status == NO_ERROR && mName < 0) {
459 status = NO_MEMORY;
460 }
461 return status;
462}
463
Eric Laurent81784c32012-11-19 14:55:58 -0800464void AudioFlinger::PlaybackThread::Track::destroy()
465{
466 // NOTE: destroyTrack_l() can remove a strong reference to this Track
467 // by removing it from mTracks vector, so there is a risk that this Tracks's
468 // destructor is called. As the destructor needs to lock mLock,
469 // we must acquire a strong reference on this Track before locking mLock
470 // here so that the destructor is called only when exiting this function.
471 // On the other hand, as long as Track::destroy() is only called by
472 // TrackHandle destructor, the TrackHandle still holds a strong ref on
473 // this Track with its member mTrack.
474 sp<Track> keep(this);
475 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700476 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800477 sp<ThreadBase> thread = mThread.promote();
478 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800479 Mutex::Autolock _l(thread->mLock);
480 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700481 wasActive = playbackThread->destroyTrack_l(this);
482 }
483 if (isExternalTrack() && !wasActive) {
Glenn Kastend848eb42016-03-08 13:42:11 -0800484 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800485 }
486 }
487}
488
489/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
490{
Marco Nelissenb2208842014-02-07 14:00:50 -0800491 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Andy Hung2148bf02016-11-28 19:01:02 -0800492 "L dB R dB Server Main buf Aux buf Flags UndFrmCnt Flushed\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800493}
494
Marco Nelissenb2208842014-02-07 14:00:50 -0800495void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800496{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700497 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800498 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800499 sprintf(buffer, " F %2d", mFastIndex);
500 } else if (mName >= AudioMixer::TRACK0) {
501 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800502 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800503 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800504 }
505 track_state state = mState;
506 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800507 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800508 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800509 } else {
510 switch (state) {
511 case IDLE:
512 stateChar = 'I';
513 break;
514 case STOPPING_1:
515 stateChar = 's';
516 break;
517 case STOPPING_2:
518 stateChar = '5';
519 break;
520 case STOPPED:
521 stateChar = 'S';
522 break;
523 case RESUMING:
524 stateChar = 'R';
525 break;
526 case ACTIVE:
527 stateChar = 'A';
528 break;
529 case PAUSING:
530 stateChar = 'p';
531 break;
532 case PAUSED:
533 stateChar = 'P';
534 break;
535 case FLUSHED:
536 stateChar = 'F';
537 break;
538 default:
539 stateChar = '?';
540 break;
541 }
Eric Laurent81784c32012-11-19 14:55:58 -0800542 }
543 char nowInUnderrun;
544 switch (mObservedUnderruns.mBitFields.mMostRecent) {
545 case UNDERRUN_FULL:
546 nowInUnderrun = ' ';
547 break;
548 case UNDERRUN_PARTIAL:
549 nowInUnderrun = '<';
550 break;
551 case UNDERRUN_EMPTY:
552 nowInUnderrun = '*';
553 break;
554 default:
555 nowInUnderrun = '?';
556 break;
557 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000558 snprintf(&buffer[8], size-8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u %5.2g %5.2g "
Andy Hung2148bf02016-11-28 19:01:02 -0800559 "%08X %08zX %08zX 0x%03X %9u%c %7u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800560 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800561 (mClient == 0) ? getpid_cached : mClient->pid(),
562 mStreamType,
563 mFormat,
564 mChannelMask,
565 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800566 mFrameCount,
567 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800568 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800569 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700570 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
571 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700572 mCblk->mServer,
Andy Hung2148bf02016-11-28 19:01:02 -0800573 (size_t)mMainBuffer, // use %zX as %p appends 0x
574 (size_t)mAuxBuffer, // use %zX as %p appends 0x
Glenn Kasten96f60d82013-07-12 10:21:18 -0700575 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700576 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -0800577 nowInUnderrun,
578 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000); // 7 digits
Eric Laurent81784c32012-11-19 14:55:58 -0800579}
580
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800581uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
582 return mAudioTrackServerProxy->getSampleRate();
583}
584
Eric Laurent81784c32012-11-19 14:55:58 -0800585// AudioBufferProvider interface
586status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800587 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800588{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800589 ServerProxy::Buffer buf;
590 size_t desiredFrames = buffer->frameCount;
591 buf.mFrameCount = desiredFrames;
592 status_t status = mServerProxy->obtainBuffer(&buf);
593 buffer->frameCount = buf.mFrameCount;
594 buffer->raw = buf.mRaw;
595 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700596 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800597 } else {
598 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800599 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800600
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800601 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800602}
603
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700604// releaseBuffer() is not overridden
605
606// ExtendedAudioBufferProvider interface
607
Andy Hung27876c02014-09-09 18:07:55 -0700608// framesReady() may return an approximation of the number of frames if called
609// from a different thread than the one calling Proxy->obtainBuffer() and
610// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
611// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800612size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700613 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
614 // Static tracks return zero frames immediately upon stopping (for FastTracks).
615 // The remainder of the buffer is not drained.
616 return 0;
617 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800618 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800619}
620
Andy Hung818e7a32016-02-16 18:08:07 -0800621int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700622{
623 return mAudioTrackServerProxy->framesReleased();
624}
625
Andy Hung818e7a32016-02-16 18:08:07 -0800626void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800627{
628 // This call comes from a FastTrack and should be kept lockless.
629 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800630 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800631
Andy Hung818e7a32016-02-16 18:08:07 -0800632 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hung6ae58432016-02-16 18:32:24 -0800633}
634
Eric Laurent81784c32012-11-19 14:55:58 -0800635// Don't call for fast tracks; the framesReady() could result in priority inversion
636bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800637 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
638 return true;
639 }
640
Eric Laurent16498512014-03-17 17:22:08 -0700641 if (isStopping()) {
642 if (framesReady() > 0) {
643 mFillingUpStatus = FS_FILLED;
644 }
Eric Laurent81784c32012-11-19 14:55:58 -0800645 return true;
646 }
647
Phil Burke8972b02016-03-04 11:29:57 -0800648 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700649 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800650 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700651 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800652 return true;
653 }
654 return false;
655}
656
Glenn Kasten0f11b512014-01-31 16:18:54 -0800657status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800658 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800659{
660 status_t status = NO_ERROR;
661 ALOGV("start(%d), calling pid %d session %d",
662 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
663
664 sp<ThreadBase> thread = mThread.promote();
665 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700666 if (isOffloaded()) {
667 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
668 Mutex::Autolock _lth(thread->mLock);
669 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700670 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
671 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700672 invalidate();
673 return PERMISSION_DENIED;
674 }
675 }
676 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800677 track_state state = mState;
678 // here the track could be either new, or restarted
679 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800680
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800681 // initial state-stopping. next state-pausing.
682 // What if resume is called ?
683
684 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800685 if (mResumeToStopping) {
686 // happened we need to resume to STOPPING_1
687 mState = TrackBase::STOPPING_1;
688 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
689 } else {
690 mState = TrackBase::RESUMING;
691 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
692 }
Eric Laurent81784c32012-11-19 14:55:58 -0800693 } else {
694 mState = TrackBase::ACTIVE;
695 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
696 }
697
Andy Hunge10393e2015-06-12 13:59:33 -0700698 // states to reset position info for non-offloaded/direct tracks
699 if (!isOffloaded() && !isDirect()
700 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
701 mFrameMap.reset();
702 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800703 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700704 if (isFastTrack()) {
705 // refresh fast track underruns on start because that field is never cleared
706 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
707 // after stop.
708 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
709 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800710 status = playbackThread->addTrack_l(this);
711 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800712 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800713 // restore previous state if start was rejected by policy manager
714 if (status == PERMISSION_DENIED) {
715 mState = state;
716 }
717 }
718 // track was already in the active list, not a problem
719 if (status == ALREADY_EXISTS) {
720 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700721 } else {
722 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
723 // It is usually unsafe to access the server proxy from a binder thread.
724 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
725 // isn't looking at this track yet: we still hold the normal mixer thread lock,
726 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700727 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700728 ServerProxy::Buffer buffer;
729 buffer.mFrameCount = 1;
730 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800731 }
732 } else {
733 status = BAD_VALUE;
734 }
735 return status;
736}
737
738void AudioFlinger::PlaybackThread::Track::stop()
739{
740 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
741 sp<ThreadBase> thread = mThread.promote();
742 if (thread != 0) {
743 Mutex::Autolock _l(thread->mLock);
744 track_state state = mState;
745 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
746 // If the track is not active (PAUSED and buffers full), flush buffers
747 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
748 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
749 reset();
750 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700751 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800752 mState = STOPPED;
753 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800754 // For fast tracks prepareTracks_l() will set state to STOPPING_2
755 // presentation is complete
756 // For an offloaded track this starts a drain and state will
757 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800758 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -0700759 if (isOffloaded()) {
760 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
761 }
Eric Laurent81784c32012-11-19 14:55:58 -0800762 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700763 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800764 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
765 playbackThread);
766 }
Eric Laurent81784c32012-11-19 14:55:58 -0800767 }
768}
769
770void AudioFlinger::PlaybackThread::Track::pause()
771{
772 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
773 sp<ThreadBase> thread = mThread.promote();
774 if (thread != 0) {
775 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800776 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
777 switch (mState) {
778 case STOPPING_1:
779 case STOPPING_2:
780 if (!isOffloaded()) {
781 /* nothing to do if track is not offloaded */
782 break;
783 }
784
785 // Offloaded track was draining, we need to carry on draining when resumed
786 mResumeToStopping = true;
787 // fall through...
788 case ACTIVE:
789 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800790 mState = PAUSING;
791 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700792 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800793 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800794
Eric Laurentbfb1b832013-01-07 09:53:42 -0800795 default:
796 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800797 }
798 }
799}
800
801void AudioFlinger::PlaybackThread::Track::flush()
802{
803 ALOGV("flush(%d)", mName);
804 sp<ThreadBase> thread = mThread.promote();
805 if (thread != 0) {
806 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800807 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800808
Phil Burk4bb650b2016-09-09 12:11:17 -0700809 // Flush the ring buffer now if the track is not active in the PlaybackThread.
810 // Otherwise the flush would not be done until the track is resumed.
811 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
812 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
813 (void)mServerProxy->flushBufferIfNeeded();
814 }
815
Eric Laurentbfb1b832013-01-07 09:53:42 -0800816 if (isOffloaded()) {
817 // If offloaded we allow flush during any state except terminated
818 // and keep the track active to avoid problems if user is seeking
819 // rapidly and underlying hardware has a significant delay handling
820 // a pause
821 if (isTerminated()) {
822 return;
823 }
824
825 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800826 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800827
828 if (mState == STOPPING_1 || mState == STOPPING_2) {
829 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
830 mState = ACTIVE;
831 }
832
Haynes Mathew George7844f672014-01-15 12:32:55 -0800833 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800834 mResumeToStopping = false;
835 } else {
836 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
837 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
838 return;
839 }
840 // No point remaining in PAUSED state after a flush => go to
841 // FLUSHED state
842 mState = FLUSHED;
843 // do not reset the track if it is still in the process of being stopped or paused.
844 // this will be done by prepareTracks_l() when the track is stopped.
845 // prepareTracks_l() will see mState == FLUSHED, then
846 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800847 if (isDirect()) {
848 mFlushHwPending = true;
849 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800850 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
851 reset();
852 }
Eric Laurent81784c32012-11-19 14:55:58 -0800853 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800854 // Prevent flush being lost if the track is flushed and then resumed
855 // before mixer thread can run. This is important when offloading
856 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700857 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800858 }
859}
860
Haynes Mathew George7844f672014-01-15 12:32:55 -0800861// must be called with thread lock held
862void AudioFlinger::PlaybackThread::Track::flushAck()
863{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800864 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800865 return;
866
Phil Burk4bb650b2016-09-09 12:11:17 -0700867 // Clear the client ring buffer so that the app can prime the buffer while paused.
868 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
869 mServerProxy->flushBufferIfNeeded();
870
Haynes Mathew George7844f672014-01-15 12:32:55 -0800871 mFlushHwPending = false;
872}
873
Eric Laurent81784c32012-11-19 14:55:58 -0800874void AudioFlinger::PlaybackThread::Track::reset()
875{
876 // Do not reset twice to avoid discarding data written just after a flush and before
877 // the audioflinger thread detects the track is stopped.
878 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800879 // Force underrun condition to avoid false underrun callback until first data is
880 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700881 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800882 mFillingUpStatus = FS_FILLING;
883 mResetDone = true;
884 if (mState == FLUSHED) {
885 mState = IDLE;
886 }
887 }
888}
889
Eric Laurentbfb1b832013-01-07 09:53:42 -0800890status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
891{
892 sp<ThreadBase> thread = mThread.promote();
893 if (thread == 0) {
894 ALOGE("thread is dead");
895 return FAILED_TRANSACTION;
896 } else if ((thread->type() == ThreadBase::DIRECT) ||
897 (thread->type() == ThreadBase::OFFLOAD)) {
898 return thread->setParameters(keyValuePairs);
899 } else {
900 return PERMISSION_DENIED;
901 }
902}
903
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800904VolumeShaper::Status AudioFlinger::PlaybackThread::Track::applyVolumeShaper(
905 const sp<VolumeShaper::Configuration>& configuration,
906 const sp<VolumeShaper::Operation>& operation)
907{
908 // Note: We don't check if Thread exists.
909
910 // mVolumeHandler is thread-safe.
911 return mVolumeHandler->applyVolumeShaper(configuration, operation);
912}
913
914sp<VolumeShaper::State> AudioFlinger::PlaybackThread::Track::getVolumeShaperState(int id)
915{
916 // Note: We don't check if Thread exists.
917
918 // mVolumeHandler is thread safe.
919 return mVolumeHandler->getVolumeShaperState(id);
920}
921
Glenn Kasten573d80a2013-08-26 09:36:23 -0700922status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
923{
Andy Hung818e7a32016-02-16 18:08:07 -0800924 if (!isOffloaded() && !isDirect()) {
925 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700926 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700927 sp<ThreadBase> thread = mThread.promote();
928 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700929 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700930 }
Phil Burk6140c792015-03-19 14:30:21 -0700931
Glenn Kasten573d80a2013-08-26 09:36:23 -0700932 Mutex::Autolock _l(thread->mLock);
933 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -0800934 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700935}
936
Eric Laurent81784c32012-11-19 14:55:58 -0800937status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
938{
939 status_t status = DEAD_OBJECT;
940 sp<ThreadBase> thread = mThread.promote();
941 if (thread != 0) {
942 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
943 sp<AudioFlinger> af = mClient->audioFlinger();
944
945 Mutex::Autolock _l(af->mLock);
946
947 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
948
949 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
950 Mutex::Autolock _dl(playbackThread->mLock);
951 Mutex::Autolock _sl(srcThread->mLock);
952 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
953 if (chain == 0) {
954 return INVALID_OPERATION;
955 }
956
957 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
958 if (effect == 0) {
959 return INVALID_OPERATION;
960 }
961 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700962 status = playbackThread->addEffect_l(effect);
963 if (status != NO_ERROR) {
964 srcThread->addEffect_l(effect);
965 return INVALID_OPERATION;
966 }
Eric Laurent81784c32012-11-19 14:55:58 -0800967 // removeEffect_l() has stopped the effect if it was active so it must be restarted
968 if (effect->state() == EffectModule::ACTIVE ||
969 effect->state() == EffectModule::STOPPING) {
970 effect->start();
971 }
972
973 sp<EffectChain> dstChain = effect->chain().promote();
974 if (dstChain == 0) {
975 srcThread->addEffect_l(effect);
976 return INVALID_OPERATION;
977 }
978 AudioSystem::unregisterEffect(effect->id());
979 AudioSystem::registerEffect(&effect->desc(),
980 srcThread->id(),
981 dstChain->strategy(),
982 AUDIO_SESSION_OUTPUT_MIX,
983 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700984 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800985 }
986 status = playbackThread->attachAuxEffect(this, EffectId);
987 }
988 return status;
989}
990
991void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
992{
993 mAuxEffectId = EffectId;
994 mAuxBuffer = buffer;
995}
996
Andy Hung818e7a32016-02-16 18:08:07 -0800997bool AudioFlinger::PlaybackThread::Track::presentationComplete(
998 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -0800999{
Andy Hung818e7a32016-02-16 18:08:07 -08001000 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
1001 // This assists in proper timestamp computation as well as wakelock management.
1002
Eric Laurent81784c32012-11-19 14:55:58 -08001003 // a track is considered presented when the total number of frames written to audio HAL
1004 // corresponds to the number of frames written when presentationComplete() is called for the
1005 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001006 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1007 // to detect when all frames have been played. In this case framesWritten isn't
1008 // useful because it doesn't always reflect whether there is data in the h/w
1009 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung818e7a32016-02-16 18:08:07 -08001010 ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
1011 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001012 if (mPresentationCompleteFrames == 0) {
1013 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung818e7a32016-02-16 18:08:07 -08001014 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
1015 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08001016 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001017
Andy Hungc54b1ff2016-02-23 14:07:07 -08001018 bool complete;
1019 if (isOffloaded()) {
1020 complete = true;
1021 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001022 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -08001023 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001024 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -08001025 && mAudioTrackServerProxy->isDrained();
1026 }
1027
1028 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -08001029 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001030 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001031 return true;
1032 }
1033 return false;
1034}
1035
1036void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1037{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001038 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001039 if (mSyncEvents[i]->type() == type) {
1040 mSyncEvents[i]->trigger();
1041 mSyncEvents.removeAt(i);
1042 i--;
1043 }
1044 }
1045}
1046
1047// implement VolumeBufferProvider interface
1048
Glenn Kastenc56f3422014-03-21 17:53:17 -07001049gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001050{
1051 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1052 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001053 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1054 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1055 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001056 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001057 if (vl > GAIN_FLOAT_UNITY) {
1058 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001059 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001060 if (vr > GAIN_FLOAT_UNITY) {
1061 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001062 }
1063 // now apply the cached master volume and stream type volume;
1064 // this is trusted but lacks any synchronization or barrier so may be stale
1065 float v = mCachedVolume;
1066 vl *= v;
1067 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001068 // re-combine into packed minifloat
1069 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001070 // FIXME look at mute, pause, and stop flags
1071 return vlr;
1072}
1073
1074status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1075{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001076 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001077 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1078 (mState == STOPPED)))) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001079 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001080 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1081 event->cancel();
1082 return INVALID_OPERATION;
1083 }
1084 (void) TrackBase::setSyncEvent(event);
1085 return NO_ERROR;
1086}
1087
Glenn Kasten5736c352012-12-04 12:12:34 -08001088void AudioFlinger::PlaybackThread::Track::invalidate()
1089{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001090 TrackBase::invalidate();
Eric Laurent4d231dc2016-03-11 18:38:23 -08001091 signalClientFlag(CBLK_INVALID);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001092}
1093
1094void AudioFlinger::PlaybackThread::Track::disable()
1095{
1096 signalClientFlag(CBLK_DISABLED);
1097}
1098
1099void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1100{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001101 // FIXME should use proxy, and needs work
1102 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001103 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001104 android_atomic_release_store(0x40000000, &cblk->mFutex);
1105 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001106 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001107}
1108
Eric Laurent59fe0102013-09-27 18:48:26 -07001109void AudioFlinger::PlaybackThread::Track::signal()
1110{
1111 sp<ThreadBase> thread = mThread.promote();
1112 if (thread != 0) {
1113 PlaybackThread *t = (PlaybackThread *)thread.get();
1114 Mutex::Autolock _l(t->mLock);
1115 t->broadcast_l();
1116 }
1117}
1118
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001119//To be called with thread lock held
1120bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1121
1122 if (mState == RESUMING)
1123 return true;
1124 /* Resume is pending if track was stopping before pause was called */
1125 if (mState == STOPPING_1 &&
1126 mResumeToStopping)
1127 return true;
1128
1129 return false;
1130}
1131
1132//To be called with thread lock held
1133void AudioFlinger::PlaybackThread::Track::resumeAck() {
1134
1135
1136 if (mState == RESUMING)
1137 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001138
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001139 // Other possibility of pending resume is stopping_1 state
1140 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001141 // drain being called.
1142 if (mState == STOPPING_1) {
1143 mResumeToStopping = false;
1144 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001145}
Andy Hunge10393e2015-06-12 13:59:33 -07001146
1147//To be called with thread lock held
1148void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001149 int64_t trackFramesReleased, int64_t sinkFramesWritten,
1150 const ExtendedTimestamp &timeStamp) {
1151 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001152 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001153
1154 // adjust server times and set drained state.
1155 //
1156 // Our timestamps are only updated when the track is on the Thread active list.
1157 // We need to ensure that tracks are not removed before full drain.
1158 ExtendedTimestamp local = timeStamp;
1159 bool checked = false;
1160 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1161 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1162 // Lookup the track frame corresponding to the sink frame position.
1163 if (local.mTimeNs[i] > 0) {
1164 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1165 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001166 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hung818e7a32016-02-16 18:08:07 -08001167 mAudioTrackServerProxy->setDrained(
1168 local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1169 checked = true;
1170 }
1171 }
Andy Hunge10393e2015-06-12 13:59:33 -07001172 }
Andy Hung818e7a32016-02-16 18:08:07 -08001173 if (!checked) { // no server info, assume drained.
1174 mAudioTrackServerProxy->setDrained(true);
1175 }
Andy Hungea2b9c02016-02-12 17:06:53 -08001176 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001177 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001178 mServerProxy->setTimestamp(local);
Andy Hunge10393e2015-06-12 13:59:33 -07001179}
1180
Eric Laurent81784c32012-11-19 14:55:58 -08001181// ----------------------------------------------------------------------------
1182
Eric Laurent81784c32012-11-19 14:55:58 -08001183AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1184 PlaybackThread *playbackThread,
1185 DuplicatingThread *sourceThread,
1186 uint32_t sampleRate,
1187 audio_format_t format,
1188 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001189 size_t frameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001190 uid_t uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001191 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1192 sampleRate, format, channelMask, frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001193 NULL, 0, AUDIO_SESSION_NONE, uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001194 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07001195 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08001196{
1197
1198 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001199 mOutBuffer.frameCount = 0;
1200 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001201 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001202 "frameCount %zu, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001203 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001204 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001205 // since client and server are in the same process,
1206 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001207 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1208 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001209 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001210 mClientProxy->setSendLevel(0.0);
1211 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001212 } else {
1213 ALOGW("Error creating output track on thread %p", playbackThread);
1214 }
1215}
1216
1217AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1218{
1219 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001220 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001221}
1222
1223status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001224 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001225{
1226 status_t status = Track::start(event, triggerSession);
1227 if (status != NO_ERROR) {
1228 return status;
1229 }
1230
1231 mActive = true;
1232 mRetryCount = 127;
1233 return status;
1234}
1235
1236void AudioFlinger::PlaybackThread::OutputTrack::stop()
1237{
1238 Track::stop();
1239 clearBufferQueue();
1240 mOutBuffer.frameCount = 0;
1241 mActive = false;
1242}
1243
Andy Hungc25b84a2015-01-14 19:04:10 -08001244bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001245{
1246 Buffer *pInBuffer;
1247 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001248 bool outputBufferFull = false;
1249 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001250 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001251
1252 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1253
1254 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001255 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001256 }
1257
1258 while (waitTimeLeftMs) {
1259 // First write pending buffers, then new data
1260 if (mBufferQueue.size()) {
1261 pInBuffer = mBufferQueue.itemAt(0);
1262 } else {
1263 pInBuffer = &inBuffer;
1264 }
1265
1266 if (pInBuffer->frameCount == 0) {
1267 break;
1268 }
1269
1270 if (mOutBuffer.frameCount == 0) {
1271 mOutBuffer.frameCount = pInBuffer->frameCount;
1272 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001273 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001274 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001275 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1276 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001277 outputBufferFull = true;
1278 break;
1279 }
1280 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1281 if (waitTimeLeftMs >= waitTimeMs) {
1282 waitTimeLeftMs -= waitTimeMs;
1283 } else {
1284 waitTimeLeftMs = 0;
1285 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001286 if (status == NOT_ENOUGH_DATA) {
1287 restartIfDisabled();
1288 continue;
1289 }
Eric Laurent81784c32012-11-19 14:55:58 -08001290 }
1291
1292 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1293 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001294 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001295 Proxy::Buffer buf;
1296 buf.mFrameCount = outFrames;
1297 buf.mRaw = NULL;
1298 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001299 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001300 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001301 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001302 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001303 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001304
1305 if (pInBuffer->frameCount == 0) {
1306 if (mBufferQueue.size()) {
1307 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001308 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001309 delete pInBuffer;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001310 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001311 mThread.unsafe_get(), mBufferQueue.size());
1312 } else {
1313 break;
1314 }
1315 }
1316 }
1317
1318 // If we could not write all frames, allocate a buffer and queue it for next time.
1319 if (inBuffer.frameCount) {
1320 sp<ThreadBase> thread = mThread.promote();
1321 if (thread != 0 && !thread->standby()) {
1322 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1323 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001324 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001325 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001326 pInBuffer->raw = pInBuffer->mBuffer;
1327 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001328 mBufferQueue.add(pInBuffer);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001329 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001330 mThread.unsafe_get(), mBufferQueue.size());
1331 } else {
1332 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1333 mThread.unsafe_get(), this);
1334 }
1335 }
1336 }
1337
Andy Hungc25b84a2015-01-14 19:04:10 -08001338 // Calling write() with a 0 length buffer means that no more data will be written:
1339 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1340 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1341 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001342 }
1343
1344 return outputBufferFull;
1345}
1346
1347status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1348 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1349{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001350 ClientProxy::Buffer buf;
1351 buf.mFrameCount = buffer->frameCount;
1352 struct timespec timeout;
1353 timeout.tv_sec = waitTimeMs / 1000;
1354 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1355 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1356 buffer->frameCount = buf.mFrameCount;
1357 buffer->raw = buf.mRaw;
1358 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001359}
1360
Eric Laurent81784c32012-11-19 14:55:58 -08001361void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1362{
1363 size_t size = mBufferQueue.size();
1364
1365 for (size_t i = 0; i < size; i++) {
1366 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001367 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001368 delete pBuffer;
1369 }
1370 mBufferQueue.clear();
1371}
1372
Eric Laurent4d231dc2016-03-11 18:38:23 -08001373void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1374{
1375 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1376 if (mActive && (flags & CBLK_DISABLED)) {
1377 start();
1378 }
1379}
Eric Laurent81784c32012-11-19 14:55:58 -08001380
Eric Laurent83b88082014-06-20 18:31:16 -07001381AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001382 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001383 uint32_t sampleRate,
1384 audio_channel_mask_t channelMask,
1385 audio_format_t format,
1386 size_t frameCount,
1387 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001388 audio_output_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001389 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001390 sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001391 buffer, 0, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001392 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1393{
1394 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1395 playbackThread->sampleRate();
1396 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1397 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1398
1399 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1400 this, sampleRate,
1401 (int)mPeerTimeout.tv_sec,
1402 (int)(mPeerTimeout.tv_nsec / 1000000));
1403}
1404
1405AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1406{
1407}
1408
Eric Laurent4d231dc2016-03-11 18:38:23 -08001409status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001410 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001411{
1412 status_t status = Track::start(event, triggerSession);
1413 if (status != NO_ERROR) {
1414 return status;
1415 }
1416 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1417 return status;
1418}
1419
Eric Laurent83b88082014-06-20 18:31:16 -07001420// AudioBufferProvider interface
1421status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001422 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001423{
1424 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1425 Proxy::Buffer buf;
1426 buf.mFrameCount = buffer->frameCount;
1427 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1428 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001429 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001430 if (buf.mFrameCount == 0) {
1431 return WOULD_BLOCK;
1432 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001433 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001434 return status;
1435}
1436
1437void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1438{
1439 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1440 Proxy::Buffer buf;
1441 buf.mFrameCount = buffer->frameCount;
1442 buf.mRaw = buffer->raw;
1443 mPeerProxy->releaseBuffer(&buf);
1444 TrackBase::releaseBuffer(buffer);
1445}
1446
1447status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1448 const struct timespec *timeOut)
1449{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001450 status_t status = NO_ERROR;
1451 static const int32_t kMaxTries = 5;
1452 int32_t tryCounter = kMaxTries;
1453 do {
1454 if (status == NOT_ENOUGH_DATA) {
1455 restartIfDisabled();
1456 }
1457 status = mProxy->obtainBuffer(buffer, timeOut);
1458 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1459 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001460}
1461
1462void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1463{
1464 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001465 restartIfDisabled();
1466 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1467}
1468
1469void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1470{
Eric Laurent83b88082014-06-20 18:31:16 -07001471 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1472 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1473 start();
1474 }
Eric Laurent83b88082014-06-20 18:31:16 -07001475}
1476
Eric Laurent81784c32012-11-19 14:55:58 -08001477// ----------------------------------------------------------------------------
1478// Record
1479// ----------------------------------------------------------------------------
1480
1481AudioFlinger::RecordHandle::RecordHandle(
1482 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1483 : BnAudioRecord(),
1484 mRecordTrack(recordTrack)
1485{
1486}
1487
1488AudioFlinger::RecordHandle::~RecordHandle() {
1489 stop_nonvirtual();
1490 mRecordTrack->destroy();
1491}
1492
Eric Laurent81784c32012-11-19 14:55:58 -08001493status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001494 audio_session_t triggerSession) {
Eric Laurent81784c32012-11-19 14:55:58 -08001495 ALOGV("RecordHandle::start()");
1496 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1497}
1498
1499void AudioFlinger::RecordHandle::stop() {
1500 stop_nonvirtual();
1501}
1502
1503void AudioFlinger::RecordHandle::stop_nonvirtual() {
1504 ALOGV("RecordHandle::stop()");
1505 mRecordTrack->stop();
1506}
1507
1508status_t AudioFlinger::RecordHandle::onTransact(
1509 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1510{
1511 return BnAudioRecord::onTransact(code, data, reply, flags);
1512}
1513
1514// ----------------------------------------------------------------------------
1515
Glenn Kasten05997e22014-03-13 15:08:33 -07001516// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001517AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1518 RecordThread *thread,
1519 const sp<Client>& client,
1520 uint32_t sampleRate,
1521 audio_format_t format,
1522 audio_channel_mask_t channelMask,
1523 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001524 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001525 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001526 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001527 audio_input_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001528 track_type type,
1529 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001530 : TrackBase(thread, client, sampleRate, format,
Eric Laurent05067782016-06-01 18:27:28 -07001531 channelMask, frameCount, buffer, sessionId, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001532 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001533 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001534 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
Eric Laurent20b9ef02016-12-05 11:03:16 -08001535 type, portId),
Andy Hung97a893e2015-03-29 01:03:07 -07001536 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001537 mFramesToDrop(0),
1538 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001539 mRecordBufferConverter(NULL),
1540 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001541{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001542 if (mCblk == NULL) {
1543 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001544 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001545
Andy Hung97a893e2015-03-29 01:03:07 -07001546 mRecordBufferConverter = new RecordBufferConverter(
1547 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1548 channelMask, format, sampleRate);
1549 // Check if the RecordBufferConverter construction was successful.
1550 // If not, don't continue with construction.
1551 //
1552 // NOTE: It would be extremely rare that the record track cannot be created
1553 // for the current device, but a pending or future device change would make
1554 // the record track configuration valid.
1555 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1556 ALOGE("RecordTrack unable to create record buffer converter");
1557 return;
1558 }
1559
Andy Hung6ae58432016-02-16 18:32:24 -08001560 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001561 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001562
Andy Hung97a893e2015-03-29 01:03:07 -07001563 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001564
Eric Laurent05067782016-06-01 18:27:28 -07001565 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001566 ALOG_ASSERT(thread->mFastTrackAvail);
1567 thread->mFastTrackAvail = false;
1568 }
Eric Laurent81784c32012-11-19 14:55:58 -08001569}
1570
1571AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1572{
1573 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001574 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001575 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001576}
1577
Andy Hung97a893e2015-03-29 01:03:07 -07001578status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1579{
1580 status_t status = TrackBase::initCheck();
1581 if (status == NO_ERROR && mServerProxy == 0) {
1582 status = BAD_VALUE;
1583 }
1584 return status;
1585}
1586
Eric Laurent81784c32012-11-19 14:55:58 -08001587// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001588status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001589{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001590 ServerProxy::Buffer buf;
1591 buf.mFrameCount = buffer->frameCount;
1592 status_t status = mServerProxy->obtainBuffer(&buf);
1593 buffer->frameCount = buf.mFrameCount;
1594 buffer->raw = buf.mRaw;
1595 if (buf.mFrameCount == 0) {
1596 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001597 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001598 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001599 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001600}
1601
1602status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001603 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001604{
1605 sp<ThreadBase> thread = mThread.promote();
1606 if (thread != 0) {
1607 RecordThread *recordThread = (RecordThread *)thread.get();
1608 return recordThread->start(this, event, triggerSession);
1609 } else {
1610 return BAD_VALUE;
1611 }
1612}
1613
1614void AudioFlinger::RecordThread::RecordTrack::stop()
1615{
1616 sp<ThreadBase> thread = mThread.promote();
1617 if (thread != 0) {
1618 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001619 if (recordThread->stop(this) && isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001620 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001621 }
1622 }
1623}
1624
1625void AudioFlinger::RecordThread::RecordTrack::destroy()
1626{
1627 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1628 sp<RecordTrack> keep(this);
1629 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001630 if (isExternalTrack()) {
1631 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001632 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001633 }
Glenn Kastend848eb42016-03-08 13:42:11 -08001634 AudioSystem::releaseInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001635 }
Eric Laurent81784c32012-11-19 14:55:58 -08001636 sp<ThreadBase> thread = mThread.promote();
1637 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001638 Mutex::Autolock _l(thread->mLock);
1639 RecordThread *recordThread = (RecordThread *) thread.get();
1640 recordThread->destroyTrack_l(this);
1641 }
1642 }
1643}
1644
Eric Laurent9a54bc22013-09-09 09:08:44 -07001645void AudioFlinger::RecordThread::RecordTrack::invalidate()
1646{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001647 TrackBase::invalidate();
Eric Laurent9a54bc22013-09-09 09:08:44 -07001648 // FIXME should use proxy, and needs work
1649 audio_track_cblk_t* cblk = mCblk;
1650 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1651 android_atomic_release_store(0x40000000, &cblk->mFutex);
1652 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001653 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001654}
1655
Eric Laurent81784c32012-11-19 14:55:58 -08001656
1657/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1658{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001659 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001660}
1661
Marco Nelissenb2208842014-02-07 14:00:50 -08001662void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001663{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001664 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001665 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001666 (mClient == 0) ? getpid_cached : mClient->pid(),
1667 mFormat,
1668 mChannelMask,
1669 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001670 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001671 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001672 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001673 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001674
Eric Laurent81784c32012-11-19 14:55:58 -08001675}
1676
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001677void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1678{
1679 if (event == mSyncStartEvent) {
1680 ssize_t framesToDrop = 0;
1681 sp<ThreadBase> threadBase = mThread.promote();
1682 if (threadBase != 0) {
1683 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1684 // from audio HAL
1685 framesToDrop = threadBase->mFrameCount * 2;
1686 }
1687 mFramesToDrop = framesToDrop;
1688 }
1689}
1690
1691void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1692{
1693 if (mSyncStartEvent != 0) {
1694 mSyncStartEvent->cancel();
1695 mSyncStartEvent.clear();
1696 }
1697 mFramesToDrop = 0;
1698}
1699
Andy Hung3f0c9022016-01-15 17:49:46 -08001700void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1701 int64_t trackFramesReleased, int64_t sourceFramesRead,
1702 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1703{
1704 ExtendedTimestamp local = timestamp;
1705
1706 // Convert HAL frames to server-side track frames at track sample rate.
1707 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1708 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1709 if (local.mTimeNs[i] != 0) {
1710 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1711 const int64_t relativeTrackFrames = relativeServerFrames
1712 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1713 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1714 }
1715 }
Andy Hung6ae58432016-02-16 18:32:24 -08001716 mServerProxy->setTimestamp(local);
Andy Hung3f0c9022016-01-15 17:49:46 -08001717}
Eric Laurent83b88082014-06-20 18:31:16 -07001718
1719AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1720 uint32_t sampleRate,
1721 audio_channel_mask_t channelMask,
1722 audio_format_t format,
1723 size_t frameCount,
1724 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001725 audio_input_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07001726 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001727 buffer, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001728 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1729{
1730 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1731 recordThread->sampleRate();
1732 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1733 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1734
1735 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1736 this, sampleRate,
1737 (int)mPeerTimeout.tv_sec,
1738 (int)(mPeerTimeout.tv_nsec / 1000000));
1739}
1740
1741AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1742{
1743}
1744
1745// AudioBufferProvider interface
1746status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001747 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001748{
1749 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1750 Proxy::Buffer buf;
1751 buf.mFrameCount = buffer->frameCount;
1752 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1753 ALOGV_IF(status != NO_ERROR,
1754 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001755 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001756 if (buf.mFrameCount == 0) {
1757 return WOULD_BLOCK;
1758 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001759 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001760 return status;
1761}
1762
1763void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1764{
1765 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1766 Proxy::Buffer buf;
1767 buf.mFrameCount = buffer->frameCount;
1768 buf.mRaw = buffer->raw;
1769 mPeerProxy->releaseBuffer(&buf);
1770 TrackBase::releaseBuffer(buffer);
1771}
1772
1773status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1774 const struct timespec *timeOut)
1775{
1776 return mProxy->obtainBuffer(buffer, timeOut);
1777}
1778
1779void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1780{
1781 mProxy->releaseBuffer(buffer);
1782}
1783
Eric Laurent6acd1d42017-01-04 14:23:29 -08001784
1785
1786AudioFlinger::MmapThread::MmapTrack::MmapTrack(ThreadBase *thread,
1787 uint32_t sampleRate,
1788 audio_format_t format,
1789 audio_channel_mask_t channelMask,
1790 audio_session_t sessionId,
1791 uid_t uid,
1792 audio_port_handle_t portId)
1793 : TrackBase(thread, NULL, sampleRate, format,
1794 channelMask, 0, NULL, sessionId, uid, false,
1795 ALLOC_NONE,
1796 TYPE_DEFAULT, portId)
1797{
1798}
1799
1800AudioFlinger::MmapThread::MmapTrack::~MmapTrack()
1801{
1802}
1803
1804status_t AudioFlinger::MmapThread::MmapTrack::initCheck() const
1805{
1806 return NO_ERROR;
1807}
1808
1809status_t AudioFlinger::MmapThread::MmapTrack::start(AudioSystem::sync_event_t event __unused,
1810 audio_session_t triggerSession __unused)
1811{
1812 return NO_ERROR;
1813}
1814
1815void AudioFlinger::MmapThread::MmapTrack::stop()
1816{
1817}
1818
1819// AudioBufferProvider interface
1820status_t AudioFlinger::MmapThread::MmapTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
1821{
1822 buffer->frameCount = 0;
1823 buffer->raw = nullptr;
1824 return INVALID_OPERATION;
1825}
1826
1827// ExtendedAudioBufferProvider interface
1828size_t AudioFlinger::MmapThread::MmapTrack::framesReady() const {
1829 return 0;
1830}
1831
1832int64_t AudioFlinger::MmapThread::MmapTrack::framesReleased() const
1833{
1834 return 0;
1835}
1836
1837void AudioFlinger::MmapThread::MmapTrack::onTimestamp(const ExtendedTimestamp &timestamp __unused)
1838{
1839}
1840
1841/*static*/ void AudioFlinger::MmapThread::MmapTrack::appendDumpHeader(String8& result)
1842{
1843 result.append(" Client Fmt Chn mask SRate\n");
1844}
1845
1846void AudioFlinger::MmapThread::MmapTrack::dump(char* buffer, size_t size)
1847{
1848 snprintf(buffer, size, " %6u %3u %08X %5u\n",
1849 mUid,
1850 mFormat,
1851 mChannelMask,
1852 mSampleRate);
1853
1854}
1855
Glenn Kasten63238ef2015-03-02 15:50:29 -08001856} // namespace android