xref: /btstack/example/a2dp_sink_demo.c (revision 502593062dab8967d3767a7d40e5cfc0183cb224)
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__ "a2dp_sink_demo.c"
39 
40 /*
41  * a2dp_sink_demo.c
42  */
43 
44 // *****************************************************************************
45 /* EXAMPLE_START(a2dp_sink_demo): Receive audio stream and control its playback.
46  *
47  * @text This A2DP Sink example demonstrates how to use the A2DP Sink service to
48  * receive an audio data stream from a remote A2DP Source device. In addition,
49  * the AVRCP Controller is used to get information on currently played media,
50  * such are title, artist and album, as well as to control the playback,
51  * i.e. to play, stop, repeat, etc.
52  *
53  * @test To test with a remote device, e.g. a mobile phone,
54  * pair from the remote device with the demo, then start playing music on the remote device.
55  * Alternatively, set the device_addr_string to the Bluetooth address of your
56  * remote device in the code, and call connect from the UI.
57  *
58  * @test To controll the playback, tap SPACE on the console to show the available
59  * AVRCP commands.
60  */
61 // *****************************************************************************
62 
63 #include <inttypes.h>
64 #include <stdint.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 
69 #include "btstack.h"
70 #include "btstack_resample.h"
71 
72 //#define AVRCP_BROWSING_ENABLED
73 
74 #ifdef HAVE_BTSTACK_STDIN
75 #include "btstack_stdin.h"
76 #endif
77 
78 #include "btstack_ring_buffer.h"
79 
80 #ifdef HAVE_POSIX_FILE_IO
81 #include "wav_util.h"
82 #define STORE_SBC_TO_SBC_FILE
83 #define STORE_SBC_TO_WAV_FILE
84 #endif
85 
86 #define NUM_CHANNELS 2
87 #define BYTES_PER_FRAME     (2*NUM_CHANNELS)
88 #define MAX_SBC_FRAME_SIZE 120
89 
90 // SBC Decoder for WAV file or live playback
91 static btstack_sbc_decoder_state_t state;
92 static btstack_sbc_mode_t mode = SBC_MODE_STANDARD;
93 
94 // ring buffer for SBC Frames
95 // below 30: add samples, 30-40: fine, above 40: drop samples
96 #define OPTIMAL_FRAMES_MIN 30
97 #define OPTIMAL_FRAMES_MAX 40
98 #define ADDITIONAL_FRAMES  20
99 static uint8_t sbc_frame_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE];
100 static btstack_ring_buffer_t sbc_frame_ring_buffer;
101 static unsigned int sbc_frame_size;
102 
103 // rest buffer for not fully used sbc frames, with additional frames for resampling
104 static uint8_t decoded_audio_storage[(128+16) * BYTES_PER_FRAME];
105 static btstack_ring_buffer_t decoded_audio_ring_buffer;
106 
107 //
108 static int audio_stream_started;
109 
110 // temp storage of lower-layer request
111 static int16_t * request_buffer;
112 static int       request_frames;
113 
114 #define STORE_FROM_PLAYBACK
115 
116 // WAV File
117 #ifdef STORE_SBC_TO_WAV_FILE
118 static int frame_count = 0;
119 static char * wav_filename = "avdtp_sink.wav";
120 #endif
121 
122 #ifdef STORE_SBC_TO_SBC_FILE
123 static FILE * sbc_file;
124 static char * sbc_filename = "avdtp_sink.sbc";
125 #endif
126 
127 typedef struct {
128     // bitmaps
129     uint8_t sampling_frequency_bitmap;
130     uint8_t channel_mode_bitmap;
131     uint8_t block_length_bitmap;
132     uint8_t subbands_bitmap;
133     uint8_t allocation_method_bitmap;
134     uint8_t min_bitpool_value;
135     uint8_t max_bitpool_value;
136 } adtvp_media_codec_information_sbc_t;
137 
138 typedef struct {
139     int reconfigure;
140     int num_channels;
141     int sampling_frequency;
142     int channel_mode;
143     int block_length;
144     int subbands;
145     int allocation_method;
146     int min_bitpool_value;
147     int max_bitpool_value;
148     int frames_per_buffer;
149 } avdtp_media_codec_configuration_sbc_t;
150 
151 static uint8_t events_num = 1;
152 
153 static uint8_t events[] = {
154     AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED
155 };
156 
157 static uint8_t companies_num = 1;
158 static uint8_t companies[] = {
159     0x00, 0x19, 0x58 //BT SIG registered CompanyID
160 };
161 #ifdef HAVE_BTSTACK_STDIN
162 // pts: static bd_addr_t remote = {0x00, 0x1B, 0xDC, 0x08, 0x0A, 0xA5};
163 // mac 2013: static const char * device_addr_string = "84:38:35:65:d1:15";
164 // iPhone 5S:
165 static const char * device_addr_string = "54:E4:3A:26:A2:39";
166 #endif
167 
168 static uint8_t  sdp_avdtp_sink_service_buffer[150];
169 static uint8_t  sdp_avrcp_target_service_buffer[150];
170 static avdtp_media_codec_configuration_sbc_t sbc_configuration;
171 static uint16_t a2dp_cid = 0;
172 static uint8_t  local_seid = 0;
173 static uint8_t  value[100];
174 
175 static btstack_packet_callback_registration_t hci_event_callback_registration;
176 
177 static int media_initialized = 0;
178 
179 #ifdef HAVE_BTSTACK_STDIN
180 static bd_addr_t device_addr;
181 #endif
182 
183 static uint16_t a2dp_sink_connected = 0;
184 static uint16_t avrcp_controller_cid = 0;
185 static uint16_t avrcp_target_cid = 0;
186 static uint8_t  avrcp_connected = 0;
187 static uint8_t  sdp_avrcp_controller_service_buffer[200];
188 
189 static uint8_t media_sbc_codec_capabilities[] = {
190     0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
191     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
192     2, 53
193 };
194 
195 static uint8_t media_sbc_codec_configuration[] = {
196     (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
197     (AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
198     2, 53
199 };
200 
201 static btstack_resample_t resample_instance;
202 
203 /* @section Main Application Setup
204  *
205  * @text The Listing MainConfiguration shows how to setup AD2P Sink and AVRCP controller services.
206  * To announce A2DP Sink and AVRCP Controller services, you need to create corresponding
207  * SDP records and register them with the SDP service.
208  * You'll also need to register several packet handlers:
209  * - a2dp_sink_packet_handler - handles events on stream connection status (established, released), the media codec configuration, and, the status of the stream itself (opened, paused, stopped).
210  * - handle_l2cap_media_data_packet - used to receive streaming data. If HAVE_PORTAUDIO or STORE_SBC_TO_WAV_FILE directives (check btstack_config.h) are used, the SBC decoder will be used to decode the SBC data into PCM frames. The resulting PCM frames are then processed in the SBC Decoder callback.
211  * - stdin_process callback - used to trigger AVRCP commands to the A2DP Source device, such are get now playing info, start, stop, volume control. Requires HAVE_BTSTACK_STDIN.
212  * - avrcp_controller_packet_handler - used to receive answers for AVRCP commands,
213  *
214  * @text Note, currently only the SBC codec is supported.
215  * If you want to store the audio data in a file, you'll need to define STORE_SBC_TO_WAV_FILE. The HAVE_PORTAUDIO directive indicates if the audio is played back via PortAudio.
216  * If HAVE_PORTAUDIO or STORE_SBC_TO_WAV_FILE directives is defined, the SBC decoder needs to get initialized when a2dp_sink_packet_handler receives event A2DP_SUBEVENT_STREAM_STARTED.
217  * The initialization of the SBC decoder requires a callback that handles PCM data:
218  * - handle_pcm_data - handles PCM audio frames. Here, they are stored a in wav file if STORE_SBC_TO_WAV_FILE is defined, and/or played using the PortAudio library if HAVE_PORTAUDIO is defined.
219  */
220 
221 /* LISTING_START(MainConfiguration): Setup Audio Sink and AVRCP Controller services */
222 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * event, uint16_t event_size);
223 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
224 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
225 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
226 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size);
227 
228 static int a2dp_and_avrcp_setup(void){
229 
230     l2cap_init();
231     // Initialize AVDTP Sink
232     a2dp_sink_init();
233     a2dp_sink_register_packet_handler(&a2dp_sink_packet_handler);
234     a2dp_sink_register_media_handler(&handle_l2cap_media_data_packet);
235 
236     uint8_t status = a2dp_sink_create_stream_endpoint(AVDTP_AUDIO, AVDTP_CODEC_SBC, media_sbc_codec_capabilities, sizeof(media_sbc_codec_capabilities), media_sbc_codec_configuration, sizeof(media_sbc_codec_configuration), &local_seid);
237     if (status != ERROR_CODE_SUCCESS){
238         printf("A2DP Sink: not enough memory to create local stream endpoint\n");
239         return 1;
240     }
241     // Initialize AVRCP Controller
242     avrcp_controller_init();
243     avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler);
244 
245      // Initialize AVRCP Target
246     avrcp_target_init();
247     avrcp_target_register_packet_handler(&avrcp_target_packet_handler);
248 
249     // Initialize SDP
250     sdp_init();
251     // setup AVDTP sink
252     memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer));
253     a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, 0x10001, 1, NULL, NULL);
254     sdp_register_service(sdp_avdtp_sink_service_buffer);
255 
256     // setup AVRCP Controller
257     memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
258     uint16_t controller_supported_features = (1 << AVRCP_TARGET_SUPPORTED_FEATURE_CATEGORY_MONITOR_OR_AMPLIFIER);
259 #ifdef AVRCP_BROWSING_ENABLED
260     controller_supported_features |= (1 << AVRCP_CONTROLLER_SUPPORTED_FEATURE_BROWSING);
261 #endif
262     avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10002, controller_supported_features, NULL, NULL);
263     sdp_register_service(sdp_avrcp_controller_service_buffer);
264 
265     // setup AVRCP Target
266     memset(sdp_avrcp_target_service_buffer, 0, sizeof(sdp_avrcp_target_service_buffer));
267     uint16_t target_supported_features = (1 << AVRCP_TARGET_SUPPORTED_FEATURE_CATEGORY_MONITOR_OR_AMPLIFIER);
268     avrcp_target_create_sdp_record(sdp_avrcp_target_service_buffer, 0x10003, target_supported_features, NULL, NULL);
269     sdp_register_service(sdp_avrcp_target_service_buffer);
270 
271     gap_set_local_name("A2DP Sink Demo 00:00:00:00:00:00");
272     gap_discoverable_control(1);
273     gap_set_class_of_device(0x200408);
274 
275     /* Register for HCI events */
276     hci_event_callback_registration.callback = &hci_packet_handler;
277     hci_add_event_handler(&hci_event_callback_registration);
278 
279     return 0;
280 }
281 
282 static void playback_handler(int16_t * buffer, uint16_t num_frames){
283 
284 #ifdef STORE_FROM_PLAYBACK
285 #ifdef STORE_SBC_TO_WAV_FILE
286     int       wav_samples = num_frames * NUM_CHANNELS;
287     int16_t * wav_buffer  = buffer;
288 #endif
289 #endif
290 
291     // called from lower-layer but guaranteed to be on main thread
292 
293     // first fill from resampled audio
294     uint32_t bytes_read;
295     btstack_ring_buffer_read(&decoded_audio_ring_buffer, (uint8_t *) buffer, num_frames * BYTES_PER_FRAME, &bytes_read);
296     buffer          += bytes_read / NUM_CHANNELS;
297     num_frames   -= bytes_read / BYTES_PER_FRAME;
298 
299     // then start decoding sbc frames using request_* globals
300     request_buffer = buffer;
301     request_frames = num_frames;
302     while (request_frames){
303         if (btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) >= sbc_frame_size){
304         // decode frame
305             uint8_t sbc_frame[MAX_SBC_FRAME_SIZE];
306             btstack_ring_buffer_read(&sbc_frame_ring_buffer, sbc_frame, sbc_frame_size, &bytes_read);
307             btstack_sbc_decoder_process_data(&state, 0, sbc_frame, sbc_frame_size);
308         } else {
309             printf("Error: no SBC frame ready in ring buffer\n");
310         }
311     }
312 
313 #ifdef STORE_FROM_PLAYBACK
314 #ifdef STORE_SBC_TO_WAV_FILE
315     wav_writer_write_int16(wav_samples, wav_buffer);
316 #endif
317 #endif
318 }
319 
320 static void handle_pcm_data(int16_t * data, int num_frames, int num_channels, int sample_rate, void * context){
321     UNUSED(sample_rate);
322     UNUSED(context);
323     UNUSED(num_channels);   // must be stereo == 2
324 
325 #ifdef STORE_DECODED
326     wav_writer_write_int16(num_frames * NUM_CHANNELS, data);
327 #endif
328 
329     // resample into request buffer - add some additional space for resampling
330     int16_t  output_buffer[(128+16) * NUM_CHANNELS]; // 16 * 8 * 2
331     uint32_t resampled_frames = btstack_resample_block(&resample_instance, data, num_frames, output_buffer);
332 
333 #ifdef STORE_RESAMPLED
334 #ifdef STORE_SBC_TO_WAV_FILE
335     wav_writer_write_int16(resampled_frames * NUM_CHANNELS, output_buffer);
336     frame_count++;
337 #endif
338 #endif
339 
340     const btstack_audio_t * audio = btstack_audio_get_instance();
341     if (!audio) return;
342 
343     // store data in btstack_audio buffer first
344     int frames_to_copy = btstack_min(resampled_frames, request_frames);
345     memcpy(request_buffer, output_buffer, frames_to_copy * BYTES_PER_FRAME);
346     request_frames  -= frames_to_copy;
347     request_buffer  += frames_to_copy * NUM_CHANNELS;
348 
349 #ifdef STORE_BEFORE_PLAYBACK
350 #ifdef STORE_SBC_TO_WAV_FILE
351     wav_writer_write_int16(frames_to_copy * NUM_CHANNELS, output_buffer);
352     frame_count++;
353 #endif
354 #endif
355 
356     // and rest in ring buffer
357     int frames_to_store = resampled_frames - frames_to_copy;
358     if (frames_to_store){
359         int status = btstack_ring_buffer_write(&decoded_audio_ring_buffer, (uint8_t *)&output_buffer[frames_to_copy * NUM_CHANNELS], frames_to_store * BYTES_PER_FRAME);
360         if (status){
361             printf("Error storing samples in PCM ring buffer!!!\n");
362         }
363 #ifdef STORE_BEFORE_PLAYBACK
364 #ifdef STORE_SBC_TO_WAV_FILE
365         wav_writer_write_int16(frames_to_store * NUM_CHANNELS, &output_buffer[frames_to_copy * NUM_CHANNELS]);
366         frame_count++;
367 #endif
368 #endif
369     }
370 }
371 
372 static int media_processing_init(avdtp_media_codec_configuration_sbc_t configuration){
373     if (media_initialized) return 0;
374 
375     btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL);
376 
377 #ifdef STORE_SBC_TO_WAV_FILE
378     wav_writer_open(wav_filename, configuration.num_channels, configuration.sampling_frequency);
379 #endif
380 
381 #ifdef STORE_SBC_TO_SBC_FILE
382    sbc_file = fopen(sbc_filename, "wb");
383 #endif
384 
385     btstack_ring_buffer_init(&sbc_frame_ring_buffer, sbc_frame_storage, sizeof(sbc_frame_storage));
386     btstack_ring_buffer_init(&decoded_audio_ring_buffer, decoded_audio_storage, sizeof(decoded_audio_storage));
387     btstack_resample_init(&resample_instance, configuration.num_channels);
388 
389     // setup audio playback
390     const btstack_audio_t * audio = btstack_audio_get_instance();
391     if (audio){
392         audio->init(NUM_CHANNELS, configuration.sampling_frequency, &playback_handler, NULL);
393     }
394 
395     audio_stream_started = 0;
396     media_initialized = 1;
397     return 0;
398 }
399 
400 static void media_processing_close(void){
401 
402     if (!media_initialized) return;
403     media_initialized = 0;
404     audio_stream_started = 0;
405 
406 #ifdef STORE_SBC_TO_WAV_FILE
407     wav_writer_close();
408     int total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr;
409 
410     printf("WAV Writer: Decoding done. Processed totaly %d frames:\n - %d good\n - %d bad\n", total_frames_nr, state.good_frames_nr, total_frames_nr - state.good_frames_nr);
411     printf("WAV Writer: Written %d frames to wav file: %s\n", frame_count, wav_filename);
412 #endif
413 
414 #ifdef STORE_SBC_TO_SBC_FILE
415     fclose(sbc_file);
416 #endif
417 
418     // stop audio playback
419     const btstack_audio_t * audio = btstack_audio_get_instance();
420     if (audio){
421         audio->close();
422     }
423 }
424 
425 /* @section Handle Media Data Packet
426  *
427  * @text Media data packets, in this case the audio data, are received through the handle_l2cap_media_data_packet callback.
428  * Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet.
429  * The SBC frame will be stored in a ring buffer for later processing (instead of decoding it to PCM right away which would require a much larger buffer)
430  * If the audio stream wasn't started already and there are enough SBC frames in the ring buffer, start playback.
431  */
432 
433 static int read_media_data_header(uint8_t * packet, int size, int * offset, avdtp_media_packet_header_t * media_header);
434 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header);
435 
436 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size){
437     UNUSED(seid);
438     int pos = 0;
439 
440     avdtp_media_packet_header_t media_header;
441     if (!read_media_data_header(packet, size, &pos, &media_header)) return;
442 
443     avdtp_sbc_codec_header_t sbc_header;
444     if (!read_sbc_header(packet, size, &pos, &sbc_header)) return;
445 
446     const btstack_audio_t * audio = btstack_audio_get_instance();
447 
448     // process data right away if there's no audio implementation active, e.g. on posix systems to store as .wav
449     if (!audio){
450         btstack_sbc_decoder_process_data(&state, 0, packet+pos, size-pos);
451         return;
452     }
453 
454     // store sbc frame size for buffer management
455     sbc_frame_size = (size-pos)/ sbc_header.num_frames;
456 
457     int status = btstack_ring_buffer_write(&sbc_frame_ring_buffer, packet+pos, size-pos);
458     if (status){
459         printf("Error storing samples in SBC ring buffer!!!\n");
460     }
461 
462     // decide on audio sync drift based on number of sbc frames in queue
463     int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) / sbc_frame_size;
464     uint32_t resampling_factor;
465 
466     // nomimal factor (fixed-point 2^16) and compensation offset
467     uint32_t nomimal_factor = 0x0FF80;
468     uint32_t compensation   = 0x00100;
469 
470     if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){
471     	resampling_factor = nomimal_factor - compensation;    // stretch samples
472     } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){
473     	resampling_factor = nomimal_factor;                   // nothing to do
474     } else {
475     	resampling_factor = nomimal_factor + compensation;    // compress samples
476     }
477 
478     btstack_resample_set_factor(&resample_instance, resampling_factor);
479 
480     // dump
481     printf("%6u %03u %05x\n",  (int) btstack_run_loop_get_time_ms(), sbc_frames_in_buffer, resampling_factor);
482     // log_info("%03u %05x", sbc_frames_in_buffer, resampling_factor);
483 
484 #ifdef STORE_SBC_TO_SBC_FILE
485     fwrite(packet+pos, size-pos, 1, sbc_file);
486 #endif
487 
488     // start stream if enough frames buffered
489     if (!audio_stream_started && sbc_frames_in_buffer >= OPTIMAL_FRAMES_MIN){
490         audio_stream_started = 1;
491         // setup audio playback
492         if (audio){
493             audio->start_stream();
494         }
495     }
496 }
497 
498 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header){
499     int sbc_header_len = 12; // without crc
500     int pos = *offset;
501 
502     if (size - pos < sbc_header_len){
503         printf("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size-pos);
504         return 0;
505     }
506 
507     sbc_header->fragmentation = get_bit16(packet[pos], 7);
508     sbc_header->starting_packet = get_bit16(packet[pos], 6);
509     sbc_header->last_packet = get_bit16(packet[pos], 5);
510     sbc_header->num_frames = packet[pos] & 0x0f;
511     pos++;
512     // printf("SBC HEADER: num_frames %u, fragmented %u, start %u, stop %u\n", sbc_header.num_frames, sbc_header.fragmentation, sbc_header.starting_packet, sbc_header.last_packet);
513     *offset = pos;
514     return 1;
515 }
516 
517 static int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header){
518     int media_header_len = 12; // without crc
519     int pos = *offset;
520 
521     if (size - pos < media_header_len){
522         printf("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size-pos);
523         return 0;
524     }
525 
526     media_header->version = packet[pos] & 0x03;
527     media_header->padding = get_bit16(packet[pos],2);
528     media_header->extension = get_bit16(packet[pos],3);
529     media_header->csrc_count = (packet[pos] >> 4) & 0x0F;
530     pos++;
531 
532     media_header->marker = get_bit16(packet[pos],0);
533     media_header->payload_type  = (packet[pos] >> 1) & 0x7F;
534     pos++;
535 
536     media_header->sequence_number = big_endian_read_16(packet, pos);
537     pos+=2;
538 
539     media_header->timestamp = big_endian_read_32(packet, pos);
540     pos+=4;
541 
542     media_header->synchronization_source = big_endian_read_32(packet, pos);
543     pos+=4;
544     *offset = pos;
545     // TODO: read csrc list
546 
547     // printf_hexdump( packet, pos );
548     // printf("MEDIA HEADER: %u timestamp, version %u, padding %u, extension %u, csrc_count %u\n",
549     //     media_header->timestamp, media_header->version, media_header->padding, media_header->extension, media_header->csrc_count);
550     // printf("MEDIA HEADER: marker %02x, payload_type %02x, sequence_number %u, synchronization_source %u\n",
551     //     media_header->marker, media_header->payload_type, media_header->sequence_number, media_header->synchronization_source);
552     return 1;
553 }
554 
555 static void dump_sbc_configuration(avdtp_media_codec_configuration_sbc_t configuration){
556     printf("Received SBC configuration:\n");
557     printf("    - num_channels: %d\n", configuration.num_channels);
558     printf("    - sampling_frequency: %d\n", configuration.sampling_frequency);
559     printf("    - channel_mode: %d\n", configuration.channel_mode);
560     printf("    - block_length: %d\n", configuration.block_length);
561     printf("    - subbands: %d\n", configuration.subbands);
562     printf("    - allocation_method: %d\n", configuration.allocation_method);
563     printf("    - bitpool_value [%d, %d] \n", configuration.min_bitpool_value, configuration.max_bitpool_value);
564     printf("\n");
565 }
566 
567 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
568     UNUSED(channel);
569     UNUSED(size);
570     uint16_t local_cid;
571     uint8_t  status = 0xFF;
572     bd_addr_t adress;
573 
574     if (packet_type != HCI_EVENT_PACKET) return;
575     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
576     switch (packet[2]){
577         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
578             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
579             if (avrcp_controller_cid != 0 && avrcp_controller_cid != local_cid) {
580                 printf("AVRCP Controller: Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_controller_cid, local_cid);
581                 return;
582             }
583 
584             status = avrcp_subevent_connection_established_get_status(packet);
585             if (status != ERROR_CODE_SUCCESS){
586                 printf("AVRCP Controller: Connection failed: status 0x%02x\n", status);
587                 avrcp_controller_cid = 0;
588                 return;
589             }
590 
591             avrcp_controller_cid = local_cid;
592             avrcp_connected = 1;
593             avrcp_subevent_connection_established_get_bd_addr(packet, adress);
594             printf("AVRCP Controller: Channel successfully opened: %s, avrcp_controller_cid 0x%02x\n", bd_addr_to_str(adress), avrcp_controller_cid);
595 
596             // automatically enable notifications
597             avrcp_controller_enable_notification(avrcp_controller_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
598             avrcp_controller_enable_notification(avrcp_controller_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
599             // avrcp_controller_enable_notification(avrcp_controller_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
600             avrcp_controller_enable_notification(avrcp_controller_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
601             return;
602         }
603         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
604             printf("AVRCP Controller: Channel released: avrcp_controller_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
605             avrcp_controller_cid = 0;
606             avrcp_connected = 0;
607             return;
608         default:
609             break;
610     }
611 
612     status = packet[5];
613     if (!avrcp_controller_cid) return;
614 
615     // ignore INTERIM status
616     if (status == AVRCP_CTYPE_RESPONSE_INTERIM){
617         switch (packet[2]){
618             case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:{
619                 uint32_t playback_position_ms = avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet);
620                 if (playback_position_ms == AVRCP_NO_TRACK_SELECTED_PLAYBACK_POSITION_CHANGED){
621                     printf("AVRCP Controller: notification, playback position changed, no track is selected\n");
622                 }
623                 break;
624             }
625             default:
626                 // printf(" INTERIM response \n");
627                 break;
628         }
629         return;
630     }
631 
632     printf("AVRCP Controller: command status: %s, ", avrcp_ctype2str(status));
633     memset(value, 0, sizeof(value));
634 
635     switch (packet[2]){
636         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:
637             printf("notification, playback position changed, position %d ms\n", (unsigned int) avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet));
638             break;
639         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
640             printf("notification, playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
641             return;
642         case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
643             printf("notification, playing content changed\n");
644             return;
645         case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
646             printf("notification track changed\n");
647             return;
648         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
649             printf("notification absolute volume changed %d\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet));
650             return;
651         case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
652             printf("notification changed\n");
653             return;
654         case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{
655             uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
656             uint8_t repeat_mode  = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
657             printf("%s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
658             break;
659         }
660         case AVRCP_SUBEVENT_NOW_PLAYING_TRACK_INFO:
661             printf("    Track: %d\n", avrcp_subevent_now_playing_track_info_get_track(packet));
662             break;
663 
664         case AVRCP_SUBEVENT_NOW_PLAYING_TOTAL_TRACKS_INFO:
665             printf("    Total Tracks: %d\n", avrcp_subevent_now_playing_total_tracks_info_get_total_tracks(packet));
666             break;
667 
668         case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO:
669             if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0){
670                 memcpy(value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet));
671                 printf("    Title: %s\n", value);
672             }
673             break;
674 
675         case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO:
676             if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0){
677                 memcpy(value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet));
678                 printf("    Artist: %s\n", value);
679             }
680             break;
681 
682         case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO:
683             if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0){
684                 memcpy(value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet));
685                 printf("    Album: %s\n", value);
686             }
687             break;
688 
689         case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO:
690             if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0){
691                 memcpy(value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet));
692                 printf("    Genre: %s\n", value);
693             }
694             break;
695 
696         case AVRCP_SUBEVENT_PLAY_STATUS:
697             printf("song length: %"PRIu32" ms, song position: %"PRIu32" ms, play status: %s\n",
698                 avrcp_subevent_play_status_get_song_length(packet),
699                 avrcp_subevent_play_status_get_song_position(packet),
700                 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
701             break;
702         case AVRCP_SUBEVENT_OPERATION_COMPLETE:
703             printf("operation done %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
704             break;
705         case AVRCP_SUBEVENT_OPERATION_START:
706             printf("operation start %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
707             break;
708         case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
709             // response to set shuffle and repeat mode
710             printf("\n");
711             break;
712         default:
713             printf("AVRCP Controller: event 0x%02x is not parsed\n", packet[2]);
714             break;
715     }
716 }
717 
718 
719 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
720     UNUSED(channel);
721     UNUSED(size);
722     bd_addr_t event_addr;
723     uint16_t local_cid;
724     uint8_t  status = ERROR_CODE_SUCCESS;
725 
726     if (packet_type != HCI_EVENT_PACKET) return;
727     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
728 
729     switch (packet[2]){
730         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
731             printf("AVRCP Target: new volume %d\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet));
732             break;
733         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED:
734             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
735             if (avrcp_target_cid != 0 && avrcp_target_cid != local_cid) {
736                 printf("AVRCP Target: Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_target_cid, local_cid);
737                 return;
738             }
739 
740             status = avrcp_subevent_connection_established_get_status(packet);
741             if (status != ERROR_CODE_SUCCESS){
742                 printf("AVRCP Target: Connection failed: status 0x%02x\n", status);
743                 avrcp_target_cid = 0;
744                 return;
745             }
746             avrcp_target_cid = local_cid;
747             printf("AVRCP Target: Connected to %s, avrcp_cid 0x%02x\n", bd_addr_to_str(event_addr), local_cid);
748             break;
749         case AVRCP_SUBEVENT_EVENT_IDS_QUERY:
750             printf("AVRCP Target: get supported events\n");
751             status = avrcp_target_supported_events(avrcp_target_cid, events_num, events, sizeof(events));
752             break;
753         case AVRCP_SUBEVENT_COMPANY_IDS_QUERY:
754             status = avrcp_target_supported_companies(avrcp_target_cid, companies_num, companies, sizeof(companies));
755             break;
756         // case AVRCP_SUBEVENT_PLAY_STATUS_QUERY:
757         //     status = avrcp_target_play_status(avrcp_target_cid, play_info.song_length_ms, play_info.song_position_ms, play_info.status);
758         //     break;
759         // case AVRCP_SUBEVENT_NOW_PLAYING_INFO_QUERY:
760         //     status = avrcp_target_now_playing_info(avrcp_target_cid);
761         //     break;
762         case AVRCP_SUBEVENT_OPERATION:{
763             avrcp_operation_id_t operation_id = avrcp_subevent_operation_get_operation_id(packet);
764             // if (!media_tracker.connected) break;
765             switch (operation_id){
766                 case AVRCP_OPERATION_ID_PLAY:
767                     printf("AVRCP Target: PLAY\n");
768                     break;
769                 case AVRCP_OPERATION_ID_PAUSE:
770                     printf("AVRCP Target: PAUSE\n");
771                     break;
772                 case AVRCP_OPERATION_ID_STOP:
773                     printf("AVRCP Target: STOP\n");
774                     break;
775                 case AVRCP_OPERATION_ID_VOLUME_UP:
776                     printf("AVRCP Target: received operation VOULME_UP\n");
777                     break;
778                 case AVRCP_OPERATION_ID_VOLUME_DOWN:
779                     printf("AVRCP Target: received operation VOLUME_DOWN\n");
780                     break;
781                 case AVRCP_OPERATION_ID_REWIND:
782                     printf("AVRCP Target: received operation REWIND\n");
783                     break;
784                 case AVRCP_OPERATION_ID_FAST_FORWARD:
785                     printf("AVRCP Target: received operation FAST_FORWARD\n");
786                     break;
787                 case AVRCP_OPERATION_ID_FORWARD:
788                     printf("AVRCP Target: received operation FORWARD\n");
789                     break;
790                 case AVRCP_OPERATION_ID_BACKWARD:
791                     printf("AVRCP Target: received operation BACKWARD\n");
792                     break;
793                 case AVRCP_OPERATION_ID_SKIP:
794                     printf("AVRCP Target: received operation SKIP\n");
795                     break;
796                 case AVRCP_OPERATION_ID_MUTE:
797                     printf("AVRCP Target: received operation MUTE\n");
798                     break;
799                 case AVRCP_OPERATION_ID_CHANNEL_UP:
800                     printf("AVRCP Target: received operation CHANNEL_UP\n");
801                     break;
802                 case AVRCP_OPERATION_ID_CHANNEL_DOWN:
803                     printf("AVRCP Target: received operation CHANNEL_DOWN\n");
804                     break;
805                 case AVRCP_OPERATION_ID_SELECT:
806                     printf("AVRCP Target: received operation SELECT\n");
807                     break;
808                 case AVRCP_OPERATION_ID_UP:
809                     printf("AVRCP Target: received operation UP\n");
810                     break;
811                 case AVRCP_OPERATION_ID_DOWN:
812                     printf("AVRCP Target: received operation DOWN\n");
813                     break;
814                 case AVRCP_OPERATION_ID_LEFT:
815                     printf("AVRCP Target: received operation LEFT\n");
816                     break;
817                 case AVRCP_OPERATION_ID_RIGHT:
818                     printf("AVRCP Target: received operation RIGTH\n");
819                     break;
820                 case AVRCP_OPERATION_ID_ROOT_MENU:
821                     printf("AVRCP Target: received operation ROOT_MENU\n");
822                     break;
823 
824                 default:
825                     return;
826             }
827             break;
828         }
829 
830         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
831             printf("AVRCP Target: Disconnected, avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
832             return;
833         default:
834             printf("AVRCP Target: event 0x%02x is not parsed\n", packet[2]);
835             break;
836     }
837 }
838 
839 
840 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
841     UNUSED(channel);
842     UNUSED(size);
843     if (packet_type != HCI_EVENT_PACKET) return;
844     if (hci_event_packet_get_type(packet) == HCI_EVENT_PIN_CODE_REQUEST) {
845         bd_addr_t address;
846         printf("Pin code request - using '0000'\n");
847         hci_event_pin_code_request_get_bd_addr(packet, address);
848         gap_pin_code_response(address, "0000");
849     }
850 }
851 
852 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
853     UNUSED(channel);
854     UNUSED(size);
855     uint16_t cid;
856     bd_addr_t address;
857     uint8_t status;
858 
859     if (packet_type != HCI_EVENT_PACKET) return;
860     if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return;
861 
862     switch (packet[2]){
863         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
864             printf("A2DP Sink Demo: received non SBC codec. not implemented.\n");
865             break;
866         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
867             printf("A2DP Sink Demo: received SBC codec configuration.\n");
868             sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
869             sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
870             sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
871             sbc_configuration.channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
872             sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
873             sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
874             sbc_configuration.allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
875             sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
876             sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
877             sbc_configuration.frames_per_buffer = sbc_configuration.subbands * sbc_configuration.block_length;
878             dump_sbc_configuration(sbc_configuration);
879 
880             if (sbc_configuration.reconfigure){
881                 media_processing_close();
882             }
883             // prepare media processing
884             media_processing_init(sbc_configuration);
885             break;
886         }
887         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
888             a2dp_subevent_stream_established_get_bd_addr(packet, address);
889             status = a2dp_subevent_stream_established_get_status(packet);
890             cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
891             printf("A2DP_SUBEVENT_STREAM_ESTABLISHED %d, %d \n", cid, a2dp_cid);
892             if (!a2dp_cid){
893                 // incoming connection
894                 a2dp_cid = cid;
895             } else if (cid != a2dp_cid) {
896                 break;
897             }
898             if (status){
899                 a2dp_sink_connected = 0;
900                 printf("A2DP Sink Demo: streaming connection failed, status 0x%02x\n", status);
901                 break;
902             }
903             printf("A2DP Sink Demo: streaming connection is established, address %s, a2dp cid 0x%02X, local_seid %d\n", bd_addr_to_str(address), a2dp_cid, local_seid);
904 
905             memcpy(device_addr, address, 6);
906 
907             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
908             a2dp_sink_connected = 1;
909             break;
910 
911         case A2DP_SUBEVENT_STREAM_STARTED:
912             cid = a2dp_subevent_stream_started_get_a2dp_cid(packet);
913             if (cid != a2dp_cid) break;
914             local_seid = a2dp_subevent_stream_started_get_local_seid(packet);
915             printf("A2DP Sink Demo: stream started, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
916             // started
917             media_processing_init(sbc_configuration);
918             break;
919 
920         case A2DP_SUBEVENT_STREAM_SUSPENDED:
921             cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet);
922             if (cid != a2dp_cid) break;
923             local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet);
924             printf("A2DP Sink Demo: stream paused, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
925             media_processing_close();
926             break;
927 
928         case A2DP_SUBEVENT_STREAM_RELEASED:
929             local_seid = a2dp_subevent_stream_released_get_local_seid(packet);
930             printf("A2DP Sink Demo: stream released, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
931             media_processing_close();
932             break;
933         case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
934             cid = a2dp_subevent_signaling_connection_released_get_a2dp_cid(packet);
935             a2dp_sink_connected = 0;
936             printf("A2DP Sink Demo: signaling connection released\n");
937             media_processing_close();
938             break;
939         default:
940             printf("A2DP Sink Demo: not parsed 0x%02x\n", packet[2]);
941             break;
942     }
943 }
944 
945 #ifdef HAVE_BTSTACK_STDIN
946 static void show_usage(void){
947     bd_addr_t      iut_address;
948     gap_local_bd_addr(iut_address);
949     printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address));
950     printf("b      - AVDTP Sink create  connection to addr %s\n", bd_addr_to_str(device_addr));
951     printf("B      - AVDTP Sink disconnect\n");
952     printf("c      - AVRCP Controller create connection to addr %s\n", bd_addr_to_str(device_addr));
953     printf("C      - AVRCP Controller disconnect\n");
954     printf("d      - AVRCP Target create connection to addr %s\n", bd_addr_to_str(device_addr));
955     printf("D      - AVRCP Target disconnect\n");
956 
957     printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address));
958     printf("O - get play status\n");
959     printf("j - get now playing info\n");
960     printf("k - play\n");
961     printf("K - stop\n");
962     printf("L - pause\n");
963     printf("u - start fast forward\n");
964     printf("U - stop  fast forward\n");
965     printf("n - start rewind\n");
966     printf("N - stop rewind\n");
967     printf("i - forward\n");
968     printf("I - backward\n");
969     printf("t - volume up to 70 percent\n");
970     printf("T - volume down to 10 percent\n");
971     printf("p - absolute volume of 50 percent\n");
972     printf("M - mute\n");
973     printf("r - skip\n");
974     printf("q - query repeat and shuffle mode\n");
975     printf("v - repeat single track\n");
976     printf("x - repeat all tracks\n");
977     printf("X - disable repeat mode\n");
978     printf("z - shuffle all tracks\n");
979     printf("Z - disable shuffle mode\n");
980 
981     printf("a/A - register/deregister TRACK_CHANGED\n");
982     printf("R/P - register/deregister PLAYBACK_POS_CHANGED\n");
983 
984     printf("---\n");
985 }
986 #endif
987 
988 #ifdef HAVE_BTSTACK_STDIN
989 static void stdin_process(char cmd){
990     uint8_t status = ERROR_CODE_SUCCESS;
991 
992     switch (cmd){
993         case 'b':
994             status = a2dp_sink_establish_stream(device_addr, local_seid, &a2dp_cid);
995             printf(" - Create AVDTP connection to addr %s, and local seid %d, expected cid 0x%02x.\n", bd_addr_to_str(device_addr), local_seid, a2dp_cid);
996             break;
997         case 'B':
998             printf(" - AVDTP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
999             status = avdtp_sink_disconnect(a2dp_cid);
1000             break;
1001         case 'c':
1002             printf(" - Create AVRCP Controller connection to addr %s.\n", bd_addr_to_str(device_addr));
1003             status = avrcp_controller_connect(device_addr, &avrcp_controller_cid);
1004             break;
1005         case 'C':
1006             printf(" - AVRCP Controller disconnect from addr %s.\n", bd_addr_to_str(device_addr));
1007             status = avrcp_controller_disconnect(avrcp_controller_cid);
1008             break;
1009         case 'd':
1010             printf(" - Create AVRCP Target connection to addr %s.\n", bd_addr_to_str(device_addr));
1011             status = avrcp_target_connect(device_addr, &avrcp_target_cid);
1012             break;
1013         case 'D':
1014             printf(" - AVRCP Target disconnect from addr %s.\n", bd_addr_to_str(device_addr));
1015             status = avrcp_target_disconnect(avrcp_target_cid);
1016             break;
1017 
1018         case '\n':
1019         case '\r':
1020             break;
1021         case 'O':
1022             printf(" - get play status, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1023             status = avrcp_controller_get_play_status(avrcp_controller_cid);
1024             break;
1025         case 'j':
1026             printf(" - get now playing info, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1027             status = avrcp_controller_get_now_playing_info(avrcp_controller_cid);
1028             break;
1029         case 'k':
1030             printf(" - play, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1031             status = avrcp_controller_play(avrcp_controller_cid);
1032             break;
1033         case 'K':
1034             printf(" - stop, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1035             status = avrcp_controller_stop(avrcp_controller_cid);
1036             break;
1037         case 'L':
1038             printf(" - pause, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1039             status = avrcp_controller_pause(avrcp_controller_cid);
1040             break;
1041         case 'u':
1042             printf(" - start fast forward, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1043             status = avrcp_controller_press_and_hold_fast_forward(avrcp_controller_cid);
1044             break;
1045         case 'U':
1046             printf(" - stop fast forward, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1047             status = avrcp_controller_release_press_and_hold_cmd(avrcp_controller_cid);
1048             break;
1049         case 'n':
1050             printf(" - start rewind, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1051             status = avrcp_controller_press_and_hold_rewind(avrcp_controller_cid);
1052             break;
1053         case 'N':
1054             printf(" - stop rewind, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1055             status = avrcp_controller_release_press_and_hold_cmd(avrcp_controller_cid);
1056             break;
1057         case 'i':
1058             printf(" - forward, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1059             status = avrcp_controller_forward(avrcp_controller_cid);
1060             break;
1061         case 'I':
1062             printf(" - backward, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1063             status = avrcp_controller_backward(avrcp_controller_cid);
1064             break;
1065         case 't':
1066             printf(" - volume up to 70 percent, avrcp target cid 0x%02x\n", avrcp_controller_cid);
1067             // status = avrcp_controller_volume_up(avrcp_controller_cid);
1068             status = avrcp_target_volume_changed(avrcp_target_cid, 70);
1069             break;
1070         case 'T':
1071             printf(" - volume down to 10 percent, avrcp target cid 0x%02x\n", avrcp_controller_cid);
1072             // status = avrcp_controller_volume_down(avrcp_controller_cid);
1073             status = avrcp_target_volume_changed(avrcp_target_cid, 10);
1074             break;
1075         case 'p':
1076             printf(" - absolute volume of 50 percent, avrcp avrcp_target_cid cid 0x%02x\n", avrcp_target_cid);
1077             status = avrcp_target_volume_changed(avrcp_target_cid, 10);
1078             break;
1079 
1080         case 'M':
1081             printf(" - mute, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1082             status = avrcp_controller_mute(avrcp_controller_cid);
1083             break;
1084         case 'r':
1085             printf(" - skip, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1086             status = avrcp_controller_skip(avrcp_controller_cid);
1087             break;
1088         case 'q':
1089             printf(" - query repeat and shuffle mode, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1090             status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_controller_cid);
1091             break;
1092         case 'v':
1093             printf(" - repeat single track, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1094             status = avrcp_controller_set_repeat_mode(avrcp_controller_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK);
1095             break;
1096         case 'x':
1097             printf(" - repeat all tracks, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1098             status = avrcp_controller_set_repeat_mode(avrcp_controller_cid, AVRCP_REPEAT_MODE_ALL_TRACKS);
1099             break;
1100         case 'X':
1101             printf(" - disable repeat mode, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1102             status = avrcp_controller_set_repeat_mode(avrcp_controller_cid, AVRCP_REPEAT_MODE_OFF);
1103             break;
1104         case 'z':
1105             printf(" - shuffle all tracks, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1106             status = avrcp_controller_set_shuffle_mode(avrcp_controller_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS);
1107             break;
1108         case 'Z':
1109             printf(" - disable shuffle mode, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1110             status = avrcp_controller_set_shuffle_mode(avrcp_controller_cid, AVRCP_SHUFFLE_MODE_OFF);
1111             break;
1112         case 'a':
1113             printf("AVRCP: enable notification TRACK_CHANGED, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1114             avrcp_controller_enable_notification(avrcp_controller_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
1115             break;
1116         case 'A':
1117             printf("AVRCP: disable notification TRACK_CHANGED, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1118             avrcp_controller_disable_notification(avrcp_controller_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
1119             break;
1120         case 'R':
1121             printf("AVRCP: enable notification PLAYBACK_POS_CHANGED, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1122             avrcp_controller_enable_notification(avrcp_controller_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
1123             break;
1124         case 'P':
1125             printf("AVRCP: disable notification PLAYBACK_POS_CHANGED, avrcp controller cid 0x%02x\n", avrcp_controller_cid);
1126             avrcp_controller_disable_notification(avrcp_controller_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED);
1127             break;
1128 
1129         default:
1130             show_usage();
1131             return;
1132     }
1133     if (status != ERROR_CODE_SUCCESS){
1134         printf("Could not perform command, status 0x%2x\n", status);
1135     }
1136 }
1137 #endif
1138 
1139 int btstack_main(int argc, const char * argv[]);
1140 int btstack_main(int argc, const char * argv[]){
1141     UNUSED(argc);
1142     (void)argv;
1143 
1144     a2dp_and_avrcp_setup();
1145 
1146 #ifdef HAVE_BTSTACK_STDIN
1147     // parse human readable Bluetooth address
1148     sscanf_bd_addr(device_addr_string, device_addr);
1149     btstack_stdin_setup(stdin_process);
1150 #endif
1151 
1152     // turn on!
1153     printf("Starting BTstack ...\n");
1154     hci_power_control(HCI_POWER_ON);
1155     return 0;
1156 }
1157