• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 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 #include "a2dp_encoding.h"
18 #include "client_interface.h"
19 
20 #include "a2dp_aac_constants.h"
21 #include "a2dp_sbc_constants.h"
22 #include "a2dp_vendor_ldac_constants.h"
23 #include "bta/av/bta_av_int.h"
24 #include "btif_a2dp_source.h"
25 #include "btif_av.h"
26 #include "btif_av_co.h"
27 #include "btif_hf.h"
28 #include "osi/include/properties.h"
29 
30 namespace {
31 
32 using ::android::hardware::bluetooth::audio::V2_0::AacObjectType;
33 using ::android::hardware::bluetooth::audio::V2_0::AacVariableBitRate;
34 using ::android::hardware::bluetooth::audio::V2_0::CodecType;
35 using ::android::hardware::bluetooth::audio::V2_0::LdacChannelMode;
36 using ::android::hardware::bluetooth::audio::V2_0::LdacQualityIndex;
37 using ::android::hardware::bluetooth::audio::V2_0::SbcAllocMethod;
38 using ::android::hardware::bluetooth::audio::V2_0::SbcBlockLength;
39 using ::android::hardware::bluetooth::audio::V2_0::SbcChannelMode;
40 using ::android::hardware::bluetooth::audio::V2_0::SbcNumSubbands;
41 using ::bluetooth::audio::AudioConfiguration;
42 using ::bluetooth::audio::BitsPerSample;
43 using ::bluetooth::audio::BluetoothAudioCtrlAck;
44 using ::bluetooth::audio::ChannelMode;
45 using ::bluetooth::audio::CodecConfiguration;
46 using ::bluetooth::audio::PcmParameters;
47 using ::bluetooth::audio::SampleRate;
48 using ::bluetooth::audio::SessionType;
49 
50 const CodecConfiguration kInvalidCodecConfiguration = {
51     .codecType = CodecType::UNKNOWN,
52     .encodedAudioBitrate = 0x00000000,
53     .peerMtu = 0xffff,
54     .isScmstEnabled = false,
55     .config = {}};
56 
57 BluetoothAudioCtrlAck a2dp_ack_to_bt_audio_ctrl_ack(tA2DP_CTRL_ACK ack);
58 
59 // Provide call-in APIs for the Bluetooth Audio HAL
60 class A2dpTransport : public ::bluetooth::audio::IBluetoothTransportInstance {
61  public:
A2dpTransport(SessionType sessionType)62   A2dpTransport(SessionType sessionType)
63       : IBluetoothTransportInstance(sessionType, {}),
64         a2dp_pending_cmd_(A2DP_CTRL_CMD_NONE),
65         remote_delay_report_(0),
66         total_bytes_read_(0),
67         data_position_({}){};
68 
StartRequest()69   BluetoothAudioCtrlAck StartRequest() override {
70     // Check if a previous request is not finished
71     if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_START) {
72       LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_START in progress";
73       return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_PENDING);
74     } else if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
75       LOG(WARNING) << __func__ << ": busy in pending_cmd=" << a2dp_pending_cmd_;
76       return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
77     }
78 
79     // Don't send START request to stack while we are in a call
80     if (!bluetooth::headset::IsCallIdle()) {
81       LOG(ERROR) << __func__ << ": call state is busy";
82       return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_INCALL_FAILURE);
83     }
84 
85     if (btif_a2dp_source_is_streaming()) {
86       LOG(ERROR) << __func__ << ": source is busy streaming";
87       return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
88     }
89 
90     if (btif_av_stream_ready()) {
91       /*
92        * Post start event and wait for audio path to open.
93        * If we are the source, the ACK will be sent after the start
94        * procedure is completed, othewise send it now.
95        */
96       a2dp_pending_cmd_ = A2DP_CTRL_CMD_START;
97       btif_av_stream_start();
98       if (btif_av_get_peer_sep() != AVDT_TSEP_SRC) {
99         LOG(INFO) << __func__ << ": accepted";
100         return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_PENDING);
101       }
102       a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
103       return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_SUCCESS);
104     }
105 
106     if (btif_av_stream_started_ready()) {
107       // Already started, ACK back immediately.
108       return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_SUCCESS);
109     }
110     LOG(ERROR) << __func__ << ": AV stream is not ready to start";
111     return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
112   }
113 
SuspendRequest()114   BluetoothAudioCtrlAck SuspendRequest() override {
115     // Previous request is not finished
116     if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_SUSPEND) {
117       LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_SUSPEND in progress";
118       return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_PENDING);
119     } else if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
120       LOG(WARNING) << __func__ << ": busy in pending_cmd=" << a2dp_pending_cmd_;
121       return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
122     }
123     // Local suspend
124     if (btif_av_stream_started_ready()) {
125       LOG(INFO) << __func__ << ": accepted";
126       a2dp_pending_cmd_ = A2DP_CTRL_CMD_SUSPEND;
127       btif_av_stream_suspend();
128       return BluetoothAudioCtrlAck::PENDING;
129     }
130     /* If we are not in started state, just ack back ok and let
131      * audioflinger close the channel. This can happen if we are
132      * remotely suspended, clear REMOTE SUSPEND flag.
133      */
134     btif_av_clear_remote_suspend_flag();
135     return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_SUCCESS);
136   }
137 
StopRequest()138   void StopRequest() override {
139     if (btif_av_get_peer_sep() == AVDT_TSEP_SNK &&
140         !btif_a2dp_source_is_streaming()) {
141       return;
142     }
143     LOG(INFO) << __func__ << ": handling";
144     a2dp_pending_cmd_ = A2DP_CTRL_CMD_STOP;
145     btif_av_stream_stop(RawAddress::kEmpty);
146   }
147 
GetPresentationPosition(uint64_t * remote_delay_report_ns,uint64_t * total_bytes_read,timespec * data_position)148   bool GetPresentationPosition(uint64_t* remote_delay_report_ns,
149                                uint64_t* total_bytes_read,
150                                timespec* data_position) override {
151     *remote_delay_report_ns = remote_delay_report_ * 100000u;
152     *total_bytes_read = total_bytes_read_;
153     *data_position = data_position_;
154     VLOG(2) << __func__ << ": delay=" << remote_delay_report_
155             << "/10ms, data=" << total_bytes_read_
156             << " byte(s), timestamp=" << data_position_.tv_sec << "."
157             << data_position_.tv_nsec << "s";
158     return true;
159   }
160 
MetadataChanged(const source_metadata_t & source_metadata)161   void MetadataChanged(const source_metadata_t& source_metadata) override {
162     auto track_count = source_metadata.track_count;
163     auto tracks = source_metadata.tracks;
164     VLOG(1) << __func__ << ": " << track_count << " track(s) received";
165     while (track_count) {
166       VLOG(2) << __func__ << ": usage=" << tracks->usage
167               << ", content_type=" << tracks->content_type
168               << ", gain=" << tracks->gain;
169       --track_count;
170       ++tracks;
171     }
172   }
173 
GetPendingCmd() const174   tA2DP_CTRL_CMD GetPendingCmd() const { return a2dp_pending_cmd_; }
175 
ResetPendingCmd()176   void ResetPendingCmd() { a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE; }
177 
ResetPresentationPosition()178   void ResetPresentationPosition() override {
179     remote_delay_report_ = 0;
180     total_bytes_read_ = 0;
181     data_position_ = {};
182   }
183 
LogBytesRead(size_t bytes_read)184   void LogBytesRead(size_t bytes_read) override {
185     if (bytes_read != 0) {
186       total_bytes_read_ += bytes_read;
187       clock_gettime(CLOCK_MONOTONIC, &data_position_);
188     }
189   }
190 
191   // delay reports from AVDTP is based on 1/10 ms (100us)
SetRemoteDelay(uint16_t delay_report)192   void SetRemoteDelay(uint16_t delay_report) {
193     remote_delay_report_ = delay_report;
194   }
195 
196  private:
197   tA2DP_CTRL_CMD a2dp_pending_cmd_;
198   uint16_t remote_delay_report_;
199   uint64_t total_bytes_read_;
200   timespec data_position_;
201 };
202 
203 A2dpTransport* a2dp_sink = nullptr;
204 
205 // Common interface to call-out into Bluetooth Audio HAL
206 bluetooth::audio::BluetoothAudioClientInterface* a2dp_hal_clientif = nullptr;
207 auto session_type = SessionType::UNKNOWN;
208 
209 // Save the value if the remote reports its delay before a2dp_sink is
210 // initialized
211 uint16_t remote_delay = 0;
212 
213 bool btaudio_a2dp_disabled = false;
214 bool is_configured = false;
215 
a2dp_ack_to_bt_audio_ctrl_ack(tA2DP_CTRL_ACK ack)216 BluetoothAudioCtrlAck a2dp_ack_to_bt_audio_ctrl_ack(tA2DP_CTRL_ACK ack) {
217   switch (ack) {
218     case A2DP_CTRL_ACK_SUCCESS:
219       return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
220     case A2DP_CTRL_ACK_PENDING:
221       return BluetoothAudioCtrlAck::PENDING;
222     case A2DP_CTRL_ACK_INCALL_FAILURE:
223       return BluetoothAudioCtrlAck::FAILURE_BUSY;
224     case A2DP_CTRL_ACK_DISCONNECT_IN_PROGRESS:
225       return BluetoothAudioCtrlAck::FAILURE_DISCONNECTING;
226     case A2DP_CTRL_ACK_UNSUPPORTED: /* Offloading but resource failure */
227       return BluetoothAudioCtrlAck::FAILURE_UNSUPPORTED;
228     case A2DP_CTRL_ACK_FAILURE:
229       return BluetoothAudioCtrlAck::FAILURE;
230     default:
231       return BluetoothAudioCtrlAck::FAILURE;
232   }
233 }
234 
a2dp_codec_to_hal_sample_rate(const btav_a2dp_codec_config_t & a2dp_codec_config)235 SampleRate a2dp_codec_to_hal_sample_rate(
236     const btav_a2dp_codec_config_t& a2dp_codec_config) {
237   switch (a2dp_codec_config.sample_rate) {
238     case BTAV_A2DP_CODEC_SAMPLE_RATE_44100:
239       return SampleRate::RATE_44100;
240     case BTAV_A2DP_CODEC_SAMPLE_RATE_48000:
241       return SampleRate::RATE_48000;
242     case BTAV_A2DP_CODEC_SAMPLE_RATE_88200:
243       return SampleRate::RATE_88200;
244     case BTAV_A2DP_CODEC_SAMPLE_RATE_96000:
245       return SampleRate::RATE_96000;
246     case BTAV_A2DP_CODEC_SAMPLE_RATE_176400:
247       return SampleRate::RATE_176400;
248     case BTAV_A2DP_CODEC_SAMPLE_RATE_192000:
249       return SampleRate::RATE_192000;
250     case BTAV_A2DP_CODEC_SAMPLE_RATE_16000:
251       return SampleRate::RATE_16000;
252     case BTAV_A2DP_CODEC_SAMPLE_RATE_24000:
253       return SampleRate::RATE_24000;
254     default:
255       return SampleRate::RATE_UNKNOWN;
256   }
257 }
258 
a2dp_codec_to_hal_bits_per_sample(const btav_a2dp_codec_config_t & a2dp_codec_config)259 BitsPerSample a2dp_codec_to_hal_bits_per_sample(
260     const btav_a2dp_codec_config_t& a2dp_codec_config) {
261   switch (a2dp_codec_config.bits_per_sample) {
262     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16:
263       return BitsPerSample::BITS_16;
264     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24:
265       return BitsPerSample::BITS_24;
266     case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32:
267       return BitsPerSample::BITS_32;
268     default:
269       return BitsPerSample::BITS_UNKNOWN;
270   }
271 }
272 
a2dp_codec_to_hal_channel_mode(const btav_a2dp_codec_config_t & a2dp_codec_config)273 ChannelMode a2dp_codec_to_hal_channel_mode(
274     const btav_a2dp_codec_config_t& a2dp_codec_config) {
275   switch (a2dp_codec_config.channel_mode) {
276     case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO:
277       return ChannelMode::MONO;
278     case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO:
279       return ChannelMode::STEREO;
280     default:
281       return ChannelMode::UNKNOWN;
282   }
283 }
284 
a2dp_get_selected_hal_codec_config(CodecConfiguration * codec_config)285 bool a2dp_get_selected_hal_codec_config(CodecConfiguration* codec_config) {
286   A2dpCodecConfig* a2dp_codec_configs = bta_av_get_a2dp_current_codec();
287   if (a2dp_codec_configs == nullptr) {
288     LOG(WARNING) << __func__ << ": failure to get A2DP codec config";
289     *codec_config = kInvalidCodecConfiguration;
290     return false;
291   }
292   btav_a2dp_codec_config_t current_codec = a2dp_codec_configs->getCodecConfig();
293   tBT_A2DP_OFFLOAD a2dp_offload;
294   a2dp_codec_configs->getCodecSpecificConfig(&a2dp_offload);
295   switch (current_codec.codec_type) {
296     case BTAV_A2DP_CODEC_INDEX_SOURCE_SBC:
297       [[fallthrough]];
298     case BTAV_A2DP_CODEC_INDEX_SINK_SBC: {
299       codec_config->codecType = CodecType::SBC;
300       codec_config->config.sbcConfig({});
301       auto sbc_config = codec_config->config.sbcConfig();
302       sbc_config.sampleRate = a2dp_codec_to_hal_sample_rate(current_codec);
303       if (sbc_config.sampleRate == SampleRate::RATE_UNKNOWN) {
304         LOG(ERROR) << __func__
305                    << ": Unknown SBC sample_rate=" << current_codec.sample_rate;
306         return false;
307       }
308       uint8_t channel_mode = a2dp_offload.codec_info[3] & A2DP_SBC_IE_CH_MD_MSK;
309       switch (channel_mode) {
310         case A2DP_SBC_IE_CH_MD_JOINT:
311           sbc_config.channelMode = SbcChannelMode::JOINT_STEREO;
312           break;
313         case A2DP_SBC_IE_CH_MD_STEREO:
314           sbc_config.channelMode = SbcChannelMode::STEREO;
315           break;
316         case A2DP_SBC_IE_CH_MD_DUAL:
317           sbc_config.channelMode = SbcChannelMode::DUAL;
318           break;
319         case A2DP_SBC_IE_CH_MD_MONO:
320           sbc_config.channelMode = SbcChannelMode::MONO;
321           break;
322         default:
323           LOG(ERROR) << __func__
324                      << ": Unknown SBC channel_mode=" << channel_mode;
325           sbc_config.channelMode = SbcChannelMode::UNKNOWN;
326           return false;
327       }
328       uint8_t block_length =
329           a2dp_offload.codec_info[0] & A2DP_SBC_IE_BLOCKS_MSK;
330       switch (block_length) {
331         case A2DP_SBC_IE_BLOCKS_4:
332           sbc_config.blockLength = SbcBlockLength::BLOCKS_4;
333           break;
334         case A2DP_SBC_IE_BLOCKS_8:
335           sbc_config.blockLength = SbcBlockLength::BLOCKS_8;
336           break;
337         case A2DP_SBC_IE_BLOCKS_12:
338           sbc_config.blockLength = SbcBlockLength::BLOCKS_12;
339           break;
340         case A2DP_SBC_IE_BLOCKS_16:
341           sbc_config.blockLength = SbcBlockLength::BLOCKS_16;
342           break;
343         default:
344           LOG(ERROR) << __func__
345                      << ": Unknown SBC block_length=" << block_length;
346           return false;
347       }
348       uint8_t sub_bands = a2dp_offload.codec_info[0] & A2DP_SBC_IE_SUBBAND_MSK;
349       switch (sub_bands) {
350         case A2DP_SBC_IE_SUBBAND_4:
351           sbc_config.numSubbands = SbcNumSubbands::SUBBAND_4;
352           break;
353         case A2DP_SBC_IE_SUBBAND_8:
354           sbc_config.numSubbands = SbcNumSubbands::SUBBAND_8;
355           break;
356         default:
357           LOG(ERROR) << __func__ << ": Unknown SBC Subbands=" << sub_bands;
358           return false;
359       }
360       uint8_t alloc_method =
361           a2dp_offload.codec_info[0] & A2DP_SBC_IE_ALLOC_MD_MSK;
362       switch (alloc_method) {
363         case A2DP_SBC_IE_ALLOC_MD_S:
364           sbc_config.allocMethod = SbcAllocMethod::ALLOC_MD_S;
365           break;
366         case A2DP_SBC_IE_ALLOC_MD_L:
367           sbc_config.allocMethod = SbcAllocMethod::ALLOC_MD_L;
368           break;
369         default:
370           LOG(ERROR) << __func__
371                      << ": Unknown SBC alloc_method=" << alloc_method;
372           return false;
373       }
374       sbc_config.minBitpool = a2dp_offload.codec_info[1];
375       sbc_config.maxBitpool = a2dp_offload.codec_info[2];
376       sbc_config.bitsPerSample =
377           a2dp_codec_to_hal_bits_per_sample(current_codec);
378       if (sbc_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) {
379         LOG(ERROR) << __func__ << ": Unknown SBC bits_per_sample="
380                    << current_codec.bits_per_sample;
381         return false;
382       }
383       codec_config->config.sbcConfig(sbc_config);
384       break;
385     }
386     case BTAV_A2DP_CODEC_INDEX_SOURCE_AAC:
387       [[fallthrough]];
388     case BTAV_A2DP_CODEC_INDEX_SINK_AAC: {
389       codec_config->codecType = CodecType::AAC;
390       codec_config->config.aacConfig({});
391       auto aac_config = codec_config->config.aacConfig();
392       uint8_t object_type = a2dp_offload.codec_info[0];
393       switch (object_type) {
394         case A2DP_AAC_OBJECT_TYPE_MPEG2_LC:
395           aac_config.objectType = AacObjectType::MPEG2_LC;
396           break;
397         case A2DP_AAC_OBJECT_TYPE_MPEG4_LC:
398           aac_config.objectType = AacObjectType::MPEG4_LC;
399           break;
400         case A2DP_AAC_OBJECT_TYPE_MPEG4_LTP:
401           aac_config.objectType = AacObjectType::MPEG4_LTP;
402           break;
403         case A2DP_AAC_OBJECT_TYPE_MPEG4_SCALABLE:
404           aac_config.objectType = AacObjectType::MPEG4_SCALABLE;
405           break;
406         default:
407           LOG(ERROR) << __func__
408                      << ": Unknown AAC object_type=" << +object_type;
409           return false;
410       }
411       aac_config.sampleRate = a2dp_codec_to_hal_sample_rate(current_codec);
412       if (aac_config.sampleRate == SampleRate::RATE_UNKNOWN) {
413         LOG(ERROR) << __func__
414                    << ": Unknown AAC sample_rate=" << current_codec.sample_rate;
415         return false;
416       }
417       aac_config.channelMode = a2dp_codec_to_hal_channel_mode(current_codec);
418       if (aac_config.channelMode == ChannelMode::UNKNOWN) {
419         LOG(ERROR) << __func__ << ": Unknown AAC channel_mode="
420                    << current_codec.channel_mode;
421         return false;
422       }
423       uint8_t vbr_enabled =
424           a2dp_offload.codec_info[1] & A2DP_AAC_VARIABLE_BIT_RATE_MASK;
425       switch (vbr_enabled) {
426         case A2DP_AAC_VARIABLE_BIT_RATE_ENABLED:
427           aac_config.variableBitRateEnabled = AacVariableBitRate::ENABLED;
428           break;
429         case A2DP_AAC_VARIABLE_BIT_RATE_DISABLED:
430           aac_config.variableBitRateEnabled = AacVariableBitRate::DISABLED;
431           break;
432         default:
433           LOG(ERROR) << __func__ << ": Unknown AAC VBR=" << +vbr_enabled;
434           return false;
435       }
436       aac_config.bitsPerSample =
437           a2dp_codec_to_hal_bits_per_sample(current_codec);
438       if (aac_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) {
439         LOG(ERROR) << __func__ << ": Unknown AAC bits_per_sample="
440                    << current_codec.bits_per_sample;
441         return false;
442       }
443       codec_config->config.aacConfig(aac_config);
444       break;
445     }
446     case BTAV_A2DP_CODEC_INDEX_SOURCE_APTX:
447       [[fallthrough]];
448     case BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD: {
449       if (current_codec.codec_type == BTAV_A2DP_CODEC_INDEX_SOURCE_APTX) {
450         codec_config->codecType = CodecType::APTX;
451       } else {
452         codec_config->codecType = CodecType::APTX_HD;
453       }
454       codec_config->config.aptxConfig({});
455       auto aptx_config = codec_config->config.aptxConfig();
456       aptx_config.sampleRate = a2dp_codec_to_hal_sample_rate(current_codec);
457       if (aptx_config.sampleRate == SampleRate::RATE_UNKNOWN) {
458         LOG(ERROR) << __func__ << ": Unknown aptX sample_rate="
459                    << current_codec.sample_rate;
460         return false;
461       }
462       aptx_config.channelMode = a2dp_codec_to_hal_channel_mode(current_codec);
463       if (aptx_config.channelMode == ChannelMode::UNKNOWN) {
464         LOG(ERROR) << __func__ << ": Unknown aptX channel_mode="
465                    << current_codec.channel_mode;
466         return false;
467       }
468       aptx_config.bitsPerSample =
469           a2dp_codec_to_hal_bits_per_sample(current_codec);
470       if (aptx_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) {
471         LOG(ERROR) << __func__ << ": Unknown aptX bits_per_sample="
472                    << current_codec.bits_per_sample;
473         return false;
474       }
475       codec_config->config.aptxConfig(aptx_config);
476       break;
477     }
478     case BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC: {
479       codec_config->codecType = CodecType::LDAC;
480       codec_config->config.ldacConfig({});
481       auto ldac_config = codec_config->config.ldacConfig();
482       ldac_config.sampleRate = a2dp_codec_to_hal_sample_rate(current_codec);
483       if (ldac_config.sampleRate == SampleRate::RATE_UNKNOWN) {
484         LOG(ERROR) << __func__ << ": Unknown LDAC sample_rate="
485                    << current_codec.sample_rate;
486         return false;
487       }
488       switch (a2dp_offload.codec_info[7]) {
489         case A2DP_LDAC_CHANNEL_MODE_STEREO:
490           ldac_config.channelMode = LdacChannelMode::STEREO;
491           break;
492         case A2DP_LDAC_CHANNEL_MODE_DUAL:
493           ldac_config.channelMode = LdacChannelMode::DUAL;
494           break;
495         case A2DP_LDAC_CHANNEL_MODE_MONO:
496           ldac_config.channelMode = LdacChannelMode::MONO;
497           break;
498         default:
499           LOG(ERROR) << __func__ << ": Unknown LDAC channel_mode="
500                      << a2dp_offload.codec_info[7];
501           ldac_config.channelMode = LdacChannelMode::UNKNOWN;
502           return false;
503       }
504       switch (a2dp_offload.codec_info[6]) {
505         case A2DP_LDAC_QUALITY_HIGH:
506           ldac_config.qualityIndex = LdacQualityIndex::QUALITY_HIGH;
507           break;
508         case A2DP_LDAC_QUALITY_MID:
509           ldac_config.qualityIndex = LdacQualityIndex::QUALITY_MID;
510           break;
511         case A2DP_LDAC_QUALITY_LOW:
512           ldac_config.qualityIndex = LdacQualityIndex::QUALITY_LOW;
513           break;
514         case A2DP_LDAC_QUALITY_ABR_OFFLOAD:
515           ldac_config.qualityIndex = LdacQualityIndex::QUALITY_ABR;
516           break;
517         default:
518           LOG(ERROR) << __func__ << ": Unknown LDAC QualityIndex="
519                      << a2dp_offload.codec_info[6];
520           return false;
521       }
522       ldac_config.bitsPerSample =
523           a2dp_codec_to_hal_bits_per_sample(current_codec);
524       if (ldac_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) {
525         LOG(ERROR) << __func__ << ": Unknown LDAC bits_per_sample="
526                    << current_codec.bits_per_sample;
527         return false;
528       }
529       codec_config->config.ldacConfig(ldac_config);
530       break;
531     }
532     case BTAV_A2DP_CODEC_INDEX_MAX:
533       [[fallthrough]];
534     default:
535       LOG(ERROR) << __func__
536                  << ": Unknown codec_type=" << current_codec.codec_type;
537       codec_config->codecType = CodecType::UNKNOWN;
538       codec_config->config = {};
539       return false;
540   }
541   codec_config->encodedAudioBitrate = a2dp_codec_configs->getTrackBitRate();
542   // Obtain the MTU
543   RawAddress peer_addr = btif_av_source_active_peer();
544   tA2DP_ENCODER_INIT_PEER_PARAMS peer_param;
545   bta_av_co_get_peer_params(peer_addr, &peer_param);
546   int effectiveMtu = a2dp_codec_configs->getEffectiveMtu();
547   if (effectiveMtu > 0 && effectiveMtu < peer_param.peer_mtu) {
548     codec_config->peerMtu = effectiveMtu;
549   } else {
550     codec_config->peerMtu = peer_param.peer_mtu;
551   }
552   LOG(INFO) << __func__ << ": CodecConfiguration=" << toString(*codec_config);
553   return true;
554 }
555 
a2dp_get_selected_hal_pcm_config(PcmParameters * pcm_config)556 bool a2dp_get_selected_hal_pcm_config(PcmParameters* pcm_config) {
557   if (pcm_config == nullptr) return false;
558   A2dpCodecConfig* a2dp_codec_configs = bta_av_get_a2dp_current_codec();
559   if (a2dp_codec_configs == nullptr) {
560     LOG(WARNING) << __func__ << ": failure to get A2DP codec config";
561     *pcm_config = ::bluetooth::audio::BluetoothAudioClientInterface::
562         kInvalidPcmConfiguration;
563     return false;
564   }
565 
566   btav_a2dp_codec_config_t current_codec = a2dp_codec_configs->getCodecConfig();
567   pcm_config->sampleRate = a2dp_codec_to_hal_sample_rate(current_codec);
568   pcm_config->bitsPerSample = a2dp_codec_to_hal_bits_per_sample(current_codec);
569   pcm_config->channelMode = a2dp_codec_to_hal_channel_mode(current_codec);
570   return (pcm_config->sampleRate != SampleRate::RATE_UNKNOWN &&
571           pcm_config->bitsPerSample != BitsPerSample::BITS_UNKNOWN &&
572           pcm_config->channelMode != ChannelMode::UNKNOWN);
573 }
574 
575 // Checking if new bluetooth_audio is supported
is_hal_2_0_force_disabled()576 bool is_hal_2_0_force_disabled() {
577   if (!is_configured) {
578     btaudio_a2dp_disabled = osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false);
579     is_configured = true;
580   }
581   return btaudio_a2dp_disabled;
582 }
583 
584 }  // namespace
585 
586 namespace bluetooth {
587 namespace audio {
588 namespace a2dp {
589 
590 // Checking if new bluetooth_audio is enabled
is_hal_2_0_enabled()591 bool is_hal_2_0_enabled() { return a2dp_hal_clientif != nullptr; }
592 
593 // Initialize BluetoothAudio HAL: openProvider
init(bluetooth::common::MessageLoopThread * message_loop)594 bool init(bluetooth::common::MessageLoopThread* message_loop) {
595   LOG(INFO) << __func__;
596 
597   if (is_hal_2_0_force_disabled()) {
598     LOG(ERROR) << __func__ << ": BluetoothAudio HAL is disabled";
599     return false;
600   }
601 
602   if (btif_av_is_a2dp_offload_enabled()) {
603     session_type = SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH;
604   } else {
605     session_type = SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH;
606   }
607   a2dp_sink = new A2dpTransport(session_type);
608   a2dp_hal_clientif = new bluetooth::audio::BluetoothAudioClientInterface(
609       a2dp_sink, message_loop);
610   if (!a2dp_hal_clientif->IsValid()) {
611     LOG(WARNING) << __func__ << ": BluetoothAudio HAL for A2DP session=" << toString(session_type) << " is invalid?!";
612     delete a2dp_hal_clientif;
613     a2dp_hal_clientif = nullptr;
614     delete a2dp_sink;
615     a2dp_sink = nullptr;
616     return false;
617   }
618 
619   if (remote_delay != 0) {
620     LOG(INFO) << __func__ << ": restore DELAY "
621               << static_cast<float>(remote_delay / 10.0) << " ms";
622     a2dp_sink->SetRemoteDelay(remote_delay);
623     remote_delay = 0;
624   }
625   return true;
626 }
627 
628 // Clean up BluetoothAudio HAL
cleanup()629 void cleanup() {
630   if (!is_hal_2_0_enabled()) return;
631   end_session();
632   delete a2dp_hal_clientif;
633   a2dp_hal_clientif = nullptr;
634   delete a2dp_sink;
635   a2dp_sink = nullptr;
636   session_type = SessionType::UNKNOWN;
637   remote_delay = 0;
638 }
639 
640 // Set up the codec into BluetoothAudio HAL
setup_codec()641 bool setup_codec() {
642   if (!is_hal_2_0_enabled()) {
643     LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
644     return false;
645   }
646   AudioConfiguration audio_config{};
647   if (session_type == SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH) {
648     CodecConfiguration codec_config{};
649     if (!a2dp_get_selected_hal_codec_config(&codec_config)) {
650       LOG(ERROR) << __func__ << ": Failed to get CodecConfiguration";
651       return false;
652     }
653     audio_config.codecConfig(codec_config);
654   } else if (session_type == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH) {
655     PcmParameters pcm_config{};
656     if (!a2dp_get_selected_hal_pcm_config(&pcm_config)) {
657       LOG(ERROR) << __func__ << ": Failed to get PcmConfiguration";
658       return false;
659     }
660     audio_config.pcmConfig(pcm_config);
661   }
662   return a2dp_hal_clientif->UpdateAudioConfig(audio_config);
663 }
664 
start_session()665 void start_session() {
666   if (!is_hal_2_0_enabled()) {
667     LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
668     return;
669   }
670   a2dp_hal_clientif->StartSession();
671 }
672 
end_session()673 void end_session() {
674   if (!is_hal_2_0_enabled()) {
675     LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
676     return;
677   }
678   a2dp_hal_clientif->EndSession();
679 }
680 
ack_stream_started(const tA2DP_CTRL_ACK & ack)681 void ack_stream_started(const tA2DP_CTRL_ACK& ack) {
682   auto ctrl_ack = a2dp_ack_to_bt_audio_ctrl_ack(ack);
683   LOG(INFO) << __func__ << ": result=" << ctrl_ack;
684   auto pending_cmd = a2dp_sink->GetPendingCmd();
685   if (pending_cmd == A2DP_CTRL_CMD_START) {
686     a2dp_hal_clientif->StreamStarted(ctrl_ack);
687   } else {
688     LOG(WARNING) << __func__ << ": pending=" << pending_cmd
689                  << " ignore result=" << ctrl_ack;
690     return;
691   }
692   if (ctrl_ack != bluetooth::audio::BluetoothAudioCtrlAck::PENDING) {
693     a2dp_sink->ResetPendingCmd();
694   }
695 }
696 
ack_stream_suspended(const tA2DP_CTRL_ACK & ack)697 void ack_stream_suspended(const tA2DP_CTRL_ACK& ack) {
698   auto ctrl_ack = a2dp_ack_to_bt_audio_ctrl_ack(ack);
699   LOG(INFO) << __func__ << ": result=" << ctrl_ack;
700   auto pending_cmd = a2dp_sink->GetPendingCmd();
701   if (pending_cmd == A2DP_CTRL_CMD_SUSPEND) {
702     a2dp_hal_clientif->StreamSuspended(ctrl_ack);
703   } else if (pending_cmd == A2DP_CTRL_CMD_STOP) {
704     LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_STOP result=" << ctrl_ack;
705   } else {
706     LOG(WARNING) << __func__ << ": pending=" << pending_cmd
707                  << " ignore result=" << ctrl_ack;
708     return;
709   }
710   if (ctrl_ack != bluetooth::audio::BluetoothAudioCtrlAck::PENDING) {
711     a2dp_sink->ResetPendingCmd();
712   }
713 }
714 
715 // Read from the FMQ of BluetoothAudio HAL
read(uint8_t * p_buf,uint32_t len)716 size_t read(uint8_t* p_buf, uint32_t len) {
717   if (!is_hal_2_0_enabled()) {
718     LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
719     return 0;
720   } else if (session_type != SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH) {
721     LOG(ERROR) << __func__ << ": session_type=" << toString(session_type)
722                << " is not A2DP_SOFTWARE_ENCODING_DATAPATH";
723     return 0;
724   }
725   return a2dp_hal_clientif->ReadAudioData(p_buf, len);
726 }
727 
728 // Update A2DP delay report to BluetoothAudio HAL
set_remote_delay(uint16_t delay_report)729 void set_remote_delay(uint16_t delay_report) {
730   if (!is_hal_2_0_enabled()) {
731     LOG(INFO) << __func__ << ":  not ready for DelayReport "
732               << static_cast<float>(delay_report / 10.0) << " ms";
733     remote_delay = delay_report;
734     return;
735   }
736   LOG(INFO) << __func__ << ": DELAY " << static_cast<float>(delay_report / 10.0)
737             << " ms";
738   a2dp_sink->SetRemoteDelay(delay_report);
739 }
740 
741 }  // namespace a2dp
742 }  // namespace audio
743 }  // namespace bluetooth
744