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