xref: /btstack/example/a2dp_sink_demo.c (revision d5e631f6ca1c5ad46a054413a54902968f0875db)
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 #define __BTSTACK_FILE__ "a2dp_sink_demo.c"
39 
40 /*
41  * a2dp_sink_demo.c
42  */
43 
44 // *****************************************************************************
45 /* EXAMPLE_START(a2dp_sink_demo): Receive audio stream and control its playback.
46  *
47  * @text This A2DP Sink example demonstrates how to use the A2DP Sink service to
48  * receive an audio data stream from a remote A2DP Source device. In addition,
49  * the AVRCP Controller is used to get information on currently played media,
50  * such are title, artist and album, as well as to control the playback,
51  * i.e. to play, stop, repeat, etc.
52  *
53  * @test To test with a remote device, e.g. a mobile phone,
54  * pair from the remote device with the demo, then start playing music on the remote device.
55  * Alternatively, set the device_addr_string to the Bluetooth address of your
56  * remote device in the code, and call connect from the UI.
57  *
58  * @test To controll the playback, tap SPACE on the console to show the available
59  * AVRCP commands.
60  */
61 // *****************************************************************************
62 
63 #include <stdint.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 
68 #include "btstack.h"
69 
70 #define AVRCP_BROWSING_ENABLED 0
71 
72 #ifdef HAVE_BTSTACK_STDIN
73 #include "btstack_stdin.h"
74 #endif
75 
76 #ifdef HAVE_AUDIO_DMA
77 #include "btstack_ring_buffer.h"
78 #include "hal_audio_dma.h"
79 #endif
80 
81 #ifdef HAVE_PORTAUDIO
82 #include "btstack_ring_buffer.h"
83 #include <portaudio.h>
84 #endif
85 
86 #ifdef HAVE_POSIX_FILE_IO
87 #include "wav_util.h"
88 #define STORE_SBC_TO_SBC_FILE
89 #define STORE_SBC_TO_WAV_FILE
90 #endif
91 
92 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE) || defined(HAVE_AUDIO_DMA)
93 #define DECODE_SBC
94 #endif
95 
96 #define NUM_CHANNELS 2
97 #define BYTES_PER_FRAME     (2*NUM_CHANNELS)
98 #define MAX_SBC_FRAME_SIZE 120
99 
100 // SBC Decoder for WAV file or PortAudio
101 #ifdef DECODE_SBC
102 static btstack_sbc_decoder_state_t state;
103 static btstack_sbc_mode_t mode = SBC_MODE_STANDARD;
104 #endif
105 
106 #if defined(HAVE_PORTAUDIO) || defined (HAVE_AUDIO_DMA)
107 #define PREBUFFER_MS        200
108 static int audio_stream_started = 0;
109 static int audio_stream_paused = 0;
110 static btstack_ring_buffer_t ring_buffer;
111 #endif
112 
113 #ifdef HAVE_AUDIO_DMA
114 // below 30: add samples, 30-40: fine, above 40: drop samples
115 #define OPTIMAL_FRAMES_MIN 30
116 #define OPTIMAL_FRAMES_MAX 40
117 #define ADDITIONAL_FRAMES  10
118 #define DMA_AUDIO_FRAMES 128
119 #define DMA_MAX_FILL_FRAMES 1
120 #define NUM_AUDIO_BUFFERS 2
121 
122 static uint16_t audio_samples[(DMA_AUDIO_FRAMES + DMA_MAX_FILL_FRAMES)*2*NUM_AUDIO_BUFFERS];
123 static uint16_t audio_samples_len[NUM_AUDIO_BUFFERS];
124 static uint8_t ring_buffer_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE];
125 static const uint16_t silent_buffer[DMA_AUDIO_FRAMES*2];
126 static volatile int playback_buffer;
127 static int write_buffer;
128 static uint8_t sbc_frame_size;
129 static int sbc_samples_fix;
130 #endif
131 
132 // PortAdudio - live playback
133 #ifdef HAVE_PORTAUDIO
134 #define PA_SAMPLE_TYPE      paInt16
135 #define SAMPLE_RATE 48000
136 #define FRAMES_PER_BUFFER   128
137 #define PREBUFFER_BYTES     (PREBUFFER_MS*SAMPLE_RATE/1000*BYTES_PER_FRAME)
138 static PaStream * stream;
139 static uint8_t ring_buffer_storage[2*PREBUFFER_BYTES];
140 #endif
141 
142 // WAV File
143 #ifdef STORE_SBC_TO_WAV_FILE
144 static int frame_count = 0;
145 static char * wav_filename = "avdtp_sink.wav";
146 #endif
147 
148 #ifdef STORE_SBC_TO_SBC_FILE
149 static FILE * sbc_file;
150 static char * sbc_filename = "avdtp_sink.sbc";
151 #endif
152 
153 typedef struct {
154     // bitmaps
155     uint8_t sampling_frequency_bitmap;
156     uint8_t channel_mode_bitmap;
157     uint8_t block_length_bitmap;
158     uint8_t subbands_bitmap;
159     uint8_t allocation_method_bitmap;
160     uint8_t min_bitpool_value;
161     uint8_t max_bitpool_value;
162 } adtvp_media_codec_information_sbc_t;
163 
164 typedef struct {
165     int reconfigure;
166     int num_channels;
167     int sampling_frequency;
168     int channel_mode;
169     int block_length;
170     int subbands;
171     int allocation_method;
172     int min_bitpool_value;
173     int max_bitpool_value;
174     int frames_per_buffer;
175 } avdtp_media_codec_configuration_sbc_t;
176 
177 #ifdef HAVE_BTSTACK_STDIN
178 // mac 2011: static bd_addr_t remote = {0x04, 0x0C, 0xCE, 0xE4, 0x85, 0xD3};
179 // pts: static bd_addr_t remote = {0x00, 0x1B, 0xDC, 0x08, 0x0A, 0xA5};
180 // mac 2013:
181 // mac 2013: static const char * device_addr_string = "84:38:35:65:d1:15";
182 // iPhone 5S:
183 static const char * device_addr_string = "54:E4:3A:26:A2:39";
184 #endif
185 
186 // bt dongle: -u 02-02 static bd_addr_t remote = {0x00, 0x02, 0x72, 0xDC, 0x31, 0xC1};
187 
188 static uint8_t  sdp_avdtp_sink_service_buffer[150];
189 static avdtp_media_codec_configuration_sbc_t sbc_configuration;
190 static uint16_t a2dp_cid = 0;
191 static uint8_t  local_seid = 0;
192 static uint8_t  value[100];
193 
194 static btstack_packet_callback_registration_t hci_event_callback_registration;
195 
196 static int media_initialized = 0;
197 
198 #ifdef HAVE_BTSTACK_STDIN
199 static bd_addr_t device_addr;
200 #endif
201 
202 static uint16_t a2dp_sink_connected = 0;
203 static uint16_t avrcp_cid = 0;
204 static uint8_t  avrcp_connected = 0;
205 static uint8_t  sdp_avrcp_controller_service_buffer[200];
206 
207 static uint8_t media_sbc_codec_capabilities[] = {
208     0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
209     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
210     2, 53
211 };
212 
213 static uint8_t media_sbc_codec_configuration[] = {
214     (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
215     (AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
216     2, 53
217 };
218 
219 
220 /* @section Main Application Setup
221  *
222  * @text The Listing MainConfiguration shows how to setup AD2P Sink and AVRCP controller services.
223  * To announce A2DP Sink and AVRCP Controller services, you need to create corresponding
224  * SDP records and register them with the SDP service.
225  * You'll also need to register several packet handlers:
226  * - a2dp_sink_packet_handler - handles events on stream connection status (established, released), the media codec configuration, and, the status of the stream itself (opened, paused, stopped).
227  * - handle_l2cap_media_data_packet - used to receive streaming data. If HAVE_PORTAUDIO or STORE_SBC_TO_WAV_FILE directives (check btstack_config.h) are used, the SBC decoder will be used to decode the SBC data into PCM frames. The resulting PCM frames are then processed in the SBC Decoder callback.
228  * - stdin_process callback - used to trigger AVRCP commands to the A2DP Source device, such are get now playing info, start, stop, volume control. Requires HAVE_BTSTACK_STDIN.
229  * - avrcp_controller_packet_handler - used to receive answers for AVRCP commands,
230  *
231  * @text Note, currently only the SBC codec is supported.
232  * If you want to store the audio data in a file, you'll need to define STORE_SBC_TO_WAV_FILE. The HAVE_PORTAUDIO directive indicates if the audio is played back via PortAudio.
233  * If HAVE_PORTAUDIO or STORE_SBC_TO_WAV_FILE directives is defined, the SBC decoder needs to get initialized when a2dp_sink_packet_handler receives event A2DP_SUBEVENT_STREAM_STARTED.
234  * The initialization of the SBC decoder requires a callback that handles PCM data:
235  * - handle_pcm_data - handles PCM audio frames. Here, they are stored a in wav file if STORE_SBC_TO_WAV_FILE is defined, and/or played using the PortAudio library if HAVE_PORTAUDIO is defined.
236  */
237 
238 /* LISTING_START(MainConfiguration): Setup Audio Sink and AVRCP Controller services */
239 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * event, uint16_t event_size);
240 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
241 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size);
242 #ifdef HAVE_BTSTACK_STDIN
243 static void stdin_process(char cmd);
244 #endif
245 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE)
246 static void handle_pcm_data(int16_t * data, int num_samples, int num_channels, int sample_rate, void * context);
247 #endif
248 
249 static int a2dp_sink_and_avrcp_services_init(void){
250     // Register for HCI events.
251     hci_event_callback_registration.callback = &a2dp_sink_packet_handler;
252     hci_add_event_handler(&hci_event_callback_registration);
253 
254     // Initialize L2CAP.
255     l2cap_init();
256 
257     // Initialize A2DP Sink.
258     a2dp_sink_init();
259     // Register A2DP Sink for HCI events.
260     a2dp_sink_register_packet_handler(&a2dp_sink_packet_handler);
261     // Register A2DP Sink for receiving media data.
262     a2dp_sink_register_media_handler(&handle_l2cap_media_data_packet);
263     // Create a stream endpoint to which the streaming channel will be opened.
264     uint8_t status = 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), &local_seid);
265     if (status != ERROR_CODE_SUCCESS){
266         printf("A2DP Sink: not enough memory to create local stream endpoint\n");
267         return 1;
268     }
269 
270     // Initialize AVRCP Controller.
271     avrcp_controller_init();
272     // Register AVRCP for HCI events.
273     avrcp_controller_register_packet_handler(&avrcp_controller_packet_handler);
274 
275     // Initialize SDP.
276     sdp_init();
277 
278     // Create A2DP sink service record and register it with SDP.
279     memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer));
280     a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, 0x10001, 1, NULL, NULL);
281     sdp_register_service(sdp_avdtp_sink_service_buffer);
282 
283     // Create AVRCP service record and register it with SDP.
284     memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
285     avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10001, AVRCP_BROWSING_ENABLED, 1, NULL, NULL);
286     sdp_register_service(sdp_avrcp_controller_service_buffer);
287 
288     // Set local name with a template Bluetooth address, that will be automatically
289     // replaced with a actual address once it is available, i.e. when BTstack boots
290     // up and starts talking to a Bluetooth module.
291     gap_set_local_name("A2DP Sink Demo 00:00:00:00:00:00");
292     gap_discoverable_control(1);
293     gap_set_class_of_device(0x200408);
294 
295 #ifdef HAVE_AUDIO_DMA
296     static btstack_data_source_t hal_audio_dma_data_source;
297     // Set up polling data source.
298     btstack_run_loop_set_data_source_handler(&hal_audio_dma_data_source, &hal_audio_dma_process);
299     btstack_run_loop_enable_data_source_callbacks(&hal_audio_dma_data_source, DATA_SOURCE_CALLBACK_POLL);
300     btstack_run_loop_add_data_source(&hal_audio_dma_data_source);
301 #endif
302 
303 #ifdef HAVE_BTSTACK_STDIN
304     // Parse human readable Bluetooth address.
305     sscanf_bd_addr(device_addr_string, device_addr);
306     btstack_stdin_setup(stdin_process);
307 #endif
308     return 0;
309 }
310 /* LISTING_END */
311 
312 #ifdef HAVE_PORTAUDIO
313 static int portaudio_callback( const void *inputBuffer, void *outputBuffer,
314                            unsigned long framesPerBuffer,
315                            const PaStreamCallbackTimeInfo* timeInfo,
316                            PaStreamCallbackFlags statusFlags,
317                            void *userData ) {
318 
319     /** portaudio_callback is called from different thread, don't use hci_dump / log_info here without additional checks */
320 
321     // Prevent unused variable warnings.
322     (void) timeInfo;
323     (void) statusFlags;
324     (void) inputBuffer;
325     (void) userData;
326 
327     int bytes_to_copy = framesPerBuffer * BYTES_PER_FRAME;
328 
329     // fill ring buffer with silence while stream is paused
330     if (audio_stream_paused){
331         if (btstack_ring_buffer_bytes_available(&ring_buffer) < PREBUFFER_BYTES){
332             memset(outputBuffer, 0, bytes_to_copy);
333             return 0;
334         } else {
335             // resume playback
336             audio_stream_paused = 0;
337         }
338     }
339 
340     // get data from ring buffer
341     uint32_t bytes_read = 0;
342     btstack_ring_buffer_read(&ring_buffer, outputBuffer, bytes_to_copy, &bytes_read);
343     bytes_to_copy -= bytes_read;
344 
345     // fill ring buffer  with silence if there are not enough bytes to copy
346     if (bytes_to_copy){
347         memset(outputBuffer + bytes_read, 0, bytes_to_copy);
348         audio_stream_paused = 1;
349     }
350     return 0;
351 }
352 #endif
353 
354 #ifdef HAVE_AUDIO_DMA
355 static int next_buffer(int current){
356 	if (current == NUM_AUDIO_BUFFERS-1) return 0;
357 	return current + 1;
358 }
359 static uint8_t * start_of_buffer(int num){
360 	return (uint8_t *) &audio_samples[num * DMA_AUDIO_FRAMES * 2];
361 }
362 void hal_audio_dma_done(void){
363 	if (audio_stream_paused){
364 		hal_audio_dma_play((const uint8_t *) silent_buffer, DMA_AUDIO_FRAMES*4);
365 		return;
366 	}
367 	// next buffer
368 	int next_playback_buffer = next_buffer(playback_buffer);
369 	uint8_t * playback_data;
370 	if (next_playback_buffer == write_buffer){
371 
372 		// TODO: stop codec while playing silence when getting 'stream paused'
373 
374 		// start playing silence
375 		audio_stream_paused = 1;
376 		hal_audio_dma_play((const uint8_t *) silent_buffer, DMA_AUDIO_FRAMES*4);
377 		printf("%6u - paused - bytes in buffer %u\n", (int) btstack_run_loop_get_time_ms(), btstack_ring_buffer_bytes_available(&ring_buffer));
378 		return;
379 	}
380 	playback_buffer = next_playback_buffer;
381 	playback_data = start_of_buffer(playback_buffer);
382 	hal_audio_dma_play(playback_data, audio_samples_len[playback_buffer]);
383     // btstack_run_loop_embedded_trigger();
384 }
385 #endif
386 
387 
388 #ifdef HAVE_AUDIO_DMA
389 static void hal_audio_dma_process(btstack_data_source_t * ds, btstack_data_source_callback_type_t callback_type){
390 	UNUSED(ds);
391 	UNUSED(callback_type);
392 
393 	if (!media_initialized) return;
394 
395 	int trigger_resume = 0;
396 	if (audio_stream_paused) {
397 		if (sbc_frame_size && btstack_ring_buffer_bytes_available(&ring_buffer) >= OPTIMAL_FRAMES_MIN * sbc_frame_size){
398 			trigger_resume = 1;
399 			// reset buffers
400 			playback_buffer = NUM_AUDIO_BUFFERS - 1;
401 			write_buffer = 0;
402 		} else {
403 			return;
404 		}
405 	}
406 
407 	while (playback_buffer != write_buffer && btstack_ring_buffer_bytes_available(&ring_buffer) >= sbc_frame_size ){
408 		uint8_t frame[MAX_SBC_FRAME_SIZE];
409 	    uint32_t bytes_read = 0;
410 	    btstack_ring_buffer_read(&ring_buffer, frame, sbc_frame_size, &bytes_read);
411 	    btstack_sbc_decoder_process_data(&state, 0, frame, sbc_frame_size);
412 	}
413 
414 	if (trigger_resume){
415 		printf("%6u - resume\n", (int) btstack_run_loop_get_time_ms());
416 		audio_stream_paused = 0;
417 	}
418 }
419 #endif
420 
421 static int media_processing_init(avdtp_media_codec_configuration_sbc_t configuration){
422     if (media_initialized) return 0;
423 #ifdef DECODE_SBC
424     btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL);
425 #endif
426 
427 #ifdef STORE_SBC_TO_WAV_FILE
428     wav_writer_open(wav_filename, configuration.num_channels, configuration.sampling_frequency);
429 #endif
430 
431 #ifdef STORE_SBC_TO_SBC_FILE
432    sbc_file = fopen(sbc_filename, "wb");
433 #endif
434 
435 #ifdef HAVE_PORTAUDIO
436     // int frames_per_buffer = configuration.frames_per_buffer;
437     PaError err;
438     PaStreamParameters outputParameters;
439     const PaDeviceInfo *deviceInfo;
440 
441     /* -- initialize PortAudio -- */
442     err = Pa_Initialize();
443     if (err != paNoError){
444         printf("Error initializing portaudio: \"%s\"\n",  Pa_GetErrorText(err));
445         return err;
446     }
447     /* -- setup input and output -- */
448     outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
449     outputParameters.channelCount = configuration.num_channels;
450     outputParameters.sampleFormat = PA_SAMPLE_TYPE;
451     outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
452     outputParameters.hostApiSpecificStreamInfo = NULL;
453     deviceInfo = Pa_GetDeviceInfo( outputParameters.device );
454     printf("PortAudio: Output device: %s\n", deviceInfo->name);
455     log_info("PortAudio: Output device: %s", deviceInfo->name);
456     /* -- setup stream -- */
457     err = Pa_OpenStream(
458            &stream,
459            NULL,                /* &inputParameters */
460            &outputParameters,
461 		   configuration.sampling_frequency,
462            0,
463            paClipOff,           /* we won't output out of range samples so don't bother clipping them */
464            portaudio_callback,      /* use callback */
465            NULL );
466 
467     if (err != paNoError){
468         printf("Error initializing portaudio: \"%s\"\n",  Pa_GetErrorText(err));
469         return err;
470     }
471     log_info("PortAudio: stream opened");
472     printf("PortAudio: stream opened\n");
473 #endif
474 #ifdef HAVE_AUDIO_DMA
475     audio_stream_paused  = 1;
476     hal_audio_dma_init(configuration.sampling_frequency);
477     hal_audio_dma_set_audio_played(&hal_audio_dma_done);
478     // start playing silence
479     hal_audio_dma_done();
480 #endif
481 
482  #if defined(HAVE_PORTAUDIO) || defined (HAVE_AUDIO_DMA)
483     memset(ring_buffer_storage, 0, sizeof(ring_buffer_storage));
484     btstack_ring_buffer_init(&ring_buffer, ring_buffer_storage, sizeof(ring_buffer_storage));
485     audio_stream_started = 0;
486     audio_stream_paused = 0;
487 #endif
488     media_initialized = 1;
489     return 0;
490 }
491 
492 static void media_processing_close(void){
493     if (!media_initialized) return;
494     media_initialized = 0;
495 
496 #ifdef STORE_SBC_TO_WAV_FILE
497     wav_writer_close();
498     int total_frames_nr = state.good_frames_nr + state.bad_frames_nr + state.zero_frames_nr;
499 
500     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);
501     printf("WAV Writer: Written %d frames to wav file: %s\n", frame_count, wav_filename);
502 #endif
503 
504 #ifdef STORE_SBC_TO_SBC_FILE
505     fclose(sbc_file);
506 #endif
507 
508 #if defined(HAVE_PORTAUDIO) || defined (HAVE_AUDIO_DMA)
509     audio_stream_started = 0;
510 #endif
511 
512 #ifdef HAVE_PORTAUDIO
513     printf("PortAudio: Steram closed\n");
514     log_info("PortAudio: Stream closed");
515 
516     PaError err = Pa_StopStream(stream);
517     if (err != paNoError){
518         printf("Error stopping the stream: \"%s\"\n",  Pa_GetErrorText(err));
519         log_error("Error stopping the stream: \"%s\"",  Pa_GetErrorText(err));
520         return;
521     }
522     err = Pa_CloseStream(stream);
523     if (err != paNoError){
524         printf("Error closing the stream: \"%s\"\n",  Pa_GetErrorText(err));
525         log_error("Error closing the stream: \"%s\"",  Pa_GetErrorText(err));
526         return;
527     }
528     err = Pa_Terminate();
529     if (err != paNoError){
530         printf("Error terminating portaudio: \"%s\"\n",  Pa_GetErrorText(err));
531         log_error("Error terminating portaudio: \"%s\"",  Pa_GetErrorText(err));
532         return;
533     }
534 #endif
535 
536 #ifdef HAVE_AUDIO_DMA
537     hal_audio_dma_close();
538 #endif
539 }
540 
541 
542 /* @section Handle Media Data Packet
543  *
544  * @text Media data packets, in this case the audio data, are received through the handle_l2cap_media_data_packet callback.
545  * Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet.
546  * The SBC data will be decoded using an SBC decoder if either HAVE_PORTAUDIO or STORE_SBC_TO_WAV_FILE directive is defined.
547  * The resulting PCM frames can be then captured through a PCM data callback registered during SBC decoder setup, i.e. the
548  * handle_pcm_data callback.
549  */
550 
551 static int read_media_data_header(uint8_t * packet, int size, int * offset, avdtp_media_packet_header_t * media_header);
552 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header);
553 
554 static void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size){
555     UNUSED(seid);
556     int pos = 0;
557 
558     avdtp_media_packet_header_t media_header;
559     if (!read_media_data_header(packet, size, &pos, &media_header)) return;
560 
561     avdtp_sbc_codec_header_t sbc_header;
562     if (!read_sbc_header(packet, size, &pos, &sbc_header)) return;
563 
564 #ifdef HAVE_AUDIO_DMA
565     // store sbc frame size for buffer management
566     sbc_frame_size = (size-pos)/ sbc_header.num_frames;
567 #endif
568 
569 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE)
570     btstack_sbc_decoder_process_data(&state, 0, packet+pos, size-pos);
571 #endif
572 
573 #ifdef HAVE_AUDIO_DMA
574     btstack_ring_buffer_write(&ring_buffer,  packet+pos, size-pos);
575 
576     // decide on audio sync drift based on number of sbc frames in queue
577     int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&ring_buffer) / sbc_frame_size;
578     if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN){
579     	sbc_samples_fix = 1;	// duplicate last sample
580     } else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX){
581     	sbc_samples_fix = 0;	// nothing to do
582     } else {
583     	sbc_samples_fix = -1;	// drop last sample
584     }
585 
586     // dump
587     printf("%6u %03u %d\n",  (int) btstack_run_loop_get_time_ms(), sbc_frames_in_buffer, sbc_samples_fix);
588 #endif
589 
590 #ifdef STORE_SBC_TO_SBC_FILE
591     fwrite(packet+pos, size-pos, 1, sbc_file);
592 #endif
593 }
594 
595  /* @section Handle PCM Data
596  *
597  * @text In this example, we use the [PortAudio library](http://www.portaudio.com) to play the audio stream.
598  * The PCM data are bufferd in a ring buffer.
599  * Aditionally, tha audio data can be stored in the avdtp_sink.wav file.
600  */
601 #if defined(HAVE_PORTAUDIO) || defined(STORE_SBC_TO_WAV_FILE) || defined(HAVE_AUDIO_DMA)
602 static void handle_pcm_data(int16_t * data, int num_samples, int num_channels, int sample_rate, void * context){
603     UNUSED(sample_rate);
604     UNUSED(context);
605 
606 #ifdef STORE_SBC_TO_WAV_FILE
607     wav_writer_write_int16(num_samples*num_channels, data);
608     frame_count++;
609 #endif
610 
611 #ifdef HAVE_PORTAUDIO
612     // store pcm samples in ring buffer
613     btstack_ring_buffer_write(&ring_buffer, (uint8_t *)data, num_samples*num_channels*2);
614 
615     if (!audio_stream_started){
616         audio_stream_paused  = 1;
617         /* -- start stream -- */
618         PaError err = Pa_StartStream(stream);
619         if (err != paNoError){
620             printf("Error starting the stream: \"%s\"\n",  Pa_GetErrorText(err));
621             return;
622         }
623         audio_stream_started = 1;
624     }
625 #endif
626 
627 #ifdef HAVE_AUDIO_DMA
628     // store in ring buffer
629     uint8_t * write_data = start_of_buffer(write_buffer);
630     uint16_t len = num_samples*num_channels*2;
631     memcpy(write_data, data, len);
632     audio_samples_len[write_buffer] = len;
633 
634     // add/drop audio frame to fix drift
635     if (sbc_samples_fix > 0){
636         memcpy(write_data + len, write_data + len - 4, 4);
637         audio_samples_len[write_buffer] += 4;
638     }
639     if (sbc_samples_fix < 0){
640         audio_samples_len[write_buffer] -= 4;
641     }
642 
643     write_buffer = next_buffer(write_buffer);
644 #endif
645 }
646 #endif
647 
648 static int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header){
649     int sbc_header_len = 12; // without crc
650     int pos = *offset;
651 
652     if (size - pos < sbc_header_len){
653         printf("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size-pos);
654         return 1;
655     }
656 
657     sbc_header->fragmentation = get_bit16(packet[pos], 7);
658     sbc_header->starting_packet = get_bit16(packet[pos], 6);
659     sbc_header->last_packet = get_bit16(packet[pos], 5);
660     sbc_header->num_frames = packet[pos] & 0x0f;
661     pos++;
662     // 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);
663     *offset = pos;
664     return 0;
665 }
666 
667 static int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header){
668     int media_header_len = 12; // without crc
669     int pos = *offset;
670 
671     if (size - pos < media_header_len){
672         printf("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size-pos);
673         return 1;
674     }
675 
676     media_header->version = packet[pos] & 0x03;
677     media_header->padding = get_bit16(packet[pos],2);
678     media_header->extension = get_bit16(packet[pos],3);
679     media_header->csrc_count = (packet[pos] >> 4) & 0x0F;
680     pos++;
681 
682     media_header->marker = get_bit16(packet[pos],0);
683     media_header->payload_type  = (packet[pos] >> 1) & 0x7F;
684     pos++;
685 
686     media_header->sequence_number = big_endian_read_16(packet, pos);
687     pos+=2;
688 
689     media_header->timestamp = big_endian_read_32(packet, pos);
690     pos+=4;
691 
692     media_header->synchronization_source = big_endian_read_32(packet, pos);
693     pos+=4;
694     *offset = pos;
695     // TODO: read csrc list
696 
697     // printf_hexdump( packet, pos );
698     // printf("MEDIA HEADER: %u timestamp, version %u, padding %u, extension %u, csrc_count %u\n",
699     //     media_header->timestamp, media_header->version, media_header->padding, media_header->extension, media_header->csrc_count);
700     // printf("MEDIA HEADER: marker %02x, payload_type %02x, sequence_number %u, synchronization_source %u\n",
701     //     media_header->marker, media_header->payload_type, media_header->sequence_number, media_header->synchronization_source);
702     return 0;
703 }
704 
705 static void dump_sbc_configuration(avdtp_media_codec_configuration_sbc_t configuration){
706     printf("Received SBC configuration:\n");
707     printf("    - num_channels: %d\n", configuration.num_channels);
708     printf("    - sampling_frequency: %d\n", configuration.sampling_frequency);
709     printf("    - channel_mode: %d\n", configuration.channel_mode);
710     printf("    - block_length: %d\n", configuration.block_length);
711     printf("    - subbands: %d\n", configuration.subbands);
712     printf("    - allocation_method: %d\n", configuration.allocation_method);
713     printf("    - bitpool_value [%d, %d] \n", configuration.min_bitpool_value, configuration.max_bitpool_value);
714     printf("\n");
715 }
716 
717 static void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
718     UNUSED(channel);
719     UNUSED(size);
720     uint16_t local_cid;
721     uint8_t  status = 0xFF;
722     bd_addr_t adress;
723 
724     if (packet_type != HCI_EVENT_PACKET) return;
725     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
726     switch (packet[2]){
727         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
728             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
729             if (avrcp_cid != 0 && avrcp_cid != local_cid) {
730                 printf("AVRCP demo: Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_cid, local_cid);
731                 return;
732             }
733 
734             status = avrcp_subevent_connection_established_get_status(packet);
735             if (status != ERROR_CODE_SUCCESS){
736                 printf("AVRCP demo: Connection failed: status 0x%02x\n", status);
737                 avrcp_cid = 0;
738                 return;
739             }
740 
741             avrcp_cid = local_cid;
742             avrcp_connected = 1;
743             avrcp_subevent_connection_established_get_bd_addr(packet, adress);
744             printf("AVRCP demo: Channel successfully opened: %s, avrcp_cid 0x%02x\n", bd_addr_to_str(adress), avrcp_cid);
745 
746             // automatically enable notifications
747             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
748             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
749             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
750             avrcp_controller_enable_notification(avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
751             return;
752         }
753         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
754             printf("AVRCP demo: Channel released: avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
755             avrcp_cid = 0;
756             avrcp_connected = 0;
757             return;
758         default:
759             break;
760     }
761 
762     status = packet[5];
763     if (!avrcp_cid) return;
764 
765     // ignore INTERIM status
766     if (status == AVRCP_CTYPE_RESPONSE_INTERIM) return;
767 
768     printf("AVRCP demo: command status: %s, ", avrcp_ctype2str(status));
769     switch (packet[2]){
770         case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
771             printf("notification, playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
772             return;
773         case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
774             printf("notification, playing content changed\n");
775             return;
776         case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
777             printf("notification track changed\n");
778             return;
779         case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
780             printf("notification absolute volume changed %d\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet));
781             return;
782         case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
783             printf("notification changed\n");
784             return;
785         case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE:{
786             uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
787             uint8_t repeat_mode  = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
788             printf("%s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
789             break;
790         }
791         case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO:
792             if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0){
793                 memcpy(value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet));
794                 printf("    Title: %s\n", value);
795             }
796             break;
797 
798         case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO:
799             if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0){
800                 memcpy(value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet));
801                 printf("    Artist: %s\n", value);
802             }
803             break;
804 
805         case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO:
806             if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0){
807                 memcpy(value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet));
808                 printf("    Album: %s\n", value);
809             }
810             break;
811 
812         case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO:
813             if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0){
814                 memcpy(value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet));
815                 printf("    Genre: %s\n", value);
816             }
817             break;
818 
819         case AVRCP_SUBEVENT_PLAY_STATUS:
820             printf("song length: %d ms, song position: %d ms, play status: %s\n",
821                 avrcp_subevent_play_status_get_song_length(packet),
822                 avrcp_subevent_play_status_get_song_position(packet),
823                 avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
824             break;
825         case AVRCP_SUBEVENT_OPERATION_COMPLETE:
826             printf("operation done %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
827             break;
828         case AVRCP_SUBEVENT_OPERATION_START:
829             printf("operation start %s\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
830             break;
831         case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
832             // response to set shuffle and repeat mode
833             printf("\n");
834             break;
835         default:
836             printf("AVRCP demo: event is not parsed\n");
837             break;
838     }
839 }
840 
841 static void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
842     UNUSED(channel);
843     UNUSED(size);
844     uint16_t cid;
845     bd_addr_t address;
846     uint8_t status;
847 
848     if (packet_type != HCI_EVENT_PACKET) return;
849     if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return;
850 
851     switch (packet[2]){
852         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
853             printf("A2DP Sink demo: received non SBC codec. not implemented.\n");
854             break;
855         case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION:{
856             printf("A2DP Sink demo: received SBC codec configuration.\n");
857             sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
858             sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
859             sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
860             sbc_configuration.channel_mode = a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
861             sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
862             sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
863             sbc_configuration.allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
864             sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
865             sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
866             sbc_configuration.frames_per_buffer = sbc_configuration.subbands * sbc_configuration.block_length;
867             dump_sbc_configuration(sbc_configuration);
868 
869             if (sbc_configuration.reconfigure){
870                 media_processing_close();
871             }
872             // prepare media processing
873             media_processing_init(sbc_configuration);
874             break;
875         }
876         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
877             a2dp_subevent_stream_established_get_bd_addr(packet, address);
878             status = a2dp_subevent_stream_established_get_status(packet);
879             cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
880             printf("A2DP_SUBEVENT_STREAM_ESTABLISHED %d, %d \n", cid, a2dp_cid);
881             if (!a2dp_cid){
882                 // incoming connection
883                 a2dp_cid = cid;
884             } else if (cid != a2dp_cid) {
885                 break;
886             }
887             if (status){
888                 a2dp_sink_connected = 0;
889                 printf("A2DP Sink demo: streaming connection failed, status 0x%02x\n", status);
890                 break;
891             }
892             printf("A2DP Sink demo: streaming connection is established, address %s, a2dp cid 0x%02X, local_seid %d\n", bd_addr_to_str(address), a2dp_cid, local_seid);
893 
894             memcpy(device_addr, address, 6);
895             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
896             a2dp_sink_connected = 1;
897             break;
898 
899         case A2DP_SUBEVENT_STREAM_STARTED:
900             cid = a2dp_subevent_stream_started_get_a2dp_cid(packet);
901             if (cid != a2dp_cid) break;
902             local_seid = a2dp_subevent_stream_started_get_local_seid(packet);
903             printf("A2DP Sink demo: stream started, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
904             // started
905             media_processing_init(sbc_configuration);
906             break;
907 
908         case A2DP_SUBEVENT_STREAM_SUSPENDED:
909             cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet);
910             if (cid != a2dp_cid) break;
911             local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet);
912             printf("A2DP Sink demo: stream paused, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
913             media_processing_close();
914             break;
915 
916         case A2DP_SUBEVENT_STREAM_RELEASED:
917             cid = a2dp_subevent_stream_released_get_a2dp_cid(packet);
918             if (cid != a2dp_cid) {
919                 printf("A2DP Sink demo: unexpected cid 0x%02x instead of 0x%02x\n", cid, a2dp_cid);
920                 break;
921             }
922             local_seid = a2dp_subevent_stream_released_get_local_seid(packet);
923             printf("A2DP Sink demo: stream released, a2dp cid 0x%02X, local_seid %d\n", a2dp_cid, local_seid);
924             media_processing_close();
925             break;
926         case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
927             cid = a2dp_subevent_signaling_connection_released_get_a2dp_cid(packet);
928             if (cid != a2dp_cid) {
929                 printf("A2DP Sink demo: unexpected cid 0x%02x instead of 0x%02x\n", cid, a2dp_cid);
930                 break;
931             }
932             a2dp_sink_connected = 0;
933             printf("A2DP Sink demo: signaling connection released\n");
934             break;
935         default:
936             printf("A2DP Sink demo: not parsed 0x%02x\n", packet[2]);
937             break;
938     }
939 }
940 
941 #ifdef HAVE_BTSTACK_STDIN
942 static void show_usage(void){
943     bd_addr_t      iut_address;
944     gap_local_bd_addr(iut_address);
945     printf("\n--- Bluetooth AVDTP Sink/AVRCP Connection Test Console %s ---\n", bd_addr_to_str(iut_address));
946     printf("b      - AVDTP Sink create  connection to addr %s\n", bd_addr_to_str(device_addr));
947     printf("B      - AVDTP Sink disconnect\n");
948     printf("c      - AVRCP create connection to addr %s\n", bd_addr_to_str(device_addr));
949     printf("C      - AVRCP disconnect\n");
950 
951     printf("\n--- Bluetooth AVRCP Commands %s ---\n", bd_addr_to_str(iut_address));
952     printf("O - get play status\n");
953     printf("j - get now playing info\n");
954     printf("k - play\n");
955     printf("K - stop\n");
956     printf("L - pause\n");
957     printf("u - start fast forward\n");
958     printf("U - stop  fast forward\n");
959     printf("n - start rewind\n");
960     printf("N - stop rewind\n");
961     printf("i - forward\n");
962     printf("I - backward\n");
963     printf("t - volume up\n");
964     printf("T - volume down\n");
965     printf("p - absolute volume of 50 percent\n");
966     printf("M - mute\n");
967     printf("r - skip\n");
968     printf("q - query repeat and shuffle mode\n");
969     printf("v - repeat single track\n");
970     printf("x - repeat all tracks\n");
971     printf("X - disable repeat mode\n");
972     printf("z - shuffle all tracks\n");
973     printf("Z - disable shuffle mode\n");
974     printf("---\n");
975 }
976 #endif
977 
978 #ifdef HAVE_BTSTACK_STDIN
979 static void stdin_process(char cmd){
980     uint8_t status = ERROR_CODE_SUCCESS;
981     printf("stdin_process \n");
982     if (!avrcp_connected){
983         switch (cmd){
984             case 'b':
985             case 'B':
986             case 'c':
987                 break;
988             default:
989                 printf("Command '%c' cannot be performed - please use 'c' to establish an AVRCP connection with device (addr %s).\n", cmd, bd_addr_to_str(device_addr));
990                 return;
991         }
992 
993     }
994 
995     switch (cmd){
996         case 'b':
997             status = a2dp_sink_establish_stream(device_addr, local_seid, &a2dp_cid);
998             printf(" - Create AVDTP connection to addr %s, and local seid %d, expected cid 0x%02x.\n", bd_addr_to_str(device_addr), local_seid, a2dp_cid);
999             break;
1000         case 'B':
1001             printf(" - AVDTP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
1002             status = avdtp_sink_disconnect(a2dp_cid);
1003             break;
1004         case 'c':
1005             printf(" - Create AVRCP connection to addr %s.\n", bd_addr_to_str(device_addr));
1006             status = avrcp_controller_connect(device_addr, &avrcp_cid);
1007             break;
1008         case 'C':
1009             printf(" - AVRCP disconnect from addr %s.\n", bd_addr_to_str(device_addr));
1010             status = avrcp_controller_disconnect(avrcp_cid);
1011             break;
1012 
1013         case '\n':
1014         case '\r':
1015             break;
1016         case 'O':
1017             printf(" - get play status\n");
1018             status = avrcp_controller_get_play_status(avrcp_cid);
1019             break;
1020         case 'j':
1021             printf(" - get now playing info\n");
1022             status = avrcp_controller_get_now_playing_info(avrcp_cid);
1023             break;
1024         case 'k':
1025             printf(" - play\n");
1026             status = avrcp_controller_play(avrcp_cid);
1027             break;
1028         case 'K':
1029             printf(" - stop\n");
1030             status = avrcp_controller_stop(avrcp_cid);
1031             break;
1032         case 'L':
1033             printf(" - pause\n");
1034             status = avrcp_controller_pause(avrcp_cid);
1035             break;
1036         case 'u':
1037             printf(" - start fast forward\n");
1038             status = avrcp_controller_start_fast_forward(avrcp_cid);
1039             break;
1040         case 'U':
1041             printf(" - stop fast forward\n");
1042             status = avrcp_controller_stop_fast_forward(avrcp_cid);
1043             break;
1044         case 'n':
1045             printf(" - start rewind\n");
1046             status = avrcp_controller_start_rewind(avrcp_cid);
1047             break;
1048         case 'N':
1049             printf(" - stop rewind\n");
1050             status = avrcp_controller_stop_rewind(avrcp_cid);
1051             break;
1052         case 'i':
1053             printf(" - forward\n");
1054             status = avrcp_controller_forward(avrcp_cid);
1055             break;
1056         case 'I':
1057             printf(" - backward\n");
1058             status = avrcp_controller_backward(avrcp_cid);
1059             break;
1060         case 't':
1061             printf(" - volume up\n");
1062             status = avrcp_controller_volume_up(avrcp_cid);
1063             break;
1064         case 'T':
1065             printf(" - volume down\n");
1066             status = avrcp_controller_volume_down(avrcp_cid);
1067             break;
1068         case 'p':
1069             printf(" - absolute volume of 50 percent\n");
1070             status = avrcp_controller_set_absolute_volume(avrcp_cid, 50);
1071             break;
1072         case 'M':
1073             printf(" - mute\n");
1074             status = avrcp_controller_mute(avrcp_cid);
1075             break;
1076         case 'r':
1077             printf(" - skip\n");
1078             status = avrcp_controller_skip(avrcp_cid);
1079             break;
1080         case 'q':
1081             printf(" - query repeat and shuffle mode\n");
1082             status = avrcp_controller_query_shuffle_and_repeat_modes(avrcp_cid);
1083             break;
1084         case 'v':
1085             printf(" - repeat single track\n");
1086             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_SINGLE_TRACK);
1087             break;
1088         case 'x':
1089             printf(" - repeat all tracks\n");
1090             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_ALL_TRACKS);
1091             break;
1092         case 'X':
1093             printf(" - disable repeat mode\n");
1094             status = avrcp_controller_set_repeat_mode(avrcp_cid, AVRCP_REPEAT_MODE_OFF);
1095             break;
1096         case 'z':
1097             printf(" - shuffle all tracks\n");
1098             status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_ALL_TRACKS);
1099             break;
1100         case 'Z':
1101             printf(" - disable shuffle mode\n");
1102             status = avrcp_controller_set_shuffle_mode(avrcp_cid, AVRCP_SHUFFLE_MODE_OFF);
1103             break;
1104         default:
1105             show_usage();
1106             return;
1107     }
1108     if (status != ERROR_CODE_SUCCESS){
1109         printf("Could not perform command, status 0x%2x\n", status);
1110     }
1111 }
1112 #endif
1113 
1114 int btstack_main(int argc, const char * argv[]);
1115 int btstack_main(int argc, const char * argv[]){
1116     (void)argc;
1117     (void)argv;
1118 
1119     int err = a2dp_sink_and_avrcp_services_init();
1120     if (err) return err;
1121     // turn on!
1122     printf("Starting BTstack ...\n");
1123     hci_power_control(HCI_POWER_ON);
1124     return 0;
1125 }
1126 /* EXAMPLE_END */
1127