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