blob: f18b88d7247abc5f16339b8c3e7fdb1c6733f205 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenad8510a2015-02-17 16:24:07 -080023#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070025#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080026#include <utils/Log.h>
27
28#include <private/media/AudioTrackShared.h>
29
Eric Laurent81784c32012-11-19 14:55:58 -080030#include "AudioMixer.h"
31#include "AudioFlinger.h"
32#include "ServiceUtilities.h"
33
Glenn Kastenda6ef132013-01-10 12:31:01 -080034#include <media/nbaio/Pipe.h>
35#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070036#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080037
Eric Laurent81784c32012-11-19 14:55:58 -080038// ----------------------------------------------------------------------------
39
40// Note: the following macro is used for extremely verbose logging message. In
41// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
42// 0; but one side effect of this is to turn all LOGV's as well. Some messages
43// are so verbose that we want to suppress them even when we have ALOG_ASSERT
44// turned on. Do not uncomment the #def below unless you really know what you
45// are doing and want to see all of the extremely verbose messages.
46//#define VERY_VERY_VERBOSE_LOGGING
47#ifdef VERY_VERY_VERBOSE_LOGGING
48#define ALOGVV ALOGV
49#else
50#define ALOGVV(a...) do { } while(0)
51#endif
52
Andy Hunge10393e2015-06-12 13:59:33 -070053// TODO move to a common header (Also shared with AudioTrack.cpp)
54#define NANOS_PER_SECOND 1000000000
55#define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * NANOS_PER_SECOND + time.tv_nsec)
56
Eric Laurent81784c32012-11-19 14:55:58 -080057namespace android {
58
59// ----------------------------------------------------------------------------
60// TrackBase
61// ----------------------------------------------------------------------------
62
Glenn Kastenda6ef132013-01-10 12:31:01 -080063static volatile int32_t nextTrackId = 55;
64
Eric Laurent81784c32012-11-19 14:55:58 -080065// TrackBase constructor must be called with AudioFlinger::mLock held
66AudioFlinger::ThreadBase::TrackBase::TrackBase(
67 ThreadBase *thread,
68 const sp<Client>& client,
69 uint32_t sampleRate,
70 audio_format_t format,
71 audio_channel_mask_t channelMask,
72 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070073 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -080074 audio_session_t sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080075 int clientUid,
Glenn Kastend776ac62014-05-07 09:16:09 -070076 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070077 alloc_type alloc,
78 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080079 : RefBase(),
80 mThread(thread),
81 mClient(client),
82 mCblk(NULL),
83 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080084 mState(IDLE),
85 mSampleRate(sampleRate),
86 mFormat(format),
87 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070088 mChannelCount(isOut ?
89 audio_channel_count_from_out_mask(channelMask) :
90 audio_channel_count_from_in_mask(channelMask)),
Phil Burkfdb3c072016-02-09 10:47:02 -080091 mFrameSize(audio_has_proportional_frames(format) ?
Eric Laurent81784c32012-11-19 14:55:58 -080092 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
93 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080094 mSessionId(sessionId),
95 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080096 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080097 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070098 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -070099 mType(type),
100 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800101{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700102 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
103 if (!isTrustedCallingUid(callingUid) || clientUid == -1) {
104 ALOGW_IF(clientUid != -1 && clientUid != (int)callingUid,
105 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
106 clientUid = (int)callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800107 }
108 // clientUid contains the uid of the app that is responsible for this track, so we can blame
109 // battery usage on it.
110 mUid = clientUid;
111
Eric Laurent81784c32012-11-19 14:55:58 -0800112 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hungeaa39692017-02-13 18:48:39 -0800113
114 size_t bufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
115 // check overflow when computing bufferSize due to multiplication by mFrameSize.
116 if (bufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
117 || mFrameSize == 0 // format needs to be correct
118 || bufferSize > SIZE_MAX / mFrameSize) {
119 android_errorWriteLog(0x534e4554, "34749571");
120 return;
121 }
122 bufferSize *= mFrameSize;
123
Eric Laurent81784c32012-11-19 14:55:58 -0800124 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700125 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hungeaa39692017-02-13 18:48:39 -0800126 // check overflow when computing allocation size for streaming tracks.
127 if (size > SIZE_MAX - bufferSize) {
128 android_errorWriteLog(0x534e4554, "34749571");
129 return;
130 }
Eric Laurent81784c32012-11-19 14:55:58 -0800131 size += bufferSize;
132 }
133
134 if (client != 0) {
135 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700136 if (mCblkMemory == 0 ||
137 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700138 ALOGE("not enough memory for AudioTrack size=%zu", size);
Eric Laurent81784c32012-11-19 14:55:58 -0800139 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700140 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800141 return;
142 }
143 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800144 // this syntax avoids calling the audio_track_cblk_t constructor twice
145 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800146 // assume mCblk != NULL
147 }
148
149 // construct the shared structure in-place.
150 if (mCblk != NULL) {
151 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700152 switch (alloc) {
153 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700154 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
155 if (roHeap == 0 ||
156 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
157 (mBuffer = mBufferMemory->pointer()) == NULL) {
158 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
159 if (roHeap != 0) {
160 roHeap->dump("buffer");
161 }
162 mCblkMemory.clear();
163 mBufferMemory.clear();
164 return;
165 }
Eric Laurent81784c32012-11-19 14:55:58 -0800166 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700167 } break;
168 case ALLOC_PIPE:
169 mBufferMemory = thread->pipeMemory();
170 // mBuffer is the virtual address as seen from current process (mediaserver),
171 // and should normally be coming from mBufferMemory->pointer().
172 // However in this case the TrackBase does not reference the buffer directly.
173 // It should references the buffer via the pipe.
174 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
175 mBuffer = NULL;
176 break;
177 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700178 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700179 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700180 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
181 memset(mBuffer, 0, bufferSize);
182 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700183 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800184#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700185 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800186#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700187 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700188 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700189 case ALLOC_LOCAL:
190 mBuffer = calloc(1, bufferSize);
191 break;
192 case ALLOC_NONE:
193 mBuffer = buffer;
194 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800195 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800196
Glenn Kasten46909e72013-02-26 09:20:22 -0800197#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800198 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700199 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800200 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800201 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
202 size_t numCounterOffers = 0;
203 const NBAIO_Format offers[1] = {pipeFormat};
204 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
205 ALOG_ASSERT(index == 0);
206 PipeReader *pipeReader = new PipeReader(*pipe);
207 numCounterOffers = 0;
208 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
209 ALOG_ASSERT(index == 0);
210 mTeeSink = pipe;
211 mTeeSource = pipeReader;
212 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800213 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800214#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800215
Eric Laurent81784c32012-11-19 14:55:58 -0800216 }
217}
218
Eric Laurent83b88082014-06-20 18:31:16 -0700219status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
220{
221 status_t status;
222 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
223 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
224 } else {
225 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
226 }
227 return status;
228}
229
Eric Laurent81784c32012-11-19 14:55:58 -0800230AudioFlinger::ThreadBase::TrackBase::~TrackBase()
231{
Glenn Kasten46909e72013-02-26 09:20:22 -0800232#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800233 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800234#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800235 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
236 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800237 if (mCblk != NULL) {
238 if (mClient == 0) {
239 delete mCblk;
240 } else {
241 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
242 }
243 }
244 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
245 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700246 // Client destructor must run with AudioFlinger client mutex locked
247 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800248 // If the client's reference count drops to zero, the associated destructor
249 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
250 // relying on the automatic clear() at end of scope.
251 mClient.clear();
252 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700253 // flush the binder command buffer
254 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800255}
256
257// AudioBufferProvider interface
258// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800259// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800260void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
261{
Glenn Kasten46909e72013-02-26 09:20:22 -0800262#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800263 if (mTeeSink != 0) {
264 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
265 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800266#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800267
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800268 ServerProxy::Buffer buf;
269 buf.mFrameCount = buffer->frameCount;
270 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800271 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800272 buffer->raw = NULL;
273 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800274}
275
Eric Laurent81784c32012-11-19 14:55:58 -0800276status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
277{
278 mSyncEvents.add(event);
279 return NO_ERROR;
280}
281
282// ----------------------------------------------------------------------------
283// Playback
284// ----------------------------------------------------------------------------
285
286AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
287 : BnAudioTrack(),
288 mTrack(track)
289{
290}
291
292AudioFlinger::TrackHandle::~TrackHandle() {
293 // just stop the track on deletion, associated resources
294 // will be freed from the main thread once all pending buffers have
295 // been played. Unless it's not in the active track list, in which
296 // case we free everything now...
297 mTrack->destroy();
298}
299
300sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
301 return mTrack->getCblk();
302}
303
304status_t AudioFlinger::TrackHandle::start() {
305 return mTrack->start();
306}
307
308void AudioFlinger::TrackHandle::stop() {
309 mTrack->stop();
310}
311
312void AudioFlinger::TrackHandle::flush() {
313 mTrack->flush();
314}
315
Eric Laurent81784c32012-11-19 14:55:58 -0800316void AudioFlinger::TrackHandle::pause() {
317 mTrack->pause();
318}
319
320status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
321{
322 return mTrack->attachAuxEffect(EffectId);
323}
324
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700325status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
326 return mTrack->setParameters(keyValuePairs);
327}
328
Glenn Kasten53cec222013-08-29 09:01:02 -0700329status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
330{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700331 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700332}
333
Eric Laurent59fe0102013-09-27 18:48:26 -0700334
335void AudioFlinger::TrackHandle::signal()
336{
337 return mTrack->signal();
338}
339
Eric Laurent81784c32012-11-19 14:55:58 -0800340status_t AudioFlinger::TrackHandle::onTransact(
341 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
342{
343 return BnAudioTrack::onTransact(code, data, reply, flags);
344}
345
346// ----------------------------------------------------------------------------
347
348// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
349AudioFlinger::PlaybackThread::Track::Track(
350 PlaybackThread *thread,
351 const sp<Client>& client,
352 audio_stream_type_t streamType,
353 uint32_t sampleRate,
354 audio_format_t format,
355 audio_channel_mask_t channelMask,
356 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700357 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800358 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800359 audio_session_t sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800360 int uid,
Eric Laurent05067782016-06-01 18:27:28 -0700361 audio_output_flags_t flags,
Eric Laurent83b88082014-06-20 18:31:16 -0700362 track_type type)
363 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
364 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
Eric Laurent05067782016-06-01 18:27:28 -0700365 sessionId, uid, true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700366 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
367 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800368 mFillingUpStatus(FS_INVALID),
369 // mRetryCount initialized later when needed
370 mSharedBuffer(sharedBuffer),
371 mStreamType(streamType),
372 mName(-1), // see note below
373 mMainBuffer(thread->mixBuffer()),
374 mAuxBuffer(NULL),
375 mAuxEffectId(0), mHasVolumeController(false),
376 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700377 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Andy Hunge10393e2015-06-12 13:59:33 -0700378 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800379 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800380 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800381 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800382 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800383 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700384 mFlushHwPending(false),
385 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -0800386{
Eric Laurent83b88082014-06-20 18:31:16 -0700387 // client == 0 implies sharedBuffer == 0
388 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
389
Eric Laurente93cc032016-05-05 10:15:10 -0700390 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Eric Laurent83b88082014-06-20 18:31:16 -0700391 sharedBuffer->size());
392
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700393 if (mCblk == NULL) {
394 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800395 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700396
397 if (sharedBuffer == 0) {
398 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700399 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700400 } else {
401 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
402 mFrameSize);
403 }
404 mServerProxy = mAudioTrackServerProxy;
405
Eric Laurentad7dd962016-09-22 12:38:37 -0700406 mName = thread->getTrackName_l(channelMask, format, sessionId, uid);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700407 if (mName < 0) {
408 ALOGE("no more track names available");
409 return;
410 }
411 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700412 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700413 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
414 // race with setSyncEvent(). However, if we call it, we cannot properly start
415 // static fast tracks (SoundPool) immediately after stopping.
416 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700417 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
418 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700419 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700420 // FIXME This is too eager. We allocate a fast track index before the
421 // fast track becomes active. Since fast tracks are a scarce resource,
422 // this means we are potentially denying other more important fast tracks from
423 // being created. It would be better to allocate the index dynamically.
424 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700425 thread->mFastTrackAvailMask &= ~(1 << i);
426 }
Eric Laurent81784c32012-11-19 14:55:58 -0800427}
428
429AudioFlinger::PlaybackThread::Track::~Track()
430{
431 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700432
433 // The destructor would clear mSharedBuffer,
434 // but it will not push the decremented reference count,
435 // leaving the client's IMemory dangling indefinitely.
436 // This prevents that leak.
437 if (mSharedBuffer != 0) {
438 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700439 }
Eric Laurent81784c32012-11-19 14:55:58 -0800440}
441
Glenn Kasten03003332013-08-06 15:40:54 -0700442status_t AudioFlinger::PlaybackThread::Track::initCheck() const
443{
444 status_t status = TrackBase::initCheck();
445 if (status == NO_ERROR && mName < 0) {
446 status = NO_MEMORY;
447 }
448 return status;
449}
450
Eric Laurent81784c32012-11-19 14:55:58 -0800451void AudioFlinger::PlaybackThread::Track::destroy()
452{
453 // NOTE: destroyTrack_l() can remove a strong reference to this Track
454 // by removing it from mTracks vector, so there is a risk that this Tracks's
455 // destructor is called. As the destructor needs to lock mLock,
456 // we must acquire a strong reference on this Track before locking mLock
457 // here so that the destructor is called only when exiting this function.
458 // On the other hand, as long as Track::destroy() is only called by
459 // TrackHandle destructor, the TrackHandle still holds a strong ref on
460 // this Track with its member mTrack.
461 sp<Track> keep(this);
462 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700463 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800464 sp<ThreadBase> thread = mThread.promote();
465 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800466 Mutex::Autolock _l(thread->mLock);
467 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700468 wasActive = playbackThread->destroyTrack_l(this);
469 }
470 if (isExternalTrack() && !wasActive) {
Glenn Kastend848eb42016-03-08 13:42:11 -0800471 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800472 }
473 }
474}
475
476/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
477{
Marco Nelissenb2208842014-02-07 14:00:50 -0800478 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700479 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800480}
481
Marco Nelissenb2208842014-02-07 14:00:50 -0800482void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800483{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700484 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800485 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800486 sprintf(buffer, " F %2d", mFastIndex);
487 } else if (mName >= AudioMixer::TRACK0) {
488 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800489 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800490 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800491 }
492 track_state state = mState;
493 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800494 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800495 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800496 } else {
497 switch (state) {
498 case IDLE:
499 stateChar = 'I';
500 break;
501 case STOPPING_1:
502 stateChar = 's';
503 break;
504 case STOPPING_2:
505 stateChar = '5';
506 break;
507 case STOPPED:
508 stateChar = 'S';
509 break;
510 case RESUMING:
511 stateChar = 'R';
512 break;
513 case ACTIVE:
514 stateChar = 'A';
515 break;
516 case PAUSING:
517 stateChar = 'p';
518 break;
519 case PAUSED:
520 stateChar = 'P';
521 break;
522 case FLUSHED:
523 stateChar = 'F';
524 break;
525 default:
526 stateChar = '?';
527 break;
528 }
Eric Laurent81784c32012-11-19 14:55:58 -0800529 }
530 char nowInUnderrun;
531 switch (mObservedUnderruns.mBitFields.mMostRecent) {
532 case UNDERRUN_FULL:
533 nowInUnderrun = ' ';
534 break;
535 case UNDERRUN_PARTIAL:
536 nowInUnderrun = '<';
537 break;
538 case UNDERRUN_EMPTY:
539 nowInUnderrun = '*';
540 break;
541 default:
542 nowInUnderrun = '?';
543 break;
544 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000545 snprintf(&buffer[8], size-8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u %5.2g %5.2g "
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000546 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800547 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800548 (mClient == 0) ? getpid_cached : mClient->pid(),
549 mStreamType,
550 mFormat,
551 mChannelMask,
552 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800553 mFrameCount,
554 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800555 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800556 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700557 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
558 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700559 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000560 mMainBuffer,
561 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700562 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700563 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800564 nowInUnderrun);
565}
566
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
568 return mAudioTrackServerProxy->getSampleRate();
569}
570
Eric Laurent81784c32012-11-19 14:55:58 -0800571// AudioBufferProvider interface
572status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800573 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800574{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800575 ServerProxy::Buffer buf;
576 size_t desiredFrames = buffer->frameCount;
577 buf.mFrameCount = desiredFrames;
578 status_t status = mServerProxy->obtainBuffer(&buf);
579 buffer->frameCount = buf.mFrameCount;
580 buffer->raw = buf.mRaw;
581 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700582 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800583 } else {
584 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800585 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800586
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800587 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800588}
589
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700590// releaseBuffer() is not overridden
591
592// ExtendedAudioBufferProvider interface
593
Andy Hung27876c02014-09-09 18:07:55 -0700594// framesReady() may return an approximation of the number of frames if called
595// from a different thread than the one calling Proxy->obtainBuffer() and
596// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
597// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800598size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700599 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
600 // Static tracks return zero frames immediately upon stopping (for FastTracks).
601 // The remainder of the buffer is not drained.
602 return 0;
603 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800605}
606
Andy Hung818e7a32016-02-16 18:08:07 -0800607int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700608{
609 return mAudioTrackServerProxy->framesReleased();
610}
611
Andy Hung818e7a32016-02-16 18:08:07 -0800612void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800613{
614 // This call comes from a FastTrack and should be kept lockless.
615 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800616 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800617
Andy Hung818e7a32016-02-16 18:08:07 -0800618 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hung6ae58432016-02-16 18:32:24 -0800619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// Don't call for fast tracks; the framesReady() could result in priority inversion
622bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800623 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
624 return true;
625 }
626
Eric Laurent16498512014-03-17 17:22:08 -0700627 if (isStopping()) {
628 if (framesReady() > 0) {
629 mFillingUpStatus = FS_FILLED;
630 }
Eric Laurent81784c32012-11-19 14:55:58 -0800631 return true;
632 }
633
Phil Burke8972b02016-03-04 11:29:57 -0800634 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700635 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800636 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700637 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800638 return true;
639 }
640 return false;
641}
642
Glenn Kasten0f11b512014-01-31 16:18:54 -0800643status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800644 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
646 status_t status = NO_ERROR;
647 ALOGV("start(%d), calling pid %d session %d",
648 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
649
650 sp<ThreadBase> thread = mThread.promote();
651 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700652 if (isOffloaded()) {
653 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
654 Mutex::Autolock _lth(thread->mLock);
655 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700656 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
657 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700658 invalidate();
659 return PERMISSION_DENIED;
660 }
661 }
662 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800663 track_state state = mState;
664 // here the track could be either new, or restarted
665 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800666
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800667 // initial state-stopping. next state-pausing.
668 // What if resume is called ?
669
670 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800671 if (mResumeToStopping) {
672 // happened we need to resume to STOPPING_1
673 mState = TrackBase::STOPPING_1;
674 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
675 } else {
676 mState = TrackBase::RESUMING;
677 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
678 }
Eric Laurent81784c32012-11-19 14:55:58 -0800679 } else {
680 mState = TrackBase::ACTIVE;
681 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
682 }
683
Andy Hunge10393e2015-06-12 13:59:33 -0700684 // states to reset position info for non-offloaded/direct tracks
685 if (!isOffloaded() && !isDirect()
686 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
687 mFrameMap.reset();
688 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800689 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700690 if (isFastTrack()) {
691 // refresh fast track underruns on start because that field is never cleared
692 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
693 // after stop.
694 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
695 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800696 status = playbackThread->addTrack_l(this);
697 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800698 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800699 // restore previous state if start was rejected by policy manager
700 if (status == PERMISSION_DENIED) {
701 mState = state;
702 }
703 }
704 // track was already in the active list, not a problem
705 if (status == ALREADY_EXISTS) {
706 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700707 } else {
708 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
709 // It is usually unsafe to access the server proxy from a binder thread.
710 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
711 // isn't looking at this track yet: we still hold the normal mixer thread lock,
712 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700713 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700714 ServerProxy::Buffer buffer;
715 buffer.mFrameCount = 1;
716 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800717 }
718 } else {
719 status = BAD_VALUE;
720 }
721 return status;
722}
723
724void AudioFlinger::PlaybackThread::Track::stop()
725{
726 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
727 sp<ThreadBase> thread = mThread.promote();
728 if (thread != 0) {
729 Mutex::Autolock _l(thread->mLock);
730 track_state state = mState;
731 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
732 // If the track is not active (PAUSED and buffers full), flush buffers
733 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
734 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
735 reset();
736 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700737 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800738 mState = STOPPED;
739 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800740 // For fast tracks prepareTracks_l() will set state to STOPPING_2
741 // presentation is complete
742 // For an offloaded track this starts a drain and state will
743 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800744 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -0700745 if (isOffloaded()) {
746 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
747 }
Eric Laurent81784c32012-11-19 14:55:58 -0800748 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700749 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800750 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
751 playbackThread);
752 }
Eric Laurent81784c32012-11-19 14:55:58 -0800753 }
754}
755
756void AudioFlinger::PlaybackThread::Track::pause()
757{
758 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
759 sp<ThreadBase> thread = mThread.promote();
760 if (thread != 0) {
761 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800762 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
763 switch (mState) {
764 case STOPPING_1:
765 case STOPPING_2:
766 if (!isOffloaded()) {
767 /* nothing to do if track is not offloaded */
768 break;
769 }
770
771 // Offloaded track was draining, we need to carry on draining when resumed
772 mResumeToStopping = true;
773 // fall through...
774 case ACTIVE:
775 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800776 mState = PAUSING;
777 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700778 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800779 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800780
Eric Laurentbfb1b832013-01-07 09:53:42 -0800781 default:
782 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800783 }
784 }
785}
786
787void AudioFlinger::PlaybackThread::Track::flush()
788{
789 ALOGV("flush(%d)", mName);
790 sp<ThreadBase> thread = mThread.promote();
791 if (thread != 0) {
792 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800793 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800794
Phil Burk4bb650b2016-09-09 12:11:17 -0700795 // Flush the ring buffer now if the track is not active in the PlaybackThread.
796 // Otherwise the flush would not be done until the track is resumed.
797 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
798 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
799 (void)mServerProxy->flushBufferIfNeeded();
800 }
801
Eric Laurentbfb1b832013-01-07 09:53:42 -0800802 if (isOffloaded()) {
803 // If offloaded we allow flush during any state except terminated
804 // and keep the track active to avoid problems if user is seeking
805 // rapidly and underlying hardware has a significant delay handling
806 // a pause
807 if (isTerminated()) {
808 return;
809 }
810
811 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800812 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800813
814 if (mState == STOPPING_1 || mState == STOPPING_2) {
815 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
816 mState = ACTIVE;
817 }
818
Haynes Mathew George7844f672014-01-15 12:32:55 -0800819 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800820 mResumeToStopping = false;
821 } else {
822 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
823 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
824 return;
825 }
826 // No point remaining in PAUSED state after a flush => go to
827 // FLUSHED state
828 mState = FLUSHED;
829 // do not reset the track if it is still in the process of being stopped or paused.
830 // this will be done by prepareTracks_l() when the track is stopped.
831 // prepareTracks_l() will see mState == FLUSHED, then
832 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800833 if (isDirect()) {
834 mFlushHwPending = true;
835 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800836 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
837 reset();
838 }
Eric Laurent81784c32012-11-19 14:55:58 -0800839 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800840 // Prevent flush being lost if the track is flushed and then resumed
841 // before mixer thread can run. This is important when offloading
842 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700843 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800844 }
845}
846
Haynes Mathew George7844f672014-01-15 12:32:55 -0800847// must be called with thread lock held
848void AudioFlinger::PlaybackThread::Track::flushAck()
849{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800850 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800851 return;
852
Phil Burk4bb650b2016-09-09 12:11:17 -0700853 // Clear the client ring buffer so that the app can prime the buffer while paused.
854 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
855 mServerProxy->flushBufferIfNeeded();
856
Haynes Mathew George7844f672014-01-15 12:32:55 -0800857 mFlushHwPending = false;
858}
859
Eric Laurent81784c32012-11-19 14:55:58 -0800860void AudioFlinger::PlaybackThread::Track::reset()
861{
862 // Do not reset twice to avoid discarding data written just after a flush and before
863 // the audioflinger thread detects the track is stopped.
864 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800865 // Force underrun condition to avoid false underrun callback until first data is
866 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700867 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800868 mFillingUpStatus = FS_FILLING;
869 mResetDone = true;
870 if (mState == FLUSHED) {
871 mState = IDLE;
872 }
873 }
874}
875
Eric Laurentbfb1b832013-01-07 09:53:42 -0800876status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
877{
878 sp<ThreadBase> thread = mThread.promote();
879 if (thread == 0) {
880 ALOGE("thread is dead");
881 return FAILED_TRANSACTION;
882 } else if ((thread->type() == ThreadBase::DIRECT) ||
883 (thread->type() == ThreadBase::OFFLOAD)) {
884 return thread->setParameters(keyValuePairs);
885 } else {
886 return PERMISSION_DENIED;
887 }
888}
889
Glenn Kasten573d80a2013-08-26 09:36:23 -0700890status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
891{
Andy Hung818e7a32016-02-16 18:08:07 -0800892 if (!isOffloaded() && !isDirect()) {
893 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700894 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700895 sp<ThreadBase> thread = mThread.promote();
896 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700897 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700898 }
Phil Burk6140c792015-03-19 14:30:21 -0700899
Glenn Kasten573d80a2013-08-26 09:36:23 -0700900 Mutex::Autolock _l(thread->mLock);
901 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -0800902 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700903}
904
Eric Laurent81784c32012-11-19 14:55:58 -0800905status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
906{
907 status_t status = DEAD_OBJECT;
908 sp<ThreadBase> thread = mThread.promote();
909 if (thread != 0) {
910 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
911 sp<AudioFlinger> af = mClient->audioFlinger();
912
913 Mutex::Autolock _l(af->mLock);
914
915 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
916
917 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
918 Mutex::Autolock _dl(playbackThread->mLock);
919 Mutex::Autolock _sl(srcThread->mLock);
920 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
921 if (chain == 0) {
922 return INVALID_OPERATION;
923 }
924
925 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
926 if (effect == 0) {
927 return INVALID_OPERATION;
928 }
929 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700930 status = playbackThread->addEffect_l(effect);
931 if (status != NO_ERROR) {
932 srcThread->addEffect_l(effect);
933 return INVALID_OPERATION;
934 }
Eric Laurent81784c32012-11-19 14:55:58 -0800935 // removeEffect_l() has stopped the effect if it was active so it must be restarted
936 if (effect->state() == EffectModule::ACTIVE ||
937 effect->state() == EffectModule::STOPPING) {
938 effect->start();
939 }
940
941 sp<EffectChain> dstChain = effect->chain().promote();
942 if (dstChain == 0) {
943 srcThread->addEffect_l(effect);
944 return INVALID_OPERATION;
945 }
946 AudioSystem::unregisterEffect(effect->id());
947 AudioSystem::registerEffect(&effect->desc(),
948 srcThread->id(),
949 dstChain->strategy(),
950 AUDIO_SESSION_OUTPUT_MIX,
951 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700952 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800953 }
954 status = playbackThread->attachAuxEffect(this, EffectId);
955 }
956 return status;
957}
958
959void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
960{
961 mAuxEffectId = EffectId;
962 mAuxBuffer = buffer;
963}
964
Andy Hung818e7a32016-02-16 18:08:07 -0800965bool AudioFlinger::PlaybackThread::Track::presentationComplete(
966 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -0800967{
Andy Hung818e7a32016-02-16 18:08:07 -0800968 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
969 // This assists in proper timestamp computation as well as wakelock management.
970
Eric Laurent81784c32012-11-19 14:55:58 -0800971 // a track is considered presented when the total number of frames written to audio HAL
972 // corresponds to the number of frames written when presentationComplete() is called for the
973 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800974 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
975 // to detect when all frames have been played. In this case framesWritten isn't
976 // useful because it doesn't always reflect whether there is data in the h/w
977 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung818e7a32016-02-16 18:08:07 -0800978 ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
979 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800980 if (mPresentationCompleteFrames == 0) {
981 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung818e7a32016-02-16 18:08:07 -0800982 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
983 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800984 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800985
Andy Hungc54b1ff2016-02-23 14:07:07 -0800986 bool complete;
987 if (isOffloaded()) {
988 complete = true;
989 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700990 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -0800991 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700992 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -0800993 && mAudioTrackServerProxy->isDrained();
994 }
995
996 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -0800997 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800998 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800999 return true;
1000 }
1001 return false;
1002}
1003
1004void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1005{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001006 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001007 if (mSyncEvents[i]->type() == type) {
1008 mSyncEvents[i]->trigger();
1009 mSyncEvents.removeAt(i);
1010 i--;
1011 }
1012 }
1013}
1014
1015// implement VolumeBufferProvider interface
1016
Glenn Kastenc56f3422014-03-21 17:53:17 -07001017gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
1019 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1020 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001021 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1022 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1023 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001024 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001025 if (vl > GAIN_FLOAT_UNITY) {
1026 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001027 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001028 if (vr > GAIN_FLOAT_UNITY) {
1029 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001030 }
1031 // now apply the cached master volume and stream type volume;
1032 // this is trusted but lacks any synchronization or barrier so may be stale
1033 float v = mCachedVolume;
1034 vl *= v;
1035 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001036 // re-combine into packed minifloat
1037 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001038 // FIXME look at mute, pause, and stop flags
1039 return vlr;
1040}
1041
1042status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1043{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001044 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001045 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1046 (mState == STOPPED)))) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001047 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001048 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1049 event->cancel();
1050 return INVALID_OPERATION;
1051 }
1052 (void) TrackBase::setSyncEvent(event);
1053 return NO_ERROR;
1054}
1055
Glenn Kasten5736c352012-12-04 12:12:34 -08001056void AudioFlinger::PlaybackThread::Track::invalidate()
1057{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001058 signalClientFlag(CBLK_INVALID);
1059 mIsInvalid = true;
1060}
1061
1062void AudioFlinger::PlaybackThread::Track::disable()
1063{
1064 signalClientFlag(CBLK_DISABLED);
1065}
1066
1067void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1068{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001069 // FIXME should use proxy, and needs work
1070 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001071 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001072 android_atomic_release_store(0x40000000, &cblk->mFutex);
1073 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001074 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001075}
1076
Eric Laurent59fe0102013-09-27 18:48:26 -07001077void AudioFlinger::PlaybackThread::Track::signal()
1078{
1079 sp<ThreadBase> thread = mThread.promote();
1080 if (thread != 0) {
1081 PlaybackThread *t = (PlaybackThread *)thread.get();
1082 Mutex::Autolock _l(t->mLock);
1083 t->broadcast_l();
1084 }
1085}
1086
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001087//To be called with thread lock held
1088bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1089
1090 if (mState == RESUMING)
1091 return true;
1092 /* Resume is pending if track was stopping before pause was called */
1093 if (mState == STOPPING_1 &&
1094 mResumeToStopping)
1095 return true;
1096
1097 return false;
1098}
1099
1100//To be called with thread lock held
1101void AudioFlinger::PlaybackThread::Track::resumeAck() {
1102
1103
1104 if (mState == RESUMING)
1105 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001106
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001107 // Other possibility of pending resume is stopping_1 state
1108 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001109 // drain being called.
1110 if (mState == STOPPING_1) {
1111 mResumeToStopping = false;
1112 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001113}
Andy Hunge10393e2015-06-12 13:59:33 -07001114
1115//To be called with thread lock held
1116void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001117 int64_t trackFramesReleased, int64_t sinkFramesWritten,
1118 const ExtendedTimestamp &timeStamp) {
1119 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001120 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001121
1122 // adjust server times and set drained state.
1123 //
1124 // Our timestamps are only updated when the track is on the Thread active list.
1125 // We need to ensure that tracks are not removed before full drain.
1126 ExtendedTimestamp local = timeStamp;
1127 bool checked = false;
1128 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1129 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1130 // Lookup the track frame corresponding to the sink frame position.
1131 if (local.mTimeNs[i] > 0) {
1132 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1133 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001134 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hung818e7a32016-02-16 18:08:07 -08001135 mAudioTrackServerProxy->setDrained(
1136 local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1137 checked = true;
1138 }
1139 }
Andy Hunge10393e2015-06-12 13:59:33 -07001140 }
Andy Hung818e7a32016-02-16 18:08:07 -08001141 if (!checked) { // no server info, assume drained.
1142 mAudioTrackServerProxy->setDrained(true);
1143 }
Andy Hungea2b9c02016-02-12 17:06:53 -08001144 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001145 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001146 mServerProxy->setTimestamp(local);
Andy Hunge10393e2015-06-12 13:59:33 -07001147}
1148
Eric Laurent81784c32012-11-19 14:55:58 -08001149// ----------------------------------------------------------------------------
1150
Eric Laurent81784c32012-11-19 14:55:58 -08001151AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1152 PlaybackThread *playbackThread,
1153 DuplicatingThread *sourceThread,
1154 uint32_t sampleRate,
1155 audio_format_t format,
1156 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001157 size_t frameCount,
1158 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001159 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1160 sampleRate, format, channelMask, frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001161 NULL, 0, AUDIO_SESSION_NONE, uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001162 TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001163 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001164{
1165
1166 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001167 mOutBuffer.frameCount = 0;
1168 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001169 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001170 "frameCount %zu, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001171 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001172 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001173 // since client and server are in the same process,
1174 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001175 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1176 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001177 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001178 mClientProxy->setSendLevel(0.0);
1179 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001180 } else {
1181 ALOGW("Error creating output track on thread %p", playbackThread);
1182 }
1183}
1184
1185AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1186{
1187 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001188 delete mClientProxy;
1189 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001190}
1191
1192status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001193 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001194{
1195 status_t status = Track::start(event, triggerSession);
1196 if (status != NO_ERROR) {
1197 return status;
1198 }
1199
1200 mActive = true;
1201 mRetryCount = 127;
1202 return status;
1203}
1204
1205void AudioFlinger::PlaybackThread::OutputTrack::stop()
1206{
1207 Track::stop();
1208 clearBufferQueue();
1209 mOutBuffer.frameCount = 0;
1210 mActive = false;
1211}
1212
Andy Hungc25b84a2015-01-14 19:04:10 -08001213bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001214{
1215 Buffer *pInBuffer;
1216 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001217 bool outputBufferFull = false;
1218 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001219 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001220
1221 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1222
1223 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001224 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001225 }
1226
1227 while (waitTimeLeftMs) {
1228 // First write pending buffers, then new data
1229 if (mBufferQueue.size()) {
1230 pInBuffer = mBufferQueue.itemAt(0);
1231 } else {
1232 pInBuffer = &inBuffer;
1233 }
1234
1235 if (pInBuffer->frameCount == 0) {
1236 break;
1237 }
1238
1239 if (mOutBuffer.frameCount == 0) {
1240 mOutBuffer.frameCount = pInBuffer->frameCount;
1241 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001242 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001243 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001244 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1245 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001246 outputBufferFull = true;
1247 break;
1248 }
1249 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1250 if (waitTimeLeftMs >= waitTimeMs) {
1251 waitTimeLeftMs -= waitTimeMs;
1252 } else {
1253 waitTimeLeftMs = 0;
1254 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001255 if (status == NOT_ENOUGH_DATA) {
1256 restartIfDisabled();
1257 continue;
1258 }
Eric Laurent81784c32012-11-19 14:55:58 -08001259 }
1260
1261 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1262 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001263 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001264 Proxy::Buffer buf;
1265 buf.mFrameCount = outFrames;
1266 buf.mRaw = NULL;
1267 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001268 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001269 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001270 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001271 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001272 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001273
1274 if (pInBuffer->frameCount == 0) {
1275 if (mBufferQueue.size()) {
1276 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001277 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001278 delete pInBuffer;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001279 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001280 mThread.unsafe_get(), mBufferQueue.size());
1281 } else {
1282 break;
1283 }
1284 }
1285 }
1286
1287 // If we could not write all frames, allocate a buffer and queue it for next time.
1288 if (inBuffer.frameCount) {
1289 sp<ThreadBase> thread = mThread.promote();
1290 if (thread != 0 && !thread->standby()) {
1291 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1292 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001293 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001294 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001295 pInBuffer->raw = pInBuffer->mBuffer;
1296 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001297 mBufferQueue.add(pInBuffer);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001298 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001299 mThread.unsafe_get(), mBufferQueue.size());
1300 } else {
1301 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1302 mThread.unsafe_get(), this);
1303 }
1304 }
1305 }
1306
Andy Hungc25b84a2015-01-14 19:04:10 -08001307 // Calling write() with a 0 length buffer means that no more data will be written:
1308 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1309 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1310 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001311 }
1312
1313 return outputBufferFull;
1314}
1315
1316status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1317 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1318{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001319 ClientProxy::Buffer buf;
1320 buf.mFrameCount = buffer->frameCount;
1321 struct timespec timeout;
1322 timeout.tv_sec = waitTimeMs / 1000;
1323 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1324 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1325 buffer->frameCount = buf.mFrameCount;
1326 buffer->raw = buf.mRaw;
1327 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001328}
1329
Eric Laurent81784c32012-11-19 14:55:58 -08001330void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1331{
1332 size_t size = mBufferQueue.size();
1333
1334 for (size_t i = 0; i < size; i++) {
1335 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001336 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001337 delete pBuffer;
1338 }
1339 mBufferQueue.clear();
1340}
1341
Eric Laurent4d231dc2016-03-11 18:38:23 -08001342void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1343{
1344 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1345 if (mActive && (flags & CBLK_DISABLED)) {
1346 start();
1347 }
1348}
Eric Laurent81784c32012-11-19 14:55:58 -08001349
Eric Laurent83b88082014-06-20 18:31:16 -07001350AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001351 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001352 uint32_t sampleRate,
1353 audio_channel_mask_t channelMask,
1354 audio_format_t format,
1355 size_t frameCount,
1356 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001357 audio_output_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001358 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001359 sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001360 buffer, 0, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001361 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1362{
1363 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1364 playbackThread->sampleRate();
1365 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1366 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1367
1368 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1369 this, sampleRate,
1370 (int)mPeerTimeout.tv_sec,
1371 (int)(mPeerTimeout.tv_nsec / 1000000));
1372}
1373
1374AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1375{
1376}
1377
Eric Laurent4d231dc2016-03-11 18:38:23 -08001378status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001379 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001380{
1381 status_t status = Track::start(event, triggerSession);
1382 if (status != NO_ERROR) {
1383 return status;
1384 }
1385 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1386 return status;
1387}
1388
Eric Laurent83b88082014-06-20 18:31:16 -07001389// AudioBufferProvider interface
1390status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001391 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001392{
1393 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1394 Proxy::Buffer buf;
1395 buf.mFrameCount = buffer->frameCount;
1396 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1397 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001398 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001399 if (buf.mFrameCount == 0) {
1400 return WOULD_BLOCK;
1401 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001402 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001403 return status;
1404}
1405
1406void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1407{
1408 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1409 Proxy::Buffer buf;
1410 buf.mFrameCount = buffer->frameCount;
1411 buf.mRaw = buffer->raw;
1412 mPeerProxy->releaseBuffer(&buf);
1413 TrackBase::releaseBuffer(buffer);
1414}
1415
1416status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1417 const struct timespec *timeOut)
1418{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001419 status_t status = NO_ERROR;
1420 static const int32_t kMaxTries = 5;
1421 int32_t tryCounter = kMaxTries;
1422 do {
1423 if (status == NOT_ENOUGH_DATA) {
1424 restartIfDisabled();
1425 }
1426 status = mProxy->obtainBuffer(buffer, timeOut);
1427 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1428 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001429}
1430
1431void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1432{
1433 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001434 restartIfDisabled();
1435 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1436}
1437
1438void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1439{
Eric Laurent83b88082014-06-20 18:31:16 -07001440 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1441 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1442 start();
1443 }
Eric Laurent83b88082014-06-20 18:31:16 -07001444}
1445
Eric Laurent81784c32012-11-19 14:55:58 -08001446// ----------------------------------------------------------------------------
1447// Record
1448// ----------------------------------------------------------------------------
1449
1450AudioFlinger::RecordHandle::RecordHandle(
1451 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1452 : BnAudioRecord(),
1453 mRecordTrack(recordTrack)
1454{
1455}
1456
1457AudioFlinger::RecordHandle::~RecordHandle() {
1458 stop_nonvirtual();
1459 mRecordTrack->destroy();
1460}
1461
Eric Laurent81784c32012-11-19 14:55:58 -08001462status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001463 audio_session_t triggerSession) {
Eric Laurent81784c32012-11-19 14:55:58 -08001464 ALOGV("RecordHandle::start()");
1465 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1466}
1467
1468void AudioFlinger::RecordHandle::stop() {
1469 stop_nonvirtual();
1470}
1471
1472void AudioFlinger::RecordHandle::stop_nonvirtual() {
1473 ALOGV("RecordHandle::stop()");
1474 mRecordTrack->stop();
1475}
1476
1477status_t AudioFlinger::RecordHandle::onTransact(
1478 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1479{
1480 return BnAudioRecord::onTransact(code, data, reply, flags);
1481}
1482
1483// ----------------------------------------------------------------------------
1484
Glenn Kasten05997e22014-03-13 15:08:33 -07001485// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001486AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1487 RecordThread *thread,
1488 const sp<Client>& client,
1489 uint32_t sampleRate,
1490 audio_format_t format,
1491 audio_channel_mask_t channelMask,
1492 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001493 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001494 audio_session_t sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001495 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07001496 audio_input_flags_t flags,
Eric Laurent83b88082014-06-20 18:31:16 -07001497 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001498 : TrackBase(thread, client, sampleRate, format,
Eric Laurent05067782016-06-01 18:27:28 -07001499 channelMask, frameCount, buffer, sessionId, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001500 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001501 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001502 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1503 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001504 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001505 mFramesToDrop(0),
1506 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001507 mRecordBufferConverter(NULL),
1508 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001509{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001510 if (mCblk == NULL) {
1511 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001512 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001513
Andy Hung97a893e2015-03-29 01:03:07 -07001514 mRecordBufferConverter = new RecordBufferConverter(
1515 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1516 channelMask, format, sampleRate);
1517 // Check if the RecordBufferConverter construction was successful.
1518 // If not, don't continue with construction.
1519 //
1520 // NOTE: It would be extremely rare that the record track cannot be created
1521 // for the current device, but a pending or future device change would make
1522 // the record track configuration valid.
1523 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1524 ALOGE("RecordTrack unable to create record buffer converter");
1525 return;
1526 }
1527
Andy Hung6ae58432016-02-16 18:32:24 -08001528 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001529 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001530
Andy Hung97a893e2015-03-29 01:03:07 -07001531 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001532
Eric Laurent05067782016-06-01 18:27:28 -07001533 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001534 ALOG_ASSERT(thread->mFastTrackAvail);
1535 thread->mFastTrackAvail = false;
1536 }
Eric Laurent81784c32012-11-19 14:55:58 -08001537}
1538
1539AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1540{
1541 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001542 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001543 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001544}
1545
Andy Hung97a893e2015-03-29 01:03:07 -07001546status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1547{
1548 status_t status = TrackBase::initCheck();
1549 if (status == NO_ERROR && mServerProxy == 0) {
1550 status = BAD_VALUE;
1551 }
1552 return status;
1553}
1554
Eric Laurent81784c32012-11-19 14:55:58 -08001555// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001556status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001557{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001558 ServerProxy::Buffer buf;
1559 buf.mFrameCount = buffer->frameCount;
1560 status_t status = mServerProxy->obtainBuffer(&buf);
1561 buffer->frameCount = buf.mFrameCount;
1562 buffer->raw = buf.mRaw;
1563 if (buf.mFrameCount == 0) {
1564 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001565 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001566 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001567 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001568}
1569
1570status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001571 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001572{
1573 sp<ThreadBase> thread = mThread.promote();
1574 if (thread != 0) {
1575 RecordThread *recordThread = (RecordThread *)thread.get();
1576 return recordThread->start(this, event, triggerSession);
1577 } else {
1578 return BAD_VALUE;
1579 }
1580}
1581
1582void AudioFlinger::RecordThread::RecordTrack::stop()
1583{
1584 sp<ThreadBase> thread = mThread.promote();
1585 if (thread != 0) {
1586 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001587 if (recordThread->stop(this) && isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001588 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001589 }
1590 }
1591}
1592
1593void AudioFlinger::RecordThread::RecordTrack::destroy()
1594{
1595 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1596 sp<RecordTrack> keep(this);
1597 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001598 if (isExternalTrack()) {
1599 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001600 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001601 }
Glenn Kastend848eb42016-03-08 13:42:11 -08001602 AudioSystem::releaseInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001603 }
Eric Laurent81784c32012-11-19 14:55:58 -08001604 sp<ThreadBase> thread = mThread.promote();
1605 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001606 Mutex::Autolock _l(thread->mLock);
1607 RecordThread *recordThread = (RecordThread *) thread.get();
1608 recordThread->destroyTrack_l(this);
1609 }
1610 }
1611}
1612
Eric Laurent9a54bc22013-09-09 09:08:44 -07001613void AudioFlinger::RecordThread::RecordTrack::invalidate()
1614{
1615 // FIXME should use proxy, and needs work
1616 audio_track_cblk_t* cblk = mCblk;
1617 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1618 android_atomic_release_store(0x40000000, &cblk->mFutex);
1619 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001620 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001621}
1622
Eric Laurent81784c32012-11-19 14:55:58 -08001623
1624/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1625{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001626 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001627}
1628
Marco Nelissenb2208842014-02-07 14:00:50 -08001629void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001630{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001631 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001632 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001633 (mClient == 0) ? getpid_cached : mClient->pid(),
1634 mFormat,
1635 mChannelMask,
1636 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001637 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001638 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001639 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001640 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001641
Eric Laurent81784c32012-11-19 14:55:58 -08001642}
1643
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001644void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1645{
1646 if (event == mSyncStartEvent) {
1647 ssize_t framesToDrop = 0;
1648 sp<ThreadBase> threadBase = mThread.promote();
1649 if (threadBase != 0) {
1650 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1651 // from audio HAL
1652 framesToDrop = threadBase->mFrameCount * 2;
1653 }
1654 mFramesToDrop = framesToDrop;
1655 }
1656}
1657
1658void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1659{
1660 if (mSyncStartEvent != 0) {
1661 mSyncStartEvent->cancel();
1662 mSyncStartEvent.clear();
1663 }
1664 mFramesToDrop = 0;
1665}
1666
Andy Hung3f0c9022016-01-15 17:49:46 -08001667void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1668 int64_t trackFramesReleased, int64_t sourceFramesRead,
1669 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1670{
1671 ExtendedTimestamp local = timestamp;
1672
1673 // Convert HAL frames to server-side track frames at track sample rate.
1674 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1675 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1676 if (local.mTimeNs[i] != 0) {
1677 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1678 const int64_t relativeTrackFrames = relativeServerFrames
1679 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1680 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1681 }
1682 }
Andy Hung6ae58432016-02-16 18:32:24 -08001683 mServerProxy->setTimestamp(local);
Andy Hung3f0c9022016-01-15 17:49:46 -08001684}
Eric Laurent83b88082014-06-20 18:31:16 -07001685
1686AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1687 uint32_t sampleRate,
1688 audio_channel_mask_t channelMask,
1689 audio_format_t format,
1690 size_t frameCount,
1691 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001692 audio_input_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07001693 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001694 buffer, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001695 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1696{
1697 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1698 recordThread->sampleRate();
1699 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1700 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1701
1702 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1703 this, sampleRate,
1704 (int)mPeerTimeout.tv_sec,
1705 (int)(mPeerTimeout.tv_nsec / 1000000));
1706}
1707
1708AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1709{
1710}
1711
1712// AudioBufferProvider interface
1713status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001714 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001715{
1716 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1717 Proxy::Buffer buf;
1718 buf.mFrameCount = buffer->frameCount;
1719 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1720 ALOGV_IF(status != NO_ERROR,
1721 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001722 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001723 if (buf.mFrameCount == 0) {
1724 return WOULD_BLOCK;
1725 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001726 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001727 return status;
1728}
1729
1730void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1731{
1732 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1733 Proxy::Buffer buf;
1734 buf.mFrameCount = buffer->frameCount;
1735 buf.mRaw = buffer->raw;
1736 mPeerProxy->releaseBuffer(&buf);
1737 TrackBase::releaseBuffer(buffer);
1738}
1739
1740status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1741 const struct timespec *timeOut)
1742{
1743 return mProxy->obtainBuffer(buffer, timeOut);
1744}
1745
1746void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1747{
1748 mProxy->releaseBuffer(buffer);
1749}
1750
Glenn Kasten63238ef2015-03-02 15:50:29 -08001751} // namespace android