xref: /btstack/src/classic/avrcp.c (revision 58c560219426df86e08670b9ca7d3d1f9979a6c1)
1 /*
2  * Copyright (C) 2016 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 MATTHIAS
24  * RINGWALD 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__ "avrcp.c"
39 
40 #include <stdint.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 #include "btstack.h"
47 #include "classic/avrcp.h"
48 
49 #define AV_REMOTE_CONTROL_TARGET        0x110C
50 #define AV_REMOTE_CONTROL               0x110E
51 #define AV_REMOTE_CONTROL_CONTROLLER    0x110F
52 
53 #define PSM_AVCTP                       BLUETOOTH_PROTOCOL_AVCTP
54 #define PSM_AVCTP_BROWSING              0xFF17
55 
56 /*
57 Category 1: Player/Recorder
58 Category 2: Monitor/Amplifier
59 Category 3: Tuner
60 Category 4: Menu
61 */
62 
63 /* controller supported features
64 Bit 0 = Category 1
65 Bit 1 = Category 2
66 Bit 2 = Category 3
67 Bit 3 = Category 4
68 Bit 4-5 = RFA
69 Bit 6 = Supports browsing
70 Bit 7-15 = RFA
71 The bits for supported categories are set to 1. Others are set to 0.
72 */
73 
74 /* target supported features
75 Bit 0 = Category 1
76 Bit 1 = Category 2
77 Bit 2 = Category 3
78 Bit 3 = Category 4
79 Bit 4 = Player Application Settings. Bit 0 should be set for this bit to be set.
80 Bit 5 = Group Navigation. Bit 0 should be set for this bit to be set.
81 Bit 6 = Supports browsing*4
82 Bit 7 = Supports multiple media player applications
83 Bit 8-15 = RFA
84 The bits for supported categories are set to 1. Others are set to 0.
85 */
86 
87 // TODO: merge with avdtp_packet_type_t
88 typedef enum {
89     AVRCP_SINGLE_PACKET= 0,
90     AVRCP_START_PACKET    ,
91     AVRCP_CONTINUE_PACKET ,
92     AVRCP_END_PACKET
93 } avrcp_packet_type_t;
94 
95 typedef enum {
96     AVRCP_COMMAND_FRAME = 0,
97     AVRCP_RESPONSE_FRAME
98 } avrcp_frame_type_t;
99 
100 static const char * default_avrcp_controller_service_name = "BTstack AVRCP Controller Service";
101 static const char * default_avrcp_controller_service_provider_name = "BTstack AVRCP Controller Service Provider";
102 static const char * default_avrcp_target_service_name = "BTstack AVRCP Target Service";
103 static const char * default_avrcp_target_service_provider_name = "BTstack AVRCP Target Service Provider";
104 
105 static btstack_linked_list_t avrcp_connections;
106 static btstack_packet_handler_t avrcp_callback;
107 
108 static const char * avrcp_subunit_type_name[] = {
109     "MONITOR", "AUDIO", "PRINTER", "DISC", "TAPE_RECORDER_PLAYER", "TUNER",
110     "CA", "CAMERA", "RESERVED", "PANEL", "BULLETIN_BOARD", "CAMERA_STORAGE",
111     "VENDOR_UNIQUE", "RESERVED_FOR_ALL_SUBUNIT_TYPES",
112     "EXTENDED_TO_NEXT_BYTE", "UNIT", "ERROR"
113 };
114 const char * avrcp_subunit2str(uint16_t index){
115     if (index <= 11) return avrcp_subunit_type_name[index];
116     if (index >= 0x1C && index <= 0x1F) return avrcp_subunit_type_name[index - 0x10];
117     return avrcp_subunit_type_name[16];
118 }
119 
120 static const char * avrcp_event_name[] = {
121     "ERROR", "PLAYBACK_STATUS_CHANGED",
122     "TRACK_CHANGED", "TRACK_REACHED_END", "TRACK_REACHED_START",
123     "PLAYBACK_POS_CHANGED", "BATT_STATUS_CHANGED", "SYSTEM_STATUS_CHANGED",
124     "PLAYER_APPLICATION_SETTING_CHANGED", "NOW_PLAYING_CONTENT_CHANGED",
125     "AVAILABLE_PLAYERS_CHANGED", "ADDRESSED_PLAYER_CHANGED", "UIDS_CHANGED", "VOLUME_CHANGED"
126 };
127 const char * avrcp_event2str(uint16_t index){
128     if (index <= 0x0d) return avrcp_event_name[index];
129     return avrcp_event_name[0];
130 }
131 
132 static const char * avrcp_operation_name[] = {
133     "NOT SUPPORTED", // 0x3B
134     "SKIP", "NOT SUPPORTED", "NOT SUPPORTED", "NOT SUPPORTED", "NOT SUPPORTED",
135     "VOLUME_UP", "VOLUME_DOWN", "MUTE", "PLAY", "STOP", "PAUSE", "NOT SUPPORTED",
136     "REWIND", "FAST_FORWARD", "NOT SUPPORTED", "FORWARD", "BACKWARD" // 0x4C
137 };
138 const char * avrcp_operation2str(uint8_t index){
139     if (index >= 0x3B && index <= 0x4C) return avrcp_operation_name[index - 0x3B];
140     return avrcp_operation_name[0];
141 }
142 
143 static const char * avrcp_media_attribute_id_name[] = {
144     "NONE", "TITLE", "ARTIST", "ALBUM", "TRACK", "TOTAL TRACKS", "GENRE", "SONG LENGTH"
145 };
146 const char * avrcp_attribute2str(uint8_t index){
147     if (index >= 1 && index <= 7) return avrcp_media_attribute_id_name[index];
148     return avrcp_media_attribute_id_name[0];
149 }
150 
151 static const char * avrcp_play_status_name[] = {
152     "STOPPED", "PLAYING", "PAUSED", "FORWARD SEEK", "REVERSE SEEK",
153     "ERROR" // 0xFF
154 };
155 const char * avrcp_play_status2str(uint8_t index){
156     if (index >= 1 && index <= 4) return avrcp_play_status_name[index];
157     return avrcp_play_status_name[5];
158 }
159 
160 static const char * avrcp_ctype_name[] = {
161     "CONTROL",
162     "STATUS",
163     "SPECIFIC_INQUIRY",
164     "NOTIFY",
165     "GENERAL_INQUIRY",
166     "RESERVED5",
167     "RESERVED6",
168     "RESERVED7",
169     "NOT_IMPLEMENTED",
170     "ACCEPTED",
171     "REJECTED",
172     "IN_TRANSITION",
173     "IMPLEMENTED_STABLE",
174     "CHANGED_STABLE",
175     "RESERVED",
176     "INTERIM"
177 };
178 const char * avrcp_ctype2str(uint8_t index){
179     if (index < sizeof(avrcp_ctype_name)){
180         return avrcp_ctype_name[index];
181     }
182     return "NONE";
183 }
184 
185 static const char * avrcp_shuffle_mode_name[] = {
186     "SHUFFLE OFF",
187     "SHUFFLE ALL TRACKS",
188     "SHUFFLE GROUP"
189 };
190 
191 const char * avrcp_shuffle2str(uint8_t index){
192     if (index >= 1 && index <= 3) return avrcp_shuffle_mode_name[index-1];
193     return "NONE";
194 }
195 
196 static const char * avrcp_repeat_mode_name[] = {
197     "REPEAT OFF",
198     "REPEAT SINGLE TRACK",
199     "REPEAT ALL TRACKS",
200     "REPEAT GROUP"
201 };
202 
203 const char * avrcp_repeat2str(uint8_t index){
204     if (index >= 1 && index <= 4) return avrcp_repeat_mode_name[index-1];
205     return "NONE";
206 }
207 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
208 
209 static void avrcp_create_sdp_record(uint8_t controller, uint8_t * service, uint32_t service_record_handle, uint8_t browsing, uint16_t supported_features, const char * service_name, const char * service_provider_name){
210     uint8_t* attribute;
211     de_create_sequence(service);
212 
213     // 0x0000 "Service Record Handle"
214     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
215     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
216 
217     // 0x0001 "Service Class ID List"
218     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
219     attribute = de_push_sequence(service);
220     {
221         if (controller){
222             de_add_number(attribute, DE_UUID, DE_SIZE_16, AV_REMOTE_CONTROL);
223             de_add_number(attribute, DE_UUID, DE_SIZE_16, AV_REMOTE_CONTROL_CONTROLLER);
224         } else {
225             de_add_number(attribute, DE_UUID, DE_SIZE_16, AV_REMOTE_CONTROL_TARGET);
226         }
227     }
228     de_pop_sequence(service, attribute);
229 
230     // 0x0004 "Protocol Descriptor List"
231     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
232     attribute = de_push_sequence(service);
233     {
234         uint8_t* l2cpProtocol = de_push_sequence(attribute);
235         {
236             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
237             de_add_number(l2cpProtocol,  DE_UINT, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);
238         }
239         de_pop_sequence(attribute, l2cpProtocol);
240 
241         uint8_t* avctpProtocol = de_push_sequence(attribute);
242         {
243             de_add_number(avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // avctpProtocol_service
244             de_add_number(avctpProtocol,  DE_UINT, DE_SIZE_16,  0x0103);    // version
245         }
246         de_pop_sequence(attribute, avctpProtocol);
247 
248         if (browsing){
249             de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
250             attribute = de_push_sequence(service);
251             {
252                 uint8_t* browsing_l2cpProtocol = de_push_sequence(attribute);
253                 {
254                     de_add_number(browsing_l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
255                     de_add_number(browsing_l2cpProtocol,  DE_UINT, DE_SIZE_16, PSM_AVCTP_BROWSING);
256                 }
257                 de_pop_sequence(attribute, browsing_l2cpProtocol);
258 
259                 uint8_t* browsing_avctpProtocol = de_push_sequence(attribute);
260                 {
261                     de_add_number(browsing_avctpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_AVCTP);  // browsing_avctpProtocol_service
262                     de_add_number(browsing_avctpProtocol,  DE_UINT, DE_SIZE_16,  0x0103);    // version
263                 }
264                 de_pop_sequence(attribute, browsing_avctpProtocol);
265             }
266             de_pop_sequence(service, attribute);
267         }
268     }
269     de_pop_sequence(service, attribute);
270 
271     // 0x0005 "Public Browse Group"
272     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
273     attribute = de_push_sequence(service);
274     {
275         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
276     }
277     de_pop_sequence(service, attribute);
278 
279     // 0x0009 "Bluetooth Profile Descriptor List"
280     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
281     attribute = de_push_sequence(service);
282     {
283         uint8_t *avrcProfile = de_push_sequence(attribute);
284         {
285             de_add_number(avrcProfile,  DE_UUID, DE_SIZE_16, AV_REMOTE_CONTROL);
286             de_add_number(avrcProfile,  DE_UINT, DE_SIZE_16, 0x0105);
287         }
288         de_pop_sequence(attribute, avrcProfile);
289     }
290     de_pop_sequence(service, attribute);
291 
292 
293     // 0x0100 "Service Name"
294     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
295     if (service_name){
296         de_add_data(service,  DE_STRING, strlen(service_name), (uint8_t *) service_name);
297     } else {
298         if (controller){
299             de_add_data(service,  DE_STRING, strlen(default_avrcp_controller_service_name), (uint8_t *) default_avrcp_controller_service_name);
300         } else {
301             de_add_data(service,  DE_STRING, strlen(default_avrcp_target_service_name), (uint8_t *) default_avrcp_target_service_name);
302         }
303     }
304 
305     // 0x0100 "Provider Name"
306     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0102);
307     if (service_provider_name){
308         de_add_data(service,  DE_STRING, strlen(service_provider_name), (uint8_t *) service_provider_name);
309     } else {
310         if (controller){
311             de_add_data(service,  DE_STRING, strlen(default_avrcp_controller_service_provider_name), (uint8_t *) default_avrcp_controller_service_provider_name);
312         } else {
313             de_add_data(service,  DE_STRING, strlen(default_avrcp_target_service_provider_name), (uint8_t *) default_avrcp_target_service_provider_name);
314         }
315     }
316 
317     // 0x0311 "Supported Features"
318     de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);
319     de_add_number(service, DE_UINT, DE_SIZE_16, supported_features);
320 }
321 
322 void avrcp_controller_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint8_t browsing, uint16_t supported_features, const char * service_name, const char * service_provider_name){
323     avrcp_create_sdp_record(1, service, service_record_handle, browsing, supported_features, service_name, service_provider_name);
324 }
325 
326 void avrcp_target_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint8_t browsing, uint16_t supported_features, const char * service_name, const char * service_provider_name){
327     avrcp_create_sdp_record(0, service, service_record_handle, browsing, supported_features, service_name, service_provider_name);
328 }
329 
330 static void avrcp_emit_repeat_and_shuffle_mode(btstack_packet_handler_t callback, uint16_t con_handle, uint8_t status, avrcp_repeat_mode_t repeat_mode, avrcp_shuffle_mode_t shuffle_mode){
331     if (!callback) return;
332     uint8_t event[8];
333     int pos = 0;
334     event[pos++] = HCI_EVENT_AVRCP_META;
335     event[pos++] = sizeof(event) - 2;
336     event[pos++] = AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE;
337     little_endian_store_16(event, pos, con_handle);
338     pos += 2;
339     event[pos++] = status;
340     event[pos++] = repeat_mode;
341     event[pos++] = shuffle_mode;
342     (*callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
343 }
344 
345 static void avrcp_emit_connection_established(btstack_packet_handler_t callback, uint16_t con_handle, uint8_t status, uint16_t local_cid, bd_addr_t addr){
346     if (!callback) return;
347     uint8_t event[14];
348     int pos = 0;
349     event[pos++] = HCI_EVENT_AVRCP_META;
350     event[pos++] = sizeof(event) - 2;
351     event[pos++] = AVRCP_SUBEVENT_CONNECTION_ESTABLISHED;
352     little_endian_store_16(event, pos, con_handle);
353     pos += 2;
354     event[pos++] = status;
355     little_endian_store_16(event, pos, local_cid);
356     pos += 2;
357     reverse_bd_addr(addr,&event[pos]);
358     pos += 6;
359     (*callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
360 }
361 
362 static void avrcp_emit_operation_status(btstack_packet_handler_t callback, uint8_t subevent, uint16_t con_handle, uint8_t status, uint8_t operation_id){
363     if (!callback) return;
364     uint8_t event[7];
365     int pos = 0;
366     event[pos++] = HCI_EVENT_AVRCP_META;
367     event[pos++] = sizeof(event) - 2;
368     event[pos++] = subevent;
369     little_endian_store_16(event, pos, con_handle);
370     pos += 2;
371     event[pos++] = status;
372     event[pos++] = operation_id;
373     (*callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
374 }
375 
376 static void avrcp_emit_connection_closed(btstack_packet_handler_t callback, uint16_t con_handle){
377     if (!callback) return;
378     uint8_t event[5];
379     int pos = 0;
380     event[pos++] = HCI_EVENT_AVRCP_META;
381     event[pos++] = sizeof(event) - 2;
382     event[pos++] = AVRCP_SUBEVENT_CONNECTION_RELEASED;
383     little_endian_store_16(event, pos, con_handle);
384     pos += 2;
385     (*callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
386 }
387 
388 static avrcp_connection_t * get_avrcp_connection_for_bd_addr(bd_addr_t addr){
389     btstack_linked_list_iterator_t it;
390     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
391     while (btstack_linked_list_iterator_has_next(&it)){
392         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
393         if (memcmp(addr, connection->remote_addr, 6) != 0) continue;
394         return connection;
395     }
396     return NULL;
397 }
398 
399 static avrcp_connection_t * get_avrcp_connection_for_con_handle(hci_con_handle_t con_handle){
400     btstack_linked_list_iterator_t it;
401     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
402     while (btstack_linked_list_iterator_has_next(&it)){
403         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
404         if (connection->con_handle != con_handle) continue;
405         return connection;
406     }
407     return NULL;
408 }
409 
410 static avrcp_connection_t * get_avrcp_connection_for_l2cap_signaling_cid(uint16_t l2cap_cid){
411     btstack_linked_list_iterator_t it;
412     btstack_linked_list_iterator_init(&it, (btstack_linked_list_t *) &avrcp_connections);
413     while (btstack_linked_list_iterator_has_next(&it)){
414         avrcp_connection_t * connection = (avrcp_connection_t *)btstack_linked_list_iterator_next(&it);
415         if (connection->l2cap_signaling_cid != l2cap_cid) continue;
416         return connection;
417     }
418     return NULL;
419 }
420 
421 static void avrcp_request_can_send_now(avrcp_connection_t * connection, uint16_t l2cap_cid){
422     connection->wait_to_send = 1;
423     l2cap_request_can_send_now_event(l2cap_cid);
424 }
425 
426 static void avrcp_press_and_hold_timeout_handler(btstack_timer_source_t * timer){
427     UNUSED(timer);
428     avrcp_connection_t * connection = btstack_run_loop_get_timer_context(timer);
429     btstack_run_loop_set_timer(&connection->press_and_hold_cmd_timer, 2000); // 2 seconds timeout
430     btstack_run_loop_add_timer(&connection->press_and_hold_cmd_timer);
431     connection->state = AVCTP_W2_SEND_PRESS_COMMAND;
432     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
433 }
434 
435 static void avrcp_press_and_hold_timer_start(avrcp_connection_t * connection){
436     btstack_run_loop_remove_timer(&connection->press_and_hold_cmd_timer);
437     btstack_run_loop_set_timer_handler(&connection->press_and_hold_cmd_timer, avrcp_press_and_hold_timeout_handler);
438     btstack_run_loop_set_timer_context(&connection->press_and_hold_cmd_timer, connection);
439     btstack_run_loop_set_timer(&connection->press_and_hold_cmd_timer, 2000); // 2 seconds timeout
440     btstack_run_loop_add_timer(&connection->press_and_hold_cmd_timer);
441 }
442 
443 static void avrcp_press_and_hold_timer_stop(avrcp_connection_t * connection){
444     btstack_run_loop_remove_timer(&connection->press_and_hold_cmd_timer);
445 }
446 
447 static void request_pass_through_release_control_cmd(avrcp_connection_t * connection){
448     connection->state = AVCTP_W2_SEND_RELEASE_COMMAND;
449     switch (connection->cmd_operands[0]){
450         case AVRCP_OPERATION_ID_REWIND:
451         case AVRCP_OPERATION_ID_FAST_FORWARD:
452             avrcp_press_and_hold_timer_stop(connection);
453             break;
454         default:
455             break;
456     }
457     connection->cmd_operands[0] = 0x80 | connection->cmd_operands[0];
458     connection->transaction_label++;
459     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
460 }
461 
462 static void request_pass_through_press_control_cmd(uint16_t con_handle, avrcp_operation_id_t opid, uint16_t playback_speed){
463     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
464     if (!connection){
465         log_error("avrcp: could not find a connection.");
466         return;
467     }
468     if (connection->state != AVCTP_CONNECTION_OPENED) return;
469     connection->state = AVCTP_W2_SEND_PRESS_COMMAND;
470     connection->cmd_to_send =  AVRCP_CMD_OPCODE_PASS_THROUGH;
471     connection->command_type = AVRCP_CTYPE_CONTROL;
472     connection->subunit_type = AVRCP_SUBUNIT_TYPE_PANEL;
473     connection->subunit_id =   0;
474     connection->cmd_operands_lenght = 0;
475 
476     connection->cmd_operands_lenght = 2;
477     connection->cmd_operands[0] = opid;
478     if (playback_speed > 0){
479         connection->cmd_operands[2] = playback_speed;
480         connection->cmd_operands_lenght++;
481     }
482     connection->cmd_operands[1] = connection->cmd_operands_lenght - 2;
483 
484     switch (connection->cmd_operands[0]){
485         case AVRCP_OPERATION_ID_REWIND:
486         case AVRCP_OPERATION_ID_FAST_FORWARD:
487             avrcp_press_and_hold_timer_start(connection);
488             break;
489         default:
490             break;
491     }
492     connection->transaction_label++;
493     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
494 }
495 
496 
497 static int avrcp_send_cmd(uint16_t cid, avrcp_connection_t * connection){
498     uint8_t command[20];
499     int pos = 0;
500     // transport header
501     // Transaction label | Packet_type | C/R | IPID (1 == invalid profile identifier)
502     command[pos++] = (connection->transaction_label << 4) | (AVRCP_SINGLE_PACKET << 2) | (AVRCP_COMMAND_FRAME << 1) | 0;
503     // Profile IDentifier (PID)
504     command[pos++] = AV_REMOTE_CONTROL >> 8;
505     command[pos++] = AV_REMOTE_CONTROL & 0x00FF;
506 
507     // command_type
508     command[pos++] = connection->command_type;
509     // subunit_type | subunit ID
510     command[pos++] = (connection->subunit_type << 3) | connection->subunit_id;
511     // opcode
512     command[pos++] = (uint8_t)connection->cmd_to_send;
513     // operands
514     memcpy(command+pos, connection->cmd_operands, connection->cmd_operands_lenght);
515     pos += connection->cmd_operands_lenght;
516 
517     return l2cap_send(cid, command, pos);
518 }
519 
520 static int avrcp_register_notification(avrcp_connection_t * connection, avrcp_notification_event_id_t event_id){
521     if (connection->notifications_to_deregister & (1 << event_id)) return 0;
522     if (connection->notifications_enabled & (1 << event_id)) return 0;
523     if (connection->notifications_to_register & (1 << event_id)) return 0;
524     connection->notifications_to_register |= (1 << event_id);
525     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
526     return 1;
527 }
528 
529 static void avrcp_prepare_notification(avrcp_connection_t * connection, avrcp_notification_event_id_t event_id){
530     if (connection->state != AVCTP_CONNECTION_OPENED) return;
531     connection->state = AVCTP_W2_SEND_COMMAND;
532 
533     connection->transaction_label++;
534     connection->cmd_to_send = AVRCP_CMD_OPCODE_VENDOR_DEPENDENT;
535     connection->command_type = AVRCP_CTYPE_NOTIFY;
536     connection->subunit_type = AVRCP_SUBUNIT_TYPE_PANEL;
537     connection->subunit_id = 0;
538     int pos = 0;
539     big_endian_store_24(connection->cmd_operands, pos, BT_SIG_COMPANY_ID);
540     pos += 3;
541     connection->cmd_operands[pos++] = AVRCP_PDU_ID_REGISTER_NOTIFICATION;
542     connection->cmd_operands[pos++] = 0;                     // reserved(upper 6) | packet_type -> 0
543     big_endian_store_16(connection->cmd_operands, pos, 5);     // parameter length
544     pos += 2;
545     connection->cmd_operands[pos++] = event_id;
546     big_endian_store_32(connection->cmd_operands, pos, 0);
547     pos += 4;
548     connection->cmd_operands_lenght = pos;
549     // AVRCP_SPEC_V14.pdf 166
550     // answer page 61
551 }
552 
553 static void avrcp_handle_l2cap_data_packet_for_signaling_connection(avrcp_connection_t * connection, uint8_t *packet, uint16_t size){
554     switch (connection->state){
555         case AVCTP_W2_RECEIVE_PRESS_RESPONSE:
556             switch (connection->cmd_operands[0]){
557                 case AVRCP_OPERATION_ID_REWIND:
558                 case AVRCP_OPERATION_ID_FAST_FORWARD:
559                     connection->state = AVCTP_W4_STOP;
560                     break;
561                 default:
562                     connection->state = AVCTP_W2_SEND_RELEASE_COMMAND;
563                     break;
564             }
565             break;
566         case AVCTP_W2_RECEIVE_RESPONSE:
567             connection->state = AVCTP_CONNECTION_OPENED;
568             break;
569         default:
570             // check for notifications? move state transition down
571             break;
572     }
573 
574     avrcp_command_type_t ctype;
575     avrcp_subunit_type_t subunit_type;
576     avrcp_subunit_type_t subunit_id;
577 
578     uint8_t operands[20];
579     uint8_t opcode;
580     int pos = 0;
581     // uint8_t transport_header = packet[0];
582     // uint8_t transaction_label = transport_header >> 4;
583     // uint8_t packet_type = (transport_header & 0x0F) >> 2;
584     // uint8_t frame_type = (transport_header & 0x03) >> 1;
585     // uint8_t ipid = transport_header & 0x01;
586     uint8_t byte_value = packet[2];
587     // uint16_t pid = (byte_value << 8) | packet[2];
588     pos = 3;
589 
590     // printf("    Transport header 0x%02x (transaction_label %d, packet_type %d, frame_type %d, ipid %d), pid 0x%4x\n",
591     //     transport_header, transaction_label, packet_type, frame_type, ipid, pid);
592     // // printf_hexdump(packet+pos, size-pos);
593 
594     switch (connection->cmd_to_send){
595         case AVRCP_CMD_OPCODE_UNIT_INFO:{
596             ctype = packet[pos++];
597             byte_value = packet[pos++];
598             subunit_type = byte_value >> 3;
599             subunit_id = byte_value & 0x07;
600             opcode = packet[pos++];
601 
602             // operands:
603             memcpy(operands, packet+pos, 5);
604             uint8_t unit_type = operands[1] >> 3;
605             uint8_t unit = operands[1] & 0x07;
606             uint32_t company_id = operands[2] << 16 | operands[3] << 8 | operands[4];
607             log_info("    UNIT INFO response: ctype 0x%02x (0C), subunit_type 0x%02x (1F), subunit_id 0x%02x (07), opcode 0x%02x (30), unit_type 0x%02x, unit %d, company_id 0x%06x",
608                 ctype, subunit_type, subunit_id, opcode, unit_type, unit, company_id );
609             break;
610         }
611         case AVRCP_CMD_OPCODE_VENDOR_DEPENDENT:
612             ctype = packet[pos++];
613             byte_value = packet[pos++];
614             subunit_type = byte_value >> 3;
615             subunit_id = byte_value & 0x07;
616             opcode = packet[pos++];
617 
618             if (size - pos < 7) {
619                 log_error("avrcp: wrong packet size");
620                 return;
621             };
622             // operands:
623             memcpy(operands, packet+pos, 7);
624             pos += 7;
625             // uint32_t company_id = operands[0] << 16 | operands[1] << 8 | operands[2];
626             uint8_t pdu_id = operands[3];
627             // uint8_t unit_type = operands[4] >> 3;
628             // uint8_t unit = operands[4] & 0x07;
629             uint16_t param_length = big_endian_read_16(operands, 5);
630 
631             // printf("    VENDOR DEPENDENT response: ctype 0x%02x (0C), subunit_type 0x%02x (1F), subunit_id 0x%02x (07), opcode 0x%02x (30), unit_type 0x%02x, unit %d, company_id 0x%06x\n",
632             //     ctype, subunit_type, subunit_id, opcode, unit_type, unit, company_id );
633 
634             // if (ctype == AVRCP_CTYPE_RESPONSE_INTERIM) return;
635             log_info("        VENDOR DEPENDENT response: pdu id 0x%02x, param_length %d, status %s", pdu_id, param_length, avrcp_ctype2str(ctype));
636             switch (pdu_id){
637                 case AVRCP_PDU_ID_GetCurrentPlayerApplicationSettingValue:{
638                     uint8_t num_attributes = packet[pos++];
639                     int i;
640                     uint8_t repeat_mode = 0;
641                     uint8_t shuffle_mode = 0;
642                     for (i = 0; i < num_attributes; i++){
643                         uint8_t attribute_id    = packet[pos++];
644                         uint8_t attribute_value = packet[pos++];
645                         switch (attribute_id){
646                             case 0x02:
647                                 repeat_mode = attribute_value;
648                                 break;
649                             case 0x03:
650                                 shuffle_mode = attribute_value;
651                                 break;
652                             default:
653                                 break;
654                         }
655                     }
656                     avrcp_emit_repeat_and_shuffle_mode(avrcp_callback, connection->con_handle, ctype, repeat_mode, shuffle_mode);
657                     break;
658                 }
659                 case AVRCP_PDU_ID_SetPlayerApplicationSettingValue:{
660                     uint8_t event[6];
661                     int offset = 0;
662                     event[offset++] = HCI_EVENT_AVRCP_META;
663                     event[offset++] = sizeof(event) - 2;
664                     event[offset++] = AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE;
665                     little_endian_store_16(event, offset, connection->con_handle);
666                     offset += 2;
667                     event[offset++] = ctype;
668                     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
669                     break;
670                 }
671                 case AVRCP_PDU_ID_SET_ABSOLUTE_VOLUME:{
672                     uint8_t event[7];
673                     int offset = 0;
674                     event[offset++] = HCI_EVENT_AVRCP_META;
675                     event[offset++] = sizeof(event) - 2;
676                     event[offset++] = AVRCP_SUBEVENT_SET_ABSOLUTE_VOLUME_RESPONSE;
677                     little_endian_store_16(event, offset, connection->con_handle);
678                     offset += 2;
679                     event[offset++] = ctype;
680                     event[offset++] = packet[pos++];
681                     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
682                     break;
683                 }
684                 case AVRCP_PDU_ID_GET_CAPABILITIES:{
685                     avrcp_capability_id_t capability_id = packet[pos++];
686                     uint8_t capability_count = packet[pos++];
687                     int i;
688                     switch (capability_id){
689                         case AVRCP_CAPABILITY_ID_COMPANY:
690                             // log_info("Supported companies %d: ", capability_count);
691                             for (i = 0; i < capability_count; i++){
692                                 uint32_t company_id = big_endian_read_24(packet, pos);
693                                 pos += 3;
694                                 log_info("  0x%06x, ", company_id);
695                             }
696                             break;
697                         case AVRCP_CAPABILITY_ID_EVENT:
698                             // log_info("Supported events %d: ", capability_count);
699                             for (i = 0; i < capability_count; i++){
700                                 uint8_t event_id = packet[pos++];
701                                 log_info("  0x%02x %s", event_id, avrcp_event2str(event_id));
702                             }
703                             break;
704                     }
705                     break;
706                 }
707                 case AVRCP_PDU_ID_GET_PLAY_STATUS:{
708                     uint32_t song_length = big_endian_read_32(packet, pos);
709                     pos += 4;
710                     uint32_t song_position = big_endian_read_32(packet, pos);
711                     pos += 4;
712                     uint8_t play_status = packet[pos];
713                     // log_info("        GET_PLAY_STATUS length 0x%04X, position 0x%04X, status %s", song_length, song_position, avrcp_play_status2str(play_status));
714 
715                     uint8_t event[15];
716                     int offset = 0;
717                     event[offset++] = HCI_EVENT_AVRCP_META;
718                     event[offset++] = sizeof(event) - 2;
719                     event[offset++] = AVRCP_SUBEVENT_PLAY_STATUS;
720                     little_endian_store_16(event, offset, connection->con_handle);
721                     offset += 2;
722                     event[offset++] = ctype;
723                     little_endian_store_32(event, offset, song_length);
724                     offset += 4;
725                     little_endian_store_32(event, offset, song_position);
726                     offset += 4;
727                     event[offset++] = play_status;
728                     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
729                     break;
730                 }
731                 case AVRCP_PDU_ID_REGISTER_NOTIFICATION:{
732                     uint8_t  event_id = packet[pos++];
733                     uint16_t event_mask = (1 << event_id);
734                     uint16_t reset_event_mask = ~event_mask;
735                     switch (ctype){
736                         case AVRCP_CTYPE_RESPONSE_INTERIM:
737                             // register as enabled
738                             connection->notifications_enabled |= event_mask;
739                             connection->state = AVCTP_CONNECTION_OPENED;
740                             // printf("INTERIM notifications_enabled 0x%2x, notifications_to_register 0x%2x\n", connection->notifications_enabled,  connection->notifications_to_register);
741                             break;
742                         case AVRCP_CTYPE_RESPONSE_CHANGED_STABLE:
743                             // received change, event is considered deregistered
744                             // we are re-enabling it automatically, if it is not
745                             // explicitly disabled
746                             connection->notifications_enabled &= reset_event_mask;
747                             if (! (connection->notifications_to_deregister & event_mask)){
748                                 avrcp_register_notification(connection, event_id);
749                                 // printf("CHANGED_STABLE notifications_enabled 0x%2x, notifications_to_register 0x%2x\n", connection->notifications_enabled,  connection->notifications_to_register);
750                             } else {
751                                 connection->notifications_to_deregister &= reset_event_mask;
752                             }
753                             break;
754                         default:
755                             connection->notifications_to_register &= reset_event_mask;
756                             connection->notifications_enabled &= reset_event_mask;
757                             connection->notifications_to_deregister &= reset_event_mask;
758                             break;
759                     }
760 
761                     switch (event_id){
762                         case AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED:{
763                             uint8_t event[7];
764                             int offset = 0;
765                             event[offset++] = HCI_EVENT_AVRCP_META;
766                             event[offset++] = sizeof(event) - 2;
767                             event[offset++] = AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED;
768                             little_endian_store_16(event, offset, connection->con_handle);
769                             offset += 2;
770                             event[offset++] = ctype;
771                             event[offset++] = packet[pos];
772                             (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
773                             break;
774                         }
775                         case AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED:{
776                             uint8_t event[7];
777                             int offset = 0;
778                             event[offset++] = HCI_EVENT_AVRCP_META;
779                             event[offset++] = sizeof(event) - 2;
780                             event[offset++] = AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED;
781                             little_endian_store_16(event, offset, connection->con_handle);
782                             offset += 2;
783                             event[offset++] = ctype;
784                             event[offset++] = packet[pos];
785                             (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
786                             break;
787                         }
788                         case AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED:{
789                             uint8_t event[6];
790                             int offset = 0;
791                             event[offset++] = HCI_EVENT_AVRCP_META;
792                             event[offset++] = sizeof(event) - 2;
793                             event[offset++] = AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED;
794                             little_endian_store_16(event, offset, connection->con_handle);
795                             offset += 2;
796                             event[offset++] = ctype;
797                             (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
798                             break;
799                         }
800                         case AVRCP_NOTIFICATION_EVENT_AVAILABLE_PLAYERS_CHANGED:{
801                             uint8_t event[6];
802                             int offset = 0;
803                             event[offset++] = HCI_EVENT_AVRCP_META;
804                             event[offset++] = sizeof(event) - 2;
805                             event[offset++] = AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED;
806                             little_endian_store_16(event, offset, connection->con_handle);
807                             offset += 2;
808                             event[offset++] = ctype;
809                             (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
810                             break;
811                         }
812                         case AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED:{
813                             uint8_t event[7];
814                             int offset = 0;
815                             event[offset++] = HCI_EVENT_AVRCP_META;
816                             event[offset++] = sizeof(event) - 2;
817                             event[offset++] = AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED;
818                             little_endian_store_16(event, offset, connection->con_handle);
819                             offset += 2;
820                             event[offset++] = ctype;
821                             event[offset++] = packet[pos++] & 0x7F;
822                             (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
823                             break;
824                         }
825                         // case AVRCP_NOTIFICATION_EVENT_PLAYER_APPLICATION_SETTING_CHANGED:{
826                         //     uint8_t num_PlayerApplicationSettingAttributes = packet[pos++];
827                         //     int i;
828                         //     for (i = 0; i < num_PlayerApplicationSettingAttributes; i++){
829                         //         uint8_t PlayerApplicationSetting_AttributeID = packet[pos++];
830                         //         uint8_t PlayerApplicationSettingValueID = packet[pos++];
831                         //     }
832                         //     break;
833                         // }
834                         // case AVRCP_NOTIFICATION_EVENT_ADDRESSED_PLAYER_CHANGED:
835                         //     uint16_t player_id = big_endian_read_16(packet, pos);
836                         //     pos += 2;
837                         //     uint16_t uid_counter = big_endian_read_16(packet, pos);
838                         //     pos += 2;
839                         //     break;
840                         // case AVRCP_NOTIFICATION_EVENT_UIDS_CHANGED:
841                         //     uint16_t uid_counter = big_endian_read_16(packet, pos);
842                         //     pos += 2;
843                         //     break;
844                         default:
845                             log_info("avrcp: not implemented");
846                             break;
847                     }
848                     if (connection->notifications_to_register != 0){
849                         avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
850                     }
851                     break;
852                 }
853 
854                 case AVRCP_PDU_ID_GET_ELEMENT_ATTRIBUTES:{
855                     uint8_t num_attributes = packet[pos++];
856                     int i;
857                     struct item {
858                         uint16_t len;
859                         uint8_t  * value;
860                     } items[AVRCP_MEDIA_ATTR_COUNT];
861                     memset(items, 0, sizeof(items));
862 
863                     uint16_t string_attributes_len = 0;
864                     uint8_t  num_string_attributes = 0;
865                     uint16_t total_event_payload_for_string_attributes = HCI_EVENT_PAYLOAD_SIZE-2;
866                     uint16_t max_string_attribute_value_len = 0;
867                     for (i = 0; i < num_attributes; i++){
868                         avrcp_media_attribute_id_t attr_id = big_endian_read_32(packet, pos);
869                         pos += 4;
870                         // uint16_t character_set = big_endian_read_16(packet, pos);
871                         pos += 2;
872                         uint16_t attr_value_length = big_endian_read_16(packet, pos);
873                         pos += 2;
874 
875                         // debug - to remove later
876                         uint8_t  value[100];
877                         uint16_t value_len = sizeof(value) <= attr_value_length? sizeof(value) - 1 : attr_value_length;
878                         memcpy(value, packet+pos, value_len);
879                         value[value_len] = 0;
880                         // printf("Now Playing Info %s: %s \n", attribute2str(attr_id), value);
881                         // end debug
882 
883                         if ((attr_id >= 1) || (attr_id <= AVRCP_MEDIA_ATTR_COUNT)) {
884                             items[attr_id-1].len = attr_value_length;
885                             items[attr_id-1].value = &packet[pos];
886                             switch (attr_id){
887                                 case AVRCP_MEDIA_ATTR_TITLE:
888                                 case AVRCP_MEDIA_ATTR_ARTIST:
889                                 case AVRCP_MEDIA_ATTR_ALBUM:
890                                 case AVRCP_MEDIA_ATTR_GENRE:
891                                     num_string_attributes++;
892                                     string_attributes_len += attr_value_length;
893                                     if (max_string_attribute_value_len < attr_value_length){
894                                         max_string_attribute_value_len = attr_value_length;
895                                     }
896                                     break;
897                                 default:
898                                     break;
899                             }
900                         }
901                         pos += attr_value_length;
902                     }
903                     // subtract space for fixed fields
904                     total_event_payload_for_string_attributes -= 14 + 4;    // 4 for '\0'
905 
906                     // @TODO optimize space by repeatedly decreasing max_string_attribute_value_len until it fits into buffer instead of crude divion
907                     uint16_t max_value_len = total_event_payload_for_string_attributes > string_attributes_len? max_string_attribute_value_len : total_event_payload_for_string_attributes/(string_attributes_len+1) - 1;
908                     // printf("num_string_attributes %d, string_attributes_len %d, total_event_payload_for_string_attributes %d, max_value_len %d \n", num_string_attributes, string_attributes_len, total_event_payload_for_string_attributes, max_value_len);
909 
910                     const uint8_t attribute_order[] = {
911                         AVRCP_MEDIA_ATTR_TRACK,
912                         AVRCP_MEDIA_ATTR_TOTAL_TRACKS,
913                         AVRCP_MEDIA_ATTR_SONG_LENGTH,
914                         AVRCP_MEDIA_ATTR_TITLE,
915                         AVRCP_MEDIA_ATTR_ARTIST,
916                         AVRCP_MEDIA_ATTR_ALBUM,
917                         AVRCP_MEDIA_ATTR_GENRE
918                     };
919 
920                     uint8_t event[HCI_EVENT_BUFFER_SIZE];
921                     event[0] = HCI_EVENT_AVRCP_META;
922                     pos = 2;
923                     event[pos++] = AVRCP_SUBEVENT_NOW_PLAYING_INFO;
924                     little_endian_store_16(event, pos, connection->con_handle);
925                     pos += 2;
926                     event[pos++] = ctype;
927                     for (i = 0; i < sizeof(attribute_order); i++){
928                         avrcp_media_attribute_id_t attr_id = attribute_order[i];
929                         uint16_t value_len = 0;
930                         switch (attr_id){
931                             case AVRCP_MEDIA_ATTR_TITLE:
932                             case AVRCP_MEDIA_ATTR_ARTIST:
933                             case AVRCP_MEDIA_ATTR_ALBUM:
934                             case AVRCP_MEDIA_ATTR_GENRE:
935                                 if (items[attr_id-1].value){
936                                     value_len = items[attr_id-1].len <= max_value_len ? items[attr_id-1].len : max_value_len;
937                                 }
938                                 event[pos++] = value_len + 1;
939                                 if (value_len){
940                                     memcpy(event+pos, items[attr_id-1].value, value_len);
941                                     pos += value_len;
942                                 }
943                                 event[pos++] = 0;
944                                 break;
945                             case AVRCP_MEDIA_ATTR_SONG_LENGTH:
946                                 if (items[attr_id-1].value){
947                                     little_endian_store_32(event, pos, btstack_atoi((char *)items[attr_id-1].value));
948                                 } else {
949                                     little_endian_store_32(event, pos, 0);
950                                 }
951                                 pos += 4;
952                                 break;
953                             case AVRCP_MEDIA_ATTR_TRACK:
954                             case AVRCP_MEDIA_ATTR_TOTAL_TRACKS:
955                                 if (items[attr_id-1].value){
956                                     event[pos++] = btstack_atoi((char *)items[attr_id-1].value);
957                                 } else {
958                                     event[pos++] = 0;
959                                 }
960                                 break;
961                         }
962                     }
963                     event[1] = pos - 2;
964                     // printf_hexdump(event, pos);
965                     (*avrcp_callback)(HCI_EVENT_PACKET, 0, event, pos);
966                     break;
967                 }
968                 default:
969                     break;
970             }
971             break;
972         case AVRCP_CMD_OPCODE_PASS_THROUGH:{
973             // 0x80 | connection->cmd_operands[0]
974             ctype = packet[pos++];
975             byte_value = packet[pos++];
976             subunit_type = byte_value >> 3;
977             subunit_id = byte_value & 0x07;
978             opcode = packet[pos++];
979             uint8_t operation_id = packet[pos++];
980 
981             if (connection->state == AVCTP_W4_STOP){
982                 avrcp_emit_operation_status(avrcp_callback, AVRCP_SUBEVENT_OPERATION_START, connection->con_handle, ctype, operation_id);
983             }
984             if (connection->state == AVCTP_CONNECTION_OPENED) {
985                 // RELEASE response
986                 operation_id = operation_id & 0x7F;
987                 avrcp_emit_operation_status(avrcp_callback, AVRCP_SUBEVENT_OPERATION_COMPLETE, connection->con_handle, ctype, operation_id);
988             }
989             if (connection->state == AVCTP_W2_SEND_RELEASE_COMMAND){
990                 // PRESS response
991                 request_pass_through_release_control_cmd(connection);
992             }
993             break;
994         }
995         default:
996             break;
997     }
998 }
999 
1000 static void avrcp_handle_can_send_now(avrcp_connection_t * connection){
1001     int i;
1002     switch (connection->state){
1003         case AVCTP_W2_SEND_PRESS_COMMAND:
1004             connection->state = AVCTP_W2_RECEIVE_PRESS_RESPONSE;
1005             break;
1006         case AVCTP_W2_SEND_COMMAND:
1007         case AVCTP_W2_SEND_RELEASE_COMMAND:
1008             connection->state = AVCTP_W2_RECEIVE_RESPONSE;
1009             break;
1010         case AVCTP_CONNECTION_OPENED:
1011             if (connection->disconnect){
1012                 connection->wait_to_send = 0;
1013                 connection->disconnect = 0;
1014                 connection->state = AVCTP_CONNECTION_W4_L2CAP_DISCONNECTED;
1015                 l2cap_disconnect(connection->l2cap_signaling_cid, 0);
1016                 return;
1017             }
1018             if (connection->notifications_to_register != 0){
1019                 for (i = 1; i < 13; i++){
1020                     if (connection->notifications_to_register & (1<<i)){
1021                          // clear registration bit before sending command
1022                         connection->notifications_to_register &= ~ (1 <<i);
1023                         avrcp_prepare_notification(connection, i);
1024                         avrcp_send_cmd(connection->l2cap_signaling_cid, connection);
1025                         return;
1026                     }
1027                 }
1028             }
1029             return;
1030         default:
1031             return;
1032     }
1033     avrcp_send_cmd(connection->l2cap_signaling_cid, connection);
1034 }
1035 
1036 static avrcp_connection_t * avrcp_create_connection(bd_addr_t remote_addr){
1037     avrcp_connection_t * connection = btstack_memory_avrcp_connection_get();
1038     memset(connection, 0, sizeof(avrcp_connection_t));
1039     connection->state = AVCTP_CONNECTION_IDLE;
1040     connection->transaction_label = 0xFF;
1041     memcpy(connection->remote_addr, remote_addr, 6);
1042     btstack_linked_list_add(&avrcp_connections, (btstack_linked_item_t *) connection);
1043     return connection;
1044 }
1045 
1046 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1047     bd_addr_t event_addr;
1048     hci_con_handle_t con_handle;
1049     uint16_t psm;
1050     uint16_t local_cid;
1051     avrcp_connection_t * connection = NULL;
1052 
1053     switch (packet_type) {
1054         case L2CAP_DATA_PACKET:
1055             connection = get_avrcp_connection_for_l2cap_signaling_cid(channel);
1056             if (!connection) break;
1057             avrcp_handle_l2cap_data_packet_for_signaling_connection(connection, packet, size);
1058             break;
1059 
1060         case HCI_EVENT_PACKET:
1061             switch (hci_event_packet_get_type(packet)) {
1062                 case L2CAP_EVENT_INCOMING_CONNECTION:
1063                     l2cap_event_incoming_connection_get_address(packet, event_addr);
1064                     local_cid = l2cap_event_incoming_connection_get_local_cid(packet);
1065 
1066                     connection = get_avrcp_connection_for_bd_addr(event_addr);
1067                     if (!connection){
1068                         connection = avrcp_create_connection(event_addr);
1069                         connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
1070                         l2cap_accept_connection(local_cid);
1071                         break;
1072                     }
1073                     break;
1074 
1075                 case L2CAP_EVENT_CHANNEL_OPENED:
1076                     l2cap_event_channel_opened_get_address(packet, event_addr);
1077 
1078                     if (l2cap_event_channel_opened_get_status(packet)){
1079                         log_error("L2CAP connection to connection %s failed. status code 0x%02x",
1080                             bd_addr_to_str(event_addr), l2cap_event_channel_opened_get_status(packet));
1081                         break;
1082                     }
1083                     psm = l2cap_event_channel_opened_get_psm(packet);
1084                     if (psm != BLUETOOTH_PROTOCOL_AVCTP){
1085                         log_error("unexpected PSM - Not implemented yet: L2CAP_EVENT_CHANNEL_OPENED");
1086                         return;
1087                     }
1088 
1089                     connection = get_avrcp_connection_for_bd_addr(event_addr);
1090                     if (!connection) break;
1091 
1092                     con_handle = l2cap_event_channel_opened_get_handle(packet);
1093                     local_cid  = l2cap_event_channel_opened_get_local_cid(packet);
1094                     // printf("L2CAP_EVENT_CHANNEL_OPENED: Channel successfully opened: %s, handle 0x%02x, psm 0x%02x, local cid 0x%02x, remote cid 0x%02x\n",
1095                     //        bd_addr_to_str(event_addr), con_handle, psm, local_cid,  l2cap_event_channel_opened_get_remote_cid(packet));
1096                     if (connection->l2cap_signaling_cid == 0) {
1097                         connection->l2cap_signaling_cid = local_cid;
1098                         connection->con_handle = con_handle;
1099                         connection->state = AVCTP_CONNECTION_OPENED;
1100                         avrcp_emit_connection_established(avrcp_callback, con_handle, 0, local_cid, event_addr);
1101                         break;
1102                     }
1103                     break;
1104 
1105                 case L2CAP_EVENT_CAN_SEND_NOW:
1106                     connection = get_avrcp_connection_for_l2cap_signaling_cid(channel);
1107                     if (!connection) break;
1108                     avrcp_handle_can_send_now(connection);
1109                     break;
1110 
1111                 case L2CAP_EVENT_CHANNEL_CLOSED:
1112                     // data: event (8), len(8), channel (16)
1113                     local_cid = l2cap_event_channel_closed_get_local_cid(packet);
1114                     connection = get_avrcp_connection_for_l2cap_signaling_cid(local_cid);
1115                     if (connection){
1116                         avrcp_emit_connection_closed(avrcp_callback, connection->con_handle);
1117                         btstack_linked_list_remove(&avrcp_connections, (btstack_linked_item_t*) connection);
1118                         break;
1119                     }
1120                     break;
1121                 default:
1122                     break;
1123             }
1124             break;
1125         default:
1126             break;
1127     }
1128 }
1129 
1130 void avrcp_init(void){
1131     avrcp_connections = NULL;
1132     l2cap_register_service(&packet_handler, BLUETOOTH_PROTOCOL_AVCTP, 0xffff, LEVEL_0);
1133 }
1134 
1135 void avrcp_register_packet_handler(btstack_packet_handler_t callback){
1136     if (callback == NULL){
1137         log_error("avrcp_register_packet_handler called with NULL callback");
1138         return;
1139     }
1140     avrcp_callback = callback;
1141 }
1142 
1143 void avrcp_connect(bd_addr_t bd_addr){
1144     avrcp_connection_t * connection = get_avrcp_connection_for_bd_addr(bd_addr);
1145     if (!connection){
1146         connection = avrcp_create_connection(bd_addr);
1147     }
1148     if (!connection){
1149         log_error("avrcp: could not find or create a connection.");
1150         return;
1151     }
1152     if (connection->state != AVCTP_CONNECTION_IDLE) return;
1153     connection->state = AVCTP_CONNECTION_W4_L2CAP_CONNECTED;
1154     l2cap_create_channel(packet_handler, connection->remote_addr, BLUETOOTH_PROTOCOL_AVCTP, 0xffff, NULL);
1155 }
1156 
1157 void avrcp_unit_info(uint16_t con_handle){
1158     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1159     if (!connection){
1160         log_error("avrcp_unit_info: could not find a connection.");
1161         return;
1162     }
1163     if (connection->state != AVCTP_CONNECTION_OPENED) return;
1164     connection->state = AVCTP_W2_SEND_COMMAND;
1165 
1166     connection->transaction_label++;
1167     connection->cmd_to_send = AVRCP_CMD_OPCODE_UNIT_INFO;
1168     connection->command_type = AVRCP_CTYPE_STATUS;
1169     connection->subunit_type = AVRCP_SUBUNIT_TYPE_UNIT; //vendor unique
1170     connection->subunit_id =   AVRCP_SUBUNIT_ID_IGNORE;
1171     memset(connection->cmd_operands, 0xFF, connection->cmd_operands_lenght);
1172     connection->cmd_operands_lenght = 5;
1173     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
1174 }
1175 
1176 static void avrcp_get_capabilities(uint16_t con_handle, uint8_t capability_id){
1177     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1178     if (!connection){
1179         log_error("avrcp_get_capabilities: could not find a connection.");
1180         return;
1181     }
1182     if (connection->state != AVCTP_CONNECTION_OPENED) return;
1183     connection->state = AVCTP_W2_SEND_COMMAND;
1184 
1185     connection->transaction_label++;
1186     connection->cmd_to_send = AVRCP_CMD_OPCODE_VENDOR_DEPENDENT;
1187     connection->command_type = AVRCP_CTYPE_STATUS;
1188     connection->subunit_type = AVRCP_SUBUNIT_TYPE_PANEL;
1189     connection->subunit_id = 0;
1190     big_endian_store_24(connection->cmd_operands, 0, BT_SIG_COMPANY_ID);
1191     connection->cmd_operands[3] = AVRCP_PDU_ID_GET_CAPABILITIES; // PDU ID
1192     connection->cmd_operands[4] = 0;
1193     big_endian_store_16(connection->cmd_operands, 5, 1); // parameter length
1194     connection->cmd_operands[7] = capability_id;                  // capability ID
1195     connection->cmd_operands_lenght = 8;
1196     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
1197 }
1198 
1199 void avrcp_get_supported_company_ids(uint16_t con_handle){
1200     avrcp_get_capabilities(con_handle, AVRCP_CAPABILITY_ID_COMPANY);
1201 }
1202 
1203 void avrcp_get_supported_events(uint16_t con_handle){
1204     avrcp_get_capabilities(con_handle, AVRCP_CAPABILITY_ID_EVENT);
1205 }
1206 
1207 
1208 void avrcp_play(uint16_t con_handle){
1209     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_PLAY, 0);
1210 }
1211 
1212 void avrcp_stop(uint16_t con_handle){
1213     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_STOP, 0);
1214 }
1215 
1216 void avrcp_pause(uint16_t con_handle){
1217     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_PAUSE, 0);
1218 }
1219 
1220 void avrcp_forward(uint16_t con_handle){
1221     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_FORWARD, 0);
1222 }
1223 
1224 void avrcp_backward(uint16_t con_handle){
1225     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_BACKWARD, 0);
1226 }
1227 
1228 void avrcp_start_rewind(uint16_t con_handle){
1229     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_REWIND, 0);
1230 }
1231 
1232 void avrcp_volume_up(uint16_t con_handle){
1233     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_VOLUME_UP, 0);
1234 }
1235 
1236 void avrcp_volume_down(uint16_t con_handle){
1237     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_VOLUME_DOWN, 0);
1238 }
1239 
1240 void avrcp_mute(uint16_t con_handle){
1241     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_MUTE, 0);
1242 }
1243 
1244 void avrcp_skip(uint16_t con_handle){
1245     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_SKIP, 0);
1246 }
1247 
1248 void avrcp_stop_rewind(uint16_t con_handle){
1249     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1250     if (!connection){
1251         log_error("avrcp_stop_rewind: could not find a connection.");
1252         return;
1253     }
1254     if (connection->state != AVCTP_W4_STOP) return;
1255     request_pass_through_release_control_cmd(connection);
1256 }
1257 
1258 void avrcp_start_fast_forward(uint16_t con_handle){
1259     request_pass_through_press_control_cmd(con_handle, AVRCP_OPERATION_ID_FAST_FORWARD, 0);
1260 }
1261 
1262 void avrcp_stop_fast_forward(uint16_t con_handle){
1263     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1264     if (!connection){
1265         log_error("avrcp_stop_fast_forward: could not find a connection.");
1266         return;
1267     }
1268     if (connection->state != AVCTP_W4_STOP) return;
1269     request_pass_through_release_control_cmd(connection);
1270 }
1271 
1272 void avrcp_get_play_status(uint16_t con_handle){
1273     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1274     if (!connection){
1275         log_error("avrcp_get_play_status: could not find a connection.");
1276         return;
1277     }
1278     if (connection->state != AVCTP_CONNECTION_OPENED) return;
1279     connection->state = AVCTP_W2_SEND_COMMAND;
1280 
1281     connection->transaction_label++;
1282     connection->cmd_to_send = AVRCP_CMD_OPCODE_VENDOR_DEPENDENT;
1283     connection->command_type = AVRCP_CTYPE_STATUS;
1284     connection->subunit_type = AVRCP_SUBUNIT_TYPE_PANEL;
1285     connection->subunit_id = 0;
1286     big_endian_store_24(connection->cmd_operands, 0, BT_SIG_COMPANY_ID);
1287     connection->cmd_operands[3] = AVRCP_PDU_ID_GET_PLAY_STATUS;
1288     connection->cmd_operands[4] = 0;                     // reserved(upper 6) | packet_type -> 0
1289     big_endian_store_16(connection->cmd_operands, 5, 0); // parameter length
1290     connection->cmd_operands_lenght = 7;
1291     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
1292 }
1293 
1294 void avrcp_enable_notification(uint16_t con_handle, avrcp_notification_event_id_t event_id){
1295     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1296     if (!connection){
1297         log_error("avrcp_get_play_status: could not find a connection.");
1298         return;
1299     }
1300     avrcp_register_notification(connection, event_id);
1301 }
1302 
1303 void avrcp_disable_notification(uint16_t con_handle, avrcp_notification_event_id_t event_id){
1304     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1305     if (!connection){
1306         log_error("avrcp_get_play_status: could not find a connection.");
1307         return;
1308     }
1309     connection->notifications_to_deregister |= (1 << event_id);
1310 }
1311 
1312 void avrcp_get_now_playing_info(uint16_t con_handle){
1313     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1314     if (!connection){
1315         log_error("avrcp_get_capabilities: could not find a connection.");
1316         return;
1317     }
1318     if (connection->state != AVCTP_CONNECTION_OPENED) return;
1319     connection->state = AVCTP_W2_SEND_COMMAND;
1320 
1321     connection->transaction_label++;
1322     connection->cmd_to_send = AVRCP_CMD_OPCODE_VENDOR_DEPENDENT;
1323     connection->command_type = AVRCP_CTYPE_STATUS;
1324     connection->subunit_type = AVRCP_SUBUNIT_TYPE_PANEL;
1325     connection->subunit_id = 0;
1326     int pos = 0;
1327     big_endian_store_24(connection->cmd_operands, pos, BT_SIG_COMPANY_ID);
1328     pos += 3;
1329     connection->cmd_operands[pos++] = AVRCP_PDU_ID_GET_ELEMENT_ATTRIBUTES; // PDU ID
1330     connection->cmd_operands[pos++] = 0;
1331 
1332     // Parameter Length
1333     big_endian_store_16(connection->cmd_operands, pos, 9);
1334     pos += 2;
1335 
1336     // write 8 bytes value
1337     memset(connection->cmd_operands + pos, 0, 8); // identifier: PLAYING
1338     pos += 8;
1339 
1340     connection->cmd_operands[pos++] = 0; // attribute count, if 0 get all attributes
1341     // every attribute is 4 bytes long
1342 
1343     connection->cmd_operands_lenght = pos;
1344     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
1345 
1346 }
1347 
1348 void avrcp_set_absolute_volume(uint16_t con_handle, uint8_t volume){
1349      avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1350     if (!connection){
1351         log_error("avrcp_get_capabilities: could not find a connection.");
1352         return;
1353     }
1354     if (connection->state != AVCTP_CONNECTION_OPENED) return;
1355     connection->state = AVCTP_W2_SEND_COMMAND;
1356 
1357     connection->transaction_label++;
1358     connection->cmd_to_send = AVRCP_CMD_OPCODE_VENDOR_DEPENDENT;
1359     connection->command_type = AVRCP_CTYPE_CONTROL;
1360     connection->subunit_type = AVRCP_SUBUNIT_TYPE_PANEL;
1361     connection->subunit_id = 0;
1362     int pos = 0;
1363     big_endian_store_24(connection->cmd_operands, pos, BT_SIG_COMPANY_ID);
1364     pos += 3;
1365     connection->cmd_operands[pos++] = AVRCP_PDU_ID_SET_ABSOLUTE_VOLUME; // PDU ID
1366     connection->cmd_operands[pos++] = 0;
1367 
1368     // Parameter Length
1369     big_endian_store_16(connection->cmd_operands, pos, 1);
1370     pos += 2;
1371     connection->cmd_operands[pos++] = volume;
1372 
1373     connection->cmd_operands_lenght = pos;
1374     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
1375 }
1376 
1377 void avrcp_query_shuffle_and_repeat_modes(uint16_t con_handle){
1378     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1379     if (!connection){
1380         log_error("avrcp_get_capabilities: could not find a connection.");
1381         return;
1382     }
1383     if (connection->state != AVCTP_CONNECTION_OPENED) return;
1384     connection->state = AVCTP_W2_SEND_COMMAND;
1385 
1386     connection->transaction_label++;
1387     connection->cmd_to_send = AVRCP_CMD_OPCODE_VENDOR_DEPENDENT;
1388     connection->command_type = AVRCP_CTYPE_STATUS;
1389     connection->subunit_type = AVRCP_SUBUNIT_TYPE_PANEL;
1390     connection->subunit_id = 0;
1391     big_endian_store_24(connection->cmd_operands, 0, BT_SIG_COMPANY_ID);
1392     connection->cmd_operands[3] = AVRCP_PDU_ID_GetCurrentPlayerApplicationSettingValue; // PDU ID
1393     connection->cmd_operands[4] = 0;
1394     big_endian_store_16(connection->cmd_operands, 5, 5); // parameter length
1395     connection->cmd_operands[7] = 4;                     // NumPlayerApplicationSettingAttributeID
1396     // PlayerApplicationSettingAttributeID1 AVRCP Spec, Appendix F, 133
1397     connection->cmd_operands[8]  = 0x01;    // equalizer  (1-OFF, 2-ON)
1398     connection->cmd_operands[9]  = 0x02;    // repeat     (1-off, 2-single track, 3-all tracks, 4-group repeat)
1399     connection->cmd_operands[10] = 0x03;    // shuffle    (1-off, 2-all tracks, 3-group shuffle)
1400     connection->cmd_operands[11] = 0x04;    // scan       (1-off, 2-all tracks, 3-group scan)
1401     connection->cmd_operands_lenght = 12;
1402     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
1403 }
1404 
1405 
1406 static void avrcp_set_current_player_application_setting_value(uint16_t con_handle, uint8_t attribute_id, uint8_t attribute_value){
1407     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1408     if (!connection){
1409         log_error("avrcp_get_capabilities: could not find a connection.");
1410         return;
1411     }
1412     if (connection->state != AVCTP_CONNECTION_OPENED) return;
1413     connection->state = AVCTP_W2_SEND_COMMAND;
1414 
1415     connection->transaction_label++;
1416     connection->cmd_to_send = AVRCP_CMD_OPCODE_VENDOR_DEPENDENT;
1417     connection->command_type = AVRCP_CTYPE_CONTROL;
1418     connection->subunit_type = AVRCP_SUBUNIT_TYPE_PANEL;
1419     connection->subunit_id = 0;
1420     int pos = 0;
1421     big_endian_store_24(connection->cmd_operands, pos, BT_SIG_COMPANY_ID);
1422     pos += 3;
1423     connection->cmd_operands[pos++] = AVRCP_PDU_ID_SetPlayerApplicationSettingValue; // PDU ID
1424     connection->cmd_operands[pos++] = 0;
1425     // Parameter Length
1426     big_endian_store_16(connection->cmd_operands, pos, 3);
1427     pos += 2;
1428     connection->cmd_operands[pos++] = 2;
1429     connection->cmd_operands_lenght = pos;
1430     connection->cmd_operands[pos++]  = attribute_id;
1431     connection->cmd_operands[pos++]  = attribute_value;
1432     connection->cmd_operands_lenght = pos;
1433     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
1434 }
1435 
1436 void avrcp_set_shuffle_mode(uint16_t con_handle, avrcp_shuffle_mode_t mode){
1437     if (mode < AVRCP_SHUFFLE_MODE_OFF || mode > AVRCP_SHUFFLE_MODE_GROUP) return;
1438     avrcp_set_current_player_application_setting_value(con_handle, 0x03, mode);
1439 }
1440 
1441 void avrcp_set_repeat_mode(uint16_t con_handle, avrcp_repeat_mode_t mode){
1442     if (mode < AVRCP_REPEAT_MODE_OFF || mode > AVRCP_REPEAT_MODE_GROUP) return;
1443     avrcp_set_current_player_application_setting_value(con_handle, 0x02, mode);
1444 }
1445 
1446 void avrcp_disconnect(uint16_t con_handle){
1447     avrcp_connection_t * connection = get_avrcp_connection_for_con_handle(con_handle);
1448     if (!connection){
1449         log_error("avrcp_get_capabilities: could not find a connection.");
1450         return;
1451     }
1452     if (connection->state != AVCTP_CONNECTION_OPENED) return;
1453     if (connection->state == AVCTP_CONNECTION_W4_L2CAP_DISCONNECTED) return;
1454 
1455     connection->disconnect = 1;
1456     avrcp_request_can_send_now(connection, connection->l2cap_signaling_cid);
1457 }