xref: /btstack/src/classic/hfp.c (revision 22029648dbaf7b329b48db7cbda905ed784c5ee2)
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_INVALID_LMP_PARAMETERS_INVALID_LL_PARAMETERS:
833         case ERROR_CODE_SCO_AIR_MODE_REJECTED:
834         case ERROR_CODE_SCO_INTERVAL_REJECTED:
835         case ERROR_CODE_SCO_OFFSET_REJECTED:
836         case ERROR_CODE_UNSPECIFIED_ERROR:
837         case ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE:
838         case ERROR_CODE_UNSUPPORTED_REMOTE_FEATURE_UNSUPPORTED_LMP_FEATURE:
839             break;
840         default:
841             return 0;
842     }
843 
844     // note: eSCO_S4 supported flag not available, but it's only relevant for highest CVSD link setting (and the current failed)
845     hfp_link_settings_t next_setting = hfp_next_link_setting_for_connection(hfp_sco_establishment_active->link_setting, hfp_sco_establishment_active, false);
846 
847     // handle no valid setting found
848     if (next_setting == HFP_LINK_SETTINGS_NONE) {
849         if (hfp_sco_establishment_active->negotiated_codec == HFP_CODEC_MSBC){
850             log_info("T2/T1 failed, fallback to CVSD - D1");
851             hfp_sco_establishment_active->negotiated_codec = HFP_CODEC_CVSD;
852             hfp_sco_establishment_active->sco_for_msbc_failed = 1;
853             hfp_sco_establishment_active->ag_send_common_codec = true;
854             hfp_sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D1;
855         } else {
856             // no other options
857             return 0;
858         }
859     }
860 
861     log_info("e)SCO Connection: try new link_setting %d", next_setting);
862     hfp_sco_establishment_active->establish_audio_connection = 1;
863     hfp_sco_establishment_active->link_setting = next_setting;
864     hfp_sco_establishment_active->accept_sco = 0;
865     hfp_sco_establishment_active = NULL;
866     return 1;
867 }
868 
869 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
870     UNUSED(packet_type);
871     UNUSED(channel);    // ok: no channel
872     UNUSED(size);
873 
874     bd_addr_t event_addr;
875     hci_con_handle_t handle;
876     hfp_connection_t * hfp_connection = NULL;
877     uint8_t status;
878 
879     log_debug("HFP HCI event handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
880 
881     switch (hci_event_packet_get_type(packet)) {
882 
883         case HCI_EVENT_CONNECTION_REQUEST:
884             switch(hci_event_connection_request_get_link_type(packet)){
885                 case 0: //  SCO
886                 case 2: // eSCO
887                     hci_event_connection_request_get_bd_addr(packet, event_addr);
888                     hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
889                     if (!hfp_connection) break;
890                     if (hci_event_connection_request_get_link_type(packet) == 2){
891                         hfp_connection->accept_sco = 2;
892                     } else {
893                         hfp_connection->accept_sco = 1;
894                     }
895                     // configure SBC coded if needed
896                     hfp_prepare_for_sco(hfp_connection);
897                     log_info("accept sco %u\n", hfp_connection->accept_sco);
898                     break;
899                 default:
900                     break;
901             }
902             break;
903 
904         case HCI_EVENT_COMMAND_STATUS:
905             if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) {
906                 if (hfp_sco_establishment_active == NULL) break;
907                 status = hci_event_command_status_get_status(packet);
908                 if (status == ERROR_CODE_SUCCESS) break;
909 
910                 hfp_connection = hfp_sco_establishment_active;
911                 if (hfp_handle_failed_sco_connection(status)) break;
912 
913                 hfp_connection->accept_sco = 0;
914                 hfp_connection->establish_audio_connection = 0;
915                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
916                 hfp_sco_establishment_active = NULL;
917                 hfp_emit_sco_connection_established(hfp_connection, status,
918                                                     hfp_connection->negotiated_codec, 0, 0);
919             }
920             break;
921 
922         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
923             if (hfp_sco_establishment_active == NULL) break;
924 
925             hfp_connection = hfp_sco_establishment_active;
926 
927             status = hci_event_synchronous_connection_complete_get_status(packet);
928             if (status != ERROR_CODE_SUCCESS){
929                 if (hfp_handle_failed_sco_connection(status)) break;
930 
931                 hfp_connection->accept_sco = 0;
932                 hfp_connection->establish_audio_connection = 0;
933                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
934                 hfp_sco_establishment_active = NULL;
935                 hfp_emit_sco_connection_established(hfp_connection, status,
936                                                     hfp_connection->negotiated_codec, 0, 0);
937                 break;
938             }
939 
940             uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet);
941             uint8_t  link_type = hci_event_synchronous_connection_complete_get_link_type(packet);
942             uint8_t  transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet);  // measured in slots
943             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots
944             uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes
945             uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes
946 
947             switch (link_type){
948                 case 0x00:
949                     log_info("SCO Connection established.");
950                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
951                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
952                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
953                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
954                     break;
955                 case 0x02:
956                     log_info("eSCO Connection established. \n");
957                     break;
958                 default:
959                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
960                     break;
961             }
962 
963             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
964                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
965                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length,
966                  hci_event_synchronous_connection_complete_get_air_mode(packet));
967 
968             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
969                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
970                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
971                 break;
972             }
973             hfp_connection->sco_handle = sco_handle;
974             hfp_connection->accept_sco = 0;
975             hfp_connection->establish_audio_connection = 0;
976 
977             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
978 
979             switch (hfp_connection->vra_state){
980                 case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
981                     hfp_connection->ag_audio_connection_opened_before_vra = false;
982                     break;
983                 default:
984                     hfp_connection->ag_audio_connection_opened_before_vra = true;
985                     break;
986             }
987 
988             hfp_sco_establishment_active = NULL;
989 
990             hfp_emit_sco_connection_established(hfp_connection, status,
991                                                 hfp_connection->negotiated_codec, rx_packet_length, tx_packet_length);
992 
993 #ifdef ENABLE_NXP_PCM_WBS
994             hfp_connection->nxp_start_audio_handle = hfp_connection->sco_handle;
995 #endif
996             break;
997         }
998 
999         case HCI_EVENT_DISCONNECTION_COMPLETE:
1000             handle = little_endian_read_16(packet,3);
1001             hfp_connection = get_hfp_connection_context_for_sco_handle(handle, local_role);
1002 
1003             if (!hfp_connection) break;
1004 
1005 #ifdef ENABLE_CC256X_ASSISTED_HFP
1006             hfp_connection->cc256x_send_wbs_disassociate = true;
1007 #endif
1008 #ifdef ENABLE_BCM_PCM_WBS
1009             hfp_connection->bcm_send_disable_wbs = true;
1010 #endif
1011 #ifdef ENABLE_NXP_PCM_WBS
1012             hfp_connection->nxp_stop_audio_handle = hfp_connection->sco_handle;
1013 #endif
1014 
1015             if (hfp_connection->sco_handle == handle){
1016                 hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
1017                 hfp_connection->release_audio_connection = 0;
1018                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1019                 hfp_emit_audio_connection_released(hfp_connection, handle);
1020 
1021                 hfp_connection->ag_audio_connection_opened_before_vra = false;
1022 
1023                 if (hfp_connection->acl_handle == HCI_CON_HANDLE_INVALID){
1024                     hfp_reset_voice_recognition(hfp_connection);
1025                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
1026                     hfp_finalize_connection_context(hfp_connection);
1027                     break;
1028                 } else if (hfp_connection->release_slc_connection == 1){
1029                     hfp_connection->release_slc_connection = 0;
1030                     hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1031                     rfcomm_disconnect(hfp_connection->acl_handle);
1032                 }
1033             }
1034 
1035             if (hfp_connection->state == HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN){
1036                 // RFCOMM already closed -> remote power off
1037 #if defined(ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
1038                 hfp_connection->state = HFP_W4_WBS_SHUTDOWN;
1039 #else
1040                 hfp_finalize_connection_context(hfp_connection);
1041 #endif
1042                 break;
1043             }
1044             break;
1045 
1046         default:
1047             break;
1048     }
1049 }
1050 
1051 
1052 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
1053     UNUSED(packet_type);
1054     UNUSED(channel);    // ok: no channel
1055     UNUSED(size);
1056 
1057     bd_addr_t event_addr;
1058     uint16_t rfcomm_cid;
1059     hfp_connection_t * hfp_connection = NULL;
1060     uint8_t status;
1061 
1062     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
1063 
1064     switch (hci_event_packet_get_type(packet)) {
1065 
1066         case RFCOMM_EVENT_INCOMING_CONNECTION:
1067             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
1068             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
1069             hfp_connection = hfp_create_connection(event_addr, local_role);
1070             if (!hfp_connection){
1071                 log_info("hfp: no memory to accept incoming connection - decline");
1072                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1073                 return;
1074             }
1075             if (hfp_connection->state != HFP_IDLE) {
1076                 log_error("hfp: incoming connection but not idle, reject");
1077                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1078                 return;
1079             }
1080 
1081             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
1082             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
1083             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
1084             break;
1085 
1086         case RFCOMM_EVENT_CHANNEL_OPENED:
1087             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
1088 
1089             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
1090             btstack_assert(hfp_connection != NULL);
1091 
1092             if (hfp_connection->state != HFP_W4_RFCOMM_CONNECTED){
1093                 break;
1094             }
1095 
1096             status = rfcomm_event_channel_opened_get_status(packet);
1097             if (status != ERROR_CODE_SUCCESS) {
1098                 hfp_handle_slc_setup_error(hfp_connection, status);
1099                 break;
1100             }
1101 
1102             hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
1103             hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
1104             hfp_connection->rfcomm_mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
1105             bd_addr_copy(hfp_connection->remote_addr, event_addr);
1106             hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
1107 
1108             rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1109             break;
1110 
1111         case RFCOMM_EVENT_CHANNEL_CLOSED:
1112             rfcomm_cid = little_endian_read_16(packet,2);
1113             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
1114             if (!hfp_connection) break;
1115             switch (hfp_connection->state){
1116                 case HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART:
1117                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1118                     hfp_connection->state = HFP_IDLE;
1119                     hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
1120                     break;
1121 
1122                 case HFP_AUDIO_CONNECTION_ESTABLISHED:
1123                     // service connection was released, this implicitly releases audio connection as well
1124                     hfp_connection->release_audio_connection = 0;
1125                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1126                     hfp_connection->state = HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN;
1127                     gap_disconnect(hfp_connection->sco_handle);
1128                     break;
1129 
1130                 default:
1131                     // regular case
1132                     hfp_reset_voice_recognition(hfp_connection);
1133                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
1134                     hfp_finalize_connection_context(hfp_connection);
1135                     break;
1136             }
1137             break;
1138 
1139         default:
1140             break;
1141     }
1142 }
1143 // translates command string into hfp_command_t CMD
1144 
1145 typedef struct {
1146     const char * command;
1147     hfp_command_t command_id;
1148 } hfp_command_entry_t;
1149 
1150 static hfp_command_entry_t hfp_ag_command_table[] = {
1151     { "AT+BAC=",   HFP_CMD_AVAILABLE_CODECS },
1152     { "AT+BCC",    HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP },
1153     { "AT+BCS=",   HFP_CMD_HF_CONFIRMED_CODEC },
1154     { "AT+BIA=",   HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE, }, // +BIA:<enabled>,,<enabled>,,,<enabled>
1155     { "AT+BIEV=",  HFP_CMD_HF_INDICATOR_STATUS },
1156     { "AT+BIND=",  HFP_CMD_LIST_GENERIC_STATUS_INDICATORS },
1157     { "AT+BIND=?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS },
1158     { "AT+BIND?",  HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE },
1159     { "AT+BINP=",  HFP_CMD_HF_REQUEST_PHONE_NUMBER },
1160     { "AT+BLDN",   HFP_CMD_REDIAL_LAST_NUMBER },
1161     { "AT+BRSF=",  HFP_CMD_SUPPORTED_FEATURES },
1162     { "AT+BTRH=",  HFP_CMD_RESPONSE_AND_HOLD_COMMAND },
1163     { "AT+BTRH?",  HFP_CMD_RESPONSE_AND_HOLD_QUERY },
1164     { "AT+BVRA=",  HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION },
1165     { "AT+CCWA=",  HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION},
1166     { "AT+CHLD=",  HFP_CMD_CALL_HOLD },
1167     { "AT+CHLD=?", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1168     { "AT+CHUP",   HFP_CMD_HANG_UP_CALL },
1169     { "AT+CIND=?", HFP_CMD_RETRIEVE_AG_INDICATORS },
1170     { "AT+CIND?",  HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS },
1171     { "AT+CLCC",   HFP_CMD_LIST_CURRENT_CALLS },
1172     { "AT+CLIP=",  HFP_CMD_ENABLE_CLIP},
1173     { "AT+CMEE=",  HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR},
1174     { "AT+CMER=",  HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE },
1175     { "AT+CNUM",   HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION },
1176     { "AT+COPS=",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT },
1177     { "AT+COPS?",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1178     { "AT+NREC=",  HFP_CMD_TURN_OFF_EC_AND_NR, },
1179     { "AT+VGM=",   HFP_CMD_SET_MICROPHONE_GAIN },
1180     { "AT+VGS=",   HFP_CMD_SET_SPEAKER_GAIN },
1181     { "AT+VTS=",   HFP_CMD_TRANSMIT_DTMF_CODES },
1182     { "ATA",       HFP_CMD_CALL_ANSWERED },
1183 };
1184 
1185 static hfp_command_entry_t hfp_hf_command_table[] = {
1186     { "+BCS:",  HFP_CMD_AG_SUGGESTED_CODEC },
1187     { "+BIND:", HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS },
1188     { "+BINP:", HFP_CMD_AG_SENT_PHONE_NUMBER },
1189     { "+BRSF:", HFP_CMD_SUPPORTED_FEATURES },
1190     { "+BSIR:", HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING },
1191     { "+BTRH:", HFP_CMD_RESPONSE_AND_HOLD_STATUS },
1192     { "+BVRA:", HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
1193     { "+CCWA:", HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE, },
1194     { "+CHLD:", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1195     { "+CIEV:", HFP_CMD_TRANSFER_AG_INDICATOR_STATUS},
1196     { "+CIND:", HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC },
1197     { "+CLCC:", HFP_CMD_LIST_CURRENT_CALLS },
1198     { "+CLIP:", HFP_CMD_AG_SENT_CLIP_INFORMATION },
1199     { "+CME ERROR:", HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR },
1200     { "+CNUM:", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION},
1201     { "+COPS:", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1202     { "+VGM:",  HFP_CMD_SET_MICROPHONE_GAIN },
1203     { "+VGM=",  HFP_CMD_SET_MICROPHONE_GAIN },
1204     { "+VGS:",  HFP_CMD_SET_SPEAKER_GAIN},
1205     { "+VGS=",  HFP_CMD_SET_SPEAKER_GAIN},
1206     { "ERROR",  HFP_CMD_ERROR},
1207     { "NOP",    HFP_CMD_NONE}, // dummy command used by unit tests
1208     { "OK",     HFP_CMD_OK },
1209     { "RING",   HFP_CMD_RING },
1210 };
1211 
1212 static const hfp_custom_at_command_t *
1213 hfp_custom_command_lookup(bool isHandsFree, const char *text) {
1214     btstack_linked_list_t * custom_commands = isHandsFree ? &hfp_custom_commands_hf : &hfp_custom_commands_ag;
1215     btstack_linked_list_iterator_t it;
1216     btstack_linked_list_iterator_init(&it, custom_commands);
1217     while (btstack_linked_list_iterator_has_next(&it)) {
1218         hfp_custom_at_command_t *at_command = (hfp_custom_at_command_t *) btstack_linked_list_iterator_next(&it);
1219         int match = strcmp(text, at_command->command);
1220         if (match == 0) {
1221             return at_command;
1222         }
1223     }
1224     return NULL;
1225 }
1226 
1227 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
1228 
1229     // check for custom commands, AG only
1230     const hfp_custom_at_command_t * custom_at_command = hfp_custom_command_lookup(isHandsFree, line_buffer);
1231     if (custom_at_command != NULL){
1232         return HFP_CMD_CUSTOM_MESSAGE;
1233     }
1234 
1235     // table lookup based on role
1236     uint16_t num_entries;
1237     hfp_command_entry_t * table;
1238     if (isHandsFree == 0){
1239         table = hfp_ag_command_table;
1240         num_entries = sizeof(hfp_ag_command_table) / sizeof(hfp_command_entry_t);
1241     } else {
1242         table = hfp_hf_command_table;
1243         num_entries = sizeof(hfp_hf_command_table) / sizeof(hfp_command_entry_t);
1244     }
1245     // binary search
1246     uint16_t left = 0;
1247     uint16_t right = num_entries - 1;
1248     while (left <= right){
1249         uint16_t middle = left + (right - left) / 2;
1250         hfp_command_entry_t *entry = &table[middle];
1251         int match = strcmp(line_buffer, entry->command);
1252         if (match < 0){
1253             // search term is lower than middle element
1254             if (right == 0) break;
1255             right = middle - 1;
1256         } else if (match == 0){
1257             return entry->command_id;
1258         } else {
1259             // search term is higher than middle element
1260             left = middle + 1;
1261         }
1262     }
1263 
1264     // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work.
1265     // note: phone number is currently expected in line_buffer[3..]
1266     // prefix match on 'ATD', AG only
1267     if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){
1268         return HFP_CMD_CALL_PHONE_NUMBER;
1269     }
1270 
1271     // Valid looking, but unknown commands/responses
1272     if ((isHandsFree == 0) && (strncmp(line_buffer, "AT+", 3) == 0)){
1273         return HFP_CMD_UNKNOWN;
1274     }
1275 
1276     if ((isHandsFree != 0) && (strncmp(line_buffer, "+", 1) == 0)){
1277         return HFP_CMD_UNKNOWN;
1278     }
1279 
1280     return HFP_CMD_NONE;
1281 }
1282 
1283 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
1284     if ((hfp_connection->line_size + 1) >= HFP_MAX_VR_TEXT_SIZE) return;
1285     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1286     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1287 }
1288 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
1289     return hfp_connection->line_size == 0;
1290 }
1291 
1292 static int hfp_parser_is_end_of_line(uint8_t byte){
1293     return (byte == '\n') || (byte == '\r');
1294 }
1295 
1296 void hfp_parser_reset_line_buffer(hfp_connection_t *hfp_connection) {
1297     hfp_connection->line_size = 0;
1298     // we don't set the first byte to '\0' to allow access to last argument e.g. in hfp_hf_handle_rfcommand
1299 }
1300 
1301 static void hfp_parser_store_if_token(hfp_connection_t * hfp_connection, uint8_t byte){
1302     switch (byte){
1303         case ',':
1304 		case '-':
1305         case ';':
1306         case '(':
1307         case ')':
1308         case '\n':
1309         case '\r':
1310             break;
1311         default:
1312             hfp_parser_store_byte(hfp_connection, byte);
1313             break;
1314     }
1315 }
1316 
1317 static bool hfp_parser_is_separator( uint8_t byte){
1318     switch (byte){
1319         case ',':
1320 		case '-':
1321         case ';':
1322         case '\n':
1323         case '\r':
1324             return true;
1325         default:
1326             return false;
1327     }
1328 }
1329 
1330 // returns true if received bytes was processed. Otherwise, functions will be called with same byte again
1331 // this is used to for a one byte lookahead, where an unexpected byte is pushed back by returning false
1332 static bool hfp_parse_byte(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1333 
1334 #ifdef HFP_DEBUG
1335     if (byte >= ' '){
1336         printf("Parse  '%c' - state %u, buffer %s\n", byte, hfp_connection->parser_state, hfp_connection->line_buffer);
1337     } else {
1338         printf("Parse 0x%02x - state %u, buffer %s\n", byte, hfp_connection->parser_state, hfp_connection->line_buffer);
1339     }
1340 #endif
1341 
1342     // handle doubles quotes
1343     if (byte == '"'){
1344         hfp_connection->parser_quoted = !hfp_connection->parser_quoted;
1345         return true;
1346     }
1347     if (hfp_connection->parser_quoted) {
1348         hfp_parser_store_byte(hfp_connection, byte);
1349         return true;
1350     }
1351 
1352     // ignore spaces outside command or double quotes (required e.g. for '+CME ERROR:..") command
1353     if ((byte == ' ') && (hfp_connection->parser_state != HFP_PARSER_CMD_HEADER)) return true;
1354 
1355     bool processed = true;
1356 
1357     switch (hfp_connection->parser_state) {
1358         case HFP_PARSER_CMD_HEADER:
1359             switch (byte) {
1360                 case '\n':
1361                 case '\r':
1362                 case ';':
1363                     // ignore separator
1364                     break;
1365                 case ':':
1366                 case '?':
1367                     // store separator
1368                     hfp_parser_store_byte(hfp_connection, byte);
1369                     break;
1370                 case '=':
1371                     // equal sign: remember and wait for next char to decided between '=?' and '=\?'
1372                     hfp_connection->found_equal_sign = true;
1373                     hfp_parser_store_byte(hfp_connection, byte);
1374                     return true;
1375                 default:
1376                     // store if not lookahead
1377                     if (!hfp_connection->found_equal_sign) {
1378                         hfp_parser_store_byte(hfp_connection, byte);
1379                         return true;
1380                     }
1381                     // mark as lookahead
1382                     processed = false;
1383                     break;
1384             }
1385 
1386             // ignore empty tokens
1387             if (hfp_parser_is_buffer_empty(hfp_connection)) return true;
1388 
1389             // parse
1390             hfp_connection->command = parse_command((char *)hfp_connection->line_buffer, isHandsFree);
1391 
1392             // pick +CIND version based on connection state: descriptions during SLC vs. states later
1393             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC){
1394                 switch(hfp_connection->state){
1395                     case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1396                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1397                         break;
1398                     case HFP_W4_RETRIEVE_INDICATORS:
1399                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1400                         break;
1401                     default:
1402                         hfp_connection->command = HFP_CMD_UNKNOWN;
1403                         break;
1404                 }
1405             }
1406 
1407             log_info("command string '%s', handsfree %u -> cmd id %u", (char *)hfp_connection->line_buffer, isHandsFree, hfp_connection->command);
1408 
1409             // store command id for custom command and just store rest of line
1410             if (hfp_connection->command == HFP_CMD_CUSTOM_MESSAGE){
1411                 const hfp_custom_at_command_t * at_command = hfp_custom_command_lookup(isHandsFree, (const char *) hfp_connection->line_buffer);
1412                 hfp_connection->custom_at_command_id = at_command->command_id;
1413                 hfp_connection->parser_state = HFP_PARSER_CUSTOM_COMMAND;
1414                 return processed;
1415             }
1416 
1417             // next state
1418             hfp_parser_reset_line_buffer(hfp_connection);
1419             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1420 
1421             return processed;
1422 
1423         case HFP_PARSER_CMD_SEQUENCE:
1424             // handle empty fields
1425             if ((byte == ',' ) && (hfp_connection->line_size == 0)){
1426                 hfp_connection->line_buffer[0] = 0;
1427                 hfp_connection->ignore_value = 1;
1428                 parse_sequence(hfp_connection);
1429                 return true;
1430             }
1431 
1432             hfp_parser_store_if_token(hfp_connection, byte);
1433             if (!hfp_parser_is_separator(byte)) return true;
1434 
1435             // ignore empty tokens
1436             switch (hfp_connection->command){
1437                 case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1438                     // don't ignore empty string
1439                     break;
1440                 default:
1441                     if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) {
1442                         return true;
1443                     }
1444                     break;
1445             }
1446 
1447             parse_sequence(hfp_connection);
1448 
1449             hfp_parser_reset_line_buffer(hfp_connection);
1450 
1451             switch (hfp_connection->command){
1452                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1453                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1454                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1455                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1456                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1457                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1458                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1459                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1460                 case HFP_CMD_HF_INDICATOR_STATUS:
1461                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1462                     break;
1463                 default:
1464                     break;
1465             }
1466             return true;
1467 
1468         case HFP_PARSER_SECOND_ITEM:
1469 
1470             hfp_parser_store_if_token(hfp_connection, byte);
1471             if (!hfp_parser_is_separator(byte)) return true;
1472 
1473             switch (hfp_connection->command){
1474                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1475                     log_info("format %s, ", hfp_connection->line_buffer);
1476                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1477                     break;
1478                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1479                     log_info("format %s \n", hfp_connection->line_buffer);
1480                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1481                     break;
1482                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1483                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1484                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1485                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1486                     break;
1487                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1488                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1489                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1490                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1491                     break;
1492                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1493                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1494                     log_info("%s, ", hfp_connection->line_buffer);
1495                     break;
1496                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1497                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1498                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1499                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1500                     break;
1501                 case HFP_CMD_HF_INDICATOR_STATUS:
1502                     hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1503                     break;
1504                 default:
1505                     break;
1506             }
1507 
1508             hfp_parser_reset_line_buffer(hfp_connection);
1509 
1510             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1511 
1512             return true;
1513 
1514         case HFP_PARSER_THIRD_ITEM:
1515 
1516             hfp_parser_store_if_token(hfp_connection, byte);
1517             if (!hfp_parser_is_separator(byte)) return true;
1518 
1519             switch (hfp_connection->command){
1520                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1521                     btstack_strcpy(hfp_connection->network_operator.name, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE,  (char *)hfp_connection->line_buffer);
1522                     break;
1523                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1524                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1525                     hfp_next_indicators_index(hfp_connection);
1526                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1527                     break;
1528                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1529                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1530                     // track if last argument exists
1531                     hfp_connection->clip_have_alpha = hfp_connection->line_size != 0;
1532                     break;
1533                 default:
1534                     break;
1535             }
1536 
1537             hfp_parser_reset_line_buffer(hfp_connection);
1538 
1539             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1540                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1541             }
1542             return true;
1543 
1544         case HFP_PARSER_CUSTOM_COMMAND:
1545             if (hfp_parser_is_end_of_line(byte) == false){
1546                 hfp_parser_store_byte(hfp_connection, byte);
1547             }
1548             return true;
1549 
1550         default:
1551             btstack_assert(false);
1552             return true;
1553     }
1554 }
1555 
1556 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1557     bool processed = false;
1558     while (!processed){
1559         processed = hfp_parse_byte(hfp_connection, byte, isHandsFree);
1560     }
1561     // reset parser state on end-of-line
1562     if (hfp_parser_is_end_of_line(byte)){
1563         hfp_connection->found_equal_sign = false;
1564         hfp_connection->parser_item_index = 0;
1565         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1566     }
1567 }
1568 
1569 static void parse_sequence(hfp_connection_t * hfp_connection){
1570     int value;
1571     switch (hfp_connection->command){
1572         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1573             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1574             int i;
1575             switch (hfp_connection->parser_item_index){
1576                 case 0:
1577                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1578                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1579                             hfp_connection->parser_indicator_index = i;
1580                             break;
1581                         }
1582                     }
1583                     break;
1584                 case 1:
1585                     if (hfp_connection->parser_indicator_index <0) break;
1586                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1587                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1588                      hfp_connection->parser_item_index, value);
1589                     break;
1590                 default:
1591                     break;
1592             }
1593             hfp_next_indicators_index(hfp_connection);
1594             break;
1595 
1596         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1597             switch(hfp_connection->parser_item_index){
1598                 case 0:
1599                     // <alpha>: This optional field is not supported, and shall be left blank.
1600                     break;
1601                 case 1:
1602                     // <number>: Quoted string containing the phone number in the format specified by <type>.
1603                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1604                     break;
1605                 case 2:
1606                     /*
1607                       <type> field specifies the format of the phone number provided, and can be one of the following values:
1608                       - 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.
1609                      - 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.
1610                      - values 160-175: National number. No prefix nor escape digits included.
1611                      */
1612                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1613                     hfp_connection->bnip_type = value;
1614                     break;
1615                 case 3:
1616                     // <speed>: This optional field is not supported, and shall be left blank.
1617                     break;
1618                 case 4:
1619                     // <service>: Indicates which service this phone number relates to. Shall be either 4 (voice) or 5 (fax).
1620                 default:
1621                     break;
1622             }
1623             // index > 2 are ignored in switch above
1624             hfp_connection->parser_item_index++;
1625             break;
1626         case HFP_CMD_LIST_CURRENT_CALLS:
1627             switch(hfp_connection->parser_item_index){
1628                 case 0:
1629                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1630                     hfp_connection->clcc_idx = value;
1631                     break;
1632                 case 1:
1633                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1634                     hfp_connection->clcc_dir = value;
1635                     break;
1636                 case 2:
1637                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1638                     hfp_connection->clcc_status = value;
1639                     break;
1640                 case 3:
1641                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1642                     hfp_connection->clcc_mode = value;
1643                     break;
1644                 case 4:
1645                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1646                     hfp_connection->clcc_mpty = value;
1647                     break;
1648                 case 5:
1649                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1650                     break;
1651                 case 6:
1652                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1653                     hfp_connection->bnip_type = value;
1654                     break;
1655                 default:
1656                     break;
1657             }
1658             // index > 6 are ignored in switch above
1659             hfp_connection->parser_item_index++;
1660             break;
1661         case HFP_CMD_SET_MICROPHONE_GAIN:
1662             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1663             hfp_connection->microphone_gain = value;
1664             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1665             break;
1666         case HFP_CMD_SET_SPEAKER_GAIN:
1667             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1668             hfp_connection->speaker_gain = value;
1669             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1670             break;
1671         case HFP_CMD_TURN_OFF_EC_AND_NR:
1672             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1673             hfp_connection->ag_echo_and_noise_reduction = value;
1674             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1675             break;
1676         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1677             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1678             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1679             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1680             break;
1681         case HFP_CMD_HF_CONFIRMED_CODEC:
1682             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1683             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1684             break;
1685         case HFP_CMD_AG_SUGGESTED_CODEC:
1686             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1687             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1688             break;
1689         case HFP_CMD_SUPPORTED_FEATURES:
1690             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1691             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1692             break;
1693         case HFP_CMD_AVAILABLE_CODECS:
1694             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1695             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1696             hfp_next_codec_index(hfp_connection);
1697             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1698             break;
1699         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1700             btstack_strcpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, HFP_MAX_INDICATOR_DESC_SIZE, (char *)hfp_connection->line_buffer);
1701             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1702             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1703             break;
1704         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1705             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1706             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1707             hfp_next_indicators_index(hfp_connection);
1708             break;
1709         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1710             hfp_next_indicators_index(hfp_connection);
1711             if (hfp_connection->parser_item_index != 4) break;
1712             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1713             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1714             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1715             break;
1716         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1717             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1718             if (hfp_connection->line_size > 2 ) break;
1719             memcpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE-1);
1720             hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1721             hfp_next_remote_call_services_index(hfp_connection);
1722             break;
1723         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1724         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1725             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1726             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1727             hfp_next_indicators_index(hfp_connection);
1728             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1729             break;
1730         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1731             // HF parses inital AG gen. ind. state
1732             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1733             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1734             break;
1735         case HFP_CMD_HF_INDICATOR_STATUS:
1736             hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection);
1737             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1738             break;
1739         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1740             // AG parses new gen. ind. state
1741             if (hfp_connection->ignore_value){
1742                 hfp_connection->ignore_value = 0;
1743                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1744                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1745             }
1746             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1747                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1748                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1749             } else {
1750                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1751                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1752                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1753                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1754             }
1755             hfp_next_indicators_index(hfp_connection);
1756             break;
1757         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1758             // indicators are indexed starting with 1
1759             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1760             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1761             break;
1762         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1763             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1764             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1765             break;
1766         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1767             if (hfp_connection->line_buffer[0] == '3'){
1768                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1769                 break;
1770             }
1771             // TODO emit ERROR, wrong format
1772             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1773             break;
1774         case HFP_CMD_ERROR:
1775             break;
1776         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1777             hfp_connection->extended_audio_gateway_error = 1;
1778             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1779             break;
1780         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1781             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1782             hfp_connection->extended_audio_gateway_error = 0;
1783             break;
1784         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1785         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1786         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1787             btstack_strcpy((char *)hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1788             break;
1789         case HFP_CMD_CALL_HOLD:
1790             hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0';
1791             if (hfp_connection->line_buffer[1] != '\0'){
1792                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1793             }
1794             break;
1795         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1796             hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1797             break;
1798         case HFP_CMD_TRANSMIT_DTMF_CODES:
1799             hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0];
1800             break;
1801         case HFP_CMD_ENABLE_CLIP:
1802             hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0';
1803             break;
1804         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1805             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0';
1806             break;
1807         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1808             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1809             hfp_connection->ag_activate_voice_recognition_value = value;
1810             break;
1811         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1812             switch(hfp_connection->parser_item_index){
1813                 case 0:
1814                     hfp_connection->ag_vra_status = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1815                     break;
1816                 case 1:
1817                     hfp_connection->ag_vra_state = (hfp_voice_recognition_state_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1818                     break;
1819                 case 2:
1820                     hfp_connection->ag_msg.text_id = 0;
1821                     for (i = 0 ; i < 4; i++){
1822                         hfp_connection->ag_msg.text_id = (hfp_connection->ag_msg.text_id << 4) | nibble_for_char(hfp_connection->line_buffer[i]);
1823                     }
1824                     break;
1825                 case 3:
1826                     hfp_connection->ag_msg.text_type = (hfp_text_type_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1827                     break;
1828                 case 4:
1829                     hfp_connection->ag_msg.text_operation = (hfp_text_operation_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1830                     break;
1831                 case 5:
1832                     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1833                     hfp_connection->ag_vra_msg_length = hfp_connection->line_size + 1;
1834                     break;
1835                 default:
1836                     break;
1837             }
1838             hfp_connection->parser_item_index++;
1839             break;
1840         default:
1841             break;
1842     }
1843 }
1844 
1845 static void hfp_handle_start_sdp_client_query(void * context){
1846     UNUSED(context);
1847 
1848     btstack_linked_list_iterator_t it;
1849     btstack_linked_list_iterator_init(&it, &hfp_connections);
1850     while (btstack_linked_list_iterator_has_next(&it)){
1851         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1852 
1853         if (connection->state != HFP_W2_SEND_SDP_QUERY) continue;
1854 
1855         connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1856         hfp_sdp_query_context.local_role = connection->local_role;
1857         (void)memcpy(hfp_sdp_query_context.remote_address, connection->remote_addr, 6);
1858         sdp_client_query_rfcomm_channel_and_name_for_service_class_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid);
1859         return;
1860     }
1861 }
1862 
1863 uint8_t hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1864     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1865     if (connection != NULL){
1866         // allow to call hfp_establish_service_level_connection after SLC was triggered remotely
1867         // @note this also allows to call hfp_establish_service_level_connection again before SLC is complete
1868         if (connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1869             return ERROR_CODE_SUCCESS;
1870         } else {
1871             return ERROR_CODE_COMMAND_DISALLOWED;
1872         }
1873     }
1874 
1875     connection = hfp_create_connection(bd_addr, local_role);
1876     if (!connection){
1877         return BTSTACK_MEMORY_ALLOC_FAILED;
1878     }
1879 
1880     connection->state = HFP_W2_SEND_SDP_QUERY;
1881 
1882     bd_addr_copy(connection->remote_addr, bd_addr);
1883     connection->service_uuid = service_uuid;
1884 
1885     hfp_sdp_query_request.callback = &hfp_handle_start_sdp_client_query;
1886     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1887     (void) sdp_client_register_query_callback(&hfp_sdp_query_request);
1888     return ERROR_CODE_SUCCESS;
1889 }
1890 
1891 void hfp_trigger_release_service_level_connection(hfp_connection_t * hfp_connection){
1892     // called internally, NULL check already performed
1893     btstack_assert(hfp_connection != NULL);
1894 
1895     hfp_trigger_release_audio_connection(hfp_connection);
1896     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1897         hfp_connection->state = HFP_IDLE;
1898         return;
1899     }
1900 
1901     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1902         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1903         return;
1904     }
1905     hfp_connection->release_slc_connection = 1;
1906     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1907         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1908         return;
1909     }
1910 
1911     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1912         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1913         hfp_connection->release_audio_connection = 1;
1914         return;
1915     }
1916 }
1917 
1918 uint8_t hfp_trigger_release_audio_connection(hfp_connection_t * hfp_connection){
1919     // called internally, NULL check already performed
1920     btstack_assert(hfp_connection != NULL);
1921     if (hfp_connection->state <= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1922         return ERROR_CODE_COMMAND_DISALLOWED;
1923     }
1924     switch (hfp_connection->state) {
1925         case HFP_W2_CONNECT_SCO:
1926             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1927             break;
1928         case HFP_W4_SCO_CONNECTED:
1929         case HFP_AUDIO_CONNECTION_ESTABLISHED:
1930             hfp_connection->release_audio_connection = 1;
1931             break;
1932         default:
1933             return ERROR_CODE_COMMAND_DISALLOWED;
1934     }
1935     return ERROR_CODE_SUCCESS;
1936 }
1937 
1938 bool hfp_sco_setup_active(void){
1939     return hfp_sco_establishment_active != NULL;
1940 }
1941 
1942 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1943 
1944     hfp_sco_establishment_active = hfp_connection;
1945 
1946     // all packet types, fixed bandwidth
1947     int setting = hfp_connection->link_setting;
1948     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1949     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1950     if (hfp_connection->negotiated_codec != HFP_CODEC_CVSD){
1951 #ifdef ENABLE_BCM_PCM_WBS
1952         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1953 #else
1954         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1955 #endif
1956     }
1957     uint16_t packet_types = hfp_link_settings[setting].packet_types;
1958     hfp_connection->packet_types = packet_types;
1959 
1960     // get packet types - bits 6-9 are 'don't allow'
1961     uint16_t packet_types_flipped = packet_types ^ 0x03c0;
1962 #if defined(ENABLE_SCO_OVER_PCM) && defined(ENABLE_NXP_PCM_WBS)
1963     uint8_t  radio_coding_format = 3;
1964     uint32_t host_bandwidth      = 0;
1965     uint8_t  coded_data_size     = 0;
1966     switch (hfp_connection->negotiated_codec){
1967         case HFP_CODEC_CVSD:
1968             radio_coding_format = 0x02;
1969             host_bandwidth = 16000;
1970             coded_data_size = 0x10;
1971             break;
1972         case HFP_CODEC_MSBC:
1973             radio_coding_format = 0x05;
1974             host_bandwidth = 32000;
1975             coded_data_size = 0x08;
1976             break;
1977         default:
1978             log_error("Coding format %u not supported by Controller", hfp_connection->negotiated_codec);
1979             btstack_assert(false);
1980             break;
1981     }
1982     hci_send_cmd(&hci_enhanced_setup_synchronous_connection,
1983         // ACL Handle
1984         hfp_connection->acl_handle,
1985         // Transmit_Bandwidth
1986         8000,
1987         // Receive_Bandwidth
1988         8000,
1989         // Transmit_Coding_Format: radio_config_format, company, codec
1990         radio_coding_format, 0x00, 0x00,
1991         // Receive_Coding_Format: radio_config_format, company, codec
1992         radio_coding_format, 0x00, 0x00,
1993         // Transmit_Codec_Frame_Size
1994         0x3c,
1995         // Receive_Codec_Frame_Size
1996         0x3c,
1997         // Input_Bandwidth
1998         host_bandwidth,
1999         // Output_Bandwidth
2000         host_bandwidth,
2001         // Input_Coding_Format, 0x04 = Linear PCM, company, codec
2002         0x04, 0x00, 0x00,
2003         // Output_Coding_Format, 0x04 = Linear PCM, company, codec
2004         0x04, 0x00, 0x00,
2005         // Input_Coded_Data_Size
2006         coded_data_size,
2007         // Output_Coded_Data_Size
2008         coded_data_size,
2009         // Input_PCM_Data_Format, 0x02 = 2’s complement
2010         0x02,
2011         // Output_PCM_Data_Format, 0x02 = 2’s complement
2012         0x02,
2013         // Input_PCM_Sample_Payload_MSB_Position
2014         0x00,
2015         // Output_PCM_Sample_Payload_MSB_Position
2016         0x00,
2017         // Input_Data_Path - vendor specific: NXP - I2S/PCM
2018         0x01,
2019         // Output_Data_Path - vendor specific: NXP - I2S/PCM
2020         0x01,
2021         // Input_Transport_Unit_Size
2022         0x10,
2023         // Output_Transport_Unit_Size
2024         0x10,
2025         //
2026         hfp_link_settings[setting].max_latency,
2027         packet_types_flipped,
2028         hfp_link_settings[setting].retransmission_effort);
2029 #else
2030     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
2031         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types_flipped);
2032 #endif
2033 }
2034 
2035 #ifdef ENABLE_HFP_HF_SAFE_SETTINGS
2036 hfp_link_settings_t hfp_safe_settings_for_context(bool use_eSCO, uint8_t negotiated_codec, bool secure_connection_in_use){
2037     uint8_t i;
2038     hfp_link_settings_t link_setting = HFP_LINK_SETTINGS_NONE;
2039     for (i=0 ; i < (sizeof(hfp_mandatory_safe_settings) / sizeof(struct hfp_mandatory_safe_setting)) ; i++){
2040         uint16_t packet_types = hfp_link_settings[(uint8_t)(hfp_mandatory_safe_settings[i].link_setting)].packet_types;
2041         bool is_eSCO_setting = (packet_types & SCO_PACKET_TYPES_ESCO) != 0;
2042         if (is_eSCO_setting != use_eSCO) continue;
2043         if ((hfp_mandatory_safe_settings[i].codec_mask & (1 << negotiated_codec)) == 0) continue;
2044         if (hfp_mandatory_safe_settings[i].secure_connection_in_use != secure_connection_in_use) continue;
2045         link_setting = hfp_mandatory_safe_settings[i].link_setting;
2046         break;
2047     }
2048     return link_setting;
2049 }
2050 #endif
2051 
2052 void hfp_accept_synchronous_connection(hfp_connection_t * hfp_connection, bool use_eSCO){
2053 
2054     hfp_sco_establishment_active = hfp_connection;
2055 
2056     // lookup safe settings based on SCO type, SC use and Codec type
2057     uint16_t max_latency;
2058     uint16_t packet_types;
2059     uint16_t retransmission_effort;
2060 
2061 #ifdef ENABLE_HFP_HF_SAFE_SETTINGS
2062     hfp_link_settings_t link_setting = HFP_LINK_SETTINGS_NONE;
2063     // fallback for non-CVSD codec and SCO connection
2064     if ((hfp_connection->negotiated_codec != HFP_CODEC_CVSD) && (use_eSCO == false)){
2065         max_latency           = 0xffff;
2066         retransmission_effort = 0xff;
2067         packet_types          = SCO_PACKET_TYPES_HV3 | SCO_PACKET_TYPES_HV1;
2068     } else {
2069         // use safe settings from HFP v1.9, table 6.10
2070     bool secure_connection_in_use = gap_secure_connection(hfp_connection->acl_handle);
2071         link_setting = hfp_safe_settings_for_context(use_eSCO, hfp_connection->negotiated_codec, secure_connection_in_use);
2072         max_latency             = hfp_link_settings[(uint8_t) link_setting].max_latency;
2073         retransmission_effort   = hfp_link_settings[(uint8_t) link_setting].retransmission_effort;
2074         packet_types            = hfp_link_settings[(uint8_t) link_setting].packet_types;
2075     }
2076 #else
2077     max_latency           = 0xffff;
2078     retransmission_effort = 0xff;
2079     if (use_eSCO) {
2080         packet_types      = SCO_PACKET_TYPES_EV3 | SCO_PACKET_TYPES_2EV3;
2081     } else {
2082         packet_types      = SCO_PACKET_TYPES_HV3 | SCO_PACKET_TYPES_HV1;
2083     }
2084 #endif
2085 
2086     // transparent data for non-CVSD connections or if codec provided by Controller
2087     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
2088     if (hfp_connection->negotiated_codec != HFP_CODEC_CVSD){
2089 #ifdef ENABLE_BCM_PCM_WBS
2090         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
2091 #else
2092         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
2093 #endif
2094     }
2095 
2096     // filter packet types
2097     packet_types &= hfp_get_sco_packet_types();
2098 
2099     hfp_connection->packet_types = packet_types;
2100 
2101     // bits 6-9 are 'don't allow'
2102     uint16_t packet_types_flipped = packet_types ^ 0x3c0;
2103 
2104     log_info("Sending hci_accept_connection_request: packet types 0x%04x, sco_voice_setting 0x%02x",
2105             packet_types, sco_voice_setting);
2106 
2107 #if defined(ENABLE_SCO_OVER_PCM) && defined(ENABLE_NXP_PCM_WBS)
2108     uint8_t radio_coding_format = 3;
2109     uint32_t host_bandwidth = 0;
2110     uint8_t  coded_data_size = 0;
2111     switch (hfp_connection->negotiated_codec){
2112         case HFP_CODEC_CVSD:
2113             radio_coding_format = 0x02;
2114             host_bandwidth = 16000;
2115             coded_data_size = 0x10;
2116             break;
2117         case HFP_CODEC_MSBC:
2118             radio_coding_format = 0x05;
2119             host_bandwidth = 32000;
2120             coded_data_size = 0x08;
2121             break;
2122         default:
2123             log_error("Coding format %u not supported by Controller", hfp_connection->negotiated_codec);
2124             btstack_assert(false);
2125             break;
2126     }
2127     hci_send_cmd(&hci_enhanced_accept_synchronous_connection,
2128         // BD_ADDR
2129         hfp_connection->remote_addr,
2130         // Transmit_Bandwidth
2131         8000,
2132         // Receive_Bandwidth
2133         8000,
2134         // Transmit_Coding_Format: radio_config_format, company, codec
2135         radio_coding_format, 0x00, 0x00,
2136         // Receive_Coding_Format: radio_config_format, company, codec
2137         radio_coding_format, 0x00, 0x00,
2138         // Transmit_Codec_Frame_Size
2139         0x3c,
2140         // Receive_Codec_Frame_Size
2141         0x3c,
2142         // Input_Bandwidth
2143         host_bandwidth,
2144         // Output_Bandwidth
2145         host_bandwidth,
2146         // Input_Coding_Format, 0x04 = Linear PCM, company, codec
2147         0x04, 0x00, 0x00,
2148         // Output_Coding_Format, 0x04 = Linear PCM, company, codec
2149         0x04, 0x00, 0x00,
2150         // Input_Coded_Data_Size
2151         coded_data_size,
2152         // Output_Coded_Data_Size
2153         coded_data_size,
2154         // Input_PCM_Data_Format, 0x02 = 2’s complement
2155         0x02,
2156         // Output_PCM_Data_Format, 0x02 = 2’s complement
2157         0x02,
2158         // Input_PCM_Sample_Payload_MSB_Position
2159         0x00,
2160         // Output_PCM_Sample_Payload_MSB_Position
2161         0x00,
2162         // Input_Data_Path - vendor specific: NXP - I2S/PCM
2163         0x01,
2164         // Output_Data_Path - vendor specific: NXP - I2S/PCM
2165         0x01,
2166         // Input_Transport_Unit_Size
2167         0x10,
2168         // Output_Transport_Unit_Size
2169         0x10,
2170         //
2171         max_latency,
2172         packet_types_flipped,
2173         retransmission_effort);
2174 #else
2175     hci_send_cmd(&hci_accept_synchronous_connection, hfp_connection->remote_addr, 8000, 8000, max_latency,
2176                  sco_voice_setting, retransmission_effort, packet_types_flipped);
2177 #endif
2178 }
2179 
2180 #ifdef ENABLE_CC256X_ASSISTED_HFP
2181 void hfp_cc256x_write_codec_config(hfp_connection_t * hfp_connection){
2182     uint32_t sample_rate_hz;
2183     uint16_t clock_rate_khz;
2184     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
2185         clock_rate_khz = 512;
2186         sample_rate_hz = 16000;
2187     } else {
2188         clock_rate_khz = 256;
2189         sample_rate_hz = 8000;
2190     }
2191     uint8_t clock_direction = 0;        // master
2192     uint16_t frame_sync_duty_cycle = 0; // i2s with 50%
2193     uint8_t  frame_sync_edge = 1;       // rising edge
2194     uint8_t  frame_sync_polarity = 0;   // active high
2195     uint8_t  reserved = 0;
2196     uint16_t size = 16;
2197     uint16_t chan_1_offset = 1;
2198     uint16_t chan_2_offset = chan_1_offset + size;
2199     uint8_t  out_edge = 1;              // rising
2200     uint8_t  in_edge = 0;               // falling
2201     hci_send_cmd(&hci_ti_write_codec_config, clock_rate_khz, clock_direction, sample_rate_hz, frame_sync_duty_cycle,
2202                  frame_sync_edge, frame_sync_polarity, reserved,
2203                  size, chan_1_offset, out_edge, size, chan_1_offset, in_edge, reserved,
2204                  size, chan_2_offset, out_edge, size, chan_2_offset, in_edge, reserved);
2205 }
2206 #endif
2207 
2208 #ifdef ENABLE_BCM_PCM_WBS
2209 void hfp_bcm_write_i2spcm_interface_param(hfp_connection_t * hfp_connection){
2210     uint8_t sample_rate = (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? 1 : 0;
2211     // i2s enable, master, 8/16 kHz, 512 kHz
2212     hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, sample_rate, 2);
2213 }
2214 #endif
2215 
2216 void hfp_prepare_for_sco(hfp_connection_t * hfp_connection){
2217 #ifdef ENABLE_CC256X_ASSISTED_HFP
2218     hfp_connection->cc256x_send_write_codec_config = true;
2219     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
2220         hfp_connection->cc256x_send_wbs_associate = true;
2221     }
2222 #endif
2223 
2224 #ifdef ENABLE_BCM_PCM_WBS
2225 #ifndef HAVE_BCM_PCM_NBS_16KHZ
2226     hfp_connection->bcm_send_write_i2spcm_interface_param = true;
2227 #endif
2228     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
2229         hfp_connection->bcm_send_enable_wbs = true;
2230     }
2231 #endif
2232 
2233 #ifdef ENABLE_RTK_PCM_WBS
2234     hfp_connection->rtk_send_sco_config = true;
2235 #endif
2236 }
2237 
2238 void hfp_set_hf_callback(btstack_packet_handler_t callback){
2239     hfp_hf_callback = callback;
2240 }
2241 
2242 void hfp_set_ag_callback(btstack_packet_handler_t callback){
2243     hfp_ag_callback = callback;
2244 }
2245 
2246 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
2247     hfp_ag_rfcomm_packet_handler = handler;
2248 }
2249 
2250 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
2251     hfp_hf_rfcomm_packet_handler = handler;
2252 }
2253 
2254 void hfp_init(void){
2255     hfp_allowed_sco_packet_types = SCO_PACKET_TYPES_ALL;
2256 }
2257 
2258 void hfp_deinit(void){
2259     hfp_allowed_sco_packet_types = 0;
2260     hfp_connections = NULL;
2261     hfp_hf_callback = NULL;
2262     hfp_ag_callback = NULL;
2263     hfp_hf_rfcomm_packet_handler = NULL;
2264     hfp_ag_rfcomm_packet_handler = NULL;
2265     hfp_sco_establishment_active = NULL;
2266     hfp_custom_commands_ag = NULL;
2267     hfp_custom_commands_hf = NULL;
2268     (void) memset(&hfp_sdp_query_context, 0, sizeof(hfp_sdp_query_context_t));
2269     (void) memset(&hfp_sdp_query_request, 0, sizeof(btstack_context_callback_registration_t));
2270 }
2271 
2272 void hfp_set_sco_packet_types(uint16_t packet_types){
2273     hfp_allowed_sco_packet_types = packet_types;
2274 }
2275 
2276 uint16_t hfp_get_sco_packet_types(void){
2277     return hfp_allowed_sco_packet_types;
2278 }
2279 
2280 hfp_link_settings_t hfp_next_link_setting(hfp_link_settings_t current_setting, uint16_t local_sco_packet_types,
2281                                           uint16_t remote_sco_packet_types, bool eSCO_S4_supported,
2282                                           uint8_t negotiated_codec) {
2283     int8_t setting = (int8_t) current_setting;
2284     while (setting > 0){
2285         setting--;
2286         // skip S4 if not supported
2287         if ((setting == (int8_t) HFP_LINK_SETTINGS_S4) && !eSCO_S4_supported) continue;
2288         // skip wrong codec
2289         if ((hfp_link_settings[setting].codec_mask & (1 << negotiated_codec)) == 0) continue;
2290         // skip disabled or not supported packet types
2291         uint16_t required_packet_types = hfp_link_settings[setting].packet_types;
2292         uint16_t allowed_packet_types  = hfp_allowed_sco_packet_types & local_sco_packet_types & remote_sco_packet_types;
2293         if ((required_packet_types & allowed_packet_types) == 0) continue;
2294 
2295         // found matching setting
2296         return (hfp_link_settings_t) setting;
2297     }
2298     return HFP_LINK_SETTINGS_NONE;
2299 }
2300 
2301 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){
2302     uint8_t negotiated_codec   = hfp_connection->negotiated_codec;
2303     uint16_t local_sco_packet_types = hci_usable_sco_packet_types();
2304     uint16_t remote_sco_packet_types = hci_remote_sco_packet_types(hfp_connection->acl_handle);
2305     return hfp_next_link_setting(current_setting, local_sco_packet_types, remote_sco_packet_types, eSCO_S4_supported,
2306                                  negotiated_codec);
2307 }
2308 
2309 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
2310     // get highest possible link setting
2311     hfp_connection->link_setting = hfp_next_link_setting_for_connection(HFP_LINK_SETTINGS_NONE, hfp_connection, eSCO_S4_supported);
2312     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
2313 }
2314 
2315 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
2316 
2317 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
2318 #ifdef ENABLE_LOG_INFO
2319     // encode \n\r
2320     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
2321     int i = 0;
2322     int pos;
2323     for (pos=0 ; (pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)) ; pos++){
2324         switch (packet[pos]){
2325             case '\n':
2326                 printable[i++] = '\\';
2327                 printable[i++] = 'n';
2328                 break;
2329             case '\r':
2330                 printable[i++] = '\\';
2331                 printable[i++] = 'r';
2332                 break;
2333             default:
2334                 printable[i++] = packet[pos];
2335                 break;
2336         }
2337     }
2338     printable[i] = 0;
2339     log_info("%s: '%s'", tag, printable);
2340 #endif
2341 }
2342 
2343 void hfp_register_custom_ag_command(hfp_custom_at_command_t * custom_at_command){
2344     btstack_linked_list_add(&hfp_custom_commands_ag, (btstack_linked_item_t *) custom_at_command);
2345 }
2346 
2347 void hfp_register_custom_hf_command(hfp_custom_at_command_t * custom_at_command){
2348     btstack_linked_list_add(&hfp_custom_commands_hf, (btstack_linked_item_t *) custom_at_command);
2349 }
2350 
2351 // HFP H2 Synchronization - might get moved into a hfp_h2.c
2352 
2353 // find position of h2 sync header, returns -1 if not found, or h2 sync position
2354 static int16_t hfp_h2_sync_find(const uint8_t * frame_data, uint16_t frame_len){
2355     uint16_t i;
2356     for (i=0;i<(frame_len - 1);i++){
2357         // check: first byte == 1
2358         uint8_t h2_first_byte = frame_data[i];
2359         if (h2_first_byte == 0x01) {
2360             uint8_t h2_second_byte = frame_data[i + 1];
2361             // check lower nibble of second byte == 0x08
2362             if ((h2_second_byte & 0x0F) == 8) {
2363                 // check if bits 0+2 == bits 1+3
2364                 uint8_t hn = h2_second_byte >> 4;
2365                 if (((hn >> 1) & 0x05) == (hn & 0x05)) {
2366                     return (int16_t) i;
2367                 }
2368             }
2369         }
2370     }
2371     return -1;
2372 }
2373 
2374 static void hfp_h2_sync_reset(hfp_h2_sync_t * hfp_h2_sync){
2375     hfp_h2_sync->frame_len = 0;
2376 }
2377 
2378 void hfp_h2_sync_init(hfp_h2_sync_t * hfp_h2_sync,
2379                       bool (*callback)(bool bad_frame, const uint8_t * frame_data, uint16_t frame_len)){
2380     hfp_h2_sync->callback = callback;
2381     hfp_h2_sync->dropped_bytes = 0;
2382     hfp_h2_sync_reset(hfp_h2_sync);
2383 }
2384 
2385 static void hfp_h2_report_bad_frames(hfp_h2_sync_t *hfp_h2_sync){
2386     // report bad frames
2387     while (hfp_h2_sync->dropped_bytes >= HFP_H2_SYNC_FRAME_SIZE){
2388         hfp_h2_sync->dropped_bytes -= HFP_H2_SYNC_FRAME_SIZE;
2389         (void)(*hfp_h2_sync->callback)(true,NULL, HFP_H2_SYNC_FRAME_SIZE);
2390     }
2391 }
2392 
2393 static void hfp_h2_sync_drop_bytes(hfp_h2_sync_t * hfp_h2_sync, uint16_t bytes_to_drop){
2394     btstack_assert(bytes_to_drop <= hfp_h2_sync->frame_len);
2395     memmove(hfp_h2_sync->frame_data, &hfp_h2_sync->frame_data[bytes_to_drop], hfp_h2_sync->frame_len - bytes_to_drop);
2396     hfp_h2_sync->dropped_bytes += bytes_to_drop;
2397     hfp_h2_sync->frame_len     -= bytes_to_drop;
2398     hfp_h2_report_bad_frames(hfp_h2_sync);
2399 }
2400 
2401 void hfp_h2_sync_process(hfp_h2_sync_t *hfp_h2_sync, bool bad_frame, const uint8_t *frame_data, uint16_t frame_len) {
2402 
2403     if (bad_frame){
2404         // drop all data
2405         hfp_h2_sync->dropped_bytes += hfp_h2_sync->frame_len;
2406         hfp_h2_sync->frame_len = 0;
2407         // all new data is bad, too
2408         hfp_h2_sync->dropped_bytes += frame_len;
2409         // report frames
2410         hfp_h2_report_bad_frames(hfp_h2_sync);
2411         return;
2412     }
2413 
2414     while (frame_len > 0){
2415         // Fill hfp_h2_sync->frame_buffer
2416         uint16_t bytes_free_in_frame_buffer = HFP_H2_SYNC_FRAME_SIZE - hfp_h2_sync->frame_len;
2417         uint16_t bytes_to_append = btstack_min(frame_len, bytes_free_in_frame_buffer);
2418         memcpy(&hfp_h2_sync->frame_data[hfp_h2_sync->frame_len], frame_data, bytes_to_append);
2419         frame_data             += bytes_to_append;
2420         frame_len              -= bytes_to_append;
2421         hfp_h2_sync->frame_len += bytes_to_append;
2422         // check complete frame for h2 sync
2423         if (hfp_h2_sync->frame_len == HFP_H2_SYNC_FRAME_SIZE){
2424             bool valid_frame = true;
2425             int16_t h2_pos = hfp_h2_sync_find(hfp_h2_sync->frame_data, hfp_h2_sync->frame_len);
2426             if (h2_pos < 0){
2427                 // no h2 sync, no valid frame, keep last byte if it is 0x01
2428                 if (hfp_h2_sync->frame_data[HFP_H2_SYNC_FRAME_SIZE-1] == 0x01){
2429                     hfp_h2_sync_drop_bytes(hfp_h2_sync, HFP_H2_SYNC_FRAME_SIZE - 1);
2430                 } else {
2431                     hfp_h2_sync_drop_bytes(hfp_h2_sync, HFP_H2_SYNC_FRAME_SIZE);
2432                 }
2433                 valid_frame = false;
2434             }
2435             else if (h2_pos > 0){
2436                 // drop data before h2 sync
2437                 hfp_h2_sync_drop_bytes(hfp_h2_sync, h2_pos);
2438                 valid_frame = false;
2439             }
2440             if (valid_frame) {
2441                 // h2 sync at pos 0 and complete frame
2442                 bool codec_ok = (*hfp_h2_sync->callback)(false, hfp_h2_sync->frame_data, hfp_h2_sync->frame_len);
2443                 if (codec_ok){
2444                     hfp_h2_sync_reset(hfp_h2_sync);
2445                 } else {
2446                     // drop first two bytes
2447                     hfp_h2_sync_drop_bytes(hfp_h2_sync, 2);
2448                 }
2449             }
2450         }
2451     }
2452 }
2453