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