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