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