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