blob: 48e09c72f5a3262bc84a46969b1393e29857cb1b [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenad8510a2015-02-17 16:24:07 -080023#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070025#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080026#include <utils/Log.h>
27
28#include <private/media/AudioTrackShared.h>
29
Eric Laurent81784c32012-11-19 14:55:58 -080030#include "AudioFlinger.h"
31#include "ServiceUtilities.h"
32
Glenn Kastenda6ef132013-01-10 12:31:01 -080033#include <media/nbaio/Pipe.h>
34#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070035#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080036
Eric Laurent81784c32012-11-19 14:55:58 -080037// ----------------------------------------------------------------------------
38
39// Note: the following macro is used for extremely verbose logging message. In
40// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
41// 0; but one side effect of this is to turn all LOGV's as well. Some messages
42// are so verbose that we want to suppress them even when we have ALOG_ASSERT
43// turned on. Do not uncomment the #def below unless you really know what you
44// are doing and want to see all of the extremely verbose messages.
45//#define VERY_VERY_VERBOSE_LOGGING
46#ifdef VERY_VERY_VERBOSE_LOGGING
47#define ALOGVV ALOGV
48#else
49#define ALOGVV(a...) do { } while(0)
50#endif
51
Andy Hunge10393e2015-06-12 13:59:33 -070052// TODO move to a common header (Also shared with AudioTrack.cpp)
53#define NANOS_PER_SECOND 1000000000
Chih-Hung Hsieh9a3fbd92016-06-03 15:09:07 -070054#define TIME_TO_NANOS(time) ((uint64_t)(time).tv_sec * NANOS_PER_SECOND + (time).tv_nsec)
Andy Hunge10393e2015-06-12 13:59:33 -070055
Eric Laurent81784c32012-11-19 14:55:58 -080056namespace android {
57
58// ----------------------------------------------------------------------------
59// TrackBase
60// ----------------------------------------------------------------------------
61
Glenn Kastenda6ef132013-01-10 12:31:01 -080062static volatile int32_t nextTrackId = 55;
63
Eric Laurent81784c32012-11-19 14:55:58 -080064// TrackBase constructor must be called with AudioFlinger::mLock held
65AudioFlinger::ThreadBase::TrackBase::TrackBase(
66 ThreadBase *thread,
67 const sp<Client>& client,
68 uint32_t sampleRate,
69 audio_format_t format,
70 audio_channel_mask_t channelMask,
71 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070072 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -080073 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -080074 uid_t clientUid,
Glenn Kastend776ac62014-05-07 09:16:09 -070075 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070076 alloc_type alloc,
Eric Laurent20b9ef02016-12-05 11:03:16 -080077 track_type type,
78 audio_port_handle_t portId)
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),
Eric Laurent20b9ef02016-12-05 11:03:16 -080099 mThreadIoHandle(thread->id()),
100 mPortId(portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800101{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700102 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung1f12a8a2016-11-07 16:10:30 -0800103 if (!isTrustedCallingUid(callingUid) || clientUid == AUDIO_UID_INVALID) {
104 ALOGW_IF(clientUid != AUDIO_UID_INVALID && clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -0700105 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
Andy Hung1f12a8a2016-11-07 16:10:30 -0800106 clientUid = 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);
113 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700114 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
115 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800116 size += bufferSize;
117 }
118
119 if (client != 0) {
120 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700121 if (mCblkMemory == 0 ||
122 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700123 ALOGE("not enough memory for AudioTrack size=%zu", size);
Eric Laurent81784c32012-11-19 14:55:58 -0800124 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700125 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800126 return;
127 }
128 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800129 // this syntax avoids calling the audio_track_cblk_t constructor twice
130 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800131 // assume mCblk != NULL
132 }
133
134 // construct the shared structure in-place.
135 if (mCblk != NULL) {
136 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700137 switch (alloc) {
138 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700139 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
140 if (roHeap == 0 ||
141 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
142 (mBuffer = mBufferMemory->pointer()) == NULL) {
143 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
144 if (roHeap != 0) {
145 roHeap->dump("buffer");
146 }
147 mCblkMemory.clear();
148 mBufferMemory.clear();
149 return;
150 }
Eric Laurent81784c32012-11-19 14:55:58 -0800151 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700152 } break;
153 case ALLOC_PIPE:
154 mBufferMemory = thread->pipeMemory();
155 // mBuffer is the virtual address as seen from current process (mediaserver),
156 // and should normally be coming from mBufferMemory->pointer().
157 // However in this case the TrackBase does not reference the buffer directly.
158 // It should references the buffer via the pipe.
159 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
160 mBuffer = NULL;
161 break;
162 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700163 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700164 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700165 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
166 memset(mBuffer, 0, bufferSize);
167 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700168 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800169#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700170 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800171#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700172 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700173 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700174 case ALLOC_LOCAL:
175 mBuffer = calloc(1, bufferSize);
176 break;
177 case ALLOC_NONE:
178 mBuffer = buffer;
179 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800180 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800181
Glenn Kasten46909e72013-02-26 09:20:22 -0800182#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800183 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700184 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800185 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800186 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
187 size_t numCounterOffers = 0;
188 const NBAIO_Format offers[1] = {pipeFormat};
189 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
190 ALOG_ASSERT(index == 0);
191 PipeReader *pipeReader = new PipeReader(*pipe);
192 numCounterOffers = 0;
193 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
194 ALOG_ASSERT(index == 0);
195 mTeeSink = pipe;
196 mTeeSource = pipeReader;
197 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800198 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800199#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800200
Eric Laurent81784c32012-11-19 14:55:58 -0800201 }
202}
203
Eric Laurent83b88082014-06-20 18:31:16 -0700204status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
205{
206 status_t status;
207 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
208 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
209 } else {
210 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
211 }
212 return status;
213}
214
Eric Laurent81784c32012-11-19 14:55:58 -0800215AudioFlinger::ThreadBase::TrackBase::~TrackBase()
216{
Glenn Kasten46909e72013-02-26 09:20:22 -0800217#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800218 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800219#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800220 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
Eric Laurent5bba2f62016-03-18 11:14:14 -0700221 mServerProxy.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800222 if (mCblk != NULL) {
223 if (mClient == 0) {
224 delete mCblk;
225 } else {
226 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
227 }
228 }
229 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
230 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700231 // Client destructor must run with AudioFlinger client mutex locked
232 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800233 // If the client's reference count drops to zero, the associated destructor
234 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
235 // relying on the automatic clear() at end of scope.
236 mClient.clear();
237 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700238 // flush the binder command buffer
239 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800240}
241
242// AudioBufferProvider interface
243// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800244// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800245void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
246{
Glenn Kasten46909e72013-02-26 09:20:22 -0800247#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800248 if (mTeeSink != 0) {
249 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
250 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800251#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800252
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800253 ServerProxy::Buffer buf;
254 buf.mFrameCount = buffer->frameCount;
255 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800256 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800257 buffer->raw = NULL;
258 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800259}
260
Eric Laurent81784c32012-11-19 14:55:58 -0800261status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
262{
263 mSyncEvents.add(event);
264 return NO_ERROR;
265}
266
267// ----------------------------------------------------------------------------
268// Playback
269// ----------------------------------------------------------------------------
270
271AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
272 : BnAudioTrack(),
273 mTrack(track)
274{
275}
276
277AudioFlinger::TrackHandle::~TrackHandle() {
278 // just stop the track on deletion, associated resources
279 // will be freed from the main thread once all pending buffers have
280 // been played. Unless it's not in the active track list, in which
281 // case we free everything now...
282 mTrack->destroy();
283}
284
285sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
286 return mTrack->getCblk();
287}
288
289status_t AudioFlinger::TrackHandle::start() {
290 return mTrack->start();
291}
292
293void AudioFlinger::TrackHandle::stop() {
294 mTrack->stop();
295}
296
297void AudioFlinger::TrackHandle::flush() {
298 mTrack->flush();
299}
300
Eric Laurent81784c32012-11-19 14:55:58 -0800301void AudioFlinger::TrackHandle::pause() {
302 mTrack->pause();
303}
304
305status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
306{
307 return mTrack->attachAuxEffect(EffectId);
308}
309
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700310status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
311 return mTrack->setParameters(keyValuePairs);
312}
313
Glenn Kasten53cec222013-08-29 09:01:02 -0700314status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
315{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700316 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700317}
318
Eric Laurent59fe0102013-09-27 18:48:26 -0700319
320void AudioFlinger::TrackHandle::signal()
321{
322 return mTrack->signal();
323}
324
Eric Laurent81784c32012-11-19 14:55:58 -0800325status_t AudioFlinger::TrackHandle::onTransact(
326 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
327{
328 return BnAudioTrack::onTransact(code, data, reply, flags);
329}
330
331// ----------------------------------------------------------------------------
332
333// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
334AudioFlinger::PlaybackThread::Track::Track(
335 PlaybackThread *thread,
336 const sp<Client>& client,
337 audio_stream_type_t streamType,
338 uint32_t sampleRate,
339 audio_format_t format,
340 audio_channel_mask_t channelMask,
341 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700342 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800343 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800344 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800345 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -0700346 audio_output_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800347 track_type type,
348 audio_port_handle_t portId)
Eric Laurent83b88082014-06-20 18:31:16 -0700349 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
350 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
Eric Laurent05067782016-06-01 18:27:28 -0700351 sessionId, uid, true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700352 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800353 type, portId),
Eric Laurent81784c32012-11-19 14:55:58 -0800354 mFillingUpStatus(FS_INVALID),
355 // mRetryCount initialized later when needed
356 mSharedBuffer(sharedBuffer),
357 mStreamType(streamType),
358 mName(-1), // see note below
359 mMainBuffer(thread->mixBuffer()),
360 mAuxBuffer(NULL),
361 mAuxEffectId(0), mHasVolumeController(false),
362 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700363 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Andy Hunge10393e2015-06-12 13:59:33 -0700364 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800365 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800366 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800367 mIsInvalid(false),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800368 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700369 mFlushHwPending(false),
370 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -0800371{
Eric Laurent83b88082014-06-20 18:31:16 -0700372 // client == 0 implies sharedBuffer == 0
373 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
374
Eric Laurente93cc032016-05-05 10:15:10 -0700375 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Eric Laurent83b88082014-06-20 18:31:16 -0700376 sharedBuffer->size());
377
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700378 if (mCblk == NULL) {
379 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800380 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700381
382 if (sharedBuffer == 0) {
383 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700384 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700385 } else {
386 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
387 mFrameSize);
388 }
389 mServerProxy = mAudioTrackServerProxy;
390
Eric Laurentad7dd962016-09-22 12:38:37 -0700391 mName = thread->getTrackName_l(channelMask, format, sessionId, uid);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700392 if (mName < 0) {
393 ALOGE("no more track names available");
394 return;
395 }
396 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700397 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700398 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
399 // race with setSyncEvent(). However, if we call it, we cannot properly start
400 // static fast tracks (SoundPool) immediately after stopping.
401 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700402 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
403 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700404 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700405 // FIXME This is too eager. We allocate a fast track index before the
406 // fast track becomes active. Since fast tracks are a scarce resource,
407 // this means we are potentially denying other more important fast tracks from
408 // being created. It would be better to allocate the index dynamically.
409 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700410 thread->mFastTrackAvailMask &= ~(1 << i);
411 }
Eric Laurent81784c32012-11-19 14:55:58 -0800412}
413
414AudioFlinger::PlaybackThread::Track::~Track()
415{
416 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700417
418 // The destructor would clear mSharedBuffer,
419 // but it will not push the decremented reference count,
420 // leaving the client's IMemory dangling indefinitely.
421 // This prevents that leak.
422 if (mSharedBuffer != 0) {
423 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700424 }
Eric Laurent81784c32012-11-19 14:55:58 -0800425}
426
Glenn Kasten03003332013-08-06 15:40:54 -0700427status_t AudioFlinger::PlaybackThread::Track::initCheck() const
428{
429 status_t status = TrackBase::initCheck();
430 if (status == NO_ERROR && mName < 0) {
431 status = NO_MEMORY;
432 }
433 return status;
434}
435
Eric Laurent81784c32012-11-19 14:55:58 -0800436void AudioFlinger::PlaybackThread::Track::destroy()
437{
438 // NOTE: destroyTrack_l() can remove a strong reference to this Track
439 // by removing it from mTracks vector, so there is a risk that this Tracks's
440 // destructor is called. As the destructor needs to lock mLock,
441 // we must acquire a strong reference on this Track before locking mLock
442 // here so that the destructor is called only when exiting this function.
443 // On the other hand, as long as Track::destroy() is only called by
444 // TrackHandle destructor, the TrackHandle still holds a strong ref on
445 // this Track with its member mTrack.
446 sp<Track> keep(this);
447 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700448 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800449 sp<ThreadBase> thread = mThread.promote();
450 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800451 Mutex::Autolock _l(thread->mLock);
452 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700453 wasActive = playbackThread->destroyTrack_l(this);
454 }
455 if (isExternalTrack() && !wasActive) {
Glenn Kastend848eb42016-03-08 13:42:11 -0800456 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800457 }
458 }
459}
460
461/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
462{
Marco Nelissenb2208842014-02-07 14:00:50 -0800463 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Andy Hung2148bf02016-11-28 19:01:02 -0800464 "L dB R dB Server Main buf Aux buf Flags UndFrmCnt Flushed\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800465}
466
Marco Nelissenb2208842014-02-07 14:00:50 -0800467void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800468{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700469 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800470 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800471 sprintf(buffer, " F %2d", mFastIndex);
472 } else if (mName >= AudioMixer::TRACK0) {
473 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800474 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800475 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800476 }
477 track_state state = mState;
478 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800479 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800480 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800481 } else {
482 switch (state) {
483 case IDLE:
484 stateChar = 'I';
485 break;
486 case STOPPING_1:
487 stateChar = 's';
488 break;
489 case STOPPING_2:
490 stateChar = '5';
491 break;
492 case STOPPED:
493 stateChar = 'S';
494 break;
495 case RESUMING:
496 stateChar = 'R';
497 break;
498 case ACTIVE:
499 stateChar = 'A';
500 break;
501 case PAUSING:
502 stateChar = 'p';
503 break;
504 case PAUSED:
505 stateChar = 'P';
506 break;
507 case FLUSHED:
508 stateChar = 'F';
509 break;
510 default:
511 stateChar = '?';
512 break;
513 }
Eric Laurent81784c32012-11-19 14:55:58 -0800514 }
515 char nowInUnderrun;
516 switch (mObservedUnderruns.mBitFields.mMostRecent) {
517 case UNDERRUN_FULL:
518 nowInUnderrun = ' ';
519 break;
520 case UNDERRUN_PARTIAL:
521 nowInUnderrun = '<';
522 break;
523 case UNDERRUN_EMPTY:
524 nowInUnderrun = '*';
525 break;
526 default:
527 nowInUnderrun = '?';
528 break;
529 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000530 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 -0800531 "%08X %08zX %08zX 0x%03X %9u%c %7u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800532 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800533 (mClient == 0) ? getpid_cached : mClient->pid(),
534 mStreamType,
535 mFormat,
536 mChannelMask,
537 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800538 mFrameCount,
539 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800540 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800541 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700542 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
543 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700544 mCblk->mServer,
Andy Hung2148bf02016-11-28 19:01:02 -0800545 (size_t)mMainBuffer, // use %zX as %p appends 0x
546 (size_t)mAuxBuffer, // use %zX as %p appends 0x
Glenn Kasten96f60d82013-07-12 10:21:18 -0700547 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700548 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -0800549 nowInUnderrun,
550 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000); // 7 digits
Eric Laurent81784c32012-11-19 14:55:58 -0800551}
552
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
554 return mAudioTrackServerProxy->getSampleRate();
555}
556
Eric Laurent81784c32012-11-19 14:55:58 -0800557// AudioBufferProvider interface
558status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800559 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800560{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561 ServerProxy::Buffer buf;
562 size_t desiredFrames = buffer->frameCount;
563 buf.mFrameCount = desiredFrames;
564 status_t status = mServerProxy->obtainBuffer(&buf);
565 buffer->frameCount = buf.mFrameCount;
566 buffer->raw = buf.mRaw;
567 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700568 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800569 } else {
570 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800571 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800572
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800573 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800574}
575
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700576// releaseBuffer() is not overridden
577
578// ExtendedAudioBufferProvider interface
579
Andy Hung27876c02014-09-09 18:07:55 -0700580// framesReady() may return an approximation of the number of frames if called
581// from a different thread than the one calling Proxy->obtainBuffer() and
582// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
583// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800584size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700585 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
586 // Static tracks return zero frames immediately upon stopping (for FastTracks).
587 // The remainder of the buffer is not drained.
588 return 0;
589 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800590 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800591}
592
Andy Hung818e7a32016-02-16 18:08:07 -0800593int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700594{
595 return mAudioTrackServerProxy->framesReleased();
596}
597
Andy Hung818e7a32016-02-16 18:08:07 -0800598void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800599{
600 // This call comes from a FastTrack and should be kept lockless.
601 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800602 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800603
Andy Hung818e7a32016-02-16 18:08:07 -0800604 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hung6ae58432016-02-16 18:32:24 -0800605}
606
Eric Laurent81784c32012-11-19 14:55:58 -0800607// Don't call for fast tracks; the framesReady() could result in priority inversion
608bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800609 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
610 return true;
611 }
612
Eric Laurent16498512014-03-17 17:22:08 -0700613 if (isStopping()) {
614 if (framesReady() > 0) {
615 mFillingUpStatus = FS_FILLED;
616 }
Eric Laurent81784c32012-11-19 14:55:58 -0800617 return true;
618 }
619
Phil Burke8972b02016-03-04 11:29:57 -0800620 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700621 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800622 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700623 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800624 return true;
625 }
626 return false;
627}
628
Glenn Kasten0f11b512014-01-31 16:18:54 -0800629status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800630 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
632 status_t status = NO_ERROR;
633 ALOGV("start(%d), calling pid %d session %d",
634 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
635
636 sp<ThreadBase> thread = mThread.promote();
637 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700638 if (isOffloaded()) {
639 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
640 Mutex::Autolock _lth(thread->mLock);
641 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700642 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
643 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700644 invalidate();
645 return PERMISSION_DENIED;
646 }
647 }
648 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800649 track_state state = mState;
650 // here the track could be either new, or restarted
651 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800652
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800653 // initial state-stopping. next state-pausing.
654 // What if resume is called ?
655
656 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800657 if (mResumeToStopping) {
658 // happened we need to resume to STOPPING_1
659 mState = TrackBase::STOPPING_1;
660 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
661 } else {
662 mState = TrackBase::RESUMING;
663 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
664 }
Eric Laurent81784c32012-11-19 14:55:58 -0800665 } else {
666 mState = TrackBase::ACTIVE;
667 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
668 }
669
Andy Hunge10393e2015-06-12 13:59:33 -0700670 // states to reset position info for non-offloaded/direct tracks
671 if (!isOffloaded() && !isDirect()
672 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
673 mFrameMap.reset();
674 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800675 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700676 if (isFastTrack()) {
677 // refresh fast track underruns on start because that field is never cleared
678 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
679 // after stop.
680 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
681 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800682 status = playbackThread->addTrack_l(this);
683 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800684 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800685 // restore previous state if start was rejected by policy manager
686 if (status == PERMISSION_DENIED) {
687 mState = state;
688 }
689 }
690 // track was already in the active list, not a problem
691 if (status == ALREADY_EXISTS) {
692 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700693 } else {
694 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
695 // It is usually unsafe to access the server proxy from a binder thread.
696 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
697 // isn't looking at this track yet: we still hold the normal mixer thread lock,
698 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700699 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700700 ServerProxy::Buffer buffer;
701 buffer.mFrameCount = 1;
702 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800703 }
704 } else {
705 status = BAD_VALUE;
706 }
707 return status;
708}
709
710void AudioFlinger::PlaybackThread::Track::stop()
711{
712 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
713 sp<ThreadBase> thread = mThread.promote();
714 if (thread != 0) {
715 Mutex::Autolock _l(thread->mLock);
716 track_state state = mState;
717 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
718 // If the track is not active (PAUSED and buffers full), flush buffers
719 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
720 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
721 reset();
722 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700723 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800724 mState = STOPPED;
725 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800726 // For fast tracks prepareTracks_l() will set state to STOPPING_2
727 // presentation is complete
728 // For an offloaded track this starts a drain and state will
729 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800730 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -0700731 if (isOffloaded()) {
732 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
733 }
Eric Laurent81784c32012-11-19 14:55:58 -0800734 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700735 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800736 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
737 playbackThread);
738 }
Eric Laurent81784c32012-11-19 14:55:58 -0800739 }
740}
741
742void AudioFlinger::PlaybackThread::Track::pause()
743{
744 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
745 sp<ThreadBase> thread = mThread.promote();
746 if (thread != 0) {
747 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800748 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
749 switch (mState) {
750 case STOPPING_1:
751 case STOPPING_2:
752 if (!isOffloaded()) {
753 /* nothing to do if track is not offloaded */
754 break;
755 }
756
757 // Offloaded track was draining, we need to carry on draining when resumed
758 mResumeToStopping = true;
759 // fall through...
760 case ACTIVE:
761 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800762 mState = PAUSING;
763 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700764 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800765 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800766
Eric Laurentbfb1b832013-01-07 09:53:42 -0800767 default:
768 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800769 }
770 }
771}
772
773void AudioFlinger::PlaybackThread::Track::flush()
774{
775 ALOGV("flush(%d)", mName);
776 sp<ThreadBase> thread = mThread.promote();
777 if (thread != 0) {
778 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800779 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800780
Phil Burk4bb650b2016-09-09 12:11:17 -0700781 // Flush the ring buffer now if the track is not active in the PlaybackThread.
782 // Otherwise the flush would not be done until the track is resumed.
783 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
784 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
785 (void)mServerProxy->flushBufferIfNeeded();
786 }
787
Eric Laurentbfb1b832013-01-07 09:53:42 -0800788 if (isOffloaded()) {
789 // If offloaded we allow flush during any state except terminated
790 // and keep the track active to avoid problems if user is seeking
791 // rapidly and underlying hardware has a significant delay handling
792 // a pause
793 if (isTerminated()) {
794 return;
795 }
796
797 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800798 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800799
800 if (mState == STOPPING_1 || mState == STOPPING_2) {
801 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
802 mState = ACTIVE;
803 }
804
Haynes Mathew George7844f672014-01-15 12:32:55 -0800805 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800806 mResumeToStopping = false;
807 } else {
808 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
809 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
810 return;
811 }
812 // No point remaining in PAUSED state after a flush => go to
813 // FLUSHED state
814 mState = FLUSHED;
815 // do not reset the track if it is still in the process of being stopped or paused.
816 // this will be done by prepareTracks_l() when the track is stopped.
817 // prepareTracks_l() will see mState == FLUSHED, then
818 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800819 if (isDirect()) {
820 mFlushHwPending = true;
821 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800822 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
823 reset();
824 }
Eric Laurent81784c32012-11-19 14:55:58 -0800825 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800826 // Prevent flush being lost if the track is flushed and then resumed
827 // before mixer thread can run. This is important when offloading
828 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700829 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800830 }
831}
832
Haynes Mathew George7844f672014-01-15 12:32:55 -0800833// must be called with thread lock held
834void AudioFlinger::PlaybackThread::Track::flushAck()
835{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800836 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800837 return;
838
Phil Burk4bb650b2016-09-09 12:11:17 -0700839 // Clear the client ring buffer so that the app can prime the buffer while paused.
840 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
841 mServerProxy->flushBufferIfNeeded();
842
Haynes Mathew George7844f672014-01-15 12:32:55 -0800843 mFlushHwPending = false;
844}
845
Eric Laurent81784c32012-11-19 14:55:58 -0800846void AudioFlinger::PlaybackThread::Track::reset()
847{
848 // Do not reset twice to avoid discarding data written just after a flush and before
849 // the audioflinger thread detects the track is stopped.
850 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800851 // Force underrun condition to avoid false underrun callback until first data is
852 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700853 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800854 mFillingUpStatus = FS_FILLING;
855 mResetDone = true;
856 if (mState == FLUSHED) {
857 mState = IDLE;
858 }
859 }
860}
861
Eric Laurentbfb1b832013-01-07 09:53:42 -0800862status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
863{
864 sp<ThreadBase> thread = mThread.promote();
865 if (thread == 0) {
866 ALOGE("thread is dead");
867 return FAILED_TRANSACTION;
868 } else if ((thread->type() == ThreadBase::DIRECT) ||
869 (thread->type() == ThreadBase::OFFLOAD)) {
870 return thread->setParameters(keyValuePairs);
871 } else {
872 return PERMISSION_DENIED;
873 }
874}
875
Glenn Kasten573d80a2013-08-26 09:36:23 -0700876status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
877{
Andy Hung818e7a32016-02-16 18:08:07 -0800878 if (!isOffloaded() && !isDirect()) {
879 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700880 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700881 sp<ThreadBase> thread = mThread.promote();
882 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700883 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700884 }
Phil Burk6140c792015-03-19 14:30:21 -0700885
Glenn Kasten573d80a2013-08-26 09:36:23 -0700886 Mutex::Autolock _l(thread->mLock);
887 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -0800888 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700889}
890
Eric Laurent81784c32012-11-19 14:55:58 -0800891status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
892{
893 status_t status = DEAD_OBJECT;
894 sp<ThreadBase> thread = mThread.promote();
895 if (thread != 0) {
896 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
897 sp<AudioFlinger> af = mClient->audioFlinger();
898
899 Mutex::Autolock _l(af->mLock);
900
901 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
902
903 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
904 Mutex::Autolock _dl(playbackThread->mLock);
905 Mutex::Autolock _sl(srcThread->mLock);
906 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
907 if (chain == 0) {
908 return INVALID_OPERATION;
909 }
910
911 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
912 if (effect == 0) {
913 return INVALID_OPERATION;
914 }
915 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700916 status = playbackThread->addEffect_l(effect);
917 if (status != NO_ERROR) {
918 srcThread->addEffect_l(effect);
919 return INVALID_OPERATION;
920 }
Eric Laurent81784c32012-11-19 14:55:58 -0800921 // removeEffect_l() has stopped the effect if it was active so it must be restarted
922 if (effect->state() == EffectModule::ACTIVE ||
923 effect->state() == EffectModule::STOPPING) {
924 effect->start();
925 }
926
927 sp<EffectChain> dstChain = effect->chain().promote();
928 if (dstChain == 0) {
929 srcThread->addEffect_l(effect);
930 return INVALID_OPERATION;
931 }
932 AudioSystem::unregisterEffect(effect->id());
933 AudioSystem::registerEffect(&effect->desc(),
934 srcThread->id(),
935 dstChain->strategy(),
936 AUDIO_SESSION_OUTPUT_MIX,
937 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700938 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800939 }
940 status = playbackThread->attachAuxEffect(this, EffectId);
941 }
942 return status;
943}
944
945void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
946{
947 mAuxEffectId = EffectId;
948 mAuxBuffer = buffer;
949}
950
Andy Hung818e7a32016-02-16 18:08:07 -0800951bool AudioFlinger::PlaybackThread::Track::presentationComplete(
952 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -0800953{
Andy Hung818e7a32016-02-16 18:08:07 -0800954 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
955 // This assists in proper timestamp computation as well as wakelock management.
956
Eric Laurent81784c32012-11-19 14:55:58 -0800957 // a track is considered presented when the total number of frames written to audio HAL
958 // corresponds to the number of frames written when presentationComplete() is called for the
959 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800960 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
961 // to detect when all frames have been played. In this case framesWritten isn't
962 // useful because it doesn't always reflect whether there is data in the h/w
963 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung818e7a32016-02-16 18:08:07 -0800964 ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
965 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800966 if (mPresentationCompleteFrames == 0) {
967 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung818e7a32016-02-16 18:08:07 -0800968 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
969 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800970 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800971
Andy Hungc54b1ff2016-02-23 14:07:07 -0800972 bool complete;
973 if (isOffloaded()) {
974 complete = true;
975 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700976 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -0800977 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700978 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -0800979 && mAudioTrackServerProxy->isDrained();
980 }
981
982 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -0800983 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800984 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800985 return true;
986 }
987 return false;
988}
989
990void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
991{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700992 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800993 if (mSyncEvents[i]->type() == type) {
994 mSyncEvents[i]->trigger();
995 mSyncEvents.removeAt(i);
996 i--;
997 }
998 }
999}
1000
1001// implement VolumeBufferProvider interface
1002
Glenn Kastenc56f3422014-03-21 17:53:17 -07001003gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001004{
1005 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1006 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001007 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1008 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1009 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001010 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001011 if (vl > GAIN_FLOAT_UNITY) {
1012 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001013 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001014 if (vr > GAIN_FLOAT_UNITY) {
1015 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001016 }
1017 // now apply the cached master volume and stream type volume;
1018 // this is trusted but lacks any synchronization or barrier so may be stale
1019 float v = mCachedVolume;
1020 vl *= v;
1021 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001022 // re-combine into packed minifloat
1023 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001024 // FIXME look at mute, pause, and stop flags
1025 return vlr;
1026}
1027
1028status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1029{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001030 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001031 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1032 (mState == STOPPED)))) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001033 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001034 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1035 event->cancel();
1036 return INVALID_OPERATION;
1037 }
1038 (void) TrackBase::setSyncEvent(event);
1039 return NO_ERROR;
1040}
1041
Glenn Kasten5736c352012-12-04 12:12:34 -08001042void AudioFlinger::PlaybackThread::Track::invalidate()
1043{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001044 signalClientFlag(CBLK_INVALID);
1045 mIsInvalid = true;
1046}
1047
1048void AudioFlinger::PlaybackThread::Track::disable()
1049{
1050 signalClientFlag(CBLK_DISABLED);
1051}
1052
1053void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1054{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001055 // FIXME should use proxy, and needs work
1056 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001057 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001058 android_atomic_release_store(0x40000000, &cblk->mFutex);
1059 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001060 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001061}
1062
Eric Laurent59fe0102013-09-27 18:48:26 -07001063void AudioFlinger::PlaybackThread::Track::signal()
1064{
1065 sp<ThreadBase> thread = mThread.promote();
1066 if (thread != 0) {
1067 PlaybackThread *t = (PlaybackThread *)thread.get();
1068 Mutex::Autolock _l(t->mLock);
1069 t->broadcast_l();
1070 }
1071}
1072
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001073//To be called with thread lock held
1074bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1075
1076 if (mState == RESUMING)
1077 return true;
1078 /* Resume is pending if track was stopping before pause was called */
1079 if (mState == STOPPING_1 &&
1080 mResumeToStopping)
1081 return true;
1082
1083 return false;
1084}
1085
1086//To be called with thread lock held
1087void AudioFlinger::PlaybackThread::Track::resumeAck() {
1088
1089
1090 if (mState == RESUMING)
1091 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001092
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001093 // Other possibility of pending resume is stopping_1 state
1094 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001095 // drain being called.
1096 if (mState == STOPPING_1) {
1097 mResumeToStopping = false;
1098 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001099}
Andy Hunge10393e2015-06-12 13:59:33 -07001100
1101//To be called with thread lock held
1102void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001103 int64_t trackFramesReleased, int64_t sinkFramesWritten,
1104 const ExtendedTimestamp &timeStamp) {
1105 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001106 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001107
1108 // adjust server times and set drained state.
1109 //
1110 // Our timestamps are only updated when the track is on the Thread active list.
1111 // We need to ensure that tracks are not removed before full drain.
1112 ExtendedTimestamp local = timeStamp;
1113 bool checked = false;
1114 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1115 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1116 // Lookup the track frame corresponding to the sink frame position.
1117 if (local.mTimeNs[i] > 0) {
1118 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1119 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001120 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hung818e7a32016-02-16 18:08:07 -08001121 mAudioTrackServerProxy->setDrained(
1122 local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1123 checked = true;
1124 }
1125 }
Andy Hunge10393e2015-06-12 13:59:33 -07001126 }
Andy Hung818e7a32016-02-16 18:08:07 -08001127 if (!checked) { // no server info, assume drained.
1128 mAudioTrackServerProxy->setDrained(true);
1129 }
Andy Hungea2b9c02016-02-12 17:06:53 -08001130 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001131 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001132 mServerProxy->setTimestamp(local);
Andy Hunge10393e2015-06-12 13:59:33 -07001133}
1134
Eric Laurent81784c32012-11-19 14:55:58 -08001135// ----------------------------------------------------------------------------
1136
Eric Laurent81784c32012-11-19 14:55:58 -08001137AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1138 PlaybackThread *playbackThread,
1139 DuplicatingThread *sourceThread,
1140 uint32_t sampleRate,
1141 audio_format_t format,
1142 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001143 size_t frameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001144 uid_t uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001145 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1146 sampleRate, format, channelMask, frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001147 NULL, 0, AUDIO_SESSION_NONE, uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001148 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07001149 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08001150{
1151
1152 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001153 mOutBuffer.frameCount = 0;
1154 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001155 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001156 "frameCount %zu, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001157 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001158 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001159 // since client and server are in the same process,
1160 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001161 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1162 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001163 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001164 mClientProxy->setSendLevel(0.0);
1165 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001166 } else {
1167 ALOGW("Error creating output track on thread %p", playbackThread);
1168 }
1169}
1170
1171AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1172{
1173 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001174 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001175}
1176
1177status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001178 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001179{
1180 status_t status = Track::start(event, triggerSession);
1181 if (status != NO_ERROR) {
1182 return status;
1183 }
1184
1185 mActive = true;
1186 mRetryCount = 127;
1187 return status;
1188}
1189
1190void AudioFlinger::PlaybackThread::OutputTrack::stop()
1191{
1192 Track::stop();
1193 clearBufferQueue();
1194 mOutBuffer.frameCount = 0;
1195 mActive = false;
1196}
1197
Andy Hungc25b84a2015-01-14 19:04:10 -08001198bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001199{
1200 Buffer *pInBuffer;
1201 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001202 bool outputBufferFull = false;
1203 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001204 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001205
1206 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1207
1208 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001209 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001210 }
1211
1212 while (waitTimeLeftMs) {
1213 // First write pending buffers, then new data
1214 if (mBufferQueue.size()) {
1215 pInBuffer = mBufferQueue.itemAt(0);
1216 } else {
1217 pInBuffer = &inBuffer;
1218 }
1219
1220 if (pInBuffer->frameCount == 0) {
1221 break;
1222 }
1223
1224 if (mOutBuffer.frameCount == 0) {
1225 mOutBuffer.frameCount = pInBuffer->frameCount;
1226 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001227 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001228 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001229 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1230 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001231 outputBufferFull = true;
1232 break;
1233 }
1234 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1235 if (waitTimeLeftMs >= waitTimeMs) {
1236 waitTimeLeftMs -= waitTimeMs;
1237 } else {
1238 waitTimeLeftMs = 0;
1239 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001240 if (status == NOT_ENOUGH_DATA) {
1241 restartIfDisabled();
1242 continue;
1243 }
Eric Laurent81784c32012-11-19 14:55:58 -08001244 }
1245
1246 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1247 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001248 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 Proxy::Buffer buf;
1250 buf.mFrameCount = outFrames;
1251 buf.mRaw = NULL;
1252 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001253 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001254 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001255 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001256 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001257 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001258
1259 if (pInBuffer->frameCount == 0) {
1260 if (mBufferQueue.size()) {
1261 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001262 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001263 delete pInBuffer;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001264 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001265 mThread.unsafe_get(), mBufferQueue.size());
1266 } else {
1267 break;
1268 }
1269 }
1270 }
1271
1272 // If we could not write all frames, allocate a buffer and queue it for next time.
1273 if (inBuffer.frameCount) {
1274 sp<ThreadBase> thread = mThread.promote();
1275 if (thread != 0 && !thread->standby()) {
1276 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1277 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001278 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001279 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001280 pInBuffer->raw = pInBuffer->mBuffer;
1281 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001282 mBufferQueue.add(pInBuffer);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001283 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001284 mThread.unsafe_get(), mBufferQueue.size());
1285 } else {
1286 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1287 mThread.unsafe_get(), this);
1288 }
1289 }
1290 }
1291
Andy Hungc25b84a2015-01-14 19:04:10 -08001292 // Calling write() with a 0 length buffer means that no more data will be written:
1293 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1294 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1295 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001296 }
1297
1298 return outputBufferFull;
1299}
1300
1301status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1302 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1303{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001304 ClientProxy::Buffer buf;
1305 buf.mFrameCount = buffer->frameCount;
1306 struct timespec timeout;
1307 timeout.tv_sec = waitTimeMs / 1000;
1308 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1309 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1310 buffer->frameCount = buf.mFrameCount;
1311 buffer->raw = buf.mRaw;
1312 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001313}
1314
Eric Laurent81784c32012-11-19 14:55:58 -08001315void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1316{
1317 size_t size = mBufferQueue.size();
1318
1319 for (size_t i = 0; i < size; i++) {
1320 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001321 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001322 delete pBuffer;
1323 }
1324 mBufferQueue.clear();
1325}
1326
Eric Laurent4d231dc2016-03-11 18:38:23 -08001327void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1328{
1329 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1330 if (mActive && (flags & CBLK_DISABLED)) {
1331 start();
1332 }
1333}
Eric Laurent81784c32012-11-19 14:55:58 -08001334
Eric Laurent83b88082014-06-20 18:31:16 -07001335AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001336 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001337 uint32_t sampleRate,
1338 audio_channel_mask_t channelMask,
1339 audio_format_t format,
1340 size_t frameCount,
1341 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001342 audio_output_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001343 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001344 sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001345 buffer, 0, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001346 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1347{
1348 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1349 playbackThread->sampleRate();
1350 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1351 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1352
1353 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1354 this, sampleRate,
1355 (int)mPeerTimeout.tv_sec,
1356 (int)(mPeerTimeout.tv_nsec / 1000000));
1357}
1358
1359AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1360{
1361}
1362
Eric Laurent4d231dc2016-03-11 18:38:23 -08001363status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001364 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001365{
1366 status_t status = Track::start(event, triggerSession);
1367 if (status != NO_ERROR) {
1368 return status;
1369 }
1370 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1371 return status;
1372}
1373
Eric Laurent83b88082014-06-20 18:31:16 -07001374// AudioBufferProvider interface
1375status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001376 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001377{
1378 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1379 Proxy::Buffer buf;
1380 buf.mFrameCount = buffer->frameCount;
1381 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1382 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001383 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001384 if (buf.mFrameCount == 0) {
1385 return WOULD_BLOCK;
1386 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001387 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001388 return status;
1389}
1390
1391void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1392{
1393 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1394 Proxy::Buffer buf;
1395 buf.mFrameCount = buffer->frameCount;
1396 buf.mRaw = buffer->raw;
1397 mPeerProxy->releaseBuffer(&buf);
1398 TrackBase::releaseBuffer(buffer);
1399}
1400
1401status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1402 const struct timespec *timeOut)
1403{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001404 status_t status = NO_ERROR;
1405 static const int32_t kMaxTries = 5;
1406 int32_t tryCounter = kMaxTries;
1407 do {
1408 if (status == NOT_ENOUGH_DATA) {
1409 restartIfDisabled();
1410 }
1411 status = mProxy->obtainBuffer(buffer, timeOut);
1412 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1413 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001414}
1415
1416void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1417{
1418 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001419 restartIfDisabled();
1420 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1421}
1422
1423void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1424{
Eric Laurent83b88082014-06-20 18:31:16 -07001425 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1426 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1427 start();
1428 }
Eric Laurent83b88082014-06-20 18:31:16 -07001429}
1430
Eric Laurent81784c32012-11-19 14:55:58 -08001431// ----------------------------------------------------------------------------
1432// Record
1433// ----------------------------------------------------------------------------
1434
1435AudioFlinger::RecordHandle::RecordHandle(
1436 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1437 : BnAudioRecord(),
1438 mRecordTrack(recordTrack)
1439{
1440}
1441
1442AudioFlinger::RecordHandle::~RecordHandle() {
1443 stop_nonvirtual();
1444 mRecordTrack->destroy();
1445}
1446
Eric Laurent81784c32012-11-19 14:55:58 -08001447status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001448 audio_session_t triggerSession) {
Eric Laurent81784c32012-11-19 14:55:58 -08001449 ALOGV("RecordHandle::start()");
1450 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1451}
1452
1453void AudioFlinger::RecordHandle::stop() {
1454 stop_nonvirtual();
1455}
1456
1457void AudioFlinger::RecordHandle::stop_nonvirtual() {
1458 ALOGV("RecordHandle::stop()");
1459 mRecordTrack->stop();
1460}
1461
1462status_t AudioFlinger::RecordHandle::onTransact(
1463 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1464{
1465 return BnAudioRecord::onTransact(code, data, reply, flags);
1466}
1467
1468// ----------------------------------------------------------------------------
1469
Glenn Kasten05997e22014-03-13 15:08:33 -07001470// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001471AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1472 RecordThread *thread,
1473 const sp<Client>& client,
1474 uint32_t sampleRate,
1475 audio_format_t format,
1476 audio_channel_mask_t channelMask,
1477 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001478 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001479 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001480 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001481 audio_input_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001482 track_type type,
1483 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001484 : TrackBase(thread, client, sampleRate, format,
Eric Laurent05067782016-06-01 18:27:28 -07001485 channelMask, frameCount, buffer, sessionId, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001486 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001487 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001488 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
Eric Laurent20b9ef02016-12-05 11:03:16 -08001489 type, portId),
Andy Hung97a893e2015-03-29 01:03:07 -07001490 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001491 mFramesToDrop(0),
1492 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001493 mRecordBufferConverter(NULL),
1494 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001495{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001496 if (mCblk == NULL) {
1497 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001498 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001499
Andy Hung97a893e2015-03-29 01:03:07 -07001500 mRecordBufferConverter = new RecordBufferConverter(
1501 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1502 channelMask, format, sampleRate);
1503 // Check if the RecordBufferConverter construction was successful.
1504 // If not, don't continue with construction.
1505 //
1506 // NOTE: It would be extremely rare that the record track cannot be created
1507 // for the current device, but a pending or future device change would make
1508 // the record track configuration valid.
1509 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1510 ALOGE("RecordTrack unable to create record buffer converter");
1511 return;
1512 }
1513
Andy Hung6ae58432016-02-16 18:32:24 -08001514 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001515 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001516
Andy Hung97a893e2015-03-29 01:03:07 -07001517 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001518
Eric Laurent05067782016-06-01 18:27:28 -07001519 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001520 ALOG_ASSERT(thread->mFastTrackAvail);
1521 thread->mFastTrackAvail = false;
1522 }
Eric Laurent81784c32012-11-19 14:55:58 -08001523}
1524
1525AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1526{
1527 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001528 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001529 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001530}
1531
Andy Hung97a893e2015-03-29 01:03:07 -07001532status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1533{
1534 status_t status = TrackBase::initCheck();
1535 if (status == NO_ERROR && mServerProxy == 0) {
1536 status = BAD_VALUE;
1537 }
1538 return status;
1539}
1540
Eric Laurent81784c32012-11-19 14:55:58 -08001541// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001542status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001543{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001544 ServerProxy::Buffer buf;
1545 buf.mFrameCount = buffer->frameCount;
1546 status_t status = mServerProxy->obtainBuffer(&buf);
1547 buffer->frameCount = buf.mFrameCount;
1548 buffer->raw = buf.mRaw;
1549 if (buf.mFrameCount == 0) {
1550 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001551 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001552 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001553 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001554}
1555
1556status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001557 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001558{
1559 sp<ThreadBase> thread = mThread.promote();
1560 if (thread != 0) {
1561 RecordThread *recordThread = (RecordThread *)thread.get();
1562 return recordThread->start(this, event, triggerSession);
1563 } else {
1564 return BAD_VALUE;
1565 }
1566}
1567
1568void AudioFlinger::RecordThread::RecordTrack::stop()
1569{
1570 sp<ThreadBase> thread = mThread.promote();
1571 if (thread != 0) {
1572 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001573 if (recordThread->stop(this) && isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001574 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001575 }
1576 }
1577}
1578
1579void AudioFlinger::RecordThread::RecordTrack::destroy()
1580{
1581 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1582 sp<RecordTrack> keep(this);
1583 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001584 if (isExternalTrack()) {
1585 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001586 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001587 }
Glenn Kastend848eb42016-03-08 13:42:11 -08001588 AudioSystem::releaseInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001589 }
Eric Laurent81784c32012-11-19 14:55:58 -08001590 sp<ThreadBase> thread = mThread.promote();
1591 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001592 Mutex::Autolock _l(thread->mLock);
1593 RecordThread *recordThread = (RecordThread *) thread.get();
1594 recordThread->destroyTrack_l(this);
1595 }
1596 }
1597}
1598
Eric Laurent9a54bc22013-09-09 09:08:44 -07001599void AudioFlinger::RecordThread::RecordTrack::invalidate()
1600{
1601 // FIXME should use proxy, and needs work
1602 audio_track_cblk_t* cblk = mCblk;
1603 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1604 android_atomic_release_store(0x40000000, &cblk->mFutex);
1605 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001606 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001607}
1608
Eric Laurent81784c32012-11-19 14:55:58 -08001609
1610/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1611{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001612 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001613}
1614
Marco Nelissenb2208842014-02-07 14:00:50 -08001615void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001616{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001617 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001618 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001619 (mClient == 0) ? getpid_cached : mClient->pid(),
1620 mFormat,
1621 mChannelMask,
1622 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001623 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001624 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001625 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001626 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001627
Eric Laurent81784c32012-11-19 14:55:58 -08001628}
1629
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001630void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1631{
1632 if (event == mSyncStartEvent) {
1633 ssize_t framesToDrop = 0;
1634 sp<ThreadBase> threadBase = mThread.promote();
1635 if (threadBase != 0) {
1636 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1637 // from audio HAL
1638 framesToDrop = threadBase->mFrameCount * 2;
1639 }
1640 mFramesToDrop = framesToDrop;
1641 }
1642}
1643
1644void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1645{
1646 if (mSyncStartEvent != 0) {
1647 mSyncStartEvent->cancel();
1648 mSyncStartEvent.clear();
1649 }
1650 mFramesToDrop = 0;
1651}
1652
Andy Hung3f0c9022016-01-15 17:49:46 -08001653void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1654 int64_t trackFramesReleased, int64_t sourceFramesRead,
1655 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1656{
1657 ExtendedTimestamp local = timestamp;
1658
1659 // Convert HAL frames to server-side track frames at track sample rate.
1660 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1661 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1662 if (local.mTimeNs[i] != 0) {
1663 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1664 const int64_t relativeTrackFrames = relativeServerFrames
1665 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1666 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1667 }
1668 }
Andy Hung6ae58432016-02-16 18:32:24 -08001669 mServerProxy->setTimestamp(local);
Andy Hung3f0c9022016-01-15 17:49:46 -08001670}
Eric Laurent83b88082014-06-20 18:31:16 -07001671
1672AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1673 uint32_t sampleRate,
1674 audio_channel_mask_t channelMask,
1675 audio_format_t format,
1676 size_t frameCount,
1677 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001678 audio_input_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07001679 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001680 buffer, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001681 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1682{
1683 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1684 recordThread->sampleRate();
1685 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1686 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1687
1688 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1689 this, sampleRate,
1690 (int)mPeerTimeout.tv_sec,
1691 (int)(mPeerTimeout.tv_nsec / 1000000));
1692}
1693
1694AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1695{
1696}
1697
1698// AudioBufferProvider interface
1699status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001700 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001701{
1702 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1703 Proxy::Buffer buf;
1704 buf.mFrameCount = buffer->frameCount;
1705 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1706 ALOGV_IF(status != NO_ERROR,
1707 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001708 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001709 if (buf.mFrameCount == 0) {
1710 return WOULD_BLOCK;
1711 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001712 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001713 return status;
1714}
1715
1716void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1717{
1718 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1719 Proxy::Buffer buf;
1720 buf.mFrameCount = buffer->frameCount;
1721 buf.mRaw = buffer->raw;
1722 mPeerProxy->releaseBuffer(&buf);
1723 TrackBase::releaseBuffer(buffer);
1724}
1725
1726status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1727 const struct timespec *timeOut)
1728{
1729 return mProxy->obtainBuffer(buffer, timeOut);
1730}
1731
1732void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1733{
1734 mProxy->releaseBuffer(buffer);
1735}
1736
Glenn Kasten63238ef2015-03-02 15:50:29 -08001737} // namespace android