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