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