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