blob: e8e27e4f6f7b945862a0773634e00c500d72b0e0 [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
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,
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),
Eric Laurentbfb1b832013-01-07 09:53:42 -080096 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070097 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -070098 mType(type),
99 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800100{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700101 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung1f12a8a2016-11-07 16:10:30 -0800102 if (!isTrustedCallingUid(callingUid) || clientUid == AUDIO_UID_INVALID) {
103 ALOGW_IF(clientUid != AUDIO_UID_INVALID && clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -0700104 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
Andy Hung1f12a8a2016-11-07 16:10:30 -0800105 clientUid = callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800106 }
107 // clientUid contains the uid of the app that is responsible for this track, so we can blame
108 // battery usage on it.
109 mUid = clientUid;
110
Eric Laurent81784c32012-11-19 14:55:58 -0800111 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
112 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700113 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
114 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800115 size += bufferSize;
116 }
117
118 if (client != 0) {
119 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700120 if (mCblkMemory == 0 ||
121 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700122 ALOGE("not enough memory for AudioTrack size=%zu", size);
Eric Laurent81784c32012-11-19 14:55:58 -0800123 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700124 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800125 return;
126 }
127 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800128 // this syntax avoids calling the audio_track_cblk_t constructor twice
129 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800130 // assume mCblk != NULL
131 }
132
133 // construct the shared structure in-place.
134 if (mCblk != NULL) {
135 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700136 switch (alloc) {
137 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700138 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
139 if (roHeap == 0 ||
140 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
141 (mBuffer = mBufferMemory->pointer()) == NULL) {
142 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
143 if (roHeap != 0) {
144 roHeap->dump("buffer");
145 }
146 mCblkMemory.clear();
147 mBufferMemory.clear();
148 return;
149 }
Eric Laurent81784c32012-11-19 14:55:58 -0800150 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700151 } break;
152 case ALLOC_PIPE:
153 mBufferMemory = thread->pipeMemory();
154 // mBuffer is the virtual address as seen from current process (mediaserver),
155 // and should normally be coming from mBufferMemory->pointer().
156 // However in this case the TrackBase does not reference the buffer directly.
157 // It should references the buffer via the pipe.
158 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
159 mBuffer = NULL;
160 break;
161 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700162 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700163 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700164 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
165 memset(mBuffer, 0, bufferSize);
166 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700167 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800168#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700169 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700171 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700172 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700173 case ALLOC_LOCAL:
174 mBuffer = calloc(1, bufferSize);
175 break;
176 case ALLOC_NONE:
177 mBuffer = buffer;
178 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800179 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800180
Glenn Kasten46909e72013-02-26 09:20:22 -0800181#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800182 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700183 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800184 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800185 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
186 size_t numCounterOffers = 0;
187 const NBAIO_Format offers[1] = {pipeFormat};
188 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
189 ALOG_ASSERT(index == 0);
190 PipeReader *pipeReader = new PipeReader(*pipe);
191 numCounterOffers = 0;
192 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
193 ALOG_ASSERT(index == 0);
194 mTeeSink = pipe;
195 mTeeSource = pipeReader;
196 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800197 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800198#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199
Eric Laurent81784c32012-11-19 14:55:58 -0800200 }
201}
202
Eric Laurent83b88082014-06-20 18:31:16 -0700203status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
204{
205 status_t status;
206 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
207 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
208 } else {
209 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
210 }
211 return status;
212}
213
Eric Laurent81784c32012-11-19 14:55:58 -0800214AudioFlinger::ThreadBase::TrackBase::~TrackBase()
215{
Glenn Kasten46909e72013-02-26 09:20:22 -0800216#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800217 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800218#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800219 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
Eric Laurent5bba2f62016-03-18 11:14:14 -0700220 mServerProxy.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800221 if (mCblk != NULL) {
222 if (mClient == 0) {
223 delete mCblk;
224 } else {
225 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
226 }
227 }
228 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
229 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700230 // Client destructor must run with AudioFlinger client mutex locked
231 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800232 // If the client's reference count drops to zero, the associated destructor
233 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
234 // relying on the automatic clear() at end of scope.
235 mClient.clear();
236 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700237 // flush the binder command buffer
238 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800239}
240
241// AudioBufferProvider interface
242// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800243// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800244void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
245{
Glenn Kasten46909e72013-02-26 09:20:22 -0800246#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800247 if (mTeeSink != 0) {
248 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
249 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800250#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800251
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800252 ServerProxy::Buffer buf;
253 buf.mFrameCount = buffer->frameCount;
254 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800255 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800256 buffer->raw = NULL;
257 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800258}
259
Eric Laurent81784c32012-11-19 14:55:58 -0800260status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
261{
262 mSyncEvents.add(event);
263 return NO_ERROR;
264}
265
266// ----------------------------------------------------------------------------
267// Playback
268// ----------------------------------------------------------------------------
269
270AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
271 : BnAudioTrack(),
272 mTrack(track)
273{
274}
275
276AudioFlinger::TrackHandle::~TrackHandle() {
277 // just stop the track on deletion, associated resources
278 // will be freed from the main thread once all pending buffers have
279 // been played. Unless it's not in the active track list, in which
280 // case we free everything now...
281 mTrack->destroy();
282}
283
284sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
285 return mTrack->getCblk();
286}
287
288status_t AudioFlinger::TrackHandle::start() {
289 return mTrack->start();
290}
291
292void AudioFlinger::TrackHandle::stop() {
293 mTrack->stop();
294}
295
296void AudioFlinger::TrackHandle::flush() {
297 mTrack->flush();
298}
299
Eric Laurent81784c32012-11-19 14:55:58 -0800300void AudioFlinger::TrackHandle::pause() {
301 mTrack->pause();
302}
303
304status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
305{
306 return mTrack->attachAuxEffect(EffectId);
307}
308
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700309status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
310 return mTrack->setParameters(keyValuePairs);
311}
312
Glenn Kasten53cec222013-08-29 09:01:02 -0700313status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
314{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700315 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700316}
317
Eric Laurent59fe0102013-09-27 18:48:26 -0700318
319void AudioFlinger::TrackHandle::signal()
320{
321 return mTrack->signal();
322}
323
Eric Laurent81784c32012-11-19 14:55:58 -0800324status_t AudioFlinger::TrackHandle::onTransact(
325 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
326{
327 return BnAudioTrack::onTransact(code, data, reply, flags);
328}
329
330// ----------------------------------------------------------------------------
331
332// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
333AudioFlinger::PlaybackThread::Track::Track(
334 PlaybackThread *thread,
335 const sp<Client>& client,
336 audio_stream_type_t streamType,
337 uint32_t sampleRate,
338 audio_format_t format,
339 audio_channel_mask_t channelMask,
340 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700341 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800342 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800343 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800344 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -0700345 audio_output_flags_t flags,
Eric Laurent83b88082014-06-20 18:31:16 -0700346 track_type type)
347 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
348 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
Eric Laurent05067782016-06-01 18:27:28 -0700349 sessionId, uid, true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700350 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
351 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800352 mFillingUpStatus(FS_INVALID),
353 // mRetryCount initialized later when needed
354 mSharedBuffer(sharedBuffer),
355 mStreamType(streamType),
356 mName(-1), // see note below
357 mMainBuffer(thread->mixBuffer()),
358 mAuxBuffer(NULL),
359 mAuxEffectId(0), mHasVolumeController(false),
360 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700361 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Andy Hunge10393e2015-06-12 13:59:33 -0700362 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800363 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800364 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800365 mIsInvalid(false),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800366 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700367 mFlushHwPending(false),
368 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -0800369{
Eric Laurent83b88082014-06-20 18:31:16 -0700370 // client == 0 implies sharedBuffer == 0
371 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
372
Eric Laurente93cc032016-05-05 10:15:10 -0700373 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Eric Laurent83b88082014-06-20 18:31:16 -0700374 sharedBuffer->size());
375
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700376 if (mCblk == NULL) {
377 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800378 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700379
380 if (sharedBuffer == 0) {
381 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700382 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700383 } else {
384 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
385 mFrameSize);
386 }
387 mServerProxy = mAudioTrackServerProxy;
388
Eric Laurentad7dd962016-09-22 12:38:37 -0700389 mName = thread->getTrackName_l(channelMask, format, sessionId, uid);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700390 if (mName < 0) {
391 ALOGE("no more track names available");
392 return;
393 }
394 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700395 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700396 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
397 // race with setSyncEvent(). However, if we call it, we cannot properly start
398 // static fast tracks (SoundPool) immediately after stopping.
399 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700400 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
401 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700402 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700403 // FIXME This is too eager. We allocate a fast track index before the
404 // fast track becomes active. Since fast tracks are a scarce resource,
405 // this means we are potentially denying other more important fast tracks from
406 // being created. It would be better to allocate the index dynamically.
407 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700408 thread->mFastTrackAvailMask &= ~(1 << i);
409 }
Eric Laurent81784c32012-11-19 14:55:58 -0800410}
411
412AudioFlinger::PlaybackThread::Track::~Track()
413{
414 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700415
416 // The destructor would clear mSharedBuffer,
417 // but it will not push the decremented reference count,
418 // leaving the client's IMemory dangling indefinitely.
419 // This prevents that leak.
420 if (mSharedBuffer != 0) {
421 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700422 }
Eric Laurent81784c32012-11-19 14:55:58 -0800423}
424
Glenn Kasten03003332013-08-06 15:40:54 -0700425status_t AudioFlinger::PlaybackThread::Track::initCheck() const
426{
427 status_t status = TrackBase::initCheck();
428 if (status == NO_ERROR && mName < 0) {
429 status = NO_MEMORY;
430 }
431 return status;
432}
433
Eric Laurent81784c32012-11-19 14:55:58 -0800434void AudioFlinger::PlaybackThread::Track::destroy()
435{
436 // NOTE: destroyTrack_l() can remove a strong reference to this Track
437 // by removing it from mTracks vector, so there is a risk that this Tracks's
438 // destructor is called. As the destructor needs to lock mLock,
439 // we must acquire a strong reference on this Track before locking mLock
440 // here so that the destructor is called only when exiting this function.
441 // On the other hand, as long as Track::destroy() is only called by
442 // TrackHandle destructor, the TrackHandle still holds a strong ref on
443 // this Track with its member mTrack.
444 sp<Track> keep(this);
445 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700446 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800447 sp<ThreadBase> thread = mThread.promote();
448 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800449 Mutex::Autolock _l(thread->mLock);
450 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700451 wasActive = playbackThread->destroyTrack_l(this);
452 }
453 if (isExternalTrack() && !wasActive) {
Glenn Kastend848eb42016-03-08 13:42:11 -0800454 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800455 }
456 }
457}
458
459/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
460{
Marco Nelissenb2208842014-02-07 14:00:50 -0800461 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Andy Hung2148bf02016-11-28 19:01:02 -0800462 "L dB R dB Server Main buf Aux buf Flags UndFrmCnt Flushed\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800463}
464
Marco Nelissenb2208842014-02-07 14:00:50 -0800465void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800466{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700467 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800468 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800469 sprintf(buffer, " F %2d", mFastIndex);
470 } else if (mName >= AudioMixer::TRACK0) {
471 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800472 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800473 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800474 }
475 track_state state = mState;
476 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800477 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800478 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800479 } else {
480 switch (state) {
481 case IDLE:
482 stateChar = 'I';
483 break;
484 case STOPPING_1:
485 stateChar = 's';
486 break;
487 case STOPPING_2:
488 stateChar = '5';
489 break;
490 case STOPPED:
491 stateChar = 'S';
492 break;
493 case RESUMING:
494 stateChar = 'R';
495 break;
496 case ACTIVE:
497 stateChar = 'A';
498 break;
499 case PAUSING:
500 stateChar = 'p';
501 break;
502 case PAUSED:
503 stateChar = 'P';
504 break;
505 case FLUSHED:
506 stateChar = 'F';
507 break;
508 default:
509 stateChar = '?';
510 break;
511 }
Eric Laurent81784c32012-11-19 14:55:58 -0800512 }
513 char nowInUnderrun;
514 switch (mObservedUnderruns.mBitFields.mMostRecent) {
515 case UNDERRUN_FULL:
516 nowInUnderrun = ' ';
517 break;
518 case UNDERRUN_PARTIAL:
519 nowInUnderrun = '<';
520 break;
521 case UNDERRUN_EMPTY:
522 nowInUnderrun = '*';
523 break;
524 default:
525 nowInUnderrun = '?';
526 break;
527 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000528 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 -0800529 "%08X %08zX %08zX 0x%03X %9u%c %7u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800530 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800531 (mClient == 0) ? getpid_cached : mClient->pid(),
532 mStreamType,
533 mFormat,
534 mChannelMask,
535 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800536 mFrameCount,
537 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800538 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800539 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700540 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
541 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700542 mCblk->mServer,
Andy Hung2148bf02016-11-28 19:01:02 -0800543 (size_t)mMainBuffer, // use %zX as %p appends 0x
544 (size_t)mAuxBuffer, // use %zX as %p appends 0x
Glenn Kasten96f60d82013-07-12 10:21:18 -0700545 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700546 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -0800547 nowInUnderrun,
548 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000); // 7 digits
Eric Laurent81784c32012-11-19 14:55:58 -0800549}
550
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800551uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
552 return mAudioTrackServerProxy->getSampleRate();
553}
554
Eric Laurent81784c32012-11-19 14:55:58 -0800555// AudioBufferProvider interface
556status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800557 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800558{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800559 ServerProxy::Buffer buf;
560 size_t desiredFrames = buffer->frameCount;
561 buf.mFrameCount = desiredFrames;
562 status_t status = mServerProxy->obtainBuffer(&buf);
563 buffer->frameCount = buf.mFrameCount;
564 buffer->raw = buf.mRaw;
565 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700566 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800567 } else {
568 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800569 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800570
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800571 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800572}
573
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700574// releaseBuffer() is not overridden
575
576// ExtendedAudioBufferProvider interface
577
Andy Hung27876c02014-09-09 18:07:55 -0700578// framesReady() may return an approximation of the number of frames if called
579// from a different thread than the one calling Proxy->obtainBuffer() and
580// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
581// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800582size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700583 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
584 // Static tracks return zero frames immediately upon stopping (for FastTracks).
585 // The remainder of the buffer is not drained.
586 return 0;
587 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800588 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800589}
590
Andy Hung818e7a32016-02-16 18:08:07 -0800591int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700592{
593 return mAudioTrackServerProxy->framesReleased();
594}
595
Andy Hung818e7a32016-02-16 18:08:07 -0800596void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800597{
598 // This call comes from a FastTrack and should be kept lockless.
599 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800600 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800601
Andy Hung818e7a32016-02-16 18:08:07 -0800602 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hung6ae58432016-02-16 18:32:24 -0800603}
604
Eric Laurent81784c32012-11-19 14:55:58 -0800605// Don't call for fast tracks; the framesReady() could result in priority inversion
606bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800607 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
608 return true;
609 }
610
Eric Laurent16498512014-03-17 17:22:08 -0700611 if (isStopping()) {
612 if (framesReady() > 0) {
613 mFillingUpStatus = FS_FILLED;
614 }
Eric Laurent81784c32012-11-19 14:55:58 -0800615 return true;
616 }
617
Phil Burke8972b02016-03-04 11:29:57 -0800618 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700619 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800620 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700621 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800622 return true;
623 }
624 return false;
625}
626
Glenn Kasten0f11b512014-01-31 16:18:54 -0800627status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800628 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800629{
630 status_t status = NO_ERROR;
631 ALOGV("start(%d), calling pid %d session %d",
632 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
633
634 sp<ThreadBase> thread = mThread.promote();
635 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700636 if (isOffloaded()) {
637 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
638 Mutex::Autolock _lth(thread->mLock);
639 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700640 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
641 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700642 invalidate();
643 return PERMISSION_DENIED;
644 }
645 }
646 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800647 track_state state = mState;
648 // here the track could be either new, or restarted
649 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800650
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800651 // initial state-stopping. next state-pausing.
652 // What if resume is called ?
653
654 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800655 if (mResumeToStopping) {
656 // happened we need to resume to STOPPING_1
657 mState = TrackBase::STOPPING_1;
658 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
659 } else {
660 mState = TrackBase::RESUMING;
661 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
662 }
Eric Laurent81784c32012-11-19 14:55:58 -0800663 } else {
664 mState = TrackBase::ACTIVE;
665 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
666 }
667
Andy Hunge10393e2015-06-12 13:59:33 -0700668 // states to reset position info for non-offloaded/direct tracks
669 if (!isOffloaded() && !isDirect()
670 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
671 mFrameMap.reset();
672 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800673 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700674 if (isFastTrack()) {
675 // refresh fast track underruns on start because that field is never cleared
676 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
677 // after stop.
678 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
679 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800680 status = playbackThread->addTrack_l(this);
681 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800682 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800683 // restore previous state if start was rejected by policy manager
684 if (status == PERMISSION_DENIED) {
685 mState = state;
686 }
687 }
688 // track was already in the active list, not a problem
689 if (status == ALREADY_EXISTS) {
690 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700691 } else {
692 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
693 // It is usually unsafe to access the server proxy from a binder thread.
694 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
695 // isn't looking at this track yet: we still hold the normal mixer thread lock,
696 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700697 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700698 ServerProxy::Buffer buffer;
699 buffer.mFrameCount = 1;
700 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800701 }
702 } else {
703 status = BAD_VALUE;
704 }
705 return status;
706}
707
708void AudioFlinger::PlaybackThread::Track::stop()
709{
710 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
711 sp<ThreadBase> thread = mThread.promote();
712 if (thread != 0) {
713 Mutex::Autolock _l(thread->mLock);
714 track_state state = mState;
715 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
716 // If the track is not active (PAUSED and buffers full), flush buffers
717 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
718 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
719 reset();
720 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700721 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800722 mState = STOPPED;
723 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800724 // For fast tracks prepareTracks_l() will set state to STOPPING_2
725 // presentation is complete
726 // For an offloaded track this starts a drain and state will
727 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800728 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -0700729 if (isOffloaded()) {
730 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
731 }
Eric Laurent81784c32012-11-19 14:55:58 -0800732 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700733 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800734 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
735 playbackThread);
736 }
Eric Laurent81784c32012-11-19 14:55:58 -0800737 }
738}
739
740void AudioFlinger::PlaybackThread::Track::pause()
741{
742 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
743 sp<ThreadBase> thread = mThread.promote();
744 if (thread != 0) {
745 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800746 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
747 switch (mState) {
748 case STOPPING_1:
749 case STOPPING_2:
750 if (!isOffloaded()) {
751 /* nothing to do if track is not offloaded */
752 break;
753 }
754
755 // Offloaded track was draining, we need to carry on draining when resumed
756 mResumeToStopping = true;
757 // fall through...
758 case ACTIVE:
759 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800760 mState = PAUSING;
761 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700762 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800763 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800764
Eric Laurentbfb1b832013-01-07 09:53:42 -0800765 default:
766 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800767 }
768 }
769}
770
771void AudioFlinger::PlaybackThread::Track::flush()
772{
773 ALOGV("flush(%d)", mName);
774 sp<ThreadBase> thread = mThread.promote();
775 if (thread != 0) {
776 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800777 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800778
Phil Burk4bb650b2016-09-09 12:11:17 -0700779 // Flush the ring buffer now if the track is not active in the PlaybackThread.
780 // Otherwise the flush would not be done until the track is resumed.
781 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
782 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
783 (void)mServerProxy->flushBufferIfNeeded();
784 }
785
Eric Laurentbfb1b832013-01-07 09:53:42 -0800786 if (isOffloaded()) {
787 // If offloaded we allow flush during any state except terminated
788 // and keep the track active to avoid problems if user is seeking
789 // rapidly and underlying hardware has a significant delay handling
790 // a pause
791 if (isTerminated()) {
792 return;
793 }
794
795 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800796 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800797
798 if (mState == STOPPING_1 || mState == STOPPING_2) {
799 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
800 mState = ACTIVE;
801 }
802
Haynes Mathew George7844f672014-01-15 12:32:55 -0800803 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800804 mResumeToStopping = false;
805 } else {
806 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
807 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
808 return;
809 }
810 // No point remaining in PAUSED state after a flush => go to
811 // FLUSHED state
812 mState = FLUSHED;
813 // do not reset the track if it is still in the process of being stopped or paused.
814 // this will be done by prepareTracks_l() when the track is stopped.
815 // prepareTracks_l() will see mState == FLUSHED, then
816 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800817 if (isDirect()) {
818 mFlushHwPending = true;
819 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800820 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
821 reset();
822 }
Eric Laurent81784c32012-11-19 14:55:58 -0800823 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800824 // Prevent flush being lost if the track is flushed and then resumed
825 // before mixer thread can run. This is important when offloading
826 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700827 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800828 }
829}
830
Haynes Mathew George7844f672014-01-15 12:32:55 -0800831// must be called with thread lock held
832void AudioFlinger::PlaybackThread::Track::flushAck()
833{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800834 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800835 return;
836
Phil Burk4bb650b2016-09-09 12:11:17 -0700837 // Clear the client ring buffer so that the app can prime the buffer while paused.
838 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
839 mServerProxy->flushBufferIfNeeded();
840
Haynes Mathew George7844f672014-01-15 12:32:55 -0800841 mFlushHwPending = false;
842}
843
Eric Laurent81784c32012-11-19 14:55:58 -0800844void AudioFlinger::PlaybackThread::Track::reset()
845{
846 // Do not reset twice to avoid discarding data written just after a flush and before
847 // the audioflinger thread detects the track is stopped.
848 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800849 // Force underrun condition to avoid false underrun callback until first data is
850 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700851 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800852 mFillingUpStatus = FS_FILLING;
853 mResetDone = true;
854 if (mState == FLUSHED) {
855 mState = IDLE;
856 }
857 }
858}
859
Eric Laurentbfb1b832013-01-07 09:53:42 -0800860status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
861{
862 sp<ThreadBase> thread = mThread.promote();
863 if (thread == 0) {
864 ALOGE("thread is dead");
865 return FAILED_TRANSACTION;
866 } else if ((thread->type() == ThreadBase::DIRECT) ||
867 (thread->type() == ThreadBase::OFFLOAD)) {
868 return thread->setParameters(keyValuePairs);
869 } else {
870 return PERMISSION_DENIED;
871 }
872}
873
Glenn Kasten573d80a2013-08-26 09:36:23 -0700874status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
875{
Andy Hung818e7a32016-02-16 18:08:07 -0800876 if (!isOffloaded() && !isDirect()) {
877 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700878 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700879 sp<ThreadBase> thread = mThread.promote();
880 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700881 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700882 }
Phil Burk6140c792015-03-19 14:30:21 -0700883
Glenn Kasten573d80a2013-08-26 09:36:23 -0700884 Mutex::Autolock _l(thread->mLock);
885 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -0800886 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700887}
888
Eric Laurent81784c32012-11-19 14:55:58 -0800889status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
890{
891 status_t status = DEAD_OBJECT;
892 sp<ThreadBase> thread = mThread.promote();
893 if (thread != 0) {
894 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
895 sp<AudioFlinger> af = mClient->audioFlinger();
896
897 Mutex::Autolock _l(af->mLock);
898
899 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
900
901 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
902 Mutex::Autolock _dl(playbackThread->mLock);
903 Mutex::Autolock _sl(srcThread->mLock);
904 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
905 if (chain == 0) {
906 return INVALID_OPERATION;
907 }
908
909 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
910 if (effect == 0) {
911 return INVALID_OPERATION;
912 }
913 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700914 status = playbackThread->addEffect_l(effect);
915 if (status != NO_ERROR) {
916 srcThread->addEffect_l(effect);
917 return INVALID_OPERATION;
918 }
Eric Laurent81784c32012-11-19 14:55:58 -0800919 // removeEffect_l() has stopped the effect if it was active so it must be restarted
920 if (effect->state() == EffectModule::ACTIVE ||
921 effect->state() == EffectModule::STOPPING) {
922 effect->start();
923 }
924
925 sp<EffectChain> dstChain = effect->chain().promote();
926 if (dstChain == 0) {
927 srcThread->addEffect_l(effect);
928 return INVALID_OPERATION;
929 }
930 AudioSystem::unregisterEffect(effect->id());
931 AudioSystem::registerEffect(&effect->desc(),
932 srcThread->id(),
933 dstChain->strategy(),
934 AUDIO_SESSION_OUTPUT_MIX,
935 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700936 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800937 }
938 status = playbackThread->attachAuxEffect(this, EffectId);
939 }
940 return status;
941}
942
943void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
944{
945 mAuxEffectId = EffectId;
946 mAuxBuffer = buffer;
947}
948
Andy Hung818e7a32016-02-16 18:08:07 -0800949bool AudioFlinger::PlaybackThread::Track::presentationComplete(
950 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -0800951{
Andy Hung818e7a32016-02-16 18:08:07 -0800952 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
953 // This assists in proper timestamp computation as well as wakelock management.
954
Eric Laurent81784c32012-11-19 14:55:58 -0800955 // a track is considered presented when the total number of frames written to audio HAL
956 // corresponds to the number of frames written when presentationComplete() is called for the
957 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800958 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
959 // to detect when all frames have been played. In this case framesWritten isn't
960 // useful because it doesn't always reflect whether there is data in the h/w
961 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung818e7a32016-02-16 18:08:07 -0800962 ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
963 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800964 if (mPresentationCompleteFrames == 0) {
965 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung818e7a32016-02-16 18:08:07 -0800966 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
967 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800968 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800969
Andy Hungc54b1ff2016-02-23 14:07:07 -0800970 bool complete;
971 if (isOffloaded()) {
972 complete = true;
973 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700974 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -0800975 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700976 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -0800977 && mAudioTrackServerProxy->isDrained();
978 }
979
980 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -0800981 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800982 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800983 return true;
984 }
985 return false;
986}
987
988void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
989{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700990 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800991 if (mSyncEvents[i]->type() == type) {
992 mSyncEvents[i]->trigger();
993 mSyncEvents.removeAt(i);
994 i--;
995 }
996 }
997}
998
999// implement VolumeBufferProvider interface
1000
Glenn Kastenc56f3422014-03-21 17:53:17 -07001001gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001002{
1003 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1004 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001005 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1006 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1007 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001008 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001009 if (vl > GAIN_FLOAT_UNITY) {
1010 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001011 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001012 if (vr > GAIN_FLOAT_UNITY) {
1013 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001014 }
1015 // now apply the cached master volume and stream type volume;
1016 // this is trusted but lacks any synchronization or barrier so may be stale
1017 float v = mCachedVolume;
1018 vl *= v;
1019 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001020 // re-combine into packed minifloat
1021 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001022 // FIXME look at mute, pause, and stop flags
1023 return vlr;
1024}
1025
1026status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1027{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001028 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001029 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1030 (mState == STOPPED)))) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001031 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001032 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1033 event->cancel();
1034 return INVALID_OPERATION;
1035 }
1036 (void) TrackBase::setSyncEvent(event);
1037 return NO_ERROR;
1038}
1039
Glenn Kasten5736c352012-12-04 12:12:34 -08001040void AudioFlinger::PlaybackThread::Track::invalidate()
1041{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001042 signalClientFlag(CBLK_INVALID);
1043 mIsInvalid = true;
1044}
1045
1046void AudioFlinger::PlaybackThread::Track::disable()
1047{
1048 signalClientFlag(CBLK_DISABLED);
1049}
1050
1051void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1052{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001053 // FIXME should use proxy, and needs work
1054 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001055 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001056 android_atomic_release_store(0x40000000, &cblk->mFutex);
1057 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001058 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001059}
1060
Eric Laurent59fe0102013-09-27 18:48:26 -07001061void AudioFlinger::PlaybackThread::Track::signal()
1062{
1063 sp<ThreadBase> thread = mThread.promote();
1064 if (thread != 0) {
1065 PlaybackThread *t = (PlaybackThread *)thread.get();
1066 Mutex::Autolock _l(t->mLock);
1067 t->broadcast_l();
1068 }
1069}
1070
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001071//To be called with thread lock held
1072bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1073
1074 if (mState == RESUMING)
1075 return true;
1076 /* Resume is pending if track was stopping before pause was called */
1077 if (mState == STOPPING_1 &&
1078 mResumeToStopping)
1079 return true;
1080
1081 return false;
1082}
1083
1084//To be called with thread lock held
1085void AudioFlinger::PlaybackThread::Track::resumeAck() {
1086
1087
1088 if (mState == RESUMING)
1089 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001090
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001091 // Other possibility of pending resume is stopping_1 state
1092 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001093 // drain being called.
1094 if (mState == STOPPING_1) {
1095 mResumeToStopping = false;
1096 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001097}
Andy Hunge10393e2015-06-12 13:59:33 -07001098
1099//To be called with thread lock held
1100void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001101 int64_t trackFramesReleased, int64_t sinkFramesWritten,
1102 const ExtendedTimestamp &timeStamp) {
1103 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001104 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001105
1106 // adjust server times and set drained state.
1107 //
1108 // Our timestamps are only updated when the track is on the Thread active list.
1109 // We need to ensure that tracks are not removed before full drain.
1110 ExtendedTimestamp local = timeStamp;
1111 bool checked = false;
1112 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1113 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1114 // Lookup the track frame corresponding to the sink frame position.
1115 if (local.mTimeNs[i] > 0) {
1116 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1117 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001118 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hung818e7a32016-02-16 18:08:07 -08001119 mAudioTrackServerProxy->setDrained(
1120 local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1121 checked = true;
1122 }
1123 }
Andy Hunge10393e2015-06-12 13:59:33 -07001124 }
Andy Hung818e7a32016-02-16 18:08:07 -08001125 if (!checked) { // no server info, assume drained.
1126 mAudioTrackServerProxy->setDrained(true);
1127 }
Andy Hungea2b9c02016-02-12 17:06:53 -08001128 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001129 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001130 mServerProxy->setTimestamp(local);
Andy Hunge10393e2015-06-12 13:59:33 -07001131}
1132
Eric Laurent81784c32012-11-19 14:55:58 -08001133// ----------------------------------------------------------------------------
1134
Eric Laurent81784c32012-11-19 14:55:58 -08001135AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1136 PlaybackThread *playbackThread,
1137 DuplicatingThread *sourceThread,
1138 uint32_t sampleRate,
1139 audio_format_t format,
1140 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001141 size_t frameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001142 uid_t uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001143 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1144 sampleRate, format, channelMask, frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001145 NULL, 0, AUDIO_SESSION_NONE, uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001146 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07001147 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08001148{
1149
1150 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001151 mOutBuffer.frameCount = 0;
1152 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001153 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001154 "frameCount %zu, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001155 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001156 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001157 // since client and server are in the same process,
1158 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001159 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1160 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001161 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001162 mClientProxy->setSendLevel(0.0);
1163 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001164 } else {
1165 ALOGW("Error creating output track on thread %p", playbackThread);
1166 }
1167}
1168
1169AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1170{
1171 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001172 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001173}
1174
1175status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001176 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001177{
1178 status_t status = Track::start(event, triggerSession);
1179 if (status != NO_ERROR) {
1180 return status;
1181 }
1182
1183 mActive = true;
1184 mRetryCount = 127;
1185 return status;
1186}
1187
1188void AudioFlinger::PlaybackThread::OutputTrack::stop()
1189{
1190 Track::stop();
1191 clearBufferQueue();
1192 mOutBuffer.frameCount = 0;
1193 mActive = false;
1194}
1195
Andy Hungc25b84a2015-01-14 19:04:10 -08001196bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001197{
1198 Buffer *pInBuffer;
1199 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001200 bool outputBufferFull = false;
1201 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001202 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001203
1204 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1205
1206 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001207 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001208 }
1209
1210 while (waitTimeLeftMs) {
1211 // First write pending buffers, then new data
1212 if (mBufferQueue.size()) {
1213 pInBuffer = mBufferQueue.itemAt(0);
1214 } else {
1215 pInBuffer = &inBuffer;
1216 }
1217
1218 if (pInBuffer->frameCount == 0) {
1219 break;
1220 }
1221
1222 if (mOutBuffer.frameCount == 0) {
1223 mOutBuffer.frameCount = pInBuffer->frameCount;
1224 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001225 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001226 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001227 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1228 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001229 outputBufferFull = true;
1230 break;
1231 }
1232 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1233 if (waitTimeLeftMs >= waitTimeMs) {
1234 waitTimeLeftMs -= waitTimeMs;
1235 } else {
1236 waitTimeLeftMs = 0;
1237 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001238 if (status == NOT_ENOUGH_DATA) {
1239 restartIfDisabled();
1240 continue;
1241 }
Eric Laurent81784c32012-11-19 14:55:58 -08001242 }
1243
1244 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1245 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001246 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001247 Proxy::Buffer buf;
1248 buf.mFrameCount = outFrames;
1249 buf.mRaw = NULL;
1250 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001251 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001252 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001253 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001254 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001255 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001256
1257 if (pInBuffer->frameCount == 0) {
1258 if (mBufferQueue.size()) {
1259 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001260 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001261 delete pInBuffer;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001262 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001263 mThread.unsafe_get(), mBufferQueue.size());
1264 } else {
1265 break;
1266 }
1267 }
1268 }
1269
1270 // If we could not write all frames, allocate a buffer and queue it for next time.
1271 if (inBuffer.frameCount) {
1272 sp<ThreadBase> thread = mThread.promote();
1273 if (thread != 0 && !thread->standby()) {
1274 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1275 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001276 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001277 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001278 pInBuffer->raw = pInBuffer->mBuffer;
1279 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001280 mBufferQueue.add(pInBuffer);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001281 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001282 mThread.unsafe_get(), mBufferQueue.size());
1283 } else {
1284 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1285 mThread.unsafe_get(), this);
1286 }
1287 }
1288 }
1289
Andy Hungc25b84a2015-01-14 19:04:10 -08001290 // Calling write() with a 0 length buffer means that no more data will be written:
1291 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1292 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1293 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001294 }
1295
1296 return outputBufferFull;
1297}
1298
1299status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1300 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1301{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001302 ClientProxy::Buffer buf;
1303 buf.mFrameCount = buffer->frameCount;
1304 struct timespec timeout;
1305 timeout.tv_sec = waitTimeMs / 1000;
1306 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1307 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1308 buffer->frameCount = buf.mFrameCount;
1309 buffer->raw = buf.mRaw;
1310 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001311}
1312
Eric Laurent81784c32012-11-19 14:55:58 -08001313void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1314{
1315 size_t size = mBufferQueue.size();
1316
1317 for (size_t i = 0; i < size; i++) {
1318 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001319 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001320 delete pBuffer;
1321 }
1322 mBufferQueue.clear();
1323}
1324
Eric Laurent4d231dc2016-03-11 18:38:23 -08001325void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1326{
1327 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1328 if (mActive && (flags & CBLK_DISABLED)) {
1329 start();
1330 }
1331}
Eric Laurent81784c32012-11-19 14:55:58 -08001332
Eric Laurent83b88082014-06-20 18:31:16 -07001333AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001334 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001335 uint32_t sampleRate,
1336 audio_channel_mask_t channelMask,
1337 audio_format_t format,
1338 size_t frameCount,
1339 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001340 audio_output_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001341 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001342 sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001343 buffer, 0, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001344 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1345{
1346 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1347 playbackThread->sampleRate();
1348 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1349 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1350
1351 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1352 this, sampleRate,
1353 (int)mPeerTimeout.tv_sec,
1354 (int)(mPeerTimeout.tv_nsec / 1000000));
1355}
1356
1357AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1358{
1359}
1360
Eric Laurent4d231dc2016-03-11 18:38:23 -08001361status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001362 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001363{
1364 status_t status = Track::start(event, triggerSession);
1365 if (status != NO_ERROR) {
1366 return status;
1367 }
1368 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1369 return status;
1370}
1371
Eric Laurent83b88082014-06-20 18:31:16 -07001372// AudioBufferProvider interface
1373status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001374 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001375{
1376 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1377 Proxy::Buffer buf;
1378 buf.mFrameCount = buffer->frameCount;
1379 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1380 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001381 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001382 if (buf.mFrameCount == 0) {
1383 return WOULD_BLOCK;
1384 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001385 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001386 return status;
1387}
1388
1389void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1390{
1391 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1392 Proxy::Buffer buf;
1393 buf.mFrameCount = buffer->frameCount;
1394 buf.mRaw = buffer->raw;
1395 mPeerProxy->releaseBuffer(&buf);
1396 TrackBase::releaseBuffer(buffer);
1397}
1398
1399status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1400 const struct timespec *timeOut)
1401{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001402 status_t status = NO_ERROR;
1403 static const int32_t kMaxTries = 5;
1404 int32_t tryCounter = kMaxTries;
1405 do {
1406 if (status == NOT_ENOUGH_DATA) {
1407 restartIfDisabled();
1408 }
1409 status = mProxy->obtainBuffer(buffer, timeOut);
1410 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1411 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001412}
1413
1414void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1415{
1416 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001417 restartIfDisabled();
1418 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1419}
1420
1421void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1422{
Eric Laurent83b88082014-06-20 18:31:16 -07001423 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1424 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1425 start();
1426 }
Eric Laurent83b88082014-06-20 18:31:16 -07001427}
1428
Eric Laurent81784c32012-11-19 14:55:58 -08001429// ----------------------------------------------------------------------------
1430// Record
1431// ----------------------------------------------------------------------------
1432
1433AudioFlinger::RecordHandle::RecordHandle(
1434 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1435 : BnAudioRecord(),
1436 mRecordTrack(recordTrack)
1437{
1438}
1439
1440AudioFlinger::RecordHandle::~RecordHandle() {
1441 stop_nonvirtual();
1442 mRecordTrack->destroy();
1443}
1444
Eric Laurent81784c32012-11-19 14:55:58 -08001445status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001446 audio_session_t triggerSession) {
Eric Laurent81784c32012-11-19 14:55:58 -08001447 ALOGV("RecordHandle::start()");
1448 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1449}
1450
1451void AudioFlinger::RecordHandle::stop() {
1452 stop_nonvirtual();
1453}
1454
1455void AudioFlinger::RecordHandle::stop_nonvirtual() {
1456 ALOGV("RecordHandle::stop()");
1457 mRecordTrack->stop();
1458}
1459
1460status_t AudioFlinger::RecordHandle::onTransact(
1461 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1462{
1463 return BnAudioRecord::onTransact(code, data, reply, flags);
1464}
1465
1466// ----------------------------------------------------------------------------
1467
Glenn Kasten05997e22014-03-13 15:08:33 -07001468// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001469AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1470 RecordThread *thread,
1471 const sp<Client>& client,
1472 uint32_t sampleRate,
1473 audio_format_t format,
1474 audio_channel_mask_t channelMask,
1475 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001476 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001477 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001478 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001479 audio_input_flags_t flags,
Eric Laurent83b88082014-06-20 18:31:16 -07001480 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001481 : TrackBase(thread, client, sampleRate, format,
Eric Laurent05067782016-06-01 18:27:28 -07001482 channelMask, frameCount, buffer, sessionId, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001483 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001484 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001485 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1486 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001487 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001488 mFramesToDrop(0),
1489 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001490 mRecordBufferConverter(NULL),
1491 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001492{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001493 if (mCblk == NULL) {
1494 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001495 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001496
Andy Hung97a893e2015-03-29 01:03:07 -07001497 mRecordBufferConverter = new RecordBufferConverter(
1498 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1499 channelMask, format, sampleRate);
1500 // Check if the RecordBufferConverter construction was successful.
1501 // If not, don't continue with construction.
1502 //
1503 // NOTE: It would be extremely rare that the record track cannot be created
1504 // for the current device, but a pending or future device change would make
1505 // the record track configuration valid.
1506 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1507 ALOGE("RecordTrack unable to create record buffer converter");
1508 return;
1509 }
1510
Andy Hung6ae58432016-02-16 18:32:24 -08001511 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001512 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001513
Andy Hung97a893e2015-03-29 01:03:07 -07001514 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001515
Eric Laurent05067782016-06-01 18:27:28 -07001516 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001517 ALOG_ASSERT(thread->mFastTrackAvail);
1518 thread->mFastTrackAvail = false;
1519 }
Eric Laurent81784c32012-11-19 14:55:58 -08001520}
1521
1522AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1523{
1524 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001525 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001526 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001527}
1528
Andy Hung97a893e2015-03-29 01:03:07 -07001529status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1530{
1531 status_t status = TrackBase::initCheck();
1532 if (status == NO_ERROR && mServerProxy == 0) {
1533 status = BAD_VALUE;
1534 }
1535 return status;
1536}
1537
Eric Laurent81784c32012-11-19 14:55:58 -08001538// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001539status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001540{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001541 ServerProxy::Buffer buf;
1542 buf.mFrameCount = buffer->frameCount;
1543 status_t status = mServerProxy->obtainBuffer(&buf);
1544 buffer->frameCount = buf.mFrameCount;
1545 buffer->raw = buf.mRaw;
1546 if (buf.mFrameCount == 0) {
1547 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001548 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001549 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001550 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001551}
1552
1553status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001554 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001555{
1556 sp<ThreadBase> thread = mThread.promote();
1557 if (thread != 0) {
1558 RecordThread *recordThread = (RecordThread *)thread.get();
1559 return recordThread->start(this, event, triggerSession);
1560 } else {
1561 return BAD_VALUE;
1562 }
1563}
1564
1565void AudioFlinger::RecordThread::RecordTrack::stop()
1566{
1567 sp<ThreadBase> thread = mThread.promote();
1568 if (thread != 0) {
1569 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001570 if (recordThread->stop(this) && isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001571 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001572 }
1573 }
1574}
1575
1576void AudioFlinger::RecordThread::RecordTrack::destroy()
1577{
1578 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1579 sp<RecordTrack> keep(this);
1580 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001581 if (isExternalTrack()) {
1582 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001583 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001584 }
Glenn Kastend848eb42016-03-08 13:42:11 -08001585 AudioSystem::releaseInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001586 }
Eric Laurent81784c32012-11-19 14:55:58 -08001587 sp<ThreadBase> thread = mThread.promote();
1588 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001589 Mutex::Autolock _l(thread->mLock);
1590 RecordThread *recordThread = (RecordThread *) thread.get();
1591 recordThread->destroyTrack_l(this);
1592 }
1593 }
1594}
1595
Eric Laurent9a54bc22013-09-09 09:08:44 -07001596void AudioFlinger::RecordThread::RecordTrack::invalidate()
1597{
1598 // FIXME should use proxy, and needs work
1599 audio_track_cblk_t* cblk = mCblk;
1600 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1601 android_atomic_release_store(0x40000000, &cblk->mFutex);
1602 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001603 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001604}
1605
Eric Laurent81784c32012-11-19 14:55:58 -08001606
1607/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1608{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001609 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001610}
1611
Marco Nelissenb2208842014-02-07 14:00:50 -08001612void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001613{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001614 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001615 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001616 (mClient == 0) ? getpid_cached : mClient->pid(),
1617 mFormat,
1618 mChannelMask,
1619 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001620 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001621 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001622 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001623 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001624
Eric Laurent81784c32012-11-19 14:55:58 -08001625}
1626
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001627void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1628{
1629 if (event == mSyncStartEvent) {
1630 ssize_t framesToDrop = 0;
1631 sp<ThreadBase> threadBase = mThread.promote();
1632 if (threadBase != 0) {
1633 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1634 // from audio HAL
1635 framesToDrop = threadBase->mFrameCount * 2;
1636 }
1637 mFramesToDrop = framesToDrop;
1638 }
1639}
1640
1641void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1642{
1643 if (mSyncStartEvent != 0) {
1644 mSyncStartEvent->cancel();
1645 mSyncStartEvent.clear();
1646 }
1647 mFramesToDrop = 0;
1648}
1649
Andy Hung3f0c9022016-01-15 17:49:46 -08001650void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1651 int64_t trackFramesReleased, int64_t sourceFramesRead,
1652 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1653{
1654 ExtendedTimestamp local = timestamp;
1655
1656 // Convert HAL frames to server-side track frames at track sample rate.
1657 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1658 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1659 if (local.mTimeNs[i] != 0) {
1660 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1661 const int64_t relativeTrackFrames = relativeServerFrames
1662 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1663 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1664 }
1665 }
Andy Hung6ae58432016-02-16 18:32:24 -08001666 mServerProxy->setTimestamp(local);
Andy Hung3f0c9022016-01-15 17:49:46 -08001667}
Eric Laurent83b88082014-06-20 18:31:16 -07001668
1669AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1670 uint32_t sampleRate,
1671 audio_channel_mask_t channelMask,
1672 audio_format_t format,
1673 size_t frameCount,
1674 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001675 audio_input_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07001676 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001677 buffer, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001678 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1679{
1680 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1681 recordThread->sampleRate();
1682 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1683 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1684
1685 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1686 this, sampleRate,
1687 (int)mPeerTimeout.tv_sec,
1688 (int)(mPeerTimeout.tv_nsec / 1000000));
1689}
1690
1691AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1692{
1693}
1694
1695// AudioBufferProvider interface
1696status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001697 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001698{
1699 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1700 Proxy::Buffer buf;
1701 buf.mFrameCount = buffer->frameCount;
1702 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1703 ALOGV_IF(status != NO_ERROR,
1704 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001705 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001706 if (buf.mFrameCount == 0) {
1707 return WOULD_BLOCK;
1708 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001709 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001710 return status;
1711}
1712
1713void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1714{
1715 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1716 Proxy::Buffer buf;
1717 buf.mFrameCount = buffer->frameCount;
1718 buf.mRaw = buffer->raw;
1719 mPeerProxy->releaseBuffer(&buf);
1720 TrackBase::releaseBuffer(buffer);
1721}
1722
1723status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1724 const struct timespec *timeOut)
1725{
1726 return mProxy->obtainBuffer(buffer, timeOut);
1727}
1728
1729void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1730{
1731 mProxy->releaseBuffer(buffer);
1732}
1733
Glenn Kasten63238ef2015-03-02 15:50:29 -08001734} // namespace android