xref: /btstack/example/a2dp_sink_demo.c (revision 72c514e816484a4062d46d8667ade116fb4931f1)
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 
39 #include <stdint.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #include "btstack.h"
45 
46 #define AVRCP_BROWSING_ENABLED 0
47 
48 #ifdef HAVE_BTSTACK_STDIN
49 #include "btstack_stdin.h"
50 #endif
51 
52 #ifdef HAVE_AUDIO_DMA
53 #include "btstack_ring_buffer.h"
54 #include "hal_audio_dma.h"
55 #endif
56 
57 #ifdef HAVE_PORTAUDIO
58 #include "btstack_ring_buffer.h"
59 #include <portaudio.h>
60 #endif
61 
62 #ifdef HAVE_POSIX_FILE_IO
63 #include "wav_util.h"
64 #define STORE_SBC_TO_SBC_FILE
65 #define STORE_SBC_TO_WAV_FILE
66 #endif
67 
68 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE) || defined(HAVE_AUDIO_DMA)
69 #define DECODE_SBC
70 #endif
71 
72 #define NUM_CHANNELS 2
73 #define BYTES_PER_FRAME     (2*NUM_CHANNELS)
74 #define MAX_SBC_FRAME_SIZE 120
75 
76 // SBC Decoder for WAV file or PortAudio
77 #ifdef DECODE_SBC
78 static btstack_sbc_decoder_state_t state;
79 static btstack_sbc_mode_t mode = SBC_MODE_STANDARD;
80 #endif
81 
82 #if defined(HAVE_PORTAUDIO) || defined (HAVE_AUDIO_DMA)
83 #define PREBUFFER_MS        200
84 static int audio_stream_started = 0;
85 static int audio_stream_paused = 0;
86 static btstack_ring_buffer_t ring_buffer;
87 #endif
88 
89 #ifdef HAVE_AUDIO_DMA
90 // below 30: add samples, 30-40: fine, above 40: drop samples
91 #define OPTIMAL_FRAMES_MIN 30
92 #define OPTIMAL_FRAMES_MAX 40
93 #define ADDITIONAL_FRAMES  10
94 #define DMA_AUDIO_FRAMES 128
95 #define DMA_MAX_FILL_FRAMES 1
96 #define NUM_AUDIO_BUFFERS 2
97 
98 static uint16_t audio_samples[(DMA_AUDIO_FRAMES + DMA_MAX_FILL_FRAMES)*2*NUM_AUDIO_BUFFERS];
99 static uint16_t audio_samples_len[NUM_AUDIO_BUFFERS];
100 static uint8_t ring_buffer_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE];
101 static const uint16_t silent_buffer[DMA_AUDIO_FRAMES*2];
102 static volatile int playback_buffer;
103 static int write_buffer;
104 static uint8_t sbc_frame_size;
105 static int sbc_samples_fix;
106 #endif
107 
108 // PortAdudio - live playback
109 #ifdef HAVE_PORTAUDIO
110 #define PA_SAMPLE_TYPE      paInt16
111 #define SAMPLE_RATE 48000
112 #define FRAMES_PER_BUFFER   128
113 #define PREBUFFER_BYTES     (PREBUFFER_MS*SAMPLE_RATE/1000*BYTES_PER_FRAME)
114 static PaStream * stream;
115 static uint8_t ring_buffer_storage[2*PREBUFFER_BYTES];
116 static btstack_ring_buffer_t ring_buffer;
117 static int total_num_samples = 0;
118 #endif
119 
120 // WAV File
121 #ifdef STORE_SBC_TO_WAV_FILE
122 static int frame_count = 0;
123 static char * wav_filename = "avdtp_sink.wav";
124 #endif
125 
126 #ifdef STORE_SBC_TO_SBC_FILE
127 static FILE * sbc_file;
128 static char * sbc_filename = "avdtp_sink.sbc";
129 #endif
130 
131 typedef struct {
132     // bitmaps
133     uint8_t sampling_frequency_bitmap;
134     uint8_t channel_mode_bitmap;
135     uint8_t block_length_bitmap;
136     uint8_t subbands_bitmap;
137     uint8_t allocation_method_bitmap;
138     uint8_t min_bitpool_value;
139     uint8_t max_bitpool_value;
140 } adtvp_media_codec_information_sbc_t;
141 
142 typedef struct {
143     int reconfigure;
144     int num_channels;
145     int sampling_frequency;
146     int channel_mode;
147     int block_length;
148     int subbands;
149     int allocation_method;
150     int min_bitpool_value;
151     int max_bitpool_value;
152     int frames_per_buffer;
153 } avdtp_media_codec_configuration_sbc_t;
154 
155 #ifdef HAVE_BTSTACK_STDIN
156 // mac 2011: static bd_addr_t remote = {0x04, 0x0C, 0xCE, 0xE4, 0x85, 0xD3};
157 // pts: static bd_addr_t remote = {0x00, 0x1B, 0xDC, 0x08, 0x0A, 0xA5};
158 // mac 2013:
159 // mac 2013: static const char * device_addr_string = "84:38:35:65:d1:15";
160 // iPhone 5S:
161 static const char * device_addr_string = "54:E4:3A:26:A2:39";
162 #endif
163 
164 // bt dongle: -u 02-02 static bd_addr_t remote = {0x00, 0x02, 0x72, 0xDC, 0x31, 0xC1};
165 
166 static uint8_t  sdp_avdtp_sink_service_buffer[150];
167 static avdtp_media_codec_configuration_sbc_t sbc_configuration;
168 static uint16_t a2dp_cid = 0;
169 static uint8_t  local_seid = 0;
170 
171 typedef enum {
172     AVDTP_APPLICATION_IDLE,
173     AVDTP_APPLICATION_CONNECTED,
174     AVDTP_APPLICATION_STREAMING
175 } avdtp_application_state_t;
176 
177 avdtp_application_state_t app_state = AVDTP_APPLICATION_IDLE;
178 
179 static btstack_packet_callback_registration_t hci_event_callback_registration;
180 
181 static int media_initialized = 0;
182 
183 #ifdef HAVE_BTSTACK_STDIN
184 static bd_addr_t device_addr;
185 #endif
186 
187 static uint16_t avrcp_cid = 0;
188 static uint8_t sdp_avrcp_controller_service_buffer[200];
189 
190 #ifdef HAVE_PORTAUDIO
191 static int patestCallback( const void *inputBuffer, void *outputBuffer,
192                            unsigned long framesPerBuffer,
193                            const PaStreamCallbackTimeInfo* timeInfo,
194                            PaStreamCallbackFlags statusFlags,
195                            void *userData ) {
196 
197     /** patestCallback is called from different thread, don't use hci_dump / log_info here without additional checks */
198 
199     (void) timeInfo; /* Prevent unused variable warnings. */
200     (void) statusFlags;
201     (void) inputBuffer;
202     (void) userData;
203 
204     int bytes_to_copy = framesPerBuffer * BYTES_PER_FRAME;
205 
206     // fill with silence while paused
207     if (audio_stream_paused){
208 
209         if (btstack_ring_buffer_bytes_available(&ring_buffer) < PREBUFFER_BYTES){
210             // printf("PA: silence\n");
211             memset(outputBuffer, 0, bytes_to_copy);
212             return 0;
213         } else {
214             // resume playback
215             audio_stream_paused = 0;
216         }
217     }
218 
219     // get data from ringbuffer
220     uint32_t bytes_read = 0;
221     btstack_ring_buffer_read(&ring_buffer, outputBuffer, bytes_to_copy, &bytes_read);
222     bytes_to_copy -= bytes_read;
223 
224     // fill with 0 if not enough
225     if (bytes_to_copy){
226         memset(outputBuffer + bytes_read, 0, bytes_to_copy);
227         audio_stream_paused = 1;
228     }
229     return 0;
230 }
231 #endif
232 
233 #ifdef HAVE_AUDIO_DMA
234 static int next_buffer(int current){
235 	if (current == NUM_AUDIO_BUFFERS-1) return 0;
236 	return current + 1;
237 }
238 static uint8_t * start_of_buffer(int num){
239 	return (uint8_t *) &audio_samples[num * DMA_AUDIO_FRAMES * 2];
240 }
241 void hal_audio_dma_done(void){
242 	if (audio_stream_paused){
243 		hal_audio_dma_play((const uint8_t *) silent_buffer, DMA_AUDIO_FRAMES*4);
244 		return;
245 	}
246 	// next buffer
247 	int next_playback_buffer = next_buffer(playback_buffer);
248 	uint8_t * playback_data;
249 	if (next_playback_buffer == write_buffer){
250 
251 		// TODO: stop codec while playing silence when getting 'stream paused'
252 
253 		// start playing silence
254 		audio_stream_paused = 1;
255 		hal_audio_dma_play((const uint8_t *) silent_buffer, DMA_AUDIO_FRAMES*4);
256 		printf("%6u - paused - bytes in buffer %u\n", (int) btstack_run_loop_get_time_ms(), btstack_ring_buffer_bytes_available(&ring_buffer));
257 		return;
258 	}
259 	playback_buffer = next_playback_buffer;
260 	playback_data = start_of_buffer(playback_buffer);
261 	hal_audio_dma_play(playback_data, audio_samples_len[playback_buffer]);
262     // btstack_run_loop_embedded_trigger();
263 }
264 #endif
265 
266 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE)
267 
268 static void handle_pcm_data(int16_t * data, int num_samples, int num_channels, int sample_rate, void * context){
269     UNUSED(sample_rate);
270     UNUSED(context);
271 
272 #ifdef STORE_SBC_TO_WAV_FILE
273     wav_writer_write_int16(num_samples*num_channels, data);
274     frame_count++;
275 #endif
276 
277 #ifdef HAVE_PORTAUDIO
278     total_num_samples+=num_samples*num_channels;
279 
280     // store pcm samples in ringbuffer
281     btstack_ring_buffer_write(&ring_buffer, (uint8_t *)data, num_samples*num_channels*2);
282 
283     if (!audio_stream_started){
284         audio_stream_paused  = 1;
285         /* -- start stream -- */
286         PaError err = Pa_StartStream(stream);
287         if (err != paNoError){
288             printf("Error starting the stream: \"%s\"\n",  Pa_GetErrorText(err));
289             return;
290         }
291         audio_stream_started = 1;
292     }
293 #endif
294 
295 }
296 #endif
297 
298 
299 #ifdef HAVE_AUDIO_DMA
300 
301 static void handle_pcm_data(int16_t * data, int num_samples, int num_channels, int sample_rate, void * context){
302     UNUSED(sample_rate);
303     UNUSED(context);
304     total_num_samples+=num_samples*num_channels;
305 
306     // store in ring buffer
307     uint8_t * write_data = start_of_buffer(write_buffer);
308     uint16_t len = num_samples*num_channels*2;
309     memcpy(write_data, data, len);
310     audio_samples_len[write_buffer] = len;
311 
312     // add/drop audio frame to fix drift
313     if (sbc_samples_fix > 0){
314         memcpy(write_data + len, write_data + len - 4, 4);
315         audio_samples_len[write_buffer] += 4;
316     }
317     if (sbc_samples_fix < 0){
318         audio_samples_len[write_buffer] -= 4;
319     }
320 
321     write_buffer = next_buffer(write_buffer);
322 }
323 
324 static void hal_audio_dma_process(btstack_data_source_t * ds, btstack_data_source_callback_type_t callback_type){
325 	UNUSED(ds);
326 	UNUSED(callback_type);
327 
328 	if (!media_initialized) return;
329 
330 	int trigger_resume = 0;
331 	if (audio_stream_paused) {
332 		if (sbc_frame_size && btstack_ring_buffer_bytes_available(&ring_buffer) >= OPTIMAL_FRAMES_MIN * sbc_frame_size){
333 			trigger_resume = 1;
334 			// reset buffers
335 			playback_buffer = NUM_AUDIO_BUFFERS - 1;
336 			write_buffer = 0;
337 		} else {
338 			return;
339 		}
340 	}
341 
342 	while (playback_buffer != write_buffer && btstack_ring_buffer_bytes_available(&ring_buffer) >= sbc_frame_size ){
343 		uint8_t frame[MAX_SBC_FRAME_SIZE];
344 	    uint32_t bytes_read = 0;
345 	    btstack_ring_buffer_read(&ring_buffer, frame, sbc_frame_size, &bytes_read);
346 	    btstack_sbc_decoder_process_data(&state, 0, frame, sbc_frame_size);
347 	}
348 
349 	if (trigger_resume){
350 		printf("%6u - resume\n", (int) btstack_run_loop_get_time_ms());
351 		audio_stream_paused = 0;
352 	}
353 }
354 
355 #endif
356 
357 static int media_processing_init(avdtp_media_codec_configuration_sbc_t configuration){
358     if (media_initialized) return 0;
359 
360 #ifdef DECODE_SBC
361     btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL);
362 #endif
363 
364 #ifdef STORE_SBC_TO_WAV_FILE
365     wav_writer_open(wav_filename, configuration.num_channels, configuration.sampling_frequency);
366 #endif
367 
368 #ifdef STORE_SBC_TO_SBC_FILE
369    sbc_file = fopen(sbc_filename, "wb");
370 #endif
371 
372 #ifdef HAVE_PORTAUDIO
373     // int frames_per_buffer = configuration.frames_per_buffer;
374     PaError err;
375     PaStreamParameters outputParameters;
376     const PaDeviceInfo *deviceInfo;
377 
378     /* -- initialize PortAudio -- */
379     err = Pa_Initialize();
380     if (err != paNoError){
381         printf("Error initializing portaudio: \"%s\"\n",  Pa_GetErrorText(err));
382         return err;
383     }
384     /* -- setup input and output -- */
385     outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
386     outputParameters.channelCount = configuration.num_channels;
387     outputParameters.sampleFormat = PA_SAMPLE_TYPE;
388     outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
389     outputParameters.hostApiSpecificStreamInfo = NULL;
390     deviceInfo = Pa_GetDeviceInfo( outputParameters.device );
391     printf("PortAudio: Output device: %s\n", deviceInfo->name);
392     log_info("PortAudio: Output device: %s", deviceInfo->name);
393     /* -- setup stream -- */
394     err = Pa_OpenStream(
395            &stream,
396            NULL,                /* &inputParameters */
397            &outputParameters,
398 		   configuration.sampling_frequency,
399            0,
400            paClipOff,           /* we won't output out of range samples so don't bother clipping them */
401            patestCallback,      /* use callback */
402            NULL );
403 
404     if (err != paNoError){
405         printf("Error initializing portaudio: \"%s\"\n",  Pa_GetErrorText(err));
406         return err;
407     }
408     log_info("PortAudio: stream opened");
409     printf("PortAudio: stream opened\n");
410 #endif
411 #ifdef HAVE_AUDIO_DMA
412     audio_stream_paused  = 1;
413     hal_audio_dma_init(configuration.sampling_frequency);
414     hal_audio_dma_set_audio_played(&hal_audio_dma_done);
415     // start playing silence
416     hal_audio_dma_done();
417 #endif
418 
419  #if defined(HAVE_PORTAUDIO) || defined (HAVE_AUDIO_DMA)
420     memset(ring_buffer_storage, 0, sizeof(ring_buffer_storage));
421     btstack_ring_buffer_init(&ring_buffer, ring_buffer_storage, sizeof(ring_buffer_storage));
422     audio_stream_started = 0;
423 #endif
424     media_initialized = 1;
425     return 0;
426 }
427 
428 static void media_processing_close(void){
429     if (!media_initialized) return;
430     media_initialized = 0;
431 
432 #ifdef STORE_SBC_TO_WAV_FILE
433     printf("WAV Writer: close file.\n");
434     wav_writer_close();
435     int total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr;
436 
437     printf("WAV Writer: Decoding done. Processed totaly %d frames:\n - %d good\n - %d bad\n - %d zero frames\n", total_frames_nr, state.good_frames_nr, state.bad_frames_nr, state.zero_frames_nr);
438     printf("WAV Writer: Written %d frames to wav file: %s\n", frame_count, wav_filename);
439 #endif
440 
441 #ifdef STORE_SBC_TO_SBC_FILE
442     fclose(sbc_file);
443 #endif
444 
445 #if defined(HAVE_PORTAUDIO) || defined (HAVE_AUDIO_DMA)
446     audio_stream_started = 0;
447 #endif
448 
449 #ifdef HAVE_PORTAUDIO
450     printf("PortAudio: Steram closed\n");
451     log_info("PortAudio: Stream closed");
452 
453     PaError err = Pa_StopStream(stream);
454     if (err != paNoError){
455         printf("Error stopping the stream: \"%s\"\n",  Pa_GetErrorText(err));
456         log_error("Error stopping the stream: \"%s\"",  Pa_GetErrorText(err));
457         return;
458     }
459     err = Pa_CloseStream(stream);
460     if (err != paNoError){
461         printf("Error closing the stream: \"%s\"\n",  Pa_GetErrorText(err));
462         log_error("Error closing the stream: \"%s\"",  Pa_GetErrorText(err));
463         return;
464     }
465     err = Pa_Terminate();
466     if (err != paNoError){
467         printf("Error terminating portaudio: \"%s\"\n",  Pa_GetErrorText(err));
468         log_error("Error terminating portaudio: \"%s\"",  Pa_GetErrorText(err));
469         return;
470     }
471 #endif
472 
473 #ifdef HAVE_AUDIO_DMA
474     hal_audio_dma_close();
475 #endif
476 }
477 
478 static void handle_l2cap_media_data_packet(avdtp_stream_endpoint_t * stream_endpoint, uint8_t *packet, uint16_t size){
479 
480     UNUSED(stream_endpoint);
481 
482     int pos = 0;
483 
484     avdtp_media_packet_header_t media_header;
485     media_header.version = packet[pos] & 0x03;
486     media_header.padding = get_bit16(packet[pos],2);
487     media_header.extension = get_bit16(packet[pos],3);
488     media_header.csrc_count = (packet[pos] >> 4) & 0x0F;
489 
490     pos++;
491 
492     media_header.marker = get_bit16(packet[pos],0);
493     media_header.payload_type  = (packet[pos] >> 1) & 0x7F;
494     pos++;
495 
496     media_header.sequence_number = big_endian_read_16(packet, pos);
497     pos+=2;
498 
499     media_header.timestamp = big_endian_read_32(packet, pos);
500     pos+=4;
501 
502     media_header.synchronization_source = big_endian_read_32(packet, pos);
503     pos+=4;
504 
505     UNUSED(media_header);
506 
507     // TODO: read csrc list
508 
509     // printf_hexdump( packet, pos );
510     // printf("MEDIA HEADER: %u timestamp, version %u, padding %u, extension %u, csrc_count %u\n",
511     //     media_header.timestamp, media_header.version, media_header.padding, media_header.extension, media_header.csrc_count);
512     // printf("MEDIA HEADER: marker %02x, payload_type %02x, sequence_number %u, synchronization_source %u\n",
513     //     media_header.marker, media_header.payload_type, media_header.sequence_number, media_header.synchronization_source);
514 
515     avdtp_sbc_codec_header_t sbc_header;
516     sbc_header.fragmentation = get_bit16(packet[pos], 7);
517     sbc_header.starting_packet = get_bit16(packet[pos], 6);
518     sbc_header.last_packet = get_bit16(packet[pos], 5);
519     sbc_header.num_frames = packet[pos] & 0x0f;
520     pos++;
521 
522 #ifdef HAVE_AUDIO_DMA
523     // store sbc frame size for buffer management
524     sbc_frame_size = (size-pos)/ sbc_header.num_frames;
525 #endif
526 
527     UNUSED(sbc_header);
528     // 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);
529     // printf_hexdump( packet+pos, size-pos );
530 
531 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE)
532     btstack_sbc_decoder_process_data(&state, 0, packet+pos, size-pos);
533 #endif
534 
535 #ifdef HAVE_AUDIO_DMA
536     btstack_ring_buffer_write(&ring_buffer,  packet+pos, size-pos);
537 
538     // decide on audio sync drift based on number of sbc frames in queue
539     int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&ring_buffer) / sbc_frame_size;
540     if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){
541     	sbc_samples_fix = 1;	// duplicate last sample
542     } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){
543     	sbc_samples_fix = 0;	// nothing to do
544     } else {
545     	sbc_samples_fix = -1;	// drop last sample
546     }
547 
548     // dump
549     printf("%6u %03u %d\n",  (int) btstack_run_loop_get_time_ms(), sbc_frames_in_buffer, sbc_samples_fix);
550 
551 #endif
552 
553 #ifdef STORE_SBC_TO_SBC_FILE
554     fwrite(packet+pos, size-pos, 1, sbc_file);
555 #endif
556 }
557 
558 static void dump_sbc_configuration(avdtp_media_codec_configuration_sbc_t configuration){
559     printf(" -- a2dp sink demo: Received media codec configuration:\n");
560     printf("    - num_channels: %d\n", configuration.num_channels);
561     printf("    - sampling_frequency: %d\n", configuration.sampling_frequency);
562     printf("    - channel_mode: %d\n", configuration.channel_mode);
563     printf("    - block_length: %d\n", configuration.block_length);
564     printf("    - subbands: %d\n", configuration.subbands);
565     printf("    - allocation_method: %d\n", configuration.allocation_method);
566     printf("    - bitpool_value [%d, %d] \n", configuration.min_bitpool_value, configuration.max_bitpool_value);
567     printf("\n");
568 }
569 
570 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
571     UNUSED(channel);
572     UNUSED(size);
573     uint16_t local_cid;
574     uint8_t  status = 0xFF;
575     bd_addr_t adress;
576 
577     if (packet_type != HCI_EVENT_PACKET) return;
578     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
579     switch (packet[2]){
580         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
581             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
582             if (avrcp_cid != 0 && avrcp_cid != local_cid) {
583                 printf("AVRCP Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_cid, local_cid);
584                 return;
585             }
586 
587             status = avrcp_subevent_connection_established_get_status(packet);
588             if (status != ERROR_CODE_SUCCESS){
589                 printf("AVRCP Connection failed: status 0x%02x\n", status);
590                 avrcp_cid = 0;
591                 return;
592             }
593 
594             avrcp_cid = local_cid;
595             avrcp_subevent_connection_established_get_bd_addr(packet, adress);
596             printf("Channel successfully opened: %s, avrcp_cid 0x%02x\n", bd_addr_to_str(adress), avrcp_cid);
597 
598             // automatically enable notifications
599             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
600             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
601             return;
602         }
603         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
604             printf("Channel released: avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
605             avrcp_cid = 0;
606             return;
607         default:
608             break;
609     }
610 
611     status = packet[5];
612     if (!avrcp_cid) return;
613 
614     // avoid printing INTERIM status
615     if (status == AVRCP_CTYPE_RESPONSE_INTERIM) return;
616 
617     printf("AVRCP: command status: %s, ", avrcp_ctype2str(status));
618     switch (packet[2]){
619         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
620             printf("notification, playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
621             return;
622         case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
623             printf("notification, playing content changed\n");
624             return;
625         case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
626             printf("notification track changed\n");
627             return;
628         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
629             printf("notification absolute volume changed %d\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet));
630             return;
631         case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
632             printf("notification changed\n");
633             return;
634         case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{
635             uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
636             uint8_t repeat_mode  = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
637             printf("%s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
638             break;
639         }
640         case AVRCP_SUBEVENT_NOW_PLAYING_INFO:{
641             uint8_t value[100];
642             printf("now playing: \n");
643             if (avrcp_subevent_now_playing_info_get_title_len(packet) > 0){
644                 memcpy(value, avrcp_subevent_now_playing_info_get_title(packet), avrcp_subevent_now_playing_info_get_title_len(packet));
645                 printf("    Title: %s\n", value);
646             }
647             if (avrcp_subevent_now_playing_info_get_album_len(packet) > 0){
648                 memcpy(value, avrcp_subevent_now_playing_info_get_album(packet), avrcp_subevent_now_playing_info_get_album_len(packet));
649                 printf("    Album: %s\n", value);
650             }
651             if (avrcp_subevent_now_playing_info_get_artist_len(packet) > 0){
652                 memcpy(value, avrcp_subevent_now_playing_info_get_artist(packet), avrcp_subevent_now_playing_info_get_artist_len(packet));
653                 printf("    Artist: %s\n", value);
654             }
655             if (avrcp_subevent_now_playing_info_get_genre_len(packet) > 0){
656                 memcpy(value, avrcp_subevent_now_playing_info_get_genre(packet), avrcp_subevent_now_playing_info_get_genre_len(packet));
657                 printf("    Genre: %s\n", value);
658             }
659             printf("    Track: %d\n", avrcp_subevent_now_playing_info_get_track(packet));
660             printf("    Total nr. tracks: %d\n", avrcp_subevent_now_playing_info_get_total_tracks(packet));
661             printf("    Song length: %d ms\n", avrcp_subevent_now_playing_info_get_song_length(packet));
662             break;
663         }
664         case AVRCP_SUBEVENT_PLAY_STATUS:
665             printf("song length: %d ms, song position: %d ms, play status: %s\n",
666                 avrcp_subevent_play_status_get_song_length(packet),
667                 avrcp_subevent_play_status_get_song_position(packet),
668                 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
669             break;
670         case AVRCP_SUBEVENT_OPERATION_COMPLETE:
671             printf("operation done %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
672             break;
673         case AVRCP_SUBEVENT_OPERATION_START:
674             printf("operation start %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
675             break;
676         case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
677             // response to set shuffle and repeat mode
678             printf("\n");
679             break;
680         default:
681             printf("Not implemented\n");
682             break;
683     }
684 }
685 
686 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
687     UNUSED(channel);
688     UNUSED(size);
689     uint16_t cid;
690     bd_addr_t address;
691 
692     if (packet_type != HCI_EVENT_PACKET) return;
693     if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return;
694 
695     switch (packet[2]){
696         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
697             printf(" -- a2dp sink demo: received non SBC codec. not implemented.\n");
698             break;
699         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
700             printf(" -- a2dp sink demo: received SBC codec configuration.\n");
701             sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
702             sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
703             sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
704             sbc_configuration.channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
705             sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
706             sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
707             sbc_configuration.allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
708             sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
709             sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
710             sbc_configuration.frames_per_buffer = sbc_configuration.subbands * sbc_configuration.block_length;
711             dump_sbc_configuration(sbc_configuration);
712 
713             if (sbc_configuration.reconfigure){
714                 media_processing_close();
715             }
716             // prepare media processing
717             media_processing_init(sbc_configuration);
718             break;
719         }
720         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
721             a2dp_subevent_stream_established_get_bd_addr(packet, address);
722             cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
723             if (cid != a2dp_cid) break;
724             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
725             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);
726             app_state = AVDTP_APPLICATION_STREAMING;
727             break;
728 
729         case A2DP_SUBEVENT_STREAM_STARTED:
730             cid = a2dp_subevent_stream_started_get_a2dp_cid(packet);
731             if (cid != a2dp_cid) break;
732             local_seid = a2dp_subevent_stream_started_get_local_seid(packet);
733             printf(" -- a2dp sink demo: stream started, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
734             // started
735             media_processing_init(sbc_configuration);
736             break;
737 
738         case A2DP_SUBEVENT_STREAM_SUSPENDED:
739             cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet);
740             if (cid != a2dp_cid) break;
741             local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet);
742             printf(" -- a2dp sink demo: stream paused, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
743             // paused/stopped
744             media_processing_close();
745             break;
746 
747         case A2DP_SUBEVENT_STREAM_RELEASED:
748             cid = a2dp_subevent_stream_released_get_a2dp_cid(packet);
749             if (cid != a2dp_cid) break;
750             local_seid = a2dp_subevent_stream_released_get_local_seid(packet);
751             app_state = AVDTP_APPLICATION_IDLE;
752             printf(" -- a2dp sink demo: stream released, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
753 
754             // paused/stopped
755             media_processing_close();
756             break;
757 
758         default:
759             printf(" not implemented\n");
760             break;
761     }
762 }
763 
764 #ifdef HAVE_BTSTACK_STDIN
765 static void show_usage(void){
766     bd_addr_t      iut_address;
767     gap_local_bd_addr(iut_address);
768     printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address));
769     printf("b      - AVDTP Sink create  connection to addr %s\n", device_addr_string);
770     printf("B      - AVDTP Sink disconnect\n");
771     printf("c      - AVRCP create connection to addr %s\n", device_addr_string);
772     printf("C      - AVRCP disconnect\n");
773 
774     printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address));
775     printf("O - get play status\n");
776     printf("j - get now playing info\n");
777     printf("k - play\n");
778     printf("K - stop\n");
779     printf("L - pause\n");
780     printf("u - start fast forward\n");
781     printf("U - stop  fast forward\n");
782     printf("n - start rewind\n");
783     printf("N - stop rewind\n");
784     printf("i - forward\n");
785     printf("I - backward\n");
786     printf("t - volume up\n");
787     printf("T - volume down\n");
788     printf("p - absolute volume of 50 percent\n");
789     printf("M - mute\n");
790     printf("r - skip\n");
791     printf("q - query repeat and shuffle mode\n");
792     printf("v - repeat single track\n");
793     printf("x - repeat all tracks\n");
794     printf("X - disable repeat mode\n");
795     printf("z - shuffle all tracks\n");
796     printf("Z - disable shuffle mode\n");
797 
798     printf("Ctrl-c - exit\n");
799     printf("---\n");
800 }
801 #endif
802 
803 static uint8_t media_sbc_codec_capabilities[] = {
804     0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
805     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
806     2, 53
807 };
808 
809 static uint8_t media_sbc_codec_configuration[] = {
810     (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
811     (AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
812     2, 53
813 };
814 
815 #ifdef HAVE_BTSTACK_STDIN
816 static void stdin_process(char cmd){
817     uint8_t status = ERROR_CODE_SUCCESS;
818     switch (cmd){
819         case 'b':
820             printf(" - Create AVDTP connection to addr %s.\n", bd_addr_to_str(device_addr));
821             status = a2dp_sink_establish_stream(device_addr, local_seid, &a2dp_cid);
822             break;
823         case 'B':
824             printf(" - Disconnect\n");
825             status = avdtp_sink_disconnect(a2dp_cid);
826             break;
827         case 'c':
828             printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr));
829             status = avrcp_controller_connect(device_addr, &avrcp_cid);
830             break;
831         case 'C':
832             printf(" - Disconnect\n");
833             status = avrcp_controller_disconnect(avrcp_cid);
834             break;
835 
836         case '\n':
837         case '\r':
838             break;
839         case 'O':
840             printf(" - get play status\n");
841             status = avrcp_controller_get_play_status(avrcp_cid);
842             break;
843         case 'j':
844             printf(" - get now playing info\n");
845             status = avrcp_controller_get_now_playing_info(avrcp_cid);
846             break;
847         case 'k':
848             printf(" - play\n");
849             status = avrcp_controller_play(avrcp_cid);
850             break;
851         case 'K':
852             printf(" - stop\n");
853             status = avrcp_controller_stop(avrcp_cid);
854             break;
855         case 'L':
856             printf(" - pause\n");
857             status = avrcp_controller_pause(avrcp_cid);
858             break;
859         case 'u':
860             printf(" - start fast forward\n");
861             status = avrcp_controller_start_fast_forward(avrcp_cid);
862             break;
863         case 'U':
864             printf(" - stop fast forward\n");
865             status = avrcp_controller_stop_fast_forward(avrcp_cid);
866             break;
867         case 'n':
868             printf(" - start rewind\n");
869             status = avrcp_controller_start_rewind(avrcp_cid);
870             break;
871         case 'N':
872             printf(" - stop rewind\n");
873             status = avrcp_controller_stop_rewind(avrcp_cid);
874             break;
875         case 'i':
876             printf(" - forward\n");
877             status = avrcp_controller_forward(avrcp_cid);
878             break;
879         case 'I':
880             printf(" - backward\n");
881             status = avrcp_controller_backward(avrcp_cid);
882             break;
883         case 't':
884             printf(" - volume up\n");
885             status = avrcp_controller_volume_up(avrcp_cid);
886             break;
887         case 'T':
888             printf(" - volume down\n");
889             status = avrcp_controller_volume_down(avrcp_cid);
890             break;
891         case 'p':
892             printf(" - absolute volume of 50 percent\n");
893             status = avrcp_controller_set_absolute_volume(avrcp_cid, 50);
894             break;
895         case 'M':
896             printf(" - mute\n");
897             status = avrcp_controller_mute(avrcp_cid);
898             break;
899         case 'r':
900             printf(" - skip\n");
901             status = avrcp_controller_skip(avrcp_cid);
902             break;
903         case 'q':
904             printf(" - query repeat and shuffle mode\n");
905             status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_cid);
906             break;
907         case 'v':
908             printf(" - repeat single track\n");
909             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK);
910             break;
911         case 'x':
912             printf(" - repeat all tracks\n");
913             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS);
914             break;
915         case 'X':
916             printf(" - disable repeat mode\n");
917             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_OFF);
918             break;
919         case 'z':
920             printf(" - shuffle all tracks\n");
921             status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS);
922             break;
923         case 'Z':
924             printf(" - disable shuffle mode\n");
925             status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_OFF);
926             break;
927         default:
928             show_usage();
929             return;
930     }
931     if (status != ERROR_CODE_SUCCESS){
932         printf("Could not perform command, status 0x%2x\n", status);
933     }
934 }
935 #endif
936 
937 
938 int btstack_main(int argc, const char * argv[]);
939 int btstack_main(int argc, const char * argv[]){
940 
941     UNUSED(argc);
942     (void)argv;
943 
944     /* Register for HCI events */
945     hci_event_callback_registration.callback = &packet_handler;
946     hci_add_event_handler(&hci_event_callback_registration);
947 
948     l2cap_init();
949     // Initialize AVDTP Sink
950     a2dp_sink_init();
951     a2dp_sink_register_packet_handler(&packet_handler);
952     a2dp_sink_register_media_handler(&handle_l2cap_media_data_packet);
953 
954     avdtp_stream_endpoint_t * local_stream_endpoint = 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));
955     if (!local_stream_endpoint){
956         printf("A2DP Sink: not enough memory to create local stream endpoint\n");
957         return 1;
958     }
959     local_seid = avdtp_local_seid(local_stream_endpoint);
960     // Initialize AVRCP COntroller
961     avrcp_controller_init();
962     avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler);
963 
964     // Initialize SDP
965     sdp_init();
966     // setup AVDTP sink
967     memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer));
968     a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, 0x10001, 1, NULL, NULL);
969     sdp_register_service(sdp_avdtp_sink_service_buffer);
970 
971     // setup AVRCP
972     memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
973     avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10001, AVRCP_BROWSING_ENABLED, 1, NULL, NULL);
974     sdp_register_service(sdp_avrcp_controller_service_buffer);
975 
976 
977     gap_set_local_name("BTstack A2DP Sink Test");
978     gap_discoverable_control(1);
979     gap_set_class_of_device(0x200408);
980     printf("sdp, gap done\n");
981 
982     // turn on!
983     hci_power_control(HCI_POWER_ON);
984 
985 #ifdef HAVE_AUDIO_DMA
986     static btstack_data_source_t hal_audio_dma_data_source;
987     // set up polling data_source
988     btstack_run_loop_set_data_source_handler(&hal_audio_dma_data_source, &hal_audio_dma_process);
989     btstack_run_loop_enable_data_source_callbacks(&hal_audio_dma_data_source, DATA_SOURCE_CALLBACK_POLL);
990     btstack_run_loop_add_data_source(&hal_audio_dma_data_source);
991 #endif
992 
993 #ifdef HAVE_BTSTACK_STDIN
994     // parse human readable Bluetooth address
995     sscanf_bd_addr(device_addr_string, device_addr);
996     btstack_stdin_setup(stdin_process);
997 #endif
998 
999     return 0;
1000 }
1001