blob: ec58db038ec0a36e48ce0faf6f2cc699321698fc [file] [log] [blame]
Andy Hungd29af632023-06-23 19:27:19 -07001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19namespace android {
20
21// Common interface to all Playback and Record tracks.
22class IAfTrackBase : public virtual RefBase {
23public:
24 enum track_state : int32_t {
25 IDLE,
26 FLUSHED, // for PlaybackTracks only
27 STOPPED,
28 // next 2 states are currently used for fast tracks
29 // and offloaded tracks only
30 STOPPING_1, // waiting for first underrun
31 STOPPING_2, // waiting for presentation complete
32 RESUMING, // for PlaybackTracks only
33 ACTIVE,
34 PAUSING,
35 PAUSED,
36 STARTING_1, // for RecordTrack only
37 STARTING_2, // for RecordTrack only
38 };
39
40 // where to allocate the data buffer
41 enum alloc_type {
42 ALLOC_CBLK, // allocate immediately after control block
43 ALLOC_READONLY, // allocate from a separate read-only heap per thread
44 ALLOC_PIPE, // do not allocate; use the pipe buffer
45 ALLOC_LOCAL, // allocate a local buffer
46 ALLOC_NONE, // do not allocate:use the buffer passed to TrackBase constructor
47 };
48
49 enum track_type {
50 TYPE_DEFAULT,
51 TYPE_OUTPUT,
52 TYPE_PATCH,
53 };
54
55 virtual status_t initCheck() const = 0;
56 virtual status_t start(
57 AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
58 audio_session_t triggerSession = AUDIO_SESSION_NONE) = 0;
59 virtual void stop() = 0;
60 virtual sp<IMemory> getCblk() const = 0;
61 virtual audio_track_cblk_t* cblk() const = 0;
62 virtual audio_session_t sessionId() const = 0;
63 virtual uid_t uid() const = 0;
64 virtual pid_t creatorPid() const = 0;
65 virtual uint32_t sampleRate() const = 0;
66 virtual size_t frameSize() const = 0;
67 virtual audio_port_handle_t portId() const = 0;
68 virtual status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) = 0;
69 virtual track_state state() const = 0;
70 virtual void setState(track_state state) = 0;
71 virtual sp<IMemory> getBuffers() const = 0;
72 virtual void* buffer() const = 0;
73 virtual size_t bufferSize() const = 0;
74 virtual bool isFastTrack() const = 0;
75 virtual bool isDirect() const = 0;
76 virtual bool isOutputTrack() const = 0;
77 virtual bool isPatchTrack() const = 0;
78 virtual bool isExternalTrack() const = 0;
79
80 virtual void invalidate() = 0;
81 virtual bool isInvalid() const = 0;
82
83 virtual void terminate() = 0;
84 virtual bool isTerminated() const = 0;
85
86 virtual audio_attributes_t attributes() const = 0;
87 virtual bool isSpatialized() const = 0;
88 virtual bool isBitPerfect() const = 0;
89
90 // not currently implemented in TrackBase, but overridden.
91 virtual void destroy() {}; // MmapTrack doesn't implement.
92 virtual void appendDumpHeader(String8& result) const = 0;
93 virtual void appendDump(String8& result, bool active) const = 0;
94
95 // Dup with AudioBufferProvider interface
96 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) = 0;
97 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer) = 0;
98
99 // Added for RecordTrack and OutputTrack
100 // TODO(b/288339104) type
101 virtual wp<Thread> thread() const = 0;
102 virtual const sp<ServerProxy>& serverProxy() const = 0;
103
104 // TEE_SINK
105 virtual void dumpTee(int fd __unused, const std::string& reason __unused) const {};
106
107 /** returns the buffer contents size converted to time in milliseconds
108 * for PCM Playback or Record streaming tracks. The return value is zero for
109 * PCM static tracks and not defined for non-PCM tracks.
110 *
111 * This may be called without the thread lock.
112 */
113 virtual double bufferLatencyMs() const = 0;
114
115 /** returns whether the track supports server latency computation.
116 * This is set in the constructor and constant throughout the track lifetime.
117 */
118 virtual bool isServerLatencySupported() const = 0;
119
120 /** computes the server latency for PCM Playback or Record track
121 * to the device sink/source. This is the time for the next frame in the track buffer
122 * written or read from the server thread to the device source or sink.
123 *
124 * This may be called without the thread lock, but latencyMs and fromTrack
125 * may be not be synchronized. For example PatchPanel may not obtain the
126 * thread lock before calling.
127 *
128 * \param latencyMs on success is set to the latency in milliseconds of the
129 * next frame written/read by the server thread to/from the track buffer
130 * from the device source/sink.
131 * \param fromTrack on success is set to true if latency was computed directly
132 * from the track timestamp; otherwise set to false if latency was
133 * estimated from the server timestamp.
134 * fromTrack may be nullptr or omitted if not required.
135 *
136 * \returns OK or INVALID_OPERATION on failure.
137 */
138 virtual status_t getServerLatencyMs(double* latencyMs, bool* fromTrack = nullptr) const = 0;
139
140 /** computes the total client latency for PCM Playback or Record tracks
141 * for the next client app access to the device sink/source; i.e. the
142 * server latency plus the buffer latency.
143 *
144 * This may be called without the thread lock, but latencyMs and fromTrack
145 * may be not be synchronized. For example PatchPanel may not obtain the
146 * thread lock before calling.
147 *
148 * \param latencyMs on success is set to the latency in milliseconds of the
149 * next frame written/read by the client app to/from the track buffer
150 * from the device sink/source.
151 * \param fromTrack on success is set to true if latency was computed directly
152 * from the track timestamp; otherwise set to false if latency was
153 * estimated from the server timestamp.
154 * fromTrack may be nullptr or omitted if not required.
155 *
156 * \returns OK or INVALID_OPERATION on failure.
157 */
158 virtual status_t getTrackLatencyMs(double* latencyMs, bool* fromTrack = nullptr) const = 0;
159
160 // TODO: Consider making this external.
161 struct FrameTime {
162 int64_t frames;
163 int64_t timeNs;
164 };
165
166 // KernelFrameTime is updated per "mix" period even for non-pcm tracks.
167 virtual void getKernelFrameTime(FrameTime* ft) const = 0;
168
169 virtual audio_format_t format() const = 0;
170 virtual int id() const = 0;
171
172 virtual const char* getTrackStateAsString() const = 0;
173
174 // Called by the PlaybackThread to indicate that the track is becoming active
175 // and a new interval should start with a given device list.
176 virtual void logBeginInterval(const std::string& devices) = 0;
177
178 // Called by the PlaybackThread to indicate the track is no longer active.
179 virtual void logEndInterval() = 0;
180
181 // Called to tally underrun frames in playback.
182 virtual void tallyUnderrunFrames(size_t frames) = 0;
183
184 virtual audio_channel_mask_t channelMask() const = 0;
185
186 /** @return true if the track has changed (metadata or volume) since
187 * the last time this function was called,
188 * true if this function was never called since the track creation,
189 * false otherwise.
190 * Thread safe.
191 */
192 virtual bool readAndClearHasChanged() = 0;
193
194 /** Set that a metadata has changed and needs to be notified to backend. Thread safe. */
195 virtual void setMetadataHasChanged() = 0;
196
197 /**
198 * Called when a track moves to active state to record its contribution to battery usage.
199 * Track state transitions should eventually be handled within the track class.
200 */
201 virtual void beginBatteryAttribution() = 0;
202
203 /**
204 * Called when a track moves out of the active state to record its contribution
205 * to battery usage.
206 */
207 virtual void endBatteryAttribution() = 0;
208
209 /**
210 * For RecordTrack
211 * TODO(b/288339104) either use this or add asRecordTrack or asTrack etc.
212 */
213 virtual void handleSyncStartEvent(const sp<audioflinger::SyncEvent>& event __unused){};
214
215 // For Thread use, fast tracks and offloaded tracks only
216 // TODO(b/288339104) rearrange to IAfTrack.
217 virtual bool isStopped() const = 0;
218 virtual bool isStopping() const = 0;
219 virtual bool isStopping_1() const = 0;
220 virtual bool isStopping_2() const = 0;
221};
222
223// Common interface for Playback tracks.
224class IAfTrack : public virtual IAfTrackBase {
225public:
226 // createIAudioTrackAdapter() is a static constructor which creates an
227 // IAudioTrack AIDL interface adapter from the Track object that
228 // may be passed back to the client (if needed).
229 //
230 // Only one AIDL IAudioTrack interface adapter should be created per Track.
231 static sp<media::IAudioTrack> createIAudioTrackAdapter(const sp<IAfTrack>& track);
232
233 virtual void pause() = 0;
234 virtual void flush() = 0;
235 virtual audio_stream_type_t streamType() const = 0;
236 virtual bool isOffloaded() const = 0;
237 virtual bool isOffloadedOrDirect() const = 0;
238 virtual bool isStatic() const = 0;
239 virtual status_t setParameters(const String8& keyValuePairs) = 0;
240 virtual status_t selectPresentation(int presentationId, int programId) = 0;
241 virtual status_t attachAuxEffect(int EffectId) = 0;
242 virtual void setAuxBuffer(int EffectId, int32_t* buffer) = 0;
243 virtual int32_t* auxBuffer() const = 0;
244 virtual void setMainBuffer(float* buffer) = 0;
245 virtual float* mainBuffer() const = 0;
246 virtual int auxEffectId() const = 0;
247 virtual status_t getTimestamp(AudioTimestamp& timestamp) = 0;
248 virtual void signal() = 0;
249 virtual status_t getDualMonoMode(audio_dual_mono_mode_t* mode) const = 0;
250 virtual status_t setDualMonoMode(audio_dual_mono_mode_t mode) = 0;
251 virtual status_t getAudioDescriptionMixLevel(float* leveldB) const = 0;
252 virtual status_t setAudioDescriptionMixLevel(float leveldB) = 0;
253 virtual status_t getPlaybackRateParameters(audio_playback_rate_t* playbackRate) const = 0;
254 virtual status_t setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) = 0;
255
256 // implement FastMixerState::VolumeProvider interface
257 virtual gain_minifloat_packed_t getVolumeLR() const = 0;
258
259 // implement volume handling.
260 virtual media::VolumeShaper::Status applyVolumeShaper(
261 const sp<media::VolumeShaper::Configuration>& configuration,
262 const sp<media::VolumeShaper::Operation>& operation) = 0;
263 virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) const = 0;
264 virtual sp<media::VolumeHandler> getVolumeHandler() const = 0;
265 /** Set the computed normalized final volume of the track.
266 * !masterMute * masterVolume * streamVolume * averageLRVolume */
267 virtual void setFinalVolume(float volumeLeft, float volumeRight) = 0;
268 virtual float getFinalVolume() const = 0;
269 virtual void getFinalVolume(float* left, float* right) const = 0;
270
271 using SourceMetadatas = std::vector<playback_track_metadata_v7_t>;
272 using MetadataInserter = std::back_insert_iterator<SourceMetadatas>;
273 /** Copy the track metadata in the provided iterator. Thread safe. */
274 virtual void copyMetadataTo(MetadataInserter& backInserter) const = 0;
275
276 /** Return haptic playback of the track is enabled or not, used in mixer. */
277 virtual bool getHapticPlaybackEnabled() const = 0;
278 /** Set haptic playback of the track is enabled or not, should be
279 * set after query or get callback from vibrator service */
280 virtual void setHapticPlaybackEnabled(bool hapticPlaybackEnabled) = 0;
281 /** Return at what intensity to play haptics, used in mixer. */
282 virtual os::HapticScale getHapticIntensity() const = 0;
283 /** Return the maximum amplitude allowed for haptics data, used in mixer. */
284 virtual float getHapticMaxAmplitude() const = 0;
285 /** Set intensity of haptic playback, should be set after querying vibrator service. */
286 virtual void setHapticIntensity(os::HapticScale hapticIntensity) = 0;
287 /** Set maximum amplitude allowed for haptic data, should be set after querying
288 * vibrator service.
289 */
290 virtual void setHapticMaxAmplitude(float maxAmplitude) = 0;
291 virtual sp<os::ExternalVibration> getExternalVibration() const = 0;
292
293 // This function should be called with holding thread lock.
294 virtual void updateTeePatches_l() = 0;
295
296 // TODO(b/288339104) type
297 virtual void setTeePatchesToUpdate_l(
298 const void* teePatchesToUpdate /* TeePatches& teePatchesToUpdate */) = 0;
299
300 static bool checkServerLatencySupported(audio_format_t format, audio_output_flags_t flags) {
301 return audio_is_linear_pcm(format) && (flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == 0;
302 }
303
304 virtual audio_output_flags_t getOutputFlags() const = 0;
305 virtual float getSpeed() const = 0;
306
307 /**
308 * Updates the mute state and notifies the audio service. Call this only when holding player
309 * thread lock.
310 */
311 virtual void processMuteEvent_l(
312 const sp<IAudioManager>& audioManager, mute_state_t muteState) = 0;
313
314 virtual void triggerEvents(AudioSystem::sync_event_t type) = 0;
315
316 virtual void disable() = 0;
317 virtual int& fastIndex() = 0;
318 virtual bool isPlaybackRestricted() const = 0;
319};
320
321// playback track, used by DuplicatingThread
322class IAfOutputTrack : public virtual IAfTrack {
323public:
324 virtual ssize_t write(void* data, uint32_t frames) = 0;
325 virtual bool bufferQueueEmpty() const = 0;
326 virtual bool isActive() const = 0;
327
328 /** Set the metadatas of the upstream tracks. Thread safe. */
329 virtual void setMetadatas(const SourceMetadatas& metadatas) = 0;
330 /** returns client timestamp to the upstream duplicating thread. */
331 virtual ExtendedTimestamp getClientProxyTimestamp() const = 0;
332};
333
334class IAfMmapTrack : public virtual IAfTrackBase {
335public:
336 // protected by MMapThread::mLock
337 virtual void setSilenced_l(bool silenced) = 0;
338 // protected by MMapThread::mLock
339 virtual bool isSilenced_l() const = 0;
340 // protected by MMapThread::mLock
341 virtual bool getAndSetSilencedNotified_l() = 0;
342
343 /**
344 * Updates the mute state and notifies the audio service. Call this only when holding player
345 * thread lock.
346 */
347 virtual void processMuteEvent_l( // see IAfTrack
348 const sp<IAudioManager>& audioManager, mute_state_t muteState) = 0;
349};
350
351class IAfRecordTrack : public virtual IAfTrackBase {
352public:
353 // createIAudioRecordAdapter() is a static constructor which creates an
354 // IAudioRecord AIDL interface adapter from the RecordTrack object that
355 // may be passed back to the client (if needed).
356 //
357 // Only one AIDL IAudioRecord interface adapter should be created per RecordTrack.
358 static sp<media::IAudioRecord> createIAudioRecordAdapter(const sp<IAfRecordTrack>& recordTrack);
359
360 // clear the buffer overflow flag
361 virtual void clearOverflow() = 0;
362 // set the buffer overflow flag and return previous value
363 virtual bool setOverflow() = 0;
364
365 // TODO(b/288339104) handleSyncStartEvent in IAfTrackBase should move here.
366 virtual void clearSyncStartEvent() = 0;
367 virtual void updateTrackFrameInfo(
368 int64_t trackFramesReleased, int64_t sourceFramesRead, uint32_t halSampleRate,
369 const ExtendedTimestamp& timestamp) = 0;
370
371 virtual void setSilenced(bool silenced) = 0;
372 virtual bool isSilenced() const = 0;
373 virtual status_t getActiveMicrophones(
374 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const = 0;
375
376 virtual status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) = 0;
377 virtual status_t setPreferredMicrophoneFieldDimension(float zoom) = 0;
378 virtual status_t shareAudioHistory(
379 const std::string& sharedAudioPackageName, int64_t sharedAudioStartMs) = 0;
380 virtual int32_t startFrames() const = 0;
381
382 static bool checkServerLatencySupported(audio_format_t format, audio_input_flags_t flags) {
383 return audio_is_linear_pcm(format) && (flags & AUDIO_INPUT_FLAG_HW_AV_SYNC) == 0;
384 }
385
386 using SinkMetadatas = std::vector<record_track_metadata_v7_t>;
387 using MetadataInserter = std::back_insert_iterator<SinkMetadatas>;
388 virtual void copyMetadataTo(MetadataInserter& backInserter) const = 0; // see IAfTrack
389};
390
391} // namespace android