blob: eff101b1f90f09d787600e9d639140a35461538d [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenad8510a2015-02-17 16:24:07 -080023#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070025#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080026#include <utils/Log.h>
27
28#include <private/media/AudioTrackShared.h>
29
Eric Laurent81784c32012-11-19 14:55:58 -080030#include "AudioFlinger.h"
31#include "ServiceUtilities.h"
32
Glenn Kastenda6ef132013-01-10 12:31:01 -080033#include <media/nbaio/Pipe.h>
34#include <media/nbaio/PipeReader.h>
Andy Hung89816052017-01-11 17:08:23 -080035#include <media/RecordBufferConverter.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070036#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080037
Eric Laurent81784c32012-11-19 14:55:58 -080038// ----------------------------------------------------------------------------
39
40// Note: the following macro is used for extremely verbose logging message. In
41// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
42// 0; but one side effect of this is to turn all LOGV's as well. Some messages
43// are so verbose that we want to suppress them even when we have ALOG_ASSERT
44// turned on. Do not uncomment the #def below unless you really know what you
45// are doing and want to see all of the extremely verbose messages.
46//#define VERY_VERY_VERBOSE_LOGGING
47#ifdef VERY_VERY_VERBOSE_LOGGING
48#define ALOGVV ALOGV
49#else
50#define ALOGVV(a...) do { } while(0)
51#endif
52
Andy Hunge10393e2015-06-12 13:59:33 -070053// TODO move to a common header (Also shared with AudioTrack.cpp)
54#define NANOS_PER_SECOND 1000000000
Chih-Hung Hsieh9a3fbd92016-06-03 15:09:07 -070055#define TIME_TO_NANOS(time) ((uint64_t)(time).tv_sec * NANOS_PER_SECOND + (time).tv_nsec)
Andy Hunge10393e2015-06-12 13:59:33 -070056
Eric Laurent81784c32012-11-19 14:55:58 -080057namespace android {
58
59// ----------------------------------------------------------------------------
60// TrackBase
61// ----------------------------------------------------------------------------
62
Glenn Kastenda6ef132013-01-10 12:31:01 -080063static volatile int32_t nextTrackId = 55;
64
Eric Laurent81784c32012-11-19 14:55:58 -080065// TrackBase constructor must be called with AudioFlinger::mLock held
66AudioFlinger::ThreadBase::TrackBase::TrackBase(
67 ThreadBase *thread,
68 const sp<Client>& client,
69 uint32_t sampleRate,
70 audio_format_t format,
71 audio_channel_mask_t channelMask,
72 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070073 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -080074 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -080075 uid_t clientUid,
Glenn Kastend776ac62014-05-07 09:16:09 -070076 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070077 alloc_type alloc,
Eric Laurent20b9ef02016-12-05 11:03:16 -080078 track_type type,
79 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -080080 : RefBase(),
81 mThread(thread),
82 mClient(client),
83 mCblk(NULL),
84 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080085 mState(IDLE),
86 mSampleRate(sampleRate),
87 mFormat(format),
88 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070089 mChannelCount(isOut ?
90 audio_channel_count_from_out_mask(channelMask) :
91 audio_channel_count_from_in_mask(channelMask)),
Phil Burkfdb3c072016-02-09 10:47:02 -080092 mFrameSize(audio_has_proportional_frames(format) ?
Eric Laurent81784c32012-11-19 14:55:58 -080093 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
94 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080095 mSessionId(sessionId),
96 mIsOut(isOut),
Eric Laurentbfb1b832013-01-07 09:53:42 -080097 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070098 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -070099 mType(type),
Eric Laurent20b9ef02016-12-05 11:03:16 -0800100 mThreadIoHandle(thread->id()),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800101 mPortId(portId),
102 mIsInvalid(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800103{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700104 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung1f12a8a2016-11-07 16:10:30 -0800105 if (!isTrustedCallingUid(callingUid) || clientUid == AUDIO_UID_INVALID) {
106 ALOGW_IF(clientUid != AUDIO_UID_INVALID && clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -0700107 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
Andy Hung1f12a8a2016-11-07 16:10:30 -0800108 clientUid = callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800109 }
110 // clientUid contains the uid of the app that is responsible for this track, so we can blame
111 // battery usage on it.
112 mUid = clientUid;
113
Eric Laurent81784c32012-11-19 14:55:58 -0800114 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hung1883f692017-02-13 18:48:39 -0800115
116 size_t bufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
117 // check overflow when computing bufferSize due to multiplication by mFrameSize.
118 if (bufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
119 || mFrameSize == 0 // format needs to be correct
120 || bufferSize > SIZE_MAX / mFrameSize) {
121 android_errorWriteLog(0x534e4554, "34749571");
122 return;
123 }
124 bufferSize *= mFrameSize;
125
Eric Laurent81784c32012-11-19 14:55:58 -0800126 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700127 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hung1883f692017-02-13 18:48:39 -0800128 // check overflow when computing allocation size for streaming tracks.
129 if (size > SIZE_MAX - bufferSize) {
130 android_errorWriteLog(0x534e4554, "34749571");
131 return;
132 }
Eric Laurent81784c32012-11-19 14:55:58 -0800133 size += bufferSize;
134 }
135
136 if (client != 0) {
137 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700138 if (mCblkMemory == 0 ||
139 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700140 ALOGE("not enough memory for AudioTrack size=%zu", size);
Eric Laurent81784c32012-11-19 14:55:58 -0800141 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700142 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800143 return;
144 }
145 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800146 // this syntax avoids calling the audio_track_cblk_t constructor twice
147 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800148 // assume mCblk != NULL
149 }
150
151 // construct the shared structure in-place.
152 if (mCblk != NULL) {
153 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700154 switch (alloc) {
155 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700156 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
157 if (roHeap == 0 ||
158 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
159 (mBuffer = mBufferMemory->pointer()) == NULL) {
160 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
161 if (roHeap != 0) {
162 roHeap->dump("buffer");
163 }
164 mCblkMemory.clear();
165 mBufferMemory.clear();
166 return;
167 }
Eric Laurent81784c32012-11-19 14:55:58 -0800168 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700169 } break;
170 case ALLOC_PIPE:
171 mBufferMemory = thread->pipeMemory();
172 // mBuffer is the virtual address as seen from current process (mediaserver),
173 // and should normally be coming from mBufferMemory->pointer().
174 // However in this case the TrackBase does not reference the buffer directly.
175 // It should references the buffer via the pipe.
176 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
177 mBuffer = NULL;
178 break;
179 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700180 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700181 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700182 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
183 memset(mBuffer, 0, bufferSize);
184 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700185 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800186#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700187 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800188#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700189 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700190 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700191 case ALLOC_LOCAL:
192 mBuffer = calloc(1, bufferSize);
193 break;
194 case ALLOC_NONE:
195 mBuffer = buffer;
196 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800197 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800198
Glenn Kasten46909e72013-02-26 09:20:22 -0800199#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800200 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700201 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800202 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800203 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
204 size_t numCounterOffers = 0;
205 const NBAIO_Format offers[1] = {pipeFormat};
206 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
207 ALOG_ASSERT(index == 0);
208 PipeReader *pipeReader = new PipeReader(*pipe);
209 numCounterOffers = 0;
210 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
211 ALOG_ASSERT(index == 0);
212 mTeeSink = pipe;
213 mTeeSource = pipeReader;
214 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800215 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800216#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800217
Eric Laurent81784c32012-11-19 14:55:58 -0800218 }
219}
220
Eric Laurent83b88082014-06-20 18:31:16 -0700221status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
222{
223 status_t status;
224 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
225 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
226 } else {
227 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
228 }
229 return status;
230}
231
Eric Laurent81784c32012-11-19 14:55:58 -0800232AudioFlinger::ThreadBase::TrackBase::~TrackBase()
233{
Glenn Kasten46909e72013-02-26 09:20:22 -0800234#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800235 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800236#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800237 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
Eric Laurent5bba2f62016-03-18 11:14:14 -0700238 mServerProxy.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800239 if (mCblk != NULL) {
240 if (mClient == 0) {
241 delete mCblk;
242 } else {
243 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
244 }
245 }
246 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
247 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700248 // Client destructor must run with AudioFlinger client mutex locked
249 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800250 // If the client's reference count drops to zero, the associated destructor
251 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
252 // relying on the automatic clear() at end of scope.
253 mClient.clear();
254 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700255 // flush the binder command buffer
256 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800257}
258
259// AudioBufferProvider interface
260// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800261// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800262void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
263{
Glenn Kasten46909e72013-02-26 09:20:22 -0800264#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800265 if (mTeeSink != 0) {
266 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
267 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800268#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800269
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800270 ServerProxy::Buffer buf;
271 buf.mFrameCount = buffer->frameCount;
272 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800273 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800274 buffer->raw = NULL;
275 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800276}
277
Eric Laurent81784c32012-11-19 14:55:58 -0800278status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
279{
280 mSyncEvents.add(event);
281 return NO_ERROR;
282}
283
284// ----------------------------------------------------------------------------
285// Playback
286// ----------------------------------------------------------------------------
287
288AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
289 : BnAudioTrack(),
290 mTrack(track)
291{
292}
293
294AudioFlinger::TrackHandle::~TrackHandle() {
295 // just stop the track on deletion, associated resources
296 // will be freed from the main thread once all pending buffers have
297 // been played. Unless it's not in the active track list, in which
298 // case we free everything now...
299 mTrack->destroy();
300}
301
302sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
303 return mTrack->getCblk();
304}
305
306status_t AudioFlinger::TrackHandle::start() {
307 return mTrack->start();
308}
309
310void AudioFlinger::TrackHandle::stop() {
311 mTrack->stop();
312}
313
314void AudioFlinger::TrackHandle::flush() {
315 mTrack->flush();
316}
317
Eric Laurent81784c32012-11-19 14:55:58 -0800318void AudioFlinger::TrackHandle::pause() {
319 mTrack->pause();
320}
321
322status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
323{
324 return mTrack->attachAuxEffect(EffectId);
325}
326
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700327status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
328 return mTrack->setParameters(keyValuePairs);
329}
330
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800331VolumeShaper::Status AudioFlinger::TrackHandle::applyVolumeShaper(
332 const sp<VolumeShaper::Configuration>& configuration,
333 const sp<VolumeShaper::Operation>& operation) {
334 return mTrack->applyVolumeShaper(configuration, operation);
335}
336
337sp<VolumeShaper::State> AudioFlinger::TrackHandle::getVolumeShaperState(int id) {
338 return mTrack->getVolumeShaperState(id);
339}
340
Glenn Kasten53cec222013-08-29 09:01:02 -0700341status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
342{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700343 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700344}
345
Eric Laurent59fe0102013-09-27 18:48:26 -0700346
347void AudioFlinger::TrackHandle::signal()
348{
349 return mTrack->signal();
350}
351
Eric Laurent81784c32012-11-19 14:55:58 -0800352status_t AudioFlinger::TrackHandle::onTransact(
353 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
354{
355 return BnAudioTrack::onTransact(code, data, reply, flags);
356}
357
358// ----------------------------------------------------------------------------
359
360// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
361AudioFlinger::PlaybackThread::Track::Track(
362 PlaybackThread *thread,
363 const sp<Client>& client,
364 audio_stream_type_t streamType,
365 uint32_t sampleRate,
366 audio_format_t format,
367 audio_channel_mask_t channelMask,
368 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700369 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800370 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800371 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800372 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -0700373 audio_output_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800374 track_type type,
375 audio_port_handle_t portId)
Eric Laurent83b88082014-06-20 18:31:16 -0700376 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
377 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
Eric Laurent05067782016-06-01 18:27:28 -0700378 sessionId, uid, true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700379 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800380 type, portId),
Eric Laurent81784c32012-11-19 14:55:58 -0800381 mFillingUpStatus(FS_INVALID),
382 // mRetryCount initialized later when needed
383 mSharedBuffer(sharedBuffer),
384 mStreamType(streamType),
385 mName(-1), // see note below
386 mMainBuffer(thread->mixBuffer()),
387 mAuxBuffer(NULL),
388 mAuxEffectId(0), mHasVolumeController(false),
389 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700390 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800391 mVolumeHandler(new VolumeHandler(sampleRate)),
Andy Hunge10393e2015-06-12 13:59:33 -0700392 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800393 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800394 mCachedVolume(1.0),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800395 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700396 mFlushHwPending(false),
397 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -0800398{
Eric Laurent83b88082014-06-20 18:31:16 -0700399 // client == 0 implies sharedBuffer == 0
400 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
401
Eric Laurente93cc032016-05-05 10:15:10 -0700402 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
Eric Laurent83b88082014-06-20 18:31:16 -0700403 sharedBuffer->size());
404
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700405 if (mCblk == NULL) {
406 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800407 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700408
409 if (sharedBuffer == 0) {
410 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700411 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700412 } else {
413 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
414 mFrameSize);
415 }
416 mServerProxy = mAudioTrackServerProxy;
417
Eric Laurentad7dd962016-09-22 12:38:37 -0700418 mName = thread->getTrackName_l(channelMask, format, sessionId, uid);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700419 if (mName < 0) {
420 ALOGE("no more track names available");
421 return;
422 }
423 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700424 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700425 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
426 // race with setSyncEvent(). However, if we call it, we cannot properly start
427 // static fast tracks (SoundPool) immediately after stopping.
428 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700429 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
430 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700431 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700432 // FIXME This is too eager. We allocate a fast track index before the
433 // fast track becomes active. Since fast tracks are a scarce resource,
434 // this means we are potentially denying other more important fast tracks from
435 // being created. It would be better to allocate the index dynamically.
436 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700437 thread->mFastTrackAvailMask &= ~(1 << i);
438 }
Eric Laurent81784c32012-11-19 14:55:58 -0800439}
440
441AudioFlinger::PlaybackThread::Track::~Track()
442{
443 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700444
445 // The destructor would clear mSharedBuffer,
446 // but it will not push the decremented reference count,
447 // leaving the client's IMemory dangling indefinitely.
448 // This prevents that leak.
449 if (mSharedBuffer != 0) {
450 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700451 }
Eric Laurent81784c32012-11-19 14:55:58 -0800452}
453
Glenn Kasten03003332013-08-06 15:40:54 -0700454status_t AudioFlinger::PlaybackThread::Track::initCheck() const
455{
456 status_t status = TrackBase::initCheck();
457 if (status == NO_ERROR && mName < 0) {
458 status = NO_MEMORY;
459 }
460 return status;
461}
462
Eric Laurent81784c32012-11-19 14:55:58 -0800463void AudioFlinger::PlaybackThread::Track::destroy()
464{
465 // NOTE: destroyTrack_l() can remove a strong reference to this Track
466 // by removing it from mTracks vector, so there is a risk that this Tracks's
467 // destructor is called. As the destructor needs to lock mLock,
468 // we must acquire a strong reference on this Track before locking mLock
469 // here so that the destructor is called only when exiting this function.
470 // On the other hand, as long as Track::destroy() is only called by
471 // TrackHandle destructor, the TrackHandle still holds a strong ref on
472 // this Track with its member mTrack.
473 sp<Track> keep(this);
474 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700475 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800476 sp<ThreadBase> thread = mThread.promote();
477 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800478 Mutex::Autolock _l(thread->mLock);
479 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700480 wasActive = playbackThread->destroyTrack_l(this);
481 }
482 if (isExternalTrack() && !wasActive) {
Glenn Kastend848eb42016-03-08 13:42:11 -0800483 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800484 }
485 }
486}
487
488/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
489{
Marco Nelissenb2208842014-02-07 14:00:50 -0800490 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Andy Hung2148bf02016-11-28 19:01:02 -0800491 "L dB R dB Server Main buf Aux buf Flags UndFrmCnt Flushed\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800492}
493
Marco Nelissenb2208842014-02-07 14:00:50 -0800494void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800495{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700496 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800497 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800498 sprintf(buffer, " F %2d", mFastIndex);
499 } else if (mName >= AudioMixer::TRACK0) {
500 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800501 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800502 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800503 }
504 track_state state = mState;
505 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800506 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800507 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800508 } else {
509 switch (state) {
510 case IDLE:
511 stateChar = 'I';
512 break;
513 case STOPPING_1:
514 stateChar = 's';
515 break;
516 case STOPPING_2:
517 stateChar = '5';
518 break;
519 case STOPPED:
520 stateChar = 'S';
521 break;
522 case RESUMING:
523 stateChar = 'R';
524 break;
525 case ACTIVE:
526 stateChar = 'A';
527 break;
528 case PAUSING:
529 stateChar = 'p';
530 break;
531 case PAUSED:
532 stateChar = 'P';
533 break;
534 case FLUSHED:
535 stateChar = 'F';
536 break;
537 default:
538 stateChar = '?';
539 break;
540 }
Eric Laurent81784c32012-11-19 14:55:58 -0800541 }
542 char nowInUnderrun;
543 switch (mObservedUnderruns.mBitFields.mMostRecent) {
544 case UNDERRUN_FULL:
545 nowInUnderrun = ' ';
546 break;
547 case UNDERRUN_PARTIAL:
548 nowInUnderrun = '<';
549 break;
550 case UNDERRUN_EMPTY:
551 nowInUnderrun = '*';
552 break;
553 default:
554 nowInUnderrun = '?';
555 break;
556 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000557 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 -0800558 "%08X %08zX %08zX 0x%03X %9u%c %7u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800559 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800560 (mClient == 0) ? getpid_cached : mClient->pid(),
561 mStreamType,
562 mFormat,
563 mChannelMask,
564 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800565 mFrameCount,
566 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800567 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800568 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700569 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
570 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700571 mCblk->mServer,
Andy Hung2148bf02016-11-28 19:01:02 -0800572 (size_t)mMainBuffer, // use %zX as %p appends 0x
573 (size_t)mAuxBuffer, // use %zX as %p appends 0x
Glenn Kasten96f60d82013-07-12 10:21:18 -0700574 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700575 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -0800576 nowInUnderrun,
577 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000); // 7 digits
Eric Laurent81784c32012-11-19 14:55:58 -0800578}
579
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800580uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
581 return mAudioTrackServerProxy->getSampleRate();
582}
583
Eric Laurent81784c32012-11-19 14:55:58 -0800584// AudioBufferProvider interface
585status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800586 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800587{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800588 ServerProxy::Buffer buf;
589 size_t desiredFrames = buffer->frameCount;
590 buf.mFrameCount = desiredFrames;
591 status_t status = mServerProxy->obtainBuffer(&buf);
592 buffer->frameCount = buf.mFrameCount;
593 buffer->raw = buf.mRaw;
594 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700595 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800596 } else {
597 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800598 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800599
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800601}
602
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700603// releaseBuffer() is not overridden
604
605// ExtendedAudioBufferProvider interface
606
Andy Hung27876c02014-09-09 18:07:55 -0700607// framesReady() may return an approximation of the number of frames if called
608// from a different thread than the one calling Proxy->obtainBuffer() and
609// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
610// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800611size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700612 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
613 // Static tracks return zero frames immediately upon stopping (for FastTracks).
614 // The remainder of the buffer is not drained.
615 return 0;
616 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800618}
619
Andy Hung818e7a32016-02-16 18:08:07 -0800620int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700621{
622 return mAudioTrackServerProxy->framesReleased();
623}
624
Andy Hung818e7a32016-02-16 18:08:07 -0800625void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800626{
627 // This call comes from a FastTrack and should be kept lockless.
628 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800629 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800630
Andy Hung818e7a32016-02-16 18:08:07 -0800631 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hung6ae58432016-02-16 18:32:24 -0800632}
633
Eric Laurent81784c32012-11-19 14:55:58 -0800634// Don't call for fast tracks; the framesReady() could result in priority inversion
635bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800636 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
637 return true;
638 }
639
Eric Laurent16498512014-03-17 17:22:08 -0700640 if (isStopping()) {
641 if (framesReady() > 0) {
642 mFillingUpStatus = FS_FILLED;
643 }
Eric Laurent81784c32012-11-19 14:55:58 -0800644 return true;
645 }
646
Phil Burke8972b02016-03-04 11:29:57 -0800647 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700648 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800649 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700650 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800651 return true;
652 }
653 return false;
654}
655
Glenn Kasten0f11b512014-01-31 16:18:54 -0800656status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800657 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800658{
659 status_t status = NO_ERROR;
660 ALOGV("start(%d), calling pid %d session %d",
661 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
662
663 sp<ThreadBase> thread = mThread.promote();
664 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700665 if (isOffloaded()) {
666 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
667 Mutex::Autolock _lth(thread->mLock);
668 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700669 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
670 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700671 invalidate();
672 return PERMISSION_DENIED;
673 }
674 }
675 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800676 track_state state = mState;
677 // here the track could be either new, or restarted
678 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800679
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800680 // initial state-stopping. next state-pausing.
681 // What if resume is called ?
682
683 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800684 if (mResumeToStopping) {
685 // happened we need to resume to STOPPING_1
686 mState = TrackBase::STOPPING_1;
687 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
688 } else {
689 mState = TrackBase::RESUMING;
690 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
691 }
Eric Laurent81784c32012-11-19 14:55:58 -0800692 } else {
693 mState = TrackBase::ACTIVE;
694 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
695 }
696
Andy Hunge10393e2015-06-12 13:59:33 -0700697 // states to reset position info for non-offloaded/direct tracks
698 if (!isOffloaded() && !isDirect()
699 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
700 mFrameMap.reset();
701 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800702 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700703 if (isFastTrack()) {
704 // refresh fast track underruns on start because that field is never cleared
705 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
706 // after stop.
707 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
708 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800709 status = playbackThread->addTrack_l(this);
710 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800711 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800712 // restore previous state if start was rejected by policy manager
713 if (status == PERMISSION_DENIED) {
714 mState = state;
715 }
716 }
717 // track was already in the active list, not a problem
718 if (status == ALREADY_EXISTS) {
719 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700720 } else {
721 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
722 // It is usually unsafe to access the server proxy from a binder thread.
723 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
724 // isn't looking at this track yet: we still hold the normal mixer thread lock,
725 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700726 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700727 ServerProxy::Buffer buffer;
728 buffer.mFrameCount = 1;
729 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800730 }
731 } else {
732 status = BAD_VALUE;
733 }
734 return status;
735}
736
737void AudioFlinger::PlaybackThread::Track::stop()
738{
739 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
740 sp<ThreadBase> thread = mThread.promote();
741 if (thread != 0) {
742 Mutex::Autolock _l(thread->mLock);
743 track_state state = mState;
744 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
745 // If the track is not active (PAUSED and buffers full), flush buffers
746 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
747 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
748 reset();
749 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700750 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800751 mState = STOPPED;
752 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800753 // For fast tracks prepareTracks_l() will set state to STOPPING_2
754 // presentation is complete
755 // For an offloaded track this starts a drain and state will
756 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800757 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -0700758 if (isOffloaded()) {
759 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
760 }
Eric Laurent81784c32012-11-19 14:55:58 -0800761 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700762 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800763 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
764 playbackThread);
765 }
Eric Laurent81784c32012-11-19 14:55:58 -0800766 }
767}
768
769void AudioFlinger::PlaybackThread::Track::pause()
770{
771 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
772 sp<ThreadBase> thread = mThread.promote();
773 if (thread != 0) {
774 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800775 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
776 switch (mState) {
777 case STOPPING_1:
778 case STOPPING_2:
779 if (!isOffloaded()) {
780 /* nothing to do if track is not offloaded */
781 break;
782 }
783
784 // Offloaded track was draining, we need to carry on draining when resumed
785 mResumeToStopping = true;
786 // fall through...
787 case ACTIVE:
788 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800789 mState = PAUSING;
790 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700791 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800792 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800793
Eric Laurentbfb1b832013-01-07 09:53:42 -0800794 default:
795 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800796 }
797 }
798}
799
800void AudioFlinger::PlaybackThread::Track::flush()
801{
802 ALOGV("flush(%d)", mName);
803 sp<ThreadBase> thread = mThread.promote();
804 if (thread != 0) {
805 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800806 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800807
Phil Burk4bb650b2016-09-09 12:11:17 -0700808 // Flush the ring buffer now if the track is not active in the PlaybackThread.
809 // Otherwise the flush would not be done until the track is resumed.
810 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
811 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
812 (void)mServerProxy->flushBufferIfNeeded();
813 }
814
Eric Laurentbfb1b832013-01-07 09:53:42 -0800815 if (isOffloaded()) {
816 // If offloaded we allow flush during any state except terminated
817 // and keep the track active to avoid problems if user is seeking
818 // rapidly and underlying hardware has a significant delay handling
819 // a pause
820 if (isTerminated()) {
821 return;
822 }
823
824 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800825 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800826
827 if (mState == STOPPING_1 || mState == STOPPING_2) {
828 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
829 mState = ACTIVE;
830 }
831
Haynes Mathew George7844f672014-01-15 12:32:55 -0800832 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800833 mResumeToStopping = false;
834 } else {
835 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
836 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
837 return;
838 }
839 // No point remaining in PAUSED state after a flush => go to
840 // FLUSHED state
841 mState = FLUSHED;
842 // do not reset the track if it is still in the process of being stopped or paused.
843 // this will be done by prepareTracks_l() when the track is stopped.
844 // prepareTracks_l() will see mState == FLUSHED, then
845 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800846 if (isDirect()) {
847 mFlushHwPending = true;
848 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800849 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
850 reset();
851 }
Eric Laurent81784c32012-11-19 14:55:58 -0800852 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800853 // Prevent flush being lost if the track is flushed and then resumed
854 // before mixer thread can run. This is important when offloading
855 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700856 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800857 }
858}
859
Haynes Mathew George7844f672014-01-15 12:32:55 -0800860// must be called with thread lock held
861void AudioFlinger::PlaybackThread::Track::flushAck()
862{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800863 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800864 return;
865
Phil Burk4bb650b2016-09-09 12:11:17 -0700866 // Clear the client ring buffer so that the app can prime the buffer while paused.
867 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
868 mServerProxy->flushBufferIfNeeded();
869
Haynes Mathew George7844f672014-01-15 12:32:55 -0800870 mFlushHwPending = false;
871}
872
Eric Laurent81784c32012-11-19 14:55:58 -0800873void AudioFlinger::PlaybackThread::Track::reset()
874{
875 // Do not reset twice to avoid discarding data written just after a flush and before
876 // the audioflinger thread detects the track is stopped.
877 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800878 // Force underrun condition to avoid false underrun callback until first data is
879 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700880 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800881 mFillingUpStatus = FS_FILLING;
882 mResetDone = true;
883 if (mState == FLUSHED) {
884 mState = IDLE;
885 }
886 }
887}
888
Eric Laurentbfb1b832013-01-07 09:53:42 -0800889status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
890{
891 sp<ThreadBase> thread = mThread.promote();
892 if (thread == 0) {
893 ALOGE("thread is dead");
894 return FAILED_TRANSACTION;
895 } else if ((thread->type() == ThreadBase::DIRECT) ||
896 (thread->type() == ThreadBase::OFFLOAD)) {
897 return thread->setParameters(keyValuePairs);
898 } else {
899 return PERMISSION_DENIED;
900 }
901}
902
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800903VolumeShaper::Status AudioFlinger::PlaybackThread::Track::applyVolumeShaper(
904 const sp<VolumeShaper::Configuration>& configuration,
905 const sp<VolumeShaper::Operation>& operation)
906{
907 // Note: We don't check if Thread exists.
908
909 // mVolumeHandler is thread-safe.
910 return mVolumeHandler->applyVolumeShaper(configuration, operation);
911}
912
913sp<VolumeShaper::State> AudioFlinger::PlaybackThread::Track::getVolumeShaperState(int id)
914{
915 // Note: We don't check if Thread exists.
916
917 // mVolumeHandler is thread safe.
918 return mVolumeHandler->getVolumeShaperState(id);
919}
920
Glenn Kasten573d80a2013-08-26 09:36:23 -0700921status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
922{
Andy Hung818e7a32016-02-16 18:08:07 -0800923 if (!isOffloaded() && !isDirect()) {
924 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700925 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700926 sp<ThreadBase> thread = mThread.promote();
927 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700928 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700929 }
Phil Burk6140c792015-03-19 14:30:21 -0700930
Glenn Kasten573d80a2013-08-26 09:36:23 -0700931 Mutex::Autolock _l(thread->mLock);
932 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -0800933 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700934}
935
Eric Laurent81784c32012-11-19 14:55:58 -0800936status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
937{
938 status_t status = DEAD_OBJECT;
939 sp<ThreadBase> thread = mThread.promote();
940 if (thread != 0) {
941 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
942 sp<AudioFlinger> af = mClient->audioFlinger();
943
944 Mutex::Autolock _l(af->mLock);
945
946 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
947
948 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
949 Mutex::Autolock _dl(playbackThread->mLock);
950 Mutex::Autolock _sl(srcThread->mLock);
951 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
952 if (chain == 0) {
953 return INVALID_OPERATION;
954 }
955
956 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
957 if (effect == 0) {
958 return INVALID_OPERATION;
959 }
960 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700961 status = playbackThread->addEffect_l(effect);
962 if (status != NO_ERROR) {
963 srcThread->addEffect_l(effect);
964 return INVALID_OPERATION;
965 }
Eric Laurent81784c32012-11-19 14:55:58 -0800966 // removeEffect_l() has stopped the effect if it was active so it must be restarted
967 if (effect->state() == EffectModule::ACTIVE ||
968 effect->state() == EffectModule::STOPPING) {
969 effect->start();
970 }
971
972 sp<EffectChain> dstChain = effect->chain().promote();
973 if (dstChain == 0) {
974 srcThread->addEffect_l(effect);
975 return INVALID_OPERATION;
976 }
977 AudioSystem::unregisterEffect(effect->id());
978 AudioSystem::registerEffect(&effect->desc(),
979 srcThread->id(),
980 dstChain->strategy(),
981 AUDIO_SESSION_OUTPUT_MIX,
982 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700983 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800984 }
985 status = playbackThread->attachAuxEffect(this, EffectId);
986 }
987 return status;
988}
989
990void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
991{
992 mAuxEffectId = EffectId;
993 mAuxBuffer = buffer;
994}
995
Andy Hung818e7a32016-02-16 18:08:07 -0800996bool AudioFlinger::PlaybackThread::Track::presentationComplete(
997 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -0800998{
Andy Hung818e7a32016-02-16 18:08:07 -0800999 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
1000 // This assists in proper timestamp computation as well as wakelock management.
1001
Eric Laurent81784c32012-11-19 14:55:58 -08001002 // a track is considered presented when the total number of frames written to audio HAL
1003 // corresponds to the number of frames written when presentationComplete() is called for the
1004 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001005 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1006 // to detect when all frames have been played. In this case framesWritten isn't
1007 // useful because it doesn't always reflect whether there is data in the h/w
1008 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung818e7a32016-02-16 18:08:07 -08001009 ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
1010 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001011 if (mPresentationCompleteFrames == 0) {
1012 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung818e7a32016-02-16 18:08:07 -08001013 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
1014 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08001015 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001016
Andy Hungc54b1ff2016-02-23 14:07:07 -08001017 bool complete;
1018 if (isOffloaded()) {
1019 complete = true;
1020 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001021 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -08001022 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001023 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -08001024 && mAudioTrackServerProxy->isDrained();
1025 }
1026
1027 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -08001028 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001029 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001030 return true;
1031 }
1032 return false;
1033}
1034
1035void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1036{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001037 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001038 if (mSyncEvents[i]->type() == type) {
1039 mSyncEvents[i]->trigger();
1040 mSyncEvents.removeAt(i);
1041 i--;
1042 }
1043 }
1044}
1045
1046// implement VolumeBufferProvider interface
1047
Glenn Kastenc56f3422014-03-21 17:53:17 -07001048gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001049{
1050 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1051 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001052 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1053 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1054 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001055 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001056 if (vl > GAIN_FLOAT_UNITY) {
1057 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001058 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001059 if (vr > GAIN_FLOAT_UNITY) {
1060 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001061 }
1062 // now apply the cached master volume and stream type volume;
1063 // this is trusted but lacks any synchronization or barrier so may be stale
1064 float v = mCachedVolume;
1065 vl *= v;
1066 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001067 // re-combine into packed minifloat
1068 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001069 // FIXME look at mute, pause, and stop flags
1070 return vlr;
1071}
1072
1073status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1074{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001075 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001076 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1077 (mState == STOPPED)))) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001078 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001079 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1080 event->cancel();
1081 return INVALID_OPERATION;
1082 }
1083 (void) TrackBase::setSyncEvent(event);
1084 return NO_ERROR;
1085}
1086
Glenn Kasten5736c352012-12-04 12:12:34 -08001087void AudioFlinger::PlaybackThread::Track::invalidate()
1088{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001089 TrackBase::invalidate();
Eric Laurent4d231dc2016-03-11 18:38:23 -08001090 signalClientFlag(CBLK_INVALID);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001091}
1092
1093void AudioFlinger::PlaybackThread::Track::disable()
1094{
1095 signalClientFlag(CBLK_DISABLED);
1096}
1097
1098void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1099{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001100 // FIXME should use proxy, and needs work
1101 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001102 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001103 android_atomic_release_store(0x40000000, &cblk->mFutex);
1104 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001105 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001106}
1107
Eric Laurent59fe0102013-09-27 18:48:26 -07001108void AudioFlinger::PlaybackThread::Track::signal()
1109{
1110 sp<ThreadBase> thread = mThread.promote();
1111 if (thread != 0) {
1112 PlaybackThread *t = (PlaybackThread *)thread.get();
1113 Mutex::Autolock _l(t->mLock);
1114 t->broadcast_l();
1115 }
1116}
1117
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001118//To be called with thread lock held
1119bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1120
1121 if (mState == RESUMING)
1122 return true;
1123 /* Resume is pending if track was stopping before pause was called */
1124 if (mState == STOPPING_1 &&
1125 mResumeToStopping)
1126 return true;
1127
1128 return false;
1129}
1130
1131//To be called with thread lock held
1132void AudioFlinger::PlaybackThread::Track::resumeAck() {
1133
1134
1135 if (mState == RESUMING)
1136 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001137
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001138 // Other possibility of pending resume is stopping_1 state
1139 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001140 // drain being called.
1141 if (mState == STOPPING_1) {
1142 mResumeToStopping = false;
1143 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001144}
Andy Hunge10393e2015-06-12 13:59:33 -07001145
1146//To be called with thread lock held
1147void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001148 int64_t trackFramesReleased, int64_t sinkFramesWritten,
1149 const ExtendedTimestamp &timeStamp) {
1150 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001151 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001152
1153 // adjust server times and set drained state.
1154 //
1155 // Our timestamps are only updated when the track is on the Thread active list.
1156 // We need to ensure that tracks are not removed before full drain.
1157 ExtendedTimestamp local = timeStamp;
1158 bool checked = false;
1159 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1160 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1161 // Lookup the track frame corresponding to the sink frame position.
1162 if (local.mTimeNs[i] > 0) {
1163 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1164 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001165 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hung818e7a32016-02-16 18:08:07 -08001166 mAudioTrackServerProxy->setDrained(
1167 local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1168 checked = true;
1169 }
1170 }
Andy Hunge10393e2015-06-12 13:59:33 -07001171 }
Andy Hung818e7a32016-02-16 18:08:07 -08001172 if (!checked) { // no server info, assume drained.
1173 mAudioTrackServerProxy->setDrained(true);
1174 }
Andy Hungea2b9c02016-02-12 17:06:53 -08001175 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001176 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001177 mServerProxy->setTimestamp(local);
Andy Hunge10393e2015-06-12 13:59:33 -07001178}
1179
Eric Laurent81784c32012-11-19 14:55:58 -08001180// ----------------------------------------------------------------------------
1181
Eric Laurent81784c32012-11-19 14:55:58 -08001182AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1183 PlaybackThread *playbackThread,
1184 DuplicatingThread *sourceThread,
1185 uint32_t sampleRate,
1186 audio_format_t format,
1187 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001188 size_t frameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001189 uid_t uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001190 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1191 sampleRate, format, channelMask, frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001192 NULL, 0, AUDIO_SESSION_NONE, uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001193 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07001194 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08001195{
1196
1197 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001198 mOutBuffer.frameCount = 0;
1199 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001200 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001201 "frameCount %zu, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001202 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001203 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001204 // since client and server are in the same process,
1205 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001206 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1207 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001208 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001209 mClientProxy->setSendLevel(0.0);
1210 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001211 } else {
1212 ALOGW("Error creating output track on thread %p", playbackThread);
1213 }
1214}
1215
1216AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1217{
1218 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001219 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001220}
1221
1222status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001223 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001224{
1225 status_t status = Track::start(event, triggerSession);
1226 if (status != NO_ERROR) {
1227 return status;
1228 }
1229
1230 mActive = true;
1231 mRetryCount = 127;
1232 return status;
1233}
1234
1235void AudioFlinger::PlaybackThread::OutputTrack::stop()
1236{
1237 Track::stop();
1238 clearBufferQueue();
1239 mOutBuffer.frameCount = 0;
1240 mActive = false;
1241}
1242
Andy Hungc25b84a2015-01-14 19:04:10 -08001243bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001244{
1245 Buffer *pInBuffer;
1246 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001247 bool outputBufferFull = false;
1248 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001249 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001250
1251 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1252
1253 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001254 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001255 }
1256
1257 while (waitTimeLeftMs) {
1258 // First write pending buffers, then new data
1259 if (mBufferQueue.size()) {
1260 pInBuffer = mBufferQueue.itemAt(0);
1261 } else {
1262 pInBuffer = &inBuffer;
1263 }
1264
1265 if (pInBuffer->frameCount == 0) {
1266 break;
1267 }
1268
1269 if (mOutBuffer.frameCount == 0) {
1270 mOutBuffer.frameCount = pInBuffer->frameCount;
1271 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001272 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001273 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001274 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1275 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001276 outputBufferFull = true;
1277 break;
1278 }
1279 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1280 if (waitTimeLeftMs >= waitTimeMs) {
1281 waitTimeLeftMs -= waitTimeMs;
1282 } else {
1283 waitTimeLeftMs = 0;
1284 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001285 if (status == NOT_ENOUGH_DATA) {
1286 restartIfDisabled();
1287 continue;
1288 }
Eric Laurent81784c32012-11-19 14:55:58 -08001289 }
1290
1291 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1292 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001293 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001294 Proxy::Buffer buf;
1295 buf.mFrameCount = outFrames;
1296 buf.mRaw = NULL;
1297 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001298 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001299 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001300 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001301 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001302 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001303
1304 if (pInBuffer->frameCount == 0) {
1305 if (mBufferQueue.size()) {
1306 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001307 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001308 delete pInBuffer;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001309 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001310 mThread.unsafe_get(), mBufferQueue.size());
1311 } else {
1312 break;
1313 }
1314 }
1315 }
1316
1317 // If we could not write all frames, allocate a buffer and queue it for next time.
1318 if (inBuffer.frameCount) {
1319 sp<ThreadBase> thread = mThread.promote();
1320 if (thread != 0 && !thread->standby()) {
1321 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1322 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001323 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001325 pInBuffer->raw = pInBuffer->mBuffer;
1326 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001327 mBufferQueue.add(pInBuffer);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001328 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
Eric Laurent81784c32012-11-19 14:55:58 -08001329 mThread.unsafe_get(), mBufferQueue.size());
1330 } else {
1331 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1332 mThread.unsafe_get(), this);
1333 }
1334 }
1335 }
1336
Andy Hungc25b84a2015-01-14 19:04:10 -08001337 // Calling write() with a 0 length buffer means that no more data will be written:
1338 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1339 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1340 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001341 }
1342
1343 return outputBufferFull;
1344}
1345
1346status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1347 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1348{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001349 ClientProxy::Buffer buf;
1350 buf.mFrameCount = buffer->frameCount;
1351 struct timespec timeout;
1352 timeout.tv_sec = waitTimeMs / 1000;
1353 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1354 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1355 buffer->frameCount = buf.mFrameCount;
1356 buffer->raw = buf.mRaw;
1357 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001358}
1359
Eric Laurent81784c32012-11-19 14:55:58 -08001360void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1361{
1362 size_t size = mBufferQueue.size();
1363
1364 for (size_t i = 0; i < size; i++) {
1365 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001366 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001367 delete pBuffer;
1368 }
1369 mBufferQueue.clear();
1370}
1371
Eric Laurent4d231dc2016-03-11 18:38:23 -08001372void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1373{
1374 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1375 if (mActive && (flags & CBLK_DISABLED)) {
1376 start();
1377 }
1378}
Eric Laurent81784c32012-11-19 14:55:58 -08001379
Eric Laurent83b88082014-06-20 18:31:16 -07001380AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001381 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001382 uint32_t sampleRate,
1383 audio_channel_mask_t channelMask,
1384 audio_format_t format,
1385 size_t frameCount,
1386 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001387 audio_output_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001388 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001389 sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001390 buffer, 0, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001391 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1392{
1393 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1394 playbackThread->sampleRate();
1395 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1396 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1397
1398 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1399 this, sampleRate,
1400 (int)mPeerTimeout.tv_sec,
1401 (int)(mPeerTimeout.tv_nsec / 1000000));
1402}
1403
1404AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1405{
1406}
1407
Eric Laurent4d231dc2016-03-11 18:38:23 -08001408status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001409 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001410{
1411 status_t status = Track::start(event, triggerSession);
1412 if (status != NO_ERROR) {
1413 return status;
1414 }
1415 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1416 return status;
1417}
1418
Eric Laurent83b88082014-06-20 18:31:16 -07001419// AudioBufferProvider interface
1420status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001421 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001422{
1423 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1424 Proxy::Buffer buf;
1425 buf.mFrameCount = buffer->frameCount;
1426 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1427 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001428 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001429 if (buf.mFrameCount == 0) {
1430 return WOULD_BLOCK;
1431 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001432 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001433 return status;
1434}
1435
1436void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1437{
1438 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1439 Proxy::Buffer buf;
1440 buf.mFrameCount = buffer->frameCount;
1441 buf.mRaw = buffer->raw;
1442 mPeerProxy->releaseBuffer(&buf);
1443 TrackBase::releaseBuffer(buffer);
1444}
1445
1446status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1447 const struct timespec *timeOut)
1448{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001449 status_t status = NO_ERROR;
1450 static const int32_t kMaxTries = 5;
1451 int32_t tryCounter = kMaxTries;
1452 do {
1453 if (status == NOT_ENOUGH_DATA) {
1454 restartIfDisabled();
1455 }
1456 status = mProxy->obtainBuffer(buffer, timeOut);
1457 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1458 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001459}
1460
1461void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1462{
1463 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001464 restartIfDisabled();
1465 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1466}
1467
1468void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1469{
Eric Laurent83b88082014-06-20 18:31:16 -07001470 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1471 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1472 start();
1473 }
Eric Laurent83b88082014-06-20 18:31:16 -07001474}
1475
Eric Laurent81784c32012-11-19 14:55:58 -08001476// ----------------------------------------------------------------------------
1477// Record
1478// ----------------------------------------------------------------------------
1479
1480AudioFlinger::RecordHandle::RecordHandle(
1481 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1482 : BnAudioRecord(),
1483 mRecordTrack(recordTrack)
1484{
1485}
1486
1487AudioFlinger::RecordHandle::~RecordHandle() {
1488 stop_nonvirtual();
1489 mRecordTrack->destroy();
1490}
1491
Eric Laurent81784c32012-11-19 14:55:58 -08001492status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001493 audio_session_t triggerSession) {
Eric Laurent81784c32012-11-19 14:55:58 -08001494 ALOGV("RecordHandle::start()");
1495 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1496}
1497
1498void AudioFlinger::RecordHandle::stop() {
1499 stop_nonvirtual();
1500}
1501
1502void AudioFlinger::RecordHandle::stop_nonvirtual() {
1503 ALOGV("RecordHandle::stop()");
1504 mRecordTrack->stop();
1505}
1506
1507status_t AudioFlinger::RecordHandle::onTransact(
1508 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1509{
1510 return BnAudioRecord::onTransact(code, data, reply, flags);
1511}
1512
1513// ----------------------------------------------------------------------------
1514
Glenn Kasten05997e22014-03-13 15:08:33 -07001515// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001516AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1517 RecordThread *thread,
1518 const sp<Client>& client,
1519 uint32_t sampleRate,
1520 audio_format_t format,
1521 audio_channel_mask_t channelMask,
1522 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001523 void *buffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001524 audio_session_t sessionId,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001525 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001526 audio_input_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001527 track_type type,
1528 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001529 : TrackBase(thread, client, sampleRate, format,
Eric Laurent05067782016-06-01 18:27:28 -07001530 channelMask, frameCount, buffer, sessionId, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001531 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001532 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001533 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
Eric Laurent20b9ef02016-12-05 11:03:16 -08001534 type, portId),
Andy Hung97a893e2015-03-29 01:03:07 -07001535 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001536 mFramesToDrop(0),
1537 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001538 mRecordBufferConverter(NULL),
1539 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001540{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001541 if (mCblk == NULL) {
1542 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001543 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001544
Andy Hung97a893e2015-03-29 01:03:07 -07001545 mRecordBufferConverter = new RecordBufferConverter(
1546 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1547 channelMask, format, sampleRate);
1548 // Check if the RecordBufferConverter construction was successful.
1549 // If not, don't continue with construction.
1550 //
1551 // NOTE: It would be extremely rare that the record track cannot be created
1552 // for the current device, but a pending or future device change would make
1553 // the record track configuration valid.
1554 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1555 ALOGE("RecordTrack unable to create record buffer converter");
1556 return;
1557 }
1558
Andy Hung6ae58432016-02-16 18:32:24 -08001559 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001560 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001561
Andy Hung97a893e2015-03-29 01:03:07 -07001562 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001563
Eric Laurent05067782016-06-01 18:27:28 -07001564 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001565 ALOG_ASSERT(thread->mFastTrackAvail);
1566 thread->mFastTrackAvail = false;
1567 }
Eric Laurent81784c32012-11-19 14:55:58 -08001568}
1569
1570AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1571{
1572 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001573 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001574 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001575}
1576
Andy Hung97a893e2015-03-29 01:03:07 -07001577status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1578{
1579 status_t status = TrackBase::initCheck();
1580 if (status == NO_ERROR && mServerProxy == 0) {
1581 status = BAD_VALUE;
1582 }
1583 return status;
1584}
1585
Eric Laurent81784c32012-11-19 14:55:58 -08001586// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001587status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001588{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001589 ServerProxy::Buffer buf;
1590 buf.mFrameCount = buffer->frameCount;
1591 status_t status = mServerProxy->obtainBuffer(&buf);
1592 buffer->frameCount = buf.mFrameCount;
1593 buffer->raw = buf.mRaw;
1594 if (buf.mFrameCount == 0) {
1595 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001596 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001597 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001598 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001599}
1600
1601status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001602 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001603{
1604 sp<ThreadBase> thread = mThread.promote();
1605 if (thread != 0) {
1606 RecordThread *recordThread = (RecordThread *)thread.get();
1607 return recordThread->start(this, event, triggerSession);
1608 } else {
1609 return BAD_VALUE;
1610 }
1611}
1612
1613void AudioFlinger::RecordThread::RecordTrack::stop()
1614{
1615 sp<ThreadBase> thread = mThread.promote();
1616 if (thread != 0) {
1617 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001618 if (recordThread->stop(this) && isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001619 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001620 }
1621 }
1622}
1623
1624void AudioFlinger::RecordThread::RecordTrack::destroy()
1625{
1626 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1627 sp<RecordTrack> keep(this);
1628 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001629 if (isExternalTrack()) {
1630 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001631 AudioSystem::stopInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001632 }
Glenn Kastend848eb42016-03-08 13:42:11 -08001633 AudioSystem::releaseInput(mThreadIoHandle, mSessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07001634 }
Eric Laurent81784c32012-11-19 14:55:58 -08001635 sp<ThreadBase> thread = mThread.promote();
1636 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001637 Mutex::Autolock _l(thread->mLock);
1638 RecordThread *recordThread = (RecordThread *) thread.get();
1639 recordThread->destroyTrack_l(this);
1640 }
1641 }
1642}
1643
Eric Laurent9a54bc22013-09-09 09:08:44 -07001644void AudioFlinger::RecordThread::RecordTrack::invalidate()
1645{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001646 TrackBase::invalidate();
Eric Laurent9a54bc22013-09-09 09:08:44 -07001647 // FIXME should use proxy, and needs work
1648 audio_track_cblk_t* cblk = mCblk;
1649 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1650 android_atomic_release_store(0x40000000, &cblk->mFutex);
1651 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001652 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001653}
1654
Eric Laurent81784c32012-11-19 14:55:58 -08001655
1656/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1657{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001658 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001659}
1660
Marco Nelissenb2208842014-02-07 14:00:50 -08001661void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001662{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001663 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001664 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001665 (mClient == 0) ? getpid_cached : mClient->pid(),
1666 mFormat,
1667 mChannelMask,
1668 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001669 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001670 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001671 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001672 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001673
Eric Laurent81784c32012-11-19 14:55:58 -08001674}
1675
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001676void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1677{
1678 if (event == mSyncStartEvent) {
1679 ssize_t framesToDrop = 0;
1680 sp<ThreadBase> threadBase = mThread.promote();
1681 if (threadBase != 0) {
1682 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1683 // from audio HAL
1684 framesToDrop = threadBase->mFrameCount * 2;
1685 }
1686 mFramesToDrop = framesToDrop;
1687 }
1688}
1689
1690void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1691{
1692 if (mSyncStartEvent != 0) {
1693 mSyncStartEvent->cancel();
1694 mSyncStartEvent.clear();
1695 }
1696 mFramesToDrop = 0;
1697}
1698
Andy Hung3f0c9022016-01-15 17:49:46 -08001699void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1700 int64_t trackFramesReleased, int64_t sourceFramesRead,
1701 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1702{
1703 ExtendedTimestamp local = timestamp;
1704
1705 // Convert HAL frames to server-side track frames at track sample rate.
1706 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1707 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1708 if (local.mTimeNs[i] != 0) {
1709 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1710 const int64_t relativeTrackFrames = relativeServerFrames
1711 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1712 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1713 }
1714 }
Andy Hung6ae58432016-02-16 18:32:24 -08001715 mServerProxy->setTimestamp(local);
Andy Hung3f0c9022016-01-15 17:49:46 -08001716}
Eric Laurent83b88082014-06-20 18:31:16 -07001717
1718AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1719 uint32_t sampleRate,
1720 audio_channel_mask_t channelMask,
1721 audio_format_t format,
1722 size_t frameCount,
1723 void *buffer,
Eric Laurent05067782016-06-01 18:27:28 -07001724 audio_input_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07001725 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001726 buffer, AUDIO_SESSION_NONE, getuid(), flags, TYPE_PATCH),
Eric Laurent83b88082014-06-20 18:31:16 -07001727 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1728{
1729 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1730 recordThread->sampleRate();
1731 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1732 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1733
1734 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1735 this, sampleRate,
1736 (int)mPeerTimeout.tv_sec,
1737 (int)(mPeerTimeout.tv_nsec / 1000000));
1738}
1739
1740AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1741{
1742}
1743
1744// AudioBufferProvider interface
1745status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001746 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001747{
1748 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1749 Proxy::Buffer buf;
1750 buf.mFrameCount = buffer->frameCount;
1751 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1752 ALOGV_IF(status != NO_ERROR,
1753 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001754 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001755 if (buf.mFrameCount == 0) {
1756 return WOULD_BLOCK;
1757 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001758 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001759 return status;
1760}
1761
1762void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1763{
1764 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1765 Proxy::Buffer buf;
1766 buf.mFrameCount = buffer->frameCount;
1767 buf.mRaw = buffer->raw;
1768 mPeerProxy->releaseBuffer(&buf);
1769 TrackBase::releaseBuffer(buffer);
1770}
1771
1772status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1773 const struct timespec *timeOut)
1774{
1775 return mProxy->obtainBuffer(buffer, timeOut);
1776}
1777
1778void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1779{
1780 mProxy->releaseBuffer(buffer);
1781}
1782
Eric Laurent6acd1d42017-01-04 14:23:29 -08001783
1784
1785AudioFlinger::MmapThread::MmapTrack::MmapTrack(ThreadBase *thread,
1786 uint32_t sampleRate,
1787 audio_format_t format,
1788 audio_channel_mask_t channelMask,
1789 audio_session_t sessionId,
1790 uid_t uid,
1791 audio_port_handle_t portId)
1792 : TrackBase(thread, NULL, sampleRate, format,
1793 channelMask, 0, NULL, sessionId, uid, false,
1794 ALLOC_NONE,
1795 TYPE_DEFAULT, portId)
1796{
1797}
1798
1799AudioFlinger::MmapThread::MmapTrack::~MmapTrack()
1800{
1801}
1802
1803status_t AudioFlinger::MmapThread::MmapTrack::initCheck() const
1804{
1805 return NO_ERROR;
1806}
1807
1808status_t AudioFlinger::MmapThread::MmapTrack::start(AudioSystem::sync_event_t event __unused,
1809 audio_session_t triggerSession __unused)
1810{
1811 return NO_ERROR;
1812}
1813
1814void AudioFlinger::MmapThread::MmapTrack::stop()
1815{
1816}
1817
1818// AudioBufferProvider interface
1819status_t AudioFlinger::MmapThread::MmapTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
1820{
1821 buffer->frameCount = 0;
1822 buffer->raw = nullptr;
1823 return INVALID_OPERATION;
1824}
1825
1826// ExtendedAudioBufferProvider interface
1827size_t AudioFlinger::MmapThread::MmapTrack::framesReady() const {
1828 return 0;
1829}
1830
1831int64_t AudioFlinger::MmapThread::MmapTrack::framesReleased() const
1832{
1833 return 0;
1834}
1835
1836void AudioFlinger::MmapThread::MmapTrack::onTimestamp(const ExtendedTimestamp &timestamp __unused)
1837{
1838}
1839
1840/*static*/ void AudioFlinger::MmapThread::MmapTrack::appendDumpHeader(String8& result)
1841{
1842 result.append(" Client Fmt Chn mask SRate\n");
1843}
1844
1845void AudioFlinger::MmapThread::MmapTrack::dump(char* buffer, size_t size)
1846{
1847 snprintf(buffer, size, " %6u %3u %08X %5u\n",
1848 mUid,
1849 mFormat,
1850 mChannelMask,
1851 mSampleRate);
1852
1853}
1854
Glenn Kasten63238ef2015-03-02 15:50:29 -08001855} // namespace android