xref: /aosp_15_r20/frameworks/av/services/audioflinger/IAfTrack.h (revision ec779b8e0859a360c3d303172224686826e6e0e1)
1 /*
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 
19 #include <android/media/BnAudioRecord.h>
20 #include <android/media/BnAudioTrack.h>
21 #include <audio_utils/mutex.h>
22 #include <audiomanager/IAudioManager.h>
23 #include <binder/IMemory.h>
24 #include <datapath/VolumePortInterface.h>
25 #include <fastpath/FastMixerDumpState.h>
26 #include <media/AudioSystem.h>
27 #include <media/VolumeShaper.h>
28 #include <private/media/AudioTrackShared.h>
29 #include <timing/SyncEvent.h>
30 #include <timing/SynchronizedRecordState.h>
31 #include <utils/RefBase.h>
32 #include <vibrator/ExternalVibration.h>
33 
34 #include <vector>
35 
36 namespace android {
37 
38 class Client;
39 class ResamplerBufferProvider;
40 struct Source;
41 
42 class IAfDuplicatingThread;
43 class IAfPatchRecord;
44 class IAfPatchTrack;
45 class IAfPlaybackThread;
46 class IAfRecordThread;
47 class IAfThreadBase;
48 
49 struct TeePatch {
50     sp<IAfPatchRecord> patchRecord;
51     sp<IAfPatchTrack> patchTrack;
52 };
53 
54 using TeePatches = std::vector<TeePatch>;
55 
56 // Common interface to all Playback and Record tracks.
57 class IAfTrackBase : public virtual RefBase {
58 public:
59     enum track_state : int32_t {
60         IDLE,
61         FLUSHED,  // for PlaybackTracks only
62         STOPPED,
63         // next 2 states are currently used for fast tracks
64         // and offloaded tracks only
65         STOPPING_1,  // waiting for first underrun
66         STOPPING_2,  // waiting for presentation complete
67         RESUMING,    // for PlaybackTracks only
68         ACTIVE,
69         PAUSING,
70         PAUSED,
71         STARTING_1,  // for RecordTrack only
72         STARTING_2,  // for RecordTrack only
73     };
74 
75     // where to allocate the data buffer
76     enum alloc_type {
77         ALLOC_CBLK,      // allocate immediately after control block
78         ALLOC_READONLY,  // allocate from a separate read-only heap per thread
79         ALLOC_PIPE,      // do not allocate; use the pipe buffer
80         ALLOC_LOCAL,     // allocate a local buffer
81         ALLOC_NONE,      // do not allocate:use the buffer passed to TrackBase constructor
82     };
83 
84     enum track_type {
85         TYPE_DEFAULT,
86         TYPE_OUTPUT,
87         TYPE_PATCH,
88     };
89 
90     virtual status_t initCheck() const = 0;
91     virtual status_t start(
92             AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
93             audio_session_t triggerSession = AUDIO_SESSION_NONE) = 0;
94     virtual void stop() = 0;
95     virtual sp<IMemory> getCblk() const = 0;
96     virtual audio_track_cblk_t* cblk() const = 0;
97     virtual audio_session_t sessionId() const = 0;
98     virtual uid_t uid() const = 0;
99     virtual pid_t creatorPid() const = 0;
100     virtual uint32_t sampleRate() const = 0;
101     virtual size_t frameSize() const = 0;
102     virtual audio_port_handle_t portId() const = 0;
103     virtual status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) = 0;
104     virtual track_state state() const = 0;
105     virtual void setState(track_state state) = 0;
106     virtual sp<IMemory> getBuffers() const = 0;
107     virtual void* buffer() const = 0;
108     virtual size_t bufferSize() const = 0;
109     virtual bool isFastTrack() const = 0;
110     virtual bool isDirect() const = 0;
111     virtual bool isOutputTrack() const = 0;
112     virtual bool isPatchTrack() const = 0;
113     virtual bool isExternalTrack() const = 0;
114 
115     virtual void invalidate() = 0;
116     virtual bool isInvalid() const = 0;
117 
118     virtual void terminate() = 0;
119     virtual bool isTerminated() const = 0;
120 
121     virtual audio_attributes_t attributes() const = 0;
122     virtual bool isSpatialized() const = 0;
123     virtual bool isBitPerfect() const = 0;
124 
125     // not currently implemented in TrackBase, but overridden.
destroy()126     virtual void destroy() {};  // MmapTrack doesn't implement.
127     virtual void appendDumpHeader(String8& result) const = 0;
128     virtual void appendDump(String8& result, bool active) const = 0;
129 
130     // Dup with AudioBufferProvider interface
131     virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) = 0;
132     virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer) = 0;
133 
134     // Added for RecordTrack and OutputTrack
135     virtual wp<IAfThreadBase> thread() const = 0;
136     virtual const sp<ServerProxy>& serverProxy() const = 0;
137 
138     // TEE_SINK
dumpTee(int fd __unused,const std::string & reason __unused)139     virtual void dumpTee(int fd __unused, const std::string& reason __unused) const {};
140 
141     /** returns the buffer contents size converted to time in milliseconds
142      * for PCM Playback or Record streaming tracks. The return value is zero for
143      * PCM static tracks and not defined for non-PCM tracks.
144      *
145      * This may be called without the thread lock.
146      */
147     virtual double bufferLatencyMs() const = 0;
148 
149     /** returns whether the track supports server latency computation.
150      * This is set in the constructor and constant throughout the track lifetime.
151      */
152     virtual bool isServerLatencySupported() const = 0;
153 
154     /** computes the server latency for PCM Playback or Record track
155      * to the device sink/source.  This is the time for the next frame in the track buffer
156      * written or read from the server thread to the device source or sink.
157      *
158      * This may be called without the thread lock, but latencyMs and fromTrack
159      * may be not be synchronized. For example PatchPanel may not obtain the
160      * thread lock before calling.
161      *
162      * \param latencyMs on success is set to the latency in milliseconds of the
163      *        next frame written/read by the server thread to/from the track buffer
164      *        from the device source/sink.
165      * \param fromTrack on success is set to true if latency was computed directly
166      *        from the track timestamp; otherwise set to false if latency was
167      *        estimated from the server timestamp.
168      *        fromTrack may be nullptr or omitted if not required.
169      *
170      * \returns OK or INVALID_OPERATION on failure.
171      */
172     virtual status_t getServerLatencyMs(double* latencyMs, bool* fromTrack = nullptr) const = 0;
173 
174     /** computes the total client latency for PCM Playback or Record tracks
175      * for the next client app access to the device sink/source; i.e. the
176      * server latency plus the buffer latency.
177      *
178      * This may be called without the thread lock, but latencyMs and fromTrack
179      * may be not be synchronized. For example PatchPanel may not obtain the
180      * thread lock before calling.
181      *
182      * \param latencyMs on success is set to the latency in milliseconds of the
183      *        next frame written/read by the client app to/from the track buffer
184      *        from the device sink/source.
185      * \param fromTrack on success is set to true if latency was computed directly
186      *        from the track timestamp; otherwise set to false if latency was
187      *        estimated from the server timestamp.
188      *        fromTrack may be nullptr or omitted if not required.
189      *
190      * \returns OK or INVALID_OPERATION on failure.
191      */
192     virtual status_t getTrackLatencyMs(double* latencyMs, bool* fromTrack = nullptr) const = 0;
193 
194     // TODO: Consider making this external.
195     struct FrameTime {
196         int64_t frames;
197         int64_t timeNs;
198     };
199 
200     // KernelFrameTime is updated per "mix" period even for non-pcm tracks.
201     virtual void getKernelFrameTime(FrameTime* ft) const = 0;
202 
203     virtual audio_format_t format() const = 0;
204     virtual int id() const = 0;
205 
206     virtual const char* getTrackStateAsString() const = 0;
207 
208     virtual const std::string& getTraceSuffix() const = 0;
209     // Called by the PlaybackThread to indicate that the track is becoming active
210     // and a new interval should start with a given device list.
211     virtual void logBeginInterval(const std::string& devices) = 0;
212 
213     // Called by the PlaybackThread to indicate the track is no longer active.
214     virtual void logEndInterval() = 0;
215 
216     // Called by the PlaybackThread when ATRACE is enabled.
217     virtual void logRefreshInterval(const std::string& devices) = 0;
218 
219     // Called to tally underrun frames in playback.
220     virtual void tallyUnderrunFrames(size_t frames) = 0;
221 
222     virtual audio_channel_mask_t channelMask() const = 0;
223 
224     /** @return true if the track has changed (metadata or volume) since
225      *          the last time this function was called,
226      *          true if this function was never called since the track creation,
227      *          false otherwise.
228      *  Thread safe.
229      */
230     virtual bool readAndClearHasChanged() = 0;
231 
232     /** Set that a metadata has changed and needs to be notified to backend. Thread safe. */
233     virtual void setMetadataHasChanged() = 0;
234 
235     /**
236      * Called when a track moves to active state to record its contribution to battery usage.
237      * Track state transitions should eventually be handled within the track class.
238      */
239     virtual void beginBatteryAttribution() = 0;
240 
241     /**
242      * Called when a track moves out of the active state to record its contribution
243      * to battery usage.
244      */
245     virtual void endBatteryAttribution() = 0;
246 
247     /**
248      * For RecordTrack
249      * TODO(b/291317964) either use this or add asRecordTrack or asTrack etc.
250      */
handleSyncStartEvent(const sp<audioflinger::SyncEvent> & event __unused)251     virtual void handleSyncStartEvent(const sp<audioflinger::SyncEvent>& event __unused){};
252 
253     // For Thread use, fast tracks and offloaded tracks only
254     // TODO(b/291317964) rearrange to IAfTrack.
255     virtual bool isStopped() const = 0;
256     virtual bool isStopping() const = 0;
257     virtual bool isStopping_1() const = 0;
258     virtual bool isStopping_2() const = 0;
259 };
260 
261 // Common interface for Playback tracks.
262 class IAfTrack : public virtual IAfTrackBase, public virtual VolumePortInterface {
263 public:
264     // FillingStatus is used for suppressing volume ramp at begin of playing
265     enum FillingStatus { FS_INVALID, FS_FILLING, FS_FILLED, FS_ACTIVE };
266 
267     // createIAudioTrackAdapter() is a static constructor which creates an
268     // IAudioTrack AIDL interface adapter from the Track object that
269     // may be passed back to the client (if needed).
270     //
271     // Only one AIDL IAudioTrack interface adapter should be created per Track.
272     static sp<media::IAudioTrack> createIAudioTrackAdapter(const sp<IAfTrack>& track);
273 
274     static sp<IAfTrack> create(
275             IAfPlaybackThread* thread,
276             const sp<Client>& client,
277             audio_stream_type_t streamType,
278             const audio_attributes_t& attr,
279             uint32_t sampleRate,
280             audio_format_t format,
281             audio_channel_mask_t channelMask,
282             size_t frameCount,
283             void* buffer,
284             size_t bufferSize,
285             const sp<IMemory>& sharedBuffer,
286             audio_session_t sessionId,
287             pid_t creatorPid,
288             const AttributionSourceState& attributionSource,
289             audio_output_flags_t flags,
290             track_type type,
291             audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE,
292             /** default behaviour is to start when there are as many frames
293               * ready as possible (aka. Buffer is full). */
294             size_t frameCountToBeReady = SIZE_MAX,
295             float speed = 1.0f,
296             bool isSpatialized = false,
297             bool isBitPerfect = false,
298             float volume = 0.0f,
299             bool muted = false);
300 
getLogHeader()301     static constexpr std::string_view getLogHeader() {
302         using namespace std::literals;
303         return "Type     Id Active Client(pid/uid) Session Port Id S  Flags "
304                         "  Format Chn mask  SRate "
305                         "ST Usg CT "
306                         " G db  L dB  R dB  VS dB  PortVol dB  PortMuted "
307                         "  Server FrmCnt  FrmRdy F Underruns  Flushed BitPerfect InternalMute"
308                         "   Latency\n"sv;
309     }
310 
311     virtual void pause() = 0;
312     virtual void flush() = 0;
313     virtual audio_stream_type_t streamType() const = 0;
314     virtual bool isOffloaded() const = 0;
315     virtual bool isOffloadedOrDirect() const = 0;
316     virtual bool isStatic() const = 0;
317     virtual status_t setParameters(const String8& keyValuePairs) = 0;
318     virtual status_t selectPresentation(int presentationId, int programId) = 0;
319     virtual status_t attachAuxEffect(int EffectId) = 0;
320     virtual void setAuxBuffer(int EffectId, int32_t* buffer) = 0;
321     virtual int32_t* auxBuffer() const = 0;
322     virtual void setMainBuffer(float* buffer) = 0;
323     virtual float* mainBuffer() const = 0;
324     virtual int auxEffectId() const = 0;
325     virtual status_t getTimestamp(AudioTimestamp& timestamp) = 0;
326     virtual void signal() = 0;
327     virtual status_t getDualMonoMode(audio_dual_mono_mode_t* mode) const = 0;
328     virtual status_t setDualMonoMode(audio_dual_mono_mode_t mode) = 0;
329     virtual status_t getAudioDescriptionMixLevel(float* leveldB) const = 0;
330     virtual status_t setAudioDescriptionMixLevel(float leveldB) = 0;
331     virtual status_t getPlaybackRateParameters(audio_playback_rate_t* playbackRate) const = 0;
332     virtual status_t setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) = 0;
333 
334     // implement FastMixerState::VolumeProvider interface
335     virtual gain_minifloat_packed_t getVolumeLR() const = 0;
336 
337     // implement volume handling.
338     virtual media::VolumeShaper::Status applyVolumeShaper(
339             const sp<media::VolumeShaper::Configuration>& configuration,
340             const sp<media::VolumeShaper::Operation>& operation) = 0;
341     virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) const = 0;
342     virtual sp<media::VolumeHandler> getVolumeHandler() const = 0;
343     /** Set the computed normalized final volume of the track.
344      * !masterMute * masterVolume * streamVolume * averageLRVolume */
345     virtual void setFinalVolume(float volumeLeft, float volumeRight) = 0;
346     virtual float getFinalVolume() const = 0;
347     virtual void getFinalVolume(float* left, float* right) const = 0;
348 
349     using SourceMetadatas = std::vector<playback_track_metadata_v7_t>;
350     using MetadataInserter = std::back_insert_iterator<SourceMetadatas>;
351     /** Copy the track metadata in the provided iterator. Thread safe. */
352     virtual void copyMetadataTo(MetadataInserter& backInserter) const = 0;
353 
354     /** Return haptic playback of the track is enabled or not, used in mixer. */
355     virtual bool getHapticPlaybackEnabled() const = 0;
356     /** Set haptic playback of the track is enabled or not, should be
357      * set after query or get callback from vibrator service */
358     virtual void setHapticPlaybackEnabled(bool hapticPlaybackEnabled) = 0;
359     /** Return the haptics scale, used in mixer. */
360     virtual os::HapticScale getHapticScale() const = 0;
361     /** Return the maximum amplitude allowed for haptics data, used in mixer. */
362     virtual float getHapticMaxAmplitude() const = 0;
363     /** Set scale for haptic playback, should be set after querying vibrator service. */
364     virtual void setHapticScale(os::HapticScale hapticScale) = 0;
365     /** Set maximum amplitude allowed for haptic data, should be set after querying
366      *  vibrator service.
367      */
368     virtual void setHapticMaxAmplitude(float maxAmplitude) = 0;
369     virtual sp<os::ExternalVibration> getExternalVibration() const = 0;
370 
371     // This function should be called with holding thread lock.
372     virtual void updateTeePatches_l() REQUIRES(audio_utils::ThreadBase_Mutex)
373             EXCLUDES_BELOW_ThreadBase_Mutex = 0;
374 
375     // Argument teePatchesToUpdate is by value, use std::move to optimize.
376     virtual void setTeePatchesToUpdate_l(TeePatches teePatchesToUpdate) = 0;
377 
checkServerLatencySupported(audio_format_t format,audio_output_flags_t flags)378     static bool checkServerLatencySupported(audio_format_t format, audio_output_flags_t flags) {
379         return audio_is_linear_pcm(format) && (flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == 0;
380     }
381 
382     virtual audio_output_flags_t getOutputFlags() const = 0;
383     virtual float getSpeed() const = 0;
384 
385     /**
386      * Updates the mute state and notifies the audio service. Call this only when holding player
387      * thread lock.
388      */
389     virtual void processMuteEvent_l(
390             const sp<IAudioManager>& audioManager, mute_state_t muteState) = 0;
391 
392     virtual void triggerEvents(AudioSystem::sync_event_t type) = 0;
393 
394     virtual void disable() = 0;
395     virtual bool isDisabled() const = 0;
396 
397     virtual int& fastIndex() = 0;
398     virtual bool isPlaybackRestricted() const = 0;
399 
400     // Used by thread only
401 
402     virtual bool isPausing() const = 0;
403     virtual bool isPaused() const = 0;
404     virtual bool isResuming() const = 0;
405     virtual bool isReady() const = 0;
406     virtual void setPaused() = 0;
407     virtual void reset() = 0;
408     virtual bool isFlushPending() const = 0;
409     virtual void flushAck() = 0;
410     virtual bool isResumePending() const = 0;
411     virtual void resumeAck() = 0;
412     // For direct or offloaded tracks ensure that the pause state is acknowledged
413     // by the playback thread in case of an immediate flush.
414     virtual bool isPausePending() const = 0;
415     virtual void pauseAck() = 0;
416     virtual void updateTrackFrameInfo(
417             int64_t trackFramesReleased, int64_t sinkFramesWritten, uint32_t halSampleRate,
418             const ExtendedTimestamp& timeStamp) = 0;
419     virtual sp<IMemory> sharedBuffer() const = 0;
420 
421     // Dup with ExtendedAudioBufferProvider
422     virtual size_t framesReady() const = 0;
423 
424     // presentationComplete checked by frames. (Mixed Tracks).
425     // framesWritten is cumulative, never reset, and is shared all tracks
426     // audioHalFrames is derived from output latency
427     virtual bool presentationComplete(int64_t framesWritten, size_t audioHalFrames) = 0;
428 
429     // presentationComplete checked by time. (Direct Tracks).
430     virtual bool presentationComplete(uint32_t latencyMs) = 0;
431 
432     virtual void resetPresentationComplete() = 0;
433 
434     virtual bool hasVolumeController() const = 0;
435     virtual void setHasVolumeController(bool hasVolumeController) = 0;
436     virtual const sp<AudioTrackServerProxy>& audioTrackServerProxy() const = 0;
437     virtual void setCachedVolume(float volume) = 0;
438     virtual void setResetDone(bool resetDone) = 0;
439 
440     virtual ExtendedAudioBufferProvider* asExtendedAudioBufferProvider() = 0;
441     virtual VolumeProvider* asVolumeProvider() = 0;
442 
443     // TODO(b/291317964) split into getter/setter
444     virtual FillingStatus& fillingStatus() = 0;
445     virtual int8_t& retryCount() = 0;
446     virtual FastTrackUnderruns& fastTrackUnderruns() = 0;
447 
448     // Internal mute, this is currently only used for bit-perfect playback
449     virtual bool getInternalMute() const = 0;
450     virtual void setInternalMute(bool muted) = 0;
451 };
452 
453 // playback track, used by DuplicatingThread
454 class IAfOutputTrack : public virtual IAfTrack {
455 public:
456     static sp<IAfOutputTrack> create(
457             IAfPlaybackThread* playbackThread,
458             IAfDuplicatingThread* sourceThread, uint32_t sampleRate,
459             audio_format_t format, audio_channel_mask_t channelMask, size_t frameCount,
460             const AttributionSourceState& attributionSource);
461 
462     virtual ssize_t write(void* data, uint32_t frames) = 0;
463     virtual bool bufferQueueEmpty() const = 0;
464     virtual bool isActive() const = 0;
465 
466     /** Set the metadatas of the upstream tracks. Thread safe. */
467     virtual void setMetadatas(const SourceMetadatas& metadatas) = 0;
468     /** returns client timestamp to the upstream duplicating thread. */
469     virtual ExtendedTimestamp getClientProxyTimestamp() const = 0;
470 };
471 
472 class IAfMmapTrack : public virtual IAfTrackBase, public virtual VolumePortInterface {
473 public:
474     static sp<IAfMmapTrack> create(IAfThreadBase* thread,
475             const audio_attributes_t& attr,
476             uint32_t sampleRate,
477             audio_format_t format,
478             audio_channel_mask_t channelMask,
479             audio_session_t sessionId,
480             bool isOut,
481             const android::content::AttributionSourceState& attributionSource,
482             pid_t creatorPid,
483             audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE,
484             float volume = 0.0f,
485             bool muted = false);
486 
getLogHeader()487     static constexpr std::string_view getLogHeader() {
488         using namespace std::literals;
489         return "Client(pid/uid) Session Port Id"
490                 "   Format Chn mask  SRate Flags Usg/Src PortVol dB PortMuted\n"sv;
491     };
492 
493     // protected by MMapThread::mLock
494     virtual void setSilenced_l(bool silenced) = 0;
495     // protected by MMapThread::mLock
496     virtual bool isSilenced_l() const = 0;
497     // protected by MMapThread::mLock
498     virtual bool getAndSetSilencedNotified_l() = 0;
499 
500     /**
501      * Updates the mute state and notifies the audio service. Call this only when holding player
502      * thread lock.
503      */
504     virtual void processMuteEvent_l(  // see IAfTrack
505             const sp<IAudioManager>& audioManager, mute_state_t muteState) = 0;
506 };
507 
508 class RecordBufferConverter;
509 
510 class IAfRecordTrack : public virtual IAfTrackBase {
511 public:
512     // createIAudioRecordAdapter() is a static constructor which creates an
513     // IAudioRecord AIDL interface adapter from the RecordTrack object that
514     // may be passed back to the client (if needed).
515     //
516     // Only one AIDL IAudioRecord interface adapter should be created per RecordTrack.
517     static sp<media::IAudioRecord> createIAudioRecordAdapter(const sp<IAfRecordTrack>& recordTrack);
518 
519     static sp<IAfRecordTrack> create(IAfRecordThread* thread,
520             const sp<Client>& client,
521             const audio_attributes_t& attr,
522             uint32_t sampleRate,
523             audio_format_t format,
524             audio_channel_mask_t channelMask,
525             size_t frameCount,
526             void* buffer,
527             size_t bufferSize,
528             audio_session_t sessionId,
529             pid_t creatorPid,
530             const AttributionSourceState& attributionSource,
531             audio_input_flags_t flags,
532             track_type type,
533             audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE,
534             int32_t startFrames = -1);
535 
getLogHeader()536     static constexpr std::string_view getLogHeader() {
537         using namespace std::literals;
538         return "Active     Id Client(pid/uid) Session Port Id  S  Flags  "
539                         " Format Chn mask  SRate Source  "
540                         " Server FrmCnt FrmRdy Sil   Latency\n"sv;
541     }
542 
543     // clear the buffer overflow flag
544     virtual void clearOverflow() = 0;
545     // set the buffer overflow flag and return previous value
546     virtual bool setOverflow() = 0;
547 
548     // TODO(b/291317964) handleSyncStartEvent in IAfTrackBase should move here.
549     virtual void clearSyncStartEvent() = 0;
550     virtual void updateTrackFrameInfo(
551             int64_t trackFramesReleased, int64_t sourceFramesRead, uint32_t halSampleRate,
552             const ExtendedTimestamp& timestamp) = 0;
553 
554     virtual void setSilenced(bool silenced) = 0;
555     virtual bool isSilenced() const = 0;
556     virtual status_t getActiveMicrophones(
557             std::vector<media::MicrophoneInfoFw>* activeMicrophones) const = 0;
558 
559     virtual status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) = 0;
560     virtual status_t setPreferredMicrophoneFieldDimension(float zoom) = 0;
561     virtual status_t shareAudioHistory(
562             const std::string& sharedAudioPackageName, int64_t sharedAudioStartMs) = 0;
563     virtual int32_t startFrames() const = 0;
564 
checkServerLatencySupported(audio_format_t format,audio_input_flags_t flags)565     static bool checkServerLatencySupported(audio_format_t format, audio_input_flags_t flags) {
566         return audio_is_linear_pcm(format) && (flags & AUDIO_INPUT_FLAG_HW_AV_SYNC) == 0;
567     }
568 
569     using SinkMetadatas = std::vector<record_track_metadata_v7_t>;
570     using MetadataInserter = std::back_insert_iterator<SinkMetadatas>;
571     virtual void copyMetadataTo(MetadataInserter& backInserter) const = 0; // see IAfTrack
572 
573     // private to Threads
574     virtual AudioBufferProvider::Buffer& sinkBuffer() = 0;
575     virtual audioflinger::SynchronizedRecordState& synchronizedRecordState() = 0;
576     virtual RecordBufferConverter* recordBufferConverter() const = 0;
577     virtual ResamplerBufferProvider* resamplerBufferProvider() const = 0;
578 };
579 
580 // PatchProxyBufferProvider interface is implemented by PatchTrack and PatchRecord.
581 // it provides buffer access methods that map those of a ClientProxy (see AudioTrackShared.h)
582 class PatchProxyBufferProvider {
583 public:
584     virtual ~PatchProxyBufferProvider() = default;
585     virtual bool producesBufferOnDemand() const = 0;
586     virtual status_t obtainBuffer(
587             Proxy::Buffer* buffer, const struct timespec* requested = nullptr) = 0;
588     virtual void releaseBuffer(Proxy::Buffer* buffer) = 0;
589 };
590 
591 class IAfPatchTrackBase : public virtual RefBase {
592 public:
593     using Timeout = std::optional<std::chrono::nanoseconds>;
594 
595     virtual void setPeerTimeout(std::chrono::nanoseconds timeout) = 0;
596     virtual void setPeerProxy(const sp<IAfPatchTrackBase>& proxy, bool holdReference) = 0;
597     virtual void clearPeerProxy() = 0;
598     virtual PatchProxyBufferProvider* asPatchProxyBufferProvider() = 0;
599 };
600 
601 class IAfPatchTrack : public virtual IAfTrack, public virtual IAfPatchTrackBase {
602 public:
603     static sp<IAfPatchTrack> create(
604             IAfPlaybackThread* playbackThread,
605             audio_stream_type_t streamType,
606             uint32_t sampleRate,
607             audio_channel_mask_t channelMask,
608             audio_format_t format,
609             size_t frameCount,
610             void *buffer,
611             size_t bufferSize,
612             audio_output_flags_t flags,
613             const Timeout& timeout = {},
614             size_t frameCountToBeReady = 1, /** Default behaviour is to start
615                                              *  as soon as possible to have
616                                              *  the lowest possible latency
617                                              *  even if it might glitch. */
618             float speed = 1.0f,
619             float volume = 1.0f,
620             bool muted = false);
621 };
622 
623 class IAfPatchRecord : public virtual IAfRecordTrack, public virtual IAfPatchTrackBase {
624 public:
625     static sp<IAfPatchRecord> create(
626             IAfRecordThread* recordThread,
627             uint32_t sampleRate,
628             audio_channel_mask_t channelMask,
629             audio_format_t format,
630             size_t frameCount,
631             void* buffer,
632             size_t bufferSize,
633             audio_input_flags_t flags,
634             const Timeout& timeout = {},
635             audio_source_t source = AUDIO_SOURCE_DEFAULT);
636 
637     static sp<IAfPatchRecord> createPassThru(
638             IAfRecordThread* recordThread,
639             uint32_t sampleRate,
640             audio_channel_mask_t channelMask,
641             audio_format_t format,
642             size_t frameCount,
643             audio_input_flags_t flags,
644             audio_source_t source = AUDIO_SOURCE_DEFAULT);
645 
646     virtual Source* getSource() = 0;
647     virtual size_t writeFrames(const void* src, size_t frameCount, size_t frameSize) = 0;
648 };
649 
650 }  // namespace android
651