blob: 297147e2dd834c8b08efc2dee52387d23b1c80d3 [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
Mikhail Naganov938be412019-09-04 11:38:47 -070021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Glenn Kastenad8510a2015-02-17 16:24:07 -080024#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080025#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070026#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <utils/Log.h>
Mikhail Naganov938be412019-09-04 11:38:47 -070028#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029
30#include <private/media/AudioTrackShared.h>
31
Eric Laurent81784c32012-11-19 14:55:58 -080032#include "AudioFlinger.h"
Andy Hung11e74242023-06-26 19:20:57 -070033#include "TrackBase.h"
34#include "PlaybackTracks.h"
35#include "RecordTracks.h"
36#include "MmapTracks.h"
Eric Laurent81784c32012-11-19 14:55:58 -080037
Glenn Kastenda6ef132013-01-10 12:31:01 -080038#include <media/nbaio/Pipe.h>
39#include <media/nbaio/PipeReader.h>
Kuowei Lid4adbdb2020-08-13 14:44:25 +080040#include <media/AudioValidator.h>
Andy Hung89816052017-01-11 17:08:23 -080041#include <media/RecordBufferConverter.h>
Andy Hungab7ef302018-05-15 19:35:29 -070042#include <mediautils/ServiceUtilities.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070043#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080044
Eric Laurent81784c32012-11-19 14:55:58 -080045// ----------------------------------------------------------------------------
46
47// Note: the following macro is used for extremely verbose logging message. In
48// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
49// 0; but one side effect of this is to turn all LOGV's as well. Some messages
50// are so verbose that we want to suppress them even when we have ALOG_ASSERT
51// turned on. Do not uncomment the #def below unless you really know what you
52// are doing and want to see all of the extremely verbose messages.
53//#define VERY_VERY_VERBOSE_LOGGING
54#ifdef VERY_VERY_VERBOSE_LOGGING
55#define ALOGVV ALOGV
56#else
57#define ALOGVV(a...) do { } while(0)
58#endif
59
Kuowei Lid4adbdb2020-08-13 14:44:25 +080060// TODO: Remove when this is put into AidlConversionUtil.h
61#define VALUE_OR_RETURN_BINDER_STATUS(x) \
62 ({ \
63 auto _tmp = (x); \
64 if (!_tmp.ok()) return ::android::aidl_utils::binderStatusFromStatusT(_tmp.error()); \
65 std::move(_tmp.value()); \
66 })
67
Eric Laurent81784c32012-11-19 14:55:58 -080068namespace android {
69
Kuowei Lid4adbdb2020-08-13 14:44:25 +080070using ::android::aidl_utils::binderStatusFromStatusT;
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -080071using binder::Status;
Svet Ganov33761132021-05-13 22:51:08 +000072using content::AttributionSourceState;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070073using media::VolumeShaper;
Eric Laurent81784c32012-11-19 14:55:58 -080074// ----------------------------------------------------------------------------
75// TrackBase
76// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -070077#undef LOG_TAG
78#define LOG_TAG "AF::TrackBase"
Eric Laurent81784c32012-11-19 14:55:58 -080079
Glenn Kastenda6ef132013-01-10 12:31:01 -080080static volatile int32_t nextTrackId = 55;
81
Eric Laurent81784c32012-11-19 14:55:58 -080082// TrackBase constructor must be called with AudioFlinger::mLock held
Andy Hung11e74242023-06-26 19:20:57 -070083TrackBase::TrackBase(
Andy Hung0c1e11e2023-07-06 20:56:16 -070084 IAfThreadBase *thread,
Eric Laurent81784c32012-11-19 14:55:58 -080085 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -070086 const audio_attributes_t& attr,
Eric Laurent81784c32012-11-19 14:55:58 -080087 uint32_t sampleRate,
88 audio_format_t format,
89 audio_channel_mask_t channelMask,
90 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070091 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -070092 size_t bufferSize,
Glenn Kastend848eb42016-03-08 13:42:11 -080093 audio_session_t sessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -070094 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -080095 uid_t clientUid,
Glenn Kastend776ac62014-05-07 09:16:09 -070096 bool isOut,
Dmitry Sidorenkova41c2732023-05-15 13:47:07 -070097 const alloc_type alloc,
Eric Laurent20b9ef02016-12-05 11:03:16 -080098 track_type type,
Andy Hungb68f5eb2019-12-03 16:49:17 -080099 audio_port_handle_t portId,
100 std::string metricsId)
Andy Hungfafbebc2023-06-23 19:27:19 -0700101 :
Eric Laurent81784c32012-11-19 14:55:58 -0800102 mThread(thread),
Dmitry Sidorenkova41c2732023-05-15 13:47:07 -0700103 mAllocType(alloc),
Eric Laurent81784c32012-11-19 14:55:58 -0800104 mClient(client),
105 mCblk(NULL),
Andy Hung8fe68032017-06-05 16:17:51 -0700106 // mBuffer, mBufferSize
Eric Laurent81784c32012-11-19 14:55:58 -0800107 mState(IDLE),
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700108 mAttr(attr),
Eric Laurent81784c32012-11-19 14:55:58 -0800109 mSampleRate(sampleRate),
110 mFormat(format),
111 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -0700112 mChannelCount(isOut ?
113 audio_channel_count_from_out_mask(channelMask) :
114 audio_channel_count_from_in_mask(channelMask)),
Phil Burkfdb3c072016-02-09 10:47:02 -0800115 mFrameSize(audio_has_proportional_frames(format) ?
Eric Laurent81784c32012-11-19 14:55:58 -0800116 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
117 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -0800118 mSessionId(sessionId),
119 mIsOut(isOut),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800120 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -0700121 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -0700122 mType(type),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800123 mThreadIoHandle(thread ? thread->id() : AUDIO_IO_HANDLE_NONE),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800124 mPortId(portId),
Eric Laurent09f1ed22019-04-24 17:45:17 -0700125 mIsInvalid(false),
Kunal Malhotra3be68902023-02-28 22:03:15 +0000126 mTrackMetrics(std::move(metricsId), isOut, clientUid),
Eric Laurent09f1ed22019-04-24 17:45:17 -0700127 mCreatorPid(creatorPid)
Eric Laurent81784c32012-11-19 14:55:58 -0800128{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700129 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -0700130 if (!isAudioServerOrMediaServerUid(callingUid) || clientUid == AUDIO_UID_INVALID) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800131 ALOGW_IF(clientUid != AUDIO_UID_INVALID && clientUid != callingUid,
Andy Hung9d84af52018-09-12 18:03:44 -0700132 "%s(%d): uid %d tried to pass itself off as %d",
133 __func__, mId, callingUid, clientUid);
Andy Hung1f12a8a2016-11-07 16:10:30 -0800134 clientUid = callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800135 }
136 // clientUid contains the uid of the app that is responsible for this track, so we can blame
137 // battery usage on it.
138 mUid = clientUid;
139
Eric Laurent81784c32012-11-19 14:55:58 -0800140 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hung1883f692017-02-13 18:48:39 -0800141
Andy Hung8fe68032017-06-05 16:17:51 -0700142 size_t minBufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
Andy Hung1883f692017-02-13 18:48:39 -0800143 // check overflow when computing bufferSize due to multiplication by mFrameSize.
Andy Hung8fe68032017-06-05 16:17:51 -0700144 if (minBufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
Andy Hung1883f692017-02-13 18:48:39 -0800145 || mFrameSize == 0 // format needs to be correct
Andy Hung8fe68032017-06-05 16:17:51 -0700146 || minBufferSize > SIZE_MAX / mFrameSize) {
Andy Hung1883f692017-02-13 18:48:39 -0800147 android_errorWriteLog(0x534e4554, "34749571");
148 return;
149 }
Andy Hung8fe68032017-06-05 16:17:51 -0700150 minBufferSize *= mFrameSize;
151
152 if (buffer == nullptr) {
153 bufferSize = minBufferSize; // allocated here.
154 } else if (minBufferSize > bufferSize) {
155 android_errorWriteLog(0x534e4554, "38340117");
156 return;
157 }
Andy Hung1883f692017-02-13 18:48:39 -0800158
Eric Laurent81784c32012-11-19 14:55:58 -0800159 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700160 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hung1883f692017-02-13 18:48:39 -0800161 // check overflow when computing allocation size for streaming tracks.
162 if (size > SIZE_MAX - bufferSize) {
163 android_errorWriteLog(0x534e4554, "34749571");
164 return;
165 }
Eric Laurent81784c32012-11-19 14:55:58 -0800166 size += bufferSize;
167 }
168
169 if (client != 0) {
Atneya3c61d882021-09-20 14:52:15 -0400170 mCblkMemory = client->allocator().allocate(mediautils::NamedAllocRequest{{size},
171 std::string("Track ID: ").append(std::to_string(mId))});
Glenn Kasten663c2242013-09-24 11:52:37 -0700172 if (mCblkMemory == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700173 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->unsecurePointer())) == NULL) {
Andy Hung9d84af52018-09-12 18:03:44 -0700174 ALOGE("%s(%d): not enough memory for AudioTrack size=%zu", __func__, mId, size);
Atneya3c61d882021-09-20 14:52:15 -0400175 ALOGE("%s", client->allocator().dump().c_str());
Glenn Kasten663c2242013-09-24 11:52:37 -0700176 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800177 return;
178 }
179 } else {
Andy Hungafb31482017-02-13 18:50:48 -0800180 mCblk = (audio_track_cblk_t *) malloc(size);
181 if (mCblk == NULL) {
Andy Hung9d84af52018-09-12 18:03:44 -0700182 ALOGE("%s(%d): not enough memory for AudioTrack size=%zu", __func__, mId, size);
Andy Hungafb31482017-02-13 18:50:48 -0800183 return;
184 }
Eric Laurent81784c32012-11-19 14:55:58 -0800185 }
186
187 // construct the shared structure in-place.
188 if (mCblk != NULL) {
189 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700190 switch (alloc) {
191 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700192 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
193 if (roHeap == 0 ||
194 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700195 (mBuffer = mBufferMemory->unsecurePointer()) == NULL) {
Andy Hung9d84af52018-09-12 18:03:44 -0700196 ALOGE("%s(%d): not enough memory for read-only buffer size=%zu",
197 __func__, mId, bufferSize);
Glenn Kastend776ac62014-05-07 09:16:09 -0700198 if (roHeap != 0) {
199 roHeap->dump("buffer");
200 }
201 mCblkMemory.clear();
202 mBufferMemory.clear();
203 return;
204 }
Eric Laurent81784c32012-11-19 14:55:58 -0800205 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700206 } break;
207 case ALLOC_PIPE:
208 mBufferMemory = thread->pipeMemory();
209 // mBuffer is the virtual address as seen from current process (mediaserver),
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700210 // and should normally be coming from mBufferMemory->unsecurePointer().
Glenn Kastenc263ca02014-06-04 20:31:46 -0700211 // However in this case the TrackBase does not reference the buffer directly.
212 // It should references the buffer via the pipe.
213 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
214 mBuffer = NULL;
Andy Hung8fe68032017-06-05 16:17:51 -0700215 bufferSize = 0;
Glenn Kastenc263ca02014-06-04 20:31:46 -0700216 break;
217 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700218 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700219 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700220 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
221 memset(mBuffer, 0, bufferSize);
222 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700223 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800224#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700225 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800226#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700227 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700228 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700229 case ALLOC_LOCAL:
230 mBuffer = calloc(1, bufferSize);
231 break;
232 case ALLOC_NONE:
233 mBuffer = buffer;
234 break;
Andy Hung8fe68032017-06-05 16:17:51 -0700235 default:
Andy Hung9d84af52018-09-12 18:03:44 -0700236 LOG_ALWAYS_FATAL("%s(%d): invalid allocation type: %d", __func__, mId, (int)alloc);
Eric Laurent81784c32012-11-19 14:55:58 -0800237 }
Andy Hung8fe68032017-06-05 16:17:51 -0700238 mBufferSize = bufferSize;
Glenn Kastenda6ef132013-01-10 12:31:01 -0800239
Glenn Kasten46909e72013-02-26 09:20:22 -0800240#ifdef TEE_SINK
Andy Hung8946a282018-04-19 20:04:56 -0700241 mTee.set(sampleRate, mChannelCount, format, NBAIO_Tee::TEE_FLAG_TRACK);
Glenn Kasten46909e72013-02-26 09:20:22 -0800242#endif
Andy Hung959b5b82021-09-24 10:46:20 -0700243 // mState is mirrored for the client to read.
244 mState.setMirror(&mCblk->mState);
245 // ensure our state matches up until we consolidate the enumeration.
246 static_assert(CBLK_STATE_IDLE == IDLE);
247 static_assert(CBLK_STATE_PAUSING == PAUSING);
Eric Laurent81784c32012-11-19 14:55:58 -0800248 }
249}
250
Svet Ganov33761132021-05-13 22:51:08 +0000251// TODO b/182392769: use attribution source util
252static AttributionSourceState audioServerAttributionSource(pid_t pid) {
253 AttributionSourceState attributionSource{};
254 attributionSource.uid = AID_AUDIOSERVER;
255 attributionSource.pid = pid;
256 attributionSource.token = sp<BBinder>::make();
257 return attributionSource;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700258}
259
Andy Hung11e74242023-06-26 19:20:57 -0700260status_t TrackBase::initCheck() const
Eric Laurent83b88082014-06-20 18:31:16 -0700261{
262 status_t status;
263 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
264 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
265 } else {
266 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
267 }
268 return status;
269}
270
Andy Hung11e74242023-06-26 19:20:57 -0700271TrackBase::~TrackBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800272{
Glenn Kastene3aa6592012-12-04 12:22:46 -0800273 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
Eric Laurent5bba2f62016-03-18 11:14:14 -0700274 mServerProxy.clear();
Andy Hung689e82c2019-08-21 17:53:17 -0700275 releaseCblk();
Eric Laurent81784c32012-11-19 14:55:58 -0800276 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
277 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700278 // Client destructor must run with AudioFlinger client mutex locked
Andy Hunga9b24592023-07-17 12:40:43 -0700279 Mutex::Autolock _l(mClient->afClientCallback()->clientMutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800280 // If the client's reference count drops to zero, the associated destructor
281 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
282 // relying on the automatic clear() at end of scope.
283 mClient.clear();
284 }
Dmitry Sidorenkova41c2732023-05-15 13:47:07 -0700285 if (mAllocType == ALLOC_LOCAL) {
286 free(mBuffer);
287 mBuffer = nullptr;
288 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700289 // flush the binder command buffer
290 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800291}
292
293// AudioBufferProvider interface
294// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800295// This implementation of releaseBuffer() is used by Track and RecordTrack
Andy Hung11e74242023-06-26 19:20:57 -0700296void TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800297{
Glenn Kasten46909e72013-02-26 09:20:22 -0800298#ifdef TEE_SINK
Andy Hung8946a282018-04-19 20:04:56 -0700299 mTee.write(buffer->raw, buffer->frameCount);
Glenn Kasten46909e72013-02-26 09:20:22 -0800300#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800301
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800302 ServerProxy::Buffer buf;
303 buf.mFrameCount = buffer->frameCount;
304 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800305 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800306 buffer->raw = NULL;
307 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800308}
309
Andy Hung11e74242023-06-26 19:20:57 -0700310status_t TrackBase::setSyncEvent(
Andy Hung068e08e2023-05-15 19:02:55 -0700311 const sp<audioflinger::SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -0800312{
Andy Hung068e08e2023-05-15 19:02:55 -0700313 mSyncEvents.emplace_back(event);
Eric Laurent81784c32012-11-19 14:55:58 -0800314 return NO_ERROR;
315}
316
Andy Hung11e74242023-06-26 19:20:57 -0700317PatchTrackBase::PatchTrackBase(const sp<ClientProxy>& proxy,
Andy Hung7e888b32023-07-14 16:57:01 -0700318 IAfThreadBase* thread, const Timeout& timeout)
Kevin Rocard45986c72018-12-18 18:22:59 -0800319 : mProxy(proxy)
320{
321 if (timeout) {
322 setPeerTimeout(*timeout);
323 } else {
324 // Double buffer mixer
Andy Hung7e888b32023-07-14 16:57:01 -0700325 uint64_t mixBufferNs = ((uint64_t)2 * thread->frameCount() * 1000000000) /
326 thread->sampleRate();
Kevin Rocard45986c72018-12-18 18:22:59 -0800327 setPeerTimeout(std::chrono::nanoseconds{mixBufferNs});
328 }
329}
330
Andy Hung11e74242023-06-26 19:20:57 -0700331void PatchTrackBase::setPeerTimeout(std::chrono::nanoseconds timeout) {
Kevin Rocard45986c72018-12-18 18:22:59 -0800332 mPeerTimeout.tv_sec = timeout.count() / std::nano::den;
333 mPeerTimeout.tv_nsec = timeout.count() % std::nano::den;
334}
335
336
Eric Laurent81784c32012-11-19 14:55:58 -0800337// ----------------------------------------------------------------------------
338// Playback
339// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -0700340#undef LOG_TAG
341#define LOG_TAG "AF::TrackHandle"
Eric Laurent81784c32012-11-19 14:55:58 -0800342
Andy Hunga6426302023-06-23 19:27:19 -0700343class TrackHandle : public android::media::BnAudioTrack {
344public:
Andy Hungfafbebc2023-06-23 19:27:19 -0700345 explicit TrackHandle(const sp<IAfTrack>& track);
Andy Hunga6426302023-06-23 19:27:19 -0700346 ~TrackHandle() override;
347
348 binder::Status getCblk(std::optional<media::SharedFileRegion>* _aidl_return) final;
349 binder::Status start(int32_t* _aidl_return) final;
350 binder::Status stop() final;
351 binder::Status flush() final;
352 binder::Status pause() final;
353 binder::Status attachAuxEffect(int32_t effectId, int32_t* _aidl_return) final;
354 binder::Status setParameters(const std::string& keyValuePairs,
355 int32_t* _aidl_return) final;
356 binder::Status selectPresentation(int32_t presentationId, int32_t programId,
357 int32_t* _aidl_return) final;
358 binder::Status getTimestamp(media::AudioTimestampInternal* timestamp,
359 int32_t* _aidl_return) final;
360 binder::Status signal() final;
361 binder::Status applyVolumeShaper(const media::VolumeShaperConfiguration& configuration,
362 const media::VolumeShaperOperation& operation,
363 int32_t* _aidl_return) final;
364 binder::Status getVolumeShaperState(
365 int32_t id,
366 std::optional<media::VolumeShaperState>* _aidl_return) final;
367 binder::Status getDualMonoMode(
368 media::audio::common::AudioDualMonoMode* _aidl_return) final;
369 binder::Status setDualMonoMode(
370 media::audio::common::AudioDualMonoMode mode) final;
371 binder::Status getAudioDescriptionMixLevel(float* _aidl_return) final;
372 binder::Status setAudioDescriptionMixLevel(float leveldB) final;
373 binder::Status getPlaybackRateParameters(
374 media::audio::common::AudioPlaybackRate* _aidl_return) final;
375 binder::Status setPlaybackRateParameters(
376 const media::audio::common::AudioPlaybackRate& playbackRate) final;
377
378private:
Andy Hungfafbebc2023-06-23 19:27:19 -0700379 const sp<IAfTrack> mTrack;
Andy Hunga6426302023-06-23 19:27:19 -0700380};
381
382/* static */
Andy Hungfafbebc2023-06-23 19:27:19 -0700383sp<media::IAudioTrack> IAfTrack::createIAudioTrackAdapter(const sp<IAfTrack>& track) {
Andy Hunga6426302023-06-23 19:27:19 -0700384 return sp<TrackHandle>::make(track);
385}
386
Andy Hungfafbebc2023-06-23 19:27:19 -0700387TrackHandle::TrackHandle(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -0800388 : BnAudioTrack(),
389 mTrack(track)
390{
Andy Hung225aef62022-12-06 16:33:20 -0800391 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -0800392}
393
Andy Hunga6426302023-06-23 19:27:19 -0700394TrackHandle::~TrackHandle() {
Eric Laurent81784c32012-11-19 14:55:58 -0800395 // just stop the track on deletion, associated resources
396 // will be freed from the main thread once all pending buffers have
397 // been played. Unless it's not in the active track list, in which
398 // case we free everything now...
399 mTrack->destroy();
400}
401
Andy Hunga6426302023-06-23 19:27:19 -0700402Status TrackHandle::getCblk(
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800403 std::optional<media::SharedFileRegion>* _aidl_return) {
404 *_aidl_return = legacy2aidl_NullableIMemory_SharedFileRegion(mTrack->getCblk()).value();
405 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800406}
407
Andy Hunga6426302023-06-23 19:27:19 -0700408Status TrackHandle::start(int32_t* _aidl_return) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800409 *_aidl_return = mTrack->start();
410 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800411}
412
Andy Hunga6426302023-06-23 19:27:19 -0700413Status TrackHandle::stop() {
Eric Laurent81784c32012-11-19 14:55:58 -0800414 mTrack->stop();
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800415 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800416}
417
Andy Hunga6426302023-06-23 19:27:19 -0700418Status TrackHandle::flush() {
Eric Laurent81784c32012-11-19 14:55:58 -0800419 mTrack->flush();
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800420 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800421}
422
Andy Hunga6426302023-06-23 19:27:19 -0700423Status TrackHandle::pause() {
Eric Laurent81784c32012-11-19 14:55:58 -0800424 mTrack->pause();
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800425 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800426}
427
Andy Hunga6426302023-06-23 19:27:19 -0700428Status TrackHandle::attachAuxEffect(int32_t effectId,
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800429 int32_t* _aidl_return) {
430 *_aidl_return = mTrack->attachAuxEffect(effectId);
431 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800432}
433
Andy Hunga6426302023-06-23 19:27:19 -0700434Status TrackHandle::setParameters(const std::string& keyValuePairs,
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800435 int32_t* _aidl_return) {
436 *_aidl_return = mTrack->setParameters(String8(keyValuePairs.c_str()));
437 return Status::ok();
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700438}
439
Andy Hunga6426302023-06-23 19:27:19 -0700440Status TrackHandle::selectPresentation(int32_t presentationId, int32_t programId,
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800441 int32_t* _aidl_return) {
442 *_aidl_return = mTrack->selectPresentation(presentationId, programId);
443 return Status::ok();
Mikhail Naganovac917ac2018-11-28 14:03:52 -0800444}
445
Andy Hunga6426302023-06-23 19:27:19 -0700446Status TrackHandle::getTimestamp(media::AudioTimestampInternal* timestamp,
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800447 int32_t* _aidl_return) {
448 AudioTimestamp legacy;
449 *_aidl_return = mTrack->getTimestamp(legacy);
450 if (*_aidl_return != OK) {
451 return Status::ok();
452 }
Andy Hung973638a2020-12-08 20:47:45 -0800453 *timestamp = legacy2aidl_AudioTimestamp_AudioTimestampInternal(legacy).value();
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800454 return Status::ok();
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800455}
456
Andy Hunga6426302023-06-23 19:27:19 -0700457Status TrackHandle::signal() {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800458 mTrack->signal();
459 return Status::ok();
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800460}
461
Andy Hunga6426302023-06-23 19:27:19 -0700462Status TrackHandle::applyVolumeShaper(
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800463 const media::VolumeShaperConfiguration& configuration,
464 const media::VolumeShaperOperation& operation,
465 int32_t* _aidl_return) {
466 sp<VolumeShaper::Configuration> conf = new VolumeShaper::Configuration();
467 *_aidl_return = conf->readFromParcelable(configuration);
468 if (*_aidl_return != OK) {
469 return Status::ok();
470 }
471
472 sp<VolumeShaper::Operation> op = new VolumeShaper::Operation();
473 *_aidl_return = op->readFromParcelable(operation);
474 if (*_aidl_return != OK) {
475 return Status::ok();
476 }
477
478 *_aidl_return = mTrack->applyVolumeShaper(conf, op);
479 return Status::ok();
Glenn Kasten53cec222013-08-29 09:01:02 -0700480}
481
Andy Hunga6426302023-06-23 19:27:19 -0700482Status TrackHandle::getVolumeShaperState(
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800483 int32_t id,
484 std::optional<media::VolumeShaperState>* _aidl_return) {
485 sp<VolumeShaper::State> legacy = mTrack->getVolumeShaperState(id);
486 if (legacy == nullptr) {
487 _aidl_return->reset();
488 return Status::ok();
489 }
490 media::VolumeShaperState aidl;
491 legacy->writeToParcelable(&aidl);
492 *_aidl_return = aidl;
493 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800494}
495
Andy Hunga6426302023-06-23 19:27:19 -0700496Status TrackHandle::getDualMonoMode(
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000497 media::audio::common::AudioDualMonoMode* _aidl_return)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800498{
499 audio_dual_mono_mode_t mode = AUDIO_DUAL_MONO_MODE_OFF;
500 const status_t status = mTrack->getDualMonoMode(&mode)
501 ?: AudioValidator::validateDualMonoMode(mode);
502 if (status == OK) {
503 *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
504 legacy2aidl_audio_dual_mono_mode_t_AudioDualMonoMode(mode));
505 }
506 return binderStatusFromStatusT(status);
507}
508
Andy Hunga6426302023-06-23 19:27:19 -0700509Status TrackHandle::setDualMonoMode(
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000510 media::audio::common::AudioDualMonoMode mode)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800511{
512 const auto localMonoMode = VALUE_OR_RETURN_BINDER_STATUS(
513 aidl2legacy_AudioDualMonoMode_audio_dual_mono_mode_t(mode));
514 return binderStatusFromStatusT(AudioValidator::validateDualMonoMode(localMonoMode)
515 ?: mTrack->setDualMonoMode(localMonoMode));
516}
517
Andy Hunga6426302023-06-23 19:27:19 -0700518Status TrackHandle::getAudioDescriptionMixLevel(float* _aidl_return)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800519{
520 float leveldB = -std::numeric_limits<float>::infinity();
521 const status_t status = mTrack->getAudioDescriptionMixLevel(&leveldB)
522 ?: AudioValidator::validateAudioDescriptionMixLevel(leveldB);
523 if (status == OK) *_aidl_return = leveldB;
524 return binderStatusFromStatusT(status);
525}
526
Andy Hunga6426302023-06-23 19:27:19 -0700527Status TrackHandle::setAudioDescriptionMixLevel(float leveldB)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800528{
529 return binderStatusFromStatusT(AudioValidator::validateAudioDescriptionMixLevel(leveldB)
530 ?: mTrack->setAudioDescriptionMixLevel(leveldB));
531}
532
Andy Hunga6426302023-06-23 19:27:19 -0700533Status TrackHandle::getPlaybackRateParameters(
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000534 media::audio::common::AudioPlaybackRate* _aidl_return)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800535{
536 audio_playback_rate_t localPlaybackRate{};
537 status_t status = mTrack->getPlaybackRateParameters(&localPlaybackRate)
538 ?: AudioValidator::validatePlaybackRate(localPlaybackRate);
539 if (status == NO_ERROR) {
540 *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
541 legacy2aidl_audio_playback_rate_t_AudioPlaybackRate(localPlaybackRate));
542 }
543 return binderStatusFromStatusT(status);
544}
545
Andy Hunga6426302023-06-23 19:27:19 -0700546Status TrackHandle::setPlaybackRateParameters(
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000547 const media::audio::common::AudioPlaybackRate& playbackRate)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800548{
549 const audio_playback_rate_t localPlaybackRate = VALUE_OR_RETURN_BINDER_STATUS(
550 aidl2legacy_AudioPlaybackRate_audio_playback_rate_t(playbackRate));
551 return binderStatusFromStatusT(AudioValidator::validatePlaybackRate(localPlaybackRate)
552 ?: mTrack->setPlaybackRateParameters(localPlaybackRate));
553}
554
Eric Laurent81784c32012-11-19 14:55:58 -0800555// ----------------------------------------------------------------------------
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800556// AppOp for audio playback
557// -------------------------------
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700558
559// static
Andy Hung11e74242023-06-26 19:20:57 -0700560sp<OpPlayAudioMonitor> OpPlayAudioMonitor::createIfNeeded(
Andy Hung0c1e11e2023-07-06 20:56:16 -0700561 IAfThreadBase* thread,
Svet Ganov33761132021-05-13 22:51:08 +0000562 const AttributionSourceState& attributionSource, const audio_attributes_t& attr, int id,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700563 audio_stream_type_t streamType)
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800564{
Vlad Popa103be862023-07-10 20:27:41 -0700565 Vector<String16> packages;
566 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000567 getPackagesForUid(uid, packages);
Eric Laurent9066ad32019-05-20 14:40:10 -0700568 if (isServiceUid(uid)) {
Eric Laurent9066ad32019-05-20 14:40:10 -0700569 if (packages.isEmpty()) {
570 ALOGD("OpPlayAudio: not muting track:%d usage:%d for service UID %d",
571 id,
572 attr.usage,
573 uid);
574 return nullptr;
575 }
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800576 }
577 // stream type has been filtered by audio policy to indicate whether it can be muted
578 if (streamType == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Eric Laurent2dab0302019-05-08 18:15:55 -0700579 ALOGD("OpPlayAudio: not muting track:%d usage:%d ENFORCED_AUDIBLE", id, attr.usage);
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700580 return nullptr;
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800581 }
Eric Laurent2dab0302019-05-08 18:15:55 -0700582 if ((attr.flags & AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY)
583 == AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY) {
584 ALOGD("OpPlayAudio: not muting track:%d flags %#x have FLAG_BYPASS_INTERRUPTION_POLICY",
585 id, attr.flags);
586 return nullptr;
587 }
Vlad Popa103be862023-07-10 20:27:41 -0700588 return sp<OpPlayAudioMonitor>::make(thread, attributionSource, attr.usage, id, uid);
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700589}
590
Andy Hung0c1e11e2023-07-06 20:56:16 -0700591OpPlayAudioMonitor::OpPlayAudioMonitor(IAfThreadBase* thread,
592 const AttributionSourceState& attributionSource,
593 audio_usage_t usage, int id, uid_t uid)
594 : mThread(wp<IAfThreadBase>::fromExisting(thread)),
Vlad Popa103be862023-07-10 20:27:41 -0700595 mHasOpPlayAudio(true),
596 mAttributionSource(attributionSource),
597 mUsage((int32_t)usage),
598 mId(id),
599 mUid(uid),
600 mPackageName(VALUE_OR_FATAL(aidl2legacy_string_view_String16(
601 attributionSource.packageName.value_or("")))) {}
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800602
Andy Hung11e74242023-06-26 19:20:57 -0700603OpPlayAudioMonitor::~OpPlayAudioMonitor()
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800604{
605 if (mOpCallback != 0) {
606 mAppOpsManager.stopWatchingMode(mOpCallback);
607 }
608 mOpCallback.clear();
609}
610
Andy Hung11e74242023-06-26 19:20:57 -0700611void OpPlayAudioMonitor::onFirstRef()
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700612{
Vlad Popa4ec78f52023-08-02 18:36:04 -0700613 // make sure not to broadcast the initial state since it is not needed and could
614 // cause a deadlock since this method can be called with the mThread->mLock held
615 checkPlayAudioForUsage(/*doBroadcast=*/false);
Svet Ganov33761132021-05-13 22:51:08 +0000616 if (mAttributionSource.packageName.has_value()) {
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700617 mOpCallback = new PlayAudioOpCallback(this);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700618 mAppOpsManager.startWatchingMode(AppOpsManager::OP_PLAY_AUDIO,
Vlad Popa103be862023-07-10 20:27:41 -0700619 mPackageName, mOpCallback);
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700620 }
621}
622
Andy Hung11e74242023-06-26 19:20:57 -0700623bool OpPlayAudioMonitor::hasOpPlayAudio() const {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800624 return mHasOpPlayAudio.load();
625}
626
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -0700627// Note this method is never called (and never to be) for audio server / patch record track
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800628// - not called from constructor due to check on UID,
629// - not called from PlayAudioOpCallback because the callback is not installed in this case
Vlad Popa4ec78f52023-08-02 18:36:04 -0700630void OpPlayAudioMonitor::checkPlayAudioForUsage(bool doBroadcast)
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800631{
Vlad Popa103be862023-07-10 20:27:41 -0700632 const bool hasAppOps = mAttributionSource.packageName.has_value()
633 && mAppOpsManager.checkAudioOpNoThrow(
634 AppOpsManager::OP_PLAY_AUDIO, mUsage, mUid, mPackageName) ==
635 AppOpsManager::MODE_ALLOWED;
636
637 bool shouldChange = !hasAppOps; // check if we need to update.
638 if (mHasOpPlayAudio.compare_exchange_strong(shouldChange, hasAppOps)) {
639 ALOGD("OpPlayAudio: track:%d usage:%d %smuted", mId, mUsage, hasAppOps ? "not " : "");
Vlad Popa4ec78f52023-08-02 18:36:04 -0700640 if (doBroadcast) {
641 auto thread = mThread.promote();
642 if (thread != nullptr && thread->type() == IAfThreadBase::OFFLOAD) {
643 // Wake up Thread if offloaded, otherwise it may be several seconds for update.
644 Mutex::Autolock _l(thread->mutex());
645 thread->broadcast_l();
646 }
Vlad Popa103be862023-07-10 20:27:41 -0700647 }
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800648 }
649}
650
Andy Hung11e74242023-06-26 19:20:57 -0700651OpPlayAudioMonitor::PlayAudioOpCallback::PlayAudioOpCallback(
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800652 const wp<OpPlayAudioMonitor>& monitor) : mMonitor(monitor)
653{ }
654
Andy Hung11e74242023-06-26 19:20:57 -0700655void OpPlayAudioMonitor::PlayAudioOpCallback::opChanged(int32_t op,
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800656 const String16& packageName) {
657 // we only have uid, so we need to check all package names anyway
658 UNUSED(packageName);
659 if (op != AppOpsManager::OP_PLAY_AUDIO) {
660 return;
661 }
662 sp<OpPlayAudioMonitor> monitor = mMonitor.promote();
663 if (monitor != NULL) {
Vlad Popa4ec78f52023-08-02 18:36:04 -0700664 monitor->checkPlayAudioForUsage(/*doBroadcast=*/true);
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800665 }
666}
667
Eric Laurent9066ad32019-05-20 14:40:10 -0700668// static
Andy Hung11e74242023-06-26 19:20:57 -0700669void OpPlayAudioMonitor::getPackagesForUid(
Eric Laurent9066ad32019-05-20 14:40:10 -0700670 uid_t uid, Vector<String16>& packages)
671{
672 PermissionController permissionController;
673 permissionController.getPackagesForUid(uid, packages);
674}
675
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800676// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -0700677#undef LOG_TAG
678#define LOG_TAG "AF::Track"
Eric Laurent81784c32012-11-19 14:55:58 -0800679
Andy Hung11e74242023-06-26 19:20:57 -0700680/* static */
Andy Hung0c1e11e2023-07-06 20:56:16 -0700681sp<IAfTrack> IAfTrack::create(
682 IAfPlaybackThread* thread,
Andy Hung11e74242023-06-26 19:20:57 -0700683 const sp<Client>& client,
684 audio_stream_type_t streamType,
685 const audio_attributes_t& attr,
686 uint32_t sampleRate,
687 audio_format_t format,
688 audio_channel_mask_t channelMask,
689 size_t frameCount,
690 void *buffer,
691 size_t bufferSize,
692 const sp<IMemory>& sharedBuffer,
693 audio_session_t sessionId,
694 pid_t creatorPid,
695 const AttributionSourceState& attributionSource,
696 audio_output_flags_t flags,
697 track_type type,
698 audio_port_handle_t portId,
699 /** default behaviour is to start when there are as many frames
700 * ready as possible (aka. Buffer is full). */
701 size_t frameCountToBeReady,
702 float speed,
703 bool isSpatialized,
704 bool isBitPerfect) {
Andy Hung0c1e11e2023-07-06 20:56:16 -0700705 return sp<Track>::make(thread,
Andy Hung11e74242023-06-26 19:20:57 -0700706 client,
707 streamType,
708 attr,
709 sampleRate,
710 format,
711 channelMask,
712 frameCount,
713 buffer,
714 bufferSize,
715 sharedBuffer,
716 sessionId,
717 creatorPid,
718 attributionSource,
719 flags,
720 type,
721 portId,
722 frameCountToBeReady,
723 speed,
724 isSpatialized,
725 isBitPerfect);
726}
727
Eric Laurent81784c32012-11-19 14:55:58 -0800728// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Andy Hung11e74242023-06-26 19:20:57 -0700729Track::Track(
Andy Hung0c1e11e2023-07-06 20:56:16 -0700730 IAfPlaybackThread* thread,
Eric Laurent81784c32012-11-19 14:55:58 -0800731 const sp<Client>& client,
732 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700733 const audio_attributes_t& attr,
Eric Laurent81784c32012-11-19 14:55:58 -0800734 uint32_t sampleRate,
735 audio_format_t format,
736 audio_channel_mask_t channelMask,
737 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700738 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -0700739 size_t bufferSize,
Eric Laurent81784c32012-11-19 14:55:58 -0800740 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800741 audio_session_t sessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700742 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000743 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -0700744 audio_output_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800745 track_type type,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100746 audio_port_handle_t portId,
jiabinf042b9b2021-05-07 23:46:28 +0000747 size_t frameCountToBeReady,
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200748 float speed,
jiabinc658e452022-10-21 20:52:21 +0000749 bool isSpatialized,
750 bool isBitPerfect)
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700751 : TrackBase(thread, client, attr, sampleRate, format, channelMask, frameCount,
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700752 // TODO: Using unsecurePointer() has some associated security pitfalls
753 // (see declaration for details).
754 // Either document why it is safe in this case or address the
755 // issue (e.g. by copying).
756 (sharedBuffer != 0) ? sharedBuffer->unsecurePointer() : buffer,
Andy Hung8fe68032017-06-05 16:17:51 -0700757 (sharedBuffer != 0) ? sharedBuffer->size() : bufferSize,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700758 sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000759 VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)), true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700760 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
Andy Hungb68f5eb2019-12-03 16:49:17 -0800761 type,
762 portId,
763 std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK) + std::to_string(portId)),
Andy Hung11e74242023-06-26 19:20:57 -0700764 mFillingStatus(FS_INVALID),
Eric Laurent81784c32012-11-19 14:55:58 -0800765 // mRetryCount initialized later when needed
766 mSharedBuffer(sharedBuffer),
767 mStreamType(streamType),
rago94a1ee82017-07-21 15:11:02 -0700768 mMainBuffer(thread->sinkBuffer()),
Eric Laurent81784c32012-11-19 14:55:58 -0800769 mAuxBuffer(NULL),
770 mAuxEffectId(0), mHasVolumeController(false),
Andy Hunge10393e2015-06-12 13:59:33 -0700771 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Ivan Lozano8cf3a072017-08-09 09:01:33 -0700772 mVolumeHandler(new media::VolumeHandler(sampleRate)),
Vlad Popa103be862023-07-10 20:27:41 -0700773 mOpPlayAudioMonitor(OpPlayAudioMonitor::createIfNeeded(thread, attributionSource, attr, id(),
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700774 streamType)),
Andy Hunge10393e2015-06-12 13:59:33 -0700775 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800776 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800777 mCachedVolume(1.0),
Kevin Rocard12381092018-04-11 09:19:59 -0700778 /* The track might not play immediately after being active, similarly as if its volume was 0.
779 * When the track starts playing, its volume will be computed. */
780 mFinalVolume(0.f),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800781 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700782 mFlushHwPending(false),
jiabinf042b9b2021-05-07 23:46:28 +0000783 mFlags(flags),
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200784 mSpeed(speed),
jiabinc658e452022-10-21 20:52:21 +0000785 mIsSpatialized(isSpatialized),
786 mIsBitPerfect(isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -0800787{
Eric Laurent83b88082014-06-20 18:31:16 -0700788 // client == 0 implies sharedBuffer == 0
789 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
790
Andy Hung9d84af52018-09-12 18:03:44 -0700791 ALOGV_IF(sharedBuffer != 0, "%s(%d): sharedBuffer: %p, size: %zu",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700792 __func__, mId, sharedBuffer->unsecurePointer(), sharedBuffer->size());
Eric Laurent83b88082014-06-20 18:31:16 -0700793
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700794 if (mCblk == NULL) {
795 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800796 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700797
Svet Ganov33761132021-05-13 22:51:08 +0000798 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Andy Hung689e82c2019-08-21 17:53:17 -0700799 if (!thread->isTrackAllowed_l(channelMask, format, sessionId, uid)) {
800 ALOGE("%s(%d): no more tracks available", __func__, mId);
801 releaseCblk(); // this makes the track invalid.
802 return;
803 }
804
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700805 if (sharedBuffer == 0) {
806 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700807 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700808 } else {
809 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
Kevin Rocard36862032019-10-10 10:52:19 +0100810 mFrameSize, sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700811 }
812 mServerProxy = mAudioTrackServerProxy;
Andy Hung3c7f47a2021-03-16 17:30:09 -0700813 mServerProxy->setStartThresholdInFrames(frameCountToBeReady); // update the Cblk value
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700814
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700815 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700816 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700817 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
818 // race with setSyncEvent(). However, if we call it, we cannot properly start
819 // static fast tracks (SoundPool) immediately after stopping.
820 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Andy Hung0c1e11e2023-07-06 20:56:16 -0700821 ALOG_ASSERT(thread->fastTrackAvailMask_l() != 0);
822 const int i = __builtin_ctz(thread->fastTrackAvailMask_l());
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700823 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700824 // FIXME This is too eager. We allocate a fast track index before the
825 // fast track becomes active. Since fast tracks are a scarce resource,
826 // this means we are potentially denying other more important fast tracks from
827 // being created. It would be better to allocate the index dynamically.
828 mFastIndex = i;
Andy Hung0c1e11e2023-07-06 20:56:16 -0700829 thread->fastTrackAvailMask_l() &= ~(1 << i);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700830 }
Andy Hung8946a282018-04-19 20:04:56 -0700831
Dean Wheatley7b036912020-06-18 16:22:11 +1000832 mServerLatencySupported = checkServerLatencySupported(format, flags);
Andy Hung8946a282018-04-19 20:04:56 -0700833#ifdef TEE_SINK
834 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle)
Kevin Rocard51f0e982019-02-01 19:19:11 -0800835 + "_" + std::to_string(mId) + "_T");
Andy Hung8946a282018-04-19 20:04:56 -0700836#endif
jiabin57303cc2018-12-18 15:45:57 -0800837
jiabineb3bda02020-06-30 14:07:03 -0700838 if (thread->supportsHapticPlayback()) {
839 // If the track is attached to haptic playback thread, it is potentially to have
840 // HapticGenerator effect, which will generate haptic data, on the track. In that case,
841 // external vibration is always created for all tracks attached to haptic playback thread.
jiabin57303cc2018-12-18 15:45:57 -0800842 mAudioVibrationController = new AudioVibrationController(this);
Svet Ganov33761132021-05-13 22:51:08 +0000843 std::string packageName = attributionSource.packageName.has_value() ?
844 attributionSource.packageName.value() : "";
jiabin57303cc2018-12-18 15:45:57 -0800845 mExternalVibration = new os::ExternalVibration(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700846 mUid, packageName, mAttr, mAudioVibrationController);
jiabin57303cc2018-12-18 15:45:57 -0800847 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800848
849 // Once this item is logged by the server, the client can add properties.
Andy Hunga629bd12020-06-05 16:03:53 -0700850 const char * const traits = sharedBuffer == 0 ? "" : "static";
Andy Hung5837c7f2021-02-25 10:48:24 -0800851 mTrackMetrics.logConstructor(creatorPid, uid, id(), traits, streamType);
Eric Laurent81784c32012-11-19 14:55:58 -0800852}
853
Andy Hung11e74242023-06-26 19:20:57 -0700854Track::~Track()
Eric Laurent81784c32012-11-19 14:55:58 -0800855{
Andy Hung9d84af52018-09-12 18:03:44 -0700856 ALOGV("%s(%d)", __func__, mId);
Glenn Kasten0c72b242013-09-11 09:14:16 -0700857
858 // The destructor would clear mSharedBuffer,
859 // but it will not push the decremented reference count,
860 // leaving the client's IMemory dangling indefinitely.
861 // This prevents that leak.
862 if (mSharedBuffer != 0) {
863 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700864 }
Eric Laurent81784c32012-11-19 14:55:58 -0800865}
866
Andy Hung11e74242023-06-26 19:20:57 -0700867status_t Track::initCheck() const
Glenn Kasten03003332013-08-06 15:40:54 -0700868{
869 status_t status = TrackBase::initCheck();
Andy Hungc0691382018-09-12 18:01:57 -0700870 if (status == NO_ERROR && mCblk == nullptr) {
Glenn Kasten03003332013-08-06 15:40:54 -0700871 status = NO_MEMORY;
872 }
873 return status;
874}
875
Andy Hung11e74242023-06-26 19:20:57 -0700876void Track::destroy()
Eric Laurent81784c32012-11-19 14:55:58 -0800877{
878 // NOTE: destroyTrack_l() can remove a strong reference to this Track
879 // by removing it from mTracks vector, so there is a risk that this Tracks's
880 // destructor is called. As the destructor needs to lock mLock,
881 // we must acquire a strong reference on this Track before locking mLock
882 // here so that the destructor is called only when exiting this function.
883 // On the other hand, as long as Track::destroy() is only called by
884 // TrackHandle destructor, the TrackHandle still holds a strong ref on
885 // this Track with its member mTrack.
886 sp<Track> keep(this);
887 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700888 bool wasActive = false;
Andy Hung0c1e11e2023-07-06 20:56:16 -0700889 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -0800890 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -0700891 Mutex::Autolock _l(thread->mutex());
892 auto* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700893 wasActive = playbackThread->destroyTrack_l(this);
jiabin7434e812023-06-27 18:22:35 +0000894 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->destroy(); });
Eric Laurentaaa44472014-09-12 17:41:50 -0700895 }
896 if (isExternalTrack() && !wasActive) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700897 AudioSystem::releaseOutput(mPortId);
Eric Laurent81784c32012-11-19 14:55:58 -0800898 }
899 }
900}
901
Andy Hung11e74242023-06-26 19:20:57 -0700902void Track::appendDumpHeader(String8& result) const
Eric Laurent81784c32012-11-19 14:55:58 -0800903{
Eric Laurent973db022018-11-20 14:54:31 -0800904 result.appendFormat("Type Id Active Client Session Port Id S Flags "
Kevin Rocard5f2136e2018-05-11 22:03:00 -0700905 " Format Chn mask SRate "
906 "ST Usg CT "
907 " G db L dB R dB VS dB "
jiabin5eaf0962022-12-20 20:11:38 +0000908 " Server FrmCnt FrmRdy F Underruns Flushed BitPerfect"
Kevin Rocard5f2136e2018-05-11 22:03:00 -0700909 "%s\n",
910 isServerLatencySupported() ? " Latency" : "");
Eric Laurent81784c32012-11-19 14:55:58 -0800911}
912
Andy Hung11e74242023-06-26 19:20:57 -0700913void Track::appendDump(String8& result, bool active) const
Eric Laurent81784c32012-11-19 14:55:58 -0800914{
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700915 char trackType;
916 switch (mType) {
917 case TYPE_DEFAULT:
918 case TYPE_OUTPUT:
Andy Hungf6ab58d2018-05-25 12:50:39 -0700919 if (isStatic()) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700920 trackType = 'S'; // static
921 } else {
922 trackType = ' '; // normal
Eric Laurentbfb1b832013-01-07 09:53:42 -0800923 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700924 break;
925 case TYPE_PATCH:
926 trackType = 'P';
927 break;
928 default:
929 trackType = '?';
Eric Laurent81784c32012-11-19 14:55:58 -0800930 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700931
932 if (isFastTrack()) {
Andy Hungc0691382018-09-12 18:01:57 -0700933 result.appendFormat("F%d %c %6d", mFastIndex, trackType, mId);
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700934 } else {
Andy Hungc0691382018-09-12 18:01:57 -0700935 result.appendFormat(" %c %6d", trackType, mId);
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700936 }
937
Eric Laurent81784c32012-11-19 14:55:58 -0800938 char nowInUnderrun;
939 switch (mObservedUnderruns.mBitFields.mMostRecent) {
940 case UNDERRUN_FULL:
941 nowInUnderrun = ' ';
942 break;
943 case UNDERRUN_PARTIAL:
944 nowInUnderrun = '<';
945 break;
946 case UNDERRUN_EMPTY:
947 nowInUnderrun = '*';
948 break;
949 default:
950 nowInUnderrun = '?';
951 break;
952 }
Andy Hungda540db2017-04-20 14:06:17 -0700953
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700954 char fillingStatus;
Andy Hung11e74242023-06-26 19:20:57 -0700955 switch (mFillingStatus) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700956 case FS_INVALID:
957 fillingStatus = 'I';
958 break;
959 case FS_FILLING:
960 fillingStatus = 'f';
961 break;
962 case FS_FILLED:
963 fillingStatus = 'F';
964 break;
965 case FS_ACTIVE:
966 fillingStatus = 'A';
967 break;
968 default:
969 fillingStatus = '?';
970 break;
971 }
972
973 // clip framesReadySafe to max representation in dump
974 const size_t framesReadySafe =
975 std::min(mAudioTrackServerProxy->framesReadySafe(), (size_t)99999999);
976
977 // obtain volumes
978 const gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
979 const std::pair<float /* volume */, bool /* active */> vsVolume =
980 mVolumeHandler->getLastVolume();
981
982 // Our effective frame count is obtained by ServerProxy::getBufferSizeInFrames()
983 // as it may be reduced by the application.
984 const size_t bufferSizeInFrames = (size_t)mAudioTrackServerProxy->getBufferSizeInFrames();
985 // Check whether the buffer size has been modified by the app.
986 const char modifiedBufferChar = bufferSizeInFrames < mFrameCount
987 ? 'r' /* buffer reduced */: bufferSizeInFrames > mFrameCount
988 ? 'e' /* error */ : ' ' /* identical */;
989
Eric Laurent973db022018-11-20 14:54:31 -0800990 result.appendFormat("%7s %6u %7u %7u %2s 0x%03X "
Kevin Rocard5f2136e2018-05-11 22:03:00 -0700991 "%08X %08X %6u "
992 "%2u %3x %2x "
993 "%5.2g %5.2g %5.2g %5.2g%c "
jiabin5eaf0962022-12-20 20:11:38 +0000994 "%08X %6zu%c %6zu %c %9u%c %7u %10s",
Marco Nelissenb2208842014-02-07 14:00:50 -0800995 active ? "yes" : "no",
Andy Hung4ef19fa2018-05-15 19:35:29 -0700996 (mClient == 0) ? getpid() : mClient->pid(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700997 mSessionId,
Eric Laurent973db022018-11-20 14:54:31 -0800998 mPortId,
Andy Hunge2e830f2019-12-03 12:54:46 -0800999 getTrackStateAsCodedString(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001000 mCblk->mFlags,
1001
Eric Laurent81784c32012-11-19 14:55:58 -08001002 mFormat,
1003 mChannelMask,
Andy Hungcef2daa2018-06-01 15:31:49 -07001004 sampleRate(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001005
1006 mStreamType,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07001007 mAttr.usage,
1008 mAttr.content_type,
1009
1010 20.0 * log10(mFinalVolume),
Glenn Kastenc56f3422014-03-21 17:53:17 -07001011 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
1012 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Andy Hungda540db2017-04-20 14:06:17 -07001013 20.0 * log10(vsVolume.first), // VolumeShaper(s) total volume
1014 vsVolume.second ? 'A' : ' ', // if any VolumeShapers active
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001015
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001016 mCblk->mServer,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001017 bufferSizeInFrames,
1018 modifiedBufferChar,
1019 framesReadySafe,
1020 fillingStatus,
Glenn Kasten82aaf942013-07-17 16:05:07 -07001021 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -08001022 nowInUnderrun,
jiabin5eaf0962022-12-20 20:11:38 +00001023 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000,
1024 isBitPerfect() ? "true" : "false"
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001025 );
Andy Hungcef2daa2018-06-01 15:31:49 -07001026
1027 if (isServerLatencySupported()) {
1028 double latencyMs;
1029 bool fromTrack;
1030 if (getTrackLatencyMs(&latencyMs, &fromTrack) == OK) {
1031 // Show latency in msec, followed by 't' if from track timestamp (the most accurate)
1032 // or 'k' if estimated from kernel because track frames haven't been presented yet.
1033 result.appendFormat(" %7.2lf %c", latencyMs, fromTrack ? 't' : 'k');
Andy Hungf6ab58d2018-05-25 12:50:39 -07001034 } else {
Andy Hungcef2daa2018-06-01 15:31:49 -07001035 result.appendFormat("%10s", mCblk->mServer != 0 ? "unavail" : "new");
Andy Hungf6ab58d2018-05-25 12:50:39 -07001036 }
1037 }
1038 result.append("\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001039}
1040
Andy Hung11e74242023-06-26 19:20:57 -07001041uint32_t Track::sampleRate() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001042 return mAudioTrackServerProxy->getSampleRate();
1043}
1044
Eric Laurent81784c32012-11-19 14:55:58 -08001045// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07001046status_t Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001047{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001048 ServerProxy::Buffer buf;
1049 size_t desiredFrames = buffer->frameCount;
1050 buf.mFrameCount = desiredFrames;
1051 status_t status = mServerProxy->obtainBuffer(&buf);
1052 buffer->frameCount = buf.mFrameCount;
1053 buffer->raw = buf.mRaw;
Andy Hungfc629172020-06-22 10:06:23 -07001054 if (buf.mFrameCount == 0 && !isStopping() && !isStopped() && !isPaused() && !isOffloaded()) {
Andy Hung9d84af52018-09-12 18:03:44 -07001055 ALOGV("%s(%d): underrun, framesReady(%zu) < framesDesired(%zd), state: %d",
Andy Hung959b5b82021-09-24 10:46:20 -07001056 __func__, mId, buf.mFrameCount, desiredFrames, (int)mState);
Glenn Kasten82aaf942013-07-17 16:05:07 -07001057 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08001058 } else {
1059 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08001060 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001061 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001062}
1063
Andy Hung11e74242023-06-26 19:20:57 -07001064void Track::releaseBuffer(AudioBufferProvider::Buffer* buffer)
Kevin Rocard153f92d2018-12-18 18:33:28 -08001065{
1066 interceptBuffer(*buffer);
1067 TrackBase::releaseBuffer(buffer);
1068}
1069
1070// TODO: compensate for time shift between HW modules.
Andy Hung11e74242023-06-26 19:20:57 -07001071void Track::interceptBuffer(
Kevin Rocarda134b002019-02-07 18:05:31 -08001072 const AudioBufferProvider::Buffer& sourceBuffer) {
Kevin Rocard6057fa22019-02-08 14:08:07 -08001073 auto start = std::chrono::steady_clock::now();
Kevin Rocarda134b002019-02-07 18:05:31 -08001074 const size_t frameCount = sourceBuffer.frameCount;
Kevin Rocardd83b08a2019-02-27 15:05:54 -08001075 if (frameCount == 0) {
1076 return; // No audio to intercept.
1077 // Additionally PatchProxyBufferProvider::obtainBuffer (called by PathTrack::getNextBuffer)
1078 // does not allow 0 frame size request contrary to getNextBuffer
1079 }
1080 for (auto& teePatch : mTeePatches) {
Andy Hung11e74242023-06-26 19:20:57 -07001081 IAfPatchRecord* patchRecord = teePatch.patchRecord.get();
Mikhail Naganov8296c252019-09-25 14:59:54 -07001082 const size_t framesWritten = patchRecord->writeFrames(
1083 sourceBuffer.i8, frameCount, mFrameSize);
1084 const size_t framesLeft = frameCount - framesWritten;
Kevin Rocarda134b002019-02-07 18:05:31 -08001085 ALOGW_IF(framesLeft != 0, "%s(%d) PatchRecord %d can not provide big enough "
Andy Hung11e74242023-06-26 19:20:57 -07001086 "buffer %zu/%zu, dropping %zu frames", __func__, mId, patchRecord->id(),
Kevin Rocarda134b002019-02-07 18:05:31 -08001087 framesWritten, frameCount, framesLeft);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001088 }
Kevin Rocard6057fa22019-02-08 14:08:07 -08001089 auto spent = ceil<std::chrono::microseconds>(std::chrono::steady_clock::now() - start);
1090 using namespace std::chrono_literals;
1091 // Average is ~20us per track, this should virtually never be logged (Logging takes >200us)
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01001092 ALOGD_IF(spent > 500us, "%s: took %lldus to intercept %zu tracks", __func__,
Kevin Rocard6057fa22019-02-08 14:08:07 -08001093 spent.count(), mTeePatches.size());
Kevin Rocard153f92d2018-12-18 18:33:28 -08001094}
1095
Glenn Kasten6466c9e2013-08-23 10:54:07 -07001096// ExtendedAudioBufferProvider interface
1097
Andy Hung27876c02014-09-09 18:07:55 -07001098// framesReady() may return an approximation of the number of frames if called
1099// from a different thread than the one calling Proxy->obtainBuffer() and
1100// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
1101// AudioTrackServerProxy so be especially careful calling with FastTracks.
Andy Hung11e74242023-06-26 19:20:57 -07001102size_t Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -07001103 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
1104 // Static tracks return zero frames immediately upon stopping (for FastTracks).
1105 // The remainder of the buffer is not drained.
1106 return 0;
1107 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001108 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -08001109}
1110
Andy Hung11e74242023-06-26 19:20:57 -07001111int64_t Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -07001112{
1113 return mAudioTrackServerProxy->framesReleased();
1114}
1115
Andy Hung11e74242023-06-26 19:20:57 -07001116void Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -08001117{
1118 // This call comes from a FastTrack and should be kept lockless.
1119 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -08001120 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -08001121
Andy Hung818e7a32016-02-16 18:08:07 -08001122 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hungcef2daa2018-06-01 15:31:49 -07001123
1124 // Compute latency.
1125 // TODO: Consider whether the server latency may be passed in by FastMixer
1126 // as a constant for all active FastTracks.
1127 const double latencyMs = timestamp.getOutputServerLatencyMs(sampleRate());
1128 mServerLatencyFromTrack.store(true);
1129 mServerLatencyMs.store(latencyMs);
Andy Hung6ae58432016-02-16 18:32:24 -08001130}
1131
Eric Laurent81784c32012-11-19 14:55:58 -08001132// Don't call for fast tracks; the framesReady() could result in priority inversion
Andy Hung11e74242023-06-26 19:20:57 -07001133bool Track::isReady() const {
1134 if (mFillingStatus != FS_FILLING || isStopped() || isPausing()) {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001135 return true;
1136 }
1137
Eric Laurent16498512014-03-17 17:22:08 -07001138 if (isStopping()) {
1139 if (framesReady() > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07001140 mFillingStatus = FS_FILLED;
Eric Laurent16498512014-03-17 17:22:08 -07001141 }
Eric Laurent81784c32012-11-19 14:55:58 -08001142 return true;
1143 }
1144
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01001145 size_t bufferSizeInFrames = mServerProxy->getBufferSizeInFrames();
Andy Hung3c7f47a2021-03-16 17:30:09 -07001146 // Note: mServerProxy->getStartThresholdInFrames() is clamped.
1147 const size_t startThresholdInFrames = mServerProxy->getStartThresholdInFrames();
1148 const size_t framesToBeReady = std::clamp( // clamp again to validate client values.
1149 std::min(startThresholdInFrames, bufferSizeInFrames), size_t(1), mFrameCount);
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01001150
1151 if (framesReady() >= framesToBeReady || (mCblk->mFlags & CBLK_FORCEREADY)) {
1152 ALOGV("%s(%d): consider track ready with %zu/%zu, target was %zu)",
1153 __func__, mId, framesReady(), bufferSizeInFrames, framesToBeReady);
Andy Hung11e74242023-06-26 19:20:57 -07001154 mFillingStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001155 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001156 return true;
1157 }
1158 return false;
1159}
1160
Andy Hung11e74242023-06-26 19:20:57 -07001161status_t Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08001162 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001163{
1164 status_t status = NO_ERROR;
Andy Hungc0691382018-09-12 18:01:57 -07001165 ALOGV("%s(%d): calling pid %d session %d",
1166 __func__, mId, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001167
Andy Hung0c1e11e2023-07-06 20:56:16 -07001168 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001169 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -07001170 if (isOffloaded()) {
Andy Hung7535ed92023-07-17 17:05:00 -07001171 Mutex::Autolock _laf(thread->afThreadCallback()->mutex());
Andy Hung0c1e11e2023-07-06 20:56:16 -07001172 Mutex::Autolock _lth(thread->mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001173 sp<IAfEffectChain> ec = thread->getEffectChain_l(mSessionId);
Andy Hung7535ed92023-07-17 17:05:00 -07001174 if (thread->afThreadCallback()->isNonOffloadableGlobalEffectEnabled_l() ||
Eric Laurent5baf2af2013-09-12 17:37:00 -07001175 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -07001176 invalidate();
1177 return PERMISSION_DENIED;
1178 }
1179 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07001180 Mutex::Autolock _lth(thread->mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001181 track_state state = mState;
1182 // here the track could be either new, or restarted
1183 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -08001184
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001185 // initial state-stopping. next state-pausing.
1186 // What if resume is called ?
1187
Zhou Song1ed46a22020-08-17 15:36:56 +08001188 if (state == FLUSHED) {
1189 // avoid underrun glitches when starting after flush
1190 reset();
1191 }
1192
kuowei.li576f1362021-05-11 18:02:32 +08001193 // clear mPauseHwPending because of pause (and possibly flush) during underrun.
1194 mPauseHwPending = false;
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001195 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001196 if (mResumeToStopping) {
1197 // happened we need to resume to STOPPING_1
1198 mState = TrackBase::STOPPING_1;
Andy Hungc0691382018-09-12 18:01:57 -07001199 ALOGV("%s(%d): PAUSED => STOPPING_1 on thread %d",
1200 __func__, mId, (int)mThreadIoHandle);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001201 } else {
1202 mState = TrackBase::RESUMING;
Andy Hungc0691382018-09-12 18:01:57 -07001203 ALOGV("%s(%d): PAUSED => RESUMING on thread %d",
1204 __func__, mId, (int)mThreadIoHandle);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001205 }
Eric Laurent81784c32012-11-19 14:55:58 -08001206 } else {
1207 mState = TrackBase::ACTIVE;
Andy Hungc0691382018-09-12 18:01:57 -07001208 ALOGV("%s(%d): ? => ACTIVE on thread %d",
1209 __func__, mId, (int)mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -08001210 }
1211
Andy Hung0c1e11e2023-07-06 20:56:16 -07001212 auto* const playbackThread = thread->asIAfPlaybackThread().get();
yucliu6cfb5932022-07-20 17:40:39 -07001213
1214 // states to reset position info for pcm tracks
1215 if (audio_is_linear_pcm(mFormat)
Andy Hunge10393e2015-06-12 13:59:33 -07001216 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
1217 mFrameMap.reset();
yucliu6cfb5932022-07-20 17:40:39 -07001218
1219 if (!isFastTrack() && (isDirect() || isOffloaded())) {
1220 // Start point of track -> sink frame map. If the HAL returns a
1221 // frame position smaller than the first written frame in
1222 // updateTrackFrameInfo, the timestamp can be interpolated
1223 // instead of using a larger value.
1224 mFrameMap.push(mAudioTrackServerProxy->framesReleased(),
1225 playbackThread->framesWritten());
1226 }
Andy Hunge10393e2015-06-12 13:59:33 -07001227 }
Haynes Mathew George240934b2015-03-11 18:25:50 -07001228 if (isFastTrack()) {
1229 // refresh fast track underruns on start because that field is never cleared
1230 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
1231 // after stop.
1232 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
1233 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001234 status = playbackThread->addTrack_l(this);
jiabina84c3d32022-12-02 18:59:55 +00001235 if (status == INVALID_OPERATION || status == PERMISSION_DENIED || status == DEAD_OBJECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08001236 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001237 // restore previous state if start was rejected by policy manager
jiabina84c3d32022-12-02 18:59:55 +00001238 if (status == PERMISSION_DENIED || status == DEAD_OBJECT) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001239 mState = state;
1240 }
1241 }
Andy Hung1d3556d2018-03-29 16:30:14 -07001242
Andy Hungb68f5eb2019-12-03 16:49:17 -08001243 // Audio timing metrics are computed a few mix cycles after starting.
1244 {
1245 mLogStartCountdown = LOG_START_COUNTDOWN;
1246 mLogStartTimeNs = systemTime();
1247 mLogStartFrames = mAudioTrackServerProxy->getTimestamp()
Andy Hung62921122020-05-18 10:47:31 -07001248 .mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1249 mLogLatencyMs = 0.;
Andy Hungb68f5eb2019-12-03 16:49:17 -08001250 }
Andy Hunga81a4b42022-05-19 19:24:51 -07001251 mLogForceVolumeUpdate = true; // at least one volume logged for metrics when starting.
Andy Hungb68f5eb2019-12-03 16:49:17 -08001252
Andy Hung1d3556d2018-03-29 16:30:14 -07001253 if (status == NO_ERROR || status == ALREADY_EXISTS) {
1254 // for streaming tracks, remove the buffer read stop limit.
1255 mAudioTrackServerProxy->start();
1256 }
1257
Eric Laurentbfb1b832013-01-07 09:53:42 -08001258 // track was already in the active list, not a problem
1259 if (status == ALREADY_EXISTS) {
1260 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -07001261 } else {
1262 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
1263 // It is usually unsafe to access the server proxy from a binder thread.
1264 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
1265 // isn't looking at this track yet: we still hold the normal mixer thread lock,
1266 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -07001267 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -07001268 ServerProxy::Buffer buffer;
1269 buffer.mFrameCount = 1;
1270 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001271 }
jiabin7434e812023-06-27 18:22:35 +00001272 if (status == NO_ERROR) {
1273 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->start(); });
1274 }
Eric Laurent81784c32012-11-19 14:55:58 -08001275 } else {
1276 status = BAD_VALUE;
1277 }
Kevin Rocardc43ea142019-01-31 18:17:37 -08001278 if (status == NO_ERROR) {
Jean-Michel Trivi16395ca2022-12-11 22:10:11 +00001279 // send format to AudioManager for playback activity monitoring
Andy Hung7535ed92023-07-17 17:05:00 -07001280 const sp<IAudioManager> audioManager =
1281 thread->afThreadCallback()->getOrCreateAudioManager();
Jean-Michel Trivi16395ca2022-12-11 22:10:11 +00001282 if (audioManager && mPortId != AUDIO_PORT_HANDLE_NONE) {
1283 std::unique_ptr<os::PersistableBundle> bundle =
1284 std::make_unique<os::PersistableBundle>();
1285 bundle->putBoolean(String16(kExtraPlayerEventSpatializedKey),
1286 isSpatialized());
1287 bundle->putInt(String16(kExtraPlayerEventSampleRateKey), mSampleRate);
1288 bundle->putInt(String16(kExtraPlayerEventChannelMaskKey), mChannelMask);
1289 status_t result = audioManager->portEvent(mPortId,
1290 PLAYER_UPDATE_FORMAT, bundle);
1291 if (result != OK) {
1292 ALOGE("%s: unable to send playback format for port ID %d, status error %d",
1293 __func__, mPortId, result);
1294 }
1295 }
Kevin Rocardc43ea142019-01-31 18:17:37 -08001296 }
Eric Laurent81784c32012-11-19 14:55:58 -08001297 return status;
1298}
1299
Andy Hung11e74242023-06-26 19:20:57 -07001300void Track::stop()
Eric Laurent81784c32012-11-19 14:55:58 -08001301{
Andy Hungc0691382018-09-12 18:01:57 -07001302 ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
Andy Hung0c1e11e2023-07-06 20:56:16 -07001303 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001304 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001305 Mutex::Autolock _l(thread->mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001306 track_state state = mState;
1307 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
1308 // If the track is not active (PAUSED and buffers full), flush buffers
Andy Hung0c1e11e2023-07-06 20:56:16 -07001309 auto* const playbackThread = thread->asIAfPlaybackThread().get();
1310 if (!playbackThread->isTrackActive(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001311 reset();
1312 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -07001313 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001314 mState = STOPPED;
1315 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001316 // For fast tracks prepareTracks_l() will set state to STOPPING_2
1317 // presentation is complete
1318 // For an offloaded track this starts a drain and state will
1319 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -08001320 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -07001321 if (isOffloaded()) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001322 mRetryCount = IAfPlaybackThread::kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07001323 }
Eric Laurent81784c32012-11-19 14:55:58 -08001324 }
Eric Laurentb369caf2015-03-30 20:51:47 -07001325 playbackThread->broadcast_l();
Andy Hungc0691382018-09-12 18:01:57 -07001326 ALOGV("%s(%d): not stopping/stopped => stopping/stopped on thread %d",
1327 __func__, mId, (int)mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -08001328 }
jiabin7434e812023-06-27 18:22:35 +00001329 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->stop(); });
Eric Laurent81784c32012-11-19 14:55:58 -08001330 }
1331}
1332
Andy Hung11e74242023-06-26 19:20:57 -07001333void Track::pause()
Eric Laurent81784c32012-11-19 14:55:58 -08001334{
Andy Hungc0691382018-09-12 18:01:57 -07001335 ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
Andy Hung0c1e11e2023-07-06 20:56:16 -07001336 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001337 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001338 Mutex::Autolock _l(thread->mutex());
1339 auto* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001340 switch (mState) {
1341 case STOPPING_1:
1342 case STOPPING_2:
1343 if (!isOffloaded()) {
1344 /* nothing to do if track is not offloaded */
1345 break;
1346 }
1347
1348 // Offloaded track was draining, we need to carry on draining when resumed
1349 mResumeToStopping = true;
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07001350 FALLTHROUGH_INTENDED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001351 case ACTIVE:
1352 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08001353 mState = PAUSING;
Andy Hungc0691382018-09-12 18:01:57 -07001354 ALOGV("%s(%d): ACTIVE/RESUMING => PAUSING on thread %d",
1355 __func__, mId, (int)mThreadIoHandle);
Kuowei Li23666472021-01-20 10:23:25 +08001356 if (isOffloadedOrDirect()) {
1357 mPauseHwPending = true;
1358 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07001359 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001360 break;
Eric Laurent81784c32012-11-19 14:55:58 -08001361
Eric Laurentbfb1b832013-01-07 09:53:42 -08001362 default:
1363 break;
Eric Laurent81784c32012-11-19 14:55:58 -08001364 }
jiabin7434e812023-06-27 18:22:35 +00001365 // Pausing the TeePatch to avoid a glitch on underrun, at the cost of buffered audio loss.
1366 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->pause(); });
Eric Laurent81784c32012-11-19 14:55:58 -08001367 }
1368}
1369
Andy Hung11e74242023-06-26 19:20:57 -07001370void Track::flush()
Eric Laurent81784c32012-11-19 14:55:58 -08001371{
Andy Hungc0691382018-09-12 18:01:57 -07001372 ALOGV("%s(%d)", __func__, mId);
Andy Hung0c1e11e2023-07-06 20:56:16 -07001373 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001374 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001375 Mutex::Autolock _l(thread->mutex());
1376 auto* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001377
Phil Burk4bb650b2016-09-09 12:11:17 -07001378 // Flush the ring buffer now if the track is not active in the PlaybackThread.
1379 // Otherwise the flush would not be done until the track is resumed.
1380 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
Andy Hung0c1e11e2023-07-06 20:56:16 -07001381 if (!playbackThread->isTrackActive(this)) {
Phil Burk4bb650b2016-09-09 12:11:17 -07001382 (void)mServerProxy->flushBufferIfNeeded();
1383 }
1384
Eric Laurentbfb1b832013-01-07 09:53:42 -08001385 if (isOffloaded()) {
1386 // If offloaded we allow flush during any state except terminated
1387 // and keep the track active to avoid problems if user is seeking
1388 // rapidly and underlying hardware has a significant delay handling
1389 // a pause
1390 if (isTerminated()) {
1391 return;
1392 }
1393
Andy Hung9d84af52018-09-12 18:03:44 -07001394 ALOGV("%s(%d): offload flush", __func__, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08001395 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001396
1397 if (mState == STOPPING_1 || mState == STOPPING_2) {
Andy Hung9d84af52018-09-12 18:03:44 -07001398 ALOGV("%s(%d): flushed in STOPPING_1 or 2 state, change state to ACTIVE",
1399 __func__, mId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001400 mState = ACTIVE;
1401 }
1402
Haynes Mathew George7844f672014-01-15 12:32:55 -08001403 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001404 mResumeToStopping = false;
1405 } else {
1406 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
1407 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
1408 return;
1409 }
1410 // No point remaining in PAUSED state after a flush => go to
1411 // FLUSHED state
1412 mState = FLUSHED;
1413 // do not reset the track if it is still in the process of being stopped or paused.
1414 // this will be done by prepareTracks_l() when the track is stopped.
1415 // prepareTracks_l() will see mState == FLUSHED, then
1416 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -08001417 if (isDirect()) {
1418 mFlushHwPending = true;
1419 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07001420 if (!playbackThread->isTrackActive(this)) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001421 reset();
1422 }
Eric Laurent81784c32012-11-19 14:55:58 -08001423 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001424 // Prevent flush being lost if the track is flushed and then resumed
1425 // before mixer thread can run. This is important when offloading
1426 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -07001427 playbackThread->broadcast_l();
jiabin7434e812023-06-27 18:22:35 +00001428 // Flush the Tee to avoid on resume playing old data and glitching on the transition to
1429 // new data
1430 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->flush(); });
Eric Laurent81784c32012-11-19 14:55:58 -08001431 }
1432}
1433
Haynes Mathew George7844f672014-01-15 12:32:55 -08001434// must be called with thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07001435void Track::flushAck()
Haynes Mathew George7844f672014-01-15 12:32:55 -08001436{
Andy Hung920f6572022-10-06 12:09:49 -07001437 if (!isOffloaded() && !isDirect()) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08001438 return;
Andy Hung920f6572022-10-06 12:09:49 -07001439 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08001440
Phil Burk4bb650b2016-09-09 12:11:17 -07001441 // Clear the client ring buffer so that the app can prime the buffer while paused.
1442 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
1443 mServerProxy->flushBufferIfNeeded();
1444
Haynes Mathew George7844f672014-01-15 12:32:55 -08001445 mFlushHwPending = false;
1446}
1447
Andy Hung11e74242023-06-26 19:20:57 -07001448void Track::pauseAck()
Kuowei Li23666472021-01-20 10:23:25 +08001449{
1450 mPauseHwPending = false;
1451}
1452
Andy Hung11e74242023-06-26 19:20:57 -07001453void Track::reset()
Eric Laurent81784c32012-11-19 14:55:58 -08001454{
1455 // Do not reset twice to avoid discarding data written just after a flush and before
1456 // the audioflinger thread detects the track is stopped.
1457 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -08001458 // Force underrun condition to avoid false underrun callback until first data is
1459 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -07001460 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Andy Hung11e74242023-06-26 19:20:57 -07001461 mFillingStatus = FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001462 mResetDone = true;
1463 if (mState == FLUSHED) {
1464 mState = IDLE;
1465 }
1466 }
1467}
1468
Andy Hung11e74242023-06-26 19:20:57 -07001469status_t Track::setParameters(const String8& keyValuePairs)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001470{
Andy Hung0c1e11e2023-07-06 20:56:16 -07001471 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001472 if (thread == 0) {
Andy Hung9d84af52018-09-12 18:03:44 -07001473 ALOGE("%s(%d): thread is dead", __func__, mId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001474 return FAILED_TRANSACTION;
Andy Hung0c1e11e2023-07-06 20:56:16 -07001475 } else if (thread->type() == IAfThreadBase::DIRECT
1476 || thread->type() == IAfThreadBase::OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001477 return thread->setParameters(keyValuePairs);
1478 } else {
1479 return PERMISSION_DENIED;
1480 }
1481}
1482
Andy Hung11e74242023-06-26 19:20:57 -07001483status_t Track::selectPresentation(int presentationId,
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001484 int programId) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001485 const sp<IAfThreadBase> thread = mThread.promote();
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001486 if (thread == 0) {
1487 ALOGE("thread is dead");
1488 return FAILED_TRANSACTION;
Andy Hung0c1e11e2023-07-06 20:56:16 -07001489 } else if (thread->type() == IAfThreadBase::DIRECT
1490 || thread->type() == IAfThreadBase::OFFLOAD) {
1491 auto directOutputThread = thread->asIAfDirectOutputThread().get();
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001492 return directOutputThread->selectPresentation(presentationId, programId);
1493 }
1494 return INVALID_OPERATION;
1495}
1496
Andy Hung11e74242023-06-26 19:20:57 -07001497VolumeShaper::Status Track::applyVolumeShaper(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001498 const sp<VolumeShaper::Configuration>& configuration,
1499 const sp<VolumeShaper::Operation>& operation)
1500{
Andy Hung398ffa22022-12-13 19:19:53 -08001501 VolumeShaper::Status status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung10cbff12017-02-21 17:30:14 -08001502
1503 if (isOffloadedOrDirect()) {
1504 // Signal thread to fetch new volume.
Andy Hung0c1e11e2023-07-06 20:56:16 -07001505 const sp<IAfThreadBase> thread = mThread.promote();
Andy Hung10cbff12017-02-21 17:30:14 -08001506 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001507 Mutex::Autolock _l(thread->mutex());
Andy Hung10cbff12017-02-21 17:30:14 -08001508 thread->broadcast_l();
1509 }
1510 }
1511 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001512}
1513
Andy Hung11e74242023-06-26 19:20:57 -07001514sp<VolumeShaper::State> Track::getVolumeShaperState(int id) const
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001515{
1516 // Note: We don't check if Thread exists.
1517
1518 // mVolumeHandler is thread safe.
1519 return mVolumeHandler->getVolumeShaperState(id);
1520}
1521
Andy Hung11e74242023-06-26 19:20:57 -07001522void Track::setFinalVolume(float volumeLeft, float volumeRight)
Kevin Rocard12381092018-04-11 09:19:59 -07001523{
jiabin76d94692022-12-15 21:51:21 +00001524 mFinalVolumeLeft = volumeLeft;
1525 mFinalVolumeRight = volumeRight;
1526 const float volume = (volumeLeft + volumeRight) * 0.5f;
Kevin Rocard12381092018-04-11 09:19:59 -07001527 if (mFinalVolume != volume) { // Compare to an epsilon if too many meaningless updates
1528 mFinalVolume = volume;
1529 setMetadataHasChanged();
Andy Hunga81a4b42022-05-19 19:24:51 -07001530 mLogForceVolumeUpdate = true;
1531 }
1532 if (mLogForceVolumeUpdate) {
1533 mLogForceVolumeUpdate = false;
1534 mTrackMetrics.logVolume(mFinalVolume);
Kevin Rocard12381092018-04-11 09:19:59 -07001535 }
1536}
1537
Andy Hung11e74242023-06-26 19:20:57 -07001538void Track::copyMetadataTo(MetadataInserter& backInserter) const
Kevin Rocard12381092018-04-11 09:19:59 -07001539{
Eric Laurent49e39282022-06-24 18:42:45 +02001540 // Do not forward metadata for PatchTrack with unspecified stream type
1541 if (mStreamType == AUDIO_STREAM_PATCH) {
1542 return;
1543 }
1544
Eric Laurent94579172020-11-20 18:41:04 +01001545 playback_track_metadata_v7_t metadata;
1546 metadata.base = {
Kevin Rocard12381092018-04-11 09:19:59 -07001547 .usage = mAttr.usage,
1548 .content_type = mAttr.content_type,
1549 .gain = mFinalVolume,
1550 };
Eric Laurentfdf99502021-11-26 19:05:02 +01001551
1552 // When attributes are undefined, derive default values from stream type.
1553 // See AudioAttributes.java, usageForStreamType() and Builder.setInternalLegacyStreamType()
1554 if (mAttr.usage == AUDIO_USAGE_UNKNOWN) {
1555 switch (mStreamType) {
1556 case AUDIO_STREAM_VOICE_CALL:
1557 metadata.base.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1558 metadata.base.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1559 break;
1560 case AUDIO_STREAM_SYSTEM:
1561 metadata.base.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
1562 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1563 break;
1564 case AUDIO_STREAM_RING:
1565 metadata.base.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
1566 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1567 break;
1568 case AUDIO_STREAM_MUSIC:
1569 metadata.base.usage = AUDIO_USAGE_MEDIA;
1570 metadata.base.content_type = AUDIO_CONTENT_TYPE_MUSIC;
1571 break;
1572 case AUDIO_STREAM_ALARM:
1573 metadata.base.usage = AUDIO_USAGE_ALARM;
1574 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1575 break;
1576 case AUDIO_STREAM_NOTIFICATION:
1577 metadata.base.usage = AUDIO_USAGE_NOTIFICATION;
1578 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1579 break;
1580 case AUDIO_STREAM_DTMF:
1581 metadata.base.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
1582 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1583 break;
1584 case AUDIO_STREAM_ACCESSIBILITY:
1585 metadata.base.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
1586 metadata.base.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1587 break;
1588 case AUDIO_STREAM_ASSISTANT:
1589 metadata.base.usage = AUDIO_USAGE_ASSISTANT;
1590 metadata.base.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1591 break;
1592 case AUDIO_STREAM_REROUTING:
1593 metadata.base.usage = AUDIO_USAGE_VIRTUAL_SOURCE;
1594 // unknown content type
1595 break;
1596 case AUDIO_STREAM_CALL_ASSISTANT:
1597 metadata.base.usage = AUDIO_USAGE_CALL_ASSISTANT;
1598 metadata.base.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1599 break;
1600 default:
1601 break;
1602 }
1603 }
1604
Eric Laurent78b07302022-10-07 16:20:34 +02001605 metadata.channel_mask = mChannelMask;
Eric Laurent94579172020-11-20 18:41:04 +01001606 strncpy(metadata.tags, mAttr.tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
1607 *backInserter++ = metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07001608}
1609
Andy Hung11e74242023-06-26 19:20:57 -07001610void Track::updateTeePatches_l() {
Jiabin Huangfb476842022-12-06 03:18:10 +00001611 if (mTeePatchesToUpdate.has_value()) {
jiabin7434e812023-06-27 18:22:35 +00001612 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->destroy(); });
Jiabin Huangfb476842022-12-06 03:18:10 +00001613 mTeePatches = mTeePatchesToUpdate.value();
1614 if (mState == TrackBase::ACTIVE || mState == TrackBase::RESUMING ||
1615 mState == TrackBase::STOPPING_1) {
jiabin7434e812023-06-27 18:22:35 +00001616 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->start(); });
Jiabin Huangfb476842022-12-06 03:18:10 +00001617 }
1618 mTeePatchesToUpdate.reset();
jiabinf042b9b2021-05-07 23:46:28 +00001619 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001620}
1621
Andy Hung6bad18a2023-07-14 11:45:38 -07001622void Track::setTeePatchesToUpdate_l(TeePatches teePatchesToUpdate) {
Jiabin Huangfb476842022-12-06 03:18:10 +00001623 ALOGW_IF(mTeePatchesToUpdate.has_value(),
1624 "%s, existing tee patches to update will be ignored", __func__);
1625 mTeePatchesToUpdate = std::move(teePatchesToUpdate);
1626}
1627
Vlad Popae8d99472022-06-30 16:02:48 +02001628// must be called with player thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07001629void Track::processMuteEvent_l(const sp<
Vlad Popae8d99472022-06-30 16:02:48 +02001630 IAudioManager>& audioManager, mute_state_t muteState)
1631{
1632 if (mMuteState == muteState) {
1633 // mute state did not change, do nothing
1634 return;
1635 }
1636
1637 status_t result = UNKNOWN_ERROR;
1638 if (audioManager && mPortId != AUDIO_PORT_HANDLE_NONE) {
1639 if (mMuteEventExtras == nullptr) {
1640 mMuteEventExtras = std::make_unique<os::PersistableBundle>();
1641 }
1642 mMuteEventExtras->putInt(String16(kExtraPlayerEventMuteKey),
1643 static_cast<int>(muteState));
1644
1645 result = audioManager->portEvent(mPortId,
1646 PLAYER_UPDATE_MUTED,
1647 mMuteEventExtras);
1648 }
1649
1650 if (result == OK) {
1651 mMuteState = muteState;
1652 } else {
1653 ALOGW("%s(%d): cannot process mute state for port ID %d, status error %d",
1654 __func__,
1655 id(),
1656 mPortId,
1657 result);
1658 }
1659}
1660
Andy Hung11e74242023-06-26 19:20:57 -07001661status_t Track::getTimestamp(AudioTimestamp& timestamp)
Glenn Kasten573d80a2013-08-26 09:36:23 -07001662{
Andy Hung818e7a32016-02-16 18:08:07 -08001663 if (!isOffloaded() && !isDirect()) {
1664 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -07001665 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07001666 const sp<IAfThreadBase> thread = mThread.promote();
Glenn Kasten573d80a2013-08-26 09:36:23 -07001667 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -07001668 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -07001669 }
Phil Burk6140c792015-03-19 14:30:21 -07001670
Andy Hung0c1e11e2023-07-06 20:56:16 -07001671 Mutex::Autolock _l(thread->mutex());
1672 auto* const playbackThread = thread->asIAfPlaybackThread().get();
Andy Hung818e7a32016-02-16 18:08:07 -08001673 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -07001674}
1675
Andy Hung11e74242023-06-26 19:20:57 -07001676status_t Track::attachAuxEffect(int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001677{
Andy Hung0c1e11e2023-07-06 20:56:16 -07001678 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent6c796322019-04-09 14:13:17 -07001679 if (thread == nullptr) {
1680 return DEAD_OBJECT;
1681 }
Eric Laurent81784c32012-11-19 14:55:58 -08001682
Andy Hung0c1e11e2023-07-06 20:56:16 -07001683 auto dstThread = thread->asIAfPlaybackThread();
Andy Hung11e74242023-06-26 19:20:57 -07001684 // srcThread is initialized by call to moveAuxEffectToIo()
Andy Hung0c1e11e2023-07-06 20:56:16 -07001685 sp<IAfPlaybackThread> srcThread;
Andy Hunga9b24592023-07-17 12:40:43 -07001686 const auto& af = mClient->afClientCallback();
Eric Laurent6c796322019-04-09 14:13:17 -07001687 status_t status = af->moveAuxEffectToIo(EffectId, dstThread, &srcThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001688
Eric Laurent6c796322019-04-09 14:13:17 -07001689 if (EffectId != 0 && status == NO_ERROR) {
1690 status = dstThread->attachAuxEffect(this, EffectId);
1691 if (status == NO_ERROR) {
1692 AudioSystem::moveEffectsToIo(std::vector<int>(EffectId), dstThread->id());
Eric Laurent81784c32012-11-19 14:55:58 -08001693 }
Eric Laurent6c796322019-04-09 14:13:17 -07001694 }
1695
1696 if (status != NO_ERROR && srcThread != nullptr) {
1697 af->moveAuxEffectToIo(EffectId, srcThread, &dstThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001698 }
1699 return status;
1700}
1701
Andy Hung11e74242023-06-26 19:20:57 -07001702void Track::setAuxBuffer(int EffectId, int32_t *buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001703{
1704 mAuxEffectId = EffectId;
1705 mAuxBuffer = buffer;
1706}
1707
Andy Hung59de4262021-06-14 10:53:54 -07001708// presentationComplete verified by frames, used by Mixed tracks.
Andy Hung11e74242023-06-26 19:20:57 -07001709bool Track::presentationComplete(
Andy Hung818e7a32016-02-16 18:08:07 -08001710 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001711{
Andy Hung818e7a32016-02-16 18:08:07 -08001712 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
1713 // This assists in proper timestamp computation as well as wakelock management.
1714
Eric Laurent81784c32012-11-19 14:55:58 -08001715 // a track is considered presented when the total number of frames written to audio HAL
1716 // corresponds to the number of frames written when presentationComplete() is called for the
1717 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001718 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1719 // to detect when all frames have been played. In this case framesWritten isn't
1720 // useful because it doesn't always reflect whether there is data in the h/w
1721 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung9d84af52018-09-12 18:03:44 -07001722 ALOGV("%s(%d): presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
1723 __func__, mId,
Andy Hung818e7a32016-02-16 18:08:07 -08001724 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001725 if (mPresentationCompleteFrames == 0) {
1726 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung59de4262021-06-14 10:53:54 -07001727 ALOGV("%s(%d): set:"
Andy Hung9d84af52018-09-12 18:03:44 -07001728 " mPresentationCompleteFrames %lld audioHalFrames %zu",
1729 __func__, mId,
Andy Hung818e7a32016-02-16 18:08:07 -08001730 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08001731 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001732
Andy Hungc54b1ff2016-02-23 14:07:07 -08001733 bool complete;
Andy Hung59de4262021-06-14 10:53:54 -07001734 if (isFastTrack()) { // does not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001735 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hung59de4262021-06-14 10:53:54 -07001736 ALOGV("%s(%d): %s framesWritten:%lld mPresentationCompleteFrames:%lld",
1737 __func__, mId, (complete ? "complete" : "waiting"),
1738 (long long) framesWritten, (long long) mPresentationCompleteFrames);
Andy Hungc54b1ff2016-02-23 14:07:07 -08001739 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001740 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -08001741 && mAudioTrackServerProxy->isDrained();
1742 }
1743
1744 if (complete) {
Andy Hung59de4262021-06-14 10:53:54 -07001745 notifyPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08001746 return true;
1747 }
1748 return false;
1749}
1750
Andy Hung59de4262021-06-14 10:53:54 -07001751// presentationComplete checked by time, used by DirectTracks.
Andy Hung11e74242023-06-26 19:20:57 -07001752bool Track::presentationComplete(uint32_t latencyMs)
Andy Hung59de4262021-06-14 10:53:54 -07001753{
1754 // For Offloaded or Direct tracks.
1755
1756 // For a direct track, we incorporated time based testing for presentationComplete.
1757
1758 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1759 // to detect when all frames have been played. In this case latencyMs isn't
1760 // useful because it doesn't always reflect whether there is data in the h/w
1761 // buffers, particularly if a track has been paused and resumed during draining
1762
1763 constexpr float MIN_SPEED = 0.125f; // min speed scaling allowed for timely response.
1764 if (mPresentationCompleteTimeNs == 0) {
1765 mPresentationCompleteTimeNs = systemTime() + latencyMs * 1e6 / fmax(mSpeed, MIN_SPEED);
1766 ALOGV("%s(%d): set: latencyMs %u mPresentationCompleteTimeNs:%lld",
1767 __func__, mId, latencyMs, (long long) mPresentationCompleteTimeNs);
1768 }
1769
1770 bool complete;
1771 if (isOffloaded()) {
1772 complete = true;
1773 } else { // Direct
1774 complete = systemTime() >= mPresentationCompleteTimeNs;
1775 ALOGV("%s(%d): %s", __func__, mId, (complete ? "complete" : "waiting"));
1776 }
1777 if (complete) {
1778 notifyPresentationComplete();
1779 return true;
1780 }
1781 return false;
1782}
1783
Andy Hung11e74242023-06-26 19:20:57 -07001784void Track::notifyPresentationComplete()
Andy Hung59de4262021-06-14 10:53:54 -07001785{
1786 // This only triggers once. TODO: should we enforce this?
1787 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1788 mAudioTrackServerProxy->setStreamEndDone();
1789}
1790
Andy Hung11e74242023-06-26 19:20:57 -07001791void Track::triggerEvents(AudioSystem::sync_event_t type)
Eric Laurent81784c32012-11-19 14:55:58 -08001792{
Andy Hung068e08e2023-05-15 19:02:55 -07001793 for (auto it = mSyncEvents.begin(); it != mSyncEvents.end();) {
1794 if ((*it)->type() == type) {
Andy Hung93bb5732023-05-04 21:16:34 -07001795 ALOGV("%s: triggering SyncEvent type %d", __func__, type);
Andy Hung068e08e2023-05-15 19:02:55 -07001796 (*it)->trigger();
1797 it = mSyncEvents.erase(it);
Ivan Lozano5ec161b2017-12-06 10:00:28 -08001798 } else {
Andy Hung068e08e2023-05-15 19:02:55 -07001799 ++it;
Eric Laurent81784c32012-11-19 14:55:58 -08001800 }
1801 }
1802}
1803
1804// implement VolumeBufferProvider interface
1805
Andy Hung11e74242023-06-26 19:20:57 -07001806gain_minifloat_packed_t Track::getVolumeLR() const
Eric Laurent81784c32012-11-19 14:55:58 -08001807{
1808 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1809 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001810 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1811 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1812 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001813 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001814 if (vl > GAIN_FLOAT_UNITY) {
1815 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001816 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001817 if (vr > GAIN_FLOAT_UNITY) {
1818 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001819 }
1820 // now apply the cached master volume and stream type volume;
1821 // this is trusted but lacks any synchronization or barrier so may be stale
1822 float v = mCachedVolume;
1823 vl *= v;
1824 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001825 // re-combine into packed minifloat
1826 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001827 // FIXME look at mute, pause, and stop flags
1828 return vlr;
1829}
1830
Andy Hung11e74242023-06-26 19:20:57 -07001831status_t Track::setSyncEvent(
Andy Hung068e08e2023-05-15 19:02:55 -07001832 const sp<audioflinger::SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08001833{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001834 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001835 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1836 (mState == STOPPED)))) {
Andy Hung9d84af52018-09-12 18:03:44 -07001837 ALOGW("%s(%d): in invalid state %d on session %d %s mode, framesReady %zu",
1838 __func__, mId,
Andy Hung959b5b82021-09-24 10:46:20 -07001839 (int)mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
Eric Laurent81784c32012-11-19 14:55:58 -08001840 event->cancel();
1841 return INVALID_OPERATION;
1842 }
1843 (void) TrackBase::setSyncEvent(event);
1844 return NO_ERROR;
1845}
1846
Andy Hung11e74242023-06-26 19:20:57 -07001847void Track::invalidate()
Glenn Kasten5736c352012-12-04 12:12:34 -08001848{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001849 TrackBase::invalidate();
Eric Laurent4d231dc2016-03-11 18:38:23 -08001850 signalClientFlag(CBLK_INVALID);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001851}
1852
Andy Hung11e74242023-06-26 19:20:57 -07001853void Track::disable()
Eric Laurent4d231dc2016-03-11 18:38:23 -08001854{
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01001855 // TODO(b/142394888): the filling status should also be reset to filling
Eric Laurent4d231dc2016-03-11 18:38:23 -08001856 signalClientFlag(CBLK_DISABLED);
1857}
1858
Andy Hung11e74242023-06-26 19:20:57 -07001859void Track::signalClientFlag(int32_t flag)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001860{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001861 // FIXME should use proxy, and needs work
1862 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001863 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001864 android_atomic_release_store(0x40000000, &cblk->mFutex);
1865 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001866 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001867}
1868
Andy Hung11e74242023-06-26 19:20:57 -07001869void Track::signal()
Eric Laurent59fe0102013-09-27 18:48:26 -07001870{
Andy Hung0c1e11e2023-07-06 20:56:16 -07001871 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent59fe0102013-09-27 18:48:26 -07001872 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001873 auto* const t = thread->asIAfPlaybackThread().get();
1874 Mutex::Autolock _l(t->mutex());
Eric Laurent59fe0102013-09-27 18:48:26 -07001875 t->broadcast_l();
1876 }
1877}
1878
Andy Hung11e74242023-06-26 19:20:57 -07001879status_t Track::getDualMonoMode(audio_dual_mono_mode_t* mode) const
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001880{
1881 status_t status = INVALID_OPERATION;
1882 if (isOffloadedOrDirect()) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001883 const sp<IAfThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001884 if (thread != nullptr) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001885 auto* const t = thread->asIAfPlaybackThread().get();
1886 Mutex::Autolock _l(t->mutex());
1887 status = t->getOutput_l()->stream->getDualMonoMode(mode);
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001888 ALOGD_IF((status == NO_ERROR) && (mDualMonoMode != *mode),
1889 "%s: mode %d inconsistent", __func__, mDualMonoMode);
1890 }
1891 }
1892 return status;
1893}
1894
Andy Hung11e74242023-06-26 19:20:57 -07001895status_t Track::setDualMonoMode(audio_dual_mono_mode_t mode)
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001896{
1897 status_t status = INVALID_OPERATION;
1898 if (isOffloadedOrDirect()) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001899 const sp<IAfThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001900 if (thread != nullptr) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001901 auto* const t = thread->asIAfPlaybackThread().get();
1902 Mutex::Autolock lock(t->mutex());
1903 status = t->getOutput_l()->stream->setDualMonoMode(mode);
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001904 if (status == NO_ERROR) {
1905 mDualMonoMode = mode;
1906 }
1907 }
1908 }
1909 return status;
1910}
1911
Andy Hung11e74242023-06-26 19:20:57 -07001912status_t Track::getAudioDescriptionMixLevel(float* leveldB) const
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001913{
1914 status_t status = INVALID_OPERATION;
1915 if (isOffloadedOrDirect()) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001916 sp<IAfThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001917 if (thread != nullptr) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001918 auto* const t = thread->asIAfPlaybackThread().get();
1919 Mutex::Autolock lock(t->mutex());
1920 status = t->getOutput_l()->stream->getAudioDescriptionMixLevel(leveldB);
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001921 ALOGD_IF((status == NO_ERROR) && (mAudioDescriptionMixLevel != *leveldB),
1922 "%s: level %.3f inconsistent", __func__, mAudioDescriptionMixLevel);
1923 }
1924 }
1925 return status;
1926}
1927
Andy Hung11e74242023-06-26 19:20:57 -07001928status_t Track::setAudioDescriptionMixLevel(float leveldB)
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001929{
1930 status_t status = INVALID_OPERATION;
1931 if (isOffloadedOrDirect()) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001932 const sp<IAfThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001933 if (thread != nullptr) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001934 auto* const t = thread->asIAfPlaybackThread().get();
1935 Mutex::Autolock lock(t->mutex());
1936 status = t->getOutput_l()->stream->setAudioDescriptionMixLevel(leveldB);
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001937 if (status == NO_ERROR) {
1938 mAudioDescriptionMixLevel = leveldB;
1939 }
1940 }
1941 }
1942 return status;
1943}
1944
Andy Hung11e74242023-06-26 19:20:57 -07001945status_t Track::getPlaybackRateParameters(
Andy Hungfafbebc2023-06-23 19:27:19 -07001946 audio_playback_rate_t* playbackRate) const
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001947{
1948 status_t status = INVALID_OPERATION;
1949 if (isOffloadedOrDirect()) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001950 const sp<IAfThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001951 if (thread != nullptr) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001952 auto* const t = thread->asIAfPlaybackThread().get();
1953 Mutex::Autolock lock(t->mutex());
1954 status = t->getOutput_l()->stream->getPlaybackRateParameters(playbackRate);
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001955 ALOGD_IF((status == NO_ERROR) &&
1956 !isAudioPlaybackRateEqual(mPlaybackRateParameters, *playbackRate),
1957 "%s: playbackRate inconsistent", __func__);
1958 }
1959 }
1960 return status;
1961}
1962
Andy Hung11e74242023-06-26 19:20:57 -07001963status_t Track::setPlaybackRateParameters(
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001964 const audio_playback_rate_t& playbackRate)
1965{
1966 status_t status = INVALID_OPERATION;
1967 if (isOffloadedOrDirect()) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001968 const sp<IAfThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001969 if (thread != nullptr) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07001970 auto* const t = thread->asIAfPlaybackThread().get();
1971 Mutex::Autolock lock(t->mutex());
1972 status = t->getOutput_l()->stream->setPlaybackRateParameters(playbackRate);
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001973 if (status == NO_ERROR) {
1974 mPlaybackRateParameters = playbackRate;
1975 }
1976 }
1977 }
1978 return status;
1979}
1980
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001981//To be called with thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07001982bool Track::isResumePending() const {
Andy Hung920f6572022-10-06 12:09:49 -07001983 if (mState == RESUMING) {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001984 return true;
Andy Hung920f6572022-10-06 12:09:49 -07001985 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001986 /* Resume is pending if track was stopping before pause was called */
1987 if (mState == STOPPING_1 &&
Andy Hung920f6572022-10-06 12:09:49 -07001988 mResumeToStopping) {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001989 return true;
Andy Hung920f6572022-10-06 12:09:49 -07001990 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001991
1992 return false;
1993}
1994
1995//To be called with thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07001996void Track::resumeAck() {
Andy Hung920f6572022-10-06 12:09:49 -07001997 if (mState == RESUMING) {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001998 mState = ACTIVE;
Andy Hung920f6572022-10-06 12:09:49 -07001999 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08002000
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08002001 // Other possibility of pending resume is stopping_1 state
2002 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08002003 // drain being called.
2004 if (mState == STOPPING_1) {
2005 mResumeToStopping = false;
2006 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08002007}
Andy Hunge10393e2015-06-12 13:59:33 -07002008
2009//To be called with thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07002010void Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08002011 int64_t trackFramesReleased, int64_t sinkFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07002012 uint32_t halSampleRate, const ExtendedTimestamp &timeStamp) {
Andy Hung30282562018-08-08 18:27:03 -07002013 // Make the kernel frametime available.
2014 const FrameTime ft{
2015 timeStamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
2016 timeStamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]};
2017 // ALOGD("FrameTime: %lld %lld", (long long)ft.frames, (long long)ft.timeNs);
2018 mKernelFrameTime.store(ft);
2019 if (!audio_is_linear_pcm(mFormat)) {
2020 return;
2021 }
2022
Andy Hung818e7a32016-02-16 18:08:07 -08002023 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07002024 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08002025
2026 // adjust server times and set drained state.
2027 //
2028 // Our timestamps are only updated when the track is on the Thread active list.
2029 // We need to ensure that tracks are not removed before full drain.
2030 ExtendedTimestamp local = timeStamp;
Andy Hungcef2daa2018-06-01 15:31:49 -07002031 bool drained = true; // default assume drained, if no server info found
Andy Hung818e7a32016-02-16 18:08:07 -08002032 bool checked = false;
2033 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
2034 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
2035 // Lookup the track frame corresponding to the sink frame position.
2036 if (local.mTimeNs[i] > 0) {
2037 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
2038 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07002039 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hungcef2daa2018-06-01 15:31:49 -07002040 drained = local.mPosition[i] >= mAudioTrackServerProxy->framesReleased();
Andy Hung818e7a32016-02-16 18:08:07 -08002041 checked = true;
2042 }
2043 }
Andy Hunge10393e2015-06-12 13:59:33 -07002044 }
Andy Hungcef2daa2018-06-01 15:31:49 -07002045
Andy Hung93bb5732023-05-04 21:16:34 -07002046 ALOGV("%s: trackFramesReleased:%lld sinkFramesWritten:%lld setDrained: %d",
2047 __func__, (long long)trackFramesReleased, (long long)sinkFramesWritten, drained);
Andy Hungcef2daa2018-06-01 15:31:49 -07002048 mAudioTrackServerProxy->setDrained(drained);
Andy Hungea2b9c02016-02-12 17:06:53 -08002049 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08002050 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08002051 mServerProxy->setTimestamp(local);
Andy Hungcef2daa2018-06-01 15:31:49 -07002052
2053 // Compute latency info.
2054 const bool useTrackTimestamp = !drained;
2055 const double latencyMs = useTrackTimestamp
2056 ? local.getOutputServerLatencyMs(sampleRate())
2057 : timeStamp.getOutputServerLatencyMs(halSampleRate);
2058
2059 mServerLatencyFromTrack.store(useTrackTimestamp);
2060 mServerLatencyMs.store(latencyMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08002061
Andy Hung62921122020-05-18 10:47:31 -07002062 if (mLogStartCountdown > 0
2063 && local.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0
2064 && local.mPosition[ExtendedTimestamp::LOCATION_KERNEL] > 0)
2065 {
2066 if (mLogStartCountdown > 1) {
2067 --mLogStartCountdown;
2068 } else if (latencyMs < mLogLatencyMs) { // wait for latency to stabilize (dip)
2069 mLogStartCountdown = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08002070 // startup is the difference in times for the current timestamp and our start
2071 double startUpMs =
Andy Hung62921122020-05-18 10:47:31 -07002072 (local.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] - mLogStartTimeNs) * 1e-6;
Andy Hungb68f5eb2019-12-03 16:49:17 -08002073 // adjust for frames played.
Andy Hung62921122020-05-18 10:47:31 -07002074 startUpMs -= (local.mPosition[ExtendedTimestamp::LOCATION_KERNEL] - mLogStartFrames)
2075 * 1e3 / mSampleRate;
2076 ALOGV("%s: latencyMs:%lf startUpMs:%lf"
2077 " localTime:%lld startTime:%lld"
2078 " localPosition:%lld startPosition:%lld",
2079 __func__, latencyMs, startUpMs,
2080 (long long)local.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
Andy Hungb68f5eb2019-12-03 16:49:17 -08002081 (long long)mLogStartTimeNs,
Andy Hung62921122020-05-18 10:47:31 -07002082 (long long)local.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
Andy Hungb68f5eb2019-12-03 16:49:17 -08002083 (long long)mLogStartFrames);
Andy Hungc2b11cb2020-04-22 09:04:01 -07002084 mTrackMetrics.logLatencyAndStartup(latencyMs, startUpMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08002085 }
Andy Hung62921122020-05-18 10:47:31 -07002086 mLogLatencyMs = latencyMs;
Andy Hungb68f5eb2019-12-03 16:49:17 -08002087 }
Andy Hunge10393e2015-06-12 13:59:33 -07002088}
2089
Andy Hung11e74242023-06-26 19:20:57 -07002090bool Track::AudioVibrationController::setMute(bool muted) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07002091 const sp<IAfThreadBase> thread = mTrack->mThread.promote();
jiabin57303cc2018-12-18 15:45:57 -08002092 if (thread != 0) {
2093 // Lock for updating mHapticPlaybackEnabled.
Andy Hung0c1e11e2023-07-06 20:56:16 -07002094 Mutex::Autolock _l(thread->mutex());
2095 auto* const playbackThread = thread->asIAfPlaybackThread().get();
jiabin57303cc2018-12-18 15:45:57 -08002096 if ((mTrack->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Andy Hung0c1e11e2023-07-06 20:56:16 -07002097 && playbackThread->hapticChannelCount() > 0) {
SPeak Shenc19aa9e2022-11-11 00:28:50 +08002098 ALOGD("%s, haptic playback was %s for track %d",
2099 __func__, muted ? "muted" : "unmuted", mTrack->id());
2100 mTrack->setHapticPlaybackEnabled(!muted);
2101 return true;
jiabin57303cc2018-12-18 15:45:57 -08002102 }
2103 }
SPeak Shenc19aa9e2022-11-11 00:28:50 +08002104 return false;
2105}
2106
Andy Hung11e74242023-06-26 19:20:57 -07002107binder::Status Track::AudioVibrationController::mute(
SPeak Shenc19aa9e2022-11-11 00:28:50 +08002108 /*out*/ bool *ret) {
2109 *ret = setMute(true);
jiabin57303cc2018-12-18 15:45:57 -08002110 return binder::Status::ok();
2111}
2112
Andy Hung11e74242023-06-26 19:20:57 -07002113binder::Status Track::AudioVibrationController::unmute(
jiabin57303cc2018-12-18 15:45:57 -08002114 /*out*/ bool *ret) {
SPeak Shenc19aa9e2022-11-11 00:28:50 +08002115 *ret = setMute(false);
jiabin57303cc2018-12-18 15:45:57 -08002116 return binder::Status::ok();
2117}
2118
Eric Laurent81784c32012-11-19 14:55:58 -08002119// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -07002120#undef LOG_TAG
2121#define LOG_TAG "AF::OutputTrack"
Eric Laurent81784c32012-11-19 14:55:58 -08002122
Andy Hung11e74242023-06-26 19:20:57 -07002123/* static */
Andy Hung0c1e11e2023-07-06 20:56:16 -07002124sp<IAfOutputTrack> IAfOutputTrack::create(
2125 IAfPlaybackThread* playbackThread,
2126 IAfDuplicatingThread* sourceThread,
Andy Hung11e74242023-06-26 19:20:57 -07002127 uint32_t sampleRate,
2128 audio_format_t format,
2129 audio_channel_mask_t channelMask,
2130 size_t frameCount,
2131 const AttributionSourceState& attributionSource) {
2132 return sp<OutputTrack>::make(
Andy Hung0c1e11e2023-07-06 20:56:16 -07002133 playbackThread,
2134 sourceThread,
Andy Hung11e74242023-06-26 19:20:57 -07002135 sampleRate,
2136 format,
2137 channelMask,
2138 frameCount,
2139 attributionSource);
2140}
2141
2142OutputTrack::OutputTrack(
Andy Hung0c1e11e2023-07-06 20:56:16 -07002143 IAfPlaybackThread* playbackThread,
2144 IAfDuplicatingThread* sourceThread,
Eric Laurent81784c32012-11-19 14:55:58 -08002145 uint32_t sampleRate,
2146 audio_format_t format,
2147 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002148 size_t frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00002149 const AttributionSourceState& attributionSource)
Eric Laurent223fd5c2014-11-11 13:43:36 -08002150 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002151 audio_attributes_t{} /* currently unused for output track */,
Eric Laurent223fd5c2014-11-11 13:43:36 -08002152 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07002153 nullptr /* buffer */, (size_t)0 /* bufferSize */, nullptr /* sharedBuffer */,
Svet Ganov33761132021-05-13 22:51:08 +00002154 AUDIO_SESSION_NONE, getpid(), attributionSource, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08002155 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07002156 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08002157{
2158
2159 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08002160 mOutBuffer.frameCount = 0;
Andy Hung0c1e11e2023-07-06 20:56:16 -07002161 playbackThread->addOutputTrack_l(this);
Andy Hung9d84af52018-09-12 18:03:44 -07002162 ALOGV("%s(): mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002163 "frameCount %zu, mChannelMask 0x%08x",
Andy Hung9d84af52018-09-12 18:03:44 -07002164 __func__, mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08002165 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002166 // since client and server are in the same process,
2167 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07002168 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
2169 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07002170 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07002171 mClientProxy->setSendLevel(0.0);
2172 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08002173 } else {
Andy Hung9d84af52018-09-12 18:03:44 -07002174 ALOGW("%s(%d): Error creating output track on thread %d",
2175 __func__, mId, (int)mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -08002176 }
2177}
2178
Andy Hung11e74242023-06-26 19:20:57 -07002179OutputTrack::~OutputTrack()
Eric Laurent81784c32012-11-19 14:55:58 -08002180{
2181 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08002182 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08002183}
2184
Andy Hung11e74242023-06-26 19:20:57 -07002185status_t OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08002186 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08002187{
2188 status_t status = Track::start(event, triggerSession);
2189 if (status != NO_ERROR) {
2190 return status;
2191 }
2192
2193 mActive = true;
2194 mRetryCount = 127;
2195 return status;
2196}
2197
Andy Hung11e74242023-06-26 19:20:57 -07002198void OutputTrack::stop()
Eric Laurent81784c32012-11-19 14:55:58 -08002199{
2200 Track::stop();
2201 clearBufferQueue();
2202 mOutBuffer.frameCount = 0;
2203 mActive = false;
2204}
2205
Andy Hung11e74242023-06-26 19:20:57 -07002206ssize_t OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08002207{
Eric Laurent19952e12023-04-20 10:08:29 +02002208 if (!mActive && frames != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07002209 const sp<IAfThreadBase> thread = mThread.promote();
Andy Hung3e4c8742023-06-29 21:19:25 -07002210 if (thread != nullptr && thread->inStandby()) {
Eric Laurent19952e12023-04-20 10:08:29 +02002211 // preload one silent buffer to trigger mixer on start()
2212 ClientProxy::Buffer buf { .mFrameCount = mClientProxy->getStartThresholdInFrames() };
2213 status_t status = mClientProxy->obtainBuffer(&buf);
2214 if (status != NO_ERROR && status != NOT_ENOUGH_DATA && status != WOULD_BLOCK) {
2215 ALOGE("%s(%d): could not obtain buffer on start", __func__, mId);
2216 return 0;
2217 }
2218 memset(buf.mRaw, 0, buf.mFrameCount * mFrameSize);
2219 mClientProxy->releaseBuffer(&buf);
2220
2221 (void) start();
2222
2223 // wait for HAL stream to start before sending actual audio. Doing this on each
2224 // OutputTrack makes that playback start on all output streams is synchronized.
2225 // If another OutputTrack has already started it can underrun but this is OK
2226 // as only silence has been played so far and the retry count is very high on
2227 // OutputTrack.
Andy Hung0c1e11e2023-07-06 20:56:16 -07002228 auto* const pt = thread->asIAfPlaybackThread().get();
Eric Laurent19952e12023-04-20 10:08:29 +02002229 if (!pt->waitForHalStart()) {
2230 ALOGW("%s(%d): timeout waiting for thread to exit standby", __func__, mId);
2231 stop();
2232 return 0;
2233 }
2234
2235 // enqueue the first buffer and exit so that other OutputTracks will also start before
2236 // write() is called again and this buffer actually consumed.
2237 Buffer firstBuffer;
2238 firstBuffer.frameCount = frames;
2239 firstBuffer.raw = data;
2240 queueBuffer(firstBuffer);
2241 return frames;
2242 } else {
2243 (void) start();
2244 }
2245 }
2246
Eric Laurent81784c32012-11-19 14:55:58 -08002247 Buffer *pInBuffer;
2248 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08002249 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08002250 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08002251 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurent81784c32012-11-19 14:55:58 -08002252 while (waitTimeLeftMs) {
2253 // First write pending buffers, then new data
2254 if (mBufferQueue.size()) {
2255 pInBuffer = mBufferQueue.itemAt(0);
2256 } else {
2257 pInBuffer = &inBuffer;
2258 }
2259
2260 if (pInBuffer->frameCount == 0) {
2261 break;
2262 }
2263
2264 if (mOutBuffer.frameCount == 0) {
2265 mOutBuffer.frameCount = pInBuffer->frameCount;
2266 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002267 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08002268 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Andy Hung9d84af52018-09-12 18:03:44 -07002269 ALOGV("%s(%d): thread %d no more output buffers; status %d",
2270 __func__, mId,
2271 (int)mThreadIoHandle, status);
Eric Laurent81784c32012-11-19 14:55:58 -08002272 break;
2273 }
2274 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2275 if (waitTimeLeftMs >= waitTimeMs) {
2276 waitTimeLeftMs -= waitTimeMs;
2277 } else {
2278 waitTimeLeftMs = 0;
2279 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08002280 if (status == NOT_ENOUGH_DATA) {
2281 restartIfDisabled();
2282 continue;
2283 }
Eric Laurent81784c32012-11-19 14:55:58 -08002284 }
2285
2286 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
2287 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08002288 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002289 Proxy::Buffer buf;
2290 buf.mFrameCount = outFrames;
2291 buf.mRaw = NULL;
2292 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08002293 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08002294 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08002295 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002296 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08002297 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002298
2299 if (pInBuffer->frameCount == 0) {
2300 if (mBufferQueue.size()) {
2301 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08002302 free(pInBuffer->mBuffer);
Yunlian Jiang8adc8082017-06-06 15:59:44 -07002303 if (pInBuffer != &inBuffer) {
2304 delete pInBuffer;
2305 }
Andy Hung9d84af52018-09-12 18:03:44 -07002306 ALOGV("%s(%d): thread %d released overflow buffer %zu",
2307 __func__, mId,
2308 (int)mThreadIoHandle, mBufferQueue.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002309 } else {
2310 break;
2311 }
2312 }
2313 }
2314
2315 // If we could not write all frames, allocate a buffer and queue it for next time.
2316 if (inBuffer.frameCount) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07002317 const sp<IAfThreadBase> thread = mThread.promote();
Andy Hung3e4c8742023-06-29 21:19:25 -07002318 if (thread != nullptr && !thread->inStandby()) {
Eric Laurent19952e12023-04-20 10:08:29 +02002319 queueBuffer(inBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002320 }
2321 }
2322
Andy Hungc25b84a2015-01-14 19:04:10 -08002323 // Calling write() with a 0 length buffer means that no more data will be written:
2324 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
2325 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
2326 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08002327 }
2328
Andy Hung1c86ebe2018-05-29 20:29:08 -07002329 return frames - inBuffer.frameCount; // number of frames consumed.
Eric Laurent81784c32012-11-19 14:55:58 -08002330}
2331
Andy Hung11e74242023-06-26 19:20:57 -07002332void OutputTrack::queueBuffer(Buffer& inBuffer) {
Eric Laurent19952e12023-04-20 10:08:29 +02002333
2334 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2335 Buffer *pInBuffer = new Buffer;
2336 const size_t bufferSize = inBuffer.frameCount * mFrameSize;
2337 pInBuffer->mBuffer = malloc(bufferSize);
2338 LOG_ALWAYS_FATAL_IF(pInBuffer->mBuffer == nullptr,
2339 "%s: Unable to malloc size %zu", __func__, bufferSize);
2340 pInBuffer->frameCount = inBuffer.frameCount;
2341 pInBuffer->raw = pInBuffer->mBuffer;
2342 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
2343 mBufferQueue.add(pInBuffer);
2344 ALOGV("%s(%d): thread %d adding overflow buffer %zu", __func__, mId,
2345 (int)mThreadIoHandle, mBufferQueue.size());
2346 // audio data is consumed (stored locally); set frameCount to 0.
2347 inBuffer.frameCount = 0;
2348 } else {
2349 ALOGW("%s(%d): thread %d no more overflow buffers",
2350 __func__, mId, (int)mThreadIoHandle);
2351 // TODO: return error for this.
2352 }
2353}
2354
Andy Hung11e74242023-06-26 19:20:57 -07002355void OutputTrack::copyMetadataTo(MetadataInserter& backInserter) const
Kevin Rocard12381092018-04-11 09:19:59 -07002356{
2357 std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
2358 backInserter = std::copy(mTrackMetadatas.begin(), mTrackMetadatas.end(), backInserter);
2359}
2360
Andy Hung11e74242023-06-26 19:20:57 -07002361void OutputTrack::setMetadatas(const SourceMetadatas& metadatas) {
Kevin Rocard12381092018-04-11 09:19:59 -07002362 {
2363 std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
2364 mTrackMetadatas = metadatas;
2365 }
2366 // No need to adjust metadata track volumes as OutputTrack volumes are always 0dBFS.
2367 setMetadataHasChanged();
2368}
2369
Andy Hung11e74242023-06-26 19:20:57 -07002370status_t OutputTrack::obtainBuffer(
Eric Laurent81784c32012-11-19 14:55:58 -08002371 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
2372{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002373 ClientProxy::Buffer buf;
2374 buf.mFrameCount = buffer->frameCount;
2375 struct timespec timeout;
2376 timeout.tv_sec = waitTimeMs / 1000;
2377 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
2378 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
2379 buffer->frameCount = buf.mFrameCount;
2380 buffer->raw = buf.mRaw;
2381 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002382}
2383
Andy Hung11e74242023-06-26 19:20:57 -07002384void OutputTrack::clearBufferQueue()
Eric Laurent81784c32012-11-19 14:55:58 -08002385{
2386 size_t size = mBufferQueue.size();
2387
2388 for (size_t i = 0; i < size; i++) {
2389 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08002390 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002391 delete pBuffer;
2392 }
2393 mBufferQueue.clear();
2394}
2395
Andy Hung11e74242023-06-26 19:20:57 -07002396void OutputTrack::restartIfDisabled()
Eric Laurent4d231dc2016-03-11 18:38:23 -08002397{
2398 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
2399 if (mActive && (flags & CBLK_DISABLED)) {
2400 start();
2401 }
2402}
Eric Laurent81784c32012-11-19 14:55:58 -08002403
Andy Hung9d84af52018-09-12 18:03:44 -07002404// ----------------------------------------------------------------------------
2405#undef LOG_TAG
2406#define LOG_TAG "AF::PatchTrack"
2407
Andy Hung11e74242023-06-26 19:20:57 -07002408/* static */
2409sp<IAfPatchTrack> IAfPatchTrack::create(
Andy Hung0c1e11e2023-07-06 20:56:16 -07002410 IAfPlaybackThread* playbackThread,
Andy Hung11e74242023-06-26 19:20:57 -07002411 audio_stream_type_t streamType,
2412 uint32_t sampleRate,
2413 audio_channel_mask_t channelMask,
2414 audio_format_t format,
2415 size_t frameCount,
2416 void* buffer,
2417 size_t bufferSize,
2418 audio_output_flags_t flags,
2419 const Timeout& timeout,
2420 size_t frameCountToBeReady /** Default behaviour is to start
2421 * as soon as possible to have
2422 * the lowest possible latency
2423 * even if it might glitch. */)
2424{
2425 return sp<PatchTrack>::make(
Andy Hung0c1e11e2023-07-06 20:56:16 -07002426 playbackThread,
Andy Hung11e74242023-06-26 19:20:57 -07002427 streamType,
2428 sampleRate,
2429 channelMask,
2430 format,
2431 frameCount,
2432 buffer,
2433 bufferSize,
2434 flags,
2435 timeout,
2436 frameCountToBeReady);
2437}
2438
Andy Hung0c1e11e2023-07-06 20:56:16 -07002439PatchTrack::PatchTrack(IAfPlaybackThread* playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07002440 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07002441 uint32_t sampleRate,
2442 audio_channel_mask_t channelMask,
2443 audio_format_t format,
2444 size_t frameCount,
2445 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07002446 size_t bufferSize,
Kevin Rocard45986c72018-12-18 18:22:59 -08002447 audio_output_flags_t flags,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01002448 const Timeout& timeout,
2449 size_t frameCountToBeReady)
Eric Laurent3bcf8592015-04-03 12:13:24 -07002450 : Track(playbackThread, NULL, streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002451 audio_attributes_t{} /* currently unused for patch track */,
Eric Laurent223fd5c2014-11-11 13:43:36 -08002452 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07002453 buffer, bufferSize, nullptr /* sharedBuffer */,
Svet Ganov33761132021-05-13 22:51:08 +00002454 AUDIO_SESSION_NONE, getpid(), audioServerAttributionSource(getpid()), flags,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002455 TYPE_PATCH, AUDIO_PORT_HANDLE_NONE, frameCountToBeReady),
gaoxiupei8e3a5682023-07-07 20:30:23 +08002456 PatchTrackBase(mCblk ? new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true)
2457 : nullptr,
Andy Hung7e888b32023-07-14 16:57:01 -07002458 playbackThread, timeout)
Eric Laurent83b88082014-06-20 18:31:16 -07002459{
Andy Hung9d84af52018-09-12 18:03:44 -07002460 ALOGV("%s(%d): sampleRate %d mPeerTimeout %d.%03d sec",
2461 __func__, mId, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07002462 (int)mPeerTimeout.tv_sec,
2463 (int)(mPeerTimeout.tv_nsec / 1000000));
2464}
2465
Andy Hung11e74242023-06-26 19:20:57 -07002466PatchTrack::~PatchTrack()
Eric Laurent83b88082014-06-20 18:31:16 -07002467{
Andy Hungabfab202019-03-07 19:45:54 -08002468 ALOGV("%s(%d)", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002469}
2470
Andy Hung11e74242023-06-26 19:20:57 -07002471size_t PatchTrack::framesReady() const
Mikhail Naganovcaf59942019-09-25 14:05:29 -07002472{
2473 if (mPeerProxy && mPeerProxy->producesBufferOnDemand()) {
2474 return std::numeric_limits<size_t>::max();
2475 } else {
2476 return Track::framesReady();
2477 }
2478}
2479
Andy Hung11e74242023-06-26 19:20:57 -07002480status_t PatchTrack::start(AudioSystem::sync_event_t event,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002481 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08002482{
2483 status_t status = Track::start(event, triggerSession);
2484 if (status != NO_ERROR) {
2485 return status;
2486 }
2487 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
2488 return status;
2489}
2490
Eric Laurent83b88082014-06-20 18:31:16 -07002491// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07002492status_t PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08002493 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07002494{
Andy Hung9d84af52018-09-12 18:03:44 -07002495 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002496 Proxy::Buffer buf;
2497 buf.mFrameCount = buffer->frameCount;
Mikhail Naganov938be412019-09-04 11:38:47 -07002498 if (ATRACE_ENABLED()) {
2499 std::string traceName("PTnReq");
2500 traceName += std::to_string(id());
2501 ATRACE_INT(traceName.c_str(), buf.mFrameCount);
2502 }
Eric Laurent83b88082014-06-20 18:31:16 -07002503 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
Andy Hung9d84af52018-09-12 18:03:44 -07002504 ALOGV_IF(status != NO_ERROR, "%s(%d): getNextBuffer status %d", __func__, mId, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002505 buffer->frameCount = buf.mFrameCount;
Mikhail Naganov938be412019-09-04 11:38:47 -07002506 if (ATRACE_ENABLED()) {
2507 std::string traceName("PTnObt");
2508 traceName += std::to_string(id());
2509 ATRACE_INT(traceName.c_str(), buf.mFrameCount);
2510 }
Eric Laurent83b88082014-06-20 18:31:16 -07002511 if (buf.mFrameCount == 0) {
2512 return WOULD_BLOCK;
2513 }
Glenn Kastend79072e2016-01-06 08:41:20 -08002514 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07002515 return status;
2516}
2517
Andy Hung11e74242023-06-26 19:20:57 -07002518void PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07002519{
Andy Hung9d84af52018-09-12 18:03:44 -07002520 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002521 Proxy::Buffer buf;
2522 buf.mFrameCount = buffer->frameCount;
2523 buf.mRaw = buffer->raw;
2524 mPeerProxy->releaseBuffer(&buf);
Andy Hung920f6572022-10-06 12:09:49 -07002525 TrackBase::releaseBuffer(buffer); // Note: this is the base class.
Eric Laurent83b88082014-06-20 18:31:16 -07002526}
2527
Andy Hung11e74242023-06-26 19:20:57 -07002528status_t PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
Eric Laurent83b88082014-06-20 18:31:16 -07002529 const struct timespec *timeOut)
2530{
Eric Laurent4d231dc2016-03-11 18:38:23 -08002531 status_t status = NO_ERROR;
2532 static const int32_t kMaxTries = 5;
2533 int32_t tryCounter = kMaxTries;
Andy Hungf62e1a22018-05-08 18:32:11 -07002534 const size_t originalFrameCount = buffer->mFrameCount;
Eric Laurent4d231dc2016-03-11 18:38:23 -08002535 do {
2536 if (status == NOT_ENOUGH_DATA) {
2537 restartIfDisabled();
Andy Hungf62e1a22018-05-08 18:32:11 -07002538 buffer->mFrameCount = originalFrameCount; // cleared on error, must be restored.
Eric Laurent4d231dc2016-03-11 18:38:23 -08002539 }
2540 status = mProxy->obtainBuffer(buffer, timeOut);
2541 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
2542 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07002543}
2544
Andy Hung11e74242023-06-26 19:20:57 -07002545void PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07002546{
2547 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08002548 restartIfDisabled();
naoki miyazuf37f9982019-11-28 11:18:18 +09002549
2550 // Check if the PatchTrack has enough data to write once in releaseBuffer().
2551 // If not, prevent an underrun from occurring by moving the track into FS_FILLING;
2552 // this logic avoids glitches when suspending A2DP with AudioPlaybackCapture.
2553 // TODO: perhaps underrun avoidance could be a track property checked in isReady() instead.
Andy Hung11e74242023-06-26 19:20:57 -07002554 if (mFillingStatus == FS_ACTIVE
naoki miyazuf37f9982019-11-28 11:18:18 +09002555 && audio_is_linear_pcm(mFormat)
2556 && !isOffloadedOrDirect()) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07002557 if (const sp<IAfThreadBase> thread = mThread.promote();
naoki miyazuf37f9982019-11-28 11:18:18 +09002558 thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07002559 auto* const playbackThread = thread->asIAfPlaybackThread().get();
naoki miyazuf37f9982019-11-28 11:18:18 +09002560 const size_t frameCount = playbackThread->frameCount() * sampleRate()
2561 / playbackThread->sampleRate();
2562 if (framesReady() < frameCount) {
2563 ALOGD("%s(%d) Not enough data, wait for buffer to fill", __func__, mId);
Andy Hung11e74242023-06-26 19:20:57 -07002564 mFillingStatus = FS_FILLING;
naoki miyazuf37f9982019-11-28 11:18:18 +09002565 }
2566 }
2567 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08002568}
2569
Andy Hung11e74242023-06-26 19:20:57 -07002570void PatchTrack::restartIfDisabled()
Eric Laurent4d231dc2016-03-11 18:38:23 -08002571{
Eric Laurent83b88082014-06-20 18:31:16 -07002572 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
Andy Hung9d84af52018-09-12 18:03:44 -07002573 ALOGW("%s(%d): disabled due to previous underrun, restarting", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002574 start();
2575 }
Eric Laurent83b88082014-06-20 18:31:16 -07002576}
2577
Eric Laurent81784c32012-11-19 14:55:58 -08002578// ----------------------------------------------------------------------------
2579// Record
2580// ----------------------------------------------------------------------------
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002581
2582
Andy Hung9d84af52018-09-12 18:03:44 -07002583#undef LOG_TAG
2584#define LOG_TAG "AF::RecordHandle"
Eric Laurent81784c32012-11-19 14:55:58 -08002585
Andy Hunga6426302023-06-23 19:27:19 -07002586class RecordHandle : public android::media::BnAudioRecord {
2587public:
Andy Hungfafbebc2023-06-23 19:27:19 -07002588 explicit RecordHandle(const sp<IAfRecordTrack>& recordTrack);
Andy Hunga6426302023-06-23 19:27:19 -07002589 ~RecordHandle() override;
2590 binder::Status start(int /*AudioSystem::sync_event_t*/ event,
2591 int /*audio_session_t*/ triggerSession) final;
2592 binder::Status stop() final;
2593 binder::Status getActiveMicrophones(
2594 std::vector<media::MicrophoneInfoFw>* activeMicrophones) final;
2595 binder::Status setPreferredMicrophoneDirection(
2596 int /*audio_microphone_direction_t*/ direction) final;
2597 binder::Status setPreferredMicrophoneFieldDimension(float zoom) final;
2598 binder::Status shareAudioHistory(
2599 const std::string& sharedAudioPackageName, int64_t sharedAudioStartMs) final;
2600
2601private:
Andy Hungfafbebc2023-06-23 19:27:19 -07002602 const sp<IAfRecordTrack> mRecordTrack;
Andy Hunga6426302023-06-23 19:27:19 -07002603
2604 // for use from destructor
2605 void stop_nonvirtual();
2606};
2607
2608/* static */
Andy Hungfafbebc2023-06-23 19:27:19 -07002609sp<media::IAudioRecord> IAfRecordTrack::createIAudioRecordAdapter(
2610 const sp<IAfRecordTrack>& recordTrack) {
Andy Hunga6426302023-06-23 19:27:19 -07002611 return sp<RecordHandle>::make(recordTrack);
2612}
2613
2614RecordHandle::RecordHandle(
Andy Hungfafbebc2023-06-23 19:27:19 -07002615 const sp<IAfRecordTrack>& recordTrack)
Eric Laurent81784c32012-11-19 14:55:58 -08002616 : BnAudioRecord(),
2617 mRecordTrack(recordTrack)
2618{
Andy Hung225aef62022-12-06 16:33:20 -08002619 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002620}
2621
Andy Hunga6426302023-06-23 19:27:19 -07002622RecordHandle::~RecordHandle() {
Eric Laurent81784c32012-11-19 14:55:58 -08002623 stop_nonvirtual();
2624 mRecordTrack->destroy();
2625}
2626
Andy Hunga6426302023-06-23 19:27:19 -07002627binder::Status RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Ivan Lozanoff6900d2017-08-01 15:47:38 -07002628 int /*audio_session_t*/ triggerSession) {
Andy Hung9d84af52018-09-12 18:03:44 -07002629 ALOGV("%s()", __func__);
Andy Hung1131b6e2020-12-08 20:47:45 -08002630 return binderStatusFromStatusT(
Ivan Lozanoff6900d2017-08-01 15:47:38 -07002631 mRecordTrack->start((AudioSystem::sync_event_t)event, (audio_session_t) triggerSession));
Eric Laurent81784c32012-11-19 14:55:58 -08002632}
2633
Andy Hunga6426302023-06-23 19:27:19 -07002634binder::Status RecordHandle::stop() {
Eric Laurent81784c32012-11-19 14:55:58 -08002635 stop_nonvirtual();
Ivan Lozanoff6900d2017-08-01 15:47:38 -07002636 return binder::Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -08002637}
2638
Andy Hunga6426302023-06-23 19:27:19 -07002639void RecordHandle::stop_nonvirtual() {
Andy Hung9d84af52018-09-12 18:03:44 -07002640 ALOGV("%s()", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08002641 mRecordTrack->stop();
2642}
2643
Andy Hunga6426302023-06-23 19:27:19 -07002644binder::Status RecordHandle::getActiveMicrophones(
Mikhail Naganovd5d9de72023-02-13 11:45:03 -08002645 std::vector<media::MicrophoneInfoFw>* activeMicrophones) {
Andy Hung9d84af52018-09-12 18:03:44 -07002646 ALOGV("%s()", __func__);
Mikhail Naganovd5d9de72023-02-13 11:45:03 -08002647 return binderStatusFromStatusT(mRecordTrack->getActiveMicrophones(activeMicrophones));
jiabin653cc0a2018-01-17 17:54:10 -08002648}
2649
Andy Hunga6426302023-06-23 19:27:19 -07002650binder::Status RecordHandle::setPreferredMicrophoneDirection(
Paul McLean03a6e6a2018-12-04 10:54:13 -07002651 int /*audio_microphone_direction_t*/ direction) {
2652 ALOGV("%s()", __func__);
Andy Hung1131b6e2020-12-08 20:47:45 -08002653 return binderStatusFromStatusT(mRecordTrack->setPreferredMicrophoneDirection(
Paul McLean03a6e6a2018-12-04 10:54:13 -07002654 static_cast<audio_microphone_direction_t>(direction)));
2655}
2656
Andy Hunga6426302023-06-23 19:27:19 -07002657binder::Status RecordHandle::setPreferredMicrophoneFieldDimension(float zoom) {
Paul McLean03a6e6a2018-12-04 10:54:13 -07002658 ALOGV("%s()", __func__);
Andy Hung1131b6e2020-12-08 20:47:45 -08002659 return binderStatusFromStatusT(mRecordTrack->setPreferredMicrophoneFieldDimension(zoom));
Paul McLean03a6e6a2018-12-04 10:54:13 -07002660}
2661
Andy Hunga6426302023-06-23 19:27:19 -07002662binder::Status RecordHandle::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02002663 const std::string& sharedAudioPackageName, int64_t sharedAudioStartMs) {
2664 return binderStatusFromStatusT(
2665 mRecordTrack->shareAudioHistory(sharedAudioPackageName, sharedAudioStartMs));
2666}
2667
Eric Laurent81784c32012-11-19 14:55:58 -08002668// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -07002669#undef LOG_TAG
2670#define LOG_TAG "AF::RecordTrack"
Eric Laurent81784c32012-11-19 14:55:58 -08002671
Andy Hung11e74242023-06-26 19:20:57 -07002672
Andy Hungeb6b5f82023-07-14 11:00:08 -07002673/* static */
Andy Hung0c1e11e2023-07-06 20:56:16 -07002674sp<IAfRecordTrack> IAfRecordTrack::create(IAfRecordThread* thread,
Andy Hung11e74242023-06-26 19:20:57 -07002675 const sp<Client>& client,
2676 const audio_attributes_t& attr,
2677 uint32_t sampleRate,
2678 audio_format_t format,
2679 audio_channel_mask_t channelMask,
2680 size_t frameCount,
2681 void* buffer,
2682 size_t bufferSize,
2683 audio_session_t sessionId,
2684 pid_t creatorPid,
2685 const AttributionSourceState& attributionSource,
2686 audio_input_flags_t flags,
2687 track_type type,
2688 audio_port_handle_t portId,
2689 int32_t startFrames)
2690{
2691 return sp<RecordTrack>::make(
Andy Hung0c1e11e2023-07-06 20:56:16 -07002692 thread,
Andy Hung11e74242023-06-26 19:20:57 -07002693 client,
2694 attr,
2695 sampleRate,
2696 format,
2697 channelMask,
2698 frameCount,
2699 buffer,
2700 bufferSize,
2701 sessionId,
2702 creatorPid,
2703 attributionSource,
2704 flags,
2705 type,
2706 portId,
2707 startFrames);
2708}
2709
Glenn Kasten05997e22014-03-13 15:08:33 -07002710// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Andy Hung11e74242023-06-26 19:20:57 -07002711RecordTrack::RecordTrack(
Andy Hung0c1e11e2023-07-06 20:56:16 -07002712 IAfRecordThread* thread,
Eric Laurent81784c32012-11-19 14:55:58 -08002713 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002714 const audio_attributes_t& attr,
Eric Laurent81784c32012-11-19 14:55:58 -08002715 uint32_t sampleRate,
2716 audio_format_t format,
2717 audio_channel_mask_t channelMask,
2718 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07002719 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07002720 size_t bufferSize,
Glenn Kastend848eb42016-03-08 13:42:11 -08002721 audio_session_t sessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002722 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002723 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07002724 audio_input_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002725 track_type type,
Eric Laurentec376dc2021-04-08 20:41:22 +02002726 audio_port_handle_t portId,
Eric Laurent2407ce32021-04-26 14:56:03 +02002727 int32_t startFrames)
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002728 : TrackBase(thread, client, attr, sampleRate, format,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002729 channelMask, frameCount, buffer, bufferSize, sessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002730 creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002731 VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002732 false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07002733 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07002734 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07002735 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
Andy Hungb68f5eb2019-12-03 16:49:17 -08002736 type, portId,
2737 std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_RECORD) + std::to_string(portId)),
Andy Hung97a893e2015-03-29 01:03:07 -07002738 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07002739 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07002740 mRecordBufferConverter(NULL),
jiabin9378eb92018-05-02 15:26:35 -07002741 mFlags(flags),
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002742 mSilenced(false),
Eric Laurent2407ce32021-04-26 14:56:03 +02002743 mStartFrames(startFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002744{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07002745 if (mCblk == NULL) {
2746 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002747 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002748
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002749 if (!isDirect()) {
2750 mRecordBufferConverter = new RecordBufferConverter(
Andy Hung0c1e11e2023-07-06 20:56:16 -07002751 thread->channelMask(), thread->format(), thread->sampleRate(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002752 channelMask, format, sampleRate);
2753 // Check if the RecordBufferConverter construction was successful.
2754 // If not, don't continue with construction.
2755 //
2756 // NOTE: It would be extremely rare that the record track cannot be created
2757 // for the current device, but a pending or future device change would make
2758 // the record track configuration valid.
2759 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
Andy Hung9d84af52018-09-12 18:03:44 -07002760 ALOGE("%s(%d): RecordTrack unable to create record buffer converter", __func__, mId);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002761 return;
2762 }
Andy Hung97a893e2015-03-29 01:03:07 -07002763 }
2764
Andy Hung6ae58432016-02-16 18:32:24 -08002765 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08002766 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08002767
Andy Hung97a893e2015-03-29 01:03:07 -07002768 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07002769
Eric Laurent05067782016-06-01 18:27:28 -07002770 if (flags & AUDIO_INPUT_FLAG_FAST) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07002771 ALOG_ASSERT(thread->fastTrackAvailable());
2772 thread->setFastTrackAvailable(false);
Andy Hung000adb52018-06-01 15:43:26 -07002773 } else {
2774 // TODO: only Normal Record has timestamps (Fast Record does not).
Andy Hung5d3d9562018-10-04 19:27:26 -07002775 mServerLatencySupported = checkServerLatencySupported(mFormat, flags);
Glenn Kastenc263ca02014-06-04 20:31:46 -07002776 }
Andy Hung8946a282018-04-19 20:04:56 -07002777#ifdef TEE_SINK
2778 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle)
2779 + "_" + std::to_string(mId)
2780 + "_R");
2781#endif
Andy Hungb68f5eb2019-12-03 16:49:17 -08002782
2783 // Once this item is logged by the server, the client can add properties.
Andy Hung94235282021-03-24 15:50:14 -07002784 mTrackMetrics.logConstructor(creatorPid, uid(), id());
Eric Laurent81784c32012-11-19 14:55:58 -08002785}
2786
Andy Hung11e74242023-06-26 19:20:57 -07002787RecordTrack::~RecordTrack()
Eric Laurent81784c32012-11-19 14:55:58 -08002788{
Andy Hung9d84af52018-09-12 18:03:44 -07002789 ALOGV("%s()", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07002790 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002791 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08002792}
2793
Andy Hung11e74242023-06-26 19:20:57 -07002794status_t RecordTrack::initCheck() const
Andy Hung97a893e2015-03-29 01:03:07 -07002795{
2796 status_t status = TrackBase::initCheck();
2797 if (status == NO_ERROR && mServerProxy == 0) {
2798 status = BAD_VALUE;
2799 }
2800 return status;
2801}
2802
Eric Laurent81784c32012-11-19 14:55:58 -08002803// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07002804status_t RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08002805{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002806 ServerProxy::Buffer buf;
2807 buf.mFrameCount = buffer->frameCount;
2808 status_t status = mServerProxy->obtainBuffer(&buf);
2809 buffer->frameCount = buf.mFrameCount;
2810 buffer->raw = buf.mRaw;
2811 if (buf.mFrameCount == 0) {
2812 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002813 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002814 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002815 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002816}
2817
Andy Hung11e74242023-06-26 19:20:57 -07002818status_t RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08002819 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08002820{
Andy Hung0c1e11e2023-07-06 20:56:16 -07002821 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002822 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07002823 auto* const recordThread = thread->asIAfRecordThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08002824 return recordThread->start(this, event, triggerSession);
2825 } else {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002826 ALOGW("%s track %d: thread was destroyed", __func__, portId());
2827 return DEAD_OBJECT;
Eric Laurent81784c32012-11-19 14:55:58 -08002828 }
2829}
2830
Andy Hung11e74242023-06-26 19:20:57 -07002831void RecordTrack::stop()
Eric Laurent81784c32012-11-19 14:55:58 -08002832{
Andy Hung0c1e11e2023-07-06 20:56:16 -07002833 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002834 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07002835 auto* const recordThread = thread->asIAfRecordThread().get();
Eric Laurent83b88082014-06-20 18:31:16 -07002836 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08002837 AudioSystem::stopInput(mPortId);
Eric Laurent81784c32012-11-19 14:55:58 -08002838 }
2839 }
2840}
2841
Andy Hung11e74242023-06-26 19:20:57 -07002842void RecordTrack::destroy()
Eric Laurent81784c32012-11-19 14:55:58 -08002843{
Andy Hung11e74242023-06-26 19:20:57 -07002844 // see comments at Track::destroy()
Eric Laurent81784c32012-11-19 14:55:58 -08002845 sp<RecordTrack> keep(this);
2846 {
Andy Hungce685402018-10-05 17:23:27 -07002847 track_state priorState = mState;
Andy Hung0c1e11e2023-07-06 20:56:16 -07002848 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002849 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07002850 Mutex::Autolock _l(thread->mutex());
2851 auto* const recordThread = thread->asIAfRecordThread().get();
Andy Hungce685402018-10-05 17:23:27 -07002852 priorState = mState;
Eric Laurentec376dc2021-04-08 20:41:22 +02002853 if (!mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02002854 recordThread->resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02002855 }
Andy Hungce685402018-10-05 17:23:27 -07002856 recordThread->destroyTrack_l(this); // move mState to STOPPED, terminate
2857 }
2858 // APM portid/client management done outside of lock.
2859 // NOTE: if thread doesn't exist, the input descriptor probably doesn't either.
2860 if (isExternalTrack()) {
2861 switch (priorState) {
2862 case ACTIVE: // invalidated while still active
2863 case STARTING_2: // invalidated/start-aborted after startInput successfully called
2864 case PAUSING: // invalidated while in the middle of stop() pausing (still active)
2865 AudioSystem::stopInput(mPortId);
2866 break;
2867
2868 case STARTING_1: // invalidated/start-aborted and startInput not successful
2869 case PAUSED: // OK, not active
2870 case IDLE: // OK, not active
2871 break;
2872
2873 case STOPPED: // unexpected (destroyed)
2874 default:
2875 LOG_ALWAYS_FATAL("%s(%d): invalid prior state: %d", __func__, mId, priorState);
2876 }
2877 AudioSystem::releaseInput(mPortId);
Eric Laurent81784c32012-11-19 14:55:58 -08002878 }
2879 }
2880}
2881
Andy Hung11e74242023-06-26 19:20:57 -07002882void RecordTrack::invalidate()
Eric Laurent9a54bc22013-09-09 09:08:44 -07002883{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002884 TrackBase::invalidate();
Eric Laurent9a54bc22013-09-09 09:08:44 -07002885 // FIXME should use proxy, and needs work
2886 audio_track_cblk_t* cblk = mCblk;
2887 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2888 android_atomic_release_store(0x40000000, &cblk->mFutex);
2889 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002890 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002891}
2892
Eric Laurent81784c32012-11-19 14:55:58 -08002893
Andy Hung11e74242023-06-26 19:20:57 -07002894void RecordTrack::appendDumpHeader(String8& result) const
Eric Laurent81784c32012-11-19 14:55:58 -08002895{
Eric Laurent973db022018-11-20 14:54:31 -08002896 result.appendFormat("Active Id Client Session Port Id S Flags "
Andy Hung9d84af52018-09-12 18:03:44 -07002897 " Format Chn mask SRate Source "
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002898 " Server FrmCnt FrmRdy Sil%s\n",
2899 isServerLatencySupported() ? " Latency" : "");
Eric Laurent81784c32012-11-19 14:55:58 -08002900}
2901
Andy Hung11e74242023-06-26 19:20:57 -07002902void RecordTrack::appendDump(String8& result, bool active) const
Eric Laurent81784c32012-11-19 14:55:58 -08002903{
Eric Laurent973db022018-11-20 14:54:31 -08002904 result.appendFormat("%c%5s %6d %6u %7u %7u %2s 0x%03X "
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002905 "%08X %08X %6u %6X "
Andy Hung000adb52018-06-01 15:43:26 -07002906 "%08X %6zu %6zu %3c",
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002907 isFastTrack() ? 'F' : ' ',
Marco Nelissenb2208842014-02-07 14:00:50 -08002908 active ? "yes" : "no",
Andy Hung9d84af52018-09-12 18:03:44 -07002909 mId,
Andy Hung4ef19fa2018-05-15 19:35:29 -07002910 (mClient == 0) ? getpid() : mClient->pid(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002911 mSessionId,
Eric Laurent973db022018-11-20 14:54:31 -08002912 mPortId,
Andy Hunge2e830f2019-12-03 12:54:46 -08002913 getTrackStateAsCodedString(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002914 mCblk->mFlags,
2915
Eric Laurent81784c32012-11-19 14:55:58 -08002916 mFormat,
2917 mChannelMask,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002918 mSampleRate,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002919 mAttr.source,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002920
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002921 mCblk->mServer,
Jean-Michel Trivi7d665ab2018-04-11 17:26:51 -07002922 mFrameCount,
Andy Hung000adb52018-06-01 15:43:26 -07002923 mServerProxy->framesReadySafe(),
Jean-Michel Trivi7d665ab2018-04-11 17:26:51 -07002924 isSilenced() ? 's' : 'n'
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002925 );
Andy Hung000adb52018-06-01 15:43:26 -07002926 if (isServerLatencySupported()) {
2927 double latencyMs;
2928 bool fromTrack;
2929 if (getTrackLatencyMs(&latencyMs, &fromTrack) == OK) {
2930 // Show latency in msec, followed by 't' if from track timestamp (the most accurate)
2931 // or 'k' if estimated from kernel (usually for debugging).
2932 result.appendFormat(" %7.2lf %c", latencyMs, fromTrack ? 't' : 'k');
2933 } else {
2934 result.appendFormat("%10s", mCblk->mServer != 0 ? "unavail" : "new");
2935 }
2936 }
2937 result.append("\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002938}
2939
Andy Hung93bb5732023-05-04 21:16:34 -07002940// This is invoked by SyncEvent callback.
Andy Hung11e74242023-06-26 19:20:57 -07002941void RecordTrack::handleSyncStartEvent(
Andy Hung068e08e2023-05-15 19:02:55 -07002942 const sp<audioflinger::SyncEvent>& event)
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002943{
Andy Hung93bb5732023-05-04 21:16:34 -07002944 size_t framesToDrop = 0;
Andy Hung0c1e11e2023-07-06 20:56:16 -07002945 const sp<IAfThreadBase> threadBase = mThread.promote();
Andy Hung93bb5732023-05-04 21:16:34 -07002946 if (threadBase != 0) {
2947 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2948 // from audio HAL
Andy Hung0c1e11e2023-07-06 20:56:16 -07002949 framesToDrop = threadBase->frameCount() * 2;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002950 }
Andy Hung93bb5732023-05-04 21:16:34 -07002951
2952 mSynchronizedRecordState.onPlaybackFinished(event, framesToDrop);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002953}
2954
Andy Hung11e74242023-06-26 19:20:57 -07002955void RecordTrack::clearSyncStartEvent()
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002956{
Andy Hung93bb5732023-05-04 21:16:34 -07002957 mSynchronizedRecordState.clear();
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002958}
2959
Andy Hung11e74242023-06-26 19:20:57 -07002960void RecordTrack::updateTrackFrameInfo(
Andy Hung3f0c9022016-01-15 17:49:46 -08002961 int64_t trackFramesReleased, int64_t sourceFramesRead,
2962 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
2963{
Andy Hung30282562018-08-08 18:27:03 -07002964 // Make the kernel frametime available.
2965 const FrameTime ft{
2966 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
2967 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]};
2968 // ALOGD("FrameTime: %lld %lld", (long long)ft.frames, (long long)ft.timeNs);
2969 mKernelFrameTime.store(ft);
2970 if (!audio_is_linear_pcm(mFormat)) {
Atneya Nair497fff12022-01-18 16:23:04 -05002971 // Stream is direct, return provided timestamp with no conversion
2972 mServerProxy->setTimestamp(timestamp);
Andy Hung30282562018-08-08 18:27:03 -07002973 return;
2974 }
2975
Andy Hung3f0c9022016-01-15 17:49:46 -08002976 ExtendedTimestamp local = timestamp;
2977
2978 // Convert HAL frames to server-side track frames at track sample rate.
2979 // We use trackFramesReleased and sourceFramesRead as an anchor point.
2980 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2981 if (local.mTimeNs[i] != 0) {
2982 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
2983 const int64_t relativeTrackFrames = relativeServerFrames
2984 * mSampleRate / halSampleRate; // TODO: potential computation overflow
2985 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
2986 }
2987 }
Andy Hung6ae58432016-02-16 18:32:24 -08002988 mServerProxy->setTimestamp(local);
Andy Hung000adb52018-06-01 15:43:26 -07002989
2990 // Compute latency info.
2991 const bool useTrackTimestamp = true; // use track unless debugging.
2992 const double latencyMs = - (useTrackTimestamp
2993 ? local.getOutputServerLatencyMs(sampleRate())
2994 : timestamp.getOutputServerLatencyMs(halSampleRate));
2995
2996 mServerLatencyFromTrack.store(useTrackTimestamp);
2997 mServerLatencyMs.store(latencyMs);
Andy Hung3f0c9022016-01-15 17:49:46 -08002998}
Eric Laurent83b88082014-06-20 18:31:16 -07002999
Andy Hung11e74242023-06-26 19:20:57 -07003000status_t RecordTrack::getActiveMicrophones(
Andy Hungfafbebc2023-06-23 19:27:19 -07003001 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08003002{
Andy Hung0c1e11e2023-07-06 20:56:16 -07003003 const sp<IAfThreadBase> thread = mThread.promote();
jiabin653cc0a2018-01-17 17:54:10 -08003004 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07003005 auto* const recordThread = thread->asIAfRecordThread().get();
jiabin653cc0a2018-01-17 17:54:10 -08003006 return recordThread->getActiveMicrophones(activeMicrophones);
3007 } else {
3008 return BAD_VALUE;
3009 }
3010}
3011
Andy Hung11e74242023-06-26 19:20:57 -07003012status_t RecordTrack::setPreferredMicrophoneDirection(
Paul McLean03a6e6a2018-12-04 10:54:13 -07003013 audio_microphone_direction_t direction) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07003014 const sp<IAfThreadBase> thread = mThread.promote();
Paul McLean03a6e6a2018-12-04 10:54:13 -07003015 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07003016 auto* const recordThread = thread->asIAfRecordThread().get();
Paul McLean12340082019-03-19 09:35:05 -06003017 return recordThread->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07003018 } else {
3019 return BAD_VALUE;
3020 }
3021}
3022
Andy Hung11e74242023-06-26 19:20:57 -07003023status_t RecordTrack::setPreferredMicrophoneFieldDimension(float zoom) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07003024 const sp<IAfThreadBase> thread = mThread.promote();
Paul McLean03a6e6a2018-12-04 10:54:13 -07003025 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07003026 auto* const recordThread = thread->asIAfRecordThread().get();
Paul McLean12340082019-03-19 09:35:05 -06003027 return recordThread->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07003028 } else {
3029 return BAD_VALUE;
3030 }
3031}
3032
Andy Hung11e74242023-06-26 19:20:57 -07003033status_t RecordTrack::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02003034 const std::string& sharedAudioPackageName, int64_t sharedAudioStartMs) {
3035
3036 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
3037 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3038 if (callingUid != mUid || callingPid != mCreatorPid) {
3039 return PERMISSION_DENIED;
3040 }
3041
Svet Ganov33761132021-05-13 22:51:08 +00003042 AttributionSourceState attributionSource{};
3043 attributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
3044 attributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingPid));
3045 attributionSource.token = sp<BBinder>::make();
3046 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02003047 return PERMISSION_DENIED;
3048 }
3049
Andy Hung0c1e11e2023-07-06 20:56:16 -07003050 const sp<IAfThreadBase> thread = mThread.promote();
Eric Laurentec376dc2021-04-08 20:41:22 +02003051 if (thread != 0) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07003052 auto* const recordThread = thread->asIAfRecordThread().get();
Eric Laurentec376dc2021-04-08 20:41:22 +02003053 status_t status = recordThread->shareAudioHistory(
3054 sharedAudioPackageName, mSessionId, sharedAudioStartMs);
3055 if (status == NO_ERROR) {
3056 mSharedAudioPackageName = sharedAudioPackageName;
3057 }
3058 return status;
3059 } else {
3060 return BAD_VALUE;
3061 }
3062}
3063
Andy Hung11e74242023-06-26 19:20:57 -07003064void RecordTrack::copyMetadataTo(MetadataInserter& backInserter) const
Eric Laurent78b07302022-10-07 16:20:34 +02003065{
3066
3067 // Do not forward PatchRecord metadata with unspecified audio source
3068 if (mAttr.source == AUDIO_SOURCE_DEFAULT) {
3069 return;
3070 }
3071
3072 // No track is invalid as this is called after prepareTrack_l in the same critical section
3073 record_track_metadata_v7_t metadata;
3074 metadata.base = {
3075 .source = mAttr.source,
3076 .gain = 1, // capture tracks do not have volumes
3077 };
3078 metadata.channel_mask = mChannelMask;
3079 strncpy(metadata.tags, mAttr.tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
3080
3081 *backInserter++ = metadata;
3082}
Eric Laurentec376dc2021-04-08 20:41:22 +02003083
Andy Hung9d84af52018-09-12 18:03:44 -07003084// ----------------------------------------------------------------------------
3085#undef LOG_TAG
3086#define LOG_TAG "AF::PatchRecord"
3087
Andy Hung11e74242023-06-26 19:20:57 -07003088/* static */
3089sp<IAfPatchRecord> IAfPatchRecord::create(
Andy Hung0c1e11e2023-07-06 20:56:16 -07003090 IAfRecordThread* recordThread,
Andy Hung11e74242023-06-26 19:20:57 -07003091 uint32_t sampleRate,
3092 audio_channel_mask_t channelMask,
3093 audio_format_t format,
3094 size_t frameCount,
3095 void *buffer,
3096 size_t bufferSize,
3097 audio_input_flags_t flags,
3098 const Timeout& timeout,
3099 audio_source_t source)
3100{
3101 return sp<PatchRecord>::make(
Andy Hung0c1e11e2023-07-06 20:56:16 -07003102 recordThread,
Andy Hung11e74242023-06-26 19:20:57 -07003103 sampleRate,
3104 channelMask,
3105 format,
3106 frameCount,
3107 buffer,
3108 bufferSize,
3109 flags,
3110 timeout,
3111 source);
3112}
3113
Andy Hung0c1e11e2023-07-06 20:56:16 -07003114PatchRecord::PatchRecord(IAfRecordThread* recordThread,
Eric Laurent83b88082014-06-20 18:31:16 -07003115 uint32_t sampleRate,
3116 audio_channel_mask_t channelMask,
3117 audio_format_t format,
3118 size_t frameCount,
3119 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07003120 size_t bufferSize,
Kevin Rocard45986c72018-12-18 18:22:59 -08003121 audio_input_flags_t flags,
Eric Laurent78b07302022-10-07 16:20:34 +02003122 const Timeout& timeout,
3123 audio_source_t source)
Kevin Rocard1f564ac2018-03-29 13:53:10 -07003124 : RecordTrack(recordThread, NULL,
Eric Laurent78b07302022-10-07 16:20:34 +02003125 audio_attributes_t{ .source = source } ,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07003126 sampleRate, format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003127 buffer, bufferSize, AUDIO_SESSION_NONE, getpid(),
Svet Ganov33761132021-05-13 22:51:08 +00003128 audioServerAttributionSource(getpid()), flags, TYPE_PATCH),
gaoxiupei8e3a5682023-07-07 20:30:23 +08003129 PatchTrackBase(mCblk ? new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true)
3130 : nullptr,
Andy Hung7e888b32023-07-14 16:57:01 -07003131 recordThread, timeout)
Eric Laurent83b88082014-06-20 18:31:16 -07003132{
Andy Hung9d84af52018-09-12 18:03:44 -07003133 ALOGV("%s(%d): sampleRate %d mPeerTimeout %d.%03d sec",
3134 __func__, mId, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07003135 (int)mPeerTimeout.tv_sec,
3136 (int)(mPeerTimeout.tv_nsec / 1000000));
3137}
3138
Andy Hung11e74242023-06-26 19:20:57 -07003139PatchRecord::~PatchRecord()
Eric Laurent83b88082014-06-20 18:31:16 -07003140{
Andy Hungabfab202019-03-07 19:45:54 -08003141 ALOGV("%s(%d)", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07003142}
3143
Mikhail Naganov8296c252019-09-25 14:59:54 -07003144static size_t writeFramesHelper(
3145 AudioBufferProvider* dest, const void* src, size_t frameCount, size_t frameSize)
3146{
3147 AudioBufferProvider::Buffer patchBuffer;
3148 patchBuffer.frameCount = frameCount;
3149 auto status = dest->getNextBuffer(&patchBuffer);
3150 if (status != NO_ERROR) {
3151 ALOGW("%s PathRecord getNextBuffer failed with error %d: %s",
3152 __func__, status, strerror(-status));
3153 return 0;
3154 }
3155 ALOG_ASSERT(patchBuffer.frameCount <= frameCount);
3156 memcpy(patchBuffer.raw, src, patchBuffer.frameCount * frameSize);
3157 size_t framesWritten = patchBuffer.frameCount;
3158 dest->releaseBuffer(&patchBuffer);
3159 return framesWritten;
3160}
3161
3162// static
Andy Hung11e74242023-06-26 19:20:57 -07003163size_t PatchRecord::writeFrames(
Mikhail Naganov8296c252019-09-25 14:59:54 -07003164 AudioBufferProvider* dest, const void* src, size_t frameCount, size_t frameSize)
3165{
3166 size_t framesWritten = writeFramesHelper(dest, src, frameCount, frameSize);
3167 // On buffer wrap, the buffer frame count will be less than requested,
3168 // when this happens a second buffer needs to be used to write the leftover audio
3169 const size_t framesLeft = frameCount - framesWritten;
3170 if (framesWritten != 0 && framesLeft != 0) {
3171 framesWritten += writeFramesHelper(dest, (const char*)src + framesWritten * frameSize,
3172 framesLeft, frameSize);
3173 }
3174 return framesWritten;
3175}
3176
Eric Laurent83b88082014-06-20 18:31:16 -07003177// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07003178status_t PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08003179 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07003180{
Andy Hung9d84af52018-09-12 18:03:44 -07003181 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07003182 Proxy::Buffer buf;
3183 buf.mFrameCount = buffer->frameCount;
3184 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
3185 ALOGV_IF(status != NO_ERROR,
Andy Hung9d84af52018-09-12 18:03:44 -07003186 "%s(%d): mPeerProxy->obtainBuffer status %d", __func__, mId, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07003187 buffer->frameCount = buf.mFrameCount;
Mikhail Naganov938be412019-09-04 11:38:47 -07003188 if (ATRACE_ENABLED()) {
3189 std::string traceName("PRnObt");
3190 traceName += std::to_string(id());
3191 ATRACE_INT(traceName.c_str(), buf.mFrameCount);
3192 }
Eric Laurent83b88082014-06-20 18:31:16 -07003193 if (buf.mFrameCount == 0) {
3194 return WOULD_BLOCK;
3195 }
Glenn Kastend79072e2016-01-06 08:41:20 -08003196 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07003197 return status;
3198}
3199
Andy Hung11e74242023-06-26 19:20:57 -07003200void PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07003201{
Andy Hung9d84af52018-09-12 18:03:44 -07003202 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07003203 Proxy::Buffer buf;
3204 buf.mFrameCount = buffer->frameCount;
3205 buf.mRaw = buffer->raw;
3206 mPeerProxy->releaseBuffer(&buf);
3207 TrackBase::releaseBuffer(buffer);
3208}
3209
Andy Hung11e74242023-06-26 19:20:57 -07003210status_t PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
Eric Laurent83b88082014-06-20 18:31:16 -07003211 const struct timespec *timeOut)
3212{
3213 return mProxy->obtainBuffer(buffer, timeOut);
3214}
3215
Andy Hung11e74242023-06-26 19:20:57 -07003216void PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07003217{
3218 mProxy->releaseBuffer(buffer);
3219}
3220
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003221#undef LOG_TAG
3222#define LOG_TAG "AF::PthrPatchRecord"
3223
3224static std::unique_ptr<void, decltype(free)*> allocAligned(size_t alignment, size_t size)
3225{
3226 void *ptr = nullptr;
3227 (void)posix_memalign(&ptr, alignment, size);
Andy Hung920f6572022-10-06 12:09:49 -07003228 return {ptr, free};
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003229}
3230
Andy Hung11e74242023-06-26 19:20:57 -07003231/* static */
3232sp<IAfPatchRecord> IAfPatchRecord::createPassThru(
Andy Hung0c1e11e2023-07-06 20:56:16 -07003233 IAfRecordThread* recordThread,
Andy Hung11e74242023-06-26 19:20:57 -07003234 uint32_t sampleRate,
3235 audio_channel_mask_t channelMask,
3236 audio_format_t format,
3237 size_t frameCount,
3238 audio_input_flags_t flags,
3239 audio_source_t source)
3240{
3241 return sp<PassthruPatchRecord>::make(
Andy Hung0c1e11e2023-07-06 20:56:16 -07003242 recordThread,
Andy Hung11e74242023-06-26 19:20:57 -07003243 sampleRate,
3244 channelMask,
3245 format,
3246 frameCount,
3247 flags,
3248 source);
3249}
3250
3251PassthruPatchRecord::PassthruPatchRecord(
Andy Hung0c1e11e2023-07-06 20:56:16 -07003252 IAfRecordThread* recordThread,
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003253 uint32_t sampleRate,
3254 audio_channel_mask_t channelMask,
3255 audio_format_t format,
3256 size_t frameCount,
Eric Laurent78b07302022-10-07 16:20:34 +02003257 audio_input_flags_t flags,
3258 audio_source_t source)
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003259 : PatchRecord(recordThread, sampleRate, channelMask, format, frameCount,
Eric Laurent78b07302022-10-07 16:20:34 +02003260 nullptr /*buffer*/, 0 /*bufferSize*/, flags, {} /* timeout */, source),
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003261 mPatchRecordAudioBufferProvider(*this),
3262 mSinkBuffer(allocAligned(32, mFrameCount * mFrameSize)),
3263 mStubBuffer(allocAligned(32, mFrameCount * mFrameSize))
3264{
3265 memset(mStubBuffer.get(), 0, mFrameCount * mFrameSize);
3266}
3267
Andy Hung11e74242023-06-26 19:20:57 -07003268sp<StreamInHalInterface> PassthruPatchRecord::obtainStream(
Andy Hung0c1e11e2023-07-06 20:56:16 -07003269 sp<IAfThreadBase>* thread)
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003270{
3271 *thread = mThread.promote();
3272 if (!*thread) return nullptr;
Andy Hung0c1e11e2023-07-06 20:56:16 -07003273 auto* const recordThread = (*thread)->asIAfRecordThread().get();
3274 Mutex::Autolock _l(recordThread->mutex());
3275 return recordThread->getInput() ? recordThread->getInput()->stream : nullptr;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003276}
3277
3278// PatchProxyBufferProvider methods are called on DirectOutputThread
Andy Hung11e74242023-06-26 19:20:57 -07003279status_t PassthruPatchRecord::obtainBuffer(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003280 Proxy::Buffer* buffer, const struct timespec* timeOut)
3281{
3282 if (mUnconsumedFrames) {
3283 buffer->mFrameCount = std::min(buffer->mFrameCount, mUnconsumedFrames);
3284 // mUnconsumedFrames is decreased in releaseBuffer to use actual frame consumption figure.
3285 return PatchRecord::obtainBuffer(buffer, timeOut);
3286 }
3287
3288 // Otherwise, execute a read from HAL and write into the buffer.
3289 nsecs_t startTimeNs = 0;
3290 if (timeOut && (timeOut->tv_sec != 0 || timeOut->tv_nsec != 0) && timeOut->tv_sec != INT_MAX) {
3291 // Will need to correct timeOut by elapsed time.
3292 startTimeNs = systemTime();
3293 }
3294 const size_t framesToRead = std::min(buffer->mFrameCount, mFrameCount);
3295 buffer->mFrameCount = 0;
3296 buffer->mRaw = nullptr;
Andy Hung0c1e11e2023-07-06 20:56:16 -07003297 sp<IAfThreadBase> thread;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003298 sp<StreamInHalInterface> stream = obtainStream(&thread);
3299 if (!stream) return NO_INIT; // If there is no stream, RecordThread is not reading.
3300
3301 status_t result = NO_ERROR;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003302 size_t bytesRead = 0;
3303 {
3304 ATRACE_NAME("read");
3305 result = stream->read(mSinkBuffer.get(), framesToRead * mFrameSize, &bytesRead);
3306 if (result != NO_ERROR) goto stream_error;
3307 if (bytesRead == 0) return NO_ERROR;
3308 }
3309
3310 {
3311 std::lock_guard<std::mutex> lock(mReadLock);
3312 mReadBytes += bytesRead;
3313 mReadError = NO_ERROR;
3314 }
3315 mReadCV.notify_one();
3316 // writeFrames handles wraparound and should write all the provided frames.
3317 // If it couldn't, there is something wrong with the client/server buffer of the software patch.
3318 buffer->mFrameCount = writeFrames(
3319 &mPatchRecordAudioBufferProvider,
3320 mSinkBuffer.get(), bytesRead / mFrameSize, mFrameSize);
3321 ALOGW_IF(buffer->mFrameCount < bytesRead / mFrameSize,
3322 "Lost %zu frames obtained from HAL", bytesRead / mFrameSize - buffer->mFrameCount);
3323 mUnconsumedFrames = buffer->mFrameCount;
Mikhail Naganov4de49972019-10-07 09:53:58 -07003324 struct timespec newTimeOut;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003325 if (startTimeNs) {
Mikhail Naganov4de49972019-10-07 09:53:58 -07003326 // Correct the timeout by elapsed time.
3327 nsecs_t newTimeOutNs = audio_utils_ns_from_timespec(timeOut) - (systemTime() - startTimeNs);
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003328 if (newTimeOutNs < 0) newTimeOutNs = 0;
3329 newTimeOut.tv_sec = newTimeOutNs / NANOS_PER_SECOND;
3330 newTimeOut.tv_nsec = newTimeOutNs - newTimeOut.tv_sec * NANOS_PER_SECOND;
Mikhail Naganov4de49972019-10-07 09:53:58 -07003331 timeOut = &newTimeOut;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003332 }
Mikhail Naganov4de49972019-10-07 09:53:58 -07003333 return PatchRecord::obtainBuffer(buffer, timeOut);
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003334
3335stream_error:
3336 stream->standby();
3337 {
3338 std::lock_guard<std::mutex> lock(mReadLock);
3339 mReadError = result;
3340 }
3341 mReadCV.notify_one();
3342 return result;
3343}
3344
Andy Hung11e74242023-06-26 19:20:57 -07003345void PassthruPatchRecord::releaseBuffer(Proxy::Buffer* buffer)
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003346{
3347 if (buffer->mFrameCount <= mUnconsumedFrames) {
3348 mUnconsumedFrames -= buffer->mFrameCount;
3349 } else {
3350 ALOGW("Write side has consumed more frames than we had: %zu > %zu",
3351 buffer->mFrameCount, mUnconsumedFrames);
3352 mUnconsumedFrames = 0;
3353 }
3354 PatchRecord::releaseBuffer(buffer);
3355}
3356
3357// AudioBufferProvider and Source methods are called on RecordThread
3358// 'read' emulates actual audio data with 0's. This is OK as 'getNextBuffer'
3359// and 'releaseBuffer' are stubbed out and ignore their input.
3360// It's not possible to retrieve actual data here w/o blocking 'obtainBuffer'
3361// until we copy it.
Andy Hung11e74242023-06-26 19:20:57 -07003362status_t PassthruPatchRecord::read(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003363 void* buffer, size_t bytes, size_t* read)
3364{
3365 bytes = std::min(bytes, mFrameCount * mFrameSize);
3366 {
3367 std::unique_lock<std::mutex> lock(mReadLock);
3368 mReadCV.wait(lock, [&]{ return mReadError != NO_ERROR || mReadBytes != 0; });
3369 if (mReadError != NO_ERROR) {
3370 mLastReadFrames = 0;
3371 return mReadError;
3372 }
3373 *read = std::min(bytes, mReadBytes);
3374 mReadBytes -= *read;
3375 }
3376 mLastReadFrames = *read / mFrameSize;
3377 memset(buffer, 0, *read);
3378 return 0;
3379}
3380
Andy Hung11e74242023-06-26 19:20:57 -07003381status_t PassthruPatchRecord::getCapturePosition(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003382 int64_t* frames, int64_t* time)
3383{
Andy Hung0c1e11e2023-07-06 20:56:16 -07003384 sp<IAfThreadBase> thread;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003385 sp<StreamInHalInterface> stream = obtainStream(&thread);
3386 return stream ? stream->getCapturePosition(frames, time) : NO_INIT;
3387}
3388
Andy Hung11e74242023-06-26 19:20:57 -07003389status_t PassthruPatchRecord::standby()
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003390{
3391 // RecordThread issues 'standby' command in two major cases:
3392 // 1. Error on read--this case is handled in 'obtainBuffer'.
3393 // 2. Track is stopping--as PassthruPatchRecord assumes continuous
3394 // output, this can only happen when the software patch
3395 // is being torn down. In this case, the RecordThread
3396 // will terminate and close the HAL stream.
3397 return 0;
3398}
3399
3400// As the buffer gets filled in obtainBuffer, here we only simulate data consumption.
Andy Hung11e74242023-06-26 19:20:57 -07003401status_t PassthruPatchRecord::getNextBuffer(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003402 AudioBufferProvider::Buffer* buffer)
3403{
3404 buffer->frameCount = mLastReadFrames;
3405 buffer->raw = buffer->frameCount != 0 ? mStubBuffer.get() : nullptr;
3406 return NO_ERROR;
3407}
3408
Andy Hung11e74242023-06-26 19:20:57 -07003409void PassthruPatchRecord::releaseBuffer(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003410 AudioBufferProvider::Buffer* buffer)
3411{
3412 buffer->frameCount = 0;
3413 buffer->raw = nullptr;
3414}
3415
Andy Hung9d84af52018-09-12 18:03:44 -07003416// ----------------------------------------------------------------------------
3417#undef LOG_TAG
3418#define LOG_TAG "AF::MmapTrack"
Eric Laurent6acd1d42017-01-04 14:23:29 -08003419
Andy Hung11e74242023-06-26 19:20:57 -07003420/* static */
Andy Hung0c1e11e2023-07-06 20:56:16 -07003421sp<IAfMmapTrack> IAfMmapTrack::create(IAfThreadBase* thread,
Andy Hung11e74242023-06-26 19:20:57 -07003422 const audio_attributes_t& attr,
3423 uint32_t sampleRate,
3424 audio_format_t format,
3425 audio_channel_mask_t channelMask,
3426 audio_session_t sessionId,
3427 bool isOut,
3428 const android::content::AttributionSourceState& attributionSource,
3429 pid_t creatorPid,
3430 audio_port_handle_t portId)
3431{
3432 return sp<MmapTrack>::make(
Andy Hung0c1e11e2023-07-06 20:56:16 -07003433 thread,
Andy Hung11e74242023-06-26 19:20:57 -07003434 attr,
3435 sampleRate,
3436 format,
3437 channelMask,
3438 sessionId,
3439 isOut,
3440 attributionSource,
3441 creatorPid,
3442 portId);
3443}
3444
Andy Hung0c1e11e2023-07-06 20:56:16 -07003445MmapTrack::MmapTrack(IAfThreadBase* thread,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07003446 const audio_attributes_t& attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08003447 uint32_t sampleRate,
3448 audio_format_t format,
3449 audio_channel_mask_t channelMask,
3450 audio_session_t sessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07003451 bool isOut,
Svet Ganov33761132021-05-13 22:51:08 +00003452 const AttributionSourceState& attributionSource,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003453 pid_t creatorPid,
Eric Laurent6acd1d42017-01-04 14:23:29 -08003454 audio_port_handle_t portId)
Kevin Rocard1f564ac2018-03-29 13:53:10 -07003455 : TrackBase(thread, NULL, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07003456 channelMask, (size_t)0 /* frameCount */,
3457 nullptr /* buffer */, (size_t)0 /* bufferSize */,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003458 sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00003459 VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003460 isOut,
Eric Laurent6acd1d42017-01-04 14:23:29 -08003461 ALLOC_NONE,
Andy Hungc2b11cb2020-04-22 09:04:01 -07003462 TYPE_DEFAULT, portId,
3463 std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_MMAP) + std::to_string(portId)),
Svet Ganov33761132021-05-13 22:51:08 +00003464 mPid(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.pid))),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003465 mSilenced(false), mSilencedNotified(false)
Eric Laurent6acd1d42017-01-04 14:23:29 -08003466{
Andy Hungc2b11cb2020-04-22 09:04:01 -07003467 // Once this item is logged by the server, the client can add properties.
Andy Hung94235282021-03-24 15:50:14 -07003468 mTrackMetrics.logConstructor(creatorPid, uid(), id());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003469}
3470
Andy Hung11e74242023-06-26 19:20:57 -07003471MmapTrack::~MmapTrack()
Eric Laurent6acd1d42017-01-04 14:23:29 -08003472{
3473}
3474
Andy Hung11e74242023-06-26 19:20:57 -07003475status_t MmapTrack::initCheck() const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003476{
3477 return NO_ERROR;
3478}
3479
Andy Hung11e74242023-06-26 19:20:57 -07003480status_t MmapTrack::start(AudioSystem::sync_event_t event __unused,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07003481 audio_session_t triggerSession __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08003482{
3483 return NO_ERROR;
3484}
3485
Andy Hung11e74242023-06-26 19:20:57 -07003486void MmapTrack::stop()
Eric Laurent6acd1d42017-01-04 14:23:29 -08003487{
3488}
3489
3490// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07003491status_t MmapTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent6acd1d42017-01-04 14:23:29 -08003492{
3493 buffer->frameCount = 0;
3494 buffer->raw = nullptr;
3495 return INVALID_OPERATION;
3496}
3497
3498// ExtendedAudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07003499size_t MmapTrack::framesReady() const {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003500 return 0;
3501}
3502
Andy Hung11e74242023-06-26 19:20:57 -07003503int64_t MmapTrack::framesReleased() const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003504{
3505 return 0;
3506}
3507
Andy Hung11e74242023-06-26 19:20:57 -07003508void MmapTrack::onTimestamp(const ExtendedTimestamp& timestamp __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08003509{
3510}
3511
Andy Hung11e74242023-06-26 19:20:57 -07003512void MmapTrack::processMuteEvent_l(const sp<IAudioManager>& audioManager, mute_state_t muteState)
Vlad Popaec1788e2022-08-04 11:23:30 +02003513{
3514 if (mMuteState == muteState) {
3515 // mute state did not change, do nothing
3516 return;
3517 }
3518
3519 status_t result = UNKNOWN_ERROR;
3520 if (audioManager && mPortId != AUDIO_PORT_HANDLE_NONE) {
3521 if (mMuteEventExtras == nullptr) {
3522 mMuteEventExtras = std::make_unique<os::PersistableBundle>();
3523 }
3524 mMuteEventExtras->putInt(String16(kExtraPlayerEventMuteKey),
3525 static_cast<int>(muteState));
3526
3527 result = audioManager->portEvent(mPortId,
3528 PLAYER_UPDATE_MUTED,
3529 mMuteEventExtras);
3530 }
3531
3532 if (result == OK) {
3533 mMuteState = muteState;
3534 } else {
3535 ALOGW("%s(%d): cannot process mute state for port ID %d, status error %d",
3536 __func__,
3537 id(),
3538 mPortId,
3539 result);
3540 }
3541}
3542
Andy Hung11e74242023-06-26 19:20:57 -07003543void MmapTrack::appendDumpHeader(String8& result) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003544{
Eric Laurent973db022018-11-20 14:54:31 -08003545 result.appendFormat("Client Session Port Id Format Chn mask SRate Flags %s\n",
Kevin Rocard5f2136e2018-05-11 22:03:00 -07003546 isOut() ? "Usg CT": "Source");
Eric Laurent6acd1d42017-01-04 14:23:29 -08003547}
3548
Andy Hung11e74242023-06-26 19:20:57 -07003549void MmapTrack::appendDump(String8& result, bool active __unused) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003550{
Eric Laurent973db022018-11-20 14:54:31 -08003551 result.appendFormat("%6u %7u %7u %08X %08X %6u 0x%03X ",
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003552 mPid,
3553 mSessionId,
Eric Laurent973db022018-11-20 14:54:31 -08003554 mPortId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08003555 mFormat,
3556 mChannelMask,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07003557 mSampleRate,
3558 mAttr.flags);
3559 if (isOut()) {
3560 result.appendFormat("%3x %2x", mAttr.usage, mAttr.content_type);
3561 } else {
3562 result.appendFormat("%6x", mAttr.source);
3563 }
3564 result.append("\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -08003565}
3566
Glenn Kasten63238ef2015-03-02 15:50:29 -08003567} // namespace android