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