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