OSDN Git Service

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