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