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_HIDL_H
18 #define ANDROID_HARDWARE_STREAM_HAL_HIDL_H
19 
20 #include <atomic>
21 #include <mutex>
22 
23 #include PATH(android/hardware/audio/CORE_TYPES_FILE_VERSION/IStream.h)
24 #include PATH(android/hardware/audio/CORE_TYPES_FILE_VERSION/IStreamIn.h)
25 #include PATH(android/hardware/audio/FILE_VERSION/IStreamOut.h)
26 #include <android-base/thread_annotations.h>
27 #include <fmq/EventFlag.h>
28 #include <fmq/MessageQueue.h>
29 #include <media/audiohal/EffectHalInterface.h>
30 #include <media/audiohal/StreamHalInterface.h>
31 #include <mediautils/Synchronization.h>
32 
33 #include "CoreConversionHelperHidl.h"
34 #include "StreamPowerLog.h"
35 
36 using ::android::hardware::audio::CORE_TYPES_CPP_VERSION::IStream;
37 using ::android::hardware::EventFlag;
38 using ::android::hardware::MessageQueue;
39 using ::android::hardware::Return;
40 using ReadParameters =
41         ::android::hardware::audio::CORE_TYPES_CPP_VERSION::IStreamIn::ReadParameters;
42 using ReadStatus = ::android::hardware::audio::CORE_TYPES_CPP_VERSION::IStreamIn::ReadStatus;
43 using WriteCommand = ::android::hardware::audio::CPP_VERSION::IStreamOut::WriteCommand;
44 using WriteStatus = ::android::hardware::audio::CPP_VERSION::IStreamOut::WriteStatus;
45 
46 namespace android {
47 
48 class DeviceHalHidl;
49 
50 class StreamHalHidl : public virtual StreamHalInterface, public CoreConversionHelperHidl
51 {
52   public:
53     // Return size of input/output buffer in bytes for this stream - eg. 4800.
54     virtual status_t getBufferSize(size_t *size);
55 
56     // Return the base configuration of the stream:
57     //   - channel mask;
58     //   - format - e.g. AUDIO_FORMAT_PCM_16_BIT;
59     //   - sampling rate in Hz - eg. 44100.
60     virtual status_t getAudioProperties(audio_config_base_t *configBase);
61 
62     // Set audio stream parameters.
63     virtual status_t setParameters(const String8& kvPairs);
64 
65     // Get audio stream parameters.
66     virtual status_t getParameters(const String8& keys, String8 *values);
67 
68     // Add or remove the effect on the stream.
69     virtual status_t addEffect(sp<EffectHalInterface> effect);
70     virtual status_t removeEffect(sp<EffectHalInterface> effect);
71 
72     // Put the audio hardware input/output into standby mode.
73     virtual status_t standby();
74 
75     virtual status_t dump(int fd, const Vector<String16>& args) override;
76 
77     // Start a stream operating in mmap mode.
78     virtual status_t start();
79 
80     // Stop a stream operating in mmap mode.
81     virtual status_t stop();
82 
83     // Retrieve information on the data buffer in mmap mode.
84     virtual status_t createMmapBuffer(int32_t minSizeFrames,
85                                       struct audio_mmap_buffer_info *info);
86 
87     // Get current read/write position in the mmap buffer
88     virtual status_t getMmapPosition(struct audio_mmap_position *position);
89 
90     // Set the priority of the thread that interacts with the HAL
91     // (must match the priority of the audioflinger's thread that calls 'read' / 'write')
92     virtual status_t setHalThreadPriority(int priority);
93 
94     status_t legacyCreateAudioPatch(const struct audio_port_config& port,
95                                             std::optional<audio_source_t> source,
96                                             audio_devices_t type) override;
97 
98     status_t legacyReleaseAudioPatch() override;
99 
100   protected:
101     // Subclasses can not be constructed directly by clients.
102     StreamHalHidl(std::string_view className, IStream *stream);
103 
104     ~StreamHalHidl() override;
105 
106     status_t getCachedBufferSize(size_t *size);
107 
108     status_t getHalPid(pid_t *pid);
109 
110     bool requestHalThreadPriority(pid_t threadPid, pid_t threadId);
111 
112     // mStreamPowerLog is used for audio signal power logging.
113     StreamPowerLog mStreamPowerLog;
114 
115   private:
116     const int HAL_THREAD_PRIORITY_DEFAULT = -1;
117     IStream * const mStream;
118     int mHalThreadPriority;
119     size_t mCachedBufferSize;
120 };
121 
122 class StreamOutHalHidl : public StreamOutHalInterface, public StreamHalHidl {
123   public:
124     // Put the audio hardware input/output into standby mode (from StreamHalInterface).
125     status_t standby() override;
126 
127     // Return the frame size (number of bytes per sample) of a stream.
128     virtual status_t getFrameSize(size_t *size);
129 
130     // Return the audio hardware driver estimated latency in milliseconds.
131     virtual status_t getLatency(uint32_t *latency);
132 
133     // Use this method in situations where audio mixing is done in the hardware.
134     virtual status_t setVolume(float left, float right);
135 
136     // Selects the audio presentation (if available).
137     virtual status_t selectPresentation(int presentationId, int programId);
138 
139     // Write audio buffer to driver.
140     virtual status_t write(const void *buffer, size_t bytes, size_t *written);
141 
142     // Return the number of audio frames written by the audio dsp to DAC since
143     // the output has exited standby.
144     virtual status_t getRenderPosition(uint64_t *dspFrames);
145 
146     // Set the callback for notifying completion of non-blocking write and drain.
147     virtual status_t setCallback(wp<StreamOutHalInterfaceCallback> callback);
148 
149     // Returns whether pause and resume operations are supported.
150     virtual status_t supportsPauseAndResume(bool *supportsPause, bool *supportsResume);
151 
152     // Notifies to the audio driver to resume playback following a pause.
153     virtual status_t pause();
154 
155     // Notifies to the audio driver to resume playback following a pause.
156     virtual status_t resume();
157 
158     // Returns whether drain operation is supported.
159     virtual status_t supportsDrain(bool *supportsDrain);
160 
161     // Requests notification when data buffered by the driver/hardware has been played.
162     virtual status_t drain(bool earlyNotify);
163 
164     // Notifies to the audio driver to flush (that is, drop) the queued data. Stream must
165     // already be paused before calling 'flush'.
166     virtual status_t flush();
167 
168     // Return a recent count of the number of audio frames presented to an external observer.
169     // This excludes frames which have been written but are still in the pipeline. See the
170     // table at the start of the 'StreamOutHalInterface' for the specification of the frame
171     // count behavior w.r.t. 'flush', 'drain' and 'standby' operations.
172     virtual status_t getPresentationPosition(uint64_t *frames, struct timespec *timestamp);
173 
174     // Notifies the HAL layer that the framework considers the current playback as completed.
175     status_t presentationComplete() override;
176 
177     // Called when the metadata of the stream's source has been changed.
178     status_t updateSourceMetadata(const SourceMetadata& sourceMetadata) override;
179 
180     // Methods used by StreamOutCallback (HIDL).
181     void onWriteReady();
182     void onDrainReady();
183     void onError();
184 
185     // Returns the Dual Mono mode presentation setting.
186     status_t getDualMonoMode(audio_dual_mono_mode_t* mode) override;
187 
188     // Sets the Dual Mono mode presentation on the output device.
189     status_t setDualMonoMode(audio_dual_mono_mode_t mode) override;
190 
191     // Returns the Audio Description Mix level in dB.
192     status_t getAudioDescriptionMixLevel(float* leveldB) override;
193 
194     // Sets the Audio Description Mix level in dB.
195     status_t setAudioDescriptionMixLevel(float leveldB) override;
196 
197     // Retrieves current playback rate parameters.
198     status_t getPlaybackRateParameters(audio_playback_rate_t* playbackRate) override;
199 
200     // Sets the playback rate parameters that control playback behavior.
201     status_t setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) override;
202 
203     status_t setEventCallback(const sp<StreamOutHalInterfaceEventCallback>& callback) override;
204 
205     // Methods used by StreamCodecFormatCallback (HIDL).
206     void onCodecFormatChanged(const std::vector<uint8_t>& metadataBs);
207 
208     status_t setLatencyMode(audio_latency_mode_t mode) override;
209     status_t getRecommendedLatencyModes(std::vector<audio_latency_mode_t> *modes) override;
210     status_t setLatencyModeCallback(
211             const sp<StreamOutHalInterfaceLatencyModeCallback>& callback) override;
212 
213     void onRecommendedLatencyModeChanged(const std::vector<audio_latency_mode_t>& modes);
214 
215     status_t exit() override;
216 
217   private:
218     friend class DeviceHalHidl;
219     typedef MessageQueue<WriteCommand, hardware::kSynchronizedReadWrite> CommandMQ;
220     typedef MessageQueue<uint8_t, hardware::kSynchronizedReadWrite> DataMQ;
221     typedef MessageQueue<WriteStatus, hardware::kSynchronizedReadWrite> StatusMQ;
222 
223     mediautils::atomic_wp<StreamOutHalInterfaceCallback> mCallback;
224     mediautils::atomic_wp<StreamOutHalInterfaceEventCallback> mEventCallback;
225     mediautils::atomic_wp<StreamOutHalInterfaceLatencyModeCallback> mLatencyModeCallback;
226 
227     const sp<::android::hardware::audio::CPP_VERSION::IStreamOut> mStream;
228     std::unique_ptr<CommandMQ> mCommandMQ;
229     std::unique_ptr<DataMQ> mDataMQ;
230     std::unique_ptr<StatusMQ> mStatusMQ;
231     std::atomic<pid_t> mWriterClient;
232     EventFlag* mEfGroup;
233     std::mutex mPositionMutex;
234     // Used to expand correctly the 32-bit position from the HAL.
235     uint64_t mRenderPosition GUARDED_BY(mPositionMutex) = 0;
236     bool mExpectRetrograde GUARDED_BY(mPositionMutex) = false; // See 'presentationComplete'.
237 
238     // Can not be constructed directly by clients.
239     StreamOutHalHidl(const sp<::android::hardware::audio::CPP_VERSION::IStreamOut>& stream);
240 
241     virtual ~StreamOutHalHidl();
242 
243     using WriterCallback = std::function<void(const WriteStatus& writeStatus)>;
244     status_t callWriterThread(
245             WriteCommand cmd, const char* cmdName,
246             const uint8_t* data, size_t dataSize, WriterCallback callback);
247     status_t prepareForWriting(size_t bufferSize);
248 };
249 
250 class StreamInHalHidl : public StreamInHalInterface, public StreamHalHidl {
251   public:
252     // Return the frame size (number of bytes per sample) of a stream.
253     virtual status_t getFrameSize(size_t *size);
254 
255     // Set the input gain for the audio driver.
256     virtual status_t setGain(float gain);
257 
258     // Read audio buffer in from driver.
259     virtual status_t read(void *buffer, size_t bytes, size_t *read);
260 
261     // Return the amount of input frames lost in the audio driver.
262     virtual status_t getInputFramesLost(uint32_t *framesLost);
263 
264     // Return a recent count of the number of audio frames received and
265     // the clock time associated with that frame count.
266     // The count must not reset to zero when a PCM input enters standby.
267     virtual status_t getCapturePosition(int64_t *frames, int64_t *time);
268 
269     // Get active microphones
270     status_t getActiveMicrophones(std::vector<media::MicrophoneInfoFw> *microphones) override;
271 
272     // Set microphone direction (for processing)
273     virtual status_t setPreferredMicrophoneDirection(
274                             audio_microphone_direction_t direction) override;
275 
276     // Set microphone zoom (for processing)
277     virtual status_t setPreferredMicrophoneFieldDimension(float zoom) override;
278 
279     // Called when the metadata of the stream's sink has been changed.
280     status_t updateSinkMetadata(const SinkMetadata& sinkMetadata) override;
281 
282   private:
283     friend class DeviceHalHidl;
284     typedef MessageQueue<ReadParameters, hardware::kSynchronizedReadWrite> CommandMQ;
285     typedef MessageQueue<uint8_t, hardware::kSynchronizedReadWrite> DataMQ;
286     typedef MessageQueue<ReadStatus, hardware::kSynchronizedReadWrite> StatusMQ;
287 
288     const sp<::android::hardware::audio::CORE_TYPES_CPP_VERSION::IStreamIn> mStream;
289     std::unique_ptr<CommandMQ> mCommandMQ;
290     std::unique_ptr<DataMQ> mDataMQ;
291     std::unique_ptr<StatusMQ> mStatusMQ;
292     std::atomic<pid_t> mReaderClient;
293     EventFlag* mEfGroup;
294 
295     // Can not be constructed directly by clients.
296     StreamInHalHidl(
297             const sp<::android::hardware::audio::CORE_TYPES_CPP_VERSION::IStreamIn>& stream);
298 
299     virtual ~StreamInHalHidl();
300 
301     using ReaderCallback = std::function<void(const ReadStatus& readStatus)>;
302     status_t callReaderThread(
303             const ReadParameters& params, const char* cmdName, ReaderCallback callback);
304     status_t prepareForReading(size_t bufferSize);
305 };
306 
307 } // namespace android
308 
309 #endif // ANDROID_HARDWARE_STREAM_HAL_HIDL_H
310