xref: /btstack/src/classic/hfp.c (revision caeaa206eb51459f9342b4042b1af2ec395bf0ac)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "hfp.c"
39 
40 
41 #include "btstack_config.h"
42 
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <string.h>
46 #include <inttypes.h>
47 
48 #include "bluetooth_sdp.h"
49 #include "btstack_debug.h"
50 #include "btstack_event.h"
51 #include "btstack_memory.h"
52 #include "btstack_run_loop.h"
53 #include "classic/sdp_client_rfcomm.h"
54 #include "classic/sdp_server.h"
55 #include "classic/sdp_util.h"
56 #include "classic/sdp_client.h"
57 #include "hci.h"
58 #include "hci_cmd.h"
59 #include "hci_dump.h"
60 
61 #if defined(ENABLE_CC256X_ASSISTED_HFP) && !defined(ENABLE_SCO_OVER_PCM)
62 #error "Assisted HFP is only possible over PCM/I2S. Please add define: ENABLE_SCO_OVER_PCM"
63 #endif
64 
65 #if defined(ENABLE_BCM_PCM_WBS) && !defined(ENABLE_SCO_OVER_PCM)
66 #error "WBS for PCM is only possible over PCM/I2S. Please add define: ENABLE_SCO_OVER_PCM"
67 #endif
68 
69 #define HFP_HF_FEATURES_SIZE 10
70 #define HFP_AG_FEATURES_SIZE 12
71 
72 typedef struct {
73     hfp_role_t local_role;
74     bd_addr_t  remote_address;
75 } hfp_sdp_query_context_t;
76 
77 // globals
78 
79 static btstack_linked_list_t hfp_connections ;
80 
81 static btstack_packet_handler_t hfp_hf_callback;
82 static btstack_packet_handler_t hfp_ag_callback;
83 
84 static btstack_packet_handler_t hfp_hf_rfcomm_packet_handler;
85 static btstack_packet_handler_t hfp_ag_rfcomm_packet_handler;
86 
87 static uint16_t hfp_allowed_sco_packet_types;
88 static hfp_connection_t * hfp_sco_establishment_active;
89 
90 static hfp_sdp_query_context_t                 hfp_sdp_query_context;
91 static btstack_context_callback_registration_t hfp_sdp_query_request;
92 
93 
94 
95 
96 
97 // custom commands
98 static btstack_linked_list_t hfp_custom_commands_ag;
99 static btstack_linked_list_t hfp_custom_commands_hf;
100 
101 // prototypes
102 static hfp_link_settings_t hfp_next_link_setting_for_connection(hfp_link_settings_t current_setting, hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported);
103 static void parse_sequence(hfp_connection_t * context);
104 
105 
106 #define CODEC_MASK_CVSD   (1 << HFP_CODEC_CVSD)
107 #define CODEC_MASK_OTHER ((1 << HFP_CODEC_MSBC) | (1 << HFP_CODEC_LC3_SWB))
108 
109 static const struct {
110     const uint16_t max_latency;
111     const uint8_t  retransmission_effort;
112     const uint16_t packet_types;
113     const uint8_t  codec_mask;
114 } hfp_link_settings [] = {
115         {0x0004, 0xff, SCO_PACKET_TYPES_HV1,  CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_D0
116         {0x0005, 0xff, SCO_PACKET_TYPES_HV3,  CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_D1
117         {0x0007, 0x01, SCO_PACKET_TYPES_EV3,  CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_S1
118         {0x0007, 0x01, SCO_PACKET_TYPES_2EV3, CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_S2
119         {0x000a, 0x01, SCO_PACKET_TYPES_2EV3, CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_S3
120         {0x000c, 0x02, SCO_PACKET_TYPES_2EV3, CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_S4
121         {0x0008, 0x02, SCO_PACKET_TYPES_EV3,  CODEC_MASK_OTHER}, // HFP_LINK_SETTINGS_T1
122         {0x000d, 0x02, SCO_PACKET_TYPES_2EV3, CODEC_MASK_OTHER}  // HFP_LINK_SETTINGS_T2
123 };
124 
125 #ifdef ENABLE_HFP_HF_SAFE_SETTINGS
126 // HFP v1.9, table 6.10 'mandatory safe settings' for eSCO + similar entries for SCO
127 static const struct hfp_mandatory_safe_setting {
128     const uint8_t codec_mask;
129     const bool secure_connection_in_use;
130     hfp_link_settings_t link_setting;
131 } hfp_mandatory_safe_settings[] = {
132         { CODEC_MASK_CVSD,  false, HFP_LINK_SETTINGS_D1},
133         { CODEC_MASK_CVSD,  true,  HFP_LINK_SETTINGS_D1},
134         { CODEC_MASK_CVSD,  false, HFP_LINK_SETTINGS_S1},
135         { CODEC_MASK_CVSD,  true,  HFP_LINK_SETTINGS_S4},
136         { CODEC_MASK_OTHER, false, HFP_LINK_SETTINGS_T1},
137         { CODEC_MASK_OTHER, true,  HFP_LINK_SETTINGS_T2},
138 };
139 #endif
140 
141 static const char * hfp_hf_features[] = {
142         "EC and/or NR function",
143         "Three-way calling",
144         "CLI presentation capability",
145         "Voice recognition activation",
146         "Remote volume control",
147 
148         "Enhanced call status",
149         "Enhanced call control",
150 
151         "Codec negotiation",
152 
153         "HF Indicators",
154         "eSCO S4 (and T2) Settings Supported",
155         "Reserved for future definition"
156 };
157 
158 static const char * hfp_ag_features[] = {
159         "Three-way calling",
160         "EC and/or NR function",
161         "Voice recognition function",
162         "In-band ring tone capability",
163         "Attach a number to a voice tag",
164         "Ability to reject a call",
165         "Enhanced call status",
166         "Enhanced call control",
167         "Extended Error Result Codes",
168         "Codec negotiation",
169         "HF Indicators",
170         "eSCO S4 (and T2) Settings Supported",
171         "Reserved for future definition"
172 };
173 
174 static const char * hfp_enhanced_call_dir[] = {
175         "outgoing",
176         "incoming"
177 };
178 
179 static const char * hfp_enhanced_call_status[] = {
180         "active",
181         "held",
182         "outgoing dialing",
183         "outgoing alerting",
184         "incoming",
185         "incoming waiting",
186         "call held by response and hold"
187 };
188 
189 static const char * hfp_enhanced_call_mode[] = {
190         "voice",
191         "data",
192         "fax"
193 };
194 
195 static const char * hfp_enhanced_call_mpty[] = {
196         "not a conference call",
197         "conference call"
198 };
199 
200 const char * hfp_enhanced_call_dir2str(uint16_t index){
201     if (index <= HFP_ENHANCED_CALL_DIR_INCOMING) return hfp_enhanced_call_dir[index];
202     return "not defined";
203 }
204 
205 const char * hfp_enhanced_call_status2str(uint16_t index){
206     if (index <= HFP_ENHANCED_CALL_STATUS_CALL_HELD_BY_RESPONSE_AND_HOLD) return hfp_enhanced_call_status[index];
207     return "not defined";
208 }
209 
210 const char * hfp_enhanced_call_mode2str(uint16_t index){
211     if (index <= HFP_ENHANCED_CALL_MODE_FAX) return hfp_enhanced_call_mode[index];
212     return "not defined";
213 }
214 
215 const char * hfp_enhanced_call_mpty2str(uint16_t index){
216     if (index <= HFP_ENHANCED_CALL_MPTY_CONFERENCE_CALL) return hfp_enhanced_call_mpty[index];
217     return "not defined";
218 }
219 
220 static uint16_t hfp_parse_indicator_index(hfp_connection_t * hfp_connection){
221     uint16_t index = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
222 
223     if (index > HFP_MAX_NUM_INDICATORS){
224         log_info("ignoring invalid indicator index bigger then HFP_MAX_NUM_INDICATORS");
225         return HFP_MAX_NUM_INDICATORS - 1;
226     }
227 
228     // indicator index enumeration starts with 1, we substract 1 to store in array with starting index 0
229     if (index > 0){
230         index -= 1;
231     } else {
232         log_info("ignoring invalid indicator index 0");
233         return 0;
234     }
235     return index;
236 }
237 
238 static void hfp_next_indicators_index(hfp_connection_t * hfp_connection){
239     if (hfp_connection->parser_item_index < HFP_MAX_NUM_INDICATORS - 1){
240         hfp_connection->parser_item_index++;
241     } else {
242         log_info("Ignoring additional indicator");
243     }
244 }
245 
246 static void hfp_next_codec_index(hfp_connection_t * hfp_connection){
247     if (hfp_connection->parser_item_index < HFP_MAX_NUM_CODECS - 1){
248         hfp_connection->parser_item_index++;
249     } else {
250         log_info("Ignoring additional codec index");
251     }
252 }
253 
254 static void hfp_next_remote_call_services_index(hfp_connection_t * hfp_connection){
255     if (hfp_connection->remote_call_services_index < HFP_MAX_NUM_CALL_SERVICES - 1){
256         hfp_connection->remote_call_services_index++;
257     } else {
258         log_info("Ignoring additional remote_call_services");
259     }
260 }
261 
262 const char * hfp_hf_feature(int index){
263     if (index > HFP_HF_FEATURES_SIZE){
264         return hfp_hf_features[HFP_HF_FEATURES_SIZE];
265     }
266     return hfp_hf_features[index];
267 }
268 
269 const char * hfp_ag_feature(int index){
270     if (index > HFP_AG_FEATURES_SIZE){
271         return hfp_ag_features[HFP_AG_FEATURES_SIZE];
272     }
273     return hfp_ag_features[index];
274 }
275 
276 int send_str_over_rfcomm(uint16_t cid, const char * command){
277     if (!rfcomm_can_send_packet_now(cid)) return 1;
278     log_info("HFP_TX %s", command);
279     int err = rfcomm_send(cid, (uint8_t*) command, (uint16_t) strlen(command));
280     if (err){
281         log_error("rfcomm_send -> error 0x%02x \n", err);
282     }
283 #ifdef ENABLE_HFP_AT_MESSAGES
284     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(cid);
285     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_SENT, command);
286 #endif
287     return 1;
288 }
289 
290 int hfp_supports_codec(uint8_t codec, int codecs_nr, uint8_t * codecs){
291 
292     // mSBC requires support for eSCO connections
293     if ((codec == HFP_CODEC_MSBC) && !hci_extended_sco_link_supported()) return 0;
294 
295     int i;
296     for (i = 0; i < codecs_nr; i++){
297         if (codecs[i] != codec) continue;
298         return 1;
299     }
300     return 0;
301 }
302 
303 void hfp_hf_drop_mSBC_if_eSCO_not_supported(uint8_t * codecs, uint8_t * codecs_nr){
304     if (hci_extended_sco_link_supported()) return;
305     uint8_t i;
306     int filtered_codec_count = 0;
307     for (i=0; i < *codecs_nr; i++){
308         if (codecs[i] != HFP_CODEC_MSBC) {
309             codecs[filtered_codec_count++] = codecs[i];
310         }
311     }
312     *codecs_nr = filtered_codec_count;
313 }
314 
315 // UTILS
316 int get_bit(uint16_t bitmap, int position){
317     return (bitmap >> position) & 1;
318 }
319 
320 int store_bit(uint32_t bitmap, int position, uint8_t value){
321     if (value){
322         bitmap |= 1 << position;
323     } else {
324         bitmap &= ~ (1 << position);
325     }
326     return bitmap;
327 }
328 
329 int join(char * buffer, int buffer_size, uint8_t * values, int values_nr){
330     if (buffer_size < (values_nr * 3)) return 0;
331     int i;
332     int offset = 0;
333     for (i = 0; i < (values_nr-1); i++) {
334       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", values[i]); // puts string into buffer
335     }
336     if (i<values_nr){
337         offset += snprintf(buffer+offset, buffer_size-offset, "%d", values[i]);
338     }
339     return offset;
340 }
341 
342 int join_bitmap(char * buffer, int buffer_size, uint32_t values, int values_nr){
343     if (buffer_size < (values_nr * 3)) return 0;
344 
345     int i;
346     int offset = 0;
347     for (i = 0; i < (values_nr-1); i++) {
348       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", get_bit(values,i)); // puts string into buffer
349     }
350 
351     if (i<values_nr){
352         offset += snprintf(buffer+offset, buffer_size-offset, "%d", get_bit(values,i));
353     }
354     return offset;
355 }
356 static void hfp_emit_event_for_role(hfp_role_t local_role, uint8_t * packet, uint16_t size){
357     switch (local_role){
358         case HFP_ROLE_HF:
359             (*hfp_hf_callback)(HCI_EVENT_PACKET, 0, packet, size);
360             break;
361         case HFP_ROLE_AG:
362             (*hfp_ag_callback)(HCI_EVENT_PACKET, 0, packet, size);
363             break;
364         default:
365             btstack_unreachable();
366             break;
367     }
368 }
369 
370 static void hfp_emit_event_for_context(hfp_connection_t * hfp_connection, uint8_t * packet, uint16_t size){
371     if (!hfp_connection) return;
372     hfp_emit_event_for_role(hfp_connection->local_role, packet, size);
373 }
374 
375 void hfp_emit_simple_event(hfp_connection_t * hfp_connection, uint8_t event_subtype){
376     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
377     uint8_t event[5];
378     event[0] = HCI_EVENT_HFP_META;
379     event[1] = sizeof(event) - 2;
380     event[2] = event_subtype;
381     little_endian_store_16(event, 3, acl_handle);
382     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
383 }
384 
385 void hfp_emit_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, uint8_t value){
386     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
387     uint8_t event[6];
388     event[0] = HCI_EVENT_HFP_META;
389     event[1] = sizeof(event) - 2;
390     event[2] = event_subtype;
391     little_endian_store_16(event, 3, acl_handle);
392     event[5] = value; // status 0 == OK
393     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
394 }
395 
396 void hfp_emit_voice_recognition_enabled(hfp_connection_t * hfp_connection, uint8_t status){
397     btstack_assert(hfp_connection != NULL);
398 
399     uint8_t event[7];
400     event[0] = HCI_EVENT_HFP_META;
401     event[1] = sizeof(event) - 2;
402     event[2] = HFP_SUBEVENT_VOICE_RECOGNITION_ACTIVATED;
403 
404     little_endian_store_16(event, 3, hfp_connection->acl_handle);
405     event[5] = status; // 0:success
406     event[6] = hfp_connection->enhanced_voice_recognition_enabled ? 1 : 0;
407     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
408 }
409 
410 void hfp_emit_voice_recognition_disabled(hfp_connection_t * hfp_connection, uint8_t status){
411     btstack_assert(hfp_connection != NULL);
412 
413     uint8_t event[6];
414     event[0] = HCI_EVENT_HFP_META;
415     event[1] = sizeof(event) - 2;
416     event[2] = HFP_SUBEVENT_VOICE_RECOGNITION_DEACTIVATED;
417 
418     little_endian_store_16(event, 3, hfp_connection->acl_handle);
419     event[5] = status; // 0:success
420     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
421 }
422 
423 void hfp_emit_enhanced_voice_recognition_hf_ready_for_audio_event(hfp_connection_t * hfp_connection, uint8_t status){
424     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
425 
426     uint8_t event[6];
427     event[0] = HCI_EVENT_HFP_META;
428     event[1] = sizeof(event) - 2;
429     event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_HF_READY_FOR_AUDIO;
430     little_endian_store_16(event, 3, acl_handle);
431     event[5] = status;
432     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
433 }
434 
435 void hfp_emit_enhanced_voice_recognition_state_event(hfp_connection_t * hfp_connection, uint8_t status){
436     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
437 
438     uint8_t event[6];
439     event[0] = HCI_EVENT_HFP_META;
440     event[1] = sizeof(event) - 2;
441     switch (hfp_connection->ag_vra_state){
442         case HFP_VOICE_RECOGNITION_STATE_AG_READY_TO_ACCEPT_AUDIO_INPUT:
443             event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_READY_TO_ACCEPT_AUDIO_INPUT;
444             break;
445         case HFP_VOICE_RECOGNITION_STATE_AG_IS_STARTING_SOUND:
446             event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_IS_STARTING_SOUND;
447             break;
448         case HFP_VOICE_RECOGNITION_STATE_AG_IS_PROCESSING_AUDIO_INPUT:
449             event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_IS_PROCESSING_AUDIO_INPUT;
450             break;
451         default:
452             btstack_unreachable();
453             break;
454     }
455 
456     little_endian_store_16(event, 3, acl_handle);
457     event[5] = status;
458     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
459 }
460 
461 void hfp_emit_slc_connection_event(hfp_role_t local_role, uint8_t status, hci_con_handle_t con_handle, bd_addr_t addr){
462     uint8_t event[12];
463     int pos = 0;
464     event[pos++] = HCI_EVENT_HFP_META;
465     event[pos++] = sizeof(event) - 2;
466     event[pos++] = HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
467     little_endian_store_16(event, pos, con_handle);
468     pos += 2;
469     event[pos++] = status; // status 0 == OK
470     reverse_bd_addr(addr,&event[pos]);
471     pos += 6;
472     hfp_emit_event_for_role(local_role, event, sizeof(event));
473 }
474 
475 static void hfp_emit_audio_connection_released(hfp_connection_t * hfp_connection, hci_con_handle_t sco_handle){
476     btstack_assert(hfp_connection != NULL);
477     uint8_t event[7];
478     int pos = 0;
479     event[pos++] = HCI_EVENT_HFP_META;
480     event[pos++] = sizeof(event) - 2;
481     event[pos++] = HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED;
482     little_endian_store_16(event, pos, hfp_connection->acl_handle);
483     pos += 2;
484     little_endian_store_16(event, pos, sco_handle);
485     pos += 2;
486     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
487 }
488 
489 void hfp_emit_sco_connection_established(hfp_connection_t *hfp_connection, uint8_t status, uint8_t negotiated_codec,
490                                          uint16_t rx_packet_length, uint16_t tx_packet_length) {
491     btstack_assert(hfp_connection != NULL);
492     uint8_t event[21];
493     int pos = 0;
494     event[pos++] = HCI_EVENT_HFP_META;
495     event[pos++] = sizeof(event) - 2;
496     event[pos++] = HFP_SUBEVENT_AUDIO_CONNECTION_ESTABLISHED;
497     little_endian_store_16(event, pos, hfp_connection->acl_handle);
498     pos += 2;
499     event[pos++] = status; // status 0 == OK
500     little_endian_store_16(event, pos, hfp_connection->sco_handle);
501     pos += 2;
502     reverse_bd_addr(hfp_connection->remote_addr,&event[pos]);
503     pos += 6;
504     event[pos++] = negotiated_codec;
505     little_endian_store_16(event, pos, hfp_connection->packet_types);
506     pos += 2;
507     little_endian_store_16(event, pos, rx_packet_length);
508     pos += 2;
509     little_endian_store_16(event, pos, tx_packet_length);
510     pos += 2;
511     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
512 }
513 
514 void hfp_emit_string_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, const char * value){
515     btstack_assert(hfp_connection != NULL);
516 #ifdef ENABLE_HFP_AT_MESSAGES
517     uint8_t event[256];
518 #else
519     uint8_t event[40];
520 #endif
521     uint16_t string_len = btstack_min((uint16_t) strlen(value), sizeof(event) - 6);
522     event[0] = HCI_EVENT_HFP_META;
523     event[1] = 4 + string_len;
524     event[2] = event_subtype;
525     little_endian_store_16(event, 3, hfp_connection->acl_handle);
526     memcpy((char*)&event[5], value, string_len);
527     event[5 + string_len] = 0;
528     hfp_emit_event_for_context(hfp_connection, event, 6 + string_len);
529 }
530 
531 btstack_linked_list_t * hfp_get_connections(void){
532     return (btstack_linked_list_t *) &hfp_connections;
533 }
534 
535 hfp_connection_t * get_hfp_connection_context_for_rfcomm_cid(uint16_t cid){
536     btstack_linked_list_iterator_t it;
537     btstack_linked_list_iterator_init(&it, hfp_get_connections());
538     while (btstack_linked_list_iterator_has_next(&it)){
539         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
540         if (hfp_connection->rfcomm_cid == cid){
541             return hfp_connection;
542         }
543     }
544     return NULL;
545 }
546 
547 hfp_connection_t * get_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr, hfp_role_t hfp_role){
548     btstack_linked_list_iterator_t it;
549     btstack_linked_list_iterator_init(&it, hfp_get_connections());
550     while (btstack_linked_list_iterator_has_next(&it)){
551         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
552         if ((memcmp(hfp_connection->remote_addr, bd_addr, 6) == 0) && (hfp_connection->local_role == hfp_role)) {
553             return hfp_connection;
554         }
555     }
556     return NULL;
557 }
558 
559 hfp_connection_t * get_hfp_connection_context_for_sco_handle(uint16_t handle, hfp_role_t hfp_role){
560     btstack_linked_list_iterator_t it;
561     btstack_linked_list_iterator_init(&it, hfp_get_connections());
562     while (btstack_linked_list_iterator_has_next(&it)){
563         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
564         if ((hfp_connection->sco_handle == handle) && (hfp_connection->local_role == hfp_role)){
565             return hfp_connection;
566         }
567     }
568     return NULL;
569 }
570 
571 hfp_connection_t * get_hfp_connection_context_for_acl_handle(uint16_t handle, hfp_role_t hfp_role){
572     btstack_linked_list_iterator_t it;
573     btstack_linked_list_iterator_init(&it, hfp_get_connections());
574     while (btstack_linked_list_iterator_has_next(&it)){
575         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
576         if ((hfp_connection->acl_handle == handle) && (hfp_connection->local_role == hfp_role)){
577             return hfp_connection;
578         }
579     }
580     return NULL;
581 }
582 
583 
584 static void hfp_reset_voice_recognition(hfp_connection_t * hfp_connection){
585     btstack_assert(hfp_connection != NULL);
586     hfp_voice_recognition_activation_status_t current_vra_state = hfp_connection->vra_state;
587     hfp_connection->vra_state = HFP_VRA_VOICE_RECOGNITION_OFF;
588 
589     if (current_vra_state != HFP_VRA_VOICE_RECOGNITION_OFF){
590         hfp_emit_voice_recognition_disabled(hfp_connection, ERROR_CODE_SUCCESS);
591     } else if (hfp_connection->vra_state_requested != HFP_VRA_VOICE_RECOGNITION_OFF){
592         hfp_emit_voice_recognition_disabled(hfp_connection, ERROR_CODE_SUCCESS);
593     }
594 
595     hfp_connection->vra_state_requested = HFP_VRA_VOICE_RECOGNITION_OFF;
596     hfp_connection->activate_voice_recognition = false;
597     hfp_connection->deactivate_voice_recognition = false;
598     hfp_connection->enhanced_voice_recognition_enabled = false;
599     hfp_connection->ag_vra_status = 0;
600     hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY;
601 }
602 
603 void hfp_reset_context_flags(hfp_connection_t * hfp_connection){
604     if (!hfp_connection) return;
605     hfp_connection->ok_pending = 0;
606     hfp_connection->send_error = 0;
607 
608     hfp_connection->found_equal_sign = false;
609 
610     hfp_connection->change_status_update_for_individual_ag_indicators = 0;
611     hfp_connection->operator_name_changed = 0;
612 
613     hfp_connection->enable_extended_audio_gateway_error_report = 0;
614     hfp_connection->extended_audio_gateway_error = 0;
615 
616     // establish codecs hfp_connection
617     hfp_connection->suggested_codec = 0;
618     hfp_connection->negotiated_codec = 0;
619     hfp_connection->codec_confirmed = 0;
620 
621     hfp_connection->establish_audio_connection = 0;
622     hfp_connection->call_waiting_notification_enabled = 0;
623     hfp_connection->command = HFP_CMD_NONE;
624     hfp_connection->enable_status_update_for_ag_indicators = 0xFF;
625     hfp_connection->clip_have_alpha = false;
626     hfp_reset_voice_recognition(hfp_connection);
627 }
628 
629 static hfp_connection_t * create_hfp_connection_context(void){
630     hfp_connection_t * hfp_connection = btstack_memory_hfp_connection_get();
631     if (!hfp_connection) return NULL;
632 
633     hfp_connection->state = HFP_IDLE;
634     hfp_connection->call_state = HFP_CALL_IDLE;
635     hfp_connection->codecs_state = HFP_CODECS_IDLE;
636 
637     hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
638 
639     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
640     hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
641 
642     hfp_reset_context_flags(hfp_connection);
643 
644     btstack_linked_list_add(&hfp_connections, (btstack_linked_item_t*)hfp_connection);
645     return hfp_connection;
646 }
647 
648 void hfp_finalize_connection_context(hfp_connection_t * hfp_connection){
649     btstack_linked_list_remove(&hfp_connections, (btstack_linked_item_t*) hfp_connection);
650     btstack_memory_hfp_connection_free(hfp_connection);
651 }
652 
653 static hfp_connection_t * hfp_create_connection(bd_addr_t bd_addr, hfp_role_t local_role){
654     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
655     if (hfp_connection) return  hfp_connection;
656     hfp_connection = create_hfp_connection_context();
657     if (!hfp_connection) {
658         return NULL;
659     }
660     (void)memcpy(hfp_connection->remote_addr, bd_addr, 6);
661     hfp_connection->local_role = local_role;
662     log_info("Create HFP context %p: role %u, addr %s", hfp_connection, local_role, bd_addr_to_str(bd_addr));
663 
664 #ifdef ENABLE_NXP_PCM_WBS
665     hfp_connection->nxp_start_audio_handle = HCI_CON_HANDLE_INVALID;
666     hfp_connection->nxp_stop_audio_handle = HCI_CON_HANDLE_INVALID;
667 #endif
668 
669     return hfp_connection;
670 }
671 
672 /* @param network.
673  * 0 == no ability to reject a call.
674  * 1 == ability to reject a call.
675  */
676 
677 /* @param suported_features
678  * HF bit 0: EC and/or NR function (yes/no, 1 = yes, 0 = no)
679  * HF bit 1: Call waiting or three-way calling(yes/no, 1 = yes, 0 = no)
680  * HF bit 2: CLI presentation capability (yes/no, 1 = yes, 0 = no)
681  * HF bit 3: Voice recognition activation (yes/no, 1= yes, 0 = no)
682  * HF bit 4: Remote volume control (yes/no, 1 = yes, 0 = no)
683  * HF bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
684  */
685  /* Bit position:
686  * AG bit 0: Three-way calling (yes/no, 1 = yes, 0 = no)
687  * AG bit 1: EC and/or NR function (yes/no, 1 = yes, 0 = no)
688  * AG bit 2: Voice recognition function (yes/no, 1 = yes, 0 = no)
689  * AG bit 3: In-band ring tone capability (yes/no, 1 = yes, 0 = no)
690  * AG bit 4: Attach a phone number to a voice tag (yes/no, 1 = yes, 0 = no)
691  * AG bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
692  */
693 
694 void hfp_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint16_t service_uuid, int rfcomm_channel_nr, const char * name){
695     uint8_t* attribute;
696     de_create_sequence(service);
697 
698     // 0x0000 "Service Record Handle"
699     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
700     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
701 
702     // 0x0001 "Service Class ID List"
703     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
704     attribute = de_push_sequence(service);
705     {
706         //  "UUID for Service"
707         de_add_number(attribute, DE_UUID, DE_SIZE_16, service_uuid);
708         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_GENERIC_AUDIO);
709     }
710     de_pop_sequence(service, attribute);
711 
712     // 0x0004 "Protocol Descriptor List"
713     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
714     attribute = de_push_sequence(service);
715     {
716         uint8_t* l2cpProtocol = de_push_sequence(attribute);
717         {
718             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
719         }
720         de_pop_sequence(attribute, l2cpProtocol);
721 
722         uint8_t* rfcomm = de_push_sequence(attribute);
723         {
724             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_RFCOMM);  // rfcomm_service
725             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
726         }
727         de_pop_sequence(attribute, rfcomm);
728     }
729     de_pop_sequence(service, attribute);
730 
731 
732     // 0x0005 "Public Browse Group"
733     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
734     attribute = de_push_sequence(service);
735     {
736         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
737     }
738     de_pop_sequence(service, attribute);
739 
740     // 0x0009 "Bluetooth Profile Descriptor List"
741     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
742     attribute = de_push_sequence(service);
743     {
744         uint8_t *sppProfile = de_push_sequence(attribute);
745         {
746             de_add_number(sppProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HANDSFREE);
747             de_add_number(sppProfile,  DE_UINT, DE_SIZE_16, 0x0109); // Version 1.9
748         }
749         de_pop_sequence(attribute, sppProfile);
750     }
751     de_pop_sequence(service, attribute);
752 
753     // 0x0100 "Service Name"
754     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
755     de_add_data(service,  DE_STRING, (uint16_t) strlen(name), (uint8_t *) name);
756 }
757 
758 static void hfp_handle_slc_setup_error(hfp_connection_t * hfp_connection, uint8_t status){
759     // cache fields for event
760     hfp_role_t local_role = hfp_connection->local_role;
761     bd_addr_t remote_addr;
762     // cppcheck-suppress uninitvar ; remote_addr is reported as uninitialized although it's the destination of the memcpy
763     (void)memcpy(remote_addr, hfp_connection->remote_addr, 6);
764     // finalize connection struct
765     hfp_finalize_connection_context(hfp_connection);
766     // emit event
767     hfp_emit_slc_connection_event(local_role, status, HCI_CON_HANDLE_INVALID, remote_addr);
768 }
769 
770 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
771     UNUSED(packet_type);    // ok: handling own sdp events
772     UNUSED(channel);        // ok: no channel
773     UNUSED(size);           // ok: handling own sdp events
774 
775     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(hfp_sdp_query_context.remote_address, hfp_sdp_query_context.local_role);
776     if (hfp_connection == NULL) {
777         log_info("connection with %s and local role %d not found", hfp_sdp_query_context.remote_address, hfp_sdp_query_context.local_role);
778         return;
779     }
780 
781     switch (hci_event_packet_get_type(packet)){
782         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
783             hfp_connection->rfcomm_channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
784             break;
785         case SDP_EVENT_QUERY_COMPLETE:
786             if (hfp_connection->rfcomm_channel_nr > 0){
787                 hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
788                 btstack_packet_handler_t packet_handler;
789                 switch (hfp_connection->local_role){
790                     case HFP_ROLE_AG:
791                         packet_handler = hfp_ag_rfcomm_packet_handler;
792                         break;
793                     case HFP_ROLE_HF:
794                         packet_handler = hfp_hf_rfcomm_packet_handler;
795                         break;
796                     default:
797                         btstack_assert(false);
798                         return;
799                 }
800 
801                 rfcomm_create_channel(packet_handler, hfp_connection->remote_addr, hfp_connection->rfcomm_channel_nr, NULL);
802 
803             } else {
804                 uint8_t status = sdp_event_query_complete_get_status(packet);
805                 if (status == ERROR_CODE_SUCCESS){
806                     // report service not found
807                     status = SDP_SERVICE_NOT_FOUND;
808                 }
809                 hfp_handle_slc_setup_error(hfp_connection, status);
810                 log_info("rfcomm service not found, status 0x%02x", status);
811             }
812 
813             // register the SDP Query request to check if there is another connection waiting for the query
814             // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
815             (void) sdp_client_register_query_callback(&hfp_sdp_query_request);
816             break;
817         default:
818             break;
819     }
820 }
821 
822 // returns 0 if unexpected error or no other link options remained, otherwise 1
823 static int hfp_handle_failed_sco_connection(uint8_t status){
824 
825     if (hfp_sco_establishment_active->accept_sco != 0){
826         log_info("(e)SCO Connection failed but not started by us");
827         return 0;
828     }
829 
830     log_info("(e)SCO Connection failed 0x%02x", status);
831     switch (status){
832         case ERROR_CODE_SCO_AIR_MODE_REJECTED:
833         case ERROR_CODE_SCO_INTERVAL_REJECTED:
834         case ERROR_CODE_SCO_OFFSET_REJECTED:
835         case ERROR_CODE_UNSPECIFIED_ERROR:
836         case ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE:
837         case ERROR_CODE_UNSUPPORTED_REMOTE_FEATURE_UNSUPPORTED_LMP_FEATURE:
838             break;
839         default:
840             return 0;
841     }
842 
843     // note: eSCO_S4 supported flag not available, but it's only relevant for highest CVSD link setting (and the current failed)
844     hfp_link_settings_t next_setting = hfp_next_link_setting_for_connection(hfp_sco_establishment_active->link_setting, hfp_sco_establishment_active, false);
845 
846     // handle no valid setting found
847     if (next_setting == HFP_LINK_SETTINGS_NONE) {
848         if (hfp_sco_establishment_active->negotiated_codec == HFP_CODEC_MSBC){
849             log_info("T2/T1 failed, fallback to CVSD - D1");
850             hfp_sco_establishment_active->negotiated_codec = HFP_CODEC_CVSD;
851             hfp_sco_establishment_active->sco_for_msbc_failed = 1;
852             hfp_sco_establishment_active->ag_send_common_codec = true;
853             hfp_sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D1;
854         } else {
855             // no other options
856             return 0;
857         }
858     }
859 
860     log_info("e)SCO Connection: try new link_setting %d", next_setting);
861     hfp_sco_establishment_active->establish_audio_connection = 1;
862     hfp_sco_establishment_active->link_setting = next_setting;
863     hfp_sco_establishment_active->accept_sco = 0;
864     hfp_sco_establishment_active = NULL;
865     return 1;
866 }
867 
868 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
869     UNUSED(packet_type);
870     UNUSED(channel);    // ok: no channel
871     UNUSED(size);
872 
873     bd_addr_t event_addr;
874     hci_con_handle_t handle;
875     hfp_connection_t * hfp_connection = NULL;
876     uint8_t status;
877 
878     log_debug("HFP HCI event handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
879 
880     switch (hci_event_packet_get_type(packet)) {
881 
882         case HCI_EVENT_CONNECTION_REQUEST:
883             switch(hci_event_connection_request_get_link_type(packet)){
884                 case 0: //  SCO
885                 case 2: // eSCO
886                     hci_event_connection_request_get_bd_addr(packet, event_addr);
887                     hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
888                     if (!hfp_connection) break;
889                     if (hci_event_connection_request_get_link_type(packet) == 2){
890                         hfp_connection->accept_sco = 2;
891                     } else {
892                         hfp_connection->accept_sco = 1;
893                     }
894                     // configure SBC coded if needed
895                     hfp_prepare_for_sco(hfp_connection);
896                     log_info("accept sco %u\n", hfp_connection->accept_sco);
897                     break;
898                 default:
899                     break;
900             }
901             break;
902 
903         case HCI_EVENT_COMMAND_STATUS:
904             if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) {
905                 if (hfp_sco_establishment_active == NULL) break;
906                 status = hci_event_command_status_get_status(packet);
907                 if (status == ERROR_CODE_SUCCESS) break;
908 
909                 hfp_connection = hfp_sco_establishment_active;
910                 if (hfp_handle_failed_sco_connection(status)) break;
911 
912                 hfp_connection->accept_sco = 0;
913                 hfp_connection->establish_audio_connection = 0;
914                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
915                 hfp_sco_establishment_active = NULL;
916                 hfp_emit_sco_connection_established(hfp_connection, status,
917                                                     hfp_connection->negotiated_codec, 0, 0);
918             }
919             break;
920 
921         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
922             if (hfp_sco_establishment_active == NULL) break;
923 
924             hfp_connection = hfp_sco_establishment_active;
925 
926             status = hci_event_synchronous_connection_complete_get_status(packet);
927             if (status != ERROR_CODE_SUCCESS){
928                 if (hfp_handle_failed_sco_connection(status)) break;
929 
930                 hfp_connection->accept_sco = 0;
931                 hfp_connection->establish_audio_connection = 0;
932                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
933                 hfp_sco_establishment_active = NULL;
934                 hfp_emit_sco_connection_established(hfp_connection, status,
935                                                     hfp_connection->negotiated_codec, 0, 0);
936                 break;
937             }
938 
939             uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet);
940             uint8_t  link_type = hci_event_synchronous_connection_complete_get_link_type(packet);
941             uint8_t  transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet);  // measured in slots
942             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots
943             uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes
944             uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes
945 
946             switch (link_type){
947                 case 0x00:
948                     log_info("SCO Connection established.");
949                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
950                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
951                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
952                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
953                     break;
954                 case 0x02:
955                     log_info("eSCO Connection established. \n");
956                     break;
957                 default:
958                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
959                     break;
960             }
961 
962             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
963                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
964                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length,
965                  hci_event_synchronous_connection_complete_get_air_mode(packet));
966 
967             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
968                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
969                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
970                 break;
971             }
972             hfp_connection->sco_handle = sco_handle;
973             hfp_connection->accept_sco = 0;
974             hfp_connection->establish_audio_connection = 0;
975 
976             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
977 
978             switch (hfp_connection->vra_state){
979                 case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
980                     hfp_connection->ag_audio_connection_opened_before_vra = false;
981                     break;
982                 default:
983                     hfp_connection->ag_audio_connection_opened_before_vra = true;
984                     break;
985             }
986 
987             hfp_sco_establishment_active = NULL;
988 
989             hfp_emit_sco_connection_established(hfp_connection, status,
990                                                 hfp_connection->negotiated_codec, rx_packet_length, tx_packet_length);
991 
992 #ifdef ENABLE_NXP_PCM_WBS
993             hfp_connection->nxp_start_audio_handle = hfp_connection->sco_handle;
994 #endif
995             break;
996         }
997 
998         case HCI_EVENT_DISCONNECTION_COMPLETE:
999             handle = little_endian_read_16(packet,3);
1000             hfp_connection = get_hfp_connection_context_for_sco_handle(handle, local_role);
1001 
1002             if (!hfp_connection) break;
1003 
1004 #ifdef ENABLE_CC256X_ASSISTED_HFP
1005             hfp_connection->cc256x_send_wbs_disassociate = true;
1006 #endif
1007 #ifdef ENABLE_BCM_PCM_WBS
1008             hfp_connection->bcm_send_disable_wbs = true;
1009 #endif
1010 #ifdef ENABLE_NXP_PCM_WBS
1011             hfp_connection->nxp_stop_audio_handle = hfp_connection->sco_handle;
1012 #endif
1013 
1014             if (hfp_connection->sco_handle == handle){
1015                 hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
1016                 hfp_connection->release_audio_connection = 0;
1017                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1018                 hfp_emit_audio_connection_released(hfp_connection, handle);
1019 
1020                 hfp_connection->ag_audio_connection_opened_before_vra = false;
1021 
1022                 if (hfp_connection->acl_handle == HCI_CON_HANDLE_INVALID){
1023                     hfp_reset_voice_recognition(hfp_connection);
1024                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
1025                     hfp_finalize_connection_context(hfp_connection);
1026                     break;
1027                 } else if (hfp_connection->release_slc_connection == 1){
1028                     hfp_connection->release_slc_connection = 0;
1029                     hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1030                     rfcomm_disconnect(hfp_connection->acl_handle);
1031                 }
1032             }
1033 
1034             if (hfp_connection->state == HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN){
1035                 // RFCOMM already closed -> remote power off
1036 #if defined(ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
1037                 hfp_connection->state = HFP_W4_WBS_SHUTDOWN;
1038 #else
1039                 hfp_finalize_connection_context(hfp_connection);
1040 #endif
1041                 break;
1042             }
1043             break;
1044 
1045         default:
1046             break;
1047     }
1048 }
1049 
1050 
1051 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
1052     UNUSED(packet_type);
1053     UNUSED(channel);    // ok: no channel
1054     UNUSED(size);
1055 
1056     bd_addr_t event_addr;
1057     uint16_t rfcomm_cid;
1058     hfp_connection_t * hfp_connection = NULL;
1059     uint8_t status;
1060 
1061     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
1062 
1063     switch (hci_event_packet_get_type(packet)) {
1064 
1065         case RFCOMM_EVENT_INCOMING_CONNECTION:
1066             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
1067             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
1068             hfp_connection = hfp_create_connection(event_addr, local_role);
1069             if (!hfp_connection){
1070                 log_info("hfp: no memory to accept incoming connection - decline");
1071                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1072                 return;
1073             }
1074             if (hfp_connection->state != HFP_IDLE) {
1075                 log_error("hfp: incoming connection but not idle, reject");
1076                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1077                 return;
1078             }
1079 
1080             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
1081             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
1082             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
1083             break;
1084 
1085         case RFCOMM_EVENT_CHANNEL_OPENED:
1086             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
1087 
1088             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
1089             btstack_assert(hfp_connection != NULL);
1090 
1091             if (hfp_connection->state != HFP_W4_RFCOMM_CONNECTED){
1092                 break;
1093             }
1094 
1095             status = rfcomm_event_channel_opened_get_status(packet);
1096             if (status != ERROR_CODE_SUCCESS) {
1097                 hfp_handle_slc_setup_error(hfp_connection, status);
1098                 break;
1099             }
1100 
1101             hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
1102             hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
1103             hfp_connection->rfcomm_mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
1104             bd_addr_copy(hfp_connection->remote_addr, event_addr);
1105             hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
1106 
1107             rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1108             break;
1109 
1110         case RFCOMM_EVENT_CHANNEL_CLOSED:
1111             rfcomm_cid = little_endian_read_16(packet,2);
1112             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
1113             if (!hfp_connection) break;
1114             switch (hfp_connection->state){
1115                 case HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART:
1116                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1117                     hfp_connection->state = HFP_IDLE;
1118                     hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
1119                     break;
1120 
1121                 case HFP_AUDIO_CONNECTION_ESTABLISHED:
1122                     // service connection was released, this implicitly releases audio connection as well
1123                     hfp_connection->release_audio_connection = 0;
1124                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1125                     hfp_connection->state = HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN;
1126                     gap_disconnect(hfp_connection->sco_handle);
1127                     break;
1128 
1129                 default:
1130                     // regular case
1131                     hfp_reset_voice_recognition(hfp_connection);
1132                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
1133                     hfp_finalize_connection_context(hfp_connection);
1134                     break;
1135             }
1136             break;
1137 
1138         default:
1139             break;
1140     }
1141 }
1142 // translates command string into hfp_command_t CMD
1143 
1144 typedef struct {
1145     const char * command;
1146     hfp_command_t command_id;
1147 } hfp_command_entry_t;
1148 
1149 static hfp_command_entry_t hfp_ag_command_table[] = {
1150     { "AT+BAC=",   HFP_CMD_AVAILABLE_CODECS },
1151     { "AT+BCC",    HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP },
1152     { "AT+BCS=",   HFP_CMD_HF_CONFIRMED_CODEC },
1153     { "AT+BIA=",   HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE, }, // +BIA:<enabled>,,<enabled>,,,<enabled>
1154     { "AT+BIEV=",  HFP_CMD_HF_INDICATOR_STATUS },
1155     { "AT+BIND=",  HFP_CMD_LIST_GENERIC_STATUS_INDICATORS },
1156     { "AT+BIND=?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS },
1157     { "AT+BIND?",  HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE },
1158     { "AT+BINP=",  HFP_CMD_HF_REQUEST_PHONE_NUMBER },
1159     { "AT+BLDN",   HFP_CMD_REDIAL_LAST_NUMBER },
1160     { "AT+BRSF=",  HFP_CMD_SUPPORTED_FEATURES },
1161     { "AT+BTRH=",  HFP_CMD_RESPONSE_AND_HOLD_COMMAND },
1162     { "AT+BTRH?",  HFP_CMD_RESPONSE_AND_HOLD_QUERY },
1163     { "AT+BVRA=",  HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION },
1164     { "AT+CCWA=",  HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION},
1165     { "AT+CHLD=",  HFP_CMD_CALL_HOLD },
1166     { "AT+CHLD=?", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1167     { "AT+CHUP",   HFP_CMD_HANG_UP_CALL },
1168     { "AT+CIND=?", HFP_CMD_RETRIEVE_AG_INDICATORS },
1169     { "AT+CIND?",  HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS },
1170     { "AT+CLCC",   HFP_CMD_LIST_CURRENT_CALLS },
1171     { "AT+CLIP=",  HFP_CMD_ENABLE_CLIP},
1172     { "AT+CMEE=",  HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR},
1173     { "AT+CMER=",  HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE },
1174     { "AT+CNUM",   HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION },
1175     { "AT+COPS=",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT },
1176     { "AT+COPS?",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1177     { "AT+NREC=",  HFP_CMD_TURN_OFF_EC_AND_NR, },
1178     { "AT+VGM=",   HFP_CMD_SET_MICROPHONE_GAIN },
1179     { "AT+VGS=",   HFP_CMD_SET_SPEAKER_GAIN },
1180     { "AT+VTS=",   HFP_CMD_TRANSMIT_DTMF_CODES },
1181     { "ATA",       HFP_CMD_CALL_ANSWERED },
1182 };
1183 
1184 static hfp_command_entry_t hfp_hf_command_table[] = {
1185     { "+BCS:",  HFP_CMD_AG_SUGGESTED_CODEC },
1186     { "+BIND:", HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS },
1187     { "+BINP:", HFP_CMD_AG_SENT_PHONE_NUMBER },
1188     { "+BRSF:", HFP_CMD_SUPPORTED_FEATURES },
1189     { "+BSIR:", HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING },
1190     { "+BTRH:", HFP_CMD_RESPONSE_AND_HOLD_STATUS },
1191     { "+BVRA:", HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
1192     { "+CCWA:", HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE, },
1193     { "+CHLD:", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1194     { "+CIEV:", HFP_CMD_TRANSFER_AG_INDICATOR_STATUS},
1195     { "+CIND:", HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC },
1196     { "+CLCC:", HFP_CMD_LIST_CURRENT_CALLS },
1197     { "+CLIP:", HFP_CMD_AG_SENT_CLIP_INFORMATION },
1198     { "+CME ERROR:", HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR },
1199     { "+CNUM:", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION},
1200     { "+COPS:", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1201     { "+VGM:",  HFP_CMD_SET_MICROPHONE_GAIN },
1202     { "+VGM=",  HFP_CMD_SET_MICROPHONE_GAIN },
1203     { "+VGS:",  HFP_CMD_SET_SPEAKER_GAIN},
1204     { "+VGS=",  HFP_CMD_SET_SPEAKER_GAIN},
1205     { "ERROR",  HFP_CMD_ERROR},
1206     { "NOP",    HFP_CMD_NONE}, // dummy command used by unit tests
1207     { "OK",     HFP_CMD_OK },
1208     { "RING",   HFP_CMD_RING },
1209 };
1210 
1211 static const hfp_custom_at_command_t *
1212 hfp_custom_command_lookup(bool isHandsFree, const char *text) {
1213     btstack_linked_list_t * custom_commands = isHandsFree ? &hfp_custom_commands_hf : &hfp_custom_commands_ag;
1214     btstack_linked_list_iterator_t it;
1215     btstack_linked_list_iterator_init(&it, custom_commands);
1216     while (btstack_linked_list_iterator_has_next(&it)) {
1217         hfp_custom_at_command_t *at_command = (hfp_custom_at_command_t *) btstack_linked_list_iterator_next(&it);
1218         int match = strcmp(text, at_command->command);
1219         if (match == 0) {
1220             return at_command;
1221         }
1222     }
1223     return NULL;
1224 }
1225 
1226 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
1227 
1228     // check for custom commands, AG only
1229     const hfp_custom_at_command_t * custom_at_command = hfp_custom_command_lookup(isHandsFree, line_buffer);
1230     if (custom_at_command != NULL){
1231         return HFP_CMD_CUSTOM_MESSAGE;
1232     }
1233 
1234     // table lookup based on role
1235     uint16_t num_entries;
1236     hfp_command_entry_t * table;
1237     if (isHandsFree == 0){
1238         table = hfp_ag_command_table;
1239         num_entries = sizeof(hfp_ag_command_table) / sizeof(hfp_command_entry_t);
1240     } else {
1241         table = hfp_hf_command_table;
1242         num_entries = sizeof(hfp_hf_command_table) / sizeof(hfp_command_entry_t);
1243     }
1244     // binary search
1245     uint16_t left = 0;
1246     uint16_t right = num_entries - 1;
1247     while (left <= right){
1248         uint16_t middle = left + (right - left) / 2;
1249         hfp_command_entry_t *entry = &table[middle];
1250         int match = strcmp(line_buffer, entry->command);
1251         if (match < 0){
1252             // search term is lower than middle element
1253             if (right == 0) break;
1254             right = middle - 1;
1255         } else if (match == 0){
1256             return entry->command_id;
1257         } else {
1258             // search term is higher than middle element
1259             left = middle + 1;
1260         }
1261     }
1262 
1263     // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work.
1264     // note: phone number is currently expected in line_buffer[3..]
1265     // prefix match on 'ATD', AG only
1266     if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){
1267         return HFP_CMD_CALL_PHONE_NUMBER;
1268     }
1269 
1270     // Valid looking, but unknown commands/responses
1271     if ((isHandsFree == 0) && (strncmp(line_buffer, "AT+", 3) == 0)){
1272         return HFP_CMD_UNKNOWN;
1273     }
1274 
1275     if ((isHandsFree != 0) && (strncmp(line_buffer, "+", 1) == 0)){
1276         return HFP_CMD_UNKNOWN;
1277     }
1278 
1279     return HFP_CMD_NONE;
1280 }
1281 
1282 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
1283     if ((hfp_connection->line_size + 1) >= HFP_MAX_VR_TEXT_SIZE) return;
1284     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1285     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1286 }
1287 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
1288     return hfp_connection->line_size == 0;
1289 }
1290 
1291 static int hfp_parser_is_end_of_line(uint8_t byte){
1292     return (byte == '\n') || (byte == '\r');
1293 }
1294 
1295 void hfp_parser_reset_line_buffer(hfp_connection_t *hfp_connection) {
1296     hfp_connection->line_size = 0;
1297     // we don't set the first byte to '\0' to allow access to last argument e.g. in hfp_hf_handle_rfcommand
1298 }
1299 
1300 static void hfp_parser_store_if_token(hfp_connection_t * hfp_connection, uint8_t byte){
1301     switch (byte){
1302         case ',':
1303 		case '-':
1304         case ';':
1305         case '(':
1306         case ')':
1307         case '\n':
1308         case '\r':
1309             break;
1310         default:
1311             hfp_parser_store_byte(hfp_connection, byte);
1312             break;
1313     }
1314 }
1315 
1316 static bool hfp_parser_is_separator( uint8_t byte){
1317     switch (byte){
1318         case ',':
1319 		case '-':
1320         case ';':
1321         case '\n':
1322         case '\r':
1323             return true;
1324         default:
1325             return false;
1326     }
1327 }
1328 
1329 // returns true if received bytes was processed. Otherwise, functions will be called with same byte again
1330 // this is used to for a one byte lookahead, where an unexpected byte is pushed back by returning false
1331 static bool hfp_parse_byte(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1332 
1333 #ifdef HFP_DEBUG
1334     if (byte >= ' '){
1335         printf("Parse  '%c' - state %u, buffer %s\n", byte, hfp_connection->parser_state, hfp_connection->line_buffer);
1336     } else {
1337         printf("Parse 0x%02x - state %u, buffer %s\n", byte, hfp_connection->parser_state, hfp_connection->line_buffer);
1338     }
1339 #endif
1340 
1341     // handle doubles quotes
1342     if (byte == '"'){
1343         hfp_connection->parser_quoted = !hfp_connection->parser_quoted;
1344         return true;
1345     }
1346     if (hfp_connection->parser_quoted) {
1347         hfp_parser_store_byte(hfp_connection, byte);
1348         return true;
1349     }
1350 
1351     // ignore spaces outside command or double quotes (required e.g. for '+CME ERROR:..") command
1352     if ((byte == ' ') && (hfp_connection->parser_state != HFP_PARSER_CMD_HEADER)) return true;
1353 
1354     bool processed = true;
1355 
1356     switch (hfp_connection->parser_state) {
1357         case HFP_PARSER_CMD_HEADER:
1358             switch (byte) {
1359                 case '\n':
1360                 case '\r':
1361                 case ';':
1362                     // ignore separator
1363                     break;
1364                 case ':':
1365                 case '?':
1366                     // store separator
1367                     hfp_parser_store_byte(hfp_connection, byte);
1368                     break;
1369                 case '=':
1370                     // equal sign: remember and wait for next char to decided between '=?' and '=\?'
1371                     hfp_connection->found_equal_sign = true;
1372                     hfp_parser_store_byte(hfp_connection, byte);
1373                     return true;
1374                 default:
1375                     // store if not lookahead
1376                     if (!hfp_connection->found_equal_sign) {
1377                         hfp_parser_store_byte(hfp_connection, byte);
1378                         return true;
1379                     }
1380                     // mark as lookahead
1381                     processed = false;
1382                     break;
1383             }
1384 
1385             // ignore empty tokens
1386             if (hfp_parser_is_buffer_empty(hfp_connection)) return true;
1387 
1388             // parse
1389             hfp_connection->command = parse_command((char *)hfp_connection->line_buffer, isHandsFree);
1390 
1391             // pick +CIND version based on connection state: descriptions during SLC vs. states later
1392             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC){
1393                 switch(hfp_connection->state){
1394                     case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1395                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1396                         break;
1397                     case HFP_W4_RETRIEVE_INDICATORS:
1398                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1399                         break;
1400                     default:
1401                         hfp_connection->command = HFP_CMD_UNKNOWN;
1402                         break;
1403                 }
1404             }
1405 
1406             log_info("command string '%s', handsfree %u -> cmd id %u", (char *)hfp_connection->line_buffer, isHandsFree, hfp_connection->command);
1407 
1408             // store command id for custom command and just store rest of line
1409             if (hfp_connection->command == HFP_CMD_CUSTOM_MESSAGE){
1410                 const hfp_custom_at_command_t * at_command = hfp_custom_command_lookup(isHandsFree, (const char *) hfp_connection->line_buffer);
1411                 hfp_connection->custom_at_command_id = at_command->command_id;
1412                 hfp_connection->parser_state = HFP_PARSER_CUSTOM_COMMAND;
1413                 return processed;
1414             }
1415 
1416             // next state
1417             hfp_parser_reset_line_buffer(hfp_connection);
1418             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1419 
1420             return processed;
1421 
1422         case HFP_PARSER_CMD_SEQUENCE:
1423             // handle empty fields
1424             if ((byte == ',' ) && (hfp_connection->line_size == 0)){
1425                 hfp_connection->line_buffer[0] = 0;
1426                 hfp_connection->ignore_value = 1;
1427                 parse_sequence(hfp_connection);
1428                 return true;
1429             }
1430 
1431             hfp_parser_store_if_token(hfp_connection, byte);
1432             if (!hfp_parser_is_separator(byte)) return true;
1433 
1434             // ignore empty tokens
1435             switch (hfp_connection->command){
1436                 case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1437                     // don't ignore empty string
1438                     break;
1439                 default:
1440                     if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) {
1441                         return true;
1442                     }
1443                     break;
1444             }
1445 
1446             parse_sequence(hfp_connection);
1447 
1448             hfp_parser_reset_line_buffer(hfp_connection);
1449 
1450             switch (hfp_connection->command){
1451                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1452                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1453                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1454                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1455                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1456                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1457                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1458                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1459                 case HFP_CMD_HF_INDICATOR_STATUS:
1460                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1461                     break;
1462                 default:
1463                     break;
1464             }
1465             return true;
1466 
1467         case HFP_PARSER_SECOND_ITEM:
1468 
1469             hfp_parser_store_if_token(hfp_connection, byte);
1470             if (!hfp_parser_is_separator(byte)) return true;
1471 
1472             switch (hfp_connection->command){
1473                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1474                     log_info("format %s, ", hfp_connection->line_buffer);
1475                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1476                     break;
1477                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1478                     log_info("format %s \n", hfp_connection->line_buffer);
1479                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1480                     break;
1481                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1482                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1483                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1484                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1485                     break;
1486                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1487                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1488                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1489                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1490                     break;
1491                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1492                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1493                     log_info("%s, ", hfp_connection->line_buffer);
1494                     break;
1495                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1496                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1497                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1498                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1499                     break;
1500                 case HFP_CMD_HF_INDICATOR_STATUS:
1501                     hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1502                     break;
1503                 default:
1504                     break;
1505             }
1506 
1507             hfp_parser_reset_line_buffer(hfp_connection);
1508 
1509             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1510 
1511             return true;
1512 
1513         case HFP_PARSER_THIRD_ITEM:
1514 
1515             hfp_parser_store_if_token(hfp_connection, byte);
1516             if (!hfp_parser_is_separator(byte)) return true;
1517 
1518             switch (hfp_connection->command){
1519                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1520                     btstack_strcpy(hfp_connection->network_operator.name, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE,  (char *)hfp_connection->line_buffer);
1521                     break;
1522                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1523                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1524                     hfp_next_indicators_index(hfp_connection);
1525                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1526                     break;
1527                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1528                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1529                     // track if last argument exists
1530                     hfp_connection->clip_have_alpha = hfp_connection->line_size != 0;
1531                     break;
1532                 default:
1533                     break;
1534             }
1535 
1536             hfp_parser_reset_line_buffer(hfp_connection);
1537 
1538             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1539                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1540             }
1541             return true;
1542 
1543         case HFP_PARSER_CUSTOM_COMMAND:
1544             if (hfp_parser_is_end_of_line(byte) == false){
1545                 hfp_parser_store_byte(hfp_connection, byte);
1546             }
1547             return true;
1548 
1549         default:
1550             btstack_assert(false);
1551             return true;
1552     }
1553 }
1554 
1555 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1556     bool processed = false;
1557     while (!processed){
1558         processed = hfp_parse_byte(hfp_connection, byte, isHandsFree);
1559     }
1560     // reset parser state on end-of-line
1561     if (hfp_parser_is_end_of_line(byte)){
1562         hfp_connection->found_equal_sign = false;
1563         hfp_connection->parser_item_index = 0;
1564         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1565     }
1566 }
1567 
1568 static void parse_sequence(hfp_connection_t * hfp_connection){
1569     int value;
1570     switch (hfp_connection->command){
1571         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1572             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1573             int i;
1574             switch (hfp_connection->parser_item_index){
1575                 case 0:
1576                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1577                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1578                             hfp_connection->parser_indicator_index = i;
1579                             break;
1580                         }
1581                     }
1582                     break;
1583                 case 1:
1584                     if (hfp_connection->parser_indicator_index <0) break;
1585                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1586                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1587                      hfp_connection->parser_item_index, value);
1588                     break;
1589                 default:
1590                     break;
1591             }
1592             hfp_next_indicators_index(hfp_connection);
1593             break;
1594 
1595         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1596             switch(hfp_connection->parser_item_index){
1597                 case 0:
1598                     // <alpha>: This optional field is not supported, and shall be left blank.
1599                     break;
1600                 case 1:
1601                     // <number>: Quoted string containing the phone number in the format specified by <type>.
1602                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1603                     break;
1604                 case 2:
1605                     /*
1606                       <type> field specifies the format of the phone number provided, and can be one of the following values:
1607                       - values 128-143: The phone number format may be a national or international format, and may contain prefix and/or escape digits. No changes on the number presentation are required.
1608                      - values 144-159: The phone number format is an international number, including the country code prefix. If the plus sign ("+") is not included as part of the number and shall be added by the AG as needed.
1609                      - values 160-175: National number. No prefix nor escape digits included.
1610                      */
1611                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1612                     hfp_connection->bnip_type = value;
1613                     break;
1614                 case 3:
1615                     // <speed>: This optional field is not supported, and shall be left blank.
1616                     break;
1617                 case 4:
1618                     // <service>: Indicates which service this phone number relates to. Shall be either 4 (voice) or 5 (fax).
1619                 default:
1620                     break;
1621             }
1622             // index > 2 are ignored in switch above
1623             hfp_connection->parser_item_index++;
1624             break;
1625         case HFP_CMD_LIST_CURRENT_CALLS:
1626             switch(hfp_connection->parser_item_index){
1627                 case 0:
1628                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1629                     hfp_connection->clcc_idx = value;
1630                     break;
1631                 case 1:
1632                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1633                     hfp_connection->clcc_dir = value;
1634                     break;
1635                 case 2:
1636                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1637                     hfp_connection->clcc_status = value;
1638                     break;
1639                 case 3:
1640                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1641                     hfp_connection->clcc_mode = value;
1642                     break;
1643                 case 4:
1644                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1645                     hfp_connection->clcc_mpty = value;
1646                     break;
1647                 case 5:
1648                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1649                     break;
1650                 case 6:
1651                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1652                     hfp_connection->bnip_type = value;
1653                     break;
1654                 default:
1655                     break;
1656             }
1657             // index > 6 are ignored in switch above
1658             hfp_connection->parser_item_index++;
1659             break;
1660         case HFP_CMD_SET_MICROPHONE_GAIN:
1661             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1662             hfp_connection->microphone_gain = value;
1663             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1664             break;
1665         case HFP_CMD_SET_SPEAKER_GAIN:
1666             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1667             hfp_connection->speaker_gain = value;
1668             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1669             break;
1670         case HFP_CMD_TURN_OFF_EC_AND_NR:
1671             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1672             hfp_connection->ag_echo_and_noise_reduction = value;
1673             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1674             break;
1675         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1676             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1677             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1678             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1679             break;
1680         case HFP_CMD_HF_CONFIRMED_CODEC:
1681             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1682             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1683             break;
1684         case HFP_CMD_AG_SUGGESTED_CODEC:
1685             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1686             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1687             break;
1688         case HFP_CMD_SUPPORTED_FEATURES:
1689             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1690             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1691             break;
1692         case HFP_CMD_AVAILABLE_CODECS:
1693             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1694             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1695             hfp_next_codec_index(hfp_connection);
1696             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1697             break;
1698         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1699             btstack_strcpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, HFP_MAX_INDICATOR_DESC_SIZE, (char *)hfp_connection->line_buffer);
1700             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1701             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1702             break;
1703         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1704             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1705             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1706             hfp_next_indicators_index(hfp_connection);
1707             break;
1708         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1709             hfp_next_indicators_index(hfp_connection);
1710             if (hfp_connection->parser_item_index != 4) break;
1711             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1712             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1713             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1714             break;
1715         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1716             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1717             if (hfp_connection->line_size > 2 ) break;
1718             memcpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE-1);
1719             hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1720             hfp_next_remote_call_services_index(hfp_connection);
1721             break;
1722         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1723         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1724             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1725             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1726             hfp_next_indicators_index(hfp_connection);
1727             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1728             break;
1729         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1730             // HF parses inital AG gen. ind. state
1731             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1732             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1733             break;
1734         case HFP_CMD_HF_INDICATOR_STATUS:
1735             hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection);
1736             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1737             break;
1738         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1739             // AG parses new gen. ind. state
1740             if (hfp_connection->ignore_value){
1741                 hfp_connection->ignore_value = 0;
1742                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1743                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1744             }
1745             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1746                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1747                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1748             } else {
1749                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1750                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1751                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1752                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1753             }
1754             hfp_next_indicators_index(hfp_connection);
1755             break;
1756         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1757             // indicators are indexed starting with 1
1758             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1759             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1760             break;
1761         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1762             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1763             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1764             break;
1765         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1766             if (hfp_connection->line_buffer[0] == '3'){
1767                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1768                 break;
1769             }
1770             // TODO emit ERROR, wrong format
1771             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1772             break;
1773         case HFP_CMD_ERROR:
1774             break;
1775         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1776             hfp_connection->extended_audio_gateway_error = 1;
1777             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1778             break;
1779         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1780             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1781             hfp_connection->extended_audio_gateway_error = 0;
1782             break;
1783         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1784         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1785         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1786             btstack_strcpy((char *)hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1787             break;
1788         case HFP_CMD_CALL_HOLD:
1789             hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0';
1790             if (hfp_connection->line_buffer[1] != '\0'){
1791                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1792             }
1793             break;
1794         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1795             hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1796             break;
1797         case HFP_CMD_TRANSMIT_DTMF_CODES:
1798             hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0];
1799             break;
1800         case HFP_CMD_ENABLE_CLIP:
1801             hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0';
1802             break;
1803         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1804             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0';
1805             break;
1806         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1807             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1808             hfp_connection->ag_activate_voice_recognition_value = value;
1809             break;
1810         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1811             switch(hfp_connection->parser_item_index){
1812                 case 0:
1813                     hfp_connection->ag_vra_status = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1814                     break;
1815                 case 1:
1816                     hfp_connection->ag_vra_state = (hfp_voice_recognition_state_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1817                     break;
1818                 case 2:
1819                     hfp_connection->ag_msg.text_id = 0;
1820                     for (i = 0 ; i < 4; i++){
1821                         hfp_connection->ag_msg.text_id = (hfp_connection->ag_msg.text_id << 4) | nibble_for_char(hfp_connection->line_buffer[i]);
1822                     }
1823                     break;
1824                 case 3:
1825                     hfp_connection->ag_msg.text_type = (hfp_text_type_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1826                     break;
1827                 case 4:
1828                     hfp_connection->ag_msg.text_operation = (hfp_text_operation_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1829                     break;
1830                 case 5:
1831                     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1832                     hfp_connection->ag_vra_msg_length = hfp_connection->line_size + 1;
1833                     break;
1834                 default:
1835                     break;
1836             }
1837             hfp_connection->parser_item_index++;
1838             break;
1839         default:
1840             break;
1841     }
1842 }
1843 
1844 static void hfp_handle_start_sdp_client_query(void * context){
1845     UNUSED(context);
1846 
1847     btstack_linked_list_iterator_t it;
1848     btstack_linked_list_iterator_init(&it, &hfp_connections);
1849     while (btstack_linked_list_iterator_has_next(&it)){
1850         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1851 
1852         if (connection->state != HFP_W2_SEND_SDP_QUERY) continue;
1853 
1854         connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1855         hfp_sdp_query_context.local_role = connection->local_role;
1856         (void)memcpy(hfp_sdp_query_context.remote_address, connection->remote_addr, 6);
1857         sdp_client_query_rfcomm_channel_and_name_for_service_class_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid);
1858         return;
1859     }
1860 }
1861 
1862 uint8_t hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1863     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1864     if (connection != NULL){
1865         // allow to call hfp_establish_service_level_connection after SLC was triggered remotely
1866         // @note this also allows to call hfp_establish_service_level_connection again before SLC is complete
1867         if (connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1868             return ERROR_CODE_SUCCESS;
1869         } else {
1870             return ERROR_CODE_COMMAND_DISALLOWED;
1871         }
1872     }
1873 
1874     connection = hfp_create_connection(bd_addr, local_role);
1875     if (!connection){
1876         return BTSTACK_MEMORY_ALLOC_FAILED;
1877     }
1878 
1879     connection->state = HFP_W2_SEND_SDP_QUERY;
1880 
1881     bd_addr_copy(connection->remote_addr, bd_addr);
1882     connection->service_uuid = service_uuid;
1883 
1884     hfp_sdp_query_request.callback = &hfp_handle_start_sdp_client_query;
1885     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1886     (void) sdp_client_register_query_callback(&hfp_sdp_query_request);
1887     return ERROR_CODE_SUCCESS;
1888 }
1889 
1890 void hfp_trigger_release_service_level_connection(hfp_connection_t * hfp_connection){
1891     // called internally, NULL check already performed
1892     btstack_assert(hfp_connection != NULL);
1893 
1894     hfp_trigger_release_audio_connection(hfp_connection);
1895     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1896         hfp_connection->state = HFP_IDLE;
1897         return;
1898     }
1899 
1900     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1901         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1902         return;
1903     }
1904     hfp_connection->release_slc_connection = 1;
1905     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1906         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1907         return;
1908     }
1909 
1910     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1911         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1912         hfp_connection->release_audio_connection = 1;
1913         return;
1914     }
1915 }
1916 
1917 uint8_t hfp_trigger_release_audio_connection(hfp_connection_t * hfp_connection){
1918     // called internally, NULL check already performed
1919     btstack_assert(hfp_connection != NULL);
1920     if (hfp_connection->state <= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1921         return ERROR_CODE_COMMAND_DISALLOWED;
1922     }
1923     switch (hfp_connection->state) {
1924         case HFP_W2_CONNECT_SCO:
1925             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1926             break;
1927         case HFP_W4_SCO_CONNECTED:
1928         case HFP_AUDIO_CONNECTION_ESTABLISHED:
1929             hfp_connection->release_audio_connection = 1;
1930             break;
1931         default:
1932             return ERROR_CODE_COMMAND_DISALLOWED;
1933     }
1934     return ERROR_CODE_SUCCESS;
1935 }
1936 
1937 bool hfp_sco_setup_active(void){
1938     return hfp_sco_establishment_active != NULL;
1939 }
1940 
1941 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1942 
1943     hfp_sco_establishment_active = hfp_connection;
1944 
1945     // all packet types, fixed bandwidth
1946     int setting = hfp_connection->link_setting;
1947     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1948     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1949     if (hfp_connection->negotiated_codec != HFP_CODEC_CVSD){
1950 #ifdef ENABLE_BCM_PCM_WBS
1951         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1952 #else
1953         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1954 #endif
1955     }
1956     uint16_t packet_types = hfp_link_settings[setting].packet_types;
1957     hfp_connection->packet_types = packet_types;
1958 
1959     // get packet types - bits 6-9 are 'don't allow'
1960     uint16_t packet_types_flipped = packet_types ^ 0x03c0;
1961 #if defined(ENABLE_SCO_OVER_PCM) && defined(ENABLE_NXP_PCM_WBS)
1962     uint8_t  radio_coding_format = 3;
1963     uint32_t host_bandwidth      = 0;
1964     uint8_t  coded_data_size     = 0;
1965     switch (hfp_connection->negotiated_codec){
1966         case HFP_CODEC_CVSD:
1967             radio_coding_format = 0x02;
1968             host_bandwidth = 16000;
1969             coded_data_size = 0x10;
1970             break;
1971         case HFP_CODEC_MSBC:
1972             radio_coding_format = 0x05;
1973             host_bandwidth = 32000;
1974             coded_data_size = 0x08;
1975             break;
1976         default:
1977             log_error("Coding format %u not supported by Controller", hfp_connection->negotiated_codec);
1978             btstack_assert(false);
1979             break;
1980     }
1981     hci_send_cmd(&hci_enhanced_setup_synchronous_connection,
1982         // ACL Handle
1983         hfp_connection->acl_handle,
1984         // Transmit_Bandwidth
1985         8000,
1986         // Receive_Bandwidth
1987         8000,
1988         // Transmit_Coding_Format: radio_config_format, company, codec
1989         radio_coding_format, 0x00, 0x00,
1990         // Receive_Coding_Format: radio_config_format, company, codec
1991         radio_coding_format, 0x00, 0x00,
1992         // Transmit_Codec_Frame_Size
1993         0x3c,
1994         // Receive_Codec_Frame_Size
1995         0x3c,
1996         // Input_Bandwidth
1997         host_bandwidth,
1998         // Output_Bandwidth
1999         host_bandwidth,
2000         // Input_Coding_Format, 0x04 = Linear PCM, company, codec
2001         0x04, 0x00, 0x00,
2002         // Output_Coding_Format, 0x04 = Linear PCM, company, codec
2003         0x04, 0x00, 0x00,
2004         // Input_Coded_Data_Size
2005         coded_data_size,
2006         // Output_Coded_Data_Size
2007         coded_data_size,
2008         // Input_PCM_Data_Format, 0x02 = 2’s complement
2009         0x02,
2010         // Output_PCM_Data_Format, 0x02 = 2’s complement
2011         0x02,
2012         // Input_PCM_Sample_Payload_MSB_Position
2013         0x00,
2014         // Output_PCM_Sample_Payload_MSB_Position
2015         0x00,
2016         // Input_Data_Path - vendor specific: NXP - I2S/PCM
2017         0x01,
2018         // Output_Data_Path - vendor specific: NXP - I2S/PCM
2019         0x01,
2020         // Input_Transport_Unit_Size
2021         0x10,
2022         // Output_Transport_Unit_Size
2023         0x10,
2024         //
2025         hfp_link_settings[setting].max_latency,
2026         packet_types_flipped,
2027         hfp_link_settings[setting].retransmission_effort);
2028 #else
2029     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
2030         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types_flipped);
2031 #endif
2032 }
2033 
2034 #ifdef ENABLE_HFP_HF_SAFE_SETTINGS
2035 hfp_link_settings_t hfp_safe_settings_for_context(bool use_eSCO, uint8_t negotiated_codec, bool secure_connection_in_use){
2036     uint8_t i;
2037     hfp_link_settings_t link_setting = HFP_LINK_SETTINGS_NONE;
2038     for (i=0 ; i < (sizeof(hfp_mandatory_safe_settings) / sizeof(struct hfp_mandatory_safe_setting)) ; i++){
2039         uint16_t packet_types = hfp_link_settings[(uint8_t)(hfp_mandatory_safe_settings[i].link_setting)].packet_types;
2040         bool is_eSCO_setting = (packet_types & SCO_PACKET_TYPES_ESCO) != 0;
2041         if (is_eSCO_setting != use_eSCO) continue;
2042         if ((hfp_mandatory_safe_settings[i].codec_mask & (1 << negotiated_codec)) == 0) continue;
2043         if (hfp_mandatory_safe_settings[i].secure_connection_in_use != secure_connection_in_use) continue;
2044         link_setting = hfp_mandatory_safe_settings[i].link_setting;
2045         break;
2046     }
2047     return link_setting;
2048 }
2049 #endif
2050 
2051 void hfp_accept_synchronous_connection(hfp_connection_t * hfp_connection, bool use_eSCO){
2052 
2053     hfp_sco_establishment_active = hfp_connection;
2054 
2055     // lookup safe settings based on SCO type, SC use and Codec type
2056     uint16_t max_latency;
2057     uint16_t packet_types;
2058     uint16_t retransmission_effort;
2059     hfp_link_settings_t link_setting = HFP_LINK_SETTINGS_NONE;
2060 
2061 #ifdef ENABLE_HFP_HF_SAFE_SETTINGS
2062     // fallback for non-CVSD codec and SCO connection
2063     if ((hfp_connection->negotiated_codec != HFP_CODEC_CVSD) && (use_eSCO == false)){
2064         max_latency           = 0xffff;
2065         retransmission_effort = 0xff;
2066         packet_types          = SCO_PACKET_TYPES_HV3 | SCO_PACKET_TYPES_HV1;
2067     } else {
2068         // use safe settings from HFP v1.9, table 6.10
2069     bool secure_connection_in_use = gap_secure_connection(hfp_connection->acl_handle);
2070         link_setting = hfp_safe_settings_for_context(use_eSCO, hfp_connection->negotiated_codec, secure_connection_in_use);
2071         max_latency             = hfp_link_settings[(uint8_t) link_setting].max_latency;
2072         retransmission_effort   = hfp_link_settings[(uint8_t) link_setting].retransmission_effort;
2073         packet_types            = hfp_link_settings[(uint8_t) link_setting].packet_types;
2074     }
2075 #else
2076     max_latency           = 0xffff;
2077     retransmission_effort = 0xff;
2078     if (use_eSCO) {
2079         packet_types      = SCO_PACKET_TYPES_EV3 | SCO_PACKET_TYPES_2EV3;
2080     } else {
2081         packet_types      = SCO_PACKET_TYPES_HV3 | SCO_PACKET_TYPES_HV1;
2082     }
2083 #endif
2084 
2085     // transparent data for non-CVSD connections or if codec provided by Controller
2086     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
2087     if (hfp_connection->negotiated_codec != HFP_CODEC_CVSD){
2088 #ifdef ENABLE_BCM_PCM_WBS
2089         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
2090 #else
2091         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
2092 #endif
2093     }
2094 
2095     // filter packet types
2096     packet_types &= hfp_get_sco_packet_types();
2097 
2098     hfp_connection->packet_types = packet_types;
2099 
2100     // bits 6-9 are 'don't allow'
2101     uint16_t packet_types_flipped = packet_types ^ 0x3c0;
2102 
2103     log_info("Sending hci_accept_connection_request for link settings %u: packet types 0x%04x, sco_voice_setting 0x%02x",
2104              (uint8_t) link_setting, packet_types, sco_voice_setting);
2105 
2106 #if defined(ENABLE_SCO_OVER_PCM) && defined(ENABLE_NXP_PCM_WBS)
2107     uint8_t radio_coding_format = 3;
2108     uint32_t host_bandwidth = 0;
2109     uint8_t  coded_data_size = 0;
2110     switch (hfp_connection->negotiated_codec){
2111         case HFP_CODEC_CVSD:
2112             radio_coding_format = 0x02;
2113             host_bandwidth = 16000;
2114             coded_data_size = 0x10;
2115             break;
2116         case HFP_CODEC_MSBC:
2117             radio_coding_format = 0x05;
2118             host_bandwidth = 32000;
2119             coded_data_size = 0x08;
2120             break;
2121         default:
2122             log_error("Coding format %u not supported by Controller", hfp_connection->negotiated_codec);
2123             btstack_assert(false);
2124             break;
2125     }
2126     hci_send_cmd(&hci_enhanced_accept_synchronous_connection,
2127         // BD_ADDR
2128         hfp_connection->remote_addr,
2129         // Transmit_Bandwidth
2130         8000,
2131         // Receive_Bandwidth
2132         8000,
2133         // Transmit_Coding_Format: radio_config_format, company, codec
2134         radio_coding_format, 0x00, 0x00,
2135         // Receive_Coding_Format: radio_config_format, company, codec
2136         radio_coding_format, 0x00, 0x00,
2137         // Transmit_Codec_Frame_Size
2138         0x3c,
2139         // Receive_Codec_Frame_Size
2140         0x3c,
2141         // Input_Bandwidth
2142         host_bandwidth,
2143         // Output_Bandwidth
2144         host_bandwidth,
2145         // Input_Coding_Format, 0x04 = Linear PCM, company, codec
2146         0x04, 0x00, 0x00,
2147         // Output_Coding_Format, 0x04 = Linear PCM, company, codec
2148         0x04, 0x00, 0x00,
2149         // Input_Coded_Data_Size
2150         coded_data_size,
2151         // Output_Coded_Data_Size
2152         coded_data_size,
2153         // Input_PCM_Data_Format, 0x02 = 2’s complement
2154         0x02,
2155         // Output_PCM_Data_Format, 0x02 = 2’s complement
2156         0x02,
2157         // Input_PCM_Sample_Payload_MSB_Position
2158         0x00,
2159         // Output_PCM_Sample_Payload_MSB_Position
2160         0x00,
2161         // Input_Data_Path - vendor specific: NXP - I2S/PCM
2162         0x01,
2163         // Output_Data_Path - vendor specific: NXP - I2S/PCM
2164         0x01,
2165         // Input_Transport_Unit_Size
2166         0x10,
2167         // Output_Transport_Unit_Size
2168         0x10,
2169         //
2170         max_latency,
2171         packet_types_flipped,
2172         retransmission_effort);
2173 #else
2174     hci_send_cmd(&hci_accept_synchronous_connection, hfp_connection->remote_addr, 8000, 8000, max_latency,
2175                  sco_voice_setting, retransmission_effort, packet_types_flipped);
2176 #endif
2177 }
2178 
2179 #ifdef ENABLE_CC256X_ASSISTED_HFP
2180 void hfp_cc256x_write_codec_config(hfp_connection_t * hfp_connection){
2181     uint32_t sample_rate_hz;
2182     uint16_t clock_rate_khz;
2183     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
2184         clock_rate_khz = 512;
2185         sample_rate_hz = 16000;
2186     } else {
2187         clock_rate_khz = 256;
2188         sample_rate_hz = 8000;
2189     }
2190     uint8_t clock_direction = 0;        // master
2191     uint16_t frame_sync_duty_cycle = 0; // i2s with 50%
2192     uint8_t  frame_sync_edge = 1;       // rising edge
2193     uint8_t  frame_sync_polarity = 0;   // active high
2194     uint8_t  reserved = 0;
2195     uint16_t size = 16;
2196     uint16_t chan_1_offset = 1;
2197     uint16_t chan_2_offset = chan_1_offset + size;
2198     uint8_t  out_edge = 1;              // rising
2199     uint8_t  in_edge = 0;               // falling
2200     hci_send_cmd(&hci_ti_write_codec_config, clock_rate_khz, clock_direction, sample_rate_hz, frame_sync_duty_cycle,
2201                  frame_sync_edge, frame_sync_polarity, reserved,
2202                  size, chan_1_offset, out_edge, size, chan_1_offset, in_edge, reserved,
2203                  size, chan_2_offset, out_edge, size, chan_2_offset, in_edge, reserved);
2204 }
2205 #endif
2206 
2207 #ifdef ENABLE_BCM_PCM_WBS
2208 void hfp_bcm_write_i2spcm_interface_param(hfp_connection_t * hfp_connection){
2209     uint8_t sample_rate = (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? 1 : 0;
2210     // i2s enable, master, 8/16 kHz, 512 kHz
2211     hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, sample_rate, 2);
2212 }
2213 #endif
2214 
2215 void hfp_prepare_for_sco(hfp_connection_t * hfp_connection){
2216 #ifdef ENABLE_CC256X_ASSISTED_HFP
2217     hfp_connection->cc256x_send_write_codec_config = true;
2218     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
2219         hfp_connection->cc256x_send_wbs_associate = true;
2220     }
2221 #endif
2222 
2223 #ifdef ENABLE_BCM_PCM_WBS
2224 #ifndef HAVE_BCM_PCM_NBS_16KHZ
2225     hfp_connection->bcm_send_write_i2spcm_interface_param = true;
2226 #endif
2227     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
2228         hfp_connection->bcm_send_enable_wbs = true;
2229     }
2230 #endif
2231 
2232 #ifdef ENABLE_RTK_PCM_WBS
2233     hfp_connection->rtk_send_sco_config = true;
2234 #endif
2235 }
2236 
2237 void hfp_set_hf_callback(btstack_packet_handler_t callback){
2238     hfp_hf_callback = callback;
2239 }
2240 
2241 void hfp_set_ag_callback(btstack_packet_handler_t callback){
2242     hfp_ag_callback = callback;
2243 }
2244 
2245 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
2246     hfp_ag_rfcomm_packet_handler = handler;
2247 }
2248 
2249 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
2250     hfp_hf_rfcomm_packet_handler = handler;
2251 }
2252 
2253 void hfp_init(void){
2254     hfp_allowed_sco_packet_types = SCO_PACKET_TYPES_ALL;
2255 }
2256 
2257 void hfp_deinit(void){
2258     hfp_allowed_sco_packet_types = 0;
2259     hfp_connections = NULL;
2260     hfp_hf_callback = NULL;
2261     hfp_ag_callback = NULL;
2262     hfp_hf_rfcomm_packet_handler = NULL;
2263     hfp_ag_rfcomm_packet_handler = NULL;
2264     hfp_sco_establishment_active = NULL;
2265     hfp_custom_commands_ag = NULL;
2266     hfp_custom_commands_hf = NULL;
2267     (void) memset(&hfp_sdp_query_context, 0, sizeof(hfp_sdp_query_context_t));
2268     (void) memset(&hfp_sdp_query_request, 0, sizeof(btstack_context_callback_registration_t));
2269 }
2270 
2271 void hfp_set_sco_packet_types(uint16_t packet_types){
2272     hfp_allowed_sco_packet_types = packet_types;
2273 }
2274 
2275 uint16_t hfp_get_sco_packet_types(void){
2276     return hfp_allowed_sco_packet_types;
2277 }
2278 
2279 hfp_link_settings_t hfp_next_link_setting(hfp_link_settings_t current_setting, uint16_t local_sco_packet_types,
2280                                           uint16_t remote_sco_packet_types, bool eSCO_S4_supported,
2281                                           uint8_t negotiated_codec) {
2282     int8_t setting = (int8_t) current_setting;
2283     while (setting > 0){
2284         setting--;
2285         // skip S4 if not supported
2286         if ((setting == (int8_t) HFP_LINK_SETTINGS_S4) && !eSCO_S4_supported) continue;
2287         // skip wrong codec
2288         if ((hfp_link_settings[setting].codec_mask & (1 << negotiated_codec)) == 0) continue;
2289         // skip disabled or not supported packet types
2290         uint16_t required_packet_types = hfp_link_settings[setting].packet_types;
2291         uint16_t allowed_packet_types  = hfp_allowed_sco_packet_types & local_sco_packet_types & remote_sco_packet_types;
2292         if ((required_packet_types & allowed_packet_types) == 0) continue;
2293 
2294         // found matching setting
2295         return (hfp_link_settings_t) setting;
2296     }
2297     return HFP_LINK_SETTINGS_NONE;
2298 }
2299 
2300 static hfp_link_settings_t hfp_next_link_setting_for_connection(hfp_link_settings_t current_setting, hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
2301     uint8_t negotiated_codec   = hfp_connection->negotiated_codec;
2302     uint16_t local_sco_packet_types = hci_usable_sco_packet_types();
2303     uint16_t remote_sco_packet_types = hci_remote_sco_packet_types(hfp_connection->acl_handle);
2304     return hfp_next_link_setting(current_setting, local_sco_packet_types, remote_sco_packet_types, eSCO_S4_supported,
2305                                  negotiated_codec);
2306 }
2307 
2308 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
2309     // get highest possible link setting
2310     hfp_connection->link_setting = hfp_next_link_setting_for_connection(HFP_LINK_SETTINGS_NONE, hfp_connection, eSCO_S4_supported);
2311     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
2312 }
2313 
2314 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
2315 
2316 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
2317 #ifdef ENABLE_LOG_INFO
2318     // encode \n\r
2319     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
2320     int i = 0;
2321     int pos;
2322     for (pos=0 ; (pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)) ; pos++){
2323         switch (packet[pos]){
2324             case '\n':
2325                 printable[i++] = '\\';
2326                 printable[i++] = 'n';
2327                 break;
2328             case '\r':
2329                 printable[i++] = '\\';
2330                 printable[i++] = 'r';
2331                 break;
2332             default:
2333                 printable[i++] = packet[pos];
2334                 break;
2335         }
2336     }
2337     printable[i] = 0;
2338     log_info("%s: '%s'", tag, printable);
2339 #endif
2340 }
2341 
2342 void hfp_register_custom_ag_command(hfp_custom_at_command_t * custom_at_command){
2343     btstack_linked_list_add(&hfp_custom_commands_ag, (btstack_linked_item_t *) custom_at_command);
2344 }
2345 
2346 void hfp_register_custom_hf_command(hfp_custom_at_command_t * custom_at_command){
2347     btstack_linked_list_add(&hfp_custom_commands_hf, (btstack_linked_item_t *) custom_at_command);
2348 }
2349 
2350 // HFP H2 Synchronization - might get moved into a hfp_h2.c
2351 
2352 // find position of h2 sync header, returns -1 if not found, or h2 sync position
2353 static int16_t hfp_h2_sync_find(const uint8_t * frame_data, uint16_t frame_len){
2354     uint16_t i;
2355     for (i=0;i<(frame_len - 1);i++){
2356         // check: first byte == 1
2357         uint8_t h2_first_byte = frame_data[i];
2358         if (h2_first_byte == 0x01) {
2359             uint8_t h2_second_byte = frame_data[i + 1];
2360             // check lower nibble of second byte == 0x08
2361             if ((h2_second_byte & 0x0F) == 8) {
2362                 // check if bits 0+2 == bits 1+3
2363                 uint8_t hn = h2_second_byte >> 4;
2364                 if (((hn >> 1) & 0x05) == (hn & 0x05)) {
2365                     return (int16_t) i;
2366                 }
2367             }
2368         }
2369     }
2370     return -1;
2371 }
2372 
2373 static void hfp_h2_sync_reset(hfp_h2_sync_t * hfp_h2_sync){
2374     hfp_h2_sync->frame_len = 0;
2375 }
2376 
2377 void hfp_h2_sync_init(hfp_h2_sync_t * hfp_h2_sync,
2378                       bool (*callback)(bool bad_frame, const uint8_t * frame_data, uint16_t frame_len)){
2379     hfp_h2_sync->callback = callback;
2380     hfp_h2_sync->dropped_bytes = 0;
2381     hfp_h2_sync_reset(hfp_h2_sync);
2382 }
2383 
2384 static void hfp_h2_report_bad_frames(hfp_h2_sync_t *hfp_h2_sync){
2385     // report bad frames
2386     while (hfp_h2_sync->dropped_bytes >= HFP_H2_SYNC_FRAME_SIZE){
2387         hfp_h2_sync->dropped_bytes -= HFP_H2_SYNC_FRAME_SIZE;
2388         (void)(*hfp_h2_sync->callback)(true,NULL, HFP_H2_SYNC_FRAME_SIZE);
2389     }
2390 }
2391 
2392 static void hfp_h2_sync_drop_bytes(hfp_h2_sync_t * hfp_h2_sync, uint16_t bytes_to_drop){
2393     btstack_assert(bytes_to_drop <= hfp_h2_sync->frame_len);
2394     memmove(hfp_h2_sync->frame_data, &hfp_h2_sync->frame_data[bytes_to_drop], hfp_h2_sync->frame_len - bytes_to_drop);
2395     hfp_h2_sync->dropped_bytes += bytes_to_drop;
2396     hfp_h2_sync->frame_len     -= bytes_to_drop;
2397     hfp_h2_report_bad_frames(hfp_h2_sync);
2398 }
2399 
2400 void hfp_h2_sync_process(hfp_h2_sync_t *hfp_h2_sync, bool bad_frame, const uint8_t *frame_data, uint16_t frame_len) {
2401 
2402     if (bad_frame){
2403         // drop all data
2404         hfp_h2_sync->dropped_bytes += hfp_h2_sync->frame_len;
2405         hfp_h2_sync->frame_len = 0;
2406         // all new data is bad, too
2407         hfp_h2_sync->dropped_bytes += frame_len;
2408         // report frames
2409         hfp_h2_report_bad_frames(hfp_h2_sync);
2410         return;
2411     }
2412 
2413     while (frame_len > 0){
2414         // Fill hfp_h2_sync->frame_buffer
2415         uint16_t bytes_free_in_frame_buffer = HFP_H2_SYNC_FRAME_SIZE - hfp_h2_sync->frame_len;
2416         uint16_t bytes_to_append = btstack_min(frame_len, bytes_free_in_frame_buffer);
2417         memcpy(&hfp_h2_sync->frame_data[hfp_h2_sync->frame_len], frame_data, bytes_to_append);
2418         frame_data             += bytes_to_append;
2419         frame_len              -= bytes_to_append;
2420         hfp_h2_sync->frame_len += bytes_to_append;
2421         // check complete frame for h2 sync
2422         if (hfp_h2_sync->frame_len == HFP_H2_SYNC_FRAME_SIZE){
2423             bool valid_frame = true;
2424             int16_t h2_pos = hfp_h2_sync_find(hfp_h2_sync->frame_data, hfp_h2_sync->frame_len);
2425             if (h2_pos < 0){
2426                 // no h2 sync, no valid frame, keep last byte if it is 0x01
2427                 if (hfp_h2_sync->frame_data[HFP_H2_SYNC_FRAME_SIZE-1] == 0x01){
2428                     hfp_h2_sync_drop_bytes(hfp_h2_sync, HFP_H2_SYNC_FRAME_SIZE - 1);
2429                 } else {
2430                     hfp_h2_sync_drop_bytes(hfp_h2_sync, HFP_H2_SYNC_FRAME_SIZE);
2431                 }
2432                 valid_frame = false;
2433             }
2434             else if (h2_pos > 0){
2435                 // drop data before h2 sync
2436                 hfp_h2_sync_drop_bytes(hfp_h2_sync, h2_pos);
2437                 valid_frame = false;
2438             }
2439             if (valid_frame) {
2440                 // h2 sync at pos 0 and complete frame
2441                 bool codec_ok = (*hfp_h2_sync->callback)(false, hfp_h2_sync->frame_data, hfp_h2_sync->frame_len);
2442                 if (codec_ok){
2443                     hfp_h2_sync_reset(hfp_h2_sync);
2444                 } else {
2445                     // drop first two bytes
2446                     hfp_h2_sync_drop_bytes(hfp_h2_sync, 2);
2447                 }
2448             }
2449         }
2450     }
2451 }
2452