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