1 /*
2  * Copyright (C) 2016 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 #ifndef ANDROID_HARDWARE_STREAM_HAL_INTERFACE_H
18 #define ANDROID_HARDWARE_STREAM_HAL_INTERFACE_H
19 
20 #include <vector>
21 
22 #include <android/media/MicrophoneInfoFw.h>
23 #include <media/audiohal/EffectHalInterface.h>
24 #include <system/audio.h>
25 #include <utils/Errors.h>
26 #include <utils/RefBase.h>
27 #include <utils/String8.h>
28 #include <utils/Vector.h>
29 
30 namespace android {
31 
32 class StreamHalInterface : public virtual RefBase
33 {
34   public:
35     // Return size of input/output buffer in bytes for this stream - eg. 4800.
36     virtual status_t getBufferSize(size_t *size) = 0;
37 
38     // Return the base configuration of the stream:
39     //   - channel mask;
40     //   - format - e.g. AUDIO_FORMAT_PCM_16_BIT;
41     //   - sampling rate in Hz - eg. 44100.
42     virtual status_t getAudioProperties(audio_config_base_t *configBase) = 0;
43 
44     // Convenience method.
getAudioProperties(uint32_t * sampleRate,audio_channel_mask_t * mask,audio_format_t * format)45     inline status_t getAudioProperties(
46             uint32_t *sampleRate, audio_channel_mask_t *mask, audio_format_t *format) {
47         audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
48         const status_t result = getAudioProperties(&config);
49         if (result == NO_ERROR) {
50             if (sampleRate != nullptr) *sampleRate = config.sample_rate;
51             if (mask != nullptr) *mask = config.channel_mask;
52             if (format != nullptr) *format = config.format;
53         }
54         return result;
55     }
56 
57     // Set audio stream parameters.
58     virtual status_t setParameters(const String8& kvPairs) = 0;
59 
60     // Get audio stream parameters.
61     virtual status_t getParameters(const String8& keys, String8 *values) = 0;
62 
63     // Return the frame size (number of bytes per sample) of a stream.
64     virtual status_t getFrameSize(size_t *size) = 0;
65 
66     // Add or remove the effect on the stream.
67     virtual status_t addEffect(sp<EffectHalInterface> effect) = 0;
68     virtual status_t removeEffect(sp<EffectHalInterface> effect) = 0;
69 
70     // Put the audio hardware input/output into standby mode.
71     virtual status_t standby() = 0;
72 
73     virtual status_t dump(int fd, const Vector<String16>& args = {}) = 0;
74 
75     // Start a stream operating in mmap mode.
76     virtual status_t start() = 0;
77 
78     // Stop a stream operating in mmap mode.
79     virtual status_t stop() = 0;
80 
81     // Retrieve information on the data buffer in mmap mode.
82     virtual status_t createMmapBuffer(int32_t minSizeFrames,
83                                       struct audio_mmap_buffer_info *info) = 0;
84 
85     // Get current read/write position in the mmap buffer
86     virtual status_t getMmapPosition(struct audio_mmap_position *position) = 0;
87 
88     // Set the priority of the thread that interacts with the HAL
89     // (must match the priority of the audioflinger's thread that calls 'read' / 'write')
90     virtual status_t setHalThreadPriority(int priority) = 0;
91 
92     virtual status_t legacyCreateAudioPatch(const struct audio_port_config& port,
93                                             std::optional<audio_source_t> source,
94                                             audio_devices_t type) = 0;
95 
96     virtual status_t legacyReleaseAudioPatch() = 0;
97 
98   protected:
99     // Subclasses can not be constructed directly by clients.
StreamHalInterface()100     StreamHalInterface() {}
101 
102     // The destructor automatically closes the stream.
~StreamHalInterface()103     virtual ~StreamHalInterface() {}
104 };
105 
106 class StreamOutHalInterfaceCallback : public virtual RefBase {
107   public:
onWriteReady()108     virtual void onWriteReady() {}
onDrainReady()109     virtual void onDrainReady() {}
onError(bool)110     virtual void onError(bool /*isHardError*/) {}
111 
112   protected:
113     StreamOutHalInterfaceCallback() = default;
114     virtual ~StreamOutHalInterfaceCallback() = default;
115 };
116 
117 class StreamOutHalInterfaceEventCallback : public virtual RefBase {
118 public:
119     virtual void onCodecFormatChanged(const std::vector<uint8_t>& metadataBs) = 0;
120 
121 protected:
122     StreamOutHalInterfaceEventCallback() = default;
123     virtual ~StreamOutHalInterfaceEventCallback() = default;
124 };
125 
126 class StreamOutHalInterfaceLatencyModeCallback : public virtual RefBase {
127 public:
128     /**
129      * Called with the new list of supported latency modes when a change occurs.
130      */
131     virtual void onRecommendedLatencyModeChanged(std::vector<audio_latency_mode_t> modes) = 0;
132 
133 protected:
134     StreamOutHalInterfaceLatencyModeCallback() = default;
135     virtual ~StreamOutHalInterfaceLatencyModeCallback() = default;
136 };
137 
138 /**
139  * On position reporting. There are two methods: 'getRenderPosition' and
140  * 'getPresentationPosition'. The first difference is that they may have a
141  * time offset because "render" position relates to what happens between
142  * ADSP and DAC, while "observable" position is relative to the external
143  * observer. The second difference is that 'getRenderPosition' always
144  * resets on standby (for all types of stream data) according to its
145  * definition. Since the original C definition of 'getRenderPosition' used
146  * 32-bit frame counters, and also because in complex playback chains that
147  * include wireless devices the "observable" position has more practical
148  * meaning, 'getRenderPosition' does not exist in the AIDL HAL interface.
149  * The table below summarizes frame count behavior for 'getPresentationPosition':
150  *
151  *               | Mixed      | Direct       | Direct
152  *               |            | non-offload  | offload
153  * ==============|============|==============|==============
154  *  PCM and      | Continuous |              |
155  *  encapsulated |            |              |
156  *  bitstream    |            |              |
157  * --------------|------------| Continuous†  |
158  *  Bitstream    |            |              | Reset on
159  *  encapsulated |            |              | flush, drain
160  *  into PCM     |            |              | and standby
161  *               | Not        |              |
162  * --------------| supported  |--------------|
163  *  Bitstream    |            | Reset on     |
164  *               |            | flush, drain |
165  *               |            | and standby  |
166  *               |            |              |
167  *
168  * † - on standby, reset of the frame count happens at the framework level.
169  */
170 class StreamOutHalInterface : public virtual StreamHalInterface {
171   public:
172     // Return the audio hardware driver estimated latency in milliseconds.
173     virtual status_t getLatency(uint32_t *latency) = 0;
174 
175     // Use this method in situations where audio mixing is done in the hardware.
176     virtual status_t setVolume(float left, float right) = 0;
177 
178     // Selects the audio presentation (if available).
179     virtual status_t selectPresentation(int presentationId, int programId) = 0;
180 
181     // Write audio buffer to driver.
182     virtual status_t write(const void *buffer, size_t bytes, size_t *written) = 0;
183 
184     // Return the number of audio frames written by the audio dsp to DAC since
185     // the output has exited standby.
186     virtual status_t getRenderPosition(uint64_t *dspFrames) = 0;
187 
188     // Set the callback for notifying completion of non-blocking write and drain.
189     // The callback must be owned by someone else. The output stream does not own it
190     // to avoid strong pointer loops.
191     virtual status_t setCallback(wp<StreamOutHalInterfaceCallback> callback) = 0;
192 
193     // Returns whether pause and resume operations are supported.
194     virtual status_t supportsPauseAndResume(bool *supportsPause, bool *supportsResume) = 0;
195 
196     // Notifies to the audio driver to resume playback following a pause.
197     virtual status_t pause() = 0;
198 
199     // Notifies to the audio driver to resume playback following a pause.
200     virtual status_t resume() = 0;
201 
202     // Returns whether drain operation is supported.
203     virtual status_t supportsDrain(bool *supportsDrain) = 0;
204 
205     // Requests notification when data buffered by the driver/hardware has been played.
206     virtual status_t drain(bool earlyNotify) = 0;
207 
208     // Notifies to the audio driver to flush (that is, drop) the queued data. Stream must
209     // already be paused before calling 'flush'.
210     virtual status_t flush() = 0;
211 
212     // Return a recent count of the number of audio frames presented to an external observer.
213     // This excludes frames which have been written but are still in the pipeline. See the
214     // table at the start of the 'StreamOutHalInterface' for the specification of the frame
215     // count behavior w.r.t. 'flush', 'drain' and 'standby' operations.
216     virtual status_t getPresentationPosition(uint64_t *frames, struct timespec *timestamp) = 0;
217 
218     // Notifies the HAL layer that the framework considers the current playback as completed.
219     virtual status_t presentationComplete() = 0;
220 
221     struct SourceMetadata {
222         std::vector<playback_track_metadata_v7_t> tracks;
223     };
224 
225     /**
226      * Called when the metadata of the stream's source has been changed.
227      * @param sourceMetadata Description of the audio that is played by the clients.
228      */
229     virtual status_t updateSourceMetadata(const SourceMetadata& sourceMetadata) = 0;
230 
231     // Returns the Dual Mono mode presentation setting.
232     virtual status_t getDualMonoMode(audio_dual_mono_mode_t* mode) = 0;
233 
234     // Sets the Dual Mono mode presentation on the output device.
235     virtual status_t setDualMonoMode(audio_dual_mono_mode_t mode) = 0;
236 
237     // Returns the Audio Description Mix level in dB.
238     virtual status_t getAudioDescriptionMixLevel(float* leveldB) = 0;
239 
240     // Sets the Audio Description Mix level in dB.
241     virtual status_t setAudioDescriptionMixLevel(float leveldB) = 0;
242 
243     // Retrieves current playback rate parameters.
244     virtual status_t getPlaybackRateParameters(audio_playback_rate_t* playbackRate) = 0;
245 
246     // Sets the playback rate parameters that control playback behavior.
247     virtual status_t setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) = 0;
248 
249     virtual status_t setEventCallback(const sp<StreamOutHalInterfaceEventCallback>& callback) = 0;
250 
251     /**
252      * Indicates the requested latency mode for this output stream.
253      *
254      * The requested mode can be one of the modes returned by
255      * getRecommendedLatencyModes() API.
256      *
257      * @param mode the requested latency mode.
258      * @return operation completion status.
259      */
260     virtual status_t setLatencyMode(audio_latency_mode_t mode) = 0;
261 
262     /**
263      * Indicates which latency modes are currently supported on this output stream.
264      * If the transport protocol (e.g Bluetooth A2DP) used by this output stream to reach
265      * the output device supports variable latency modes, the HAL indicates which
266      * modes are currently supported.
267      * The framework can then call setLatencyMode() with one of the supported modes to select
268      * the desired operation mode.
269      *
270      * @param modes currrently supported latency modes.
271      * @return operation completion status.
272      */
273     virtual status_t getRecommendedLatencyModes(std::vector<audio_latency_mode_t> *modes) = 0;
274 
275     /**
276      * Set the callback interface for notifying changes in supported latency modes.
277      *
278      * Calling this method with a null pointer will result in releasing
279      * the callback.
280      *
281      * @param callback the registered callback or null to unregister.
282      * @return operation completion status.
283      */
284     virtual status_t setLatencyModeCallback(
285             const sp<StreamOutHalInterfaceLatencyModeCallback>& callback) = 0;
286 
287     /**
288      * Signal the end of audio output, interrupting an ongoing 'write' operation.
289      */
290     virtual status_t exit() = 0;
291 
292   protected:
~StreamOutHalInterface()293     virtual ~StreamOutHalInterface() {}
294 };
295 
296 class StreamInHalInterface : public virtual StreamHalInterface {
297   public:
298     // Set the input gain for the audio driver.
299     virtual status_t setGain(float gain) = 0;
300 
301     // Read audio buffer in from driver.
302     virtual status_t read(void *buffer, size_t bytes, size_t *read) = 0;
303 
304     // Return the amount of input frames lost in the audio driver.
305     virtual status_t getInputFramesLost(uint32_t *framesLost) = 0;
306 
307     // Return a recent count of the number of audio frames received and
308     // the clock time associated with that frame count.
309     // The count must not reset to zero when a PCM input enters standby.
310     virtual status_t getCapturePosition(int64_t *frames, int64_t *time) = 0;
311 
312     // Get active microphones
313     virtual status_t getActiveMicrophones(std::vector<media::MicrophoneInfoFw> *microphones) = 0;
314 
315     // Set direction for capture processing
316     virtual status_t setPreferredMicrophoneDirection(audio_microphone_direction_t) = 0;
317 
318     // Set zoom factor for capture stream
319     virtual status_t setPreferredMicrophoneFieldDimension(float zoom) = 0;
320 
321     struct SinkMetadata {
322         std::vector<record_track_metadata_v7_t> tracks;
323     };
324     /**
325      * Called when the metadata of the stream's sink has been changed.
326      * @param sinkMetadata Description of the audio that is suggested by the clients.
327      */
328     virtual status_t updateSinkMetadata(const SinkMetadata& sinkMetadata) = 0;
329 
330   protected:
~StreamInHalInterface()331     virtual ~StreamInHalInterface() {}
332 };
333 
334 } // namespace android
335 
336 #endif // ANDROID_HARDWARE_STREAM_HAL_INTERFACE_H
337