1 /******************************************************************************
2 *
3 * Copyright 2009-2012 Broadcom Corporation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 /*******************************************************************************
20 *
21 * Filename: btif_hf.c
22 *
23 * Description: Handsfree Profile Bluetooth Interface
24 *
25 *
26 ******************************************************************************/
27
28 #define LOG_TAG "bt_btif_hf"
29
30 #include <cstdlib>
31 #include <cstring>
32 #include <ctime>
33
34 #include <bta/include/bta_ag_api.h>
35 #include <hardware/bluetooth.h>
36 #include <hardware/bluetooth_headset_callbacks.h>
37 #include <hardware/bluetooth_headset_interface.h>
38 #include <hardware/bt_hf.h>
39 #include <log/log.h>
40
41 #include "bta/include/utl.h"
42 #include "bta_ag_api.h"
43 #include "btif_common.h"
44 #include "btif_hf.h"
45 #include "btif_profile_queue.h"
46 #include "btif_util.h"
47 #include "common/metrics.h"
48
49 namespace bluetooth {
50 namespace headset {
51
52 /*******************************************************************************
53 * Constants & Macros
54 ******************************************************************************/
55 #ifndef BTIF_HSAG_SERVICE_NAME
56 #define BTIF_HSAG_SERVICE_NAME ("Headset Gateway")
57 #endif
58
59 #ifndef BTIF_HFAG_SERVICE_NAME
60 #define BTIF_HFAG_SERVICE_NAME ("Handsfree Gateway")
61 #endif
62
63 #ifndef BTIF_HF_SERVICES
64 #define BTIF_HF_SERVICES (BTA_HSP_SERVICE_MASK | BTA_HFP_SERVICE_MASK)
65 #endif
66
67 #ifndef BTIF_HF_SERVICE_NAMES
68 #define BTIF_HF_SERVICE_NAMES \
69 { BTIF_HSAG_SERVICE_NAME, BTIF_HFAG_SERVICE_NAME }
70 #endif
71
72 #ifndef BTIF_HF_SECURITY
73 #define BTIF_HF_SECURITY (BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)
74 #endif
75
76 #ifndef BTIF_HF_FEATURES
77 #define BTIF_HF_FEATURES \
78 (BTA_AG_FEAT_3WAY | BTA_AG_FEAT_ECNR | BTA_AG_FEAT_REJECT | \
79 BTA_AG_FEAT_ECS | BTA_AG_FEAT_EXTERR | BTA_AG_FEAT_VREC | \
80 BTA_AG_FEAT_CODEC | BTA_AG_FEAT_HF_IND | BTA_AG_FEAT_ESCO | \
81 BTA_AG_FEAT_UNAT)
82 #endif
83
84 /* HF features supported at runtime */
85 static uint32_t btif_hf_features = BTIF_HF_FEATURES;
86
87 #define BTIF_HF_INVALID_IDX (-1)
88
89 /* Max HF clients supported from App */
90 static int btif_max_hf_clients = 1;
91 static RawAddress active_bda = {};
92
93 /*******************************************************************************
94 * Static variables
95 ******************************************************************************/
96 static Callbacks* bt_hf_callbacks = nullptr;
97
98 #define CHECK_BTHF_INIT() \
99 do { \
100 if (!bt_hf_callbacks) { \
101 BTIF_TRACE_WARNING("BTHF: %s: BTHF not initialized", __func__); \
102 return BT_STATUS_NOT_READY; \
103 } else { \
104 BTIF_TRACE_EVENT("BTHF: %s", __func__); \
105 } \
106 } while (false)
107
108 /* BTIF-HF control block to map bdaddr to BTA handle */
109 struct btif_hf_cb_t {
110 uint16_t handle;
111 bool is_initiator;
112 RawAddress connected_bda;
113 bthf_connection_state_t state;
114 tBTA_AG_PEER_FEAT peer_feat;
115 int num_active;
116 int num_held;
117 bthf_call_state_t call_setup_state;
118 };
119
120 static btif_hf_cb_t btif_hf_cb[BTA_AG_MAX_NUM_CLIENTS];
121
dump_hf_call_state(bthf_call_state_t call_state)122 static const char* dump_hf_call_state(bthf_call_state_t call_state) {
123 switch (call_state) {
124 CASE_RETURN_STR(BTHF_CALL_STATE_IDLE)
125 CASE_RETURN_STR(BTHF_CALL_STATE_HELD)
126 CASE_RETURN_STR(BTHF_CALL_STATE_DIALING)
127 CASE_RETURN_STR(BTHF_CALL_STATE_ALERTING)
128 CASE_RETURN_STR(BTHF_CALL_STATE_INCOMING)
129 CASE_RETURN_STR(BTHF_CALL_STATE_WAITING)
130 CASE_RETURN_STR(BTHF_CALL_STATE_ACTIVE)
131 CASE_RETURN_STR(BTHF_CALL_STATE_DISCONNECTED)
132 default:
133 return "UNKNOWN CALL STATE";
134 }
135 }
136
137 /**
138 * Check if bd_addr is the current active device.
139 *
140 * @param bd_addr target device address
141 * @return True if bd_addr is the current active device, False otherwise or if
142 * no active device is set (i.e. active_device_addr is empty)
143 */
is_active_device(const RawAddress & bd_addr)144 static bool is_active_device(const RawAddress& bd_addr) {
145 return !active_bda.IsEmpty() && active_bda == bd_addr;
146 }
147
148 /*******************************************************************************
149 *
150 * Function is_connected
151 *
152 * Description Internal function to check if HF is connected
153 * is_connected(nullptr) returns TRUE if one of the control
154 * blocks is connected
155 *
156 * Returns true if connected
157 *
158 ******************************************************************************/
is_connected(RawAddress * bd_addr)159 static bool is_connected(RawAddress* bd_addr) {
160 for (int i = 0; i < btif_max_hf_clients; ++i) {
161 if (((btif_hf_cb[i].state == BTHF_CONNECTION_STATE_CONNECTED) ||
162 (btif_hf_cb[i].state == BTHF_CONNECTION_STATE_SLC_CONNECTED)) &&
163 (!bd_addr || *bd_addr == btif_hf_cb[i].connected_bda))
164 return true;
165 }
166 return false;
167 }
168
169 /*******************************************************************************
170 *
171 * Function btif_hf_idx_by_bdaddr
172 *
173 * Description Internal function to get idx by bdaddr
174 *
175 * Returns idx
176 *
177 ******************************************************************************/
btif_hf_idx_by_bdaddr(RawAddress * bd_addr)178 static int btif_hf_idx_by_bdaddr(RawAddress* bd_addr) {
179 for (int i = 0; i < btif_max_hf_clients; ++i) {
180 if (*bd_addr == btif_hf_cb[i].connected_bda) return i;
181 }
182 return BTIF_HF_INVALID_IDX;
183 }
184
185 /*******************************************************************************
186 *
187 * Function callstate_to_callsetup
188 *
189 * Description Converts HAL call state to BTA call setup indicator value
190 *
191 * Returns BTA call indicator value
192 *
193 ******************************************************************************/
callstate_to_callsetup(bthf_call_state_t call_state)194 static uint8_t callstate_to_callsetup(bthf_call_state_t call_state) {
195 switch (call_state) {
196 case BTHF_CALL_STATE_INCOMING:
197 return 1;
198 case BTHF_CALL_STATE_DIALING:
199 return 2;
200 case BTHF_CALL_STATE_ALERTING:
201 return 3;
202 default:
203 return 0;
204 }
205 }
206
207 /*******************************************************************************
208 *
209 * Function send_at_result
210 *
211 * Description Send AT result code (OK/ERROR)
212 *
213 * Returns void
214 *
215 ******************************************************************************/
send_at_result(uint8_t ok_flag,uint16_t errcode,int idx)216 static void send_at_result(uint8_t ok_flag, uint16_t errcode, int idx) {
217 tBTA_AG_RES_DATA ag_res = {};
218 ag_res.ok_flag = ok_flag;
219 if (ok_flag == BTA_AG_OK_ERROR) {
220 ag_res.errcode = errcode;
221 }
222 BTA_AgResult(btif_hf_cb[idx].handle, BTA_AG_UNAT_RES, ag_res);
223 }
224
225 /*******************************************************************************
226 *
227 * Function send_indicator_update
228 *
229 * Description Send indicator update (CIEV)
230 *
231 * Returns void
232 *
233 ******************************************************************************/
send_indicator_update(const btif_hf_cb_t & control_block,uint16_t indicator,uint16_t value)234 static void send_indicator_update(const btif_hf_cb_t& control_block,
235 uint16_t indicator, uint16_t value) {
236 tBTA_AG_RES_DATA ag_res = {};
237 ag_res.ind.id = indicator;
238 ag_res.ind.value = value;
239 BTA_AgResult(control_block.handle, BTA_AG_IND_RES, ag_res);
240 }
241
is_nth_bit_enabled(uint32_t value,int n)242 static bool is_nth_bit_enabled(uint32_t value, int n) {
243 return (value & (static_cast<uint32_t>(1) << n)) != 0;
244 }
245
clear_phone_state_multihf(btif_hf_cb_t * hf_cb)246 void clear_phone_state_multihf(btif_hf_cb_t* hf_cb) {
247 hf_cb->call_setup_state = BTHF_CALL_STATE_IDLE;
248 hf_cb->num_active = 0;
249 hf_cb->num_held = 0;
250 }
251
reset_control_block(btif_hf_cb_t * hf_cb)252 static void reset_control_block(btif_hf_cb_t* hf_cb) {
253 hf_cb->state = BTHF_CONNECTION_STATE_DISCONNECTED;
254 hf_cb->is_initiator = false;
255 hf_cb->connected_bda = RawAddress::kEmpty;
256 hf_cb->peer_feat = 0;
257 clear_phone_state_multihf(hf_cb);
258 }
259
260 /**
261 * Check if Service Level Connection (SLC) is established for bd_addr
262 *
263 * @param bd_addr remote device address
264 * @return true if SLC is established for bd_addr
265 */
IsSlcConnected(RawAddress * bd_addr)266 static bool IsSlcConnected(RawAddress* bd_addr) {
267 if (!bd_addr) {
268 LOG(WARNING) << __func__ << ": bd_addr is null";
269 return false;
270 }
271 int idx = btif_hf_idx_by_bdaddr(bd_addr);
272 if (idx < 0 || idx > BTA_AG_MAX_NUM_CLIENTS) {
273 LOG(WARNING) << __func__ << ": invalid index " << idx << " for "
274 << *bd_addr;
275 return false;
276 }
277 return btif_hf_cb[idx].state == BTHF_CONNECTION_STATE_SLC_CONNECTED;
278 }
279
280 /*******************************************************************************
281 *
282 * Function btif_hf_upstreams_evt
283 *
284 * Description Executes HF UPSTREAMS events in btif context
285 *
286 * Returns void
287 *
288 ******************************************************************************/
btif_hf_upstreams_evt(uint16_t event,char * p_param)289 static void btif_hf_upstreams_evt(uint16_t event, char* p_param) {
290 if (event == BTA_AG_ENABLE_EVT || event == BTA_AG_DISABLE_EVT) {
291 LOG(INFO) << __func__ << ": AG enable/disable event " << event;
292 return;
293 }
294 if (p_param == nullptr) {
295 LOG(ERROR) << __func__ << ": parameter is null";
296 return;
297 }
298 tBTA_AG* p_data = (tBTA_AG*)p_param;
299 int idx = p_data->hdr.handle - 1;
300
301 BTIF_TRACE_DEBUG("%s: event=%s", __func__, dump_hf_event(event));
302
303 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
304 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
305 return;
306 }
307 if (!bt_hf_callbacks) {
308 BTIF_TRACE_ERROR("%s: Headset callback is NULL", __func__);
309 return;
310 }
311
312 switch (event) {
313 case BTA_AG_REGISTER_EVT:
314 btif_hf_cb[idx].handle = p_data->reg.hdr.handle;
315 BTIF_TRACE_DEBUG("%s: BTA_AG_REGISTER_EVT, btif_hf_cb.handle = %d",
316 __func__, btif_hf_cb[idx].handle);
317 break;
318 // RFCOMM connected or failed to connect
319 case BTA_AG_OPEN_EVT:
320 // Check if an outoging connection is pending
321 if (btif_hf_cb[idx].is_initiator) {
322 if ((p_data->open.status != BTA_AG_SUCCESS) &&
323 btif_hf_cb[idx].state != BTHF_CONNECTION_STATE_CONNECTING) {
324 if (p_data->open.bd_addr == btif_hf_cb[idx].connected_bda) {
325 LOG(WARNING) << __func__ << ": btif_hf_cb state["
326 << p_data->open.status
327 << "] is not expected, possible connection collision, "
328 "ignoring AG open "
329 "failure event for the same device "
330 << p_data->open.bd_addr;
331 } else {
332 LOG(WARNING) << __func__ << ": btif_hf_cb state["
333 << p_data->open.status
334 << "] is not expected, possible connection collision, "
335 "ignoring AG open failure "
336 "event for the different devices btif_hf_cb bda: "
337 << btif_hf_cb[idx].connected_bda
338 << ", p_data bda: " << p_data->open.bd_addr
339 << ", report disconnect state for p_data bda.";
340 bt_hf_callbacks->ConnectionStateCallback(
341 BTHF_CONNECTION_STATE_DISCONNECTED, &(p_data->open.bd_addr));
342 }
343 break;
344 }
345
346 CHECK_EQ(btif_hf_cb[idx].state, BTHF_CONNECTION_STATE_CONNECTING)
347 << "Control block must be in connecting state when initiating";
348 CHECK(!btif_hf_cb[idx].connected_bda.IsEmpty())
349 << "Remote device address must not be empty when initiating";
350 if (btif_hf_cb[idx].connected_bda != p_data->open.bd_addr) {
351 LOG(WARNING) << __func__
352 << ": possible connection collision, ignore the "
353 "outgoing connection for the "
354 "different devices btif_hf_cb bda: "
355 << btif_hf_cb[idx].connected_bda
356 << ", p_data bda: " << p_data->open.bd_addr
357 << ", report disconnect state for btif_hf_cb bda.";
358 bt_hf_callbacks->ConnectionStateCallback(
359 BTHF_CONNECTION_STATE_DISCONNECTED,
360 &(btif_hf_cb[idx].connected_bda));
361 reset_control_block(&btif_hf_cb[idx]);
362 btif_queue_advance();
363 }
364 }
365 if (p_data->open.status == BTA_AG_SUCCESS) {
366 // In case this is an incoming connection
367 btif_hf_cb[idx].connected_bda = p_data->open.bd_addr;
368 btif_hf_cb[idx].state = BTHF_CONNECTION_STATE_CONNECTED;
369 btif_hf_cb[idx].peer_feat = 0;
370 clear_phone_state_multihf(&btif_hf_cb[idx]);
371 bluetooth::common::BluetoothMetricsLogger::GetInstance()
372 ->LogHeadsetProfileRfcConnection(p_data->open.service_id);
373 bt_hf_callbacks->ConnectionStateCallback(
374 btif_hf_cb[idx].state, &btif_hf_cb[idx].connected_bda);
375 } else {
376 if (!btif_hf_cb[idx].is_initiator) {
377 // Ignore remote initiated open failures
378 LOG(WARNING) << __func__ << ": Unexpected AG open failure "
379 << std::to_string(p_data->open.status) << " for "
380 << p_data->open.bd_addr << " is ignored";
381 break;
382 }
383 LOG(ERROR) << __func__ << ": self initiated AG open failed for "
384 << btif_hf_cb[idx].connected_bda << ", status "
385 << std::to_string(p_data->open.status);
386 RawAddress connected_bda = btif_hf_cb[idx].connected_bda;
387 reset_control_block(&btif_hf_cb[idx]);
388 bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state,
389 &connected_bda);
390 btif_queue_advance();
391 }
392 break;
393 // SLC and RFCOMM both disconnected
394 case BTA_AG_CLOSE_EVT: {
395 BTIF_TRACE_DEBUG("%s: BTA_AG_CLOSE_EVT, idx = %d, btif_hf_cb.handle = %d",
396 __func__, idx, btif_hf_cb[idx].handle);
397 // If AG_OPEN was received but SLC was not connected in time, then
398 // AG_CLOSE may be received. We need to advance the queue here.
399 bool failed_to_setup_slc =
400 (btif_hf_cb[idx].state != BTHF_CONNECTION_STATE_SLC_CONNECTED) &&
401 btif_hf_cb[idx].is_initiator;
402 RawAddress connected_bda = btif_hf_cb[idx].connected_bda;
403 reset_control_block(&btif_hf_cb[idx]);
404 bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state,
405 &connected_bda);
406 if (failed_to_setup_slc) {
407 LOG(ERROR) << __func__ << ": failed to setup SLC for " << connected_bda;
408 btif_queue_advance();
409 }
410 break;
411 }
412 // SLC connected
413 case BTA_AG_CONN_EVT:
414 BTIF_TRACE_DEBUG("%s: BTA_AG_CONN_EVT, idx = %d ", __func__, idx);
415 btif_hf_cb[idx].peer_feat = p_data->conn.peer_feat;
416 btif_hf_cb[idx].state = BTHF_CONNECTION_STATE_SLC_CONNECTED;
417 bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state,
418 &btif_hf_cb[idx].connected_bda);
419 if (btif_hf_cb[idx].is_initiator) {
420 btif_queue_advance();
421 }
422 break;
423
424 case BTA_AG_AUDIO_OPEN_EVT:
425 bt_hf_callbacks->AudioStateCallback(BTHF_AUDIO_STATE_CONNECTED,
426 &btif_hf_cb[idx].connected_bda);
427 break;
428
429 case BTA_AG_AUDIO_CLOSE_EVT:
430 bt_hf_callbacks->AudioStateCallback(BTHF_AUDIO_STATE_DISCONNECTED,
431 &btif_hf_cb[idx].connected_bda);
432 break;
433
434 /* BTA auto-responds, silently discard */
435 case BTA_AG_SPK_EVT:
436 case BTA_AG_MIC_EVT:
437 bt_hf_callbacks->VolumeControlCallback(
438 (event == BTA_AG_SPK_EVT) ? BTHF_VOLUME_TYPE_SPK
439 : BTHF_VOLUME_TYPE_MIC,
440 p_data->val.num, &btif_hf_cb[idx].connected_bda);
441 break;
442
443 case BTA_AG_AT_A_EVT:
444 bt_hf_callbacks->AnswerCallCallback(&btif_hf_cb[idx].connected_bda);
445 break;
446
447 /* Java needs to send OK/ERROR for these commands */
448 case BTA_AG_AT_BLDN_EVT:
449 case BTA_AG_AT_D_EVT:
450 bt_hf_callbacks->DialCallCallback(
451 (event == BTA_AG_AT_D_EVT) ? p_data->val.str : (char*)"",
452 &btif_hf_cb[idx].connected_bda);
453 break;
454
455 case BTA_AG_AT_CHUP_EVT:
456 bt_hf_callbacks->HangupCallCallback(&btif_hf_cb[idx].connected_bda);
457 break;
458
459 case BTA_AG_AT_CIND_EVT:
460 bt_hf_callbacks->AtCindCallback(&btif_hf_cb[idx].connected_bda);
461 break;
462
463 case BTA_AG_AT_VTS_EVT:
464 bt_hf_callbacks->DtmfCmdCallback(p_data->val.str[0],
465 &btif_hf_cb[idx].connected_bda);
466 break;
467
468 case BTA_AG_AT_BVRA_EVT:
469 bt_hf_callbacks->VoiceRecognitionCallback((p_data->val.num == 1)
470 ? BTHF_VR_STATE_STARTED
471 : BTHF_VR_STATE_STOPPED,
472 &btif_hf_cb[idx].connected_bda);
473 break;
474
475 case BTA_AG_AT_NREC_EVT:
476 bt_hf_callbacks->NoiseReductionCallback(
477 (p_data->val.num == 1) ? BTHF_NREC_START : BTHF_NREC_STOP,
478 &btif_hf_cb[idx].connected_bda);
479 break;
480
481 /* TODO: Add a callback for CBC */
482 case BTA_AG_AT_CBC_EVT:
483 break;
484
485 case BTA_AG_AT_CKPD_EVT:
486 bt_hf_callbacks->KeyPressedCallback(&btif_hf_cb[idx].connected_bda);
487 break;
488
489 case BTA_AG_WBS_EVT:
490 BTIF_TRACE_DEBUG(
491 "BTA_AG_WBS_EVT Set codec status %d codec %d 1=CVSD 2=MSBC",
492 p_data->val.hdr.status, p_data->val.num);
493 if (p_data->val.num == BTA_AG_CODEC_CVSD) {
494 bt_hf_callbacks->WbsCallback(BTHF_WBS_NO,
495 &btif_hf_cb[idx].connected_bda);
496 } else if (p_data->val.num == BTA_AG_CODEC_MSBC) {
497 bt_hf_callbacks->WbsCallback(BTHF_WBS_YES,
498 &btif_hf_cb[idx].connected_bda);
499 } else {
500 bt_hf_callbacks->WbsCallback(BTHF_WBS_NONE,
501 &btif_hf_cb[idx].connected_bda);
502 }
503 break;
504
505 /* Java needs to send OK/ERROR for these commands */
506 case BTA_AG_AT_CHLD_EVT:
507 bt_hf_callbacks->AtChldCallback((bthf_chld_type_t)atoi(p_data->val.str),
508 &btif_hf_cb[idx].connected_bda);
509 break;
510
511 case BTA_AG_AT_CLCC_EVT:
512 bt_hf_callbacks->AtClccCallback(&btif_hf_cb[idx].connected_bda);
513 break;
514
515 case BTA_AG_AT_COPS_EVT:
516 bt_hf_callbacks->AtCopsCallback(&btif_hf_cb[idx].connected_bda);
517 break;
518
519 case BTA_AG_AT_UNAT_EVT:
520 bt_hf_callbacks->UnknownAtCallback(p_data->val.str,
521 &btif_hf_cb[idx].connected_bda);
522 break;
523
524 case BTA_AG_AT_CNUM_EVT:
525 bt_hf_callbacks->AtCnumCallback(&btif_hf_cb[idx].connected_bda);
526 break;
527
528 /* TODO: Some of these commands may need to be sent to app. For now respond
529 * with error */
530 case BTA_AG_AT_BINP_EVT:
531 case BTA_AG_AT_BTRH_EVT:
532 send_at_result(BTA_AG_OK_ERROR, BTA_AG_ERR_OP_NOT_SUPPORTED, idx);
533 break;
534 case BTA_AG_AT_BAC_EVT:
535 BTIF_TRACE_DEBUG("AG Bitmap of peer-codecs %d", p_data->val.num);
536 /* If the peer supports mSBC and the BTIF preferred codec is also mSBC,
537 then
538 we should set the BTA AG Codec to mSBC. This would trigger a +BCS to mSBC
539 at the time
540 of SCO connection establishment */
541 if (p_data->val.num & BTA_AG_CODEC_MSBC) {
542 BTIF_TRACE_EVENT("%s: btif_hf override-Preferred Codec to MSBC",
543 __func__);
544 BTA_AgSetCodec(btif_hf_cb[idx].handle, BTA_AG_CODEC_MSBC);
545 } else {
546 BTIF_TRACE_EVENT("%s btif_hf override-Preferred Codec to CVSD",
547 __func__);
548 BTA_AgSetCodec(btif_hf_cb[idx].handle, BTA_AG_CODEC_CVSD);
549 }
550 break;
551 case BTA_AG_AT_BCS_EVT:
552 BTIF_TRACE_DEBUG("%s: AG final selected codec is 0x%02x 1=CVSD 2=MSBC",
553 __func__, p_data->val.num);
554 /* No BTHF_WBS_NONE case, because HF1.6 supported device can send BCS */
555 /* Only CVSD is considered narrow band speech */
556 bt_hf_callbacks->WbsCallback(
557 (p_data->val.num == BTA_AG_CODEC_CVSD) ? BTHF_WBS_NO : BTHF_WBS_YES,
558 &btif_hf_cb[idx].connected_bda);
559 break;
560
561 case BTA_AG_AT_BIND_EVT:
562 if (p_data->val.hdr.status == BTA_AG_SUCCESS) {
563 bt_hf_callbacks->AtBindCallback(p_data->val.str,
564 &btif_hf_cb[idx].connected_bda);
565 }
566 break;
567
568 case BTA_AG_AT_BIEV_EVT:
569 if (p_data->val.hdr.status == BTA_AG_SUCCESS) {
570 bt_hf_callbacks->AtBievCallback((bthf_hf_ind_type_t)p_data->val.lidx,
571 (int)p_data->val.num,
572 &btif_hf_cb[idx].connected_bda);
573 }
574 break;
575 case BTA_AG_AT_BIA_EVT:
576 if (p_data->val.hdr.status == BTA_AG_SUCCESS) {
577 uint32_t bia_mask_out = p_data->val.num;
578 bool service = !is_nth_bit_enabled(bia_mask_out, BTA_AG_IND_SERVICE);
579 bool roam = !is_nth_bit_enabled(bia_mask_out, BTA_AG_IND_ROAM);
580 bool signal = !is_nth_bit_enabled(bia_mask_out, BTA_AG_IND_SIGNAL);
581 bool battery = !is_nth_bit_enabled(bia_mask_out, BTA_AG_IND_BATTCHG);
582 bt_hf_callbacks->AtBiaCallback(service, roam, signal, battery,
583 &btif_hf_cb[idx].connected_bda);
584 }
585 break;
586 default:
587 LOG(WARNING) << __func__ << ": unhandled event " << event;
588 break;
589 }
590 }
591
592 /*******************************************************************************
593 *
594 * Function bte_hf_evt
595 *
596 * Description Switches context from BTE to BTIF for all HF events
597 *
598 * Returns void
599 *
600 ******************************************************************************/
601
bte_hf_evt(tBTA_AG_EVT event,tBTA_AG * p_data)602 static void bte_hf_evt(tBTA_AG_EVT event, tBTA_AG* p_data) {
603 bt_status_t status;
604 int param_len = 0;
605
606 /* TODO: BTA sends the union members and not tBTA_AG. If using
607 * param_len=sizeof(tBTA_AG), we get a crash on memcpy */
608 if (BTA_AG_REGISTER_EVT == event)
609 param_len = sizeof(tBTA_AG_REGISTER);
610 else if (BTA_AG_OPEN_EVT == event)
611 param_len = sizeof(tBTA_AG_OPEN);
612 else if (BTA_AG_CONN_EVT == event)
613 param_len = sizeof(tBTA_AG_CONN);
614 else if ((BTA_AG_CLOSE_EVT == event) || (BTA_AG_AUDIO_OPEN_EVT == event) ||
615 (BTA_AG_AUDIO_CLOSE_EVT == event))
616 param_len = sizeof(tBTA_AG_HDR);
617 else if (p_data)
618 param_len = sizeof(tBTA_AG_VAL);
619
620 /* switch context to btif task context (copy full union size for convenience)
621 */
622 status = btif_transfer_context(btif_hf_upstreams_evt, (uint16_t)event,
623 (char*)p_data, param_len, nullptr);
624
625 /* catch any failed context transfers */
626 ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status);
627 }
628
629 /*******************************************************************************
630 *
631 * Function connect
632 *
633 * Description connect to headset
634 *
635 * Returns bt_status_t
636 *
637 ******************************************************************************/
connect_int(RawAddress * bd_addr,uint16_t uuid)638 static bt_status_t connect_int(RawAddress* bd_addr, uint16_t uuid) {
639 CHECK_BTHF_INIT();
640 if (is_connected(bd_addr)) {
641 BTIF_TRACE_WARNING("%s: device %s is already connected", __func__,
642 bd_addr->ToString().c_str());
643 return BT_STATUS_BUSY;
644 }
645 btif_hf_cb_t* hf_cb = nullptr;
646 for (int i = 0; i < btif_max_hf_clients; i++) {
647 if (btif_hf_cb[i].state == BTHF_CONNECTION_STATE_DISCONNECTED) {
648 hf_cb = &btif_hf_cb[i];
649 break;
650 }
651 // Due to btif queue implementation, when connect_int is called, no btif
652 // control block should be in connecting state
653 // Crash here to prevent future code changes from breaking this mechanism
654 if (btif_hf_cb[i].state == BTHF_CONNECTION_STATE_CONNECTING) {
655 LOG(FATAL) << __func__ << ": " << btif_hf_cb[i].connected_bda
656 << ", handle " << btif_hf_cb[i].handle
657 << ", is still in connecting state " << btif_hf_cb[i].state;
658 }
659 }
660 if (hf_cb == nullptr) {
661 BTIF_TRACE_WARNING(
662 "%s: Cannot connect %s: maximum %d clients already connected", __func__,
663 bd_addr->ToString().c_str(), btif_max_hf_clients);
664 return BT_STATUS_BUSY;
665 }
666 hf_cb->state = BTHF_CONNECTION_STATE_CONNECTING;
667 hf_cb->connected_bda = *bd_addr;
668 hf_cb->is_initiator = true;
669 hf_cb->peer_feat = 0;
670 BTA_AgOpen(hf_cb->handle, hf_cb->connected_bda, BTIF_HF_SECURITY);
671 return BT_STATUS_SUCCESS;
672 }
673
UpdateCallStates(btif_hf_cb_t * control_block,int num_active,int num_held,bthf_call_state_t call_setup_state)674 static void UpdateCallStates(btif_hf_cb_t* control_block, int num_active,
675 int num_held, bthf_call_state_t call_setup_state) {
676 control_block->num_active = num_active;
677 control_block->num_held = num_held;
678 control_block->call_setup_state = call_setup_state;
679 }
680
681 /*******************************************************************************
682 *
683 * Function btif_hf_is_call_idle
684 *
685 * Description returns true if no call is in progress
686 *
687 * Returns bt_status_t
688 *
689 ******************************************************************************/
IsCallIdle()690 bool IsCallIdle() {
691 if (!bt_hf_callbacks) return true;
692
693 for (int i = 0; i < btif_max_hf_clients; ++i) {
694 if ((btif_hf_cb[i].call_setup_state != BTHF_CALL_STATE_IDLE) ||
695 ((btif_hf_cb[i].num_held + btif_hf_cb[i].num_active) > 0))
696 return false;
697 }
698
699 return true;
700 }
701
702 class HeadsetInterface : Interface {
703 public:
GetInstance()704 static Interface* GetInstance() {
705 static Interface* instance = new HeadsetInterface();
706 return instance;
707 }
708 bt_status_t Init(Callbacks* callbacks, int max_hf_clients,
709 bool inband_ringing_enabled) override;
710 bt_status_t Connect(RawAddress* bd_addr) override;
711 bt_status_t Disconnect(RawAddress* bd_addr) override;
712 bt_status_t ConnectAudio(RawAddress* bd_addr) override;
713 bt_status_t DisconnectAudio(RawAddress* bd_addr) override;
714 bt_status_t StartVoiceRecognition(RawAddress* bd_addr) override;
715 bt_status_t StopVoiceRecognition(RawAddress* bd_addr) override;
716 bt_status_t VolumeControl(bthf_volume_type_t type, int volume,
717 RawAddress* bd_addr) override;
718 bt_status_t DeviceStatusNotification(bthf_network_state_t ntk_state,
719 bthf_service_type_t svc_type, int signal,
720 int batt_chg,
721 RawAddress* bd_addr) override;
722 bt_status_t CopsResponse(const char* cops, RawAddress* bd_addr) override;
723 bt_status_t CindResponse(int svc, int num_active, int num_held,
724 bthf_call_state_t call_setup_state, int signal,
725 int roam, int batt_chg,
726 RawAddress* bd_addr) override;
727 bt_status_t FormattedAtResponse(const char* rsp,
728 RawAddress* bd_addr) override;
729 bt_status_t AtResponse(bthf_at_response_t response_code, int error_code,
730 RawAddress* bd_addr) override;
731 bt_status_t ClccResponse(int index, bthf_call_direction_t dir,
732 bthf_call_state_t state, bthf_call_mode_t mode,
733 bthf_call_mpty_type_t mpty, const char* number,
734 bthf_call_addrtype_t type,
735 RawAddress* bd_addr) override;
736 bt_status_t PhoneStateChange(int num_active, int num_held,
737 bthf_call_state_t call_setup_state,
738 const char* number, bthf_call_addrtype_t type,
739 const char* name, RawAddress* bd_addr) override;
740
741 void Cleanup() override;
742 bt_status_t SetScoAllowed(bool value) override;
743 bt_status_t SendBsir(bool value, RawAddress* bd_addr) override;
744 bt_status_t SetActiveDevice(RawAddress* active_device_addr) override;
745 };
746
Init(Callbacks * callbacks,int max_hf_clients,bool inband_ringing_enabled)747 bt_status_t HeadsetInterface::Init(Callbacks* callbacks, int max_hf_clients,
748 bool inband_ringing_enabled) {
749 if (inband_ringing_enabled) {
750 btif_hf_features |= BTA_AG_FEAT_INBAND;
751 } else {
752 btif_hf_features &= ~BTA_AG_FEAT_INBAND;
753 }
754 CHECK_LE(max_hf_clients, BTA_AG_MAX_NUM_CLIENTS)
755 << __func__
756 << "Too many HF clients,"
757 " maximum is "
758 << BTA_AG_MAX_NUM_CLIENTS << " was given " << max_hf_clients;
759 btif_max_hf_clients = max_hf_clients;
760 BTIF_TRACE_DEBUG(
761 "%s: btif_hf_features=%zu, max_hf_clients=%d, inband_ringing_enabled=%d",
762 __func__, btif_hf_features, btif_max_hf_clients, inband_ringing_enabled);
763 bt_hf_callbacks = callbacks;
764 for (btif_hf_cb_t& hf_cb : btif_hf_cb) {
765 reset_control_block(&hf_cb);
766 }
767
768 // Invoke the enable service API to the core to set the appropriate service_id
769 // Internally, the HSP_SERVICE_ID shall also be enabled if HFP is enabled
770 // (phone) otherwise only HSP is enabled (tablet)
771 #if (defined(BTIF_HF_SERVICES) && (BTIF_HF_SERVICES & BTA_HFP_SERVICE_MASK))
772 btif_enable_service(BTA_HFP_SERVICE_ID);
773 #else
774 btif_enable_service(BTA_HSP_SERVICE_ID);
775 #endif
776
777 return BT_STATUS_SUCCESS;
778 }
779
Connect(RawAddress * bd_addr)780 bt_status_t HeadsetInterface::Connect(RawAddress* bd_addr) {
781 CHECK_BTHF_INIT();
782 return btif_queue_connect(UUID_SERVCLASS_AG_HANDSFREE, bd_addr, connect_int);
783 }
784
Disconnect(RawAddress * bd_addr)785 bt_status_t HeadsetInterface::Disconnect(RawAddress* bd_addr) {
786 CHECK_BTHF_INIT();
787 int idx = btif_hf_idx_by_bdaddr(bd_addr);
788 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
789 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
790 return BT_STATUS_FAIL;
791 }
792 if (!is_connected(bd_addr)) {
793 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
794 bd_addr->ToString().c_str());
795 return BT_STATUS_FAIL;
796 }
797 BTA_AgClose(btif_hf_cb[idx].handle);
798 return BT_STATUS_SUCCESS;
799 }
800
ConnectAudio(RawAddress * bd_addr)801 bt_status_t HeadsetInterface::ConnectAudio(RawAddress* bd_addr) {
802 CHECK_BTHF_INIT();
803 int idx = btif_hf_idx_by_bdaddr(bd_addr);
804 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
805 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
806 return BT_STATUS_FAIL;
807 }
808 /* Check if SLC is connected */
809 if (!IsSlcConnected(bd_addr)) {
810 LOG(ERROR) << ": SLC not connected for " << *bd_addr;
811 return BT_STATUS_NOT_READY;
812 }
813 do_in_jni_thread(base::Bind(&Callbacks::AudioStateCallback,
814 // Manual pointer management for now
815 base::Unretained(bt_hf_callbacks),
816 BTHF_AUDIO_STATE_CONNECTING,
817 &btif_hf_cb[idx].connected_bda));
818 BTA_AgAudioOpen(btif_hf_cb[idx].handle);
819 return BT_STATUS_SUCCESS;
820 }
821
DisconnectAudio(RawAddress * bd_addr)822 bt_status_t HeadsetInterface::DisconnectAudio(RawAddress* bd_addr) {
823 CHECK_BTHF_INIT();
824 int idx = btif_hf_idx_by_bdaddr(bd_addr);
825 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
826 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
827 return BT_STATUS_FAIL;
828 }
829 if (!is_connected(bd_addr)) {
830 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
831 bd_addr->ToString().c_str());
832 return BT_STATUS_FAIL;
833 }
834 BTA_AgAudioClose(btif_hf_cb[idx].handle);
835 return BT_STATUS_SUCCESS;
836 }
837
StartVoiceRecognition(RawAddress * bd_addr)838 bt_status_t HeadsetInterface::StartVoiceRecognition(RawAddress* bd_addr) {
839 CHECK_BTHF_INIT();
840 int idx = btif_hf_idx_by_bdaddr(bd_addr);
841 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
842 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
843 return BT_STATUS_FAIL;
844 }
845 if (!is_connected(bd_addr)) {
846 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
847 bd_addr->ToString().c_str());
848 return BT_STATUS_NOT_READY;
849 }
850 if (!(btif_hf_cb[idx].peer_feat & BTA_AG_PEER_FEAT_VREC)) {
851 BTIF_TRACE_ERROR("%s: voice recognition not supported, features=0x%x",
852 __func__, btif_hf_cb[idx].peer_feat);
853 return BT_STATUS_UNSUPPORTED;
854 }
855 tBTA_AG_RES_DATA ag_res = {};
856 ag_res.state = true;
857 BTA_AgResult(btif_hf_cb[idx].handle, BTA_AG_BVRA_RES, ag_res);
858 return BT_STATUS_SUCCESS;
859 }
860
StopVoiceRecognition(RawAddress * bd_addr)861 bt_status_t HeadsetInterface::StopVoiceRecognition(RawAddress* bd_addr) {
862 CHECK_BTHF_INIT();
863 int idx = btif_hf_idx_by_bdaddr(bd_addr);
864
865 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
866 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
867 return BT_STATUS_FAIL;
868 }
869 if (!is_connected(bd_addr)) {
870 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
871 bd_addr->ToString().c_str());
872 return BT_STATUS_NOT_READY;
873 }
874 if (!(btif_hf_cb[idx].peer_feat & BTA_AG_PEER_FEAT_VREC)) {
875 BTIF_TRACE_ERROR("%s: voice recognition not supported, features=0x%x",
876 __func__, btif_hf_cb[idx].peer_feat);
877 return BT_STATUS_UNSUPPORTED;
878 }
879 tBTA_AG_RES_DATA ag_res = {};
880 ag_res.state = false;
881 BTA_AgResult(btif_hf_cb[idx].handle, BTA_AG_BVRA_RES, ag_res);
882 return BT_STATUS_SUCCESS;
883 }
884
VolumeControl(bthf_volume_type_t type,int volume,RawAddress * bd_addr)885 bt_status_t HeadsetInterface::VolumeControl(bthf_volume_type_t type, int volume,
886 RawAddress* bd_addr) {
887 CHECK_BTHF_INIT();
888 int idx = btif_hf_idx_by_bdaddr(bd_addr);
889 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
890 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
891 return BT_STATUS_FAIL;
892 }
893 if (!is_connected(bd_addr)) {
894 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
895 bd_addr->ToString().c_str());
896 return BT_STATUS_FAIL;
897 }
898 tBTA_AG_RES_DATA ag_res = {};
899 ag_res.num = static_cast<uint16_t>(volume);
900 BTA_AgResult(btif_hf_cb[idx].handle,
901 (type == BTHF_VOLUME_TYPE_SPK) ? BTA_AG_SPK_RES : BTA_AG_MIC_RES,
902 ag_res);
903 return BT_STATUS_SUCCESS;
904 }
905
DeviceStatusNotification(bthf_network_state_t ntk_state,bthf_service_type_t svc_type,int signal,int batt_chg,RawAddress * bd_addr)906 bt_status_t HeadsetInterface::DeviceStatusNotification(
907 bthf_network_state_t ntk_state, bthf_service_type_t svc_type, int signal,
908 int batt_chg, RawAddress* bd_addr) {
909 CHECK_BTHF_INIT();
910 if (!bd_addr) {
911 BTIF_TRACE_WARNING("%s: bd_addr is null", __func__);
912 return BT_STATUS_FAIL;
913 }
914 int idx = btif_hf_idx_by_bdaddr(bd_addr);
915 if (idx < 0 || idx > BTA_AG_MAX_NUM_CLIENTS) {
916 BTIF_TRACE_WARNING("%s: invalid index %d for %s", __func__, idx,
917 bd_addr->ToString().c_str());
918 return BT_STATUS_FAIL;
919 }
920 const btif_hf_cb_t& control_block = btif_hf_cb[idx];
921 // ok if no device is connected
922 if (is_connected(nullptr)) {
923 // send all indicators to BTA.
924 // BTA will make sure no duplicates are sent out
925 send_indicator_update(control_block, BTA_AG_IND_SERVICE,
926 (ntk_state == BTHF_NETWORK_STATE_AVAILABLE) ? 1 : 0);
927 send_indicator_update(control_block, BTA_AG_IND_ROAM,
928 (svc_type == BTHF_SERVICE_TYPE_HOME) ? 0 : 1);
929 send_indicator_update(control_block, BTA_AG_IND_SIGNAL, signal);
930 send_indicator_update(control_block, BTA_AG_IND_BATTCHG, batt_chg);
931 }
932 return BT_STATUS_SUCCESS;
933 }
934
CopsResponse(const char * cops,RawAddress * bd_addr)935 bt_status_t HeadsetInterface::CopsResponse(const char* cops,
936 RawAddress* bd_addr) {
937 CHECK_BTHF_INIT();
938 int idx = btif_hf_idx_by_bdaddr(bd_addr);
939 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
940 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
941 return BT_STATUS_FAIL;
942 }
943 if (!is_connected(bd_addr)) {
944 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
945 bd_addr->ToString().c_str());
946 return BT_STATUS_FAIL;
947 }
948 tBTA_AG_RES_DATA ag_res = {};
949 /* Format the response */
950 snprintf(ag_res.str, sizeof(ag_res.str), "0,0,\"%.16s\"", cops);
951 ag_res.ok_flag = BTA_AG_OK_DONE;
952 BTA_AgResult(btif_hf_cb[idx].handle, BTA_AG_COPS_RES, ag_res);
953 return BT_STATUS_SUCCESS;
954 }
955
CindResponse(int svc,int num_active,int num_held,bthf_call_state_t call_setup_state,int signal,int roam,int batt_chg,RawAddress * bd_addr)956 bt_status_t HeadsetInterface::CindResponse(int svc, int num_active,
957 int num_held,
958 bthf_call_state_t call_setup_state,
959 int signal, int roam, int batt_chg,
960 RawAddress* bd_addr) {
961 CHECK_BTHF_INIT();
962 int idx = btif_hf_idx_by_bdaddr(bd_addr);
963 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
964 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
965 return BT_STATUS_FAIL;
966 }
967 if (!is_connected(bd_addr)) {
968 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
969 bd_addr->ToString().c_str());
970 return BT_STATUS_FAIL;
971 }
972 tBTA_AG_RES_DATA ag_res = {};
973 // per the errata 2043, call=1 implies atleast one call is in progress
974 // (active/held), see:
975 // https://www.bluetooth.org/errata/errata_view.cfm?errata_id=2043
976 snprintf(ag_res.str, sizeof(ag_res.str), "%d,%d,%d,%d,%d,%d,%d",
977 (num_active + num_held) ? 1 : 0, /* Call state */
978 callstate_to_callsetup(call_setup_state), /* Callsetup state */
979 svc, /* network service */
980 signal, /* Signal strength */
981 roam, /* Roaming indicator */
982 batt_chg, /* Battery level */
983 ((num_held == 0) ? 0 : ((num_active == 0) ? 2 : 1))); /* Call held */
984 BTA_AgResult(btif_hf_cb[idx].handle, BTA_AG_CIND_RES, ag_res);
985 return BT_STATUS_SUCCESS;
986 }
987
FormattedAtResponse(const char * rsp,RawAddress * bd_addr)988 bt_status_t HeadsetInterface::FormattedAtResponse(const char* rsp,
989 RawAddress* bd_addr) {
990 CHECK_BTHF_INIT();
991 tBTA_AG_RES_DATA ag_res = {};
992 int idx = btif_hf_idx_by_bdaddr(bd_addr);
993 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
994 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
995 return BT_STATUS_FAIL;
996 }
997 if (!is_connected(bd_addr)) {
998 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
999 bd_addr->ToString().c_str());
1000 return BT_STATUS_FAIL;
1001 }
1002 /* Format the response and send */
1003 strncpy(ag_res.str, rsp, BTA_AG_AT_MAX_LEN);
1004 BTA_AgResult(btif_hf_cb[idx].handle, BTA_AG_UNAT_RES, ag_res);
1005 return BT_STATUS_SUCCESS;
1006 }
1007
AtResponse(bthf_at_response_t response_code,int error_code,RawAddress * bd_addr)1008 bt_status_t HeadsetInterface::AtResponse(bthf_at_response_t response_code,
1009 int error_code, RawAddress* bd_addr) {
1010 CHECK_BTHF_INIT();
1011 int idx = btif_hf_idx_by_bdaddr(bd_addr);
1012 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
1013 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
1014 return BT_STATUS_FAIL;
1015 }
1016 if (!is_connected(bd_addr)) {
1017 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
1018 bd_addr->ToString().c_str());
1019 return BT_STATUS_FAIL;
1020 }
1021 send_at_result(
1022 (response_code == BTHF_AT_RESPONSE_OK) ? BTA_AG_OK_DONE : BTA_AG_OK_ERROR,
1023 static_cast<uint16_t>(error_code), idx);
1024 return BT_STATUS_SUCCESS;
1025 }
1026
ClccResponse(int index,bthf_call_direction_t dir,bthf_call_state_t state,bthf_call_mode_t mode,bthf_call_mpty_type_t mpty,const char * number,bthf_call_addrtype_t type,RawAddress * bd_addr)1027 bt_status_t HeadsetInterface::ClccResponse(
1028 int index, bthf_call_direction_t dir, bthf_call_state_t state,
1029 bthf_call_mode_t mode, bthf_call_mpty_type_t mpty, const char* number,
1030 bthf_call_addrtype_t type, RawAddress* bd_addr) {
1031 CHECK_BTHF_INIT();
1032 int idx = btif_hf_idx_by_bdaddr(bd_addr);
1033 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
1034 BTIF_TRACE_ERROR("%s: Invalid index %d", __func__, idx);
1035 return BT_STATUS_FAIL;
1036 }
1037 if (!is_connected(bd_addr)) {
1038 BTIF_TRACE_ERROR("%s: %s is not connected", __func__,
1039 bd_addr->ToString().c_str());
1040 return BT_STATUS_FAIL;
1041 }
1042 tBTA_AG_RES_DATA ag_res = {};
1043 /* Format the response */
1044 if (index == 0) {
1045 ag_res.ok_flag = BTA_AG_OK_DONE;
1046 } else {
1047 BTIF_TRACE_EVENT(
1048 "clcc_response: [%d] dir %d state %d mode %d number = %s type = %d",
1049 index, dir, state, mode, number, type);
1050 int res_strlen = snprintf(ag_res.str, sizeof(ag_res.str), "%d,%d,%d,%d,%d",
1051 index, dir, state, mode, mpty);
1052 if (number) {
1053 size_t rem_bytes = sizeof(ag_res.str) - res_strlen;
1054 char dialnum[sizeof(ag_res.str)];
1055 size_t newidx = 0;
1056 if (type == BTHF_CALL_ADDRTYPE_INTERNATIONAL && *number != '+') {
1057 dialnum[newidx++] = '+';
1058 }
1059 for (size_t i = 0; number[i] != 0; i++) {
1060 if (newidx >= (sizeof(dialnum) - res_strlen - 1)) {
1061 android_errorWriteLog(0x534e4554, "79266386");
1062 break;
1063 }
1064 if (utl_isdialchar(number[i])) {
1065 dialnum[newidx++] = number[i];
1066 }
1067 }
1068 dialnum[newidx] = 0;
1069 // Reserve 5 bytes for ["][,][3_digit_type]
1070 snprintf(&ag_res.str[res_strlen], rem_bytes - 5, ",\"%s", dialnum);
1071 std::stringstream remaining_string;
1072 remaining_string << "\"," << type;
1073 strncat(&ag_res.str[res_strlen], remaining_string.str().c_str(), 5);
1074 }
1075 }
1076 BTA_AgResult(btif_hf_cb[idx].handle, BTA_AG_CLCC_RES, ag_res);
1077 return BT_STATUS_SUCCESS;
1078 }
1079
PhoneStateChange(int num_active,int num_held,bthf_call_state_t call_setup_state,const char * number,bthf_call_addrtype_t type,const char * name,RawAddress * bd_addr)1080 bt_status_t HeadsetInterface::PhoneStateChange(
1081 int num_active, int num_held, bthf_call_state_t call_setup_state,
1082 const char* number, bthf_call_addrtype_t type, const char* name,
1083 RawAddress* bd_addr) {
1084 CHECK_BTHF_INIT();
1085 if (!bd_addr) {
1086 BTIF_TRACE_WARNING("%s: bd_addr is null", __func__);
1087 return BT_STATUS_FAIL;
1088 }
1089 int idx = btif_hf_idx_by_bdaddr(bd_addr);
1090 if (idx < 0 || idx > BTA_AG_MAX_NUM_CLIENTS) {
1091 BTIF_TRACE_WARNING("%s: invalid index %d for %s", __func__, idx,
1092 bd_addr->ToString().c_str());
1093 return BT_STATUS_FAIL;
1094 }
1095 const btif_hf_cb_t& control_block = btif_hf_cb[idx];
1096 if (!IsSlcConnected(bd_addr)) {
1097 LOG(WARNING) << ": SLC not connected for " << *bd_addr;
1098 return BT_STATUS_NOT_READY;
1099 }
1100 if (call_setup_state == BTHF_CALL_STATE_DISCONNECTED) {
1101 // HFP spec does not handle cases when a call is being disconnected.
1102 // Since DISCONNECTED state must lead to IDLE state, ignoring it here.s
1103 LOG(INFO) << __func__
1104 << ": Ignore call state change to DISCONNECTED, idx=" << idx
1105 << ", addr=" << *bd_addr << ", num_active=" << num_active
1106 << ", num_held=" << num_held;
1107 return BT_STATUS_SUCCESS;
1108 }
1109 LOG(INFO) << __func__ << ": idx=" << idx << ", addr=" << *bd_addr
1110 << ", active_bda=" << active_bda << ", num_active=" << num_active
1111 << ", prev_num_active" << control_block.num_active
1112 << ", num_held=" << num_held
1113 << ", prev_num_held=" << control_block.num_held
1114 << ", call_state=" << dump_hf_call_state(call_setup_state)
1115 << ", prev_call_state="
1116 << dump_hf_call_state(control_block.call_setup_state);
1117 tBTA_AG_RES res = 0xFF;
1118 bt_status_t status = BT_STATUS_SUCCESS;
1119 bool active_call_updated = false;
1120
1121 /* if all indicators are 0, send end call and return */
1122 if (num_active == 0 && num_held == 0 &&
1123 call_setup_state == BTHF_CALL_STATE_IDLE) {
1124 VLOG(1) << __func__ << ": call ended";
1125 BTA_AgResult(control_block.handle, BTA_AG_END_CALL_RES,
1126 tBTA_AG_RES_DATA::kEmpty);
1127 /* if held call was present, reset that as well */
1128 if (control_block.num_held) {
1129 send_indicator_update(control_block, BTA_AG_IND_CALLHELD, 0);
1130 }
1131 UpdateCallStates(&btif_hf_cb[idx], num_active, num_held, call_setup_state);
1132 return status;
1133 }
1134
1135 /* active state can change when:
1136 ** 1. an outgoing/incoming call was answered
1137 ** 2. an held was resumed
1138 ** 3. without callsetup notifications, call became active
1139 ** (3) can happen if call is active and a headset connects to us
1140 **
1141 ** In the case of (3), we will have to notify the stack of an active
1142 ** call, instead of sending an indicator update. This will also
1143 ** force the SCO to be setup. Handle this special case here prior to
1144 ** call setup handling
1145 */
1146 if (((num_active + num_held) > 0) && (control_block.num_active == 0) &&
1147 (control_block.num_held == 0) &&
1148 (control_block.call_setup_state == BTHF_CALL_STATE_IDLE)) {
1149 tBTA_AG_RES_DATA ag_res = {};
1150 BTIF_TRACE_DEBUG(
1151 "%s: Active/Held call notification received without call setup "
1152 "update",
1153 __func__);
1154
1155 ag_res.audio_handle = BTA_AG_HANDLE_SCO_NO_CHANGE;
1156 // Addition call setup with the Active call
1157 // CIND response should have been updated.
1158 // just open SCO connection.
1159 if (call_setup_state != BTHF_CALL_STATE_IDLE) {
1160 res = BTA_AG_MULTI_CALL_RES;
1161 } else {
1162 res = BTA_AG_OUT_CALL_CONN_RES;
1163 }
1164 BTA_AgResult(control_block.handle, res, ag_res);
1165 active_call_updated = true;
1166 }
1167
1168 /* Ringing call changed? */
1169 if (call_setup_state != control_block.call_setup_state) {
1170 tBTA_AG_RES_DATA ag_res = {};
1171 ag_res.audio_handle = BTA_AG_HANDLE_SCO_NO_CHANGE;
1172 BTIF_TRACE_DEBUG("%s: Call setup states changed. old: %s new: %s", __func__,
1173 dump_hf_call_state(control_block.call_setup_state),
1174 dump_hf_call_state(call_setup_state));
1175 switch (call_setup_state) {
1176 case BTHF_CALL_STATE_IDLE: {
1177 switch (control_block.call_setup_state) {
1178 case BTHF_CALL_STATE_INCOMING:
1179 if (num_active > control_block.num_active) {
1180 res = BTA_AG_IN_CALL_CONN_RES;
1181 if (is_active_device(*bd_addr)) {
1182 ag_res.audio_handle = control_block.handle;
1183 }
1184 } else if (num_held > control_block.num_held)
1185 res = BTA_AG_IN_CALL_HELD_RES;
1186 else
1187 res = BTA_AG_CALL_CANCEL_RES;
1188 break;
1189 case BTHF_CALL_STATE_DIALING:
1190 case BTHF_CALL_STATE_ALERTING:
1191 if (num_active > control_block.num_active) {
1192 res = BTA_AG_OUT_CALL_CONN_RES;
1193 } else
1194 res = BTA_AG_CALL_CANCEL_RES;
1195 break;
1196 default:
1197 BTIF_TRACE_ERROR("%s: Incorrect call state prev=%d, now=%d",
1198 __func__, control_block.call_setup_state,
1199 call_setup_state);
1200 status = BT_STATUS_PARM_INVALID;
1201 break;
1202 }
1203 } break;
1204
1205 case BTHF_CALL_STATE_INCOMING:
1206 if (num_active || num_held) {
1207 res = BTA_AG_CALL_WAIT_RES;
1208 } else {
1209 res = BTA_AG_IN_CALL_RES;
1210 if (is_active_device(*bd_addr)) {
1211 ag_res.audio_handle = control_block.handle;
1212 }
1213 }
1214 if (number) {
1215 std::ostringstream call_number_stream;
1216 if ((type == BTHF_CALL_ADDRTYPE_INTERNATIONAL) && (*number != '+')) {
1217 call_number_stream << "\"+";
1218 } else {
1219 call_number_stream << "\"";
1220 }
1221
1222 std::string name_str;
1223 if (name) {
1224 name_str.append(name);
1225 }
1226 std::string number_str(number);
1227 // 13 = ["][+]["][,][3_digit_type][,,,]["]["][null_terminator]
1228 int overflow_size =
1229 13 + static_cast<int>(number_str.length() + name_str.length()) -
1230 static_cast<int>(sizeof(ag_res.str));
1231 if (overflow_size > 0) {
1232 android_errorWriteLog(0x534e4554, "79431031");
1233 int extra_overflow_size =
1234 overflow_size - static_cast<int>(name_str.length());
1235 if (extra_overflow_size > 0) {
1236 number_str.resize(number_str.length() - extra_overflow_size);
1237 name_str.clear();
1238 } else {
1239 name_str.resize(name_str.length() - overflow_size);
1240 }
1241 }
1242 call_number_stream << number_str << "\"";
1243
1244 // Store caller id string and append type info.
1245 // Make sure type info is valid, otherwise add 129 as default type
1246 ag_res.num = static_cast<uint16_t>(type);
1247 if ((ag_res.num < BTA_AG_CLIP_TYPE_MIN) ||
1248 (ag_res.num > BTA_AG_CLIP_TYPE_MAX)) {
1249 if (ag_res.num != BTA_AG_CLIP_TYPE_VOIP) {
1250 ag_res.num = BTA_AG_CLIP_TYPE_DEFAULT;
1251 }
1252 }
1253
1254 if (res == BTA_AG_CALL_WAIT_RES || name_str.empty()) {
1255 call_number_stream << "," << std::to_string(ag_res.num);
1256 } else {
1257 call_number_stream << "," << std::to_string(ag_res.num) << ",,,\""
1258 << name_str << "\"";
1259 }
1260 snprintf(ag_res.str, sizeof(ag_res.str), "%s",
1261 call_number_stream.str().c_str());
1262 }
1263 break;
1264 case BTHF_CALL_STATE_DIALING:
1265 if (!(num_active + num_held) && is_active_device(*bd_addr)) {
1266 ag_res.audio_handle = control_block.handle;
1267 }
1268 res = BTA_AG_OUT_CALL_ORIG_RES;
1269 break;
1270 case BTHF_CALL_STATE_ALERTING:
1271 /* if we went from idle->alert, force SCO setup here. dialing usually
1272 * triggers it */
1273 if ((control_block.call_setup_state == BTHF_CALL_STATE_IDLE) &&
1274 !(num_active + num_held) && is_active_device(*bd_addr)) {
1275 ag_res.audio_handle = control_block.handle;
1276 }
1277 res = BTA_AG_OUT_CALL_ALERT_RES;
1278 break;
1279 default:
1280 BTIF_TRACE_ERROR("%s: Incorrect call state prev=%d, now=%d", __func__,
1281 control_block.call_setup_state, call_setup_state);
1282 status = BT_STATUS_PARM_INVALID;
1283 break;
1284 }
1285 BTIF_TRACE_DEBUG("%s: Call setup state changed. res=%d, audio_handle=%d",
1286 __func__, res, ag_res.audio_handle);
1287
1288 if (res != 0xFF) {
1289 BTA_AgResult(control_block.handle, res, ag_res);
1290 }
1291
1292 /* if call setup is idle, we have already updated call indicator, jump out
1293 */
1294 if (call_setup_state == BTHF_CALL_STATE_IDLE) {
1295 /* check & update callheld */
1296 if ((num_held > 0) && (num_active > 0)) {
1297 send_indicator_update(control_block, BTA_AG_IND_CALLHELD, 1);
1298 }
1299 UpdateCallStates(&btif_hf_cb[idx], num_active, num_held,
1300 call_setup_state);
1301 return status;
1302 }
1303 }
1304
1305 /**
1306 * Handle call indicator change
1307 *
1308 * Per the errata 2043, call=1 implies at least one call is in progress
1309 * (active or held)
1310 * See: https://www.bluetooth.org/errata/errata_view.cfm?errata_id=2043
1311 *
1312 **/
1313 if (!active_call_updated &&
1314 ((num_active + num_held) !=
1315 (control_block.num_active + control_block.num_held))) {
1316 VLOG(1) << __func__ << ": in progress call states changed, active=["
1317 << control_block.num_active << "->" << num_active << "], held=["
1318 << control_block.num_held << "->" << num_held;
1319 send_indicator_update(control_block, BTA_AG_IND_CALL,
1320 ((num_active + num_held) > 0) ? BTA_AG_CALL_ACTIVE
1321 : BTA_AG_CALL_INACTIVE);
1322 }
1323
1324 /* Held Changed? */
1325 if (num_held != control_block.num_held ||
1326 ((num_active == 0) && ((num_held + control_block.num_held) > 1))) {
1327 BTIF_TRACE_DEBUG("%s: Held call states changed. old: %d new: %d", __func__,
1328 control_block.num_held, num_held);
1329 send_indicator_update(control_block, BTA_AG_IND_CALLHELD,
1330 ((num_held == 0) ? 0 : ((num_active == 0) ? 2 : 1)));
1331 }
1332
1333 /* Calls Swapped? */
1334 if ((call_setup_state == control_block.call_setup_state) &&
1335 (num_active && num_held) && (num_active == control_block.num_active) &&
1336 (num_held == control_block.num_held)) {
1337 BTIF_TRACE_DEBUG("%s: Calls swapped", __func__);
1338 send_indicator_update(control_block, BTA_AG_IND_CALLHELD, 1);
1339 }
1340
1341 /* When call is hung up and still there is another call is in active,
1342 * some of the HF cannot acquire the call states by its own. If HF try
1343 * to terminate a call, it may not send the command AT+CHUP because the
1344 * call states are not updated properly. HF should get informed the call
1345 * status forcibly.
1346 */
1347 if ((control_block.num_active == num_active && num_active != 0) &&
1348 (control_block.num_held != num_held && num_held == 0)) {
1349 tBTA_AG_RES_DATA ag_res = {};
1350 ag_res.ind.id = BTA_AG_IND_CALL;
1351 ag_res.ind.value = num_active;
1352 BTA_AgResult(control_block.handle, BTA_AG_IND_RES_ON_DEMAND, ag_res);
1353 }
1354
1355 UpdateCallStates(&btif_hf_cb[idx], num_active, num_held, call_setup_state);
1356 return status;
1357 }
1358
Cleanup()1359 void HeadsetInterface::Cleanup() {
1360 BTIF_TRACE_EVENT("%s", __func__);
1361
1362 btif_queue_cleanup(UUID_SERVCLASS_AG_HANDSFREE);
1363
1364 tBTA_SERVICE_MASK mask = btif_get_enabled_services_mask();
1365 #if (defined(BTIF_HF_SERVICES) && (BTIF_HF_SERVICES & BTA_HFP_SERVICE_MASK))
1366 if ((mask & (1 << BTA_HFP_SERVICE_ID)) != 0) {
1367 btif_disable_service(BTA_HFP_SERVICE_ID);
1368 }
1369 #else
1370 if ((mask & (1 << BTA_HSP_SERVICE_ID)) != 0) {
1371 btif_disable_service(BTA_HSP_SERVICE_ID);
1372 }
1373 #endif
1374 do_in_jni_thread(FROM_HERE, base::Bind([]() { bt_hf_callbacks = nullptr; }));
1375 }
1376
SetScoAllowed(bool value)1377 bt_status_t HeadsetInterface::SetScoAllowed(bool value) {
1378 CHECK_BTHF_INIT();
1379 BTA_AgSetScoAllowed(value);
1380 return BT_STATUS_SUCCESS;
1381 }
1382
SendBsir(bool value,RawAddress * bd_addr)1383 bt_status_t HeadsetInterface::SendBsir(bool value, RawAddress* bd_addr) {
1384 CHECK_BTHF_INIT();
1385 int idx = btif_hf_idx_by_bdaddr(bd_addr);
1386 if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) {
1387 BTIF_TRACE_ERROR("%s: Invalid index %d for %s", __func__, idx,
1388 bd_addr->ToString().c_str());
1389 return BT_STATUS_FAIL;
1390 }
1391 if (!is_connected(bd_addr)) {
1392 BTIF_TRACE_ERROR("%s: %s not connected", __func__,
1393 bd_addr->ToString().c_str());
1394 return BT_STATUS_FAIL;
1395 }
1396 tBTA_AG_RES_DATA ag_result = {};
1397 ag_result.state = value;
1398 BTA_AgResult(btif_hf_cb[idx].handle, BTA_AG_INBAND_RING_RES, ag_result);
1399 return BT_STATUS_SUCCESS;
1400 }
1401
SetActiveDevice(RawAddress * active_device_addr)1402 bt_status_t HeadsetInterface::SetActiveDevice(RawAddress* active_device_addr) {
1403 CHECK_BTHF_INIT();
1404 active_bda = *active_device_addr;
1405 BTA_AgSetActiveDevice(*active_device_addr);
1406 return BT_STATUS_SUCCESS;
1407 }
1408
1409 /*******************************************************************************
1410 *
1411 * Function btif_hf_execute_service
1412 *
1413 * Description Initializes/Shuts down the service
1414 *
1415 * Returns BT_STATUS_SUCCESS on success, BT_STATUS_FAIL otherwise
1416 *
1417 ******************************************************************************/
ExecuteService(bool b_enable)1418 bt_status_t ExecuteService(bool b_enable) {
1419 const char* service_names_raw[] = BTIF_HF_SERVICE_NAMES;
1420 std::vector<std::string> service_names;
1421 for (const char* service_name_raw : service_names_raw) {
1422 if (service_name_raw) {
1423 service_names.emplace_back(service_name_raw);
1424 }
1425 }
1426 if (b_enable) {
1427 /* Enable and register with BTA-AG */
1428 BTA_AgEnable(bte_hf_evt);
1429 for (uint8_t app_id = 0; app_id < btif_max_hf_clients; app_id++) {
1430 BTA_AgRegister(BTIF_HF_SERVICES, BTIF_HF_SECURITY, btif_hf_features,
1431 service_names, app_id);
1432 }
1433 } else {
1434 /* De-register AG */
1435 for (int i = 0; i < btif_max_hf_clients; i++) {
1436 BTA_AgDeregister(btif_hf_cb[i].handle);
1437 }
1438 /* Disable AG */
1439 BTA_AgDisable();
1440 }
1441 return BT_STATUS_SUCCESS;
1442 }
1443
1444 /*******************************************************************************
1445 *
1446 * Function btif_hf_get_interface
1447 *
1448 * Description Get the hf callback interface
1449 *
1450 * Returns bthf_interface_t
1451 *
1452 ******************************************************************************/
GetInterface()1453 Interface* GetInterface() {
1454 VLOG(0) << __func__;
1455 return HeadsetInterface::GetInstance();
1456 }
1457
1458 } // namespace headset
1459 } // namespace bluetooth
1460