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