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