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