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 #define LOG_TAG "BTAudioA2dpAIDL"
17 
18 #include "a2dp_encoding_aidl.h"
19 
20 #include <bluetooth/log.h>
21 #include <com_android_bluetooth_flags.h>
22 
23 #include <vector>
24 
25 #include "a2dp_provider_info.h"
26 #include "audio_aidl_interfaces.h"
27 #include "client_interface_aidl.h"
28 #include "codec_status_aidl.h"
29 #include "transport_instance.h"
30 
31 typedef enum {
32   A2DP_CTRL_CMD_NONE,
33   A2DP_CTRL_CMD_CHECK_READY,
34   A2DP_CTRL_CMD_START,
35   A2DP_CTRL_CMD_STOP,
36   A2DP_CTRL_CMD_SUSPEND,
37   A2DP_CTRL_GET_INPUT_AUDIO_CONFIG,
38   A2DP_CTRL_GET_OUTPUT_AUDIO_CONFIG,
39   A2DP_CTRL_SET_OUTPUT_AUDIO_CONFIG,
40   A2DP_CTRL_GET_PRESENTATION_POSITION,
41 } tA2DP_CTRL_CMD;
42 
43 namespace std {
44 template <>
45 struct formatter<tA2DP_CTRL_CMD> : enum_formatter<tA2DP_CTRL_CMD> {};
46 template <>
47 struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {};
48 template <>
49 struct formatter<audio_content_type_t> : enum_formatter<audio_content_type_t> {};
50 }  // namespace std
51 
52 namespace bluetooth {
53 namespace audio {
54 namespace aidl {
55 namespace a2dp {
56 
57 namespace {
58 
59 using ::bluetooth::audio::a2dp::Status;
60 using ::bluetooth::audio::aidl::a2dp::LatencyMode;
61 
62 // Provide call-in APIs for the Bluetooth Audio HAL
63 class A2dpTransport : public ::bluetooth::audio::aidl::a2dp::IBluetoothTransportInstance {
64 public:
65   A2dpTransport(SessionType sessionType);
66 
67   Status StartRequest(bool is_low_latency) override;
68 
69   Status SuspendRequest() override;
70 
71   void StopRequest() override;
72 
73   void SetLatencyMode(LatencyMode latency_mode) override;
74 
75   bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read,
76                                timespec* data_position) override;
77 
78   tA2DP_CTRL_CMD GetPendingCmd() const;
79 
80   void ResetPendingCmd();
81 
82   void ResetPresentationPosition();
83 
84   void LogBytesRead(size_t bytes_read) override;
85 
86   // delay reports from AVDTP is based on 1/10 ms (100us)
87   void SetRemoteDelay(uint16_t delay_report);
88 
89 private:
90   static tA2DP_CTRL_CMD a2dp_pending_cmd_;
91   static uint16_t remote_delay_report_;
92   uint64_t total_bytes_read_;
93   timespec data_position_;
94 };
95 
96 }  // namespace
97 
98 using ::bluetooth::audio::a2dp::Status;
99 using ::bluetooth::audio::a2dp::StreamCallbacks;
100 
101 static StreamCallbacks null_stream_callbacks_;
102 static StreamCallbacks const* stream_callbacks_ = &null_stream_callbacks_;
103 
104 namespace {
105 
106 using ::aidl::android::hardware::bluetooth::audio::A2dpStreamConfiguration;
107 using ::aidl::android::hardware::bluetooth::audio::AudioConfiguration;
108 using ::aidl::android::hardware::bluetooth::audio::ChannelMode;
109 using ::aidl::android::hardware::bluetooth::audio::CodecConfiguration;
110 using ::aidl::android::hardware::bluetooth::audio::PcmConfiguration;
111 using ::aidl::android::hardware::bluetooth::audio::SessionType;
112 
113 using ::bluetooth::audio::aidl::a2dp::BluetoothAudioClientInterface;
114 using ::bluetooth::audio::aidl::a2dp::codec::A2dpAacToHalConfig;
115 using ::bluetooth::audio::aidl::a2dp::codec::A2dpAptxToHalConfig;
116 using ::bluetooth::audio::aidl::a2dp::codec::A2dpCodecToHalBitsPerSample;
117 using ::bluetooth::audio::aidl::a2dp::codec::A2dpCodecToHalChannelMode;
118 using ::bluetooth::audio::aidl::a2dp::codec::A2dpCodecToHalSampleRate;
119 using ::bluetooth::audio::aidl::a2dp::codec::A2dpLdacToHalConfig;
120 using ::bluetooth::audio::aidl::a2dp::codec::A2dpOpusToHalConfig;
121 using ::bluetooth::audio::aidl::a2dp::codec::A2dpSbcToHalConfig;
122 
123 /***
124  *
125  * A2dpTransport functions and variables
126  *
127  ***/
128 
129 tA2DP_CTRL_CMD A2dpTransport::a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
130 
131 uint16_t A2dpTransport::remote_delay_report_ = 0;
132 
A2dpTransport(SessionType sessionType)133 A2dpTransport::A2dpTransport(SessionType sessionType)
134     : IBluetoothTransportInstance(sessionType, (AudioConfiguration){}),
135       total_bytes_read_(0),
136       data_position_({}) {
137   a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
138   remote_delay_report_ = 0;
139 }
140 
StartRequest(bool is_low_latency)141 Status A2dpTransport::StartRequest(bool is_low_latency) {
142   // Check if a previous Start request is ongoing.
143   if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_START) {
144     log::warn("unable to start stream: already pending");
145     return Status::PENDING;
146   }
147 
148   // Check if a different request is ongoing.
149   if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
150     log::warn("unable to start stream: busy with pending command {}", a2dp_pending_cmd_);
151     return Status::FAILURE;
152   }
153 
154   log::info("");
155 
156   auto status = stream_callbacks_->StartStream(is_low_latency);
157   a2dp_pending_cmd_ = status == Status::PENDING ? A2DP_CTRL_CMD_START : A2DP_CTRL_CMD_NONE;
158 
159   return status;
160 }
161 
SuspendRequest()162 Status A2dpTransport::SuspendRequest() {
163   // Check if a previous Suspend request is ongoing.
164   if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_SUSPEND) {
165     log::warn("unable to suspend stream: already pending");
166     return Status::PENDING;
167   }
168 
169   // Check if a different request is ongoing.
170   if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
171     log::warn("unable to suspend stream: busy with pending command {}", a2dp_pending_cmd_);
172     return Status::FAILURE;
173   }
174 
175   log::info("");
176 
177   auto status = stream_callbacks_->SuspendStream();
178   a2dp_pending_cmd_ = status == Status::PENDING ? A2DP_CTRL_CMD_SUSPEND : A2DP_CTRL_CMD_NONE;
179 
180   return status;
181 }
182 
StopRequest()183 void A2dpTransport::StopRequest() {
184   log::info("");
185 
186   auto status = stream_callbacks_->StopStream();
187   a2dp_pending_cmd_ = status == Status::PENDING ? A2DP_CTRL_CMD_STOP : A2DP_CTRL_CMD_NONE;
188 }
189 
SetLatencyMode(LatencyMode latency_mode)190 void A2dpTransport::SetLatencyMode(LatencyMode latency_mode) {
191   stream_callbacks_->SetLatencyMode(latency_mode == LatencyMode::LOW_LATENCY);
192 }
193 
GetPresentationPosition(uint64_t * remote_delay_report_ns,uint64_t * total_bytes_read,timespec * data_position)194 bool A2dpTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns,
195                                             uint64_t* total_bytes_read, timespec* data_position) {
196   *remote_delay_report_ns = remote_delay_report_ * 100000u;
197   *total_bytes_read = total_bytes_read_;
198   *data_position = data_position_;
199   log::verbose("delay={}/10ms, data={} byte(s), timestamp={}.{}s", remote_delay_report_,
200                total_bytes_read_, data_position_.tv_sec, data_position_.tv_nsec);
201   return true;
202 }
203 
GetPendingCmd() const204 tA2DP_CTRL_CMD A2dpTransport::GetPendingCmd() const { return a2dp_pending_cmd_; }
205 
ResetPendingCmd()206 void A2dpTransport::ResetPendingCmd() { a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE; }
207 
ResetPresentationPosition()208 void A2dpTransport::ResetPresentationPosition() {
209   remote_delay_report_ = 0;
210   total_bytes_read_ = 0;
211   data_position_ = {};
212 }
213 
LogBytesRead(size_t bytes_read)214 void A2dpTransport::LogBytesRead(size_t bytes_read) {
215   if (bytes_read != 0) {
216     total_bytes_read_ += bytes_read;
217     clock_gettime(CLOCK_MONOTONIC, &data_position_);
218   }
219 }
220 
221 /***
222  *
223  * Global functions and variables
224  *
225  ***/
226 
227 // delay reports from AVDTP is based on 1/10 ms (100us)
SetRemoteDelay(uint16_t delay_report)228 void A2dpTransport::SetRemoteDelay(uint16_t delay_report) { remote_delay_report_ = delay_report; }
229 
230 // Common interface to call-out into Bluetooth Audio HAL
231 BluetoothAudioClientInterface* software_hal_interface = nullptr;
232 BluetoothAudioClientInterface* offloading_hal_interface = nullptr;
233 BluetoothAudioClientInterface* active_hal_interface = nullptr;
234 
235 // ProviderInfo for A2DP hardware offload encoding and decoding data paths,
236 // if supported by the HAL and enabled. nullptr if not supported
237 // or disabled.
238 std::unique_ptr<::bluetooth::audio::aidl::a2dp::ProviderInfo> provider_info;
239 
240 // Save the value if the remote reports its delay before this interface is
241 // initialized
242 uint16_t remote_delay = 0;
243 
244 bool is_low_latency_mode_allowed = false;
245 
a2dp_get_selected_hal_codec_config(A2dpCodecConfig * a2dp_config,uint16_t peer_mtu,CodecConfiguration * codec_config)246 bool a2dp_get_selected_hal_codec_config(A2dpCodecConfig* a2dp_config, uint16_t peer_mtu,
247                                         CodecConfiguration* codec_config) {
248   btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig();
249   switch (current_codec.codec_type) {
250     case BTAV_A2DP_CODEC_INDEX_SOURCE_SBC:
251       [[fallthrough]];
252     case BTAV_A2DP_CODEC_INDEX_SINK_SBC: {
253       if (!A2dpSbcToHalConfig(codec_config, a2dp_config)) {
254         return false;
255       }
256       break;
257     }
258     case BTAV_A2DP_CODEC_INDEX_SOURCE_AAC:
259       [[fallthrough]];
260     case BTAV_A2DP_CODEC_INDEX_SINK_AAC: {
261       if (!A2dpAacToHalConfig(codec_config, a2dp_config)) {
262         return false;
263       }
264       break;
265     }
266     case BTAV_A2DP_CODEC_INDEX_SOURCE_APTX:
267       [[fallthrough]];
268     case BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD: {
269       if (!A2dpAptxToHalConfig(codec_config, a2dp_config)) {
270         return false;
271       }
272       break;
273     }
274     case BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC: {
275       if (!A2dpLdacToHalConfig(codec_config, a2dp_config)) {
276         return false;
277       }
278       break;
279     }
280     case BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS: {
281       if (!A2dpOpusToHalConfig(codec_config, a2dp_config)) {
282         return false;
283       }
284       break;
285     }
286     case BTAV_A2DP_CODEC_INDEX_MAX:
287       [[fallthrough]];
288     default:
289       log::error("Unknown codec_type={}", current_codec.codec_type);
290       return false;
291   }
292   codec_config->encodedAudioBitrate = a2dp_config->getTrackBitRate();
293   codec_config->peerMtu = peer_mtu;
294   log::info("CodecConfiguration={}", codec_config->toString());
295   return true;
296 }
297 
a2dp_get_selected_hal_pcm_config(A2dpCodecConfig * a2dp_codec_configs,int preferred_encoding_interval_us,PcmConfiguration * pcm_config)298 static bool a2dp_get_selected_hal_pcm_config(A2dpCodecConfig* a2dp_codec_configs,
299                                              int preferred_encoding_interval_us,
300                                              PcmConfiguration* pcm_config) {
301   if (pcm_config == nullptr) {
302     return false;
303   }
304 
305   btav_a2dp_codec_config_t current_codec = a2dp_codec_configs->getCodecConfig();
306   pcm_config->sampleRateHz = A2dpCodecToHalSampleRate(current_codec);
307   pcm_config->bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec);
308   pcm_config->channelMode = A2dpCodecToHalChannelMode(current_codec);
309 
310   if (com::android::bluetooth::flags::a2dp_aidl_encoding_interval()) {
311     pcm_config->dataIntervalUs = preferred_encoding_interval_us;
312   }
313 
314   return pcm_config->sampleRateHz > 0 && pcm_config->bitsPerSample > 0 &&
315          pcm_config->channelMode != ChannelMode::UNKNOWN;
316 }
317 
318 }  // namespace
319 
update_codec_offloading_capabilities(const std::vector<btav_a2dp_codec_config_t> & framework_preference,bool supports_a2dp_hw_offload_v2)320 bool update_codec_offloading_capabilities(
321         const std::vector<btav_a2dp_codec_config_t>& framework_preference,
322         bool supports_a2dp_hw_offload_v2) {
323   /* Load the provider information if supported by the HAL. */
324   provider_info = ::bluetooth::audio::aidl::a2dp::ProviderInfo::GetProviderInfo(
325           supports_a2dp_hw_offload_v2);
326   return ::bluetooth::audio::aidl::a2dp::codec::UpdateOffloadingCapabilities(framework_preference);
327 }
328 
329 // Checking if new bluetooth_audio is enabled
is_hal_enabled()330 bool is_hal_enabled() { return active_hal_interface != nullptr; }
331 
332 // Check if new bluetooth_audio is running with offloading encoders
is_hal_offloading()333 bool is_hal_offloading() {
334   if (!is_hal_enabled()) {
335     return false;
336   }
337   return active_hal_interface->GetTransportInstance()->GetSessionType() ==
338          SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH;
339 }
340 
341 // Opens the HAL client interface of the specified session type and check
342 // that is is valid. Returns nullptr if the client interface did not open
343 // properly.
new_hal_interface(SessionType session_type)344 static BluetoothAudioClientInterface* new_hal_interface(SessionType session_type) {
345   auto a2dp_transport = new A2dpTransport(session_type);
346   auto hal_interface = new BluetoothAudioClientInterface(a2dp_transport);
347   if (hal_interface->IsValid()) {
348     return hal_interface;
349   } else {
350     log::error("BluetoothAudio HAL for a2dp is invalid");
351     delete a2dp_transport;
352     delete hal_interface;
353     return nullptr;
354   }
355 }
356 
357 /// Delete the selected HAL client interface.
delete_hal_interface(BluetoothAudioClientInterface * hal_interface)358 static void delete_hal_interface(BluetoothAudioClientInterface* hal_interface) {
359   if (hal_interface == nullptr) {
360     return;
361   }
362   auto a2dp_transport = static_cast<A2dpTransport*>(hal_interface->GetTransportInstance());
363   delete a2dp_transport;
364   delete hal_interface;
365 }
366 
367 // Initialize BluetoothAudio HAL: openProvider
init(bluetooth::common::MessageLoopThread *,StreamCallbacks const * stream_callbacks,bool offload_enabled)368 bool init(bluetooth::common::MessageLoopThread* /*message_loop*/,
369           StreamCallbacks const* stream_callbacks, bool offload_enabled) {
370   log::info("");
371   log::assert_that(stream_callbacks != nullptr, "stream_callbacks != nullptr");
372 
373   if (software_hal_interface != nullptr) {
374     return true;
375   }
376 
377   if (!BluetoothAudioClientInterface::is_aidl_available()) {
378     log::error("BluetoothAudio AIDL implementation does not exist");
379     return false;
380   }
381 
382   software_hal_interface = new_hal_interface(SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH);
383   if (software_hal_interface == nullptr) {
384     return false;
385   }
386 
387   if (offload_enabled && offloading_hal_interface == nullptr) {
388     offloading_hal_interface =
389             new_hal_interface(SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH);
390     if (offloading_hal_interface == nullptr) {
391       delete_hal_interface(software_hal_interface);
392       software_hal_interface = nullptr;
393       return false;
394     }
395   }
396 
397   stream_callbacks_ = stream_callbacks;
398   active_hal_interface =
399           (offloading_hal_interface != nullptr ? offloading_hal_interface : software_hal_interface);
400 
401   if (remote_delay != 0) {
402     log::info("restore DELAY {} ms", static_cast<float>(remote_delay / 10.0));
403     static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance())
404             ->SetRemoteDelay(remote_delay);
405     remote_delay = 0;
406   }
407   return true;
408 }
409 
410 // Clean up BluetoothAudio HAL
cleanup()411 void cleanup() {
412   if (!is_hal_enabled()) {
413     return;
414   }
415   end_session();
416 
417   auto a2dp_sink = active_hal_interface->GetTransportInstance();
418   static_cast<A2dpTransport*>(a2dp_sink)->ResetPendingCmd();
419   static_cast<A2dpTransport*>(a2dp_sink)->ResetPresentationPosition();
420   active_hal_interface = nullptr;
421 
422   a2dp_sink = software_hal_interface->GetTransportInstance();
423   delete software_hal_interface;
424   software_hal_interface = nullptr;
425   delete a2dp_sink;
426   if (offloading_hal_interface != nullptr) {
427     a2dp_sink = offloading_hal_interface->GetTransportInstance();
428     delete offloading_hal_interface;
429     offloading_hal_interface = nullptr;
430     delete a2dp_sink;
431   }
432 
433   stream_callbacks_ = &null_stream_callbacks_;
434   remote_delay = 0;
435 }
436 
437 // Set up the codec into BluetoothAudio HAL
setup_codec(A2dpCodecConfig * a2dp_config,uint16_t peer_mtu,int preferred_encoding_interval_us)438 bool setup_codec(A2dpCodecConfig* a2dp_config, uint16_t peer_mtu,
439                  int preferred_encoding_interval_us) {
440   log::assert_that(a2dp_config != nullptr, "received invalid codec configuration");
441 
442   if (!is_hal_enabled()) {
443     log::error("BluetoothAudio HAL is not enabled");
444     return false;
445   }
446 
447   if (provider::supports_codec(a2dp_config->codecIndex())) {
448     // The codec is supported in the provider info (AIDL v4).
449     // In this case, the codec is offloaded, and the configuration passed
450     // as A2dpStreamConfiguration to the UpdateAudioConfig() interface
451     // method.
452     uint8_t codec_info[AVDT_CODEC_SIZE];
453     A2dpStreamConfiguration a2dp_stream_configuration;
454 
455     a2dp_config->copyOutOtaCodecConfig(codec_info);
456     a2dp_stream_configuration.peerMtu = peer_mtu;
457     a2dp_stream_configuration.codecId =
458             provider_info->GetCodec(a2dp_config->codecIndex()).value()->id;
459 
460     size_t parameters_start = 0;
461     size_t parameters_end = 0;
462     switch (a2dp_config->codecIndex()) {
463       case BTAV_A2DP_CODEC_INDEX_SOURCE_SBC:
464       case BTAV_A2DP_CODEC_INDEX_SOURCE_AAC:
465         parameters_start = 3;
466         parameters_end = 1 + codec_info[0];
467         break;
468       default:
469         parameters_start = 9;
470         parameters_end = 1 + codec_info[0];
471         break;
472     }
473 
474     a2dp_stream_configuration.configuration.insert(a2dp_stream_configuration.configuration.end(),
475                                                    codec_info + parameters_start,
476                                                    codec_info + parameters_end);
477 
478     if (!is_hal_offloading()) {
479       log::warn("Switching BluetoothAudio HAL to Hardware");
480       end_session();
481       active_hal_interface = offloading_hal_interface;
482     }
483 
484     return active_hal_interface->UpdateAudioConfig(AudioConfiguration(a2dp_stream_configuration));
485   }
486 
487   // Fallback to legacy offloading path.
488   CodecConfiguration codec_config{};
489 
490   if (!a2dp_get_selected_hal_codec_config(a2dp_config, peer_mtu, &codec_config)) {
491     log::error("Failed to get CodecConfiguration");
492     return false;
493   }
494 
495   bool should_codec_offloading =
496           bluetooth::audio::aidl::a2dp::codec::IsCodecOffloadingEnabled(codec_config);
497   if (should_codec_offloading && !is_hal_offloading()) {
498     log::warn("Switching BluetoothAudio HAL to Hardware");
499     end_session();
500     active_hal_interface = offloading_hal_interface;
501   } else if (!should_codec_offloading && is_hal_offloading()) {
502     log::warn("Switching BluetoothAudio HAL to Software");
503     end_session();
504     active_hal_interface = software_hal_interface;
505   }
506 
507   AudioConfiguration audio_config{};
508   if (active_hal_interface->GetTransportInstance()->GetSessionType() ==
509       SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH) {
510     audio_config.set<AudioConfiguration::a2dpConfig>(codec_config);
511   } else {
512     PcmConfiguration pcm_config{};
513     if (!a2dp_get_selected_hal_pcm_config(a2dp_config, preferred_encoding_interval_us,
514                                           &pcm_config)) {
515       log::error("Failed to get PcmConfiguration");
516       return false;
517     }
518     audio_config.set<AudioConfiguration::pcmConfig>(pcm_config);
519   }
520 
521   return active_hal_interface->UpdateAudioConfig(audio_config);
522 }
523 
start_session()524 void start_session() {
525   if (!is_hal_enabled()) {
526     log::error("BluetoothAudio HAL is not enabled");
527     return;
528   }
529   std::vector<LatencyMode> latency_modes = {LatencyMode::FREE};
530   if (is_low_latency_mode_allowed) {
531     latency_modes.push_back(LatencyMode::LOW_LATENCY);
532   }
533   active_hal_interface->SetAllowedLatencyModes(latency_modes);
534   active_hal_interface->StartSession();
535 }
536 
end_session()537 void end_session() {
538   if (!is_hal_enabled()) {
539     log::error("BluetoothAudio HAL is not enabled");
540     return;
541   }
542   active_hal_interface->EndSession();
543   static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance())->ResetPendingCmd();
544   static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance())
545           ->ResetPresentationPosition();
546 }
547 
ack_stream_started(Status ack)548 void ack_stream_started(Status ack) {
549   if (!is_hal_enabled()) {
550     log::error("BluetoothAudio HAL is not enabled");
551     return;
552   }
553   log::info("result={}", ack);
554   auto a2dp_sink = static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance());
555   auto pending_cmd = a2dp_sink->GetPendingCmd();
556   if (pending_cmd == A2DP_CTRL_CMD_START) {
557     active_hal_interface->StreamStarted(ack);
558   } else {
559     log::warn("pending={} ignore result={}", pending_cmd, ack);
560     return;
561   }
562   if (ack != Status::PENDING) {
563     a2dp_sink->ResetPendingCmd();
564   }
565 }
566 
ack_stream_suspended(Status ack)567 void ack_stream_suspended(Status ack) {
568   if (!is_hal_enabled()) {
569     log::error("BluetoothAudio HAL is not enabled");
570     return;
571   }
572   log::info("result={}", ack);
573   auto a2dp_sink = static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance());
574   auto pending_cmd = a2dp_sink->GetPendingCmd();
575   if (pending_cmd == A2DP_CTRL_CMD_SUSPEND) {
576     active_hal_interface->StreamSuspended(ack);
577   } else if (pending_cmd == A2DP_CTRL_CMD_STOP) {
578     log::info("A2DP_CTRL_CMD_STOP result={}", ack);
579   } else {
580     log::warn("pending={} ignore result={}", pending_cmd, ack);
581     return;
582   }
583   if (ack != Status::PENDING) {
584     a2dp_sink->ResetPendingCmd();
585   }
586 }
587 
588 // Read from the FMQ of BluetoothAudio HAL
read(uint8_t * p_buf,uint32_t len)589 size_t read(uint8_t* p_buf, uint32_t len) {
590   if (!is_hal_enabled()) {
591     log::error("BluetoothAudio HAL is not enabled");
592     return 0;
593   }
594   if (is_hal_offloading()) {
595     log::error("session_type={} is not A2DP_SOFTWARE_ENCODING_DATAPATH",
596                toString(active_hal_interface->GetTransportInstance()->GetSessionType()));
597     return 0;
598   }
599   return active_hal_interface->ReadAudioData(p_buf, len);
600 }
601 
602 // Update A2DP delay report to BluetoothAudio HAL
set_remote_delay(uint16_t delay_report)603 void set_remote_delay(uint16_t delay_report) {
604   if (!is_hal_enabled()) {
605     log::info("not ready for DelayReport {} ms", static_cast<float>(delay_report / 10.0));
606     remote_delay = delay_report;
607     return;
608   }
609   log::verbose("DELAY {} ms", static_cast<float>(delay_report / 10.0));
610   static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance())
611           ->SetRemoteDelay(delay_report);
612 }
613 
614 // Set low latency buffer mode allowed or disallowed
set_low_latency_mode_allowed(bool allowed)615 void set_low_latency_mode_allowed(bool allowed) {
616   is_low_latency_mode_allowed = allowed;
617   if (!is_hal_enabled()) {
618     log::error("BluetoothAudio HAL is not enabled");
619     return;
620   }
621   std::vector<LatencyMode> latency_modes = {LatencyMode::FREE};
622   if (is_low_latency_mode_allowed) {
623     latency_modes.push_back(LatencyMode::LOW_LATENCY);
624   }
625   active_hal_interface->SetAllowedLatencyModes(latency_modes);
626 }
627 
628 /***
629  * Lookup the codec info in the list of supported offloaded sink codecs.
630  ***/
sink_codec_index(const uint8_t * p_codec_info)631 std::optional<btav_a2dp_codec_index_t> provider::sink_codec_index(const uint8_t* p_codec_info) {
632   return provider_info ? provider_info->SinkCodecIndex(p_codec_info) : std::nullopt;
633 }
634 
635 /***
636  * Lookup the codec info in the list of supported offloaded source codecs.
637  ***/
source_codec_index(const uint8_t * p_codec_info)638 std::optional<btav_a2dp_codec_index_t> provider::source_codec_index(const uint8_t* p_codec_info) {
639   return provider_info ? provider_info->SourceCodecIndex(p_codec_info) : std::nullopt;
640 }
641 
642 /***
643  * Return the name of the codec which is assigned to the input index.
644  * The codec index must be in the ranges
645  * BTAV_A2DP_CODEC_INDEX_SINK_EXT_MIN..BTAV_A2DP_CODEC_INDEX_SINK_EXT_MAX or
646  * BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN..BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX.
647  * Returns nullopt if the codec_index is not assigned or codec extensibility
648  * is not supported or enabled.
649  ***/
codec_index_str(btav_a2dp_codec_index_t codec_index)650 std::optional<const char*> provider::codec_index_str(btav_a2dp_codec_index_t codec_index) {
651   return provider_info ? provider_info->CodecIndexStr(codec_index) : std::nullopt;
652 }
653 
654 /***
655  * Return true if the codec is supported for the session type
656  * A2DP_HARDWARE_ENCODING_DATAPATH or A2DP_HARDWARE_DECODING_DATAPATH.
657  ***/
supports_codec(btav_a2dp_codec_index_t codec_index)658 bool provider::supports_codec(btav_a2dp_codec_index_t codec_index) {
659   return provider_info ? provider_info->SupportsCodec(codec_index) : false;
660 }
661 
662 /***
663  * Return the A2DP capabilities for the selected codec.
664  ***/
codec_info(btav_a2dp_codec_index_t codec_index,bluetooth::a2dp::CodecId * codec_id,uint8_t * codec_info,btav_a2dp_codec_config_t * codec_config)665 bool provider::codec_info(btav_a2dp_codec_index_t codec_index, bluetooth::a2dp::CodecId* codec_id,
666                           uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config) {
667   return provider_info
668                  ? provider_info->CodecCapabilities(codec_index, codec_id, codec_info, codec_config)
669                  : false;
670 }
671 
convert_channel_mode(ChannelMode channel_mode)672 static btav_a2dp_codec_channel_mode_t convert_channel_mode(ChannelMode channel_mode) {
673   switch (channel_mode) {
674     case ChannelMode::MONO:
675       return BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
676     case ChannelMode::STEREO:
677       return BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
678     default:
679       log::error("unknown channel mode");
680       break;
681   }
682   return BTAV_A2DP_CODEC_CHANNEL_MODE_NONE;
683 }
684 
convert_sampling_frequency_hz(int sampling_frequency_hz)685 static btav_a2dp_codec_sample_rate_t convert_sampling_frequency_hz(int sampling_frequency_hz) {
686   switch (sampling_frequency_hz) {
687     case 44100:
688       return BTAV_A2DP_CODEC_SAMPLE_RATE_44100;
689     case 48000:
690       return BTAV_A2DP_CODEC_SAMPLE_RATE_48000;
691     case 88200:
692       return BTAV_A2DP_CODEC_SAMPLE_RATE_88200;
693     case 96000:
694       return BTAV_A2DP_CODEC_SAMPLE_RATE_96000;
695     case 176400:
696       return BTAV_A2DP_CODEC_SAMPLE_RATE_176400;
697     case 192000:
698       return BTAV_A2DP_CODEC_SAMPLE_RATE_192000;
699     case 16000:
700       return BTAV_A2DP_CODEC_SAMPLE_RATE_16000;
701     case 24000:
702       return BTAV_A2DP_CODEC_SAMPLE_RATE_24000;
703     default:
704       log::error("unknown sampling frequency {}", sampling_frequency_hz);
705       break;
706   }
707   return BTAV_A2DP_CODEC_SAMPLE_RATE_NONE;
708 }
709 
convert_bitdepth(int bitdepth)710 static btav_a2dp_codec_bits_per_sample_t convert_bitdepth(int bitdepth) {
711   switch (bitdepth) {
712     case 16:
713       return BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16;
714     case 24:
715       return BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24;
716     case 32:
717       return BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32;
718     default:
719       log::error("unknown bit depth {}", bitdepth);
720       break;
721   }
722   return BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
723 }
724 
725 /***
726  * Query the codec selection fromt the audio HAL.
727  * The HAL is expected to pick the best audio configuration based on the
728  * discovered remote SEPs.
729  ***/
730 std::optional<::bluetooth::audio::a2dp::provider::a2dp_configuration>
get_a2dp_configuration(RawAddress peer_address,std::vector<::bluetooth::audio::a2dp::provider::a2dp_remote_capabilities> const & remote_seps,btav_a2dp_codec_config_t const & user_preferences)731 provider::get_a2dp_configuration(
732         RawAddress peer_address,
733         std::vector<::bluetooth::audio::a2dp::provider::a2dp_remote_capabilities> const&
734                 remote_seps,
735         btav_a2dp_codec_config_t const& user_preferences) {
736   if (provider_info == nullptr) {
737     return std::nullopt;
738   }
739 
740   using ::aidl::android::hardware::bluetooth::audio::A2dpRemoteCapabilities;
741   using ::aidl::android::hardware::bluetooth::audio::CodecId;
742 
743   // Convert the remote audio capabilities to the exchange format used
744   // by the HAL.
745   std::vector<A2dpRemoteCapabilities> a2dp_remote_capabilities;
746   for (auto const& sep : remote_seps) {
747     size_t capabilities_start = 0;
748     size_t capabilities_end = 0;
749     CodecId id;
750     switch (sep.capabilities[2]) {
751       case A2DP_MEDIA_CT_SBC:
752       case A2DP_MEDIA_CT_AAC: {
753         id = CodecId::make<CodecId::a2dp>(static_cast<CodecId::A2dp>(sep.capabilities[2]));
754         capabilities_start = 3;
755         capabilities_end = 1 + sep.capabilities[0];
756         break;
757       }
758       case A2DP_MEDIA_CT_NON_A2DP: {
759         uint32_t vendor_id = (static_cast<uint32_t>(sep.capabilities[3]) << 0) |
760                              (static_cast<uint32_t>(sep.capabilities[4]) << 8) |
761                              (static_cast<uint32_t>(sep.capabilities[5]) << 16) |
762                              (static_cast<uint32_t>(sep.capabilities[6]) << 24);
763         uint16_t codec_id = (static_cast<uint16_t>(sep.capabilities[7]) << 0) |
764                             (static_cast<uint16_t>(sep.capabilities[8]) << 8);
765         id = CodecId::make<CodecId::vendor>(
766                 CodecId::Vendor({.id = (int32_t)vendor_id, .codecId = codec_id}));
767         capabilities_start = 9;
768         capabilities_end = 1 + sep.capabilities[0];
769         break;
770       }
771       default:
772         continue;
773     }
774     A2dpRemoteCapabilities& capabilities = a2dp_remote_capabilities.emplace_back();
775     capabilities.seid = sep.seid;
776     capabilities.id = id;
777     capabilities.capabilities.insert(capabilities.capabilities.end(),
778                                      sep.capabilities + capabilities_start,
779                                      sep.capabilities + capabilities_end);
780   }
781 
782   // Convert the user preferences into a configuration hint.
783   A2dpConfigurationHint hint;
784   hint.bdAddr = peer_address.ToArray();
785   auto& codecParameters = hint.codecParameters.emplace();
786   switch (user_preferences.channel_mode) {
787     case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO:
788       codecParameters.channelMode = ChannelMode::MONO;
789       break;
790     case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO:
791       codecParameters.channelMode = ChannelMode::STEREO;
792       break;
793     default:
794       break;
795   }
796   switch (user_preferences.sample_rate) {
797     case BTAV_A2DP_CODEC_SAMPLE_RATE_44100:
798       codecParameters.samplingFrequencyHz = 44100;
799       break;
800     case BTAV_A2DP_CODEC_SAMPLE_RATE_48000:
801       codecParameters.samplingFrequencyHz = 48000;
802       break;
803     case BTAV_A2DP_CODEC_SAMPLE_RATE_88200:
804       codecParameters.samplingFrequencyHz = 88200;
805       break;
806     case BTAV_A2DP_CODEC_SAMPLE_RATE_96000:
807       codecParameters.samplingFrequencyHz = 96000;
808       break;
809     case BTAV_A2DP_CODEC_SAMPLE_RATE_176400:
810       codecParameters.samplingFrequencyHz = 176400;
811       break;
812     case BTAV_A2DP_CODEC_SAMPLE_RATE_192000:
813       codecParameters.samplingFrequencyHz = 192000;
814       break;
815     case BTAV_A2DP_CODEC_SAMPLE_RATE_16000:
816       codecParameters.samplingFrequencyHz = 16000;
817       break;
818     case BTAV_A2DP_CODEC_SAMPLE_RATE_24000:
819       codecParameters.samplingFrequencyHz = 24000;
820       break;
821     default:
822       break;
823   }
824   switch (user_preferences.bits_per_sample) {
825     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16:
826       codecParameters.bitdepth = 16;
827       break;
828     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24:
829       codecParameters.bitdepth = 24;
830       break;
831     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32:
832       codecParameters.bitdepth = 32;
833       break;
834     default:
835       break;
836   }
837 
838   log::info("remote capabilities:");
839   for (auto const& sep : a2dp_remote_capabilities) {
840     log::info("- {}", sep.toString());
841   }
842   log::info("hint: {}", hint.toString());
843 
844   if (offloading_hal_interface == nullptr &&
845       (offloading_hal_interface = new_hal_interface(
846                SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH)) == nullptr) {
847     log::error("the offloading HAL interface cannot be opened");
848     return std::nullopt;
849   }
850 
851   // Invoke the HAL GetAdpCapabilities method with the
852   // remote capabilities.
853   auto result = offloading_hal_interface->GetA2dpConfiguration(a2dp_remote_capabilities, hint);
854 
855   // Convert the result configuration back to the stack's format.
856   if (!result.has_value()) {
857     log::info("provider cannot resolve the a2dp configuration");
858     return std::nullopt;
859   }
860 
861   log::info("provider selected {}", result->toString());
862 
863   ::bluetooth::audio::a2dp::provider::a2dp_configuration a2dp_configuration;
864   a2dp_configuration.remote_seid = result->remoteSeid;
865   a2dp_configuration.vendor_specific_parameters = result->parameters.vendorSpecificParameters;
866   ProviderInfo::BuildCodecCapabilities(result->id, result->configuration,
867                                        a2dp_configuration.codec_config);
868   a2dp_configuration.codec_parameters.codec_type =
869           provider_info->SourceCodecIndex(result->id).value();
870   a2dp_configuration.codec_parameters.channel_mode =
871           convert_channel_mode(result->parameters.channelMode);
872   a2dp_configuration.codec_parameters.sample_rate =
873           convert_sampling_frequency_hz(result->parameters.samplingFrequencyHz);
874   a2dp_configuration.codec_parameters.bits_per_sample =
875           convert_bitdepth(result->parameters.bitdepth);
876 
877   return std::make_optional(a2dp_configuration);
878 }
879 
880 /***
881  * Query the codec parameters from the audio HAL.
882  * The HAL is expected to parse the codec configuration
883  * received from the peer and decide whether accept
884  * the it or not.
885  ***/
parse_a2dp_configuration(btav_a2dp_codec_index_t codec_index,const uint8_t * codec_info,btav_a2dp_codec_config_t * codec_parameters,std::vector<uint8_t> * vendor_specific_parameters)886 tA2DP_STATUS provider::parse_a2dp_configuration(btav_a2dp_codec_index_t codec_index,
887                                                 const uint8_t* codec_info,
888                                                 btav_a2dp_codec_config_t* codec_parameters,
889                                                 std::vector<uint8_t>* vendor_specific_parameters) {
890   std::vector<uint8_t> configuration;
891   CodecParameters codec_parameters_aidl;
892 
893   if (provider_info == nullptr) {
894     log::error("provider_info is null");
895     return A2DP_FAIL;
896   }
897 
898   auto codec = provider_info->GetCodec(codec_index);
899   if (!codec.has_value()) {
900     log::error("codec index not recognized by provider");
901     return A2DP_FAIL;
902   }
903 
904   std::copy(codec_info, codec_info + AVDT_CODEC_SIZE, std::back_inserter(configuration));
905 
906   auto a2dp_status = offloading_hal_interface->ParseA2dpConfiguration(
907           codec.value()->id, configuration, &codec_parameters_aidl);
908 
909   if (!a2dp_status.has_value()) {
910     log::error("provider failed to parse configuration");
911     return A2DP_FAIL;
912   }
913 
914   if (codec_parameters != nullptr) {
915     codec_parameters->channel_mode = convert_channel_mode(codec_parameters_aidl.channelMode);
916     codec_parameters->sample_rate =
917             convert_sampling_frequency_hz(codec_parameters_aidl.samplingFrequencyHz);
918     codec_parameters->bits_per_sample = convert_bitdepth(codec_parameters_aidl.bitdepth);
919   }
920 
921   if (vendor_specific_parameters != nullptr) {
922     *vendor_specific_parameters = codec_parameters_aidl.vendorSpecificParameters;
923   }
924 
925   return static_cast<tA2DP_STATUS>(a2dp_status.value());
926 }
927 
928 }  // namespace a2dp
929 }  // namespace aidl
930 }  // namespace audio
931 }  // namespace bluetooth
932