blob: e1f00c190d8d3d6a81a13eedf4d84a4f55cda335 [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"
Eric Laurent81784c32012-11-19 14:55:58 -080031
Glenn Kastenda6ef132013-01-10 12:31:01 -080032#include <media/nbaio/Pipe.h>
33#include <media/nbaio/PipeReader.h>
Andy Hung89816052017-01-11 17:08:23 -080034#include <media/RecordBufferConverter.h>
Andy Hungab7ef302018-05-15 19:35:29 -070035#include <mediautils/ServiceUtilities.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
53namespace android {
54
Ivan Lozano8cf3a072017-08-09 09:01:33 -070055using media::VolumeShaper;
Eric Laurent81784c32012-11-19 14:55:58 -080056// ----------------------------------------------------------------------------
57// TrackBase
58// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -070059#undef LOG_TAG
60#define LOG_TAG "AF::TrackBase"
Eric Laurent81784c32012-11-19 14:55:58 -080061
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,
Kevin Rocard1f564ac2018-03-29 13:53:10 -070068 const audio_attributes_t& attr,
Eric Laurent81784c32012-11-19 14:55:58 -080069 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,
Andy Hung8fe68032017-06-05 16:17:51 -070074 size_t bufferSize,
Glenn Kastend848eb42016-03-08 13:42:11 -080075 audio_session_t sessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -070076 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -080077 uid_t clientUid,
Glenn Kastend776ac62014-05-07 09:16:09 -070078 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070079 alloc_type alloc,
Eric Laurent20b9ef02016-12-05 11:03:16 -080080 track_type type,
81 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -080082 : RefBase(),
83 mThread(thread),
84 mClient(client),
85 mCblk(NULL),
Andy Hung8fe68032017-06-05 16:17:51 -070086 // mBuffer, mBufferSize
Eric Laurent81784c32012-11-19 14:55:58 -080087 mState(IDLE),
Kevin Rocard1f564ac2018-03-29 13:53:10 -070088 mAttr(attr),
Eric Laurent81784c32012-11-19 14:55:58 -080089 mSampleRate(sampleRate),
90 mFormat(format),
91 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070092 mChannelCount(isOut ?
93 audio_channel_count_from_out_mask(channelMask) :
94 audio_channel_count_from_in_mask(channelMask)),
Phil Burkfdb3c072016-02-09 10:47:02 -080095 mFrameSize(audio_has_proportional_frames(format) ?
Eric Laurent81784c32012-11-19 14:55:58 -080096 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
97 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080098 mSessionId(sessionId),
99 mIsOut(isOut),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800100 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -0700101 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -0700102 mType(type),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800103 mThreadIoHandle(thread ? thread->id() : AUDIO_IO_HANDLE_NONE),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800104 mPortId(portId),
Eric Laurent09f1ed22019-04-24 17:45:17 -0700105 mIsInvalid(false),
106 mCreatorPid(creatorPid)
Eric Laurent81784c32012-11-19 14:55:58 -0800107{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700108 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -0700109 if (!isAudioServerOrMediaServerUid(callingUid) || clientUid == AUDIO_UID_INVALID) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800110 ALOGW_IF(clientUid != AUDIO_UID_INVALID && clientUid != callingUid,
Andy Hung9d84af52018-09-12 18:03:44 -0700111 "%s(%d): uid %d tried to pass itself off as %d",
112 __func__, mId, callingUid, clientUid);
Andy Hung1f12a8a2016-11-07 16:10:30 -0800113 clientUid = callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800114 }
115 // clientUid contains the uid of the app that is responsible for this track, so we can blame
116 // battery usage on it.
117 mUid = clientUid;
118
Eric Laurent81784c32012-11-19 14:55:58 -0800119 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hung1883f692017-02-13 18:48:39 -0800120
Andy Hung8fe68032017-06-05 16:17:51 -0700121 size_t minBufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
Andy Hung1883f692017-02-13 18:48:39 -0800122 // check overflow when computing bufferSize due to multiplication by mFrameSize.
Andy Hung8fe68032017-06-05 16:17:51 -0700123 if (minBufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
Andy Hung1883f692017-02-13 18:48:39 -0800124 || mFrameSize == 0 // format needs to be correct
Andy Hung8fe68032017-06-05 16:17:51 -0700125 || minBufferSize > SIZE_MAX / mFrameSize) {
Andy Hung1883f692017-02-13 18:48:39 -0800126 android_errorWriteLog(0x534e4554, "34749571");
127 return;
128 }
Andy Hung8fe68032017-06-05 16:17:51 -0700129 minBufferSize *= mFrameSize;
130
131 if (buffer == nullptr) {
132 bufferSize = minBufferSize; // allocated here.
133 } else if (minBufferSize > bufferSize) {
134 android_errorWriteLog(0x534e4554, "38340117");
135 return;
136 }
Andy Hung1883f692017-02-13 18:48:39 -0800137
Eric Laurent81784c32012-11-19 14:55:58 -0800138 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700139 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hung1883f692017-02-13 18:48:39 -0800140 // check overflow when computing allocation size for streaming tracks.
141 if (size > SIZE_MAX - bufferSize) {
142 android_errorWriteLog(0x534e4554, "34749571");
143 return;
144 }
Eric Laurent81784c32012-11-19 14:55:58 -0800145 size += bufferSize;
146 }
147
148 if (client != 0) {
149 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700150 if (mCblkMemory == 0 ||
151 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Andy Hung9d84af52018-09-12 18:03:44 -0700152 ALOGE("%s(%d): not enough memory for AudioTrack size=%zu", __func__, mId, size);
Eric Laurent81784c32012-11-19 14:55:58 -0800153 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700154 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800155 return;
156 }
157 } else {
Andy Hungafb31482017-02-13 18:50:48 -0800158 mCblk = (audio_track_cblk_t *) malloc(size);
159 if (mCblk == NULL) {
Andy Hung9d84af52018-09-12 18:03:44 -0700160 ALOGE("%s(%d): not enough memory for AudioTrack size=%zu", __func__, mId, size);
Andy Hungafb31482017-02-13 18:50:48 -0800161 return;
162 }
Eric Laurent81784c32012-11-19 14:55:58 -0800163 }
164
165 // construct the shared structure in-place.
166 if (mCblk != NULL) {
167 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700168 switch (alloc) {
169 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700170 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
171 if (roHeap == 0 ||
172 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
173 (mBuffer = mBufferMemory->pointer()) == NULL) {
Andy Hung9d84af52018-09-12 18:03:44 -0700174 ALOGE("%s(%d): not enough memory for read-only buffer size=%zu",
175 __func__, mId, bufferSize);
Glenn Kastend776ac62014-05-07 09:16:09 -0700176 if (roHeap != 0) {
177 roHeap->dump("buffer");
178 }
179 mCblkMemory.clear();
180 mBufferMemory.clear();
181 return;
182 }
Eric Laurent81784c32012-11-19 14:55:58 -0800183 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700184 } break;
185 case ALLOC_PIPE:
186 mBufferMemory = thread->pipeMemory();
187 // mBuffer is the virtual address as seen from current process (mediaserver),
188 // and should normally be coming from mBufferMemory->pointer().
189 // However in this case the TrackBase does not reference the buffer directly.
190 // It should references the buffer via the pipe.
191 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
192 mBuffer = NULL;
Andy Hung8fe68032017-06-05 16:17:51 -0700193 bufferSize = 0;
Glenn Kastenc263ca02014-06-04 20:31:46 -0700194 break;
195 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700196 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700197 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700198 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
199 memset(mBuffer, 0, bufferSize);
200 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700201 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800202#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700203 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800204#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700205 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700206 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700207 case ALLOC_LOCAL:
208 mBuffer = calloc(1, bufferSize);
209 break;
210 case ALLOC_NONE:
211 mBuffer = buffer;
212 break;
Andy Hung8fe68032017-06-05 16:17:51 -0700213 default:
Andy Hung9d84af52018-09-12 18:03:44 -0700214 LOG_ALWAYS_FATAL("%s(%d): invalid allocation type: %d", __func__, mId, (int)alloc);
Eric Laurent81784c32012-11-19 14:55:58 -0800215 }
Andy Hung8fe68032017-06-05 16:17:51 -0700216 mBufferSize = bufferSize;
Glenn Kastenda6ef132013-01-10 12:31:01 -0800217
Glenn Kasten46909e72013-02-26 09:20:22 -0800218#ifdef TEE_SINK
Andy Hung8946a282018-04-19 20:04:56 -0700219 mTee.set(sampleRate, mChannelCount, format, NBAIO_Tee::TEE_FLAG_TRACK);
Glenn Kasten46909e72013-02-26 09:20:22 -0800220#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800221
Eric Laurent81784c32012-11-19 14:55:58 -0800222 }
223}
224
Eric Laurent83b88082014-06-20 18:31:16 -0700225status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
226{
227 status_t status;
228 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
229 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
230 } else {
231 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
232 }
233 return status;
234}
235
Eric Laurent81784c32012-11-19 14:55:58 -0800236AudioFlinger::ThreadBase::TrackBase::~TrackBase()
237{
Glenn Kastene3aa6592012-12-04 12:22:46 -0800238 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
Eric Laurent5bba2f62016-03-18 11:14:14 -0700239 mServerProxy.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800240 if (mCblk != NULL) {
Andy Hungafb31482017-02-13 18:50:48 -0800241 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurent81784c32012-11-19 14:55:58 -0800242 if (mClient == 0) {
Andy Hungafb31482017-02-13 18:50:48 -0800243 free(mCblk);
Eric Laurent81784c32012-11-19 14:55:58 -0800244 }
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
Andy Hung8946a282018-04-19 20:04:56 -0700265 mTee.write(buffer->raw, buffer->frameCount);
Glenn Kasten46909e72013-02-26 09:20:22 -0800266#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800267
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800268 ServerProxy::Buffer buf;
269 buf.mFrameCount = buffer->frameCount;
270 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800271 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800272 buffer->raw = NULL;
273 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800274}
275
Eric Laurent81784c32012-11-19 14:55:58 -0800276status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
277{
278 mSyncEvents.add(event);
279 return NO_ERROR;
280}
281
Kevin Rocard45986c72018-12-18 18:22:59 -0800282AudioFlinger::ThreadBase::PatchTrackBase::PatchTrackBase(sp<ClientProxy> proxy,
283 const ThreadBase& thread,
284 const Timeout& timeout)
285 : mProxy(proxy)
286{
287 if (timeout) {
288 setPeerTimeout(*timeout);
289 } else {
290 // Double buffer mixer
291 uint64_t mixBufferNs = ((uint64_t)2 * thread.frameCount() * 1000000000) /
292 thread.sampleRate();
293 setPeerTimeout(std::chrono::nanoseconds{mixBufferNs});
294 }
295}
296
297void AudioFlinger::ThreadBase::PatchTrackBase::setPeerTimeout(std::chrono::nanoseconds timeout) {
298 mPeerTimeout.tv_sec = timeout.count() / std::nano::den;
299 mPeerTimeout.tv_nsec = timeout.count() % std::nano::den;
300}
301
302
Eric Laurent81784c32012-11-19 14:55:58 -0800303// ----------------------------------------------------------------------------
304// Playback
305// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -0700306#undef LOG_TAG
307#define LOG_TAG "AF::TrackHandle"
Eric Laurent81784c32012-11-19 14:55:58 -0800308
309AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
310 : BnAudioTrack(),
311 mTrack(track)
312{
313}
314
315AudioFlinger::TrackHandle::~TrackHandle() {
316 // just stop the track on deletion, associated resources
317 // will be freed from the main thread once all pending buffers have
318 // been played. Unless it's not in the active track list, in which
319 // case we free everything now...
320 mTrack->destroy();
321}
322
323sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
324 return mTrack->getCblk();
325}
326
327status_t AudioFlinger::TrackHandle::start() {
328 return mTrack->start();
329}
330
331void AudioFlinger::TrackHandle::stop() {
332 mTrack->stop();
333}
334
335void AudioFlinger::TrackHandle::flush() {
336 mTrack->flush();
337}
338
Eric Laurent81784c32012-11-19 14:55:58 -0800339void AudioFlinger::TrackHandle::pause() {
340 mTrack->pause();
341}
342
343status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
344{
345 return mTrack->attachAuxEffect(EffectId);
346}
347
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700348status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
349 return mTrack->setParameters(keyValuePairs);
350}
351
Mikhail Naganovac917ac2018-11-28 14:03:52 -0800352status_t AudioFlinger::TrackHandle::selectPresentation(int presentationId, int programId) {
353 return mTrack->selectPresentation(presentationId, programId);
354}
355
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800356VolumeShaper::Status AudioFlinger::TrackHandle::applyVolumeShaper(
357 const sp<VolumeShaper::Configuration>& configuration,
358 const sp<VolumeShaper::Operation>& operation) {
359 return mTrack->applyVolumeShaper(configuration, operation);
360}
361
362sp<VolumeShaper::State> AudioFlinger::TrackHandle::getVolumeShaperState(int id) {
363 return mTrack->getVolumeShaperState(id);
364}
365
Glenn Kasten53cec222013-08-29 09:01:02 -0700366status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
367{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700368 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700369}
370
Eric Laurent59fe0102013-09-27 18:48:26 -0700371
372void AudioFlinger::TrackHandle::signal()
373{
374 return mTrack->signal();
375}
376
Eric Laurent81784c32012-11-19 14:55:58 -0800377status_t AudioFlinger::TrackHandle::onTransact(
378 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
379{
380 return BnAudioTrack::onTransact(code, data, reply, flags);
381}
382
383// ----------------------------------------------------------------------------
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800384// AppOp for audio playback
385// -------------------------------
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700386
387// static
388sp<AudioFlinger::PlaybackThread::OpPlayAudioMonitor>
389AudioFlinger::PlaybackThread::OpPlayAudioMonitor::createIfNeeded(
390 uid_t uid, audio_usage_t usage, int id, audio_stream_type_t streamType)
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800391{
392 if (isAudioServerOrRootUid(uid)) {
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700393 ALOGD("OpPlayAudio: not muting track:%d usage:%d root or audioserver", id, usage);
394 return nullptr;
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800395 }
396 // stream type has been filtered by audio policy to indicate whether it can be muted
397 if (streamType == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700398 ALOGD("OpPlayAudio: not muting track:%d usage:%d ENFORCED_AUDIBLE", id, usage);
399 return nullptr;
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800400 }
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700401 return new OpPlayAudioMonitor(uid, usage, id);
402}
403
404AudioFlinger::PlaybackThread::OpPlayAudioMonitor::OpPlayAudioMonitor(
405 uid_t uid, audio_usage_t usage, int id)
406 : mHasOpPlayAudio(true), mUid(uid), mUsage((int32_t) usage), mId(id)
407{
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800408}
409
410AudioFlinger::PlaybackThread::OpPlayAudioMonitor::~OpPlayAudioMonitor()
411{
412 if (mOpCallback != 0) {
413 mAppOpsManager.stopWatchingMode(mOpCallback);
414 }
415 mOpCallback.clear();
416}
417
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700418void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::onFirstRef()
419{
420 PermissionController permissionController;
421 permissionController.getPackagesForUid(mUid, mPackages);
422 checkPlayAudioForUsage();
423 if (!mPackages.isEmpty()) {
424 mOpCallback = new PlayAudioOpCallback(this);
425 mAppOpsManager.startWatchingMode(AppOpsManager::OP_PLAY_AUDIO, mPackages[0], mOpCallback);
426 }
427}
428
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800429bool AudioFlinger::PlaybackThread::OpPlayAudioMonitor::hasOpPlayAudio() const {
430 return mHasOpPlayAudio.load();
431}
432
433// Note this method is never called (and never to be) for audio server / root track
434// - not called from constructor due to check on UID,
435// - not called from PlayAudioOpCallback because the callback is not installed in this case
436void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::checkPlayAudioForUsage()
437{
438 if (mPackages.isEmpty()) {
439 mHasOpPlayAudio.store(false);
440 } else {
441 bool hasIt = true;
442 for (const String16& packageName : mPackages) {
443 const int32_t mode = mAppOpsManager.checkAudioOpNoThrow(AppOpsManager::OP_PLAY_AUDIO,
444 mUsage, mUid, packageName);
445 if (mode != AppOpsManager::MODE_ALLOWED) {
446 hasIt = false;
447 break;
448 }
449 }
450 ALOGD("OpPlayAudio: track:%d usage:%d %smuted", mId, mUsage, hasIt ? "not " : "");
451 mHasOpPlayAudio.store(hasIt);
452 }
453}
454
455AudioFlinger::PlaybackThread::OpPlayAudioMonitor::PlayAudioOpCallback::PlayAudioOpCallback(
456 const wp<OpPlayAudioMonitor>& monitor) : mMonitor(monitor)
457{ }
458
459void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::PlayAudioOpCallback::opChanged(int32_t op,
460 const String16& packageName) {
461 // we only have uid, so we need to check all package names anyway
462 UNUSED(packageName);
463 if (op != AppOpsManager::OP_PLAY_AUDIO) {
464 return;
465 }
466 sp<OpPlayAudioMonitor> monitor = mMonitor.promote();
467 if (monitor != NULL) {
468 monitor->checkPlayAudioForUsage();
469 }
470}
471
472// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -0700473#undef LOG_TAG
474#define LOG_TAG "AF::Track"
Eric Laurent81784c32012-11-19 14:55:58 -0800475
476// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
477AudioFlinger::PlaybackThread::Track::Track(
478 PlaybackThread *thread,
479 const sp<Client>& client,
480 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700481 const audio_attributes_t& attr,
Eric Laurent81784c32012-11-19 14:55:58 -0800482 uint32_t sampleRate,
483 audio_format_t format,
484 audio_channel_mask_t channelMask,
485 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700486 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -0700487 size_t bufferSize,
Eric Laurent81784c32012-11-19 14:55:58 -0800488 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800489 audio_session_t sessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700490 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800491 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -0700492 audio_output_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800493 track_type type,
494 audio_port_handle_t portId)
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700495 : TrackBase(thread, client, attr, sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700496 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
Andy Hung8fe68032017-06-05 16:17:51 -0700497 (sharedBuffer != 0) ? sharedBuffer->size() : bufferSize,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700498 sessionId, creatorPid, uid, true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700499 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800500 type, portId),
Eric Laurent81784c32012-11-19 14:55:58 -0800501 mFillingUpStatus(FS_INVALID),
502 // mRetryCount initialized later when needed
503 mSharedBuffer(sharedBuffer),
504 mStreamType(streamType),
rago94a1ee82017-07-21 15:11:02 -0700505 mMainBuffer(thread->sinkBuffer()),
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mAuxBuffer(NULL),
507 mAuxEffectId(0), mHasVolumeController(false),
508 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700509 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Ivan Lozano8cf3a072017-08-09 09:01:33 -0700510 mVolumeHandler(new media::VolumeHandler(sampleRate)),
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700511 mOpPlayAudioMonitor(OpPlayAudioMonitor::createIfNeeded(uid, attr.usage, id(), streamType)),
Andy Hunge10393e2015-06-12 13:59:33 -0700512 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800513 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800514 mCachedVolume(1.0),
Kevin Rocard12381092018-04-11 09:19:59 -0700515 /* The track might not play immediately after being active, similarly as if its volume was 0.
516 * When the track starts playing, its volume will be computed. */
517 mFinalVolume(0.f),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800518 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700519 mFlushHwPending(false),
520 mFlags(flags)
Eric Laurent81784c32012-11-19 14:55:58 -0800521{
Eric Laurent83b88082014-06-20 18:31:16 -0700522 // client == 0 implies sharedBuffer == 0
523 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
524
Andy Hung9d84af52018-09-12 18:03:44 -0700525 ALOGV_IF(sharedBuffer != 0, "%s(%d): sharedBuffer: %p, size: %zu",
526 __func__, mId, sharedBuffer->pointer(), sharedBuffer->size());
Eric Laurent83b88082014-06-20 18:31:16 -0700527
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700528 if (mCblk == NULL) {
529 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800530 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700531
532 if (sharedBuffer == 0) {
533 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700534 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700535 } else {
536 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
537 mFrameSize);
538 }
539 mServerProxy = mAudioTrackServerProxy;
540
Andy Hung1bc088a2018-02-09 15:57:31 -0800541 if (!thread->isTrackAllowed_l(channelMask, format, sessionId, uid)) {
Andy Hung9d84af52018-09-12 18:03:44 -0700542 ALOGE("%s(%d): no more tracks available", __func__, mId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700543 return;
544 }
545 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700546 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700547 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
548 // race with setSyncEvent(). However, if we call it, we cannot properly start
549 // static fast tracks (SoundPool) immediately after stopping.
550 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700551 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
552 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700553 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700554 // FIXME This is too eager. We allocate a fast track index before the
555 // fast track becomes active. Since fast tracks are a scarce resource,
556 // this means we are potentially denying other more important fast tracks from
557 // being created. It would be better to allocate the index dynamically.
558 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700559 thread->mFastTrackAvailMask &= ~(1 << i);
560 }
Andy Hung8946a282018-04-19 20:04:56 -0700561
Andy Hung1c86ebe2018-05-29 20:29:08 -0700562 mServerLatencySupported = thread->type() == ThreadBase::MIXER
563 || thread->type() == ThreadBase::DUPLICATING;
Andy Hung8946a282018-04-19 20:04:56 -0700564#ifdef TEE_SINK
565 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle)
Kevin Rocard51f0e982019-02-01 19:19:11 -0800566 + "_" + std::to_string(mId) + "_T");
Andy Hung8946a282018-04-19 20:04:56 -0700567#endif
jiabin57303cc2018-12-18 15:45:57 -0800568
569 if (channelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
570 mAudioVibrationController = new AudioVibrationController(this);
571 mExternalVibration = new os::ExternalVibration(
572 mUid, "" /* pkg */, mAttr, mAudioVibrationController);
573 }
Eric Laurent81784c32012-11-19 14:55:58 -0800574}
575
576AudioFlinger::PlaybackThread::Track::~Track()
577{
Andy Hung9d84af52018-09-12 18:03:44 -0700578 ALOGV("%s(%d)", __func__, mId);
Glenn Kasten0c72b242013-09-11 09:14:16 -0700579
580 // The destructor would clear mSharedBuffer,
581 // but it will not push the decremented reference count,
582 // leaving the client's IMemory dangling indefinitely.
583 // This prevents that leak.
584 if (mSharedBuffer != 0) {
585 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700586 }
Eric Laurent81784c32012-11-19 14:55:58 -0800587}
588
Glenn Kasten03003332013-08-06 15:40:54 -0700589status_t AudioFlinger::PlaybackThread::Track::initCheck() const
590{
591 status_t status = TrackBase::initCheck();
Andy Hungc0691382018-09-12 18:01:57 -0700592 if (status == NO_ERROR && mCblk == nullptr) {
Glenn Kasten03003332013-08-06 15:40:54 -0700593 status = NO_MEMORY;
594 }
595 return status;
596}
597
Eric Laurent81784c32012-11-19 14:55:58 -0800598void AudioFlinger::PlaybackThread::Track::destroy()
599{
600 // NOTE: destroyTrack_l() can remove a strong reference to this Track
601 // by removing it from mTracks vector, so there is a risk that this Tracks's
602 // destructor is called. As the destructor needs to lock mLock,
603 // we must acquire a strong reference on this Track before locking mLock
604 // here so that the destructor is called only when exiting this function.
605 // On the other hand, as long as Track::destroy() is only called by
606 // TrackHandle destructor, the TrackHandle still holds a strong ref on
607 // this Track with its member mTrack.
608 sp<Track> keep(this);
609 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700610 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800611 sp<ThreadBase> thread = mThread.promote();
612 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800613 Mutex::Autolock _l(thread->mLock);
614 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700615 wasActive = playbackThread->destroyTrack_l(this);
616 }
617 if (isExternalTrack() && !wasActive) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700618 AudioSystem::releaseOutput(mPortId);
Eric Laurent81784c32012-11-19 14:55:58 -0800619 }
620 }
Kevin Rocardc43ea142019-01-31 18:17:37 -0800621 forEachTeePatchTrack([](auto patchTrack) { patchTrack->destroy(); });
Eric Laurent81784c32012-11-19 14:55:58 -0800622}
623
Andy Hungf6ab58d2018-05-25 12:50:39 -0700624void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
Eric Laurent81784c32012-11-19 14:55:58 -0800625{
Eric Laurent973db022018-11-20 14:54:31 -0800626 result.appendFormat("Type Id Active Client Session Port Id S Flags "
Kevin Rocard5f2136e2018-05-11 22:03:00 -0700627 " Format Chn mask SRate "
628 "ST Usg CT "
629 " G db L dB R dB VS dB "
630 " Server FrmCnt FrmRdy F Underruns Flushed"
631 "%s\n",
632 isServerLatencySupported() ? " Latency" : "");
Eric Laurent81784c32012-11-19 14:55:58 -0800633}
634
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700635void AudioFlinger::PlaybackThread::Track::appendDump(String8& result, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800636{
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700637 char trackType;
638 switch (mType) {
639 case TYPE_DEFAULT:
640 case TYPE_OUTPUT:
Andy Hungf6ab58d2018-05-25 12:50:39 -0700641 if (isStatic()) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700642 trackType = 'S'; // static
643 } else {
644 trackType = ' '; // normal
Eric Laurentbfb1b832013-01-07 09:53:42 -0800645 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700646 break;
647 case TYPE_PATCH:
648 trackType = 'P';
649 break;
650 default:
651 trackType = '?';
Eric Laurent81784c32012-11-19 14:55:58 -0800652 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700653
654 if (isFastTrack()) {
Andy Hungc0691382018-09-12 18:01:57 -0700655 result.appendFormat("F%d %c %6d", mFastIndex, trackType, mId);
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700656 } else {
Andy Hungc0691382018-09-12 18:01:57 -0700657 result.appendFormat(" %c %6d", trackType, mId);
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700658 }
659
Eric Laurent81784c32012-11-19 14:55:58 -0800660 char nowInUnderrun;
661 switch (mObservedUnderruns.mBitFields.mMostRecent) {
662 case UNDERRUN_FULL:
663 nowInUnderrun = ' ';
664 break;
665 case UNDERRUN_PARTIAL:
666 nowInUnderrun = '<';
667 break;
668 case UNDERRUN_EMPTY:
669 nowInUnderrun = '*';
670 break;
671 default:
672 nowInUnderrun = '?';
673 break;
674 }
Andy Hungda540db2017-04-20 14:06:17 -0700675
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700676 char fillingStatus;
677 switch (mFillingUpStatus) {
678 case FS_INVALID:
679 fillingStatus = 'I';
680 break;
681 case FS_FILLING:
682 fillingStatus = 'f';
683 break;
684 case FS_FILLED:
685 fillingStatus = 'F';
686 break;
687 case FS_ACTIVE:
688 fillingStatus = 'A';
689 break;
690 default:
691 fillingStatus = '?';
692 break;
693 }
694
695 // clip framesReadySafe to max representation in dump
696 const size_t framesReadySafe =
697 std::min(mAudioTrackServerProxy->framesReadySafe(), (size_t)99999999);
698
699 // obtain volumes
700 const gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
701 const std::pair<float /* volume */, bool /* active */> vsVolume =
702 mVolumeHandler->getLastVolume();
703
704 // Our effective frame count is obtained by ServerProxy::getBufferSizeInFrames()
705 // as it may be reduced by the application.
706 const size_t bufferSizeInFrames = (size_t)mAudioTrackServerProxy->getBufferSizeInFrames();
707 // Check whether the buffer size has been modified by the app.
708 const char modifiedBufferChar = bufferSizeInFrames < mFrameCount
709 ? 'r' /* buffer reduced */: bufferSizeInFrames > mFrameCount
710 ? 'e' /* error */ : ' ' /* identical */;
711
Eric Laurent973db022018-11-20 14:54:31 -0800712 result.appendFormat("%7s %6u %7u %7u %2s 0x%03X "
Kevin Rocard5f2136e2018-05-11 22:03:00 -0700713 "%08X %08X %6u "
714 "%2u %3x %2x "
715 "%5.2g %5.2g %5.2g %5.2g%c "
716 "%08X %6zu%c %6zu %c %9u%c %7u",
Marco Nelissenb2208842014-02-07 14:00:50 -0800717 active ? "yes" : "no",
Andy Hung4ef19fa2018-05-15 19:35:29 -0700718 (mClient == 0) ? getpid() : mClient->pid(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700719 mSessionId,
Eric Laurent973db022018-11-20 14:54:31 -0800720 mPortId,
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700721 getTrackStateString(),
722 mCblk->mFlags,
723
Eric Laurent81784c32012-11-19 14:55:58 -0800724 mFormat,
725 mChannelMask,
Andy Hungcef2daa2018-06-01 15:31:49 -0700726 sampleRate(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700727
728 mStreamType,
Kevin Rocard5f2136e2018-05-11 22:03:00 -0700729 mAttr.usage,
730 mAttr.content_type,
731
732 20.0 * log10(mFinalVolume),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700733 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
734 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Andy Hungda540db2017-04-20 14:06:17 -0700735 20.0 * log10(vsVolume.first), // VolumeShaper(s) total volume
736 vsVolume.second ? 'A' : ' ', // if any VolumeShapers active
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700737
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700738 mCblk->mServer,
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700739 bufferSizeInFrames,
740 modifiedBufferChar,
741 framesReadySafe,
742 fillingStatus,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700743 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -0800744 nowInUnderrun,
Andy Hungf6ab58d2018-05-25 12:50:39 -0700745 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700746 );
Andy Hungcef2daa2018-06-01 15:31:49 -0700747
748 if (isServerLatencySupported()) {
749 double latencyMs;
750 bool fromTrack;
751 if (getTrackLatencyMs(&latencyMs, &fromTrack) == OK) {
752 // Show latency in msec, followed by 't' if from track timestamp (the most accurate)
753 // or 'k' if estimated from kernel because track frames haven't been presented yet.
754 result.appendFormat(" %7.2lf %c", latencyMs, fromTrack ? 't' : 'k');
Andy Hungf6ab58d2018-05-25 12:50:39 -0700755 } else {
Andy Hungcef2daa2018-06-01 15:31:49 -0700756 result.appendFormat("%10s", mCblk->mServer != 0 ? "unavail" : "new");
Andy Hungf6ab58d2018-05-25 12:50:39 -0700757 }
758 }
759 result.append("\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800760}
761
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800762uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
763 return mAudioTrackServerProxy->getSampleRate();
764}
765
Eric Laurent81784c32012-11-19 14:55:58 -0800766// AudioBufferProvider interface
Kevin Rocard153f92d2018-12-18 18:33:28 -0800767status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800768{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800769 ServerProxy::Buffer buf;
770 size_t desiredFrames = buffer->frameCount;
771 buf.mFrameCount = desiredFrames;
772 status_t status = mServerProxy->obtainBuffer(&buf);
773 buffer->frameCount = buf.mFrameCount;
774 buffer->raw = buf.mRaw;
Mikhail Naganova66d3892017-05-03 16:50:56 -0700775 if (buf.mFrameCount == 0 && !isStopping() && !isStopped() && !isPaused()) {
Andy Hung9d84af52018-09-12 18:03:44 -0700776 ALOGV("%s(%d): underrun, framesReady(%zu) < framesDesired(%zd), state: %d",
777 __func__, mId, buf.mFrameCount, desiredFrames, mState);
Glenn Kasten82aaf942013-07-17 16:05:07 -0700778 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800779 } else {
780 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800781 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800782 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800783}
784
Kevin Rocard153f92d2018-12-18 18:33:28 -0800785void AudioFlinger::PlaybackThread::Track::releaseBuffer(AudioBufferProvider::Buffer* buffer)
786{
787 interceptBuffer(*buffer);
788 TrackBase::releaseBuffer(buffer);
789}
790
791// TODO: compensate for time shift between HW modules.
792void AudioFlinger::PlaybackThread::Track::interceptBuffer(
Kevin Rocarda134b002019-02-07 18:05:31 -0800793 const AudioBufferProvider::Buffer& sourceBuffer) {
Kevin Rocard6057fa22019-02-08 14:08:07 -0800794 auto start = std::chrono::steady_clock::now();
Kevin Rocarda134b002019-02-07 18:05:31 -0800795 const size_t frameCount = sourceBuffer.frameCount;
Kevin Rocardd83b08a2019-02-27 15:05:54 -0800796 if (frameCount == 0) {
797 return; // No audio to intercept.
798 // Additionally PatchProxyBufferProvider::obtainBuffer (called by PathTrack::getNextBuffer)
799 // does not allow 0 frame size request contrary to getNextBuffer
800 }
801 for (auto& teePatch : mTeePatches) {
802 RecordThread::PatchRecord* patchRecord = teePatch.patchRecord.get();
Kevin Rocarda134b002019-02-07 18:05:31 -0800803
804 size_t framesWritten = writeFrames(patchRecord, sourceBuffer.i8, frameCount);
805 // On buffer wrap, the buffer frame count will be less than requested,
806 // when this happens a second buffer needs to be used to write the leftover audio
807 size_t framesLeft = frameCount - framesWritten;
808 if (framesWritten != 0 && framesLeft != 0) {
809 framesWritten +=
810 writeFrames(patchRecord, sourceBuffer.i8 + framesWritten * mFrameSize, framesLeft);
811 framesLeft = frameCount - framesWritten;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800812 }
Kevin Rocarda134b002019-02-07 18:05:31 -0800813 ALOGW_IF(framesLeft != 0, "%s(%d) PatchRecord %d can not provide big enough "
814 "buffer %zu/%zu, dropping %zu frames", __func__, mId, patchRecord->mId,
815 framesWritten, frameCount, framesLeft);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800816 }
Kevin Rocard6057fa22019-02-08 14:08:07 -0800817 auto spent = ceil<std::chrono::microseconds>(std::chrono::steady_clock::now() - start);
818 using namespace std::chrono_literals;
819 // Average is ~20us per track, this should virtually never be logged (Logging takes >200us)
820 ALOGD_IF(spent > 200us, "%s: took %lldus to intercept %zu tracks", __func__,
821 spent.count(), mTeePatches.size());
Kevin Rocard153f92d2018-12-18 18:33:28 -0800822}
823
Kevin Rocarda134b002019-02-07 18:05:31 -0800824size_t AudioFlinger::PlaybackThread::Track::writeFrames(AudioBufferProvider* dest,
825 const void* src,
826 size_t frameCount) {
827 AudioBufferProvider::Buffer patchBuffer;
828 patchBuffer.frameCount = frameCount;
829 auto status = dest->getNextBuffer(&patchBuffer);
830 if (status != NO_ERROR) {
831 ALOGW("%s PathRecord getNextBuffer failed with error %d: %s",
832 __func__, status, strerror(-status));
833 return 0;
834 }
835 ALOG_ASSERT(patchBuffer.frameCount <= frameCount);
836 memcpy(patchBuffer.raw, src, patchBuffer.frameCount * mFrameSize);
837 auto framesWritten = patchBuffer.frameCount;
838 dest->releaseBuffer(&patchBuffer);
839 return framesWritten;
840}
841
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700842// releaseBuffer() is not overridden
843
844// ExtendedAudioBufferProvider interface
845
Andy Hung27876c02014-09-09 18:07:55 -0700846// framesReady() may return an approximation of the number of frames if called
847// from a different thread than the one calling Proxy->obtainBuffer() and
848// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
849// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800850size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700851 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
852 // Static tracks return zero frames immediately upon stopping (for FastTracks).
853 // The remainder of the buffer is not drained.
854 return 0;
855 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800856 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800857}
858
Andy Hung818e7a32016-02-16 18:08:07 -0800859int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700860{
861 return mAudioTrackServerProxy->framesReleased();
862}
863
Andy Hung818e7a32016-02-16 18:08:07 -0800864void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -0800865{
866 // This call comes from a FastTrack and should be kept lockless.
867 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -0800868 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -0800869
Andy Hung818e7a32016-02-16 18:08:07 -0800870 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hungcef2daa2018-06-01 15:31:49 -0700871
872 // Compute latency.
873 // TODO: Consider whether the server latency may be passed in by FastMixer
874 // as a constant for all active FastTracks.
875 const double latencyMs = timestamp.getOutputServerLatencyMs(sampleRate());
876 mServerLatencyFromTrack.store(true);
877 mServerLatencyMs.store(latencyMs);
Andy Hung6ae58432016-02-16 18:32:24 -0800878}
879
Eric Laurent81784c32012-11-19 14:55:58 -0800880// Don't call for fast tracks; the framesReady() could result in priority inversion
881bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800882 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
883 return true;
884 }
885
Eric Laurent16498512014-03-17 17:22:08 -0700886 if (isStopping()) {
887 if (framesReady() > 0) {
888 mFillingUpStatus = FS_FILLED;
889 }
Eric Laurent81784c32012-11-19 14:55:58 -0800890 return true;
891 }
892
Phil Burke8972b02016-03-04 11:29:57 -0800893 if (framesReady() >= mServerProxy->getBufferSizeInFrames() ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700894 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800895 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700896 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800897 return true;
898 }
899 return false;
900}
901
Glenn Kasten0f11b512014-01-31 16:18:54 -0800902status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -0800903 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800904{
905 status_t status = NO_ERROR;
Andy Hungc0691382018-09-12 18:01:57 -0700906 ALOGV("%s(%d): calling pid %d session %d",
907 __func__, mId, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800908
909 sp<ThreadBase> thread = mThread.promote();
910 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700911 if (isOffloaded()) {
912 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
913 Mutex::Autolock _lth(thread->mLock);
914 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700915 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
916 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700917 invalidate();
918 return PERMISSION_DENIED;
919 }
920 }
921 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800922 track_state state = mState;
923 // here the track could be either new, or restarted
924 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800925
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800926 // initial state-stopping. next state-pausing.
927 // What if resume is called ?
928
929 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800930 if (mResumeToStopping) {
931 // happened we need to resume to STOPPING_1
932 mState = TrackBase::STOPPING_1;
Andy Hungc0691382018-09-12 18:01:57 -0700933 ALOGV("%s(%d): PAUSED => STOPPING_1 on thread %d",
934 __func__, mId, (int)mThreadIoHandle);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800935 } else {
936 mState = TrackBase::RESUMING;
Andy Hungc0691382018-09-12 18:01:57 -0700937 ALOGV("%s(%d): PAUSED => RESUMING on thread %d",
938 __func__, mId, (int)mThreadIoHandle);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800939 }
Eric Laurent81784c32012-11-19 14:55:58 -0800940 } else {
941 mState = TrackBase::ACTIVE;
Andy Hungc0691382018-09-12 18:01:57 -0700942 ALOGV("%s(%d): ? => ACTIVE on thread %d",
943 __func__, mId, (int)mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -0800944 }
945
Andy Hunge10393e2015-06-12 13:59:33 -0700946 // states to reset position info for non-offloaded/direct tracks
947 if (!isOffloaded() && !isDirect()
948 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
949 mFrameMap.reset();
950 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800951 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700952 if (isFastTrack()) {
953 // refresh fast track underruns on start because that field is never cleared
954 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
955 // after stop.
956 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
957 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800958 status = playbackThread->addTrack_l(this);
959 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800960 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800961 // restore previous state if start was rejected by policy manager
962 if (status == PERMISSION_DENIED) {
963 mState = state;
964 }
965 }
Andy Hung1d3556d2018-03-29 16:30:14 -0700966
967 if (status == NO_ERROR || status == ALREADY_EXISTS) {
968 // for streaming tracks, remove the buffer read stop limit.
969 mAudioTrackServerProxy->start();
970 }
971
Eric Laurentbfb1b832013-01-07 09:53:42 -0800972 // track was already in the active list, not a problem
973 if (status == ALREADY_EXISTS) {
974 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700975 } else {
976 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
977 // It is usually unsafe to access the server proxy from a binder thread.
978 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
979 // isn't looking at this track yet: we still hold the normal mixer thread lock,
980 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700981 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700982 ServerProxy::Buffer buffer;
983 buffer.mFrameCount = 1;
984 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800985 }
986 } else {
987 status = BAD_VALUE;
988 }
Kevin Rocardc43ea142019-01-31 18:17:37 -0800989 if (status == NO_ERROR) {
990 forEachTeePatchTrack([](auto patchTrack) { patchTrack->start(); });
991 }
Eric Laurent81784c32012-11-19 14:55:58 -0800992 return status;
993}
994
995void AudioFlinger::PlaybackThread::Track::stop()
996{
Andy Hungc0691382018-09-12 18:01:57 -0700997 ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -0800998 sp<ThreadBase> thread = mThread.promote();
999 if (thread != 0) {
1000 Mutex::Autolock _l(thread->mLock);
1001 track_state state = mState;
1002 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
1003 // If the track is not active (PAUSED and buffers full), flush buffers
1004 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1005 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
1006 reset();
1007 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -07001008 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001009 mState = STOPPED;
1010 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001011 // For fast tracks prepareTracks_l() will set state to STOPPING_2
1012 // presentation is complete
1013 // For an offloaded track this starts a drain and state will
1014 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -08001015 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -07001016 if (isOffloaded()) {
1017 mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
1018 }
Eric Laurent81784c32012-11-19 14:55:58 -08001019 }
Eric Laurentb369caf2015-03-30 20:51:47 -07001020 playbackThread->broadcast_l();
Andy Hungc0691382018-09-12 18:01:57 -07001021 ALOGV("%s(%d): not stopping/stopped => stopping/stopped on thread %d",
1022 __func__, mId, (int)mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -08001023 }
Eric Laurent81784c32012-11-19 14:55:58 -08001024 }
Kevin Rocardc43ea142019-01-31 18:17:37 -08001025 forEachTeePatchTrack([](auto patchTrack) { patchTrack->stop(); });
Eric Laurent81784c32012-11-19 14:55:58 -08001026}
1027
1028void AudioFlinger::PlaybackThread::Track::pause()
1029{
Andy Hungc0691382018-09-12 18:01:57 -07001030 ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001031 sp<ThreadBase> thread = mThread.promote();
1032 if (thread != 0) {
1033 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001034 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1035 switch (mState) {
1036 case STOPPING_1:
1037 case STOPPING_2:
1038 if (!isOffloaded()) {
1039 /* nothing to do if track is not offloaded */
1040 break;
1041 }
1042
1043 // Offloaded track was draining, we need to carry on draining when resumed
1044 mResumeToStopping = true;
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07001045 FALLTHROUGH_INTENDED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001046 case ACTIVE:
1047 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08001048 mState = PAUSING;
Andy Hungc0691382018-09-12 18:01:57 -07001049 ALOGV("%s(%d): ACTIVE/RESUMING => PAUSING on thread %d",
1050 __func__, mId, (int)mThreadIoHandle);
Eric Laurentede6c3b2013-09-19 14:37:46 -07001051 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001052 break;
Eric Laurent81784c32012-11-19 14:55:58 -08001053
Eric Laurentbfb1b832013-01-07 09:53:42 -08001054 default:
1055 break;
Eric Laurent81784c32012-11-19 14:55:58 -08001056 }
1057 }
Kevin Rocardc43ea142019-01-31 18:17:37 -08001058 // Pausing the TeePatch to avoid a glitch on underrun, at the cost of buffered audio loss.
1059 forEachTeePatchTrack([](auto patchTrack) { patchTrack->pause(); });
Eric Laurent81784c32012-11-19 14:55:58 -08001060}
1061
1062void AudioFlinger::PlaybackThread::Track::flush()
1063{
Andy Hungc0691382018-09-12 18:01:57 -07001064 ALOGV("%s(%d)", __func__, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08001065 sp<ThreadBase> thread = mThread.promote();
1066 if (thread != 0) {
1067 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08001068 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001069
Phil Burk4bb650b2016-09-09 12:11:17 -07001070 // Flush the ring buffer now if the track is not active in the PlaybackThread.
1071 // Otherwise the flush would not be done until the track is resumed.
1072 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
1073 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
1074 (void)mServerProxy->flushBufferIfNeeded();
1075 }
1076
Eric Laurentbfb1b832013-01-07 09:53:42 -08001077 if (isOffloaded()) {
1078 // If offloaded we allow flush during any state except terminated
1079 // and keep the track active to avoid problems if user is seeking
1080 // rapidly and underlying hardware has a significant delay handling
1081 // a pause
1082 if (isTerminated()) {
1083 return;
1084 }
1085
Andy Hung9d84af52018-09-12 18:03:44 -07001086 ALOGV("%s(%d): offload flush", __func__, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08001087 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001088
1089 if (mState == STOPPING_1 || mState == STOPPING_2) {
Andy Hung9d84af52018-09-12 18:03:44 -07001090 ALOGV("%s(%d): flushed in STOPPING_1 or 2 state, change state to ACTIVE",
1091 __func__, mId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001092 mState = ACTIVE;
1093 }
1094
Haynes Mathew George7844f672014-01-15 12:32:55 -08001095 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001096 mResumeToStopping = false;
1097 } else {
1098 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
1099 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
1100 return;
1101 }
1102 // No point remaining in PAUSED state after a flush => go to
1103 // FLUSHED state
1104 mState = FLUSHED;
1105 // do not reset the track if it is still in the process of being stopped or paused.
1106 // this will be done by prepareTracks_l() when the track is stopped.
1107 // prepareTracks_l() will see mState == FLUSHED, then
1108 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -08001109 if (isDirect()) {
1110 mFlushHwPending = true;
1111 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001112 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
1113 reset();
1114 }
Eric Laurent81784c32012-11-19 14:55:58 -08001115 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001116 // Prevent flush being lost if the track is flushed and then resumed
1117 // before mixer thread can run. This is important when offloading
1118 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -07001119 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001120 }
Kevin Rocardc43ea142019-01-31 18:17:37 -08001121 // Flush the Tee to avoid on resume playing old data and glitching on the transition to new data
1122 forEachTeePatchTrack([](auto patchTrack) { patchTrack->flush(); });
Eric Laurent81784c32012-11-19 14:55:58 -08001123}
1124
Haynes Mathew George7844f672014-01-15 12:32:55 -08001125// must be called with thread lock held
1126void AudioFlinger::PlaybackThread::Track::flushAck()
1127{
Eric Laurentd1f69b02014-12-15 14:33:13 -08001128 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -08001129 return;
1130
Phil Burk4bb650b2016-09-09 12:11:17 -07001131 // Clear the client ring buffer so that the app can prime the buffer while paused.
1132 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
1133 mServerProxy->flushBufferIfNeeded();
1134
Haynes Mathew George7844f672014-01-15 12:32:55 -08001135 mFlushHwPending = false;
1136}
1137
Eric Laurent81784c32012-11-19 14:55:58 -08001138void AudioFlinger::PlaybackThread::Track::reset()
1139{
1140 // Do not reset twice to avoid discarding data written just after a flush and before
1141 // the audioflinger thread detects the track is stopped.
1142 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -08001143 // Force underrun condition to avoid false underrun callback until first data is
1144 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -07001145 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001146 mFillingUpStatus = FS_FILLING;
1147 mResetDone = true;
1148 if (mState == FLUSHED) {
1149 mState = IDLE;
1150 }
1151 }
1152}
1153
Eric Laurentbfb1b832013-01-07 09:53:42 -08001154status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
1155{
1156 sp<ThreadBase> thread = mThread.promote();
1157 if (thread == 0) {
Andy Hung9d84af52018-09-12 18:03:44 -07001158 ALOGE("%s(%d): thread is dead", __func__, mId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001159 return FAILED_TRANSACTION;
1160 } else if ((thread->type() == ThreadBase::DIRECT) ||
1161 (thread->type() == ThreadBase::OFFLOAD)) {
1162 return thread->setParameters(keyValuePairs);
1163 } else {
1164 return PERMISSION_DENIED;
1165 }
1166}
1167
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001168status_t AudioFlinger::PlaybackThread::Track::selectPresentation(int presentationId,
1169 int programId) {
1170 sp<ThreadBase> thread = mThread.promote();
1171 if (thread == 0) {
1172 ALOGE("thread is dead");
1173 return FAILED_TRANSACTION;
1174 } else if ((thread->type() == ThreadBase::DIRECT) || (thread->type() == ThreadBase::OFFLOAD)) {
1175 DirectOutputThread *directOutputThread = static_cast<DirectOutputThread*>(thread.get());
1176 return directOutputThread->selectPresentation(presentationId, programId);
1177 }
1178 return INVALID_OPERATION;
1179}
1180
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001181VolumeShaper::Status AudioFlinger::PlaybackThread::Track::applyVolumeShaper(
1182 const sp<VolumeShaper::Configuration>& configuration,
1183 const sp<VolumeShaper::Operation>& operation)
1184{
Andy Hung10cbff12017-02-21 17:30:14 -08001185 sp<VolumeShaper::Configuration> newConfiguration;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001186
Andy Hung10cbff12017-02-21 17:30:14 -08001187 if (isOffloadedOrDirect()) {
1188 const VolumeShaper::Configuration::OptionFlag optionFlag
1189 = configuration->getOptionFlags();
1190 if ((optionFlag & VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME) == 0) {
Andy Hung9d84af52018-09-12 18:03:44 -07001191 ALOGW("%s(%d): %s tracks do not support frame counted VolumeShaper,"
1192 " using clock time instead",
1193 __func__, mId,
1194 isOffloaded() ? "Offload" : "Direct");
Andy Hung10cbff12017-02-21 17:30:14 -08001195 newConfiguration = new VolumeShaper::Configuration(*configuration);
1196 newConfiguration->setOptionFlags(
1197 VolumeShaper::Configuration::OptionFlag(optionFlag
1198 | VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME));
1199 }
1200 }
1201
1202 VolumeShaper::Status status = mVolumeHandler->applyVolumeShaper(
1203 (newConfiguration.get() != nullptr ? newConfiguration : configuration), operation);
1204
1205 if (isOffloadedOrDirect()) {
1206 // Signal thread to fetch new volume.
1207 sp<ThreadBase> thread = mThread.promote();
1208 if (thread != 0) {
Kevin Rocard5f2136e2018-05-11 22:03:00 -07001209 Mutex::Autolock _l(thread->mLock);
Andy Hung10cbff12017-02-21 17:30:14 -08001210 thread->broadcast_l();
1211 }
1212 }
1213 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001214}
1215
1216sp<VolumeShaper::State> AudioFlinger::PlaybackThread::Track::getVolumeShaperState(int id)
1217{
1218 // Note: We don't check if Thread exists.
1219
1220 // mVolumeHandler is thread safe.
1221 return mVolumeHandler->getVolumeShaperState(id);
1222}
1223
Kevin Rocard12381092018-04-11 09:19:59 -07001224void AudioFlinger::PlaybackThread::Track::setFinalVolume(float volume)
1225{
1226 if (mFinalVolume != volume) { // Compare to an epsilon if too many meaningless updates
1227 mFinalVolume = volume;
1228 setMetadataHasChanged();
1229 }
1230}
1231
1232void AudioFlinger::PlaybackThread::Track::copyMetadataTo(MetadataInserter& backInserter) const
1233{
1234 *backInserter++ = {
1235 .usage = mAttr.usage,
1236 .content_type = mAttr.content_type,
1237 .gain = mFinalVolume,
1238 };
1239}
1240
Kevin Rocard153f92d2018-12-18 18:33:28 -08001241void AudioFlinger::PlaybackThread::Track::setTeePatches(TeePatches teePatches) {
Kevin Rocardc43ea142019-01-31 18:17:37 -08001242 forEachTeePatchTrack([](auto patchTrack) { patchTrack->destroy(); });
Kevin Rocard153f92d2018-12-18 18:33:28 -08001243 mTeePatches = std::move(teePatches);
1244}
1245
Glenn Kasten573d80a2013-08-26 09:36:23 -07001246status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
1247{
Andy Hung818e7a32016-02-16 18:08:07 -08001248 if (!isOffloaded() && !isDirect()) {
1249 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -07001250 }
Glenn Kasten573d80a2013-08-26 09:36:23 -07001251 sp<ThreadBase> thread = mThread.promote();
1252 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -07001253 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -07001254 }
Phil Burk6140c792015-03-19 14:30:21 -07001255
Glenn Kasten573d80a2013-08-26 09:36:23 -07001256 Mutex::Autolock _l(thread->mLock);
1257 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Andy Hung818e7a32016-02-16 18:08:07 -08001258 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -07001259}
1260
Eric Laurent81784c32012-11-19 14:55:58 -08001261status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
1262{
Eric Laurent81784c32012-11-19 14:55:58 -08001263 sp<ThreadBase> thread = mThread.promote();
Eric Laurent6c796322019-04-09 14:13:17 -07001264 if (thread == nullptr) {
1265 return DEAD_OBJECT;
1266 }
Eric Laurent81784c32012-11-19 14:55:58 -08001267
Eric Laurent6c796322019-04-09 14:13:17 -07001268 sp<PlaybackThread> dstThread = (PlaybackThread *)thread.get();
1269 sp<PlaybackThread> srcThread; // srcThread is initialized by call to moveAuxEffectToIo()
1270 sp<AudioFlinger> af = mClient->audioFlinger();
1271 status_t status = af->moveAuxEffectToIo(EffectId, dstThread, &srcThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001272
Eric Laurent6c796322019-04-09 14:13:17 -07001273 if (EffectId != 0 && status == NO_ERROR) {
1274 status = dstThread->attachAuxEffect(this, EffectId);
1275 if (status == NO_ERROR) {
1276 AudioSystem::moveEffectsToIo(std::vector<int>(EffectId), dstThread->id());
Eric Laurent81784c32012-11-19 14:55:58 -08001277 }
Eric Laurent6c796322019-04-09 14:13:17 -07001278 }
1279
1280 if (status != NO_ERROR && srcThread != nullptr) {
1281 af->moveAuxEffectToIo(EffectId, srcThread, &dstThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001282 }
1283 return status;
1284}
1285
1286void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
1287{
1288 mAuxEffectId = EffectId;
1289 mAuxBuffer = buffer;
1290}
1291
Andy Hung818e7a32016-02-16 18:08:07 -08001292bool AudioFlinger::PlaybackThread::Track::presentationComplete(
1293 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001294{
Andy Hung818e7a32016-02-16 18:08:07 -08001295 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
1296 // This assists in proper timestamp computation as well as wakelock management.
1297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 // a track is considered presented when the total number of frames written to audio HAL
1299 // corresponds to the number of frames written when presentationComplete() is called for the
1300 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001301 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1302 // to detect when all frames have been played. In this case framesWritten isn't
1303 // useful because it doesn't always reflect whether there is data in the h/w
1304 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung9d84af52018-09-12 18:03:44 -07001305 ALOGV("%s(%d): presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
1306 __func__, mId,
Andy Hung818e7a32016-02-16 18:08:07 -08001307 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001308 if (mPresentationCompleteFrames == 0) {
1309 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung9d84af52018-09-12 18:03:44 -07001310 ALOGV("%s(%d): presentationComplete() reset:"
1311 " mPresentationCompleteFrames %lld audioHalFrames %zu",
1312 __func__, mId,
Andy Hung818e7a32016-02-16 18:08:07 -08001313 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08001314 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001315
Andy Hungc54b1ff2016-02-23 14:07:07 -08001316 bool complete;
1317 if (isOffloaded()) {
1318 complete = true;
1319 } else if (isDirect() || isFastTrack()) { // these do not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001320 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hungc54b1ff2016-02-23 14:07:07 -08001321 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001322 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -08001323 && mAudioTrackServerProxy->isDrained();
1324 }
1325
1326 if (complete) {
Eric Laurent81784c32012-11-19 14:55:58 -08001327 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001328 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001329 return true;
1330 }
1331 return false;
1332}
1333
1334void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1335{
Ivan Lozano5ec161b2017-12-06 10:00:28 -08001336 for (size_t i = 0; i < mSyncEvents.size();) {
Eric Laurent81784c32012-11-19 14:55:58 -08001337 if (mSyncEvents[i]->type() == type) {
1338 mSyncEvents[i]->trigger();
1339 mSyncEvents.removeAt(i);
Ivan Lozano5ec161b2017-12-06 10:00:28 -08001340 } else {
1341 ++i;
Eric Laurent81784c32012-11-19 14:55:58 -08001342 }
1343 }
1344}
1345
1346// implement VolumeBufferProvider interface
1347
Glenn Kastenc56f3422014-03-21 17:53:17 -07001348gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001349{
1350 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1351 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001352 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1353 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1354 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001355 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001356 if (vl > GAIN_FLOAT_UNITY) {
1357 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001358 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001359 if (vr > GAIN_FLOAT_UNITY) {
1360 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001361 }
1362 // now apply the cached master volume and stream type volume;
1363 // this is trusted but lacks any synchronization or barrier so may be stale
1364 float v = mCachedVolume;
1365 vl *= v;
1366 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001367 // re-combine into packed minifloat
1368 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001369 // FIXME look at mute, pause, and stop flags
1370 return vlr;
1371}
1372
1373status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1374{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001375 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001376 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1377 (mState == STOPPED)))) {
Andy Hung9d84af52018-09-12 18:03:44 -07001378 ALOGW("%s(%d): in invalid state %d on session %d %s mode, framesReady %zu",
1379 __func__, mId,
Eric Laurent81784c32012-11-19 14:55:58 -08001380 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1381 event->cancel();
1382 return INVALID_OPERATION;
1383 }
1384 (void) TrackBase::setSyncEvent(event);
1385 return NO_ERROR;
1386}
1387
Glenn Kasten5736c352012-12-04 12:12:34 -08001388void AudioFlinger::PlaybackThread::Track::invalidate()
1389{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001390 TrackBase::invalidate();
Eric Laurent4d231dc2016-03-11 18:38:23 -08001391 signalClientFlag(CBLK_INVALID);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001392}
1393
1394void AudioFlinger::PlaybackThread::Track::disable()
1395{
1396 signalClientFlag(CBLK_DISABLED);
1397}
1398
1399void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1400{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001401 // FIXME should use proxy, and needs work
1402 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001403 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001404 android_atomic_release_store(0x40000000, &cblk->mFutex);
1405 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001406 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001407}
1408
Eric Laurent59fe0102013-09-27 18:48:26 -07001409void AudioFlinger::PlaybackThread::Track::signal()
1410{
1411 sp<ThreadBase> thread = mThread.promote();
1412 if (thread != 0) {
1413 PlaybackThread *t = (PlaybackThread *)thread.get();
1414 Mutex::Autolock _l(t->mLock);
1415 t->broadcast_l();
1416 }
1417}
1418
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001419//To be called with thread lock held
1420bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1421
1422 if (mState == RESUMING)
1423 return true;
1424 /* Resume is pending if track was stopping before pause was called */
1425 if (mState == STOPPING_1 &&
1426 mResumeToStopping)
1427 return true;
1428
1429 return false;
1430}
1431
1432//To be called with thread lock held
1433void AudioFlinger::PlaybackThread::Track::resumeAck() {
1434
1435
1436 if (mState == RESUMING)
1437 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001438
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001439 // Other possibility of pending resume is stopping_1 state
1440 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001441 // drain being called.
1442 if (mState == STOPPING_1) {
1443 mResumeToStopping = false;
1444 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001445}
Andy Hunge10393e2015-06-12 13:59:33 -07001446
1447//To be called with thread lock held
1448void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08001449 int64_t trackFramesReleased, int64_t sinkFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07001450 uint32_t halSampleRate, const ExtendedTimestamp &timeStamp) {
Andy Hung30282562018-08-08 18:27:03 -07001451 // Make the kernel frametime available.
1452 const FrameTime ft{
1453 timeStamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
1454 timeStamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]};
1455 // ALOGD("FrameTime: %lld %lld", (long long)ft.frames, (long long)ft.timeNs);
1456 mKernelFrameTime.store(ft);
1457 if (!audio_is_linear_pcm(mFormat)) {
1458 return;
1459 }
1460
Andy Hung818e7a32016-02-16 18:08:07 -08001461 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07001462 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08001463
1464 // adjust server times and set drained state.
1465 //
1466 // Our timestamps are only updated when the track is on the Thread active list.
1467 // We need to ensure that tracks are not removed before full drain.
1468 ExtendedTimestamp local = timeStamp;
Andy Hungcef2daa2018-06-01 15:31:49 -07001469 bool drained = true; // default assume drained, if no server info found
Andy Hung818e7a32016-02-16 18:08:07 -08001470 bool checked = false;
1471 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1472 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1473 // Lookup the track frame corresponding to the sink frame position.
1474 if (local.mTimeNs[i] > 0) {
1475 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1476 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07001477 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hungcef2daa2018-06-01 15:31:49 -07001478 drained = local.mPosition[i] >= mAudioTrackServerProxy->framesReleased();
Andy Hung818e7a32016-02-16 18:08:07 -08001479 checked = true;
1480 }
1481 }
Andy Hunge10393e2015-06-12 13:59:33 -07001482 }
Andy Hungcef2daa2018-06-01 15:31:49 -07001483
1484 mAudioTrackServerProxy->setDrained(drained);
Andy Hungea2b9c02016-02-12 17:06:53 -08001485 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08001486 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08001487 mServerProxy->setTimestamp(local);
Andy Hungcef2daa2018-06-01 15:31:49 -07001488
1489 // Compute latency info.
1490 const bool useTrackTimestamp = !drained;
1491 const double latencyMs = useTrackTimestamp
1492 ? local.getOutputServerLatencyMs(sampleRate())
1493 : timeStamp.getOutputServerLatencyMs(halSampleRate);
1494
1495 mServerLatencyFromTrack.store(useTrackTimestamp);
1496 mServerLatencyMs.store(latencyMs);
Andy Hunge10393e2015-06-12 13:59:33 -07001497}
1498
jiabin57303cc2018-12-18 15:45:57 -08001499binder::Status AudioFlinger::PlaybackThread::Track::AudioVibrationController::mute(
1500 /*out*/ bool *ret) {
1501 *ret = false;
1502 sp<ThreadBase> thread = mTrack->mThread.promote();
1503 if (thread != 0) {
1504 // Lock for updating mHapticPlaybackEnabled.
1505 Mutex::Autolock _l(thread->mLock);
1506 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1507 if ((mTrack->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
1508 && playbackThread->mHapticChannelCount > 0) {
1509 mTrack->setHapticPlaybackEnabled(false);
1510 *ret = true;
1511 }
1512 }
1513 return binder::Status::ok();
1514}
1515
1516binder::Status AudioFlinger::PlaybackThread::Track::AudioVibrationController::unmute(
1517 /*out*/ bool *ret) {
1518 *ret = false;
1519 sp<ThreadBase> thread = mTrack->mThread.promote();
1520 if (thread != 0) {
1521 // Lock for updating mHapticPlaybackEnabled.
1522 Mutex::Autolock _l(thread->mLock);
1523 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1524 if ((mTrack->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
1525 && playbackThread->mHapticChannelCount > 0) {
1526 mTrack->setHapticPlaybackEnabled(true);
1527 *ret = true;
1528 }
1529 }
1530 return binder::Status::ok();
1531}
1532
Eric Laurent81784c32012-11-19 14:55:58 -08001533// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -07001534#undef LOG_TAG
1535#define LOG_TAG "AF::OutputTrack"
Eric Laurent81784c32012-11-19 14:55:58 -08001536
Eric Laurent81784c32012-11-19 14:55:58 -08001537AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1538 PlaybackThread *playbackThread,
1539 DuplicatingThread *sourceThread,
1540 uint32_t sampleRate,
1541 audio_format_t format,
1542 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001543 size_t frameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001544 uid_t uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001545 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001546 audio_attributes_t{} /* currently unused for output track */,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001547 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07001548 nullptr /* buffer */, (size_t)0 /* bufferSize */, nullptr /* sharedBuffer */,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001549 AUDIO_SESSION_NONE, getpid(), uid, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08001550 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07001551 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08001552{
1553
1554 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001555 mOutBuffer.frameCount = 0;
1556 playbackThread->mTracks.add(this);
Andy Hung9d84af52018-09-12 18:03:44 -07001557 ALOGV("%s(): mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001558 "frameCount %zu, mChannelMask 0x%08x",
Andy Hung9d84af52018-09-12 18:03:44 -07001559 __func__, mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001560 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001561 // since client and server are in the same process,
1562 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001563 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1564 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001565 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001566 mClientProxy->setSendLevel(0.0);
1567 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001568 } else {
Andy Hung9d84af52018-09-12 18:03:44 -07001569 ALOGW("%s(%d): Error creating output track on thread %d",
1570 __func__, mId, (int)mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -08001571 }
1572}
1573
1574AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1575{
1576 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001577 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001578}
1579
1580status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001581 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08001582{
1583 status_t status = Track::start(event, triggerSession);
1584 if (status != NO_ERROR) {
1585 return status;
1586 }
1587
1588 mActive = true;
1589 mRetryCount = 127;
1590 return status;
1591}
1592
1593void AudioFlinger::PlaybackThread::OutputTrack::stop()
1594{
1595 Track::stop();
1596 clearBufferQueue();
1597 mOutBuffer.frameCount = 0;
1598 mActive = false;
1599}
1600
Andy Hung1c86ebe2018-05-29 20:29:08 -07001601ssize_t AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001602{
1603 Buffer *pInBuffer;
1604 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001605 bool outputBufferFull = false;
1606 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001607 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001608
1609 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1610
1611 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001612 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001613 }
1614
1615 while (waitTimeLeftMs) {
1616 // First write pending buffers, then new data
1617 if (mBufferQueue.size()) {
1618 pInBuffer = mBufferQueue.itemAt(0);
1619 } else {
1620 pInBuffer = &inBuffer;
1621 }
1622
1623 if (pInBuffer->frameCount == 0) {
1624 break;
1625 }
1626
1627 if (mOutBuffer.frameCount == 0) {
1628 mOutBuffer.frameCount = pInBuffer->frameCount;
1629 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001630 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001631 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Andy Hung9d84af52018-09-12 18:03:44 -07001632 ALOGV("%s(%d): thread %d no more output buffers; status %d",
1633 __func__, mId,
1634 (int)mThreadIoHandle, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001635 outputBufferFull = true;
1636 break;
1637 }
1638 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1639 if (waitTimeLeftMs >= waitTimeMs) {
1640 waitTimeLeftMs -= waitTimeMs;
1641 } else {
1642 waitTimeLeftMs = 0;
1643 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08001644 if (status == NOT_ENOUGH_DATA) {
1645 restartIfDisabled();
1646 continue;
1647 }
Eric Laurent81784c32012-11-19 14:55:58 -08001648 }
1649
1650 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1651 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001652 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001653 Proxy::Buffer buf;
1654 buf.mFrameCount = outFrames;
1655 buf.mRaw = NULL;
1656 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001657 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08001658 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001659 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001660 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001661 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001662
1663 if (pInBuffer->frameCount == 0) {
1664 if (mBufferQueue.size()) {
1665 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001666 free(pInBuffer->mBuffer);
Yunlian Jiang8adc8082017-06-06 15:59:44 -07001667 if (pInBuffer != &inBuffer) {
1668 delete pInBuffer;
1669 }
Andy Hung9d84af52018-09-12 18:03:44 -07001670 ALOGV("%s(%d): thread %d released overflow buffer %zu",
1671 __func__, mId,
1672 (int)mThreadIoHandle, mBufferQueue.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001673 } else {
1674 break;
1675 }
1676 }
1677 }
1678
1679 // If we could not write all frames, allocate a buffer and queue it for next time.
1680 if (inBuffer.frameCount) {
1681 sp<ThreadBase> thread = mThread.promote();
1682 if (thread != 0 && !thread->standby()) {
1683 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1684 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001685 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001686 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001687 pInBuffer->raw = pInBuffer->mBuffer;
1688 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001689 mBufferQueue.add(pInBuffer);
Andy Hung9d84af52018-09-12 18:03:44 -07001690 ALOGV("%s(%d): thread %d adding overflow buffer %zu", __func__, mId,
1691 (int)mThreadIoHandle, mBufferQueue.size());
Andy Hung1c86ebe2018-05-29 20:29:08 -07001692 // audio data is consumed (stored locally); set frameCount to 0.
1693 inBuffer.frameCount = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001694 } else {
Andy Hung9d84af52018-09-12 18:03:44 -07001695 ALOGW("%s(%d): thread %d no more overflow buffers",
1696 __func__, mId, (int)mThreadIoHandle);
Andy Hung1c86ebe2018-05-29 20:29:08 -07001697 // TODO: return error for this.
Eric Laurent81784c32012-11-19 14:55:58 -08001698 }
1699 }
1700 }
1701
Andy Hungc25b84a2015-01-14 19:04:10 -08001702 // Calling write() with a 0 length buffer means that no more data will be written:
1703 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1704 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1705 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001706 }
1707
Andy Hung1c86ebe2018-05-29 20:29:08 -07001708 return frames - inBuffer.frameCount; // number of frames consumed.
Eric Laurent81784c32012-11-19 14:55:58 -08001709}
1710
Kevin Rocard12381092018-04-11 09:19:59 -07001711void AudioFlinger::PlaybackThread::OutputTrack::copyMetadataTo(MetadataInserter& backInserter) const
1712{
1713 std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
1714 backInserter = std::copy(mTrackMetadatas.begin(), mTrackMetadatas.end(), backInserter);
1715}
1716
1717void AudioFlinger::PlaybackThread::OutputTrack::setMetadatas(const SourceMetadatas& metadatas) {
1718 {
1719 std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
1720 mTrackMetadatas = metadatas;
1721 }
1722 // No need to adjust metadata track volumes as OutputTrack volumes are always 0dBFS.
1723 setMetadataHasChanged();
1724}
1725
Eric Laurent81784c32012-11-19 14:55:58 -08001726status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1727 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1728{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001729 ClientProxy::Buffer buf;
1730 buf.mFrameCount = buffer->frameCount;
1731 struct timespec timeout;
1732 timeout.tv_sec = waitTimeMs / 1000;
1733 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1734 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1735 buffer->frameCount = buf.mFrameCount;
1736 buffer->raw = buf.mRaw;
1737 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001738}
1739
Eric Laurent81784c32012-11-19 14:55:58 -08001740void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1741{
1742 size_t size = mBufferQueue.size();
1743
1744 for (size_t i = 0; i < size; i++) {
1745 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001746 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001747 delete pBuffer;
1748 }
1749 mBufferQueue.clear();
1750}
1751
Eric Laurent4d231dc2016-03-11 18:38:23 -08001752void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1753{
1754 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1755 if (mActive && (flags & CBLK_DISABLED)) {
1756 start();
1757 }
1758}
Eric Laurent81784c32012-11-19 14:55:58 -08001759
Andy Hung9d84af52018-09-12 18:03:44 -07001760// ----------------------------------------------------------------------------
1761#undef LOG_TAG
1762#define LOG_TAG "AF::PatchTrack"
1763
Eric Laurent83b88082014-06-20 18:31:16 -07001764AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001765 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001766 uint32_t sampleRate,
1767 audio_channel_mask_t channelMask,
1768 audio_format_t format,
1769 size_t frameCount,
1770 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07001771 size_t bufferSize,
Kevin Rocard45986c72018-12-18 18:22:59 -08001772 audio_output_flags_t flags,
1773 const Timeout& timeout)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001774 : Track(playbackThread, NULL, streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001775 audio_attributes_t{} /* currently unused for patch track */,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001776 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07001777 buffer, bufferSize, nullptr /* sharedBuffer */,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001778 AUDIO_SESSION_NONE, getpid(), AID_AUDIOSERVER, flags, TYPE_PATCH),
Kevin Rocard45986c72018-12-18 18:22:59 -08001779 PatchTrackBase(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true),
1780 *playbackThread, timeout)
Eric Laurent83b88082014-06-20 18:31:16 -07001781{
Andy Hung9d84af52018-09-12 18:03:44 -07001782 ALOGV("%s(%d): sampleRate %d mPeerTimeout %d.%03d sec",
1783 __func__, mId, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07001784 (int)mPeerTimeout.tv_sec,
1785 (int)(mPeerTimeout.tv_nsec / 1000000));
1786}
1787
1788AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1789{
Andy Hungabfab202019-03-07 19:45:54 -08001790 ALOGV("%s(%d)", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07001791}
1792
Eric Laurent4d231dc2016-03-11 18:38:23 -08001793status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07001794 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001795{
1796 status_t status = Track::start(event, triggerSession);
1797 if (status != NO_ERROR) {
1798 return status;
1799 }
1800 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1801 return status;
1802}
1803
Eric Laurent83b88082014-06-20 18:31:16 -07001804// AudioBufferProvider interface
1805status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001806 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001807{
Andy Hung9d84af52018-09-12 18:03:44 -07001808 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07001809 Proxy::Buffer buf;
1810 buf.mFrameCount = buffer->frameCount;
1811 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
Andy Hung9d84af52018-09-12 18:03:44 -07001812 ALOGV_IF(status != NO_ERROR, "%s(%d): getNextBuffer status %d", __func__, mId, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001813 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001814 if (buf.mFrameCount == 0) {
1815 return WOULD_BLOCK;
1816 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001817 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001818 return status;
1819}
1820
1821void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1822{
Andy Hung9d84af52018-09-12 18:03:44 -07001823 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07001824 Proxy::Buffer buf;
1825 buf.mFrameCount = buffer->frameCount;
1826 buf.mRaw = buffer->raw;
1827 mPeerProxy->releaseBuffer(&buf);
1828 TrackBase::releaseBuffer(buffer);
1829}
1830
1831status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1832 const struct timespec *timeOut)
1833{
Eric Laurent4d231dc2016-03-11 18:38:23 -08001834 status_t status = NO_ERROR;
1835 static const int32_t kMaxTries = 5;
1836 int32_t tryCounter = kMaxTries;
Andy Hungf62e1a22018-05-08 18:32:11 -07001837 const size_t originalFrameCount = buffer->mFrameCount;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001838 do {
1839 if (status == NOT_ENOUGH_DATA) {
1840 restartIfDisabled();
Andy Hungf62e1a22018-05-08 18:32:11 -07001841 buffer->mFrameCount = originalFrameCount; // cleared on error, must be restored.
Eric Laurent4d231dc2016-03-11 18:38:23 -08001842 }
1843 status = mProxy->obtainBuffer(buffer, timeOut);
1844 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1845 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07001846}
1847
1848void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1849{
1850 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001851 restartIfDisabled();
1852 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1853}
1854
1855void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1856{
Eric Laurent83b88082014-06-20 18:31:16 -07001857 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
Andy Hung9d84af52018-09-12 18:03:44 -07001858 ALOGW("%s(%d): disabled due to previous underrun, restarting", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07001859 start();
1860 }
Eric Laurent83b88082014-06-20 18:31:16 -07001861}
1862
Eric Laurent81784c32012-11-19 14:55:58 -08001863// ----------------------------------------------------------------------------
1864// Record
1865// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -07001866#undef LOG_TAG
1867#define LOG_TAG "AF::RecordHandle"
Eric Laurent81784c32012-11-19 14:55:58 -08001868
1869AudioFlinger::RecordHandle::RecordHandle(
1870 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1871 : BnAudioRecord(),
1872 mRecordTrack(recordTrack)
1873{
1874}
1875
1876AudioFlinger::RecordHandle::~RecordHandle() {
1877 stop_nonvirtual();
1878 mRecordTrack->destroy();
1879}
1880
Ivan Lozanoff6900d2017-08-01 15:47:38 -07001881binder::Status AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1882 int /*audio_session_t*/ triggerSession) {
Andy Hung9d84af52018-09-12 18:03:44 -07001883 ALOGV("%s()", __func__);
Ivan Lozanoff6900d2017-08-01 15:47:38 -07001884 return binder::Status::fromStatusT(
1885 mRecordTrack->start((AudioSystem::sync_event_t)event, (audio_session_t) triggerSession));
Eric Laurent81784c32012-11-19 14:55:58 -08001886}
1887
Ivan Lozanoff6900d2017-08-01 15:47:38 -07001888binder::Status AudioFlinger::RecordHandle::stop() {
Eric Laurent81784c32012-11-19 14:55:58 -08001889 stop_nonvirtual();
Ivan Lozanoff6900d2017-08-01 15:47:38 -07001890 return binder::Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -08001891}
1892
1893void AudioFlinger::RecordHandle::stop_nonvirtual() {
Andy Hung9d84af52018-09-12 18:03:44 -07001894 ALOGV("%s()", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08001895 mRecordTrack->stop();
1896}
1897
jiabin653cc0a2018-01-17 17:54:10 -08001898binder::Status AudioFlinger::RecordHandle::getActiveMicrophones(
1899 std::vector<media::MicrophoneInfo>* activeMicrophones) {
Andy Hung9d84af52018-09-12 18:03:44 -07001900 ALOGV("%s()", __func__);
jiabin653cc0a2018-01-17 17:54:10 -08001901 return binder::Status::fromStatusT(
1902 mRecordTrack->getActiveMicrophones(activeMicrophones));
1903}
1904
Paul McLean12340082019-03-19 09:35:05 -06001905binder::Status AudioFlinger::RecordHandle::setPreferredMicrophoneDirection(
Paul McLean03a6e6a2018-12-04 10:54:13 -07001906 int /*audio_microphone_direction_t*/ direction) {
1907 ALOGV("%s()", __func__);
Paul McLean12340082019-03-19 09:35:05 -06001908 return binder::Status::fromStatusT(mRecordTrack->setPreferredMicrophoneDirection(
Paul McLean03a6e6a2018-12-04 10:54:13 -07001909 static_cast<audio_microphone_direction_t>(direction)));
1910}
1911
Paul McLean12340082019-03-19 09:35:05 -06001912binder::Status AudioFlinger::RecordHandle::setPreferredMicrophoneFieldDimension(float zoom) {
Paul McLean03a6e6a2018-12-04 10:54:13 -07001913 ALOGV("%s()", __func__);
Paul McLean12340082019-03-19 09:35:05 -06001914 return binder::Status::fromStatusT(mRecordTrack->setPreferredMicrophoneFieldDimension(zoom));
Paul McLean03a6e6a2018-12-04 10:54:13 -07001915}
1916
Eric Laurent81784c32012-11-19 14:55:58 -08001917// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -07001918#undef LOG_TAG
1919#define LOG_TAG "AF::RecordTrack"
Eric Laurent81784c32012-11-19 14:55:58 -08001920
Glenn Kasten05997e22014-03-13 15:08:33 -07001921// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001922AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1923 RecordThread *thread,
1924 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001925 const audio_attributes_t& attr,
Eric Laurent81784c32012-11-19 14:55:58 -08001926 uint32_t sampleRate,
1927 audio_format_t format,
1928 audio_channel_mask_t channelMask,
1929 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001930 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07001931 size_t bufferSize,
Glenn Kastend848eb42016-03-08 13:42:11 -08001932 audio_session_t sessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001933 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001934 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001935 audio_input_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001936 track_type type,
1937 audio_port_handle_t portId)
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001938 : TrackBase(thread, client, attr, sampleRate, format,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001939 channelMask, frameCount, buffer, bufferSize, sessionId,
1940 creatorPid, uid, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001941 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07001942 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07001943 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
Eric Laurent20b9ef02016-12-05 11:03:16 -08001944 type, portId),
Andy Hung97a893e2015-03-29 01:03:07 -07001945 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001946 mFramesToDrop(0),
1947 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07001948 mRecordBufferConverter(NULL),
jiabin9378eb92018-05-02 15:26:35 -07001949 mFlags(flags),
1950 mSilenced(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001951{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001952 if (mCblk == NULL) {
1953 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001954 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001955
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07001956 if (!isDirect()) {
1957 mRecordBufferConverter = new RecordBufferConverter(
1958 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1959 channelMask, format, sampleRate);
1960 // Check if the RecordBufferConverter construction was successful.
1961 // If not, don't continue with construction.
1962 //
1963 // NOTE: It would be extremely rare that the record track cannot be created
1964 // for the current device, but a pending or future device change would make
1965 // the record track configuration valid.
1966 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
Andy Hung9d84af52018-09-12 18:03:44 -07001967 ALOGE("%s(%d): RecordTrack unable to create record buffer converter", __func__, mId);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07001968 return;
1969 }
Andy Hung97a893e2015-03-29 01:03:07 -07001970 }
1971
Andy Hung6ae58432016-02-16 18:32:24 -08001972 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08001973 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08001974
Andy Hung97a893e2015-03-29 01:03:07 -07001975 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001976
Eric Laurent05067782016-06-01 18:27:28 -07001977 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07001978 ALOG_ASSERT(thread->mFastTrackAvail);
1979 thread->mFastTrackAvail = false;
Andy Hung000adb52018-06-01 15:43:26 -07001980 } else {
1981 // TODO: only Normal Record has timestamps (Fast Record does not).
Andy Hung5d3d9562018-10-04 19:27:26 -07001982 mServerLatencySupported = checkServerLatencySupported(mFormat, flags);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001983 }
Andy Hung8946a282018-04-19 20:04:56 -07001984#ifdef TEE_SINK
1985 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle)
1986 + "_" + std::to_string(mId)
1987 + "_R");
1988#endif
Eric Laurent81784c32012-11-19 14:55:58 -08001989}
1990
1991AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1992{
Andy Hung9d84af52018-09-12 18:03:44 -07001993 ALOGV("%s()", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001994 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001995 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001996}
1997
Andy Hung97a893e2015-03-29 01:03:07 -07001998status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1999{
2000 status_t status = TrackBase::initCheck();
2001 if (status == NO_ERROR && mServerProxy == 0) {
2002 status = BAD_VALUE;
2003 }
2004 return status;
2005}
2006
Eric Laurent81784c32012-11-19 14:55:58 -08002007// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08002008status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08002009{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002010 ServerProxy::Buffer buf;
2011 buf.mFrameCount = buffer->frameCount;
2012 status_t status = mServerProxy->obtainBuffer(&buf);
2013 buffer->frameCount = buf.mFrameCount;
2014 buffer->raw = buf.mRaw;
2015 if (buf.mFrameCount == 0) {
2016 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002017 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002018 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002019 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002020}
2021
2022status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08002023 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08002024{
2025 sp<ThreadBase> thread = mThread.promote();
2026 if (thread != 0) {
2027 RecordThread *recordThread = (RecordThread *)thread.get();
2028 return recordThread->start(this, event, triggerSession);
2029 } else {
2030 return BAD_VALUE;
2031 }
2032}
2033
2034void AudioFlinger::RecordThread::RecordTrack::stop()
2035{
2036 sp<ThreadBase> thread = mThread.promote();
2037 if (thread != 0) {
2038 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002039 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08002040 AudioSystem::stopInput(mPortId);
Eric Laurent81784c32012-11-19 14:55:58 -08002041 }
2042 }
2043}
2044
2045void AudioFlinger::RecordThread::RecordTrack::destroy()
2046{
2047 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2048 sp<RecordTrack> keep(this);
2049 {
Andy Hungce685402018-10-05 17:23:27 -07002050 track_state priorState = mState;
Eric Laurent81784c32012-11-19 14:55:58 -08002051 sp<ThreadBase> thread = mThread.promote();
2052 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002053 Mutex::Autolock _l(thread->mLock);
2054 RecordThread *recordThread = (RecordThread *) thread.get();
Andy Hungce685402018-10-05 17:23:27 -07002055 priorState = mState;
2056 recordThread->destroyTrack_l(this); // move mState to STOPPED, terminate
2057 }
2058 // APM portid/client management done outside of lock.
2059 // NOTE: if thread doesn't exist, the input descriptor probably doesn't either.
2060 if (isExternalTrack()) {
2061 switch (priorState) {
2062 case ACTIVE: // invalidated while still active
2063 case STARTING_2: // invalidated/start-aborted after startInput successfully called
2064 case PAUSING: // invalidated while in the middle of stop() pausing (still active)
2065 AudioSystem::stopInput(mPortId);
2066 break;
2067
2068 case STARTING_1: // invalidated/start-aborted and startInput not successful
2069 case PAUSED: // OK, not active
2070 case IDLE: // OK, not active
2071 break;
2072
2073 case STOPPED: // unexpected (destroyed)
2074 default:
2075 LOG_ALWAYS_FATAL("%s(%d): invalid prior state: %d", __func__, mId, priorState);
2076 }
2077 AudioSystem::releaseInput(mPortId);
Eric Laurent81784c32012-11-19 14:55:58 -08002078 }
2079 }
2080}
2081
Eric Laurent9a54bc22013-09-09 09:08:44 -07002082void AudioFlinger::RecordThread::RecordTrack::invalidate()
2083{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002084 TrackBase::invalidate();
Eric Laurent9a54bc22013-09-09 09:08:44 -07002085 // FIXME should use proxy, and needs work
2086 audio_track_cblk_t* cblk = mCblk;
2087 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2088 android_atomic_release_store(0x40000000, &cblk->mFutex);
2089 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002090 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002091}
2092
Eric Laurent81784c32012-11-19 14:55:58 -08002093
Andy Hung000adb52018-06-01 15:43:26 -07002094void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
Eric Laurent81784c32012-11-19 14:55:58 -08002095{
Eric Laurent973db022018-11-20 14:54:31 -08002096 result.appendFormat("Active Id Client Session Port Id S Flags "
Andy Hung9d84af52018-09-12 18:03:44 -07002097 " Format Chn mask SRate Source "
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002098 " Server FrmCnt FrmRdy Sil%s\n",
2099 isServerLatencySupported() ? " Latency" : "");
Eric Laurent81784c32012-11-19 14:55:58 -08002100}
2101
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002102void AudioFlinger::RecordThread::RecordTrack::appendDump(String8& result, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002103{
Eric Laurent973db022018-11-20 14:54:31 -08002104 result.appendFormat("%c%5s %6d %6u %7u %7u %2s 0x%03X "
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002105 "%08X %08X %6u %6X "
Andy Hung000adb52018-06-01 15:43:26 -07002106 "%08X %6zu %6zu %3c",
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002107 isFastTrack() ? 'F' : ' ',
Marco Nelissenb2208842014-02-07 14:00:50 -08002108 active ? "yes" : "no",
Andy Hung9d84af52018-09-12 18:03:44 -07002109 mId,
Andy Hung4ef19fa2018-05-15 19:35:29 -07002110 (mClient == 0) ? getpid() : mClient->pid(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002111 mSessionId,
Eric Laurent973db022018-11-20 14:54:31 -08002112 mPortId,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002113 getTrackStateString(),
2114 mCblk->mFlags,
2115
Eric Laurent81784c32012-11-19 14:55:58 -08002116 mFormat,
2117 mChannelMask,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002118 mSampleRate,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002119 mAttr.source,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002120
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002121 mCblk->mServer,
Jean-Michel Trivi7d665ab2018-04-11 17:26:51 -07002122 mFrameCount,
Andy Hung000adb52018-06-01 15:43:26 -07002123 mServerProxy->framesReadySafe(),
Jean-Michel Trivi7d665ab2018-04-11 17:26:51 -07002124 isSilenced() ? 's' : 'n'
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002125 );
Andy Hung000adb52018-06-01 15:43:26 -07002126 if (isServerLatencySupported()) {
2127 double latencyMs;
2128 bool fromTrack;
2129 if (getTrackLatencyMs(&latencyMs, &fromTrack) == OK) {
2130 // Show latency in msec, followed by 't' if from track timestamp (the most accurate)
2131 // or 'k' if estimated from kernel (usually for debugging).
2132 result.appendFormat(" %7.2lf %c", latencyMs, fromTrack ? 't' : 'k');
2133 } else {
2134 result.appendFormat("%10s", mCblk->mServer != 0 ? "unavail" : "new");
2135 }
2136 }
2137 result.append("\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002138}
2139
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002140void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2141{
2142 if (event == mSyncStartEvent) {
2143 ssize_t framesToDrop = 0;
2144 sp<ThreadBase> threadBase = mThread.promote();
2145 if (threadBase != 0) {
2146 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2147 // from audio HAL
2148 framesToDrop = threadBase->mFrameCount * 2;
2149 }
2150 mFramesToDrop = framesToDrop;
2151 }
2152}
2153
2154void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2155{
2156 if (mSyncStartEvent != 0) {
2157 mSyncStartEvent->cancel();
2158 mSyncStartEvent.clear();
2159 }
2160 mFramesToDrop = 0;
2161}
2162
Andy Hung3f0c9022016-01-15 17:49:46 -08002163void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
2164 int64_t trackFramesReleased, int64_t sourceFramesRead,
2165 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
2166{
Andy Hung30282562018-08-08 18:27:03 -07002167 // Make the kernel frametime available.
2168 const FrameTime ft{
2169 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
2170 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]};
2171 // ALOGD("FrameTime: %lld %lld", (long long)ft.frames, (long long)ft.timeNs);
2172 mKernelFrameTime.store(ft);
2173 if (!audio_is_linear_pcm(mFormat)) {
2174 return;
2175 }
2176
Andy Hung3f0c9022016-01-15 17:49:46 -08002177 ExtendedTimestamp local = timestamp;
2178
2179 // Convert HAL frames to server-side track frames at track sample rate.
2180 // We use trackFramesReleased and sourceFramesRead as an anchor point.
2181 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2182 if (local.mTimeNs[i] != 0) {
2183 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
2184 const int64_t relativeTrackFrames = relativeServerFrames
2185 * mSampleRate / halSampleRate; // TODO: potential computation overflow
2186 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
2187 }
2188 }
Andy Hung6ae58432016-02-16 18:32:24 -08002189 mServerProxy->setTimestamp(local);
Andy Hung000adb52018-06-01 15:43:26 -07002190
2191 // Compute latency info.
2192 const bool useTrackTimestamp = true; // use track unless debugging.
2193 const double latencyMs = - (useTrackTimestamp
2194 ? local.getOutputServerLatencyMs(sampleRate())
2195 : timestamp.getOutputServerLatencyMs(halSampleRate));
2196
2197 mServerLatencyFromTrack.store(useTrackTimestamp);
2198 mServerLatencyMs.store(latencyMs);
Andy Hung3f0c9022016-01-15 17:49:46 -08002199}
Eric Laurent83b88082014-06-20 18:31:16 -07002200
jiabin653cc0a2018-01-17 17:54:10 -08002201status_t AudioFlinger::RecordThread::RecordTrack::getActiveMicrophones(
2202 std::vector<media::MicrophoneInfo>* activeMicrophones)
2203{
2204 sp<ThreadBase> thread = mThread.promote();
2205 if (thread != 0) {
2206 RecordThread *recordThread = (RecordThread *)thread.get();
2207 return recordThread->getActiveMicrophones(activeMicrophones);
2208 } else {
2209 return BAD_VALUE;
2210 }
2211}
2212
Paul McLean12340082019-03-19 09:35:05 -06002213status_t AudioFlinger::RecordThread::RecordTrack::setPreferredMicrophoneDirection(
Paul McLean03a6e6a2018-12-04 10:54:13 -07002214 audio_microphone_direction_t direction) {
2215 sp<ThreadBase> thread = mThread.promote();
2216 if (thread != 0) {
2217 RecordThread *recordThread = (RecordThread *)thread.get();
Paul McLean12340082019-03-19 09:35:05 -06002218 return recordThread->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07002219 } else {
2220 return BAD_VALUE;
2221 }
2222}
2223
Paul McLean12340082019-03-19 09:35:05 -06002224status_t AudioFlinger::RecordThread::RecordTrack::setPreferredMicrophoneFieldDimension(float zoom) {
Paul McLean03a6e6a2018-12-04 10:54:13 -07002225 sp<ThreadBase> thread = mThread.promote();
2226 if (thread != 0) {
2227 RecordThread *recordThread = (RecordThread *)thread.get();
Paul McLean12340082019-03-19 09:35:05 -06002228 return recordThread->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07002229 } else {
2230 return BAD_VALUE;
2231 }
2232}
2233
Andy Hung9d84af52018-09-12 18:03:44 -07002234// ----------------------------------------------------------------------------
2235#undef LOG_TAG
2236#define LOG_TAG "AF::PatchRecord"
2237
Eric Laurent83b88082014-06-20 18:31:16 -07002238AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2239 uint32_t sampleRate,
2240 audio_channel_mask_t channelMask,
2241 audio_format_t format,
2242 size_t frameCount,
2243 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07002244 size_t bufferSize,
Kevin Rocard45986c72018-12-18 18:22:59 -08002245 audio_input_flags_t flags,
2246 const Timeout& timeout)
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002247 : RecordTrack(recordThread, NULL,
2248 audio_attributes_t{} /* currently unused for patch track */,
2249 sampleRate, format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002250 buffer, bufferSize, AUDIO_SESSION_NONE, getpid(), AID_AUDIOSERVER,
Andy Hung4ef19fa2018-05-15 19:35:29 -07002251 flags, TYPE_PATCH),
Kevin Rocard45986c72018-12-18 18:22:59 -08002252 PatchTrackBase(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true),
2253 *recordThread, timeout)
Eric Laurent83b88082014-06-20 18:31:16 -07002254{
Andy Hung9d84af52018-09-12 18:03:44 -07002255 ALOGV("%s(%d): sampleRate %d mPeerTimeout %d.%03d sec",
2256 __func__, mId, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07002257 (int)mPeerTimeout.tv_sec,
2258 (int)(mPeerTimeout.tv_nsec / 1000000));
2259}
2260
2261AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2262{
Andy Hungabfab202019-03-07 19:45:54 -08002263 ALOGV("%s(%d)", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002264}
2265
2266// AudioBufferProvider interface
2267status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08002268 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07002269{
Andy Hung9d84af52018-09-12 18:03:44 -07002270 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002271 Proxy::Buffer buf;
2272 buf.mFrameCount = buffer->frameCount;
2273 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2274 ALOGV_IF(status != NO_ERROR,
Andy Hung9d84af52018-09-12 18:03:44 -07002275 "%s(%d): mPeerProxy->obtainBuffer status %d", __func__, mId, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002276 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002277 if (buf.mFrameCount == 0) {
2278 return WOULD_BLOCK;
2279 }
Glenn Kastend79072e2016-01-06 08:41:20 -08002280 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07002281 return status;
2282}
2283
2284void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2285{
Andy Hung9d84af52018-09-12 18:03:44 -07002286 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002287 Proxy::Buffer buf;
2288 buf.mFrameCount = buffer->frameCount;
2289 buf.mRaw = buffer->raw;
2290 mPeerProxy->releaseBuffer(&buf);
2291 TrackBase::releaseBuffer(buffer);
2292}
2293
2294status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2295 const struct timespec *timeOut)
2296{
2297 return mProxy->obtainBuffer(buffer, timeOut);
2298}
2299
2300void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2301{
2302 mProxy->releaseBuffer(buffer);
2303}
2304
Andy Hung9d84af52018-09-12 18:03:44 -07002305// ----------------------------------------------------------------------------
2306#undef LOG_TAG
2307#define LOG_TAG "AF::MmapTrack"
Eric Laurent6acd1d42017-01-04 14:23:29 -08002308
2309AudioFlinger::MmapThread::MmapTrack::MmapTrack(ThreadBase *thread,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002310 const audio_attributes_t& attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002311 uint32_t sampleRate,
2312 audio_format_t format,
2313 audio_channel_mask_t channelMask,
2314 audio_session_t sessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002315 bool isOut,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002316 uid_t uid,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002317 pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002318 pid_t creatorPid,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002319 audio_port_handle_t portId)
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002320 : TrackBase(thread, NULL, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002321 channelMask, (size_t)0 /* frameCount */,
2322 nullptr /* buffer */, (size_t)0 /* bufferSize */,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002323 sessionId, creatorPid, uid, isOut,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002324 ALLOC_NONE,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002325 TYPE_DEFAULT, portId),
Eric Laurent331679c2018-04-16 17:03:16 -07002326 mPid(pid), mSilenced(false), mSilencedNotified(false)
Eric Laurent6acd1d42017-01-04 14:23:29 -08002327{
2328}
2329
2330AudioFlinger::MmapThread::MmapTrack::~MmapTrack()
2331{
2332}
2333
2334status_t AudioFlinger::MmapThread::MmapTrack::initCheck() const
2335{
2336 return NO_ERROR;
2337}
2338
2339status_t AudioFlinger::MmapThread::MmapTrack::start(AudioSystem::sync_event_t event __unused,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002340 audio_session_t triggerSession __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08002341{
2342 return NO_ERROR;
2343}
2344
2345void AudioFlinger::MmapThread::MmapTrack::stop()
2346{
2347}
2348
2349// AudioBufferProvider interface
2350status_t AudioFlinger::MmapThread::MmapTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
2351{
2352 buffer->frameCount = 0;
2353 buffer->raw = nullptr;
2354 return INVALID_OPERATION;
2355}
2356
2357// ExtendedAudioBufferProvider interface
2358size_t AudioFlinger::MmapThread::MmapTrack::framesReady() const {
2359 return 0;
2360}
2361
2362int64_t AudioFlinger::MmapThread::MmapTrack::framesReleased() const
2363{
2364 return 0;
2365}
2366
2367void AudioFlinger::MmapThread::MmapTrack::onTimestamp(const ExtendedTimestamp &timestamp __unused)
2368{
2369}
2370
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002371void AudioFlinger::MmapThread::MmapTrack::appendDumpHeader(String8& result)
Eric Laurent6acd1d42017-01-04 14:23:29 -08002372{
Eric Laurent973db022018-11-20 14:54:31 -08002373 result.appendFormat("Client Session Port Id Format Chn mask SRate Flags %s\n",
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002374 isOut() ? "Usg CT": "Source");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002375}
2376
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002377void AudioFlinger::MmapThread::MmapTrack::appendDump(String8& result, bool active __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08002378{
Eric Laurent973db022018-11-20 14:54:31 -08002379 result.appendFormat("%6u %7u %7u %08X %08X %6u 0x%03X ",
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002380 mPid,
2381 mSessionId,
Eric Laurent973db022018-11-20 14:54:31 -08002382 mPortId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002383 mFormat,
2384 mChannelMask,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002385 mSampleRate,
2386 mAttr.flags);
2387 if (isOut()) {
2388 result.appendFormat("%3x %2x", mAttr.usage, mAttr.content_type);
2389 } else {
2390 result.appendFormat("%6x", mAttr.source);
2391 }
2392 result.append("\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002393}
2394
Glenn Kasten63238ef2015-03-02 15:50:29 -08002395} // namespace android