blob: 7bdd37416ad2926fc0ea56578310868fdd901308 [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(
84 AudioFlinger::ThreadBase *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
279 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
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,
318 const AudioFlinger::ThreadBase& 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
325 uint64_t mixBufferNs = ((uint64_t)2 * thread.frameCount() * 1000000000) /
326 thread.sampleRate();
327 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 Hunga6426302023-06-23 19:27:19 -0700391 // TODO(b/288339104) binder thread priority change not needed.
Andy Hung225aef62022-12-06 16:33:20 -0800392 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -0800393}
394
Andy Hunga6426302023-06-23 19:27:19 -0700395TrackHandle::~TrackHandle() {
Eric Laurent81784c32012-11-19 14:55:58 -0800396 // just stop the track on deletion, associated resources
397 // will be freed from the main thread once all pending buffers have
398 // been played. Unless it's not in the active track list, in which
399 // case we free everything now...
400 mTrack->destroy();
401}
402
Andy Hunga6426302023-06-23 19:27:19 -0700403Status TrackHandle::getCblk(
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800404 std::optional<media::SharedFileRegion>* _aidl_return) {
405 *_aidl_return = legacy2aidl_NullableIMemory_SharedFileRegion(mTrack->getCblk()).value();
406 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800407}
408
Andy Hunga6426302023-06-23 19:27:19 -0700409Status TrackHandle::start(int32_t* _aidl_return) {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800410 *_aidl_return = mTrack->start();
411 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800412}
413
Andy Hunga6426302023-06-23 19:27:19 -0700414Status TrackHandle::stop() {
Eric Laurent81784c32012-11-19 14:55:58 -0800415 mTrack->stop();
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800416 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800417}
418
Andy Hunga6426302023-06-23 19:27:19 -0700419Status TrackHandle::flush() {
Eric Laurent81784c32012-11-19 14:55:58 -0800420 mTrack->flush();
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800421 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800422}
423
Andy Hunga6426302023-06-23 19:27:19 -0700424Status TrackHandle::pause() {
Eric Laurent81784c32012-11-19 14:55:58 -0800425 mTrack->pause();
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800426 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800427}
428
Andy Hunga6426302023-06-23 19:27:19 -0700429Status TrackHandle::attachAuxEffect(int32_t effectId,
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800430 int32_t* _aidl_return) {
431 *_aidl_return = mTrack->attachAuxEffect(effectId);
432 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800433}
434
Andy Hunga6426302023-06-23 19:27:19 -0700435Status TrackHandle::setParameters(const std::string& keyValuePairs,
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800436 int32_t* _aidl_return) {
437 *_aidl_return = mTrack->setParameters(String8(keyValuePairs.c_str()));
438 return Status::ok();
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700439}
440
Andy Hunga6426302023-06-23 19:27:19 -0700441Status TrackHandle::selectPresentation(int32_t presentationId, int32_t programId,
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800442 int32_t* _aidl_return) {
443 *_aidl_return = mTrack->selectPresentation(presentationId, programId);
444 return Status::ok();
Mikhail Naganovac917ac2018-11-28 14:03:52 -0800445}
446
Andy Hunga6426302023-06-23 19:27:19 -0700447Status TrackHandle::getTimestamp(media::AudioTimestampInternal* timestamp,
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800448 int32_t* _aidl_return) {
449 AudioTimestamp legacy;
450 *_aidl_return = mTrack->getTimestamp(legacy);
451 if (*_aidl_return != OK) {
452 return Status::ok();
453 }
Andy Hung973638a2020-12-08 20:47:45 -0800454 *timestamp = legacy2aidl_AudioTimestamp_AudioTimestampInternal(legacy).value();
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800455 return Status::ok();
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800456}
457
Andy Hunga6426302023-06-23 19:27:19 -0700458Status TrackHandle::signal() {
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800459 mTrack->signal();
460 return Status::ok();
Andy Hung9fc8b5c2017-01-24 13:36:48 -0800461}
462
Andy Hunga6426302023-06-23 19:27:19 -0700463Status TrackHandle::applyVolumeShaper(
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800464 const media::VolumeShaperConfiguration& configuration,
465 const media::VolumeShaperOperation& operation,
466 int32_t* _aidl_return) {
467 sp<VolumeShaper::Configuration> conf = new VolumeShaper::Configuration();
468 *_aidl_return = conf->readFromParcelable(configuration);
469 if (*_aidl_return != OK) {
470 return Status::ok();
471 }
472
473 sp<VolumeShaper::Operation> op = new VolumeShaper::Operation();
474 *_aidl_return = op->readFromParcelable(operation);
475 if (*_aidl_return != OK) {
476 return Status::ok();
477 }
478
479 *_aidl_return = mTrack->applyVolumeShaper(conf, op);
480 return Status::ok();
Glenn Kasten53cec222013-08-29 09:01:02 -0700481}
482
Andy Hunga6426302023-06-23 19:27:19 -0700483Status TrackHandle::getVolumeShaperState(
Ytai Ben-Tsvibdc293a2020-11-02 17:01:38 -0800484 int32_t id,
485 std::optional<media::VolumeShaperState>* _aidl_return) {
486 sp<VolumeShaper::State> legacy = mTrack->getVolumeShaperState(id);
487 if (legacy == nullptr) {
488 _aidl_return->reset();
489 return Status::ok();
490 }
491 media::VolumeShaperState aidl;
492 legacy->writeToParcelable(&aidl);
493 *_aidl_return = aidl;
494 return Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -0800495}
496
Andy Hunga6426302023-06-23 19:27:19 -0700497Status TrackHandle::getDualMonoMode(
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000498 media::audio::common::AudioDualMonoMode* _aidl_return)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800499{
500 audio_dual_mono_mode_t mode = AUDIO_DUAL_MONO_MODE_OFF;
501 const status_t status = mTrack->getDualMonoMode(&mode)
502 ?: AudioValidator::validateDualMonoMode(mode);
503 if (status == OK) {
504 *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
505 legacy2aidl_audio_dual_mono_mode_t_AudioDualMonoMode(mode));
506 }
507 return binderStatusFromStatusT(status);
508}
509
Andy Hunga6426302023-06-23 19:27:19 -0700510Status TrackHandle::setDualMonoMode(
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000511 media::audio::common::AudioDualMonoMode mode)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800512{
513 const auto localMonoMode = VALUE_OR_RETURN_BINDER_STATUS(
514 aidl2legacy_AudioDualMonoMode_audio_dual_mono_mode_t(mode));
515 return binderStatusFromStatusT(AudioValidator::validateDualMonoMode(localMonoMode)
516 ?: mTrack->setDualMonoMode(localMonoMode));
517}
518
Andy Hunga6426302023-06-23 19:27:19 -0700519Status TrackHandle::getAudioDescriptionMixLevel(float* _aidl_return)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800520{
521 float leveldB = -std::numeric_limits<float>::infinity();
522 const status_t status = mTrack->getAudioDescriptionMixLevel(&leveldB)
523 ?: AudioValidator::validateAudioDescriptionMixLevel(leveldB);
524 if (status == OK) *_aidl_return = leveldB;
525 return binderStatusFromStatusT(status);
526}
527
Andy Hunga6426302023-06-23 19:27:19 -0700528Status TrackHandle::setAudioDescriptionMixLevel(float leveldB)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800529{
530 return binderStatusFromStatusT(AudioValidator::validateAudioDescriptionMixLevel(leveldB)
531 ?: mTrack->setAudioDescriptionMixLevel(leveldB));
532}
533
Andy Hunga6426302023-06-23 19:27:19 -0700534Status TrackHandle::getPlaybackRateParameters(
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000535 media::audio::common::AudioPlaybackRate* _aidl_return)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800536{
537 audio_playback_rate_t localPlaybackRate{};
538 status_t status = mTrack->getPlaybackRateParameters(&localPlaybackRate)
539 ?: AudioValidator::validatePlaybackRate(localPlaybackRate);
540 if (status == NO_ERROR) {
541 *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
542 legacy2aidl_audio_playback_rate_t_AudioPlaybackRate(localPlaybackRate));
543 }
544 return binderStatusFromStatusT(status);
545}
546
Andy Hunga6426302023-06-23 19:27:19 -0700547Status TrackHandle::setPlaybackRateParameters(
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000548 const media::audio::common::AudioPlaybackRate& playbackRate)
Kuowei Lid4adbdb2020-08-13 14:44:25 +0800549{
550 const audio_playback_rate_t localPlaybackRate = VALUE_OR_RETURN_BINDER_STATUS(
551 aidl2legacy_AudioPlaybackRate_audio_playback_rate_t(playbackRate));
552 return binderStatusFromStatusT(AudioValidator::validatePlaybackRate(localPlaybackRate)
553 ?: mTrack->setPlaybackRateParameters(localPlaybackRate));
554}
555
Eric Laurent81784c32012-11-19 14:55:58 -0800556// ----------------------------------------------------------------------------
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800557// AppOp for audio playback
558// -------------------------------
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700559
560// static
Andy Hung11e74242023-06-26 19:20:57 -0700561sp<OpPlayAudioMonitor> OpPlayAudioMonitor::createIfNeeded(
Vlad Popa103be862023-07-10 20:27:41 -0700562 AudioFlinger::ThreadBase* thread,
Svet Ganov33761132021-05-13 22:51:08 +0000563 const AttributionSourceState& attributionSource, const audio_attributes_t& attr, int id,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700564 audio_stream_type_t streamType)
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800565{
Vlad Popa103be862023-07-10 20:27:41 -0700566 Vector<String16> packages;
567 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000568 getPackagesForUid(uid, packages);
Eric Laurent9066ad32019-05-20 14:40:10 -0700569 if (isServiceUid(uid)) {
Eric Laurent9066ad32019-05-20 14:40:10 -0700570 if (packages.isEmpty()) {
571 ALOGD("OpPlayAudio: not muting track:%d usage:%d for service UID %d",
572 id,
573 attr.usage,
574 uid);
575 return nullptr;
576 }
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800577 }
578 // stream type has been filtered by audio policy to indicate whether it can be muted
579 if (streamType == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Eric Laurent2dab0302019-05-08 18:15:55 -0700580 ALOGD("OpPlayAudio: not muting track:%d usage:%d ENFORCED_AUDIBLE", id, attr.usage);
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700581 return nullptr;
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800582 }
Eric Laurent2dab0302019-05-08 18:15:55 -0700583 if ((attr.flags & AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY)
584 == AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY) {
585 ALOGD("OpPlayAudio: not muting track:%d flags %#x have FLAG_BYPASS_INTERRUPTION_POLICY",
586 id, attr.flags);
587 return nullptr;
588 }
Vlad Popa103be862023-07-10 20:27:41 -0700589 return sp<OpPlayAudioMonitor>::make(thread, attributionSource, attr.usage, id, uid);
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700590}
591
Andy Hung11e74242023-06-26 19:20:57 -0700592OpPlayAudioMonitor::OpPlayAudioMonitor(
Vlad Popa103be862023-07-10 20:27:41 -0700593 AudioFlinger::ThreadBase* thread,
594 const AttributionSourceState& attributionSource,
595 audio_usage_t usage, int id, uid_t uid)
596 : mThread(wp<AudioFlinger::ThreadBase>::fromExisting(thread)),
597 mHasOpPlayAudio(true),
598 mAttributionSource(attributionSource),
599 mUsage((int32_t)usage),
600 mId(id),
601 mUid(uid),
602 mPackageName(VALUE_OR_FATAL(aidl2legacy_string_view_String16(
603 attributionSource.packageName.value_or("")))) {}
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800604
Andy Hung11e74242023-06-26 19:20:57 -0700605OpPlayAudioMonitor::~OpPlayAudioMonitor()
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800606{
607 if (mOpCallback != 0) {
608 mAppOpsManager.stopWatchingMode(mOpCallback);
609 }
610 mOpCallback.clear();
611}
612
Andy Hung11e74242023-06-26 19:20:57 -0700613void OpPlayAudioMonitor::onFirstRef()
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700614{
Mikhail Naganovf7e3a3a2019-04-22 16:43:26 -0700615 checkPlayAudioForUsage();
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
Andy Hung11e74242023-06-26 19:20:57 -0700630void OpPlayAudioMonitor::checkPlayAudioForUsage()
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 " : "");
640 auto thread = mThread.promote();
641 if (thread != nullptr && thread->type() == AudioFlinger::ThreadBase::OFFLOAD) {
642 // Wake up Thread if offloaded, otherwise it may be several seconds for update.
643 Mutex::Autolock _l(thread->mLock);
644 thread->broadcast_l();
645 }
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800646 }
647}
648
Andy Hung11e74242023-06-26 19:20:57 -0700649OpPlayAudioMonitor::PlayAudioOpCallback::PlayAudioOpCallback(
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800650 const wp<OpPlayAudioMonitor>& monitor) : mMonitor(monitor)
651{ }
652
Andy Hung11e74242023-06-26 19:20:57 -0700653void OpPlayAudioMonitor::PlayAudioOpCallback::opChanged(int32_t op,
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800654 const String16& packageName) {
655 // we only have uid, so we need to check all package names anyway
656 UNUSED(packageName);
657 if (op != AppOpsManager::OP_PLAY_AUDIO) {
658 return;
659 }
660 sp<OpPlayAudioMonitor> monitor = mMonitor.promote();
661 if (monitor != NULL) {
662 monitor->checkPlayAudioForUsage();
663 }
664}
665
Eric Laurent9066ad32019-05-20 14:40:10 -0700666// static
Andy Hung11e74242023-06-26 19:20:57 -0700667void OpPlayAudioMonitor::getPackagesForUid(
Eric Laurent9066ad32019-05-20 14:40:10 -0700668 uid_t uid, Vector<String16>& packages)
669{
670 PermissionController permissionController;
671 permissionController.getPackagesForUid(uid, packages);
672}
673
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -0800674// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -0700675#undef LOG_TAG
676#define LOG_TAG "AF::Track"
Eric Laurent81784c32012-11-19 14:55:58 -0800677
Andy Hung11e74242023-06-26 19:20:57 -0700678/* static */
679sp<IAfTrack> IAfTrack::create( // TODO(b/288339104) void*
680 void * /* AudioFlinger::PlaybackThread */ thread,
681 const sp<Client>& client,
682 audio_stream_type_t streamType,
683 const audio_attributes_t& attr,
684 uint32_t sampleRate,
685 audio_format_t format,
686 audio_channel_mask_t channelMask,
687 size_t frameCount,
688 void *buffer,
689 size_t bufferSize,
690 const sp<IMemory>& sharedBuffer,
691 audio_session_t sessionId,
692 pid_t creatorPid,
693 const AttributionSourceState& attributionSource,
694 audio_output_flags_t flags,
695 track_type type,
696 audio_port_handle_t portId,
697 /** default behaviour is to start when there are as many frames
698 * ready as possible (aka. Buffer is full). */
699 size_t frameCountToBeReady,
700 float speed,
701 bool isSpatialized,
702 bool isBitPerfect) {
703 return sp<Track>::make(reinterpret_cast<AudioFlinger::PlaybackThread*>(thread),
704 client,
705 streamType,
706 attr,
707 sampleRate,
708 format,
709 channelMask,
710 frameCount,
711 buffer,
712 bufferSize,
713 sharedBuffer,
714 sessionId,
715 creatorPid,
716 attributionSource,
717 flags,
718 type,
719 portId,
720 frameCountToBeReady,
721 speed,
722 isSpatialized,
723 isBitPerfect);
724}
725
Eric Laurent81784c32012-11-19 14:55:58 -0800726// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Andy Hung11e74242023-06-26 19:20:57 -0700727Track::Track(
728 AudioFlinger::PlaybackThread *thread,
Eric Laurent81784c32012-11-19 14:55:58 -0800729 const sp<Client>& client,
730 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700731 const audio_attributes_t& attr,
Eric Laurent81784c32012-11-19 14:55:58 -0800732 uint32_t sampleRate,
733 audio_format_t format,
734 audio_channel_mask_t channelMask,
735 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700736 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -0700737 size_t bufferSize,
Eric Laurent81784c32012-11-19 14:55:58 -0800738 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800739 audio_session_t sessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700740 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000741 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -0700742 audio_output_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800743 track_type type,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100744 audio_port_handle_t portId,
jiabinf042b9b2021-05-07 23:46:28 +0000745 size_t frameCountToBeReady,
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200746 float speed,
jiabinc658e452022-10-21 20:52:21 +0000747 bool isSpatialized,
748 bool isBitPerfect)
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700749 : TrackBase(thread, client, attr, sampleRate, format, channelMask, frameCount,
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700750 // TODO: Using unsecurePointer() has some associated security pitfalls
751 // (see declaration for details).
752 // Either document why it is safe in this case or address the
753 // issue (e.g. by copying).
754 (sharedBuffer != 0) ? sharedBuffer->unsecurePointer() : buffer,
Andy Hung8fe68032017-06-05 16:17:51 -0700755 (sharedBuffer != 0) ? sharedBuffer->size() : bufferSize,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700756 sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000757 VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)), true /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -0700758 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
Andy Hungb68f5eb2019-12-03 16:49:17 -0800759 type,
760 portId,
761 std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK) + std::to_string(portId)),
Andy Hung11e74242023-06-26 19:20:57 -0700762 mFillingStatus(FS_INVALID),
Eric Laurent81784c32012-11-19 14:55:58 -0800763 // mRetryCount initialized later when needed
764 mSharedBuffer(sharedBuffer),
765 mStreamType(streamType),
rago94a1ee82017-07-21 15:11:02 -0700766 mMainBuffer(thread->sinkBuffer()),
Eric Laurent81784c32012-11-19 14:55:58 -0800767 mAuxBuffer(NULL),
768 mAuxEffectId(0), mHasVolumeController(false),
Andy Hunge10393e2015-06-12 13:59:33 -0700769 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
Ivan Lozano8cf3a072017-08-09 09:01:33 -0700770 mVolumeHandler(new media::VolumeHandler(sampleRate)),
Vlad Popa103be862023-07-10 20:27:41 -0700771 mOpPlayAudioMonitor(OpPlayAudioMonitor::createIfNeeded(thread, attributionSource, attr, id(),
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700772 streamType)),
Andy Hunge10393e2015-06-12 13:59:33 -0700773 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800774 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800775 mCachedVolume(1.0),
Kevin Rocard12381092018-04-11 09:19:59 -0700776 /* The track might not play immediately after being active, similarly as if its volume was 0.
777 * When the track starts playing, its volume will be computed. */
778 mFinalVolume(0.f),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800779 mResumeToStopping(false),
Eric Laurent05067782016-06-01 18:27:28 -0700780 mFlushHwPending(false),
jiabinf042b9b2021-05-07 23:46:28 +0000781 mFlags(flags),
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200782 mSpeed(speed),
jiabinc658e452022-10-21 20:52:21 +0000783 mIsSpatialized(isSpatialized),
784 mIsBitPerfect(isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -0800785{
Eric Laurent83b88082014-06-20 18:31:16 -0700786 // client == 0 implies sharedBuffer == 0
787 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
788
Andy Hung9d84af52018-09-12 18:03:44 -0700789 ALOGV_IF(sharedBuffer != 0, "%s(%d): sharedBuffer: %p, size: %zu",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700790 __func__, mId, sharedBuffer->unsecurePointer(), sharedBuffer->size());
Eric Laurent83b88082014-06-20 18:31:16 -0700791
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700792 if (mCblk == NULL) {
793 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800794 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700795
Svet Ganov33761132021-05-13 22:51:08 +0000796 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Andy Hung689e82c2019-08-21 17:53:17 -0700797 if (!thread->isTrackAllowed_l(channelMask, format, sessionId, uid)) {
798 ALOGE("%s(%d): no more tracks available", __func__, mId);
799 releaseCblk(); // this makes the track invalid.
800 return;
801 }
802
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700803 if (sharedBuffer == 0) {
804 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700805 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700806 } else {
807 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
Kevin Rocard36862032019-10-10 10:52:19 +0100808 mFrameSize, sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700809 }
810 mServerProxy = mAudioTrackServerProxy;
Andy Hung3c7f47a2021-03-16 17:30:09 -0700811 mServerProxy->setStartThresholdInFrames(frameCountToBeReady); // update the Cblk value
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700812
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700813 // only allocate a fast track index if we were able to allocate a normal track name
Eric Laurent05067782016-06-01 18:27:28 -0700814 if (flags & AUDIO_OUTPUT_FLAG_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700815 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
816 // race with setSyncEvent(). However, if we call it, we cannot properly start
817 // static fast tracks (SoundPool) immediately after stopping.
818 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700819 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
820 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Glenn Kastendc2c50b2016-04-21 08:13:14 -0700821 ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700822 // FIXME This is too eager. We allocate a fast track index before the
823 // fast track becomes active. Since fast tracks are a scarce resource,
824 // this means we are potentially denying other more important fast tracks from
825 // being created. It would be better to allocate the index dynamically.
826 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700827 thread->mFastTrackAvailMask &= ~(1 << i);
828 }
Andy Hung8946a282018-04-19 20:04:56 -0700829
Dean Wheatley7b036912020-06-18 16:22:11 +1000830 mServerLatencySupported = checkServerLatencySupported(format, flags);
Andy Hung8946a282018-04-19 20:04:56 -0700831#ifdef TEE_SINK
832 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle)
Kevin Rocard51f0e982019-02-01 19:19:11 -0800833 + "_" + std::to_string(mId) + "_T");
Andy Hung8946a282018-04-19 20:04:56 -0700834#endif
jiabin57303cc2018-12-18 15:45:57 -0800835
jiabineb3bda02020-06-30 14:07:03 -0700836 if (thread->supportsHapticPlayback()) {
837 // If the track is attached to haptic playback thread, it is potentially to have
838 // HapticGenerator effect, which will generate haptic data, on the track. In that case,
839 // external vibration is always created for all tracks attached to haptic playback thread.
jiabin57303cc2018-12-18 15:45:57 -0800840 mAudioVibrationController = new AudioVibrationController(this);
Svet Ganov33761132021-05-13 22:51:08 +0000841 std::string packageName = attributionSource.packageName.has_value() ?
842 attributionSource.packageName.value() : "";
jiabin57303cc2018-12-18 15:45:57 -0800843 mExternalVibration = new os::ExternalVibration(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700844 mUid, packageName, mAttr, mAudioVibrationController);
jiabin57303cc2018-12-18 15:45:57 -0800845 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800846
847 // Once this item is logged by the server, the client can add properties.
Andy Hunga629bd12020-06-05 16:03:53 -0700848 const char * const traits = sharedBuffer == 0 ? "" : "static";
Andy Hung5837c7f2021-02-25 10:48:24 -0800849 mTrackMetrics.logConstructor(creatorPid, uid, id(), traits, streamType);
Eric Laurent81784c32012-11-19 14:55:58 -0800850}
851
Andy Hung11e74242023-06-26 19:20:57 -0700852Track::~Track()
Eric Laurent81784c32012-11-19 14:55:58 -0800853{
Andy Hung9d84af52018-09-12 18:03:44 -0700854 ALOGV("%s(%d)", __func__, mId);
Glenn Kasten0c72b242013-09-11 09:14:16 -0700855
856 // The destructor would clear mSharedBuffer,
857 // but it will not push the decremented reference count,
858 // leaving the client's IMemory dangling indefinitely.
859 // This prevents that leak.
860 if (mSharedBuffer != 0) {
861 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700862 }
Eric Laurent81784c32012-11-19 14:55:58 -0800863}
864
Andy Hung11e74242023-06-26 19:20:57 -0700865status_t Track::initCheck() const
Glenn Kasten03003332013-08-06 15:40:54 -0700866{
867 status_t status = TrackBase::initCheck();
Andy Hungc0691382018-09-12 18:01:57 -0700868 if (status == NO_ERROR && mCblk == nullptr) {
Glenn Kasten03003332013-08-06 15:40:54 -0700869 status = NO_MEMORY;
870 }
871 return status;
872}
873
Andy Hung11e74242023-06-26 19:20:57 -0700874void Track::destroy()
Eric Laurent81784c32012-11-19 14:55:58 -0800875{
876 // NOTE: destroyTrack_l() can remove a strong reference to this Track
877 // by removing it from mTracks vector, so there is a risk that this Tracks's
878 // destructor is called. As the destructor needs to lock mLock,
879 // we must acquire a strong reference on this Track before locking mLock
880 // here so that the destructor is called only when exiting this function.
881 // On the other hand, as long as Track::destroy() is only called by
882 // TrackHandle destructor, the TrackHandle still holds a strong ref on
883 // this Track with its member mTrack.
884 sp<Track> keep(this);
885 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700886 bool wasActive = false;
Andy Hung11e74242023-06-26 19:20:57 -0700887 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -0800888 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800889 Mutex::Autolock _l(thread->mLock);
Andy Hung11e74242023-06-26 19:20:57 -0700890 auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Eric Laurentaaa44472014-09-12 17:41:50 -0700891 wasActive = playbackThread->destroyTrack_l(this);
jiabin7434e812023-06-27 18:22:35 +0000892 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->destroy(); });
Eric Laurentaaa44472014-09-12 17:41:50 -0700893 }
894 if (isExternalTrack() && !wasActive) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700895 AudioSystem::releaseOutput(mPortId);
Eric Laurent81784c32012-11-19 14:55:58 -0800896 }
897 }
898}
899
Andy Hung11e74242023-06-26 19:20:57 -0700900void Track::appendDumpHeader(String8& result) const
Eric Laurent81784c32012-11-19 14:55:58 -0800901{
Eric Laurent973db022018-11-20 14:54:31 -0800902 result.appendFormat("Type Id Active Client Session Port Id S Flags "
Kevin Rocard5f2136e2018-05-11 22:03:00 -0700903 " Format Chn mask SRate "
904 "ST Usg CT "
905 " G db L dB R dB VS dB "
jiabin5eaf0962022-12-20 20:11:38 +0000906 " Server FrmCnt FrmRdy F Underruns Flushed BitPerfect"
Kevin Rocard5f2136e2018-05-11 22:03:00 -0700907 "%s\n",
908 isServerLatencySupported() ? " Latency" : "");
Eric Laurent81784c32012-11-19 14:55:58 -0800909}
910
Andy Hung11e74242023-06-26 19:20:57 -0700911void Track::appendDump(String8& result, bool active) const
Eric Laurent81784c32012-11-19 14:55:58 -0800912{
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700913 char trackType;
914 switch (mType) {
915 case TYPE_DEFAULT:
916 case TYPE_OUTPUT:
Andy Hungf6ab58d2018-05-25 12:50:39 -0700917 if (isStatic()) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700918 trackType = 'S'; // static
919 } else {
920 trackType = ' '; // normal
Eric Laurentbfb1b832013-01-07 09:53:42 -0800921 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700922 break;
923 case TYPE_PATCH:
924 trackType = 'P';
925 break;
926 default:
927 trackType = '?';
Eric Laurent81784c32012-11-19 14:55:58 -0800928 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700929
930 if (isFastTrack()) {
Andy Hungc0691382018-09-12 18:01:57 -0700931 result.appendFormat("F%d %c %6d", mFastIndex, trackType, mId);
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700932 } else {
Andy Hungc0691382018-09-12 18:01:57 -0700933 result.appendFormat(" %c %6d", trackType, mId);
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700934 }
935
Eric Laurent81784c32012-11-19 14:55:58 -0800936 char nowInUnderrun;
937 switch (mObservedUnderruns.mBitFields.mMostRecent) {
938 case UNDERRUN_FULL:
939 nowInUnderrun = ' ';
940 break;
941 case UNDERRUN_PARTIAL:
942 nowInUnderrun = '<';
943 break;
944 case UNDERRUN_EMPTY:
945 nowInUnderrun = '*';
946 break;
947 default:
948 nowInUnderrun = '?';
949 break;
950 }
Andy Hungda540db2017-04-20 14:06:17 -0700951
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700952 char fillingStatus;
Andy Hung11e74242023-06-26 19:20:57 -0700953 switch (mFillingStatus) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700954 case FS_INVALID:
955 fillingStatus = 'I';
956 break;
957 case FS_FILLING:
958 fillingStatus = 'f';
959 break;
960 case FS_FILLED:
961 fillingStatus = 'F';
962 break;
963 case FS_ACTIVE:
964 fillingStatus = 'A';
965 break;
966 default:
967 fillingStatus = '?';
968 break;
969 }
970
971 // clip framesReadySafe to max representation in dump
972 const size_t framesReadySafe =
973 std::min(mAudioTrackServerProxy->framesReadySafe(), (size_t)99999999);
974
975 // obtain volumes
976 const gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
977 const std::pair<float /* volume */, bool /* active */> vsVolume =
978 mVolumeHandler->getLastVolume();
979
980 // Our effective frame count is obtained by ServerProxy::getBufferSizeInFrames()
981 // as it may be reduced by the application.
982 const size_t bufferSizeInFrames = (size_t)mAudioTrackServerProxy->getBufferSizeInFrames();
983 // Check whether the buffer size has been modified by the app.
984 const char modifiedBufferChar = bufferSizeInFrames < mFrameCount
985 ? 'r' /* buffer reduced */: bufferSizeInFrames > mFrameCount
986 ? 'e' /* error */ : ' ' /* identical */;
987
Eric Laurent973db022018-11-20 14:54:31 -0800988 result.appendFormat("%7s %6u %7u %7u %2s 0x%03X "
Kevin Rocard5f2136e2018-05-11 22:03:00 -0700989 "%08X %08X %6u "
990 "%2u %3x %2x "
991 "%5.2g %5.2g %5.2g %5.2g%c "
jiabin5eaf0962022-12-20 20:11:38 +0000992 "%08X %6zu%c %6zu %c %9u%c %7u %10s",
Marco Nelissenb2208842014-02-07 14:00:50 -0800993 active ? "yes" : "no",
Andy Hung4ef19fa2018-05-15 19:35:29 -0700994 (mClient == 0) ? getpid() : mClient->pid(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700995 mSessionId,
Eric Laurent973db022018-11-20 14:54:31 -0800996 mPortId,
Andy Hunge2e830f2019-12-03 12:54:46 -0800997 getTrackStateAsCodedString(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700998 mCblk->mFlags,
999
Eric Laurent81784c32012-11-19 14:55:58 -08001000 mFormat,
1001 mChannelMask,
Andy Hungcef2daa2018-06-01 15:31:49 -07001002 sampleRate(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001003
1004 mStreamType,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07001005 mAttr.usage,
1006 mAttr.content_type,
1007
1008 20.0 * log10(mFinalVolume),
Glenn Kastenc56f3422014-03-21 17:53:17 -07001009 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
1010 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Andy Hungda540db2017-04-20 14:06:17 -07001011 20.0 * log10(vsVolume.first), // VolumeShaper(s) total volume
1012 vsVolume.second ? 'A' : ' ', // if any VolumeShapers active
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001013
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001014 mCblk->mServer,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001015 bufferSizeInFrames,
1016 modifiedBufferChar,
1017 framesReadySafe,
1018 fillingStatus,
Glenn Kasten82aaf942013-07-17 16:05:07 -07001019 mAudioTrackServerProxy->getUnderrunFrames(),
Andy Hung2148bf02016-11-28 19:01:02 -08001020 nowInUnderrun,
jiabin5eaf0962022-12-20 20:11:38 +00001021 (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000,
1022 isBitPerfect() ? "true" : "false"
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001023 );
Andy Hungcef2daa2018-06-01 15:31:49 -07001024
1025 if (isServerLatencySupported()) {
1026 double latencyMs;
1027 bool fromTrack;
1028 if (getTrackLatencyMs(&latencyMs, &fromTrack) == OK) {
1029 // Show latency in msec, followed by 't' if from track timestamp (the most accurate)
1030 // or 'k' if estimated from kernel because track frames haven't been presented yet.
1031 result.appendFormat(" %7.2lf %c", latencyMs, fromTrack ? 't' : 'k');
Andy Hungf6ab58d2018-05-25 12:50:39 -07001032 } else {
Andy Hungcef2daa2018-06-01 15:31:49 -07001033 result.appendFormat("%10s", mCblk->mServer != 0 ? "unavail" : "new");
Andy Hungf6ab58d2018-05-25 12:50:39 -07001034 }
1035 }
1036 result.append("\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001037}
1038
Andy Hung11e74242023-06-26 19:20:57 -07001039uint32_t Track::sampleRate() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001040 return mAudioTrackServerProxy->getSampleRate();
1041}
1042
Eric Laurent81784c32012-11-19 14:55:58 -08001043// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07001044status_t Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001045{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001046 ServerProxy::Buffer buf;
1047 size_t desiredFrames = buffer->frameCount;
1048 buf.mFrameCount = desiredFrames;
1049 status_t status = mServerProxy->obtainBuffer(&buf);
1050 buffer->frameCount = buf.mFrameCount;
1051 buffer->raw = buf.mRaw;
Andy Hungfc629172020-06-22 10:06:23 -07001052 if (buf.mFrameCount == 0 && !isStopping() && !isStopped() && !isPaused() && !isOffloaded()) {
Andy Hung9d84af52018-09-12 18:03:44 -07001053 ALOGV("%s(%d): underrun, framesReady(%zu) < framesDesired(%zd), state: %d",
Andy Hung959b5b82021-09-24 10:46:20 -07001054 __func__, mId, buf.mFrameCount, desiredFrames, (int)mState);
Glenn Kasten82aaf942013-07-17 16:05:07 -07001055 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08001056 } else {
1057 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08001058 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001059 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001060}
1061
Andy Hung11e74242023-06-26 19:20:57 -07001062void Track::releaseBuffer(AudioBufferProvider::Buffer* buffer)
Kevin Rocard153f92d2018-12-18 18:33:28 -08001063{
1064 interceptBuffer(*buffer);
1065 TrackBase::releaseBuffer(buffer);
1066}
1067
1068// TODO: compensate for time shift between HW modules.
Andy Hung11e74242023-06-26 19:20:57 -07001069void Track::interceptBuffer(
Kevin Rocarda134b002019-02-07 18:05:31 -08001070 const AudioBufferProvider::Buffer& sourceBuffer) {
Kevin Rocard6057fa22019-02-08 14:08:07 -08001071 auto start = std::chrono::steady_clock::now();
Kevin Rocarda134b002019-02-07 18:05:31 -08001072 const size_t frameCount = sourceBuffer.frameCount;
Kevin Rocardd83b08a2019-02-27 15:05:54 -08001073 if (frameCount == 0) {
1074 return; // No audio to intercept.
1075 // Additionally PatchProxyBufferProvider::obtainBuffer (called by PathTrack::getNextBuffer)
1076 // does not allow 0 frame size request contrary to getNextBuffer
1077 }
1078 for (auto& teePatch : mTeePatches) {
Andy Hung11e74242023-06-26 19:20:57 -07001079 IAfPatchRecord* patchRecord = teePatch.patchRecord.get();
Mikhail Naganov8296c252019-09-25 14:59:54 -07001080 const size_t framesWritten = patchRecord->writeFrames(
1081 sourceBuffer.i8, frameCount, mFrameSize);
1082 const size_t framesLeft = frameCount - framesWritten;
Kevin Rocarda134b002019-02-07 18:05:31 -08001083 ALOGW_IF(framesLeft != 0, "%s(%d) PatchRecord %d can not provide big enough "
Andy Hung11e74242023-06-26 19:20:57 -07001084 "buffer %zu/%zu, dropping %zu frames", __func__, mId, patchRecord->id(),
Kevin Rocarda134b002019-02-07 18:05:31 -08001085 framesWritten, frameCount, framesLeft);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001086 }
Kevin Rocard6057fa22019-02-08 14:08:07 -08001087 auto spent = ceil<std::chrono::microseconds>(std::chrono::steady_clock::now() - start);
1088 using namespace std::chrono_literals;
1089 // Average is ~20us per track, this should virtually never be logged (Logging takes >200us)
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01001090 ALOGD_IF(spent > 500us, "%s: took %lldus to intercept %zu tracks", __func__,
Kevin Rocard6057fa22019-02-08 14:08:07 -08001091 spent.count(), mTeePatches.size());
Kevin Rocard153f92d2018-12-18 18:33:28 -08001092}
1093
Glenn Kasten6466c9e2013-08-23 10:54:07 -07001094// ExtendedAudioBufferProvider interface
1095
Andy Hung27876c02014-09-09 18:07:55 -07001096// framesReady() may return an approximation of the number of frames if called
1097// from a different thread than the one calling Proxy->obtainBuffer() and
1098// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
1099// AudioTrackServerProxy so be especially careful calling with FastTracks.
Andy Hung11e74242023-06-26 19:20:57 -07001100size_t Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -07001101 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
1102 // Static tracks return zero frames immediately upon stopping (for FastTracks).
1103 // The remainder of the buffer is not drained.
1104 return 0;
1105 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001106 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -08001107}
1108
Andy Hung11e74242023-06-26 19:20:57 -07001109int64_t Track::framesReleased() const
Glenn Kasten6466c9e2013-08-23 10:54:07 -07001110{
1111 return mAudioTrackServerProxy->framesReleased();
1112}
1113
Andy Hung11e74242023-06-26 19:20:57 -07001114void Track::onTimestamp(const ExtendedTimestamp &timestamp)
Andy Hung6ae58432016-02-16 18:32:24 -08001115{
1116 // This call comes from a FastTrack and should be kept lockless.
1117 // The server side frames are already translated to client frames.
Andy Hung818e7a32016-02-16 18:08:07 -08001118 mAudioTrackServerProxy->setTimestamp(timestamp);
Andy Hung6ae58432016-02-16 18:32:24 -08001119
Andy Hung818e7a32016-02-16 18:08:07 -08001120 // We do not set drained here, as FastTrack timestamp may not go to very last frame.
Andy Hungcef2daa2018-06-01 15:31:49 -07001121
1122 // Compute latency.
1123 // TODO: Consider whether the server latency may be passed in by FastMixer
1124 // as a constant for all active FastTracks.
1125 const double latencyMs = timestamp.getOutputServerLatencyMs(sampleRate());
1126 mServerLatencyFromTrack.store(true);
1127 mServerLatencyMs.store(latencyMs);
Andy Hung6ae58432016-02-16 18:32:24 -08001128}
1129
Eric Laurent81784c32012-11-19 14:55:58 -08001130// Don't call for fast tracks; the framesReady() could result in priority inversion
Andy Hung11e74242023-06-26 19:20:57 -07001131bool Track::isReady() const {
1132 if (mFillingStatus != FS_FILLING || isStopped() || isPausing()) {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001133 return true;
1134 }
1135
Eric Laurent16498512014-03-17 17:22:08 -07001136 if (isStopping()) {
1137 if (framesReady() > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07001138 mFillingStatus = FS_FILLED;
Eric Laurent16498512014-03-17 17:22:08 -07001139 }
Eric Laurent81784c32012-11-19 14:55:58 -08001140 return true;
1141 }
1142
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01001143 size_t bufferSizeInFrames = mServerProxy->getBufferSizeInFrames();
Andy Hung3c7f47a2021-03-16 17:30:09 -07001144 // Note: mServerProxy->getStartThresholdInFrames() is clamped.
1145 const size_t startThresholdInFrames = mServerProxy->getStartThresholdInFrames();
1146 const size_t framesToBeReady = std::clamp( // clamp again to validate client values.
1147 std::min(startThresholdInFrames, bufferSizeInFrames), size_t(1), mFrameCount);
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01001148
1149 if (framesReady() >= framesToBeReady || (mCblk->mFlags & CBLK_FORCEREADY)) {
1150 ALOGV("%s(%d): consider track ready with %zu/%zu, target was %zu)",
1151 __func__, mId, framesReady(), bufferSizeInFrames, framesToBeReady);
Andy Hung11e74242023-06-26 19:20:57 -07001152 mFillingStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001153 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001154 return true;
1155 }
1156 return false;
1157}
1158
Andy Hung11e74242023-06-26 19:20:57 -07001159status_t Track::start(AudioSystem::sync_event_t event __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08001160 audio_session_t triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001161{
1162 status_t status = NO_ERROR;
Andy Hungc0691382018-09-12 18:01:57 -07001163 ALOGV("%s(%d): calling pid %d session %d",
1164 __func__, mId, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001165
Andy Hung11e74242023-06-26 19:20:57 -07001166 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001167 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -07001168 if (isOffloaded()) {
1169 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
1170 Mutex::Autolock _lth(thread->mLock);
Andy Hung116bc262023-06-20 18:56:17 -07001171 sp<IAfEffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001172 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
1173 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -07001174 invalidate();
1175 return PERMISSION_DENIED;
1176 }
1177 }
1178 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08001179 track_state state = mState;
1180 // here the track could be either new, or restarted
1181 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -08001182
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001183 // initial state-stopping. next state-pausing.
1184 // What if resume is called ?
1185
Zhou Song1ed46a22020-08-17 15:36:56 +08001186 if (state == FLUSHED) {
1187 // avoid underrun glitches when starting after flush
1188 reset();
1189 }
1190
kuowei.li576f1362021-05-11 18:02:32 +08001191 // clear mPauseHwPending because of pause (and possibly flush) during underrun.
1192 mPauseHwPending = false;
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001193 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001194 if (mResumeToStopping) {
1195 // happened we need to resume to STOPPING_1
1196 mState = TrackBase::STOPPING_1;
Andy Hungc0691382018-09-12 18:01:57 -07001197 ALOGV("%s(%d): PAUSED => STOPPING_1 on thread %d",
1198 __func__, mId, (int)mThreadIoHandle);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001199 } else {
1200 mState = TrackBase::RESUMING;
Andy Hungc0691382018-09-12 18:01:57 -07001201 ALOGV("%s(%d): PAUSED => RESUMING on thread %d",
1202 __func__, mId, (int)mThreadIoHandle);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001203 }
Eric Laurent81784c32012-11-19 14:55:58 -08001204 } else {
1205 mState = TrackBase::ACTIVE;
Andy Hungc0691382018-09-12 18:01:57 -07001206 ALOGV("%s(%d): ? => ACTIVE on thread %d",
1207 __func__, mId, (int)mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -08001208 }
1209
Andy Hung11e74242023-06-26 19:20:57 -07001210 auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
yucliu6cfb5932022-07-20 17:40:39 -07001211
1212 // states to reset position info for pcm tracks
1213 if (audio_is_linear_pcm(mFormat)
Andy Hunge10393e2015-06-12 13:59:33 -07001214 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
1215 mFrameMap.reset();
yucliu6cfb5932022-07-20 17:40:39 -07001216
1217 if (!isFastTrack() && (isDirect() || isOffloaded())) {
1218 // Start point of track -> sink frame map. If the HAL returns a
1219 // frame position smaller than the first written frame in
1220 // updateTrackFrameInfo, the timestamp can be interpolated
1221 // instead of using a larger value.
1222 mFrameMap.push(mAudioTrackServerProxy->framesReleased(),
1223 playbackThread->framesWritten());
1224 }
Andy Hunge10393e2015-06-12 13:59:33 -07001225 }
Haynes Mathew George240934b2015-03-11 18:25:50 -07001226 if (isFastTrack()) {
1227 // refresh fast track underruns on start because that field is never cleared
1228 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
1229 // after stop.
1230 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
1231 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001232 status = playbackThread->addTrack_l(this);
jiabina84c3d32022-12-02 18:59:55 +00001233 if (status == INVALID_OPERATION || status == PERMISSION_DENIED || status == DEAD_OBJECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08001234 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001235 // restore previous state if start was rejected by policy manager
jiabina84c3d32022-12-02 18:59:55 +00001236 if (status == PERMISSION_DENIED || status == DEAD_OBJECT) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001237 mState = state;
1238 }
1239 }
Andy Hung1d3556d2018-03-29 16:30:14 -07001240
Andy Hungb68f5eb2019-12-03 16:49:17 -08001241 // Audio timing metrics are computed a few mix cycles after starting.
1242 {
1243 mLogStartCountdown = LOG_START_COUNTDOWN;
1244 mLogStartTimeNs = systemTime();
1245 mLogStartFrames = mAudioTrackServerProxy->getTimestamp()
Andy Hung62921122020-05-18 10:47:31 -07001246 .mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1247 mLogLatencyMs = 0.;
Andy Hungb68f5eb2019-12-03 16:49:17 -08001248 }
Andy Hunga81a4b42022-05-19 19:24:51 -07001249 mLogForceVolumeUpdate = true; // at least one volume logged for metrics when starting.
Andy Hungb68f5eb2019-12-03 16:49:17 -08001250
Andy Hung1d3556d2018-03-29 16:30:14 -07001251 if (status == NO_ERROR || status == ALREADY_EXISTS) {
1252 // for streaming tracks, remove the buffer read stop limit.
1253 mAudioTrackServerProxy->start();
1254 }
1255
Eric Laurentbfb1b832013-01-07 09:53:42 -08001256 // track was already in the active list, not a problem
1257 if (status == ALREADY_EXISTS) {
1258 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -07001259 } else {
1260 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
1261 // It is usually unsafe to access the server proxy from a binder thread.
1262 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
1263 // isn't looking at this track yet: we still hold the normal mixer thread lock,
1264 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -07001265 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -07001266 ServerProxy::Buffer buffer;
1267 buffer.mFrameCount = 1;
1268 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001269 }
jiabin7434e812023-06-27 18:22:35 +00001270 if (status == NO_ERROR) {
1271 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->start(); });
1272 }
Eric Laurent81784c32012-11-19 14:55:58 -08001273 } else {
1274 status = BAD_VALUE;
1275 }
Kevin Rocardc43ea142019-01-31 18:17:37 -08001276 if (status == NO_ERROR) {
Jean-Michel Trivi16395ca2022-12-11 22:10:11 +00001277 // send format to AudioManager for playback activity monitoring
1278 sp<IAudioManager> audioManager = thread->mAudioFlinger->getOrCreateAudioManager();
1279 if (audioManager && mPortId != AUDIO_PORT_HANDLE_NONE) {
1280 std::unique_ptr<os::PersistableBundle> bundle =
1281 std::make_unique<os::PersistableBundle>();
1282 bundle->putBoolean(String16(kExtraPlayerEventSpatializedKey),
1283 isSpatialized());
1284 bundle->putInt(String16(kExtraPlayerEventSampleRateKey), mSampleRate);
1285 bundle->putInt(String16(kExtraPlayerEventChannelMaskKey), mChannelMask);
1286 status_t result = audioManager->portEvent(mPortId,
1287 PLAYER_UPDATE_FORMAT, bundle);
1288 if (result != OK) {
1289 ALOGE("%s: unable to send playback format for port ID %d, status error %d",
1290 __func__, mPortId, result);
1291 }
1292 }
Kevin Rocardc43ea142019-01-31 18:17:37 -08001293 }
Eric Laurent81784c32012-11-19 14:55:58 -08001294 return status;
1295}
1296
Andy Hung11e74242023-06-26 19:20:57 -07001297void Track::stop()
Eric Laurent81784c32012-11-19 14:55:58 -08001298{
Andy Hungc0691382018-09-12 18:01:57 -07001299 ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
Andy Hung11e74242023-06-26 19:20:57 -07001300 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001301 if (thread != 0) {
1302 Mutex::Autolock _l(thread->mLock);
1303 track_state state = mState;
1304 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
1305 // If the track is not active (PAUSED and buffers full), flush buffers
Andy Hung11e74242023-06-26 19:20:57 -07001306 auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001307 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
1308 reset();
1309 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -07001310 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001311 mState = STOPPED;
1312 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001313 // For fast tracks prepareTracks_l() will set state to STOPPING_2
1314 // presentation is complete
1315 // For an offloaded track this starts a drain and state will
1316 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -08001317 mState = STOPPING_1;
Eric Laurente93cc032016-05-05 10:15:10 -07001318 if (isOffloaded()) {
Andy Hung11e74242023-06-26 19:20:57 -07001319 mRetryCount = AudioFlinger::PlaybackThread::kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07001320 }
Eric Laurent81784c32012-11-19 14:55:58 -08001321 }
Eric Laurentb369caf2015-03-30 20:51:47 -07001322 playbackThread->broadcast_l();
Andy Hungc0691382018-09-12 18:01:57 -07001323 ALOGV("%s(%d): not stopping/stopped => stopping/stopped on thread %d",
1324 __func__, mId, (int)mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -08001325 }
jiabin7434e812023-06-27 18:22:35 +00001326 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->stop(); });
Eric Laurent81784c32012-11-19 14:55:58 -08001327 }
1328}
1329
Andy Hung11e74242023-06-26 19:20:57 -07001330void Track::pause()
Eric Laurent81784c32012-11-19 14:55:58 -08001331{
Andy Hungc0691382018-09-12 18:01:57 -07001332 ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
Andy Hung11e74242023-06-26 19:20:57 -07001333 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001334 if (thread != 0) {
1335 Mutex::Autolock _l(thread->mLock);
Andy Hung11e74242023-06-26 19:20:57 -07001336 auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001337 switch (mState) {
1338 case STOPPING_1:
1339 case STOPPING_2:
1340 if (!isOffloaded()) {
1341 /* nothing to do if track is not offloaded */
1342 break;
1343 }
1344
1345 // Offloaded track was draining, we need to carry on draining when resumed
1346 mResumeToStopping = true;
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07001347 FALLTHROUGH_INTENDED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001348 case ACTIVE:
1349 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08001350 mState = PAUSING;
Andy Hungc0691382018-09-12 18:01:57 -07001351 ALOGV("%s(%d): ACTIVE/RESUMING => PAUSING on thread %d",
1352 __func__, mId, (int)mThreadIoHandle);
Kuowei Li23666472021-01-20 10:23:25 +08001353 if (isOffloadedOrDirect()) {
1354 mPauseHwPending = true;
1355 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07001356 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001357 break;
Eric Laurent81784c32012-11-19 14:55:58 -08001358
Eric Laurentbfb1b832013-01-07 09:53:42 -08001359 default:
1360 break;
Eric Laurent81784c32012-11-19 14:55:58 -08001361 }
jiabin7434e812023-06-27 18:22:35 +00001362 // Pausing the TeePatch to avoid a glitch on underrun, at the cost of buffered audio loss.
1363 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->pause(); });
Eric Laurent81784c32012-11-19 14:55:58 -08001364 }
1365}
1366
Andy Hung11e74242023-06-26 19:20:57 -07001367void Track::flush()
Eric Laurent81784c32012-11-19 14:55:58 -08001368{
Andy Hungc0691382018-09-12 18:01:57 -07001369 ALOGV("%s(%d)", __func__, mId);
Andy Hung11e74242023-06-26 19:20:57 -07001370 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001371 if (thread != 0) {
1372 Mutex::Autolock _l(thread->mLock);
Andy Hung11e74242023-06-26 19:20:57 -07001373 auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001374
Phil Burk4bb650b2016-09-09 12:11:17 -07001375 // Flush the ring buffer now if the track is not active in the PlaybackThread.
1376 // Otherwise the flush would not be done until the track is resumed.
1377 // Requires FastTrack removal be BLOCK_UNTIL_ACKED
1378 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
1379 (void)mServerProxy->flushBufferIfNeeded();
1380 }
1381
Eric Laurentbfb1b832013-01-07 09:53:42 -08001382 if (isOffloaded()) {
1383 // If offloaded we allow flush during any state except terminated
1384 // and keep the track active to avoid problems if user is seeking
1385 // rapidly and underlying hardware has a significant delay handling
1386 // a pause
1387 if (isTerminated()) {
1388 return;
1389 }
1390
Andy Hung9d84af52018-09-12 18:03:44 -07001391 ALOGV("%s(%d): offload flush", __func__, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08001392 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001393
1394 if (mState == STOPPING_1 || mState == STOPPING_2) {
Andy Hung9d84af52018-09-12 18:03:44 -07001395 ALOGV("%s(%d): flushed in STOPPING_1 or 2 state, change state to ACTIVE",
1396 __func__, mId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001397 mState = ACTIVE;
1398 }
1399
Haynes Mathew George7844f672014-01-15 12:32:55 -08001400 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001401 mResumeToStopping = false;
1402 } else {
1403 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
1404 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
1405 return;
1406 }
1407 // No point remaining in PAUSED state after a flush => go to
1408 // FLUSHED state
1409 mState = FLUSHED;
1410 // do not reset the track if it is still in the process of being stopped or paused.
1411 // this will be done by prepareTracks_l() when the track is stopped.
1412 // prepareTracks_l() will see mState == FLUSHED, then
1413 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -08001414 if (isDirect()) {
1415 mFlushHwPending = true;
1416 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001417 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
1418 reset();
1419 }
Eric Laurent81784c32012-11-19 14:55:58 -08001420 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001421 // Prevent flush being lost if the track is flushed and then resumed
1422 // before mixer thread can run. This is important when offloading
1423 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -07001424 playbackThread->broadcast_l();
jiabin7434e812023-06-27 18:22:35 +00001425 // Flush the Tee to avoid on resume playing old data and glitching on the transition to
1426 // new data
1427 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->flush(); });
Eric Laurent81784c32012-11-19 14:55:58 -08001428 }
1429}
1430
Haynes Mathew George7844f672014-01-15 12:32:55 -08001431// must be called with thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07001432void Track::flushAck()
Haynes Mathew George7844f672014-01-15 12:32:55 -08001433{
Andy Hung920f6572022-10-06 12:09:49 -07001434 if (!isOffloaded() && !isDirect()) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08001435 return;
Andy Hung920f6572022-10-06 12:09:49 -07001436 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08001437
Phil Burk4bb650b2016-09-09 12:11:17 -07001438 // Clear the client ring buffer so that the app can prime the buffer while paused.
1439 // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
1440 mServerProxy->flushBufferIfNeeded();
1441
Haynes Mathew George7844f672014-01-15 12:32:55 -08001442 mFlushHwPending = false;
1443}
1444
Andy Hung11e74242023-06-26 19:20:57 -07001445void Track::pauseAck()
Kuowei Li23666472021-01-20 10:23:25 +08001446{
1447 mPauseHwPending = false;
1448}
1449
Andy Hung11e74242023-06-26 19:20:57 -07001450void Track::reset()
Eric Laurent81784c32012-11-19 14:55:58 -08001451{
1452 // Do not reset twice to avoid discarding data written just after a flush and before
1453 // the audioflinger thread detects the track is stopped.
1454 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -08001455 // Force underrun condition to avoid false underrun callback until first data is
1456 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -07001457 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Andy Hung11e74242023-06-26 19:20:57 -07001458 mFillingStatus = FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001459 mResetDone = true;
1460 if (mState == FLUSHED) {
1461 mState = IDLE;
1462 }
1463 }
1464}
1465
Andy Hung11e74242023-06-26 19:20:57 -07001466status_t Track::setParameters(const String8& keyValuePairs)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001467{
Andy Hung11e74242023-06-26 19:20:57 -07001468 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001469 if (thread == 0) {
Andy Hung9d84af52018-09-12 18:03:44 -07001470 ALOGE("%s(%d): thread is dead", __func__, mId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001471 return FAILED_TRANSACTION;
Andy Hung11e74242023-06-26 19:20:57 -07001472 } else if ((thread->type() == AudioFlinger::ThreadBase::DIRECT) ||
1473 (thread->type() == AudioFlinger::ThreadBase::OFFLOAD)) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001474 return thread->setParameters(keyValuePairs);
1475 } else {
1476 return PERMISSION_DENIED;
1477 }
1478}
1479
Andy Hung11e74242023-06-26 19:20:57 -07001480status_t Track::selectPresentation(int presentationId,
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001481 int programId) {
Andy Hung11e74242023-06-26 19:20:57 -07001482 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001483 if (thread == 0) {
1484 ALOGE("thread is dead");
1485 return FAILED_TRANSACTION;
Andy Hung11e74242023-06-26 19:20:57 -07001486 } else if ((thread->type() == AudioFlinger::ThreadBase::DIRECT)
1487 || (thread->type() == AudioFlinger::ThreadBase::OFFLOAD)) {
1488 auto directOutputThread = static_cast<AudioFlinger::DirectOutputThread*>(thread.get());
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001489 return directOutputThread->selectPresentation(presentationId, programId);
1490 }
1491 return INVALID_OPERATION;
1492}
1493
Andy Hung11e74242023-06-26 19:20:57 -07001494VolumeShaper::Status Track::applyVolumeShaper(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001495 const sp<VolumeShaper::Configuration>& configuration,
1496 const sp<VolumeShaper::Operation>& operation)
1497{
Andy Hung398ffa22022-12-13 19:19:53 -08001498 VolumeShaper::Status status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung10cbff12017-02-21 17:30:14 -08001499
1500 if (isOffloadedOrDirect()) {
1501 // Signal thread to fetch new volume.
Andy Hung11e74242023-06-26 19:20:57 -07001502 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Andy Hung10cbff12017-02-21 17:30:14 -08001503 if (thread != 0) {
Kevin Rocard5f2136e2018-05-11 22:03:00 -07001504 Mutex::Autolock _l(thread->mLock);
Andy Hung10cbff12017-02-21 17:30:14 -08001505 thread->broadcast_l();
1506 }
1507 }
1508 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001509}
1510
Andy Hung11e74242023-06-26 19:20:57 -07001511sp<VolumeShaper::State> Track::getVolumeShaperState(int id) const
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001512{
1513 // Note: We don't check if Thread exists.
1514
1515 // mVolumeHandler is thread safe.
1516 return mVolumeHandler->getVolumeShaperState(id);
1517}
1518
Andy Hung11e74242023-06-26 19:20:57 -07001519void Track::setFinalVolume(float volumeLeft, float volumeRight)
Kevin Rocard12381092018-04-11 09:19:59 -07001520{
jiabin76d94692022-12-15 21:51:21 +00001521 mFinalVolumeLeft = volumeLeft;
1522 mFinalVolumeRight = volumeRight;
1523 const float volume = (volumeLeft + volumeRight) * 0.5f;
Kevin Rocard12381092018-04-11 09:19:59 -07001524 if (mFinalVolume != volume) { // Compare to an epsilon if too many meaningless updates
1525 mFinalVolume = volume;
1526 setMetadataHasChanged();
Andy Hunga81a4b42022-05-19 19:24:51 -07001527 mLogForceVolumeUpdate = true;
1528 }
1529 if (mLogForceVolumeUpdate) {
1530 mLogForceVolumeUpdate = false;
1531 mTrackMetrics.logVolume(mFinalVolume);
Kevin Rocard12381092018-04-11 09:19:59 -07001532 }
1533}
1534
Andy Hung11e74242023-06-26 19:20:57 -07001535void Track::copyMetadataTo(MetadataInserter& backInserter) const
Kevin Rocard12381092018-04-11 09:19:59 -07001536{
Eric Laurent49e39282022-06-24 18:42:45 +02001537 // Do not forward metadata for PatchTrack with unspecified stream type
1538 if (mStreamType == AUDIO_STREAM_PATCH) {
1539 return;
1540 }
1541
Eric Laurent94579172020-11-20 18:41:04 +01001542 playback_track_metadata_v7_t metadata;
1543 metadata.base = {
Kevin Rocard12381092018-04-11 09:19:59 -07001544 .usage = mAttr.usage,
1545 .content_type = mAttr.content_type,
1546 .gain = mFinalVolume,
1547 };
Eric Laurentfdf99502021-11-26 19:05:02 +01001548
1549 // When attributes are undefined, derive default values from stream type.
1550 // See AudioAttributes.java, usageForStreamType() and Builder.setInternalLegacyStreamType()
1551 if (mAttr.usage == AUDIO_USAGE_UNKNOWN) {
1552 switch (mStreamType) {
1553 case AUDIO_STREAM_VOICE_CALL:
1554 metadata.base.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1555 metadata.base.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1556 break;
1557 case AUDIO_STREAM_SYSTEM:
1558 metadata.base.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
1559 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1560 break;
1561 case AUDIO_STREAM_RING:
1562 metadata.base.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
1563 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1564 break;
1565 case AUDIO_STREAM_MUSIC:
1566 metadata.base.usage = AUDIO_USAGE_MEDIA;
1567 metadata.base.content_type = AUDIO_CONTENT_TYPE_MUSIC;
1568 break;
1569 case AUDIO_STREAM_ALARM:
1570 metadata.base.usage = AUDIO_USAGE_ALARM;
1571 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1572 break;
1573 case AUDIO_STREAM_NOTIFICATION:
1574 metadata.base.usage = AUDIO_USAGE_NOTIFICATION;
1575 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1576 break;
1577 case AUDIO_STREAM_DTMF:
1578 metadata.base.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
1579 metadata.base.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1580 break;
1581 case AUDIO_STREAM_ACCESSIBILITY:
1582 metadata.base.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
1583 metadata.base.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1584 break;
1585 case AUDIO_STREAM_ASSISTANT:
1586 metadata.base.usage = AUDIO_USAGE_ASSISTANT;
1587 metadata.base.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1588 break;
1589 case AUDIO_STREAM_REROUTING:
1590 metadata.base.usage = AUDIO_USAGE_VIRTUAL_SOURCE;
1591 // unknown content type
1592 break;
1593 case AUDIO_STREAM_CALL_ASSISTANT:
1594 metadata.base.usage = AUDIO_USAGE_CALL_ASSISTANT;
1595 metadata.base.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1596 break;
1597 default:
1598 break;
1599 }
1600 }
1601
Eric Laurent78b07302022-10-07 16:20:34 +02001602 metadata.channel_mask = mChannelMask;
Eric Laurent94579172020-11-20 18:41:04 +01001603 strncpy(metadata.tags, mAttr.tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
1604 *backInserter++ = metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07001605}
1606
Andy Hung11e74242023-06-26 19:20:57 -07001607void Track::updateTeePatches_l() {
Jiabin Huangfb476842022-12-06 03:18:10 +00001608 if (mTeePatchesToUpdate.has_value()) {
jiabin7434e812023-06-27 18:22:35 +00001609 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->destroy(); });
Jiabin Huangfb476842022-12-06 03:18:10 +00001610 mTeePatches = mTeePatchesToUpdate.value();
1611 if (mState == TrackBase::ACTIVE || mState == TrackBase::RESUMING ||
1612 mState == TrackBase::STOPPING_1) {
jiabin7434e812023-06-27 18:22:35 +00001613 forEachTeePatchTrack_l([](const auto& patchTrack) { patchTrack->start(); });
Jiabin Huangfb476842022-12-06 03:18:10 +00001614 }
1615 mTeePatchesToUpdate.reset();
jiabinf042b9b2021-05-07 23:46:28 +00001616 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001617}
1618
Andy Hung11e74242023-06-26 19:20:57 -07001619void Track::setTeePatchesToUpdate_l(AudioFlinger::TeePatches teePatchesToUpdate) {
Jiabin Huangfb476842022-12-06 03:18:10 +00001620 ALOGW_IF(mTeePatchesToUpdate.has_value(),
1621 "%s, existing tee patches to update will be ignored", __func__);
1622 mTeePatchesToUpdate = std::move(teePatchesToUpdate);
1623}
1624
Vlad Popae8d99472022-06-30 16:02:48 +02001625// must be called with player thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07001626void Track::processMuteEvent_l(const sp<
Vlad Popae8d99472022-06-30 16:02:48 +02001627 IAudioManager>& audioManager, mute_state_t muteState)
1628{
1629 if (mMuteState == muteState) {
1630 // mute state did not change, do nothing
1631 return;
1632 }
1633
1634 status_t result = UNKNOWN_ERROR;
1635 if (audioManager && mPortId != AUDIO_PORT_HANDLE_NONE) {
1636 if (mMuteEventExtras == nullptr) {
1637 mMuteEventExtras = std::make_unique<os::PersistableBundle>();
1638 }
1639 mMuteEventExtras->putInt(String16(kExtraPlayerEventMuteKey),
1640 static_cast<int>(muteState));
1641
1642 result = audioManager->portEvent(mPortId,
1643 PLAYER_UPDATE_MUTED,
1644 mMuteEventExtras);
1645 }
1646
1647 if (result == OK) {
1648 mMuteState = muteState;
1649 } else {
1650 ALOGW("%s(%d): cannot process mute state for port ID %d, status error %d",
1651 __func__,
1652 id(),
1653 mPortId,
1654 result);
1655 }
1656}
1657
Andy Hung11e74242023-06-26 19:20:57 -07001658status_t Track::getTimestamp(AudioTimestamp& timestamp)
Glenn Kasten573d80a2013-08-26 09:36:23 -07001659{
Andy Hung818e7a32016-02-16 18:08:07 -08001660 if (!isOffloaded() && !isDirect()) {
1661 return INVALID_OPERATION; // normal tracks handled through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -07001662 }
Andy Hung11e74242023-06-26 19:20:57 -07001663 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Glenn Kasten573d80a2013-08-26 09:36:23 -07001664 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -07001665 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -07001666 }
Phil Burk6140c792015-03-19 14:30:21 -07001667
Glenn Kasten573d80a2013-08-26 09:36:23 -07001668 Mutex::Autolock _l(thread->mLock);
Andy Hung11e74242023-06-26 19:20:57 -07001669 auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Andy Hung818e7a32016-02-16 18:08:07 -08001670 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -07001671}
1672
Andy Hung11e74242023-06-26 19:20:57 -07001673status_t Track::attachAuxEffect(int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001674{
Andy Hung11e74242023-06-26 19:20:57 -07001675 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent6c796322019-04-09 14:13:17 -07001676 if (thread == nullptr) {
1677 return DEAD_OBJECT;
1678 }
Eric Laurent81784c32012-11-19 14:55:58 -08001679
Andy Hung11e74242023-06-26 19:20:57 -07001680 auto dstThread = sp<AudioFlinger::PlaybackThread>::cast(thread);
1681 // srcThread is initialized by call to moveAuxEffectToIo()
1682 sp<AudioFlinger::PlaybackThread> srcThread;
Eric Laurent6c796322019-04-09 14:13:17 -07001683 sp<AudioFlinger> af = mClient->audioFlinger();
1684 status_t status = af->moveAuxEffectToIo(EffectId, dstThread, &srcThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001685
Eric Laurent6c796322019-04-09 14:13:17 -07001686 if (EffectId != 0 && status == NO_ERROR) {
1687 status = dstThread->attachAuxEffect(this, EffectId);
1688 if (status == NO_ERROR) {
1689 AudioSystem::moveEffectsToIo(std::vector<int>(EffectId), dstThread->id());
Eric Laurent81784c32012-11-19 14:55:58 -08001690 }
Eric Laurent6c796322019-04-09 14:13:17 -07001691 }
1692
1693 if (status != NO_ERROR && srcThread != nullptr) {
1694 af->moveAuxEffectToIo(EffectId, srcThread, &dstThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001695 }
1696 return status;
1697}
1698
Andy Hung11e74242023-06-26 19:20:57 -07001699void Track::setAuxBuffer(int EffectId, int32_t *buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001700{
1701 mAuxEffectId = EffectId;
1702 mAuxBuffer = buffer;
1703}
1704
Andy Hung59de4262021-06-14 10:53:54 -07001705// presentationComplete verified by frames, used by Mixed tracks.
Andy Hung11e74242023-06-26 19:20:57 -07001706bool Track::presentationComplete(
Andy Hung818e7a32016-02-16 18:08:07 -08001707 int64_t framesWritten, size_t audioHalFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001708{
Andy Hung818e7a32016-02-16 18:08:07 -08001709 // TODO: improve this based on FrameMap if it exists, to ensure full drain.
1710 // This assists in proper timestamp computation as well as wakelock management.
1711
Eric Laurent81784c32012-11-19 14:55:58 -08001712 // a track is considered presented when the total number of frames written to audio HAL
1713 // corresponds to the number of frames written when presentationComplete() is called for the
1714 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001715 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1716 // to detect when all frames have been played. In this case framesWritten isn't
1717 // useful because it doesn't always reflect whether there is data in the h/w
1718 // buffers, particularly if a track has been paused and resumed during draining
Andy Hung9d84af52018-09-12 18:03:44 -07001719 ALOGV("%s(%d): presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
1720 __func__, mId,
Andy Hung818e7a32016-02-16 18:08:07 -08001721 (long long)mPresentationCompleteFrames, (long long)framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001722 if (mPresentationCompleteFrames == 0) {
1723 mPresentationCompleteFrames = framesWritten + audioHalFrames;
Andy Hung59de4262021-06-14 10:53:54 -07001724 ALOGV("%s(%d): set:"
Andy Hung9d84af52018-09-12 18:03:44 -07001725 " mPresentationCompleteFrames %lld audioHalFrames %zu",
1726 __func__, mId,
Andy Hung818e7a32016-02-16 18:08:07 -08001727 (long long)mPresentationCompleteFrames, audioHalFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08001728 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001729
Andy Hungc54b1ff2016-02-23 14:07:07 -08001730 bool complete;
Andy Hung59de4262021-06-14 10:53:54 -07001731 if (isFastTrack()) { // does not go through linear map
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001732 complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
Andy Hung59de4262021-06-14 10:53:54 -07001733 ALOGV("%s(%d): %s framesWritten:%lld mPresentationCompleteFrames:%lld",
1734 __func__, mId, (complete ? "complete" : "waiting"),
1735 (long long) framesWritten, (long long) mPresentationCompleteFrames);
Andy Hungc54b1ff2016-02-23 14:07:07 -08001736 } else { // Normal tracks, OutputTracks, and PatchTracks
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001737 complete = framesWritten >= (int64_t) mPresentationCompleteFrames
Andy Hungc54b1ff2016-02-23 14:07:07 -08001738 && mAudioTrackServerProxy->isDrained();
1739 }
1740
1741 if (complete) {
Andy Hung59de4262021-06-14 10:53:54 -07001742 notifyPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08001743 return true;
1744 }
1745 return false;
1746}
1747
Andy Hung59de4262021-06-14 10:53:54 -07001748// presentationComplete checked by time, used by DirectTracks.
Andy Hung11e74242023-06-26 19:20:57 -07001749bool Track::presentationComplete(uint32_t latencyMs)
Andy Hung59de4262021-06-14 10:53:54 -07001750{
1751 // For Offloaded or Direct tracks.
1752
1753 // For a direct track, we incorporated time based testing for presentationComplete.
1754
1755 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1756 // to detect when all frames have been played. In this case latencyMs isn't
1757 // useful because it doesn't always reflect whether there is data in the h/w
1758 // buffers, particularly if a track has been paused and resumed during draining
1759
1760 constexpr float MIN_SPEED = 0.125f; // min speed scaling allowed for timely response.
1761 if (mPresentationCompleteTimeNs == 0) {
1762 mPresentationCompleteTimeNs = systemTime() + latencyMs * 1e6 / fmax(mSpeed, MIN_SPEED);
1763 ALOGV("%s(%d): set: latencyMs %u mPresentationCompleteTimeNs:%lld",
1764 __func__, mId, latencyMs, (long long) mPresentationCompleteTimeNs);
1765 }
1766
1767 bool complete;
1768 if (isOffloaded()) {
1769 complete = true;
1770 } else { // Direct
1771 complete = systemTime() >= mPresentationCompleteTimeNs;
1772 ALOGV("%s(%d): %s", __func__, mId, (complete ? "complete" : "waiting"));
1773 }
1774 if (complete) {
1775 notifyPresentationComplete();
1776 return true;
1777 }
1778 return false;
1779}
1780
Andy Hung11e74242023-06-26 19:20:57 -07001781void Track::notifyPresentationComplete()
Andy Hung59de4262021-06-14 10:53:54 -07001782{
1783 // This only triggers once. TODO: should we enforce this?
1784 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1785 mAudioTrackServerProxy->setStreamEndDone();
1786}
1787
Andy Hung11e74242023-06-26 19:20:57 -07001788void Track::triggerEvents(AudioSystem::sync_event_t type)
Eric Laurent81784c32012-11-19 14:55:58 -08001789{
Andy Hung068e08e2023-05-15 19:02:55 -07001790 for (auto it = mSyncEvents.begin(); it != mSyncEvents.end();) {
1791 if ((*it)->type() == type) {
Andy Hung93bb5732023-05-04 21:16:34 -07001792 ALOGV("%s: triggering SyncEvent type %d", __func__, type);
Andy Hung068e08e2023-05-15 19:02:55 -07001793 (*it)->trigger();
1794 it = mSyncEvents.erase(it);
Ivan Lozano5ec161b2017-12-06 10:00:28 -08001795 } else {
Andy Hung068e08e2023-05-15 19:02:55 -07001796 ++it;
Eric Laurent81784c32012-11-19 14:55:58 -08001797 }
1798 }
1799}
1800
1801// implement VolumeBufferProvider interface
1802
Andy Hung11e74242023-06-26 19:20:57 -07001803gain_minifloat_packed_t Track::getVolumeLR() const
Eric Laurent81784c32012-11-19 14:55:58 -08001804{
1805 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1806 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001807 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1808 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1809 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001810 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001811 if (vl > GAIN_FLOAT_UNITY) {
1812 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001813 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001814 if (vr > GAIN_FLOAT_UNITY) {
1815 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001816 }
1817 // now apply the cached master volume and stream type volume;
1818 // this is trusted but lacks any synchronization or barrier so may be stale
1819 float v = mCachedVolume;
1820 vl *= v;
1821 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001822 // re-combine into packed minifloat
1823 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001824 // FIXME look at mute, pause, and stop flags
1825 return vlr;
1826}
1827
Andy Hung11e74242023-06-26 19:20:57 -07001828status_t Track::setSyncEvent(
Andy Hung068e08e2023-05-15 19:02:55 -07001829 const sp<audioflinger::SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08001830{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001831 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001832 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1833 (mState == STOPPED)))) {
Andy Hung9d84af52018-09-12 18:03:44 -07001834 ALOGW("%s(%d): in invalid state %d on session %d %s mode, framesReady %zu",
1835 __func__, mId,
Andy Hung959b5b82021-09-24 10:46:20 -07001836 (int)mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
Eric Laurent81784c32012-11-19 14:55:58 -08001837 event->cancel();
1838 return INVALID_OPERATION;
1839 }
1840 (void) TrackBase::setSyncEvent(event);
1841 return NO_ERROR;
1842}
1843
Andy Hung11e74242023-06-26 19:20:57 -07001844void Track::invalidate()
Glenn Kasten5736c352012-12-04 12:12:34 -08001845{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001846 TrackBase::invalidate();
Eric Laurent4d231dc2016-03-11 18:38:23 -08001847 signalClientFlag(CBLK_INVALID);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001848}
1849
Andy Hung11e74242023-06-26 19:20:57 -07001850void Track::disable()
Eric Laurent4d231dc2016-03-11 18:38:23 -08001851{
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01001852 // TODO(b/142394888): the filling status should also be reset to filling
Eric Laurent4d231dc2016-03-11 18:38:23 -08001853 signalClientFlag(CBLK_DISABLED);
1854}
1855
Andy Hung11e74242023-06-26 19:20:57 -07001856void Track::signalClientFlag(int32_t flag)
Eric Laurent4d231dc2016-03-11 18:38:23 -08001857{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001858 // FIXME should use proxy, and needs work
1859 audio_track_cblk_t* cblk = mCblk;
Eric Laurent4d231dc2016-03-11 18:38:23 -08001860 android_atomic_or(flag, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001861 android_atomic_release_store(0x40000000, &cblk->mFutex);
1862 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001863 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001864}
1865
Andy Hung11e74242023-06-26 19:20:57 -07001866void Track::signal()
Eric Laurent59fe0102013-09-27 18:48:26 -07001867{
Andy Hung11e74242023-06-26 19:20:57 -07001868 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent59fe0102013-09-27 18:48:26 -07001869 if (thread != 0) {
Andy Hung11e74242023-06-26 19:20:57 -07001870 auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Eric Laurent59fe0102013-09-27 18:48:26 -07001871 Mutex::Autolock _l(t->mLock);
1872 t->broadcast_l();
1873 }
1874}
1875
Andy Hung11e74242023-06-26 19:20:57 -07001876status_t Track::getDualMonoMode(audio_dual_mono_mode_t* mode) const
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001877{
1878 status_t status = INVALID_OPERATION;
1879 if (isOffloadedOrDirect()) {
Andy Hung11e74242023-06-26 19:20:57 -07001880 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001881 if (thread != nullptr) {
Andy Hung11e74242023-06-26 19:20:57 -07001882 auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001883 Mutex::Autolock _l(t->mLock);
1884 status = t->mOutput->stream->getDualMonoMode(mode);
1885 ALOGD_IF((status == NO_ERROR) && (mDualMonoMode != *mode),
1886 "%s: mode %d inconsistent", __func__, mDualMonoMode);
1887 }
1888 }
1889 return status;
1890}
1891
Andy Hung11e74242023-06-26 19:20:57 -07001892status_t Track::setDualMonoMode(audio_dual_mono_mode_t mode)
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001893{
1894 status_t status = INVALID_OPERATION;
1895 if (isOffloadedOrDirect()) {
Andy Hung11e74242023-06-26 19:20:57 -07001896 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001897 if (thread != nullptr) {
Andy Hung11e74242023-06-26 19:20:57 -07001898 auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001899 Mutex::Autolock lock(t->mLock);
1900 status = t->mOutput->stream->setDualMonoMode(mode);
1901 if (status == NO_ERROR) {
1902 mDualMonoMode = mode;
1903 }
1904 }
1905 }
1906 return status;
1907}
1908
Andy Hung11e74242023-06-26 19:20:57 -07001909status_t Track::getAudioDescriptionMixLevel(float* leveldB) const
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001910{
1911 status_t status = INVALID_OPERATION;
1912 if (isOffloadedOrDirect()) {
Andy Hung11e74242023-06-26 19:20:57 -07001913 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001914 if (thread != nullptr) {
Andy Hung11e74242023-06-26 19:20:57 -07001915 auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001916 Mutex::Autolock lock(t->mLock);
1917 status = t->mOutput->stream->getAudioDescriptionMixLevel(leveldB);
1918 ALOGD_IF((status == NO_ERROR) && (mAudioDescriptionMixLevel != *leveldB),
1919 "%s: level %.3f inconsistent", __func__, mAudioDescriptionMixLevel);
1920 }
1921 }
1922 return status;
1923}
1924
Andy Hung11e74242023-06-26 19:20:57 -07001925status_t Track::setAudioDescriptionMixLevel(float leveldB)
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001926{
1927 status_t status = INVALID_OPERATION;
1928 if (isOffloadedOrDirect()) {
Andy Hung11e74242023-06-26 19:20:57 -07001929 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001930 if (thread != nullptr) {
Andy Hung11e74242023-06-26 19:20:57 -07001931 auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001932 Mutex::Autolock lock(t->mLock);
1933 status = t->mOutput->stream->setAudioDescriptionMixLevel(leveldB);
1934 if (status == NO_ERROR) {
1935 mAudioDescriptionMixLevel = leveldB;
1936 }
1937 }
1938 }
1939 return status;
1940}
1941
Andy Hung11e74242023-06-26 19:20:57 -07001942status_t Track::getPlaybackRateParameters(
Andy Hungfafbebc2023-06-23 19:27:19 -07001943 audio_playback_rate_t* playbackRate) const
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001944{
1945 status_t status = INVALID_OPERATION;
1946 if (isOffloadedOrDirect()) {
Andy Hung11e74242023-06-26 19:20:57 -07001947 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001948 if (thread != nullptr) {
Andy Hung11e74242023-06-26 19:20:57 -07001949 auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001950 Mutex::Autolock lock(t->mLock);
1951 status = t->mOutput->stream->getPlaybackRateParameters(playbackRate);
1952 ALOGD_IF((status == NO_ERROR) &&
1953 !isAudioPlaybackRateEqual(mPlaybackRateParameters, *playbackRate),
1954 "%s: playbackRate inconsistent", __func__);
1955 }
1956 }
1957 return status;
1958}
1959
Andy Hung11e74242023-06-26 19:20:57 -07001960status_t Track::setPlaybackRateParameters(
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001961 const audio_playback_rate_t& playbackRate)
1962{
1963 status_t status = INVALID_OPERATION;
1964 if (isOffloadedOrDirect()) {
Andy Hung11e74242023-06-26 19:20:57 -07001965 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001966 if (thread != nullptr) {
Andy Hung11e74242023-06-26 19:20:57 -07001967 auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Kuowei Lid4adbdb2020-08-13 14:44:25 +08001968 Mutex::Autolock lock(t->mLock);
1969 status = t->mOutput->stream->setPlaybackRateParameters(playbackRate);
1970 if (status == NO_ERROR) {
1971 mPlaybackRateParameters = playbackRate;
1972 }
1973 }
1974 }
1975 return status;
1976}
1977
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001978//To be called with thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07001979bool Track::isResumePending() const {
Andy Hung920f6572022-10-06 12:09:49 -07001980 if (mState == RESUMING) {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001981 return true;
Andy Hung920f6572022-10-06 12:09:49 -07001982 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001983 /* Resume is pending if track was stopping before pause was called */
1984 if (mState == STOPPING_1 &&
Andy Hung920f6572022-10-06 12:09:49 -07001985 mResumeToStopping) {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001986 return true;
Andy Hung920f6572022-10-06 12:09:49 -07001987 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001988
1989 return false;
1990}
1991
1992//To be called with thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07001993void Track::resumeAck() {
Andy Hung920f6572022-10-06 12:09:49 -07001994 if (mState == RESUMING) {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001995 mState = ACTIVE;
Andy Hung920f6572022-10-06 12:09:49 -07001996 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001997
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001998 // Other possibility of pending resume is stopping_1 state
1999 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08002000 // drain being called.
2001 if (mState == STOPPING_1) {
2002 mResumeToStopping = false;
2003 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08002004}
Andy Hunge10393e2015-06-12 13:59:33 -07002005
2006//To be called with thread lock held
Andy Hung11e74242023-06-26 19:20:57 -07002007void Track::updateTrackFrameInfo(
Andy Hung818e7a32016-02-16 18:08:07 -08002008 int64_t trackFramesReleased, int64_t sinkFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07002009 uint32_t halSampleRate, const ExtendedTimestamp &timeStamp) {
Andy Hung30282562018-08-08 18:27:03 -07002010 // Make the kernel frametime available.
2011 const FrameTime ft{
2012 timeStamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
2013 timeStamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]};
2014 // ALOGD("FrameTime: %lld %lld", (long long)ft.frames, (long long)ft.timeNs);
2015 mKernelFrameTime.store(ft);
2016 if (!audio_is_linear_pcm(mFormat)) {
2017 return;
2018 }
2019
Andy Hung818e7a32016-02-16 18:08:07 -08002020 //update frame map
Andy Hunge10393e2015-06-12 13:59:33 -07002021 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
Andy Hung818e7a32016-02-16 18:08:07 -08002022
2023 // adjust server times and set drained state.
2024 //
2025 // Our timestamps are only updated when the track is on the Thread active list.
2026 // We need to ensure that tracks are not removed before full drain.
2027 ExtendedTimestamp local = timeStamp;
Andy Hungcef2daa2018-06-01 15:31:49 -07002028 bool drained = true; // default assume drained, if no server info found
Andy Hung818e7a32016-02-16 18:08:07 -08002029 bool checked = false;
2030 for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
2031 i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
2032 // Lookup the track frame corresponding to the sink frame position.
2033 if (local.mTimeNs[i] > 0) {
2034 local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
2035 // check drain state from the latest stage in the pipeline.
Andy Hung6d7b1192016-05-07 22:59:48 -07002036 if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
Andy Hungcef2daa2018-06-01 15:31:49 -07002037 drained = local.mPosition[i] >= mAudioTrackServerProxy->framesReleased();
Andy Hung818e7a32016-02-16 18:08:07 -08002038 checked = true;
2039 }
2040 }
Andy Hunge10393e2015-06-12 13:59:33 -07002041 }
Andy Hungcef2daa2018-06-01 15:31:49 -07002042
Andy Hung93bb5732023-05-04 21:16:34 -07002043 ALOGV("%s: trackFramesReleased:%lld sinkFramesWritten:%lld setDrained: %d",
2044 __func__, (long long)trackFramesReleased, (long long)sinkFramesWritten, drained);
Andy Hungcef2daa2018-06-01 15:31:49 -07002045 mAudioTrackServerProxy->setDrained(drained);
Andy Hungea2b9c02016-02-12 17:06:53 -08002046 // Set correction for flushed frames that are not accounted for in released.
Andy Hungea2b9c02016-02-12 17:06:53 -08002047 local.mFlushed = mAudioTrackServerProxy->framesFlushed();
Andy Hung818e7a32016-02-16 18:08:07 -08002048 mServerProxy->setTimestamp(local);
Andy Hungcef2daa2018-06-01 15:31:49 -07002049
2050 // Compute latency info.
2051 const bool useTrackTimestamp = !drained;
2052 const double latencyMs = useTrackTimestamp
2053 ? local.getOutputServerLatencyMs(sampleRate())
2054 : timeStamp.getOutputServerLatencyMs(halSampleRate);
2055
2056 mServerLatencyFromTrack.store(useTrackTimestamp);
2057 mServerLatencyMs.store(latencyMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08002058
Andy Hung62921122020-05-18 10:47:31 -07002059 if (mLogStartCountdown > 0
2060 && local.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0
2061 && local.mPosition[ExtendedTimestamp::LOCATION_KERNEL] > 0)
2062 {
2063 if (mLogStartCountdown > 1) {
2064 --mLogStartCountdown;
2065 } else if (latencyMs < mLogLatencyMs) { // wait for latency to stabilize (dip)
2066 mLogStartCountdown = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08002067 // startup is the difference in times for the current timestamp and our start
2068 double startUpMs =
Andy Hung62921122020-05-18 10:47:31 -07002069 (local.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] - mLogStartTimeNs) * 1e-6;
Andy Hungb68f5eb2019-12-03 16:49:17 -08002070 // adjust for frames played.
Andy Hung62921122020-05-18 10:47:31 -07002071 startUpMs -= (local.mPosition[ExtendedTimestamp::LOCATION_KERNEL] - mLogStartFrames)
2072 * 1e3 / mSampleRate;
2073 ALOGV("%s: latencyMs:%lf startUpMs:%lf"
2074 " localTime:%lld startTime:%lld"
2075 " localPosition:%lld startPosition:%lld",
2076 __func__, latencyMs, startUpMs,
2077 (long long)local.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
Andy Hungb68f5eb2019-12-03 16:49:17 -08002078 (long long)mLogStartTimeNs,
Andy Hung62921122020-05-18 10:47:31 -07002079 (long long)local.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
Andy Hungb68f5eb2019-12-03 16:49:17 -08002080 (long long)mLogStartFrames);
Andy Hungc2b11cb2020-04-22 09:04:01 -07002081 mTrackMetrics.logLatencyAndStartup(latencyMs, startUpMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08002082 }
Andy Hung62921122020-05-18 10:47:31 -07002083 mLogLatencyMs = latencyMs;
Andy Hungb68f5eb2019-12-03 16:49:17 -08002084 }
Andy Hunge10393e2015-06-12 13:59:33 -07002085}
2086
Andy Hung11e74242023-06-26 19:20:57 -07002087bool Track::AudioVibrationController::setMute(bool muted) {
2088 sp<AudioFlinger::ThreadBase> thread = mTrack->mThread.promote();
jiabin57303cc2018-12-18 15:45:57 -08002089 if (thread != 0) {
2090 // Lock for updating mHapticPlaybackEnabled.
2091 Mutex::Autolock _l(thread->mLock);
Andy Hung11e74242023-06-26 19:20:57 -07002092 auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
jiabin57303cc2018-12-18 15:45:57 -08002093 if ((mTrack->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2094 && playbackThread->mHapticChannelCount > 0) {
SPeak Shenc19aa9e2022-11-11 00:28:50 +08002095 ALOGD("%s, haptic playback was %s for track %d",
2096 __func__, muted ? "muted" : "unmuted", mTrack->id());
2097 mTrack->setHapticPlaybackEnabled(!muted);
2098 return true;
jiabin57303cc2018-12-18 15:45:57 -08002099 }
2100 }
SPeak Shenc19aa9e2022-11-11 00:28:50 +08002101 return false;
2102}
2103
Andy Hung11e74242023-06-26 19:20:57 -07002104binder::Status Track::AudioVibrationController::mute(
SPeak Shenc19aa9e2022-11-11 00:28:50 +08002105 /*out*/ bool *ret) {
2106 *ret = setMute(true);
jiabin57303cc2018-12-18 15:45:57 -08002107 return binder::Status::ok();
2108}
2109
Andy Hung11e74242023-06-26 19:20:57 -07002110binder::Status Track::AudioVibrationController::unmute(
jiabin57303cc2018-12-18 15:45:57 -08002111 /*out*/ bool *ret) {
SPeak Shenc19aa9e2022-11-11 00:28:50 +08002112 *ret = setMute(false);
jiabin57303cc2018-12-18 15:45:57 -08002113 return binder::Status::ok();
2114}
2115
Eric Laurent81784c32012-11-19 14:55:58 -08002116// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -07002117#undef LOG_TAG
2118#define LOG_TAG "AF::OutputTrack"
Eric Laurent81784c32012-11-19 14:55:58 -08002119
Andy Hung11e74242023-06-26 19:20:57 -07002120/* static */
2121sp<IAfOutputTrack> IAfOutputTrack::create( // TODO(b/288339104) void*
2122 void* /* AudioFlinger::PlaybackThread */ playbackThread,
2123 void* /* AudioFlinger::DuplicatingThread */ sourceThread,
2124 uint32_t sampleRate,
2125 audio_format_t format,
2126 audio_channel_mask_t channelMask,
2127 size_t frameCount,
2128 const AttributionSourceState& attributionSource) {
2129 return sp<OutputTrack>::make(
2130 reinterpret_cast<AudioFlinger::PlaybackThread*>(playbackThread),
2131 reinterpret_cast<AudioFlinger::DuplicatingThread*>(sourceThread),
2132 sampleRate,
2133 format,
2134 channelMask,
2135 frameCount,
2136 attributionSource);
2137}
2138
2139OutputTrack::OutputTrack(
2140 AudioFlinger::PlaybackThread *playbackThread,
2141 AudioFlinger::DuplicatingThread *sourceThread,
Eric Laurent81784c32012-11-19 14:55:58 -08002142 uint32_t sampleRate,
2143 audio_format_t format,
2144 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002145 size_t frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00002146 const AttributionSourceState& attributionSource)
Eric Laurent223fd5c2014-11-11 13:43:36 -08002147 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002148 audio_attributes_t{} /* currently unused for output track */,
Eric Laurent223fd5c2014-11-11 13:43:36 -08002149 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07002150 nullptr /* buffer */, (size_t)0 /* bufferSize */, nullptr /* sharedBuffer */,
Svet Ganov33761132021-05-13 22:51:08 +00002151 AUDIO_SESSION_NONE, getpid(), attributionSource, AUDIO_OUTPUT_FLAG_NONE,
Glenn Kastend848eb42016-03-08 13:42:11 -08002152 TYPE_OUTPUT),
Eric Laurent5bba2f62016-03-18 11:14:14 -07002153 mActive(false), mSourceThread(sourceThread)
Eric Laurent81784c32012-11-19 14:55:58 -08002154{
2155
2156 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08002157 mOutBuffer.frameCount = 0;
2158 playbackThread->mTracks.add(this);
Andy Hung9d84af52018-09-12 18:03:44 -07002159 ALOGV("%s(): mCblk %p, mBuffer %p, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002160 "frameCount %zu, mChannelMask 0x%08x",
Andy Hung9d84af52018-09-12 18:03:44 -07002161 __func__, mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08002162 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08002163 // since client and server are in the same process,
2164 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07002165 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
2166 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07002167 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07002168 mClientProxy->setSendLevel(0.0);
2169 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08002170 } else {
Andy Hung9d84af52018-09-12 18:03:44 -07002171 ALOGW("%s(%d): Error creating output track on thread %d",
2172 __func__, mId, (int)mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -08002173 }
2174}
2175
Andy Hung11e74242023-06-26 19:20:57 -07002176OutputTrack::~OutputTrack()
Eric Laurent81784c32012-11-19 14:55:58 -08002177{
2178 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08002179 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08002180}
2181
Andy Hung11e74242023-06-26 19:20:57 -07002182status_t OutputTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08002183 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08002184{
2185 status_t status = Track::start(event, triggerSession);
2186 if (status != NO_ERROR) {
2187 return status;
2188 }
2189
2190 mActive = true;
2191 mRetryCount = 127;
2192 return status;
2193}
2194
Andy Hung11e74242023-06-26 19:20:57 -07002195void OutputTrack::stop()
Eric Laurent81784c32012-11-19 14:55:58 -08002196{
2197 Track::stop();
2198 clearBufferQueue();
2199 mOutBuffer.frameCount = 0;
2200 mActive = false;
2201}
2202
Andy Hung11e74242023-06-26 19:20:57 -07002203ssize_t OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08002204{
Eric Laurent19952e12023-04-20 10:08:29 +02002205 if (!mActive && frames != 0) {
Andy Hung11e74242023-06-26 19:20:57 -07002206 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent19952e12023-04-20 10:08:29 +02002207 if (thread != nullptr && thread->standby()) {
2208 // preload one silent buffer to trigger mixer on start()
2209 ClientProxy::Buffer buf { .mFrameCount = mClientProxy->getStartThresholdInFrames() };
2210 status_t status = mClientProxy->obtainBuffer(&buf);
2211 if (status != NO_ERROR && status != NOT_ENOUGH_DATA && status != WOULD_BLOCK) {
2212 ALOGE("%s(%d): could not obtain buffer on start", __func__, mId);
2213 return 0;
2214 }
2215 memset(buf.mRaw, 0, buf.mFrameCount * mFrameSize);
2216 mClientProxy->releaseBuffer(&buf);
2217
2218 (void) start();
2219
2220 // wait for HAL stream to start before sending actual audio. Doing this on each
2221 // OutputTrack makes that playback start on all output streams is synchronized.
2222 // If another OutputTrack has already started it can underrun but this is OK
2223 // as only silence has been played so far and the retry count is very high on
2224 // OutputTrack.
Andy Hung11e74242023-06-26 19:20:57 -07002225 auto* const pt = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
Eric Laurent19952e12023-04-20 10:08:29 +02002226 if (!pt->waitForHalStart()) {
2227 ALOGW("%s(%d): timeout waiting for thread to exit standby", __func__, mId);
2228 stop();
2229 return 0;
2230 }
2231
2232 // enqueue the first buffer and exit so that other OutputTracks will also start before
2233 // write() is called again and this buffer actually consumed.
2234 Buffer firstBuffer;
2235 firstBuffer.frameCount = frames;
2236 firstBuffer.raw = data;
2237 queueBuffer(firstBuffer);
2238 return frames;
2239 } else {
2240 (void) start();
2241 }
2242 }
2243
Eric Laurent81784c32012-11-19 14:55:58 -08002244 Buffer *pInBuffer;
2245 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08002246 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08002247 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08002248 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurent81784c32012-11-19 14:55:58 -08002249 while (waitTimeLeftMs) {
2250 // First write pending buffers, then new data
2251 if (mBufferQueue.size()) {
2252 pInBuffer = mBufferQueue.itemAt(0);
2253 } else {
2254 pInBuffer = &inBuffer;
2255 }
2256
2257 if (pInBuffer->frameCount == 0) {
2258 break;
2259 }
2260
2261 if (mOutBuffer.frameCount == 0) {
2262 mOutBuffer.frameCount = pInBuffer->frameCount;
2263 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002264 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
Eric Laurent4d231dc2016-03-11 18:38:23 -08002265 if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
Andy Hung9d84af52018-09-12 18:03:44 -07002266 ALOGV("%s(%d): thread %d no more output buffers; status %d",
2267 __func__, mId,
2268 (int)mThreadIoHandle, status);
Eric Laurent81784c32012-11-19 14:55:58 -08002269 break;
2270 }
2271 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2272 if (waitTimeLeftMs >= waitTimeMs) {
2273 waitTimeLeftMs -= waitTimeMs;
2274 } else {
2275 waitTimeLeftMs = 0;
2276 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08002277 if (status == NOT_ENOUGH_DATA) {
2278 restartIfDisabled();
2279 continue;
2280 }
Eric Laurent81784c32012-11-19 14:55:58 -08002281 }
2282
2283 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
2284 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08002285 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002286 Proxy::Buffer buf;
2287 buf.mFrameCount = outFrames;
2288 buf.mRaw = NULL;
2289 mClientProxy->releaseBuffer(&buf);
Eric Laurent4d231dc2016-03-11 18:38:23 -08002290 restartIfDisabled();
Eric Laurent81784c32012-11-19 14:55:58 -08002291 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08002292 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002293 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08002294 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002295
2296 if (pInBuffer->frameCount == 0) {
2297 if (mBufferQueue.size()) {
2298 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08002299 free(pInBuffer->mBuffer);
Yunlian Jiang8adc8082017-06-06 15:59:44 -07002300 if (pInBuffer != &inBuffer) {
2301 delete pInBuffer;
2302 }
Andy Hung9d84af52018-09-12 18:03:44 -07002303 ALOGV("%s(%d): thread %d released overflow buffer %zu",
2304 __func__, mId,
2305 (int)mThreadIoHandle, mBufferQueue.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002306 } else {
2307 break;
2308 }
2309 }
2310 }
2311
2312 // If we could not write all frames, allocate a buffer and queue it for next time.
2313 if (inBuffer.frameCount) {
Andy Hung11e74242023-06-26 19:20:57 -07002314 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002315 if (thread != 0 && !thread->standby()) {
Eric Laurent19952e12023-04-20 10:08:29 +02002316 queueBuffer(inBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002317 }
2318 }
2319
Andy Hungc25b84a2015-01-14 19:04:10 -08002320 // Calling write() with a 0 length buffer means that no more data will be written:
2321 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
2322 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
2323 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08002324 }
2325
Andy Hung1c86ebe2018-05-29 20:29:08 -07002326 return frames - inBuffer.frameCount; // number of frames consumed.
Eric Laurent81784c32012-11-19 14:55:58 -08002327}
2328
Andy Hung11e74242023-06-26 19:20:57 -07002329void OutputTrack::queueBuffer(Buffer& inBuffer) {
Eric Laurent19952e12023-04-20 10:08:29 +02002330
2331 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2332 Buffer *pInBuffer = new Buffer;
2333 const size_t bufferSize = inBuffer.frameCount * mFrameSize;
2334 pInBuffer->mBuffer = malloc(bufferSize);
2335 LOG_ALWAYS_FATAL_IF(pInBuffer->mBuffer == nullptr,
2336 "%s: Unable to malloc size %zu", __func__, bufferSize);
2337 pInBuffer->frameCount = inBuffer.frameCount;
2338 pInBuffer->raw = pInBuffer->mBuffer;
2339 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
2340 mBufferQueue.add(pInBuffer);
2341 ALOGV("%s(%d): thread %d adding overflow buffer %zu", __func__, mId,
2342 (int)mThreadIoHandle, mBufferQueue.size());
2343 // audio data is consumed (stored locally); set frameCount to 0.
2344 inBuffer.frameCount = 0;
2345 } else {
2346 ALOGW("%s(%d): thread %d no more overflow buffers",
2347 __func__, mId, (int)mThreadIoHandle);
2348 // TODO: return error for this.
2349 }
2350}
2351
Andy Hung11e74242023-06-26 19:20:57 -07002352void OutputTrack::copyMetadataTo(MetadataInserter& backInserter) const
Kevin Rocard12381092018-04-11 09:19:59 -07002353{
2354 std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
2355 backInserter = std::copy(mTrackMetadatas.begin(), mTrackMetadatas.end(), backInserter);
2356}
2357
Andy Hung11e74242023-06-26 19:20:57 -07002358void OutputTrack::setMetadatas(const SourceMetadatas& metadatas) {
Kevin Rocard12381092018-04-11 09:19:59 -07002359 {
2360 std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
2361 mTrackMetadatas = metadatas;
2362 }
2363 // No need to adjust metadata track volumes as OutputTrack volumes are always 0dBFS.
2364 setMetadataHasChanged();
2365}
2366
Andy Hung11e74242023-06-26 19:20:57 -07002367status_t OutputTrack::obtainBuffer(
Eric Laurent81784c32012-11-19 14:55:58 -08002368 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
2369{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002370 ClientProxy::Buffer buf;
2371 buf.mFrameCount = buffer->frameCount;
2372 struct timespec timeout;
2373 timeout.tv_sec = waitTimeMs / 1000;
2374 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
2375 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
2376 buffer->frameCount = buf.mFrameCount;
2377 buffer->raw = buf.mRaw;
2378 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002379}
2380
Andy Hung11e74242023-06-26 19:20:57 -07002381void OutputTrack::clearBufferQueue()
Eric Laurent81784c32012-11-19 14:55:58 -08002382{
2383 size_t size = mBufferQueue.size();
2384
2385 for (size_t i = 0; i < size; i++) {
2386 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08002387 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002388 delete pBuffer;
2389 }
2390 mBufferQueue.clear();
2391}
2392
Andy Hung11e74242023-06-26 19:20:57 -07002393void OutputTrack::restartIfDisabled()
Eric Laurent4d231dc2016-03-11 18:38:23 -08002394{
2395 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
2396 if (mActive && (flags & CBLK_DISABLED)) {
2397 start();
2398 }
2399}
Eric Laurent81784c32012-11-19 14:55:58 -08002400
Andy Hung9d84af52018-09-12 18:03:44 -07002401// ----------------------------------------------------------------------------
2402#undef LOG_TAG
2403#define LOG_TAG "AF::PatchTrack"
2404
Andy Hung11e74242023-06-26 19:20:57 -07002405/* static */
2406sp<IAfPatchTrack> IAfPatchTrack::create(
2407 void* /* PlaybackThread */ playbackThread, // TODO(b/288339104)
2408 audio_stream_type_t streamType,
2409 uint32_t sampleRate,
2410 audio_channel_mask_t channelMask,
2411 audio_format_t format,
2412 size_t frameCount,
2413 void* buffer,
2414 size_t bufferSize,
2415 audio_output_flags_t flags,
2416 const Timeout& timeout,
2417 size_t frameCountToBeReady /** Default behaviour is to start
2418 * as soon as possible to have
2419 * the lowest possible latency
2420 * even if it might glitch. */)
2421{
2422 return sp<PatchTrack>::make(
2423 reinterpret_cast<AudioFlinger::PlaybackThread*>(playbackThread),
2424 streamType,
2425 sampleRate,
2426 channelMask,
2427 format,
2428 frameCount,
2429 buffer,
2430 bufferSize,
2431 flags,
2432 timeout,
2433 frameCountToBeReady);
2434}
2435
2436PatchTrack::PatchTrack(AudioFlinger::PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07002437 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07002438 uint32_t sampleRate,
2439 audio_channel_mask_t channelMask,
2440 audio_format_t format,
2441 size_t frameCount,
2442 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07002443 size_t bufferSize,
Kevin Rocard45986c72018-12-18 18:22:59 -08002444 audio_output_flags_t flags,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01002445 const Timeout& timeout,
2446 size_t frameCountToBeReady)
Eric Laurent3bcf8592015-04-03 12:13:24 -07002447 : Track(playbackThread, NULL, streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002448 audio_attributes_t{} /* currently unused for patch track */,
Eric Laurent223fd5c2014-11-11 13:43:36 -08002449 sampleRate, format, channelMask, frameCount,
Andy Hung8fe68032017-06-05 16:17:51 -07002450 buffer, bufferSize, nullptr /* sharedBuffer */,
Svet Ganov33761132021-05-13 22:51:08 +00002451 AUDIO_SESSION_NONE, getpid(), audioServerAttributionSource(getpid()), flags,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002452 TYPE_PATCH, AUDIO_PORT_HANDLE_NONE, frameCountToBeReady),
gaoxiupei8e3a5682023-07-07 20:30:23 +08002453 PatchTrackBase(mCblk ? new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true)
2454 : nullptr,
Kevin Rocard45986c72018-12-18 18:22:59 -08002455 *playbackThread, timeout)
Eric Laurent83b88082014-06-20 18:31:16 -07002456{
Andy Hung9d84af52018-09-12 18:03:44 -07002457 ALOGV("%s(%d): sampleRate %d mPeerTimeout %d.%03d sec",
2458 __func__, mId, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07002459 (int)mPeerTimeout.tv_sec,
2460 (int)(mPeerTimeout.tv_nsec / 1000000));
2461}
2462
Andy Hung11e74242023-06-26 19:20:57 -07002463PatchTrack::~PatchTrack()
Eric Laurent83b88082014-06-20 18:31:16 -07002464{
Andy Hungabfab202019-03-07 19:45:54 -08002465 ALOGV("%s(%d)", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002466}
2467
Andy Hung11e74242023-06-26 19:20:57 -07002468size_t PatchTrack::framesReady() const
Mikhail Naganovcaf59942019-09-25 14:05:29 -07002469{
2470 if (mPeerProxy && mPeerProxy->producesBufferOnDemand()) {
2471 return std::numeric_limits<size_t>::max();
2472 } else {
2473 return Track::framesReady();
2474 }
2475}
2476
Andy Hung11e74242023-06-26 19:20:57 -07002477status_t PatchTrack::start(AudioSystem::sync_event_t event,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002478 audio_session_t triggerSession)
Eric Laurent4d231dc2016-03-11 18:38:23 -08002479{
2480 status_t status = Track::start(event, triggerSession);
2481 if (status != NO_ERROR) {
2482 return status;
2483 }
2484 android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
2485 return status;
2486}
2487
Eric Laurent83b88082014-06-20 18:31:16 -07002488// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07002489status_t PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08002490 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07002491{
Andy Hung9d84af52018-09-12 18:03:44 -07002492 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002493 Proxy::Buffer buf;
2494 buf.mFrameCount = buffer->frameCount;
Mikhail Naganov938be412019-09-04 11:38:47 -07002495 if (ATRACE_ENABLED()) {
2496 std::string traceName("PTnReq");
2497 traceName += std::to_string(id());
2498 ATRACE_INT(traceName.c_str(), buf.mFrameCount);
2499 }
Eric Laurent83b88082014-06-20 18:31:16 -07002500 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
Andy Hung9d84af52018-09-12 18:03:44 -07002501 ALOGV_IF(status != NO_ERROR, "%s(%d): getNextBuffer status %d", __func__, mId, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002502 buffer->frameCount = buf.mFrameCount;
Mikhail Naganov938be412019-09-04 11:38:47 -07002503 if (ATRACE_ENABLED()) {
2504 std::string traceName("PTnObt");
2505 traceName += std::to_string(id());
2506 ATRACE_INT(traceName.c_str(), buf.mFrameCount);
2507 }
Eric Laurent83b88082014-06-20 18:31:16 -07002508 if (buf.mFrameCount == 0) {
2509 return WOULD_BLOCK;
2510 }
Glenn Kastend79072e2016-01-06 08:41:20 -08002511 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07002512 return status;
2513}
2514
Andy Hung11e74242023-06-26 19:20:57 -07002515void PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07002516{
Andy Hung9d84af52018-09-12 18:03:44 -07002517 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002518 Proxy::Buffer buf;
2519 buf.mFrameCount = buffer->frameCount;
2520 buf.mRaw = buffer->raw;
2521 mPeerProxy->releaseBuffer(&buf);
Andy Hung920f6572022-10-06 12:09:49 -07002522 TrackBase::releaseBuffer(buffer); // Note: this is the base class.
Eric Laurent83b88082014-06-20 18:31:16 -07002523}
2524
Andy Hung11e74242023-06-26 19:20:57 -07002525status_t PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
Eric Laurent83b88082014-06-20 18:31:16 -07002526 const struct timespec *timeOut)
2527{
Eric Laurent4d231dc2016-03-11 18:38:23 -08002528 status_t status = NO_ERROR;
2529 static const int32_t kMaxTries = 5;
2530 int32_t tryCounter = kMaxTries;
Andy Hungf62e1a22018-05-08 18:32:11 -07002531 const size_t originalFrameCount = buffer->mFrameCount;
Eric Laurent4d231dc2016-03-11 18:38:23 -08002532 do {
2533 if (status == NOT_ENOUGH_DATA) {
2534 restartIfDisabled();
Andy Hungf62e1a22018-05-08 18:32:11 -07002535 buffer->mFrameCount = originalFrameCount; // cleared on error, must be restored.
Eric Laurent4d231dc2016-03-11 18:38:23 -08002536 }
2537 status = mProxy->obtainBuffer(buffer, timeOut);
2538 } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
2539 return status;
Eric Laurent83b88082014-06-20 18:31:16 -07002540}
2541
Andy Hung11e74242023-06-26 19:20:57 -07002542void PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07002543{
2544 mProxy->releaseBuffer(buffer);
Eric Laurent4d231dc2016-03-11 18:38:23 -08002545 restartIfDisabled();
naoki miyazuf37f9982019-11-28 11:18:18 +09002546
2547 // Check if the PatchTrack has enough data to write once in releaseBuffer().
2548 // If not, prevent an underrun from occurring by moving the track into FS_FILLING;
2549 // this logic avoids glitches when suspending A2DP with AudioPlaybackCapture.
2550 // TODO: perhaps underrun avoidance could be a track property checked in isReady() instead.
Andy Hung11e74242023-06-26 19:20:57 -07002551 if (mFillingStatus == FS_ACTIVE
naoki miyazuf37f9982019-11-28 11:18:18 +09002552 && audio_is_linear_pcm(mFormat)
2553 && !isOffloadedOrDirect()) {
Andy Hung11e74242023-06-26 19:20:57 -07002554 if (sp<AudioFlinger::ThreadBase> thread = mThread.promote();
naoki miyazuf37f9982019-11-28 11:18:18 +09002555 thread != 0) {
Andy Hung11e74242023-06-26 19:20:57 -07002556 auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
naoki miyazuf37f9982019-11-28 11:18:18 +09002557 const size_t frameCount = playbackThread->frameCount() * sampleRate()
2558 / playbackThread->sampleRate();
2559 if (framesReady() < frameCount) {
2560 ALOGD("%s(%d) Not enough data, wait for buffer to fill", __func__, mId);
Andy Hung11e74242023-06-26 19:20:57 -07002561 mFillingStatus = FS_FILLING;
naoki miyazuf37f9982019-11-28 11:18:18 +09002562 }
2563 }
2564 }
Eric Laurent4d231dc2016-03-11 18:38:23 -08002565}
2566
Andy Hung11e74242023-06-26 19:20:57 -07002567void PatchTrack::restartIfDisabled()
Eric Laurent4d231dc2016-03-11 18:38:23 -08002568{
Eric Laurent83b88082014-06-20 18:31:16 -07002569 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
Andy Hung9d84af52018-09-12 18:03:44 -07002570 ALOGW("%s(%d): disabled due to previous underrun, restarting", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07002571 start();
2572 }
Eric Laurent83b88082014-06-20 18:31:16 -07002573}
2574
Eric Laurent81784c32012-11-19 14:55:58 -08002575// ----------------------------------------------------------------------------
2576// Record
2577// ----------------------------------------------------------------------------
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002578
2579
Andy Hung9d84af52018-09-12 18:03:44 -07002580#undef LOG_TAG
2581#define LOG_TAG "AF::RecordHandle"
Eric Laurent81784c32012-11-19 14:55:58 -08002582
Andy Hunga6426302023-06-23 19:27:19 -07002583class RecordHandle : public android::media::BnAudioRecord {
2584public:
Andy Hungfafbebc2023-06-23 19:27:19 -07002585 explicit RecordHandle(const sp<IAfRecordTrack>& recordTrack);
Andy Hunga6426302023-06-23 19:27:19 -07002586 ~RecordHandle() override;
2587 binder::Status start(int /*AudioSystem::sync_event_t*/ event,
2588 int /*audio_session_t*/ triggerSession) final;
2589 binder::Status stop() final;
2590 binder::Status getActiveMicrophones(
2591 std::vector<media::MicrophoneInfoFw>* activeMicrophones) final;
2592 binder::Status setPreferredMicrophoneDirection(
2593 int /*audio_microphone_direction_t*/ direction) final;
2594 binder::Status setPreferredMicrophoneFieldDimension(float zoom) final;
2595 binder::Status shareAudioHistory(
2596 const std::string& sharedAudioPackageName, int64_t sharedAudioStartMs) final;
2597
2598private:
Andy Hungfafbebc2023-06-23 19:27:19 -07002599 const sp<IAfRecordTrack> mRecordTrack;
Andy Hunga6426302023-06-23 19:27:19 -07002600
2601 // for use from destructor
2602 void stop_nonvirtual();
2603};
2604
2605/* static */
Andy Hungfafbebc2023-06-23 19:27:19 -07002606sp<media::IAudioRecord> IAfRecordTrack::createIAudioRecordAdapter(
2607 const sp<IAfRecordTrack>& recordTrack) {
Andy Hunga6426302023-06-23 19:27:19 -07002608 return sp<RecordHandle>::make(recordTrack);
2609}
2610
2611RecordHandle::RecordHandle(
Andy Hungfafbebc2023-06-23 19:27:19 -07002612 const sp<IAfRecordTrack>& recordTrack)
Eric Laurent81784c32012-11-19 14:55:58 -08002613 : BnAudioRecord(),
2614 mRecordTrack(recordTrack)
2615{
Andy Hunga6426302023-06-23 19:27:19 -07002616 // TODO(b/288339104) binder thread priority change not needed.
Andy Hung225aef62022-12-06 16:33:20 -08002617 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002618}
2619
Andy Hunga6426302023-06-23 19:27:19 -07002620RecordHandle::~RecordHandle() {
Eric Laurent81784c32012-11-19 14:55:58 -08002621 stop_nonvirtual();
2622 mRecordTrack->destroy();
2623}
2624
Andy Hunga6426302023-06-23 19:27:19 -07002625binder::Status RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
Ivan Lozanoff6900d2017-08-01 15:47:38 -07002626 int /*audio_session_t*/ triggerSession) {
Andy Hung9d84af52018-09-12 18:03:44 -07002627 ALOGV("%s()", __func__);
Andy Hung1131b6e2020-12-08 20:47:45 -08002628 return binderStatusFromStatusT(
Ivan Lozanoff6900d2017-08-01 15:47:38 -07002629 mRecordTrack->start((AudioSystem::sync_event_t)event, (audio_session_t) triggerSession));
Eric Laurent81784c32012-11-19 14:55:58 -08002630}
2631
Andy Hunga6426302023-06-23 19:27:19 -07002632binder::Status RecordHandle::stop() {
Eric Laurent81784c32012-11-19 14:55:58 -08002633 stop_nonvirtual();
Ivan Lozanoff6900d2017-08-01 15:47:38 -07002634 return binder::Status::ok();
Eric Laurent81784c32012-11-19 14:55:58 -08002635}
2636
Andy Hunga6426302023-06-23 19:27:19 -07002637void RecordHandle::stop_nonvirtual() {
Andy Hung9d84af52018-09-12 18:03:44 -07002638 ALOGV("%s()", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08002639 mRecordTrack->stop();
2640}
2641
Andy Hunga6426302023-06-23 19:27:19 -07002642binder::Status RecordHandle::getActiveMicrophones(
Mikhail Naganovd5d9de72023-02-13 11:45:03 -08002643 std::vector<media::MicrophoneInfoFw>* activeMicrophones) {
Andy Hung9d84af52018-09-12 18:03:44 -07002644 ALOGV("%s()", __func__);
Mikhail Naganovd5d9de72023-02-13 11:45:03 -08002645 return binderStatusFromStatusT(mRecordTrack->getActiveMicrophones(activeMicrophones));
jiabin653cc0a2018-01-17 17:54:10 -08002646}
2647
Andy Hunga6426302023-06-23 19:27:19 -07002648binder::Status RecordHandle::setPreferredMicrophoneDirection(
Paul McLean03a6e6a2018-12-04 10:54:13 -07002649 int /*audio_microphone_direction_t*/ direction) {
2650 ALOGV("%s()", __func__);
Andy Hung1131b6e2020-12-08 20:47:45 -08002651 return binderStatusFromStatusT(mRecordTrack->setPreferredMicrophoneDirection(
Paul McLean03a6e6a2018-12-04 10:54:13 -07002652 static_cast<audio_microphone_direction_t>(direction)));
2653}
2654
Andy Hunga6426302023-06-23 19:27:19 -07002655binder::Status RecordHandle::setPreferredMicrophoneFieldDimension(float zoom) {
Paul McLean03a6e6a2018-12-04 10:54:13 -07002656 ALOGV("%s()", __func__);
Andy Hung1131b6e2020-12-08 20:47:45 -08002657 return binderStatusFromStatusT(mRecordTrack->setPreferredMicrophoneFieldDimension(zoom));
Paul McLean03a6e6a2018-12-04 10:54:13 -07002658}
2659
Andy Hunga6426302023-06-23 19:27:19 -07002660binder::Status RecordHandle::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02002661 const std::string& sharedAudioPackageName, int64_t sharedAudioStartMs) {
2662 return binderStatusFromStatusT(
2663 mRecordTrack->shareAudioHistory(sharedAudioPackageName, sharedAudioStartMs));
2664}
2665
Eric Laurent81784c32012-11-19 14:55:58 -08002666// ----------------------------------------------------------------------------
Andy Hung9d84af52018-09-12 18:03:44 -07002667#undef LOG_TAG
2668#define LOG_TAG "AF::RecordTrack"
Eric Laurent81784c32012-11-19 14:55:58 -08002669
Andy Hung11e74242023-06-26 19:20:57 -07002670
2671/* static */ // TODO(b/288339104)
2672sp<IAfRecordTrack> IAfRecordTrack::create(void* /*AudioFlinger::RecordThread */ thread,
2673 const sp<Client>& client,
2674 const audio_attributes_t& attr,
2675 uint32_t sampleRate,
2676 audio_format_t format,
2677 audio_channel_mask_t channelMask,
2678 size_t frameCount,
2679 void* buffer,
2680 size_t bufferSize,
2681 audio_session_t sessionId,
2682 pid_t creatorPid,
2683 const AttributionSourceState& attributionSource,
2684 audio_input_flags_t flags,
2685 track_type type,
2686 audio_port_handle_t portId,
2687 int32_t startFrames)
2688{
2689 return sp<RecordTrack>::make(
2690 reinterpret_cast<AudioFlinger::RecordThread*>(thread),
2691 client,
2692 attr,
2693 sampleRate,
2694 format,
2695 channelMask,
2696 frameCount,
2697 buffer,
2698 bufferSize,
2699 sessionId,
2700 creatorPid,
2701 attributionSource,
2702 flags,
2703 type,
2704 portId,
2705 startFrames);
2706}
2707
Glenn Kasten05997e22014-03-13 15:08:33 -07002708// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Andy Hung11e74242023-06-26 19:20:57 -07002709RecordTrack::RecordTrack(
2710 AudioFlinger::RecordThread* thread,
Eric Laurent81784c32012-11-19 14:55:58 -08002711 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002712 const audio_attributes_t& attr,
Eric Laurent81784c32012-11-19 14:55:58 -08002713 uint32_t sampleRate,
2714 audio_format_t format,
2715 audio_channel_mask_t channelMask,
2716 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07002717 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07002718 size_t bufferSize,
Glenn Kastend848eb42016-03-08 13:42:11 -08002719 audio_session_t sessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002720 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002721 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07002722 audio_input_flags_t flags,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002723 track_type type,
Eric Laurentec376dc2021-04-08 20:41:22 +02002724 audio_port_handle_t portId,
Eric Laurent2407ce32021-04-26 14:56:03 +02002725 int32_t startFrames)
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002726 : TrackBase(thread, client, attr, sampleRate, format,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002727 channelMask, frameCount, buffer, bufferSize, sessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002728 creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002729 VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002730 false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07002731 (type == TYPE_DEFAULT) ?
Eric Laurent05067782016-06-01 18:27:28 -07002732 ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
Eric Laurent83b88082014-06-20 18:31:16 -07002733 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
Andy Hungb68f5eb2019-12-03 16:49:17 -08002734 type, portId,
2735 std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_RECORD) + std::to_string(portId)),
Andy Hung97a893e2015-03-29 01:03:07 -07002736 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07002737 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
Eric Laurent05067782016-06-01 18:27:28 -07002738 mRecordBufferConverter(NULL),
jiabin9378eb92018-05-02 15:26:35 -07002739 mFlags(flags),
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002740 mSilenced(false),
Eric Laurent2407ce32021-04-26 14:56:03 +02002741 mStartFrames(startFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002742{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07002743 if (mCblk == NULL) {
2744 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002745 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002746
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002747 if (!isDirect()) {
2748 mRecordBufferConverter = new RecordBufferConverter(
2749 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
2750 channelMask, format, sampleRate);
2751 // Check if the RecordBufferConverter construction was successful.
2752 // If not, don't continue with construction.
2753 //
2754 // NOTE: It would be extremely rare that the record track cannot be created
2755 // for the current device, but a pending or future device change would make
2756 // the record track configuration valid.
2757 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
Andy Hung9d84af52018-09-12 18:03:44 -07002758 ALOGE("%s(%d): RecordTrack unable to create record buffer converter", __func__, mId);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002759 return;
2760 }
Andy Hung97a893e2015-03-29 01:03:07 -07002761 }
2762
Andy Hung6ae58432016-02-16 18:32:24 -08002763 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
Andy Hung3f0c9022016-01-15 17:49:46 -08002764 mFrameSize, !isExternalTrack());
Andy Hung3f0c9022016-01-15 17:49:46 -08002765
Andy Hung97a893e2015-03-29 01:03:07 -07002766 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07002767
Eric Laurent05067782016-06-01 18:27:28 -07002768 if (flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kastenc263ca02014-06-04 20:31:46 -07002769 ALOG_ASSERT(thread->mFastTrackAvail);
2770 thread->mFastTrackAvail = false;
Andy Hung000adb52018-06-01 15:43:26 -07002771 } else {
2772 // TODO: only Normal Record has timestamps (Fast Record does not).
Andy Hung5d3d9562018-10-04 19:27:26 -07002773 mServerLatencySupported = checkServerLatencySupported(mFormat, flags);
Glenn Kastenc263ca02014-06-04 20:31:46 -07002774 }
Andy Hung8946a282018-04-19 20:04:56 -07002775#ifdef TEE_SINK
2776 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle)
2777 + "_" + std::to_string(mId)
2778 + "_R");
2779#endif
Andy Hungb68f5eb2019-12-03 16:49:17 -08002780
2781 // Once this item is logged by the server, the client can add properties.
Andy Hung94235282021-03-24 15:50:14 -07002782 mTrackMetrics.logConstructor(creatorPid, uid(), id());
Eric Laurent81784c32012-11-19 14:55:58 -08002783}
2784
Andy Hung11e74242023-06-26 19:20:57 -07002785RecordTrack::~RecordTrack()
Eric Laurent81784c32012-11-19 14:55:58 -08002786{
Andy Hung9d84af52018-09-12 18:03:44 -07002787 ALOGV("%s()", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07002788 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002789 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08002790}
2791
Andy Hung11e74242023-06-26 19:20:57 -07002792status_t RecordTrack::initCheck() const
Andy Hung97a893e2015-03-29 01:03:07 -07002793{
2794 status_t status = TrackBase::initCheck();
2795 if (status == NO_ERROR && mServerProxy == 0) {
2796 status = BAD_VALUE;
2797 }
2798 return status;
2799}
2800
Eric Laurent81784c32012-11-19 14:55:58 -08002801// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07002802status_t RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08002803{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002804 ServerProxy::Buffer buf;
2805 buf.mFrameCount = buffer->frameCount;
2806 status_t status = mServerProxy->obtainBuffer(&buf);
2807 buffer->frameCount = buf.mFrameCount;
2808 buffer->raw = buf.mRaw;
2809 if (buf.mFrameCount == 0) {
2810 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002811 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002812 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002813 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002814}
2815
Andy Hung11e74242023-06-26 19:20:57 -07002816status_t RecordTrack::start(AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08002817 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08002818{
Andy Hung11e74242023-06-26 19:20:57 -07002819 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002820 if (thread != 0) {
Andy Hung11e74242023-06-26 19:20:57 -07002821 auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
Eric Laurent81784c32012-11-19 14:55:58 -08002822 return recordThread->start(this, event, triggerSession);
2823 } else {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002824 ALOGW("%s track %d: thread was destroyed", __func__, portId());
2825 return DEAD_OBJECT;
Eric Laurent81784c32012-11-19 14:55:58 -08002826 }
2827}
2828
Andy Hung11e74242023-06-26 19:20:57 -07002829void RecordTrack::stop()
Eric Laurent81784c32012-11-19 14:55:58 -08002830{
Andy Hung11e74242023-06-26 19:20:57 -07002831 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002832 if (thread != 0) {
Andy Hung11e74242023-06-26 19:20:57 -07002833 auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002834 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08002835 AudioSystem::stopInput(mPortId);
Eric Laurent81784c32012-11-19 14:55:58 -08002836 }
2837 }
2838}
2839
Andy Hung11e74242023-06-26 19:20:57 -07002840void RecordTrack::destroy()
Eric Laurent81784c32012-11-19 14:55:58 -08002841{
Andy Hung11e74242023-06-26 19:20:57 -07002842 // see comments at Track::destroy()
Eric Laurent81784c32012-11-19 14:55:58 -08002843 sp<RecordTrack> keep(this);
2844 {
Andy Hungce685402018-10-05 17:23:27 -07002845 track_state priorState = mState;
Andy Hung11e74242023-06-26 19:20:57 -07002846 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002847 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002848 Mutex::Autolock _l(thread->mLock);
Andy Hung11e74242023-06-26 19:20:57 -07002849 auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
Andy Hungce685402018-10-05 17:23:27 -07002850 priorState = mState;
Eric Laurentec376dc2021-04-08 20:41:22 +02002851 if (!mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02002852 recordThread->resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02002853 }
Andy Hungce685402018-10-05 17:23:27 -07002854 recordThread->destroyTrack_l(this); // move mState to STOPPED, terminate
2855 }
2856 // APM portid/client management done outside of lock.
2857 // NOTE: if thread doesn't exist, the input descriptor probably doesn't either.
2858 if (isExternalTrack()) {
2859 switch (priorState) {
2860 case ACTIVE: // invalidated while still active
2861 case STARTING_2: // invalidated/start-aborted after startInput successfully called
2862 case PAUSING: // invalidated while in the middle of stop() pausing (still active)
2863 AudioSystem::stopInput(mPortId);
2864 break;
2865
2866 case STARTING_1: // invalidated/start-aborted and startInput not successful
2867 case PAUSED: // OK, not active
2868 case IDLE: // OK, not active
2869 break;
2870
2871 case STOPPED: // unexpected (destroyed)
2872 default:
2873 LOG_ALWAYS_FATAL("%s(%d): invalid prior state: %d", __func__, mId, priorState);
2874 }
2875 AudioSystem::releaseInput(mPortId);
Eric Laurent81784c32012-11-19 14:55:58 -08002876 }
2877 }
2878}
2879
Andy Hung11e74242023-06-26 19:20:57 -07002880void RecordTrack::invalidate()
Eric Laurent9a54bc22013-09-09 09:08:44 -07002881{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002882 TrackBase::invalidate();
Eric Laurent9a54bc22013-09-09 09:08:44 -07002883 // FIXME should use proxy, and needs work
2884 audio_track_cblk_t* cblk = mCblk;
2885 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2886 android_atomic_release_store(0x40000000, &cblk->mFutex);
2887 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002888 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002889}
2890
Eric Laurent81784c32012-11-19 14:55:58 -08002891
Andy Hung11e74242023-06-26 19:20:57 -07002892void RecordTrack::appendDumpHeader(String8& result) const
Eric Laurent81784c32012-11-19 14:55:58 -08002893{
Eric Laurent973db022018-11-20 14:54:31 -08002894 result.appendFormat("Active Id Client Session Port Id S Flags "
Andy Hung9d84af52018-09-12 18:03:44 -07002895 " Format Chn mask SRate Source "
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002896 " Server FrmCnt FrmRdy Sil%s\n",
2897 isServerLatencySupported() ? " Latency" : "");
Eric Laurent81784c32012-11-19 14:55:58 -08002898}
2899
Andy Hung11e74242023-06-26 19:20:57 -07002900void RecordTrack::appendDump(String8& result, bool active) const
Eric Laurent81784c32012-11-19 14:55:58 -08002901{
Eric Laurent973db022018-11-20 14:54:31 -08002902 result.appendFormat("%c%5s %6d %6u %7u %7u %2s 0x%03X "
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002903 "%08X %08X %6u %6X "
Andy Hung000adb52018-06-01 15:43:26 -07002904 "%08X %6zu %6zu %3c",
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002905 isFastTrack() ? 'F' : ' ',
Marco Nelissenb2208842014-02-07 14:00:50 -08002906 active ? "yes" : "no",
Andy Hung9d84af52018-09-12 18:03:44 -07002907 mId,
Andy Hung4ef19fa2018-05-15 19:35:29 -07002908 (mClient == 0) ? getpid() : mClient->pid(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002909 mSessionId,
Eric Laurent973db022018-11-20 14:54:31 -08002910 mPortId,
Andy Hunge2e830f2019-12-03 12:54:46 -08002911 getTrackStateAsCodedString(),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002912 mCblk->mFlags,
2913
Eric Laurent81784c32012-11-19 14:55:58 -08002914 mFormat,
2915 mChannelMask,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002916 mSampleRate,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07002917 mAttr.source,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002918
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002919 mCblk->mServer,
Jean-Michel Trivi7d665ab2018-04-11 17:26:51 -07002920 mFrameCount,
Andy Hung000adb52018-06-01 15:43:26 -07002921 mServerProxy->framesReadySafe(),
Jean-Michel Trivi7d665ab2018-04-11 17:26:51 -07002922 isSilenced() ? 's' : 'n'
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002923 );
Andy Hung000adb52018-06-01 15:43:26 -07002924 if (isServerLatencySupported()) {
2925 double latencyMs;
2926 bool fromTrack;
2927 if (getTrackLatencyMs(&latencyMs, &fromTrack) == OK) {
2928 // Show latency in msec, followed by 't' if from track timestamp (the most accurate)
2929 // or 'k' if estimated from kernel (usually for debugging).
2930 result.appendFormat(" %7.2lf %c", latencyMs, fromTrack ? 't' : 'k');
2931 } else {
2932 result.appendFormat("%10s", mCblk->mServer != 0 ? "unavail" : "new");
2933 }
2934 }
2935 result.append("\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002936}
2937
Andy Hung93bb5732023-05-04 21:16:34 -07002938// This is invoked by SyncEvent callback.
Andy Hung11e74242023-06-26 19:20:57 -07002939void RecordTrack::handleSyncStartEvent(
Andy Hung068e08e2023-05-15 19:02:55 -07002940 const sp<audioflinger::SyncEvent>& event)
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002941{
Andy Hung93bb5732023-05-04 21:16:34 -07002942 size_t framesToDrop = 0;
Andy Hung11e74242023-06-26 19:20:57 -07002943 sp<AudioFlinger::ThreadBase> threadBase = mThread.promote();
Andy Hung93bb5732023-05-04 21:16:34 -07002944 if (threadBase != 0) {
2945 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2946 // from audio HAL
2947 framesToDrop = threadBase->mFrameCount * 2;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002948 }
Andy Hung93bb5732023-05-04 21:16:34 -07002949
2950 mSynchronizedRecordState.onPlaybackFinished(event, framesToDrop);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002951}
2952
Andy Hung11e74242023-06-26 19:20:57 -07002953void RecordTrack::clearSyncStartEvent()
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002954{
Andy Hung93bb5732023-05-04 21:16:34 -07002955 mSynchronizedRecordState.clear();
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002956}
2957
Andy Hung11e74242023-06-26 19:20:57 -07002958void RecordTrack::updateTrackFrameInfo(
Andy Hung3f0c9022016-01-15 17:49:46 -08002959 int64_t trackFramesReleased, int64_t sourceFramesRead,
2960 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
2961{
Andy Hung30282562018-08-08 18:27:03 -07002962 // Make the kernel frametime available.
2963 const FrameTime ft{
2964 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
2965 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]};
2966 // ALOGD("FrameTime: %lld %lld", (long long)ft.frames, (long long)ft.timeNs);
2967 mKernelFrameTime.store(ft);
2968 if (!audio_is_linear_pcm(mFormat)) {
Atneya Nair497fff12022-01-18 16:23:04 -05002969 // Stream is direct, return provided timestamp with no conversion
2970 mServerProxy->setTimestamp(timestamp);
Andy Hung30282562018-08-08 18:27:03 -07002971 return;
2972 }
2973
Andy Hung3f0c9022016-01-15 17:49:46 -08002974 ExtendedTimestamp local = timestamp;
2975
2976 // Convert HAL frames to server-side track frames at track sample rate.
2977 // We use trackFramesReleased and sourceFramesRead as an anchor point.
2978 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2979 if (local.mTimeNs[i] != 0) {
2980 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
2981 const int64_t relativeTrackFrames = relativeServerFrames
2982 * mSampleRate / halSampleRate; // TODO: potential computation overflow
2983 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
2984 }
2985 }
Andy Hung6ae58432016-02-16 18:32:24 -08002986 mServerProxy->setTimestamp(local);
Andy Hung000adb52018-06-01 15:43:26 -07002987
2988 // Compute latency info.
2989 const bool useTrackTimestamp = true; // use track unless debugging.
2990 const double latencyMs = - (useTrackTimestamp
2991 ? local.getOutputServerLatencyMs(sampleRate())
2992 : timestamp.getOutputServerLatencyMs(halSampleRate));
2993
2994 mServerLatencyFromTrack.store(useTrackTimestamp);
2995 mServerLatencyMs.store(latencyMs);
Andy Hung3f0c9022016-01-15 17:49:46 -08002996}
Eric Laurent83b88082014-06-20 18:31:16 -07002997
Andy Hung11e74242023-06-26 19:20:57 -07002998status_t RecordTrack::getActiveMicrophones(
Andy Hungfafbebc2023-06-23 19:27:19 -07002999 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08003000{
Andy Hung11e74242023-06-26 19:20:57 -07003001 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
jiabin653cc0a2018-01-17 17:54:10 -08003002 if (thread != 0) {
Andy Hung11e74242023-06-26 19:20:57 -07003003 auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
jiabin653cc0a2018-01-17 17:54:10 -08003004 return recordThread->getActiveMicrophones(activeMicrophones);
3005 } else {
3006 return BAD_VALUE;
3007 }
3008}
3009
Andy Hung11e74242023-06-26 19:20:57 -07003010status_t RecordTrack::setPreferredMicrophoneDirection(
Paul McLean03a6e6a2018-12-04 10:54:13 -07003011 audio_microphone_direction_t direction) {
Andy Hung11e74242023-06-26 19:20:57 -07003012 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Paul McLean03a6e6a2018-12-04 10:54:13 -07003013 if (thread != 0) {
Andy Hung11e74242023-06-26 19:20:57 -07003014 auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
Paul McLean12340082019-03-19 09:35:05 -06003015 return recordThread->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07003016 } else {
3017 return BAD_VALUE;
3018 }
3019}
3020
Andy Hung11e74242023-06-26 19:20:57 -07003021status_t RecordTrack::setPreferredMicrophoneFieldDimension(float zoom) {
3022 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Paul McLean03a6e6a2018-12-04 10:54:13 -07003023 if (thread != 0) {
Andy Hung11e74242023-06-26 19:20:57 -07003024 auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
Paul McLean12340082019-03-19 09:35:05 -06003025 return recordThread->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07003026 } else {
3027 return BAD_VALUE;
3028 }
3029}
3030
Andy Hung11e74242023-06-26 19:20:57 -07003031status_t RecordTrack::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02003032 const std::string& sharedAudioPackageName, int64_t sharedAudioStartMs) {
3033
3034 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
3035 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3036 if (callingUid != mUid || callingPid != mCreatorPid) {
3037 return PERMISSION_DENIED;
3038 }
3039
Svet Ganov33761132021-05-13 22:51:08 +00003040 AttributionSourceState attributionSource{};
3041 attributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
3042 attributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingPid));
3043 attributionSource.token = sp<BBinder>::make();
3044 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02003045 return PERMISSION_DENIED;
3046 }
3047
Andy Hung11e74242023-06-26 19:20:57 -07003048 sp<AudioFlinger::ThreadBase> thread = mThread.promote();
Eric Laurentec376dc2021-04-08 20:41:22 +02003049 if (thread != 0) {
Andy Hung11e74242023-06-26 19:20:57 -07003050 auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
Eric Laurentec376dc2021-04-08 20:41:22 +02003051 status_t status = recordThread->shareAudioHistory(
3052 sharedAudioPackageName, mSessionId, sharedAudioStartMs);
3053 if (status == NO_ERROR) {
3054 mSharedAudioPackageName = sharedAudioPackageName;
3055 }
3056 return status;
3057 } else {
3058 return BAD_VALUE;
3059 }
3060}
3061
Andy Hung11e74242023-06-26 19:20:57 -07003062void RecordTrack::copyMetadataTo(MetadataInserter& backInserter) const
Eric Laurent78b07302022-10-07 16:20:34 +02003063{
3064
3065 // Do not forward PatchRecord metadata with unspecified audio source
3066 if (mAttr.source == AUDIO_SOURCE_DEFAULT) {
3067 return;
3068 }
3069
3070 // No track is invalid as this is called after prepareTrack_l in the same critical section
3071 record_track_metadata_v7_t metadata;
3072 metadata.base = {
3073 .source = mAttr.source,
3074 .gain = 1, // capture tracks do not have volumes
3075 };
3076 metadata.channel_mask = mChannelMask;
3077 strncpy(metadata.tags, mAttr.tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
3078
3079 *backInserter++ = metadata;
3080}
Eric Laurentec376dc2021-04-08 20:41:22 +02003081
Andy Hung9d84af52018-09-12 18:03:44 -07003082// ----------------------------------------------------------------------------
3083#undef LOG_TAG
3084#define LOG_TAG "AF::PatchRecord"
3085
Andy Hung11e74242023-06-26 19:20:57 -07003086/* static */
3087sp<IAfPatchRecord> IAfPatchRecord::create(
3088 void* /* RecordThread */ recordThread, // TODO(b/288339104)
3089 uint32_t sampleRate,
3090 audio_channel_mask_t channelMask,
3091 audio_format_t format,
3092 size_t frameCount,
3093 void *buffer,
3094 size_t bufferSize,
3095 audio_input_flags_t flags,
3096 const Timeout& timeout,
3097 audio_source_t source)
3098{
3099 return sp<PatchRecord>::make(
3100 reinterpret_cast<AudioFlinger::RecordThread*>(recordThread),
3101 sampleRate,
3102 channelMask,
3103 format,
3104 frameCount,
3105 buffer,
3106 bufferSize,
3107 flags,
3108 timeout,
3109 source);
3110}
3111
3112PatchRecord::PatchRecord(AudioFlinger::RecordThread *recordThread,
Eric Laurent83b88082014-06-20 18:31:16 -07003113 uint32_t sampleRate,
3114 audio_channel_mask_t channelMask,
3115 audio_format_t format,
3116 size_t frameCount,
3117 void *buffer,
Andy Hung8fe68032017-06-05 16:17:51 -07003118 size_t bufferSize,
Kevin Rocard45986c72018-12-18 18:22:59 -08003119 audio_input_flags_t flags,
Eric Laurent78b07302022-10-07 16:20:34 +02003120 const Timeout& timeout,
3121 audio_source_t source)
Kevin Rocard1f564ac2018-03-29 13:53:10 -07003122 : RecordTrack(recordThread, NULL,
Eric Laurent78b07302022-10-07 16:20:34 +02003123 audio_attributes_t{ .source = source } ,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07003124 sampleRate, format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003125 buffer, bufferSize, AUDIO_SESSION_NONE, getpid(),
Svet Ganov33761132021-05-13 22:51:08 +00003126 audioServerAttributionSource(getpid()), flags, TYPE_PATCH),
gaoxiupei8e3a5682023-07-07 20:30:23 +08003127 PatchTrackBase(mCblk ? new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true)
3128 : nullptr,
Kevin Rocard45986c72018-12-18 18:22:59 -08003129 *recordThread, timeout)
Eric Laurent83b88082014-06-20 18:31:16 -07003130{
Andy Hung9d84af52018-09-12 18:03:44 -07003131 ALOGV("%s(%d): sampleRate %d mPeerTimeout %d.%03d sec",
3132 __func__, mId, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07003133 (int)mPeerTimeout.tv_sec,
3134 (int)(mPeerTimeout.tv_nsec / 1000000));
3135}
3136
Andy Hung11e74242023-06-26 19:20:57 -07003137PatchRecord::~PatchRecord()
Eric Laurent83b88082014-06-20 18:31:16 -07003138{
Andy Hungabfab202019-03-07 19:45:54 -08003139 ALOGV("%s(%d)", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07003140}
3141
Mikhail Naganov8296c252019-09-25 14:59:54 -07003142static size_t writeFramesHelper(
3143 AudioBufferProvider* dest, const void* src, size_t frameCount, size_t frameSize)
3144{
3145 AudioBufferProvider::Buffer patchBuffer;
3146 patchBuffer.frameCount = frameCount;
3147 auto status = dest->getNextBuffer(&patchBuffer);
3148 if (status != NO_ERROR) {
3149 ALOGW("%s PathRecord getNextBuffer failed with error %d: %s",
3150 __func__, status, strerror(-status));
3151 return 0;
3152 }
3153 ALOG_ASSERT(patchBuffer.frameCount <= frameCount);
3154 memcpy(patchBuffer.raw, src, patchBuffer.frameCount * frameSize);
3155 size_t framesWritten = patchBuffer.frameCount;
3156 dest->releaseBuffer(&patchBuffer);
3157 return framesWritten;
3158}
3159
3160// static
Andy Hung11e74242023-06-26 19:20:57 -07003161size_t PatchRecord::writeFrames(
Mikhail Naganov8296c252019-09-25 14:59:54 -07003162 AudioBufferProvider* dest, const void* src, size_t frameCount, size_t frameSize)
3163{
3164 size_t framesWritten = writeFramesHelper(dest, src, frameCount, frameSize);
3165 // On buffer wrap, the buffer frame count will be less than requested,
3166 // when this happens a second buffer needs to be used to write the leftover audio
3167 const size_t framesLeft = frameCount - framesWritten;
3168 if (framesWritten != 0 && framesLeft != 0) {
3169 framesWritten += writeFramesHelper(dest, (const char*)src + framesWritten * frameSize,
3170 framesLeft, frameSize);
3171 }
3172 return framesWritten;
3173}
3174
Eric Laurent83b88082014-06-20 18:31:16 -07003175// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07003176status_t PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08003177 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07003178{
Andy Hung9d84af52018-09-12 18:03:44 -07003179 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07003180 Proxy::Buffer buf;
3181 buf.mFrameCount = buffer->frameCount;
3182 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
3183 ALOGV_IF(status != NO_ERROR,
Andy Hung9d84af52018-09-12 18:03:44 -07003184 "%s(%d): mPeerProxy->obtainBuffer status %d", __func__, mId, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07003185 buffer->frameCount = buf.mFrameCount;
Mikhail Naganov938be412019-09-04 11:38:47 -07003186 if (ATRACE_ENABLED()) {
3187 std::string traceName("PRnObt");
3188 traceName += std::to_string(id());
3189 ATRACE_INT(traceName.c_str(), buf.mFrameCount);
3190 }
Eric Laurent83b88082014-06-20 18:31:16 -07003191 if (buf.mFrameCount == 0) {
3192 return WOULD_BLOCK;
3193 }
Glenn Kastend79072e2016-01-06 08:41:20 -08003194 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07003195 return status;
3196}
3197
Andy Hung11e74242023-06-26 19:20:57 -07003198void PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07003199{
Andy Hung9d84af52018-09-12 18:03:44 -07003200 ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
Eric Laurent83b88082014-06-20 18:31:16 -07003201 Proxy::Buffer buf;
3202 buf.mFrameCount = buffer->frameCount;
3203 buf.mRaw = buffer->raw;
3204 mPeerProxy->releaseBuffer(&buf);
3205 TrackBase::releaseBuffer(buffer);
3206}
3207
Andy Hung11e74242023-06-26 19:20:57 -07003208status_t PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
Eric Laurent83b88082014-06-20 18:31:16 -07003209 const struct timespec *timeOut)
3210{
3211 return mProxy->obtainBuffer(buffer, timeOut);
3212}
3213
Andy Hung11e74242023-06-26 19:20:57 -07003214void PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07003215{
3216 mProxy->releaseBuffer(buffer);
3217}
3218
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003219#undef LOG_TAG
3220#define LOG_TAG "AF::PthrPatchRecord"
3221
3222static std::unique_ptr<void, decltype(free)*> allocAligned(size_t alignment, size_t size)
3223{
3224 void *ptr = nullptr;
3225 (void)posix_memalign(&ptr, alignment, size);
Andy Hung920f6572022-10-06 12:09:49 -07003226 return {ptr, free};
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003227}
3228
Andy Hung11e74242023-06-26 19:20:57 -07003229/* static */
3230sp<IAfPatchRecord> IAfPatchRecord::createPassThru(
3231 void* /* RecordThread */ recordThread, // TODO(b/288339104)
3232 uint32_t sampleRate,
3233 audio_channel_mask_t channelMask,
3234 audio_format_t format,
3235 size_t frameCount,
3236 audio_input_flags_t flags,
3237 audio_source_t source)
3238{
3239 return sp<PassthruPatchRecord>::make(
3240 reinterpret_cast<AudioFlinger::RecordThread*>(recordThread),
3241 sampleRate,
3242 channelMask,
3243 format,
3244 frameCount,
3245 flags,
3246 source);
3247}
3248
3249PassthruPatchRecord::PassthruPatchRecord(
3250 AudioFlinger::RecordThread* recordThread,
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003251 uint32_t sampleRate,
3252 audio_channel_mask_t channelMask,
3253 audio_format_t format,
3254 size_t frameCount,
Eric Laurent78b07302022-10-07 16:20:34 +02003255 audio_input_flags_t flags,
3256 audio_source_t source)
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003257 : PatchRecord(recordThread, sampleRate, channelMask, format, frameCount,
Eric Laurent78b07302022-10-07 16:20:34 +02003258 nullptr /*buffer*/, 0 /*bufferSize*/, flags, {} /* timeout */, source),
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003259 mPatchRecordAudioBufferProvider(*this),
3260 mSinkBuffer(allocAligned(32, mFrameCount * mFrameSize)),
3261 mStubBuffer(allocAligned(32, mFrameCount * mFrameSize))
3262{
3263 memset(mStubBuffer.get(), 0, mFrameCount * mFrameSize);
3264}
3265
Andy Hung11e74242023-06-26 19:20:57 -07003266sp<StreamInHalInterface> PassthruPatchRecord::obtainStream(
3267 sp<AudioFlinger::ThreadBase>* thread)
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003268{
3269 *thread = mThread.promote();
3270 if (!*thread) return nullptr;
Andy Hung11e74242023-06-26 19:20:57 -07003271 auto* const recordThread = static_cast<AudioFlinger::RecordThread*>((*thread).get());
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003272 Mutex::Autolock _l(recordThread->mLock);
3273 return recordThread->mInput ? recordThread->mInput->stream : nullptr;
3274}
3275
3276// PatchProxyBufferProvider methods are called on DirectOutputThread
Andy Hung11e74242023-06-26 19:20:57 -07003277status_t PassthruPatchRecord::obtainBuffer(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003278 Proxy::Buffer* buffer, const struct timespec* timeOut)
3279{
3280 if (mUnconsumedFrames) {
3281 buffer->mFrameCount = std::min(buffer->mFrameCount, mUnconsumedFrames);
3282 // mUnconsumedFrames is decreased in releaseBuffer to use actual frame consumption figure.
3283 return PatchRecord::obtainBuffer(buffer, timeOut);
3284 }
3285
3286 // Otherwise, execute a read from HAL and write into the buffer.
3287 nsecs_t startTimeNs = 0;
3288 if (timeOut && (timeOut->tv_sec != 0 || timeOut->tv_nsec != 0) && timeOut->tv_sec != INT_MAX) {
3289 // Will need to correct timeOut by elapsed time.
3290 startTimeNs = systemTime();
3291 }
3292 const size_t framesToRead = std::min(buffer->mFrameCount, mFrameCount);
3293 buffer->mFrameCount = 0;
3294 buffer->mRaw = nullptr;
Andy Hung11e74242023-06-26 19:20:57 -07003295 sp<AudioFlinger::ThreadBase> thread;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003296 sp<StreamInHalInterface> stream = obtainStream(&thread);
3297 if (!stream) return NO_INIT; // If there is no stream, RecordThread is not reading.
3298
3299 status_t result = NO_ERROR;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003300 size_t bytesRead = 0;
3301 {
3302 ATRACE_NAME("read");
3303 result = stream->read(mSinkBuffer.get(), framesToRead * mFrameSize, &bytesRead);
3304 if (result != NO_ERROR) goto stream_error;
3305 if (bytesRead == 0) return NO_ERROR;
3306 }
3307
3308 {
3309 std::lock_guard<std::mutex> lock(mReadLock);
3310 mReadBytes += bytesRead;
3311 mReadError = NO_ERROR;
3312 }
3313 mReadCV.notify_one();
3314 // writeFrames handles wraparound and should write all the provided frames.
3315 // If it couldn't, there is something wrong with the client/server buffer of the software patch.
3316 buffer->mFrameCount = writeFrames(
3317 &mPatchRecordAudioBufferProvider,
3318 mSinkBuffer.get(), bytesRead / mFrameSize, mFrameSize);
3319 ALOGW_IF(buffer->mFrameCount < bytesRead / mFrameSize,
3320 "Lost %zu frames obtained from HAL", bytesRead / mFrameSize - buffer->mFrameCount);
3321 mUnconsumedFrames = buffer->mFrameCount;
Mikhail Naganov4de49972019-10-07 09:53:58 -07003322 struct timespec newTimeOut;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003323 if (startTimeNs) {
Mikhail Naganov4de49972019-10-07 09:53:58 -07003324 // Correct the timeout by elapsed time.
3325 nsecs_t newTimeOutNs = audio_utils_ns_from_timespec(timeOut) - (systemTime() - startTimeNs);
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003326 if (newTimeOutNs < 0) newTimeOutNs = 0;
3327 newTimeOut.tv_sec = newTimeOutNs / NANOS_PER_SECOND;
3328 newTimeOut.tv_nsec = newTimeOutNs - newTimeOut.tv_sec * NANOS_PER_SECOND;
Mikhail Naganov4de49972019-10-07 09:53:58 -07003329 timeOut = &newTimeOut;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003330 }
Mikhail Naganov4de49972019-10-07 09:53:58 -07003331 return PatchRecord::obtainBuffer(buffer, timeOut);
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003332
3333stream_error:
3334 stream->standby();
3335 {
3336 std::lock_guard<std::mutex> lock(mReadLock);
3337 mReadError = result;
3338 }
3339 mReadCV.notify_one();
3340 return result;
3341}
3342
Andy Hung11e74242023-06-26 19:20:57 -07003343void PassthruPatchRecord::releaseBuffer(Proxy::Buffer* buffer)
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003344{
3345 if (buffer->mFrameCount <= mUnconsumedFrames) {
3346 mUnconsumedFrames -= buffer->mFrameCount;
3347 } else {
3348 ALOGW("Write side has consumed more frames than we had: %zu > %zu",
3349 buffer->mFrameCount, mUnconsumedFrames);
3350 mUnconsumedFrames = 0;
3351 }
3352 PatchRecord::releaseBuffer(buffer);
3353}
3354
3355// AudioBufferProvider and Source methods are called on RecordThread
3356// 'read' emulates actual audio data with 0's. This is OK as 'getNextBuffer'
3357// and 'releaseBuffer' are stubbed out and ignore their input.
3358// It's not possible to retrieve actual data here w/o blocking 'obtainBuffer'
3359// until we copy it.
Andy Hung11e74242023-06-26 19:20:57 -07003360status_t PassthruPatchRecord::read(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003361 void* buffer, size_t bytes, size_t* read)
3362{
3363 bytes = std::min(bytes, mFrameCount * mFrameSize);
3364 {
3365 std::unique_lock<std::mutex> lock(mReadLock);
3366 mReadCV.wait(lock, [&]{ return mReadError != NO_ERROR || mReadBytes != 0; });
3367 if (mReadError != NO_ERROR) {
3368 mLastReadFrames = 0;
3369 return mReadError;
3370 }
3371 *read = std::min(bytes, mReadBytes);
3372 mReadBytes -= *read;
3373 }
3374 mLastReadFrames = *read / mFrameSize;
3375 memset(buffer, 0, *read);
3376 return 0;
3377}
3378
Andy Hung11e74242023-06-26 19:20:57 -07003379status_t PassthruPatchRecord::getCapturePosition(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003380 int64_t* frames, int64_t* time)
3381{
Andy Hung11e74242023-06-26 19:20:57 -07003382 sp<AudioFlinger::ThreadBase> thread;
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003383 sp<StreamInHalInterface> stream = obtainStream(&thread);
3384 return stream ? stream->getCapturePosition(frames, time) : NO_INIT;
3385}
3386
Andy Hung11e74242023-06-26 19:20:57 -07003387status_t PassthruPatchRecord::standby()
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003388{
3389 // RecordThread issues 'standby' command in two major cases:
3390 // 1. Error on read--this case is handled in 'obtainBuffer'.
3391 // 2. Track is stopping--as PassthruPatchRecord assumes continuous
3392 // output, this can only happen when the software patch
3393 // is being torn down. In this case, the RecordThread
3394 // will terminate and close the HAL stream.
3395 return 0;
3396}
3397
3398// As the buffer gets filled in obtainBuffer, here we only simulate data consumption.
Andy Hung11e74242023-06-26 19:20:57 -07003399status_t PassthruPatchRecord::getNextBuffer(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003400 AudioBufferProvider::Buffer* buffer)
3401{
3402 buffer->frameCount = mLastReadFrames;
3403 buffer->raw = buffer->frameCount != 0 ? mStubBuffer.get() : nullptr;
3404 return NO_ERROR;
3405}
3406
Andy Hung11e74242023-06-26 19:20:57 -07003407void PassthruPatchRecord::releaseBuffer(
Mikhail Naganovcaf59942019-09-25 14:05:29 -07003408 AudioBufferProvider::Buffer* buffer)
3409{
3410 buffer->frameCount = 0;
3411 buffer->raw = nullptr;
3412}
3413
Andy Hung9d84af52018-09-12 18:03:44 -07003414// ----------------------------------------------------------------------------
3415#undef LOG_TAG
3416#define LOG_TAG "AF::MmapTrack"
Eric Laurent6acd1d42017-01-04 14:23:29 -08003417
Andy Hung11e74242023-06-26 19:20:57 -07003418/* static */
3419sp<IAfMmapTrack> IAfMmapTrack::create(void* /* AudioFlinger::ThreadBase */ thread,
3420 const audio_attributes_t& attr,
3421 uint32_t sampleRate,
3422 audio_format_t format,
3423 audio_channel_mask_t channelMask,
3424 audio_session_t sessionId,
3425 bool isOut,
3426 const android::content::AttributionSourceState& attributionSource,
3427 pid_t creatorPid,
3428 audio_port_handle_t portId)
3429{
3430 return sp<MmapTrack>::make(
3431 reinterpret_cast<AudioFlinger::ThreadBase*>(thread),
3432 attr,
3433 sampleRate,
3434 format,
3435 channelMask,
3436 sessionId,
3437 isOut,
3438 attributionSource,
3439 creatorPid,
3440 portId);
3441}
3442
3443MmapTrack::MmapTrack(AudioFlinger::ThreadBase* thread,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07003444 const audio_attributes_t& attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08003445 uint32_t sampleRate,
3446 audio_format_t format,
3447 audio_channel_mask_t channelMask,
3448 audio_session_t sessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07003449 bool isOut,
Svet Ganov33761132021-05-13 22:51:08 +00003450 const AttributionSourceState& attributionSource,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003451 pid_t creatorPid,
Eric Laurent6acd1d42017-01-04 14:23:29 -08003452 audio_port_handle_t portId)
Kevin Rocard1f564ac2018-03-29 13:53:10 -07003453 : TrackBase(thread, NULL, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07003454 channelMask, (size_t)0 /* frameCount */,
3455 nullptr /* buffer */, (size_t)0 /* bufferSize */,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003456 sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00003457 VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003458 isOut,
Eric Laurent6acd1d42017-01-04 14:23:29 -08003459 ALLOC_NONE,
Andy Hungc2b11cb2020-04-22 09:04:01 -07003460 TYPE_DEFAULT, portId,
3461 std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_MMAP) + std::to_string(portId)),
Svet Ganov33761132021-05-13 22:51:08 +00003462 mPid(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.pid))),
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003463 mSilenced(false), mSilencedNotified(false)
Eric Laurent6acd1d42017-01-04 14:23:29 -08003464{
Andy Hungc2b11cb2020-04-22 09:04:01 -07003465 // Once this item is logged by the server, the client can add properties.
Andy Hung94235282021-03-24 15:50:14 -07003466 mTrackMetrics.logConstructor(creatorPid, uid(), id());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003467}
3468
Andy Hung11e74242023-06-26 19:20:57 -07003469MmapTrack::~MmapTrack()
Eric Laurent6acd1d42017-01-04 14:23:29 -08003470{
3471}
3472
Andy Hung11e74242023-06-26 19:20:57 -07003473status_t MmapTrack::initCheck() const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003474{
3475 return NO_ERROR;
3476}
3477
Andy Hung11e74242023-06-26 19:20:57 -07003478status_t MmapTrack::start(AudioSystem::sync_event_t event __unused,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07003479 audio_session_t triggerSession __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08003480{
3481 return NO_ERROR;
3482}
3483
Andy Hung11e74242023-06-26 19:20:57 -07003484void MmapTrack::stop()
Eric Laurent6acd1d42017-01-04 14:23:29 -08003485{
3486}
3487
3488// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07003489status_t MmapTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent6acd1d42017-01-04 14:23:29 -08003490{
3491 buffer->frameCount = 0;
3492 buffer->raw = nullptr;
3493 return INVALID_OPERATION;
3494}
3495
3496// ExtendedAudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07003497size_t MmapTrack::framesReady() const {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003498 return 0;
3499}
3500
Andy Hung11e74242023-06-26 19:20:57 -07003501int64_t MmapTrack::framesReleased() const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003502{
3503 return 0;
3504}
3505
Andy Hung11e74242023-06-26 19:20:57 -07003506void MmapTrack::onTimestamp(const ExtendedTimestamp& timestamp __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08003507{
3508}
3509
Andy Hung11e74242023-06-26 19:20:57 -07003510void MmapTrack::processMuteEvent_l(const sp<IAudioManager>& audioManager, mute_state_t muteState)
Vlad Popaec1788e2022-08-04 11:23:30 +02003511{
3512 if (mMuteState == muteState) {
3513 // mute state did not change, do nothing
3514 return;
3515 }
3516
3517 status_t result = UNKNOWN_ERROR;
3518 if (audioManager && mPortId != AUDIO_PORT_HANDLE_NONE) {
3519 if (mMuteEventExtras == nullptr) {
3520 mMuteEventExtras = std::make_unique<os::PersistableBundle>();
3521 }
3522 mMuteEventExtras->putInt(String16(kExtraPlayerEventMuteKey),
3523 static_cast<int>(muteState));
3524
3525 result = audioManager->portEvent(mPortId,
3526 PLAYER_UPDATE_MUTED,
3527 mMuteEventExtras);
3528 }
3529
3530 if (result == OK) {
3531 mMuteState = muteState;
3532 } else {
3533 ALOGW("%s(%d): cannot process mute state for port ID %d, status error %d",
3534 __func__,
3535 id(),
3536 mPortId,
3537 result);
3538 }
3539}
3540
Andy Hung11e74242023-06-26 19:20:57 -07003541void MmapTrack::appendDumpHeader(String8& result) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003542{
Eric Laurent973db022018-11-20 14:54:31 -08003543 result.appendFormat("Client Session Port Id Format Chn mask SRate Flags %s\n",
Kevin Rocard5f2136e2018-05-11 22:03:00 -07003544 isOut() ? "Usg CT": "Source");
Eric Laurent6acd1d42017-01-04 14:23:29 -08003545}
3546
Andy Hung11e74242023-06-26 19:20:57 -07003547void MmapTrack::appendDump(String8& result, bool active __unused) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003548{
Eric Laurent973db022018-11-20 14:54:31 -08003549 result.appendFormat("%6u %7u %7u %08X %08X %6u 0x%03X ",
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003550 mPid,
3551 mSessionId,
Eric Laurent973db022018-11-20 14:54:31 -08003552 mPortId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08003553 mFormat,
3554 mChannelMask,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07003555 mSampleRate,
3556 mAttr.flags);
3557 if (isOut()) {
3558 result.appendFormat("%3x %2x", mAttr.usage, mAttr.content_type);
3559 } else {
3560 result.appendFormat("%6x", mAttr.source);
3561 }
3562 result.append("\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -08003563}
3564
Glenn Kasten63238ef2015-03-02 15:50:29 -08003565} // namespace android