xref: /btstack/example/a2dp_sink_demo.c (revision d40c3de009bce6994e726da5a427e08951b353d9)
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 != 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             avrcp_subevent_connection_established_get_bd_addr(packet, event_addr);
600             printf("Channel successfully opened: %s, avrcp_cid 0x%02x\n", bd_addr_to_str(event_addr), avrcp_cid);
601 
602             // automatically enable notifications
603             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
604             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
605             return;
606         }
607         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
608             printf("Channel released: avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
609             avrcp_cid = 0;
610             return;
611         default:
612             break;
613     }
614 
615     status = packet[5];
616     if (!avrcp_cid) return;
617 
618     // avoid printing INTERIM status
619     if (status == AVRCP_CTYPE_RESPONSE_INTERIM) return;
620 
621     printf("AVRCP: command status: %s, ", avrcp_ctype2str(status));
622     switch (packet[2]){
623         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
624             printf("notification, playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
625             return;
626         case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
627             printf("notification, playing content changed\n");
628             return;
629         case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
630             printf("notification track changed\n");
631             return;
632         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
633             printf("notification absolute volume changed %d\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet));
634             return;
635         case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
636             printf("notification changed\n");
637             return;
638         case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{
639             uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
640             uint8_t repeat_mode  = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
641             printf("%s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
642             break;
643         }
644         case AVRCP_SUBEVENT_NOW_PLAYING_INFO:{
645             uint8_t value[100];
646             printf("now playing: \n");
647             if (avrcp_subevent_now_playing_info_get_title_len(packet) > 0){
648                 memcpy(value, avrcp_subevent_now_playing_info_get_title(packet), avrcp_subevent_now_playing_info_get_title_len(packet));
649                 printf("    Title: %s\n", value);
650             }
651             if (avrcp_subevent_now_playing_info_get_album_len(packet) > 0){
652                 memcpy(value, avrcp_subevent_now_playing_info_get_album(packet), avrcp_subevent_now_playing_info_get_album_len(packet));
653                 printf("    Album: %s\n", value);
654             }
655             if (avrcp_subevent_now_playing_info_get_artist_len(packet) > 0){
656                 memcpy(value, avrcp_subevent_now_playing_info_get_artist(packet), avrcp_subevent_now_playing_info_get_artist_len(packet));
657                 printf("    Artist: %s\n", value);
658             }
659             if (avrcp_subevent_now_playing_info_get_genre_len(packet) > 0){
660                 memcpy(value, avrcp_subevent_now_playing_info_get_genre(packet), avrcp_subevent_now_playing_info_get_genre_len(packet));
661                 printf("    Genre: %s\n", value);
662             }
663             printf("    Track: %d\n", avrcp_subevent_now_playing_info_get_track(packet));
664             printf("    Total nr. tracks: %d\n", avrcp_subevent_now_playing_info_get_total_tracks(packet));
665             printf("    Song length: %d ms\n", avrcp_subevent_now_playing_info_get_song_length(packet));
666             break;
667         }
668         case AVRCP_SUBEVENT_PLAY_STATUS:
669             printf("song length: %d ms, song position: %d ms, play status: %s\n",
670                 avrcp_subevent_play_status_get_song_length(packet),
671                 avrcp_subevent_play_status_get_song_position(packet),
672                 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
673             break;
674         case AVRCP_SUBEVENT_OPERATION_COMPLETE:
675             printf("operation done %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
676             break;
677         case AVRCP_SUBEVENT_OPERATION_START:
678             printf("operation start %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
679             break;
680         case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
681             // response to set shuffle and repeat mode
682             printf("\n");
683             break;
684         default:
685             printf("Not implemented\n");
686             break;
687     }
688 }
689 
690 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
691     UNUSED(channel);
692     UNUSED(size);
693     uint16_t cid;
694 
695     switch (packet_type) {
696         case HCI_EVENT_PACKET:
697             switch (hci_event_packet_get_type(packet)) {
698                 case HCI_EVENT_A2DP_META:
699                     switch (packet[2]){
700                         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
701                             printf(" received non SBC codec. not implemented\n");
702                             break;
703                         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
704                             sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
705                             sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
706                             sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
707                             sbc_configuration.channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
708                             sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
709                             sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
710                             sbc_configuration.allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
711                             sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
712                             sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
713                             sbc_configuration.frames_per_buffer = sbc_configuration.subbands * sbc_configuration.block_length;
714                             dump_sbc_configuration(sbc_configuration);
715 
716                             if (sbc_configuration.reconfigure){
717                                 media_processing_close();
718                             }
719 
720                             // prepare media processing
721                             media_processing_init(sbc_configuration);
722                             break;
723                         }
724                         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
725                             cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
726                             if (cid != a2dp_cid) break;
727                             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
728                             printf(" -- a2dp sink demo: streaming connection is established, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
729                             app_state = AVDTP_APPLICATION_STREAMING;
730                             break;
731 
732                         case A2DP_SUBEVENT_STREAM_STARTED:
733                             cid = a2dp_subevent_stream_started_get_a2dp_cid(packet);
734                             if (cid != a2dp_cid) break;
735                             local_seid = a2dp_subevent_stream_started_get_local_seid(packet);
736                             printf(" -- a2dp sink demo: stream started, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
737 
738                             // started
739                             // media_processing_init(sbc_configuration);
740                             break;
741 
742                         case A2DP_SUBEVENT_STREAM_SUSPENDED:
743                             cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet);
744                             if (cid != a2dp_cid) break;
745                             local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet);
746                             printf(" -- a2dp sink demo: stream paused, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
747 
748                             // paused/stopped
749                             // media_processing_close();
750                             break;
751 
752                         case A2DP_SUBEVENT_STREAM_RELEASED:
753                             cid = a2dp_subevent_stream_released_get_a2dp_cid(packet);
754                             if (cid != a2dp_cid) break;
755                             local_seid = a2dp_subevent_stream_released_get_local_seid(packet);
756                             app_state = AVDTP_APPLICATION_IDLE;
757                             printf(" -- a2dp sink demo: stream released, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
758 
759                             // paused/stopped
760                             media_processing_close();
761                             break;
762 
763                         default:
764                             printf(" not implemented\n");
765                             break;
766                     }
767                     break;
768                 default:
769                     break;
770             }
771             break;
772         default:
773             // other packet type
774             break;
775     }
776 }
777 
778 #ifdef HAVE_BTSTACK_STDIN
779 static void show_usage(void){
780     bd_addr_t      iut_address;
781     gap_local_bd_addr(iut_address);
782     printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address));
783     printf("b      - AVDTP Sink create  connection to addr %s\n", device_addr_string);
784     printf("B      - AVDTP Sink disconnect\n");
785     printf("c      - AVRCP create connection to addr %s\n", device_addr_string);
786     printf("C      - AVRCP disconnect\n");
787 
788     printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address));
789     printf("O - get play status\n");
790     printf("j - get now playing info\n");
791     printf("k - play\n");
792     printf("K - stop\n");
793     printf("L - pause\n");
794     printf("u - start fast forward\n");
795     printf("U - stop  fast forward\n");
796     printf("n - start rewind\n");
797     printf("N - stop rewind\n");
798     printf("i - forward\n");
799     printf("I - backward\n");
800     printf("t - volume up\n");
801     printf("T - volume down\n");
802     printf("p - absolute volume of 50 percent\n");
803     printf("M - mute\n");
804     printf("r - skip\n");
805     printf("q - query repeat and shuffle mode\n");
806     printf("v - repeat single track\n");
807     printf("x - repeat all tracks\n");
808     printf("X - disable repeat mode\n");
809     printf("z - shuffle all tracks\n");
810     printf("Z - disable shuffle mode\n");
811 
812     printf("Ctrl-c - exit\n");
813     printf("---\n");
814 }
815 #endif
816 
817 static uint8_t media_sbc_codec_capabilities[] = {
818     0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
819     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
820     2, 53
821 };
822 
823 static uint8_t media_sbc_codec_configuration[] = {
824     (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
825     (AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
826     2, 53
827 };
828 
829 #ifdef HAVE_BTSTACK_STDIN
830 static void stdin_process(char cmd){
831     sep.seid = 1;
832     switch (cmd){
833         case 'b':
834             printf(" - Create AVDTP connection to addr %s.\n", bd_addr_to_str(device_addr));
835             a2dp_sink_establish_stream(device_addr, local_seid, &a2dp_cid);
836             break;
837         case 'B':
838             printf(" - Disconnect\n");
839             avdtp_sink_disconnect(a2dp_cid);
840             break;
841         case 'c':
842             printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr));
843             avrcp_controller_connect(device_addr, &avrcp_cid);
844             printf(" assigned avrcp cid 0x%02x\n", avrcp_cid);
845             break;
846         case 'C':
847             printf(" - Disconnect\n");
848             avrcp_controller_disconnect(avrcp_cid);
849             break;
850 
851         case '\n':
852         case '\r':
853             break;
854         case 'O':
855             printf(" - get play status\n");
856             avrcp_controller_get_play_status(avrcp_cid);
857             break;
858         case 'j':
859             printf(" - get now playing info\n");
860             avrcp_controller_get_now_playing_info(avrcp_cid);
861             break;
862         case 'k':
863             printf(" - play\n");
864             avrcp_controller_play(avrcp_cid);
865             break;
866         case 'K':
867             printf(" - stop\n");
868             avrcp_controller_stop(avrcp_cid);
869             break;
870         case 'L':
871             printf(" - pause\n");
872             avrcp_controller_pause(avrcp_cid);
873             break;
874         case 'u':
875             printf(" - start fast forward\n");
876             avrcp_controller_start_fast_forward(avrcp_cid);
877             break;
878         case 'U':
879             printf(" - stop fast forward\n");
880             avrcp_controller_stop_fast_forward(avrcp_cid);
881             break;
882         case 'n':
883             printf(" - start rewind\n");
884             avrcp_controller_start_rewind(avrcp_cid);
885             break;
886         case 'N':
887             printf(" - stop rewind\n");
888             avrcp_controller_stop_rewind(avrcp_cid);
889             break;
890         case 'i':
891             printf(" - forward\n");
892             avrcp_controller_forward(avrcp_cid);
893             break;
894         case 'I':
895             printf(" - backward\n");
896             avrcp_controller_backward(avrcp_cid);
897             break;
898         case 't':
899             printf(" - volume up\n");
900             avrcp_controller_volume_up(avrcp_cid);
901             break;
902         case 'T':
903             printf(" - volume down\n");
904             avrcp_controller_volume_down(avrcp_cid);
905             break;
906         case 'p':
907             printf(" - absolute volume of 50 percent\n");
908             avrcp_controller_set_absolute_volume(avrcp_cid, 50);
909             break;
910         case 'M':
911             printf(" - mute\n");
912             avrcp_controller_mute(avrcp_cid);
913             break;
914         case 'r':
915             printf(" - skip\n");
916             avrcp_controller_skip(avrcp_cid);
917             break;
918         case 'q':
919             printf(" - query repeat and shuffle mode\n");
920             avrcp_controller_query_shuffle_and_repeat_modes(avrcp_cid);
921             break;
922         case 'v':
923             printf(" - repeat single track\n");
924             avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK);
925             break;
926         case 'x':
927             printf(" - repeat all tracks\n");
928             avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS);
929             break;
930         case 'X':
931             printf(" - disable repeat mode\n");
932             avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_OFF);
933             break;
934         case 'z':
935             printf(" - shuffle all tracks\n");
936             avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS);
937             break;
938         case 'Z':
939             printf(" - disable shuffle mode\n");
940             avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_OFF);
941             break;
942         default:
943             show_usage();
944             break;
945 
946     }
947 }
948 #endif
949 
950 
951 int btstack_main(int argc, const char * argv[]);
952 int btstack_main(int argc, const char * argv[]){
953 
954     UNUSED(argc);
955     (void)argv;
956 
957     /* Register for HCI events */
958     hci_event_callback_registration.callback = &packet_handler;
959     hci_add_event_handler(&hci_event_callback_registration);
960 
961     l2cap_init();
962     // Initialize AVDTP Sink
963     a2dp_sink_init();
964     a2dp_sink_register_packet_handler(&packet_handler);
965     a2dp_sink_register_media_handler(&handle_l2cap_media_data_packet);
966 
967     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));
968 
969     // Initialize AVRCP COntroller
970     avrcp_controller_init();
971     avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler);
972 
973     // Initialize SDP
974     sdp_init();
975     // setup AVDTP sink
976     memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer));
977     a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, 0x10001, 1, NULL, NULL);
978     sdp_register_service(sdp_avdtp_sink_service_buffer);
979 
980     // setup AVRCP
981     memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
982     avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10001, AVRCP_BROWSING_ENABLED, 1, NULL, NULL);
983     sdp_register_service(sdp_avrcp_controller_service_buffer);
984 
985 
986     gap_set_local_name("BTstack A2DP Sink Test");
987     gap_discoverable_control(1);
988     gap_set_class_of_device(0x200408);
989     printf("sdp, gap done\n");
990 
991     // turn on!
992     hci_power_control(HCI_POWER_ON);
993 
994 #ifdef HAVE_AUDIO_DMA
995     static btstack_data_source_t hal_audio_dma_data_source;
996     // set up polling data_source
997     btstack_run_loop_set_data_source_handler(&hal_audio_dma_data_source, &hal_audio_dma_process);
998     btstack_run_loop_enable_data_source_callbacks(&hal_audio_dma_data_source, DATA_SOURCE_CALLBACK_POLL);
999     btstack_run_loop_add_data_source(&hal_audio_dma_data_source);
1000 #endif
1001 
1002 #ifdef HAVE_BTSTACK_STDIN
1003     // parse human readable Bluetooth address
1004     sscanf_bd_addr(device_addr_string, device_addr);
1005     btstack_stdin_setup(stdin_process);
1006 #endif
1007 
1008     return 0;
1009 }
1010