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