1 /*
2  * Copyright 2022 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 #define LOG_TAG "BTAudioHearingAidAIDL"
18 
19 #include "hearing_aid_software_encoding_aidl.h"
20 
21 #include <bluetooth/log.h>
22 
23 #include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h"
24 #include "client_interface_aidl.h"
25 #include "osi/include/properties.h"
26 
27 namespace std {
28 template <>
29 struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {};
30 template <>
31 struct formatter<audio_content_type_t> : enum_formatter<audio_content_type_t> {};
32 }  // namespace std
33 
34 namespace {
35 
36 using ::aidl::android::hardware::bluetooth::audio::ChannelMode;
37 using ::aidl::android::hardware::bluetooth::audio::CodecType;
38 using ::bluetooth::audio::aidl::AudioConfiguration;
39 using ::bluetooth::audio::aidl::BluetoothAudioCtrlAck;
40 using ::bluetooth::audio::aidl::LatencyMode;
41 using ::bluetooth::audio::aidl::PcmConfiguration;
42 using ::bluetooth::audio::aidl::SessionType;
43 using ::bluetooth::audio::aidl::hearing_aid::StreamCallbacks;
44 using namespace bluetooth;
45 
46 // Transport implementation for Hearing Aids
47 class HearingAidTransport : public bluetooth::audio::aidl::IBluetoothSinkTransportInstance {
48 public:
HearingAidTransport(StreamCallbacks stream_cb)49   HearingAidTransport(StreamCallbacks stream_cb)
50       : IBluetoothSinkTransportInstance(SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH,
51                                         (AudioConfiguration){}),
52         stream_cb_(std::move(stream_cb)),
53         remote_delay_report_ms_(0),
54         total_bytes_read_(0),
55         data_position_({}) {}
56 
StartRequest(bool)57   BluetoothAudioCtrlAck StartRequest(bool /*is_low_latency*/) override {
58     log::info("");
59     if (stream_cb_.on_resume_(true)) {
60       return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
61     }
62     return BluetoothAudioCtrlAck::FAILURE;
63   }
64 
SuspendRequest()65   BluetoothAudioCtrlAck SuspendRequest() override {
66     log::info("");
67     if (stream_cb_.on_suspend_()) {
68       uint8_t p_buf[AUDIO_STREAM_OUTPUT_BUFFER_SZ * 2];
69       ::bluetooth::audio::aidl::hearing_aid::read(p_buf, sizeof(p_buf));
70       return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
71     } else {
72       return BluetoothAudioCtrlAck::FAILURE;
73     }
74   }
75 
StopRequest()76   void StopRequest() override {
77     log::info("");
78     if (stream_cb_.on_suspend_()) {
79       // flush
80       uint8_t p_buf[AUDIO_STREAM_OUTPUT_BUFFER_SZ * 2];
81       ::bluetooth::audio::aidl::hearing_aid::read(p_buf, sizeof(p_buf));
82     }
83   }
84 
SetLatencyMode(LatencyMode)85   void SetLatencyMode(LatencyMode /*latency_mode*/) override {}
86 
GetPresentationPosition(uint64_t * remote_delay_report_ns,uint64_t * total_bytes_read,timespec * data_position)87   bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read,
88                                timespec* data_position) override {
89     log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", total_bytes_read_,
90                  data_position_.tv_sec, data_position_.tv_nsec, remote_delay_report_ms_);
91     if (remote_delay_report_ns != nullptr) {
92       *remote_delay_report_ns = remote_delay_report_ms_ * 1000000u;
93     }
94     if (total_bytes_read != nullptr) {
95       *total_bytes_read = total_bytes_read_;
96     }
97     if (data_position != nullptr) {
98       *data_position = data_position_;
99     }
100 
101     return true;
102   }
103 
SourceMetadataChanged(const source_metadata_v7_t & source_metadata)104   void SourceMetadataChanged(const source_metadata_v7_t& source_metadata) override {
105     auto track_count = source_metadata.track_count;
106     auto tracks = source_metadata.tracks;
107     log::info("{} track(s) received", track_count);
108     while (track_count) {
109       log::verbose("usage={}, content_type={}, gain={}", tracks->base.usage,
110                    tracks->base.content_type, tracks->base.gain);
111       --track_count;
112       ++tracks;
113     }
114   }
115 
SinkMetadataChanged(const sink_metadata_v7_t &)116   void SinkMetadataChanged(const sink_metadata_v7_t&) override {}
117 
ResetPresentationPosition()118   void ResetPresentationPosition() override {
119     log::verbose("called.");
120     remote_delay_report_ms_ = 0;
121     total_bytes_read_ = 0;
122     data_position_ = {};
123   }
124 
LogBytesRead(size_t bytes_read)125   void LogBytesRead(size_t bytes_read) override {
126     if (bytes_read) {
127       total_bytes_read_ += bytes_read;
128       clock_gettime(CLOCK_MONOTONIC, &data_position_);
129     }
130   }
131 
SetRemoteDelay(uint16_t delay_report_ms)132   void SetRemoteDelay(uint16_t delay_report_ms) {
133     log::info("delay_report={} msec", delay_report_ms);
134     remote_delay_report_ms_ = delay_report_ms;
135   }
136 
137 private:
138   StreamCallbacks stream_cb_;
139   uint16_t remote_delay_report_ms_;
140   uint64_t total_bytes_read_;
141   timespec data_position_;
142 };
143 
HearingAidGetSelectedHalPcmConfig(PcmConfiguration * hal_pcm_config)144 bool HearingAidGetSelectedHalPcmConfig(PcmConfiguration* hal_pcm_config) {
145   if (hal_pcm_config == nullptr) {
146     return false;
147   }
148   // TODO: we only support one config for now!
149   hal_pcm_config->sampleRateHz = 16000;
150   hal_pcm_config->bitsPerSample = 16;
151   hal_pcm_config->channelMode = ChannelMode::STEREO;
152   return true;
153 }
154 
155 // Sink instance of Hearing Aids to provide call-in APIs for Bluetooth Audio Hal
156 HearingAidTransport* hearing_aid_sink = nullptr;
157 // Common interface to call-out into Bluetooth Audio Hal
158 bluetooth::audio::aidl::BluetoothAudioSinkClientInterface* hearing_aid_hal_clientinterface =
159         nullptr;
160 
161 // Save the value if the remote reports its delay before hearing_aid_sink is
162 // initialized
163 uint16_t remote_delay_ms = 0;
164 
165 }  // namespace
166 
167 namespace bluetooth {
168 namespace audio {
169 namespace aidl {
170 namespace hearing_aid {
171 
is_hal_enabled()172 bool is_hal_enabled() { return hearing_aid_hal_clientinterface != nullptr; }
173 
init(StreamCallbacks stream_cb,bluetooth::common::MessageLoopThread *)174 bool init(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* /*message_loop*/) {
175   log::info("");
176 
177   if (!BluetoothAudioClientInterface::is_aidl_available()) {
178     log::error("BluetoothAudio AIDL implementation does not exist");
179     return false;
180   }
181 
182   hearing_aid_sink = new HearingAidTransport(std::move(stream_cb));
183   hearing_aid_hal_clientinterface =
184           new bluetooth::audio::aidl::BluetoothAudioSinkClientInterface(hearing_aid_sink);
185   if (!hearing_aid_hal_clientinterface->IsValid()) {
186     log::warn("BluetoothAudio HAL for Hearing Aid is invalid?!");
187     delete hearing_aid_hal_clientinterface;
188     hearing_aid_hal_clientinterface = nullptr;
189     delete hearing_aid_sink;
190     hearing_aid_sink = nullptr;
191     return false;
192   }
193 
194   if (remote_delay_ms != 0) {
195     log::info("restore DELAY {} ms", remote_delay_ms);
196     hearing_aid_sink->SetRemoteDelay(remote_delay_ms);
197     remote_delay_ms = 0;
198   }
199 
200   return true;
201 }
202 
cleanup()203 void cleanup() {
204   log::info("");
205   if (!is_hal_enabled()) {
206     return;
207   }
208   end_session();
209   delete hearing_aid_hal_clientinterface;
210   hearing_aid_hal_clientinterface = nullptr;
211   delete hearing_aid_sink;
212   hearing_aid_sink = nullptr;
213   remote_delay_ms = 0;
214 }
215 
start_session()216 void start_session() {
217   log::info("");
218   if (!is_hal_enabled()) {
219     return;
220   }
221   AudioConfiguration audio_config;
222   PcmConfiguration pcm_config{};
223   if (!HearingAidGetSelectedHalPcmConfig(&pcm_config)) {
224     log::error("cannot get PCM config");
225     return;
226   }
227   audio_config.set<AudioConfiguration::pcmConfig>(pcm_config);
228   if (!hearing_aid_hal_clientinterface->UpdateAudioConfig(audio_config)) {
229     log::error("cannot update audio config to HAL");
230     return;
231   }
232   hearing_aid_hal_clientinterface->StartSession();
233 }
234 
end_session()235 void end_session() {
236   log::info("");
237   if (!is_hal_enabled()) {
238     return;
239   }
240   hearing_aid_hal_clientinterface->EndSession();
241 }
242 
read(uint8_t * p_buf,uint32_t len)243 size_t read(uint8_t* p_buf, uint32_t len) {
244   if (!is_hal_enabled()) {
245     return 0;
246   }
247   return hearing_aid_hal_clientinterface->ReadAudioData(p_buf, len);
248 }
249 
250 // Update Hearing Aids delay report to BluetoothAudio HAL
set_remote_delay(uint16_t delay_report_ms)251 void set_remote_delay(uint16_t delay_report_ms) {
252   if (!is_hal_enabled()) {
253     log::info("not ready for DelayReport {} ms", delay_report_ms);
254     remote_delay_ms = delay_report_ms;
255     return;
256   }
257   log::info("delay_report_ms={} ms", delay_report_ms);
258   hearing_aid_sink->SetRemoteDelay(delay_report_ms);
259 }
260 
261 }  // namespace hearing_aid
262 }  // namespace aidl
263 }  // namespace audio
264 }  // namespace bluetooth
265