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