xref: /btstack/example/a2dp_source_demo.c (revision 831d3fd526fe25efb57f33af977cfc14509d4f3a)
1 /*
2  * Copyright (C) 2016 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 
39 #include <stdint.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #include "btstack.h"
45 
46 #include "hxcmod.h"
47 #include "mods/mod.h"
48 
49 #define NUM_CHANNELS                2
50 #define A2DP_SAMPLE_RATE            44100
51 #define BYTES_PER_AUDIO_SAMPLE      (2*NUM_CHANNELS)
52 #define AUDIO_TIMEOUT_MS            10
53 #define TABLE_SIZE_441HZ            100
54 
55 typedef enum {
56     STREAM_SINE,
57     STREAM_MOD
58 } stream_data_source_t;
59 
60 typedef struct {
61     uint16_t a2dp_cid;
62     uint8_t  local_seid;
63 
64     uint32_t time_audio_data_sent; // ms
65     uint32_t acc_num_missed_samples;
66     uint32_t samples_ready;
67     btstack_timer_source_t audio_timer;
68     uint8_t  streaming;
69     int      max_media_payload_size;
70 
71     uint8_t  sbc_storage[1030];
72     uint16_t sbc_storage_count;
73     uint8_t  sbc_ready_to_send;
74 } a2dp_media_sending_context_t;
75 
76 static  uint8_t media_sbc_codec_capabilities[] = {
77     (AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
78     0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
79     2, 53
80 };
81 
82 static const int16_t sine_int16[] = {
83      0,    2057,    4107,    6140,    8149,   10126,   12062,   13952,   15786,   17557,
84  19260,   20886,   22431,   23886,   25247,   26509,   27666,   28714,   29648,   30466,
85  31163,   31738,   32187,   32509,   32702,   32767,   32702,   32509,   32187,   31738,
86  31163,   30466,   29648,   28714,   27666,   26509,   25247,   23886,   22431,   20886,
87  19260,   17557,   15786,   13952,   12062,   10126,    8149,    6140,    4107,    2057,
88      0,   -2057,   -4107,   -6140,   -8149,  -10126,  -12062,  -13952,  -15786,  -17557,
89 -19260,  -20886,  -22431,  -23886,  -25247,  -26509,  -27666,  -28714,  -29648,  -30466,
90 -31163,  -31738,  -32187,  -32509,  -32702,  -32767,  -32702,  -32509,  -32187,  -31738,
91 -31163,  -30466,  -29648,  -28714,  -27666,  -26509,  -25247,  -23886,  -22431,  -20886,
92 -19260,  -17557,  -15786,  -13952,  -12062,  -10126,   -8149,   -6140,   -4107,   -2057,
93 };
94 
95 static const char * device_name = "A2DP Source Demo 00:00:00:00:00:00";
96 static btstack_packet_callback_registration_t hci_event_callback_registration;
97 
98 // mac 2011:    static const char * device_addr_string = "04:0C:CE:E4:85:D3";
99 // pts:         static const char * device_addr_string = "00:1B:DC:08:0A:A5";
100 // mac 2013:    static const char * device_addr_string = "84:38:35:65:d1:15";
101 // phone 2013:  static const char * device_addr_string = "D8:BB:2C:DF:F0:F2";
102 // minijambox:  static const char * device_addr_string = "00:21:3C:AC:F7:38";
103 // head phones: static const char * device_addr_string = "00:18:09:28:50:18";
104 // bt dongle:   static const char * device_addr_string = "00:15:83:5F:9D:46";
105 // RT-B6
106 static const char * device_addr_string = "00:75:58:FF:C9:7D";
107 
108 static bd_addr_t device_addr;
109 static uint8_t sdp_a2dp_source_service_buffer[150];
110 static uint8_t media_sbc_codec_configuration[4];
111 static a2dp_media_sending_context_t media_tracker;
112 
113 static uint16_t avrcp_cid;
114 
115 static stream_data_source_t data_source;
116 
117 static int sine_phase;
118 
119 static int hxcmod_initialized;
120 static modcontext mod_context;
121 static tracker_buffer_state trkbuf;
122 
123 
124 /* AVRCP Target context START */
125 static const uint8_t subunit_info[] = {
126     0,0,0,0,
127     1,1,1,1,
128     2,2,2,2,
129     3,3,3,3,
130     4,4,4,4,
131     5,5,5,5,
132     6,6,6,6,
133     7,7,7,7
134 };
135 
136 static uint32_t company_id = 0x112233;
137 static uint8_t companies_num = 1;
138 static uint8_t companies[] = {
139     0x00, 0x19, 0x58 //BT SIG registered CompanyID
140 };
141 
142 static uint8_t events_num = 13;
143 static uint8_t events[] = {
144     AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED,
145     AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED,
146     AVRCP_NOTIFICATION_EVENT_TRACK_REACHED_END,
147     AVRCP_NOTIFICATION_EVENT_TRACK_REACHED_START,
148     AVRCP_NOTIFICATION_EVENT_PLAYBACK_POS_CHANGED,
149     AVRCP_NOTIFICATION_EVENT_BATT_STATUS_CHANGED,
150     AVRCP_NOTIFICATION_EVENT_SYSTEM_STATUS_CHANGED,
151     AVRCP_NOTIFICATION_EVENT_PLAYER_APPLICATION_SETTING_CHANGED,
152     AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED,
153     AVRCP_NOTIFICATION_EVENT_AVAILABLE_PLAYERS_CHANGED,
154     AVRCP_NOTIFICATION_EVENT_ADDRESSED_PLAYER_CHANGED,
155     AVRCP_NOTIFICATION_EVENT_UIDS_CHANGED,
156     AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED
157 };
158 
159 typedef struct {
160     char title[40];
161     char artist[40];
162     char album[40];
163     char genre[40];
164     uint32_t song_length_ms;
165     int total_tracks;
166     int track_nr;
167 } avrcp_now_playing_info_t;
168 
169 typedef struct {
170     avrcp_play_status_t status;
171     uint32_t song_length_ms;   // 0xFFFFFFFF if not supported
172     uint32_t song_position_ms; // 0xFFFFFFFF if not supported
173 } avrcp_play_status_info_t;
174 
175 avrcp_now_playing_info_t now_playing_info;
176 avrcp_play_status_info_t play_info;
177 
178 /* AVRCP Target context END */
179 
180 static void a2dp_demo_send_media_packet(void){
181     int num_bytes_in_frame = btstack_sbc_encoder_sbc_buffer_length();
182     int bytes_in_storage = media_tracker.sbc_storage_count;
183     uint8_t num_frames = bytes_in_storage / num_bytes_in_frame;
184     a2dp_source_stream_send_media_payload(media_tracker.a2dp_cid, media_tracker.local_seid, media_tracker.sbc_storage, bytes_in_storage, num_frames, 0);
185     media_tracker.sbc_storage_count = 0;
186     media_tracker.sbc_ready_to_send = 0;
187 }
188 
189 static void produce_sine_audio(int16_t * pcm_buffer, int num_samples_to_write){
190     int count;
191     for (count = 0; count < num_samples_to_write ; count++){
192         pcm_buffer[count * 2]     = sine_int16[sine_phase];
193         pcm_buffer[count * 2 + 1] = sine_int16[sine_phase];
194         sine_phase++;
195         if (sine_phase >= TABLE_SIZE_441HZ){
196             sine_phase -= TABLE_SIZE_441HZ;
197         }
198     }
199 }
200 
201 static void produce_mod_audio(int16_t * pcm_buffer, int num_samples_to_write){
202     hxcmod_fillbuffer(&mod_context, (unsigned short *) &pcm_buffer[0], num_samples_to_write, &trkbuf);
203 }
204 
205 static void produce_audio(int16_t * pcm_buffer, int num_samples){
206     switch (data_source){
207         case STREAM_SINE:
208             produce_sine_audio(pcm_buffer, num_samples);
209             break;
210         case STREAM_MOD:
211             produce_mod_audio(pcm_buffer, num_samples);
212             break;
213     }
214 }
215 
216 static int a2dp_demo_fill_sbc_audio_buffer(a2dp_media_sending_context_t * context){
217     // perform sbc encodin
218     int total_num_bytes_read = 0;
219     unsigned int num_audio_samples_per_sbc_buffer = btstack_sbc_encoder_num_audio_frames();
220     while (context->samples_ready >= num_audio_samples_per_sbc_buffer
221         && (context->max_media_payload_size - context->sbc_storage_count) >= btstack_sbc_encoder_sbc_buffer_length()){
222 
223         int16_t pcm_frame[256*NUM_CHANNELS];
224 
225         produce_audio(pcm_frame, num_audio_samples_per_sbc_buffer);
226         btstack_sbc_encoder_process_data(pcm_frame);
227 
228         uint16_t sbc_frame_size = btstack_sbc_encoder_sbc_buffer_length();
229         uint8_t * sbc_frame = btstack_sbc_encoder_sbc_buffer();
230 
231         total_num_bytes_read += num_audio_samples_per_sbc_buffer;
232         memcpy(&context->sbc_storage[context->sbc_storage_count], sbc_frame, sbc_frame_size);
233         context->sbc_storage_count += sbc_frame_size;
234         context->samples_ready -= num_audio_samples_per_sbc_buffer;
235     }
236     return total_num_bytes_read;
237 }
238 
239 static void a2dp_demo_audio_timeout_handler(btstack_timer_source_t * timer){
240     a2dp_media_sending_context_t * context = (a2dp_media_sending_context_t *) btstack_run_loop_get_timer_context(timer);
241     btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
242     btstack_run_loop_add_timer(&context->audio_timer);
243     uint32_t now = btstack_run_loop_get_time_ms();
244 
245     uint32_t update_period_ms = AUDIO_TIMEOUT_MS;
246     if (context->time_audio_data_sent > 0){
247         update_period_ms = now - context->time_audio_data_sent;
248     }
249 
250     uint32_t num_samples = (update_period_ms * A2DP_SAMPLE_RATE) / 1000;
251     context->acc_num_missed_samples += (update_period_ms * A2DP_SAMPLE_RATE) % 1000;
252 
253     while (context->acc_num_missed_samples >= 1000){
254         num_samples++;
255         context->acc_num_missed_samples -= 1000;
256     }
257     context->time_audio_data_sent = now;
258     context->samples_ready += num_samples;
259 
260     if (context->sbc_ready_to_send) return;
261 
262     a2dp_demo_fill_sbc_audio_buffer(context);
263 
264     if ((context->sbc_storage_count + btstack_sbc_encoder_sbc_buffer_length()) > context->max_media_payload_size){
265         // schedule sending
266         context->sbc_ready_to_send = 1;
267         a2dp_source_stream_endpoint_request_can_send_now(context->a2dp_cid, context->local_seid);
268     }
269 }
270 
271 static void a2dp_demo_timer_start(a2dp_media_sending_context_t * context){
272     context->max_media_payload_size = a2dp_max_media_payload_size(context->a2dp_cid, context->local_seid);
273     context->sbc_storage_count = 0;
274     context->sbc_ready_to_send = 0;
275     context->streaming = 1;
276     btstack_run_loop_remove_timer(&context->audio_timer);
277     btstack_run_loop_set_timer_handler(&context->audio_timer, a2dp_demo_audio_timeout_handler);
278     btstack_run_loop_set_timer_context(&context->audio_timer, context);
279     btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
280     btstack_run_loop_add_timer(&context->audio_timer);
281 }
282 
283 static void a2dp_demo_timer_stop(a2dp_media_sending_context_t * context){
284     context->time_audio_data_sent = 0;
285     context->acc_num_missed_samples = 0;
286     context->samples_ready = 0;
287     context->streaming = 1;
288     context->sbc_storage_count = 0;
289     context->sbc_ready_to_send = 0;
290     btstack_run_loop_remove_timer(&context->audio_timer);
291 }
292 
293 static void a2dp_demo_timer_pause(a2dp_media_sending_context_t * context){
294     btstack_run_loop_remove_timer(&context->audio_timer);
295 }
296 
297 
298 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
299     UNUSED(channel);
300     UNUSED(size);
301     uint8_t status;
302     uint8_t local_seid;
303     bd_addr_t address;
304 
305     if (packet_type != HCI_EVENT_PACKET) return;
306 
307 #ifndef HAVE_BTSTACK_STDIN
308     if (hci_event_packet_get_type(packet) == BTSTACK_EVENT_STATE){
309         if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return;
310         printf("Create AVDTP Source connection to addr %s.\n", bd_addr_to_str(device_addr));
311         status = a2dp_source_establish_stream(device_addr, media_tracker.local_seid, &media_tracker.a2dp_cid);
312         if (status != ERROR_CODE_SUCCESS){
313             printf("Could not perform command, status 0x%2x\n", status);
314         }
315         return;
316     }
317 #endif
318 
319     if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) return;
320     switch (packet[2]){
321         case A2DP_SUBEVENT_INCOMING_CONNECTION_ESTABLISHED:
322             a2dp_subevent_incoming_connection_established_get_bd_addr(packet, address);
323             media_tracker.a2dp_cid = a2dp_subevent_incoming_connection_established_get_a2dp_cid(packet);
324             printf("A2DP: Incoming connection established: address %s, a2dp cid 0x%02x. Create stream on local seid %d.\n",
325                 bd_addr_to_str(address), media_tracker.a2dp_cid, media_tracker.local_seid);
326             status = a2dp_source_establish_stream(device_addr, media_tracker.local_seid, &media_tracker.a2dp_cid);
327             if (status != ERROR_CODE_SUCCESS){
328                 printf("Could not perform command, status 0x%2x\n", status);
329             }
330             break;
331         case A2DP_SUBEVENT_STREAM_ESTABLISHED:
332             a2dp_subevent_stream_established_get_bd_addr(packet, address);
333             status = a2dp_subevent_stream_established_get_status(packet);
334             if (status){
335                 printf("A2DP: Stream establishment failed: status 0x%02x.\n", status);
336                 break;
337             }
338             local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
339             if (local_seid != media_tracker.local_seid){
340                 printf("A2DP: Stream establishment failed: wrong local seid %d, expected %d.\n", local_seid, media_tracker.local_seid);
341                 break;
342             }
343             media_tracker.a2dp_cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
344             printf("A2DP: Stream established: address %s, a2dp cid 0x%02x, local seid %d, remote seid %d.\n", bd_addr_to_str(address),
345                 media_tracker.a2dp_cid, media_tracker.local_seid, a2dp_subevent_stream_established_get_remote_seid(packet));
346             printf("Start playing mod.\n");
347             data_source = STREAM_MOD;
348             status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
349             break;
350 
351         case A2DP_SUBEVENT_STREAM_STARTED:
352             play_info.status = AVRCP_PLAY_STATUS_PLAYING;
353             a2dp_demo_timer_start(&media_tracker);
354             printf("A2DP: Stream started.\n");
355             break;
356 
357         case A2DP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW:
358             a2dp_demo_send_media_packet();
359             break;
360 
361         case A2DP_SUBEVENT_STREAM_SUSPENDED:
362             play_info.status = AVRCP_PLAY_STATUS_PAUSED;
363             printf("A2DP: Stream paused.\n");
364             a2dp_demo_timer_pause(&media_tracker);
365             break;
366 
367         case A2DP_SUBEVENT_STREAM_RELEASED:
368             play_info.status = AVRCP_PLAY_STATUS_STOPPED;
369             printf("A2DP: Stream released.\n");
370             a2dp_demo_timer_stop(&media_tracker);
371             break;
372         case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
373             printf("A2DP: Signaling released.\n");
374             break;
375         default:
376             printf("A2DP: event 0x%02x is not parsed\n", packet[2]);
377             break;
378     }
379 }
380 
381 static void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
382     UNUSED(channel);
383     UNUSED(size);
384     bd_addr_t event_addr;
385     uint16_t local_cid;
386     uint8_t  a2dp_cmd_status = 0xFF;
387     uint8_t  avrcp_cmd_status = 0xFF;
388 
389     if (packet_type != HCI_EVENT_PACKET) return;
390     if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) return;
391 
392     switch (packet[2]){
393         case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
394             local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
395             if (avrcp_cid != 0 && avrcp_cid != local_cid) {
396                 printf("AVRCP: Connection failed, expected 0x%02X l2cap cid, received 0x%02X\n", avrcp_cid, local_cid);
397                 return;
398             }
399 
400             avrcp_cmd_status = avrcp_subevent_connection_established_get_status(packet);
401             if (avrcp_cmd_status != ERROR_CODE_SUCCESS){
402                 printf("AVRCP: Connection failed: status 0x%02x\n", avrcp_cmd_status);
403                 avrcp_cid = 0;
404                 return;
405             }
406             avrcp_cid = local_cid;
407             play_info.song_length_ms = 0xFFFFFFFF;
408             play_info.song_position_ms = 0xFFFFFFFF;
409             play_info.status = AVRCP_PLAY_STATUS_ERROR;
410 
411             avrcp_subevent_connection_established_get_bd_addr(packet, event_addr);
412             printf("AVRCP: connected to %s, avrcp_cid 0x%02x\n", bd_addr_to_str(event_addr), local_cid);
413             return;
414         }
415 
416         case AVRCP_SUBEVENT_UNIT_INFO_QUERY:
417             avrcp_target_unit_info(avrcp_cid, AVRCP_SUBUNIT_TYPE_AUDIO, company_id);
418             break;
419         case AVRCP_SUBEVENT_SUBUNIT_INFO_QUERY:
420             avrcp_target_subunit_info(avrcp_cid, AVRCP_SUBUNIT_TYPE_UNIT, avrcp_subevent_subunit_info_query_get_offset(packet), (uint8_t *)subunit_info);
421             break;
422         case AVRCP_SUBEVENT_EVENT_IDS_QUERY:
423             avrcp_target_supported_events(avrcp_cid, events_num, events, sizeof(events));
424             break;
425         case AVRCP_SUBEVENT_COMPANY_IDS_QUERY:
426             avrcp_target_supported_companies(avrcp_cid, companies_num, companies, sizeof(companies));
427             break;
428         case AVRCP_SUBEVENT_PLAY_STATUS_QUERY:
429             avrcp_target_play_status(avrcp_cid, play_info.song_length_ms, play_info.song_position_ms, play_info.status);
430             break;
431         case AVRCP_SUBEVENT_NOW_PLAYING_INFO_QUERY:
432             avrcp_target_set_now_playing_title(avrcp_cid, now_playing_info.title);
433             avrcp_target_set_now_playing_artist(avrcp_cid, now_playing_info.artist);
434             avrcp_target_set_now_playing_album(avrcp_cid, now_playing_info.album);
435             avrcp_target_set_now_playing_genre(avrcp_cid, now_playing_info.genre);
436             avrcp_target_set_now_playing_track_nr(avrcp_cid, now_playing_info.track_nr);
437             avrcp_target_set_now_playing_total_tracks(avrcp_cid, now_playing_info.total_tracks);
438             avrcp_target_set_now_playing_song_length_ms(avrcp_cid, now_playing_info.song_length_ms);
439 
440             avrcp_target_now_playing_info(avrcp_cid);
441             break;
442         case AVRCP_SUBEVENT_OPERATION:{
443             avrcp_operation_id_t operation_id = avrcp_subevent_operation_get_operation_id(packet);
444             uint8_t operands_length = avrcp_subevent_operation_get_operands_length(packet);
445             uint8_t operand =  avrcp_subevent_operation_get_operand(packet);
446             printf("AVRCP: operation 0x%02x, operands length %d\n", operation_id, operands_length);
447 
448             switch (operation_id){
449                 case AVRCP_OPERATION_ID_PLAY:
450                     a2dp_cmd_status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
451                     break;
452                 case AVRCP_OPERATION_ID_PAUSE:
453                     a2dp_cmd_status = a2dp_source_pause_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
454                     break;
455 
456                 case AVRCP_OPERATION_ID_STOP:
457                 case AVRCP_OPERATION_ID_REWIND:
458                 case AVRCP_OPERATION_ID_FAST_FORWARD:
459                 case AVRCP_OPERATION_ID_FORWARD:
460                 case AVRCP_OPERATION_ID_BACKWARD:
461                 case AVRCP_OPERATION_ID_SKIP:
462                 case AVRCP_OPERATION_ID_VOLUME_UP:
463                 case AVRCP_OPERATION_ID_VOLUME_DOWN:
464                 case AVRCP_OPERATION_ID_MUTE:
465                 case AVRCP_OPERATION_ID_UNDEFINED:
466                     avrcp_cmd_status = avrcp_target_operation_not_implemented(avrcp_cid, operation_id, operands_length, operand);
467                     return;
468             }
469             // printf("a2dp_cmd_status 0x%02x \n", a2dp_cmd_status);
470             avrcp_cmd_status = avrcp_target_operation_accepted(avrcp_cid, operation_id, operands_length, operand);
471             break;
472         }
473         case AVRCP_SUBEVENT_CONNECTION_RELEASED:
474             printf("AVRCP: Channel released: avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
475             avrcp_cid = 0;
476             return;
477         default:
478             printf("AVRCP: event not parsed %02x\n", packet[2]);
479             break;
480     }
481 }
482 
483 #ifdef HAVE_BTSTACK_STDIN
484 static void show_usage(void){
485     bd_addr_t      iut_address;
486     gap_local_bd_addr(iut_address);
487     printf("\n--- Bluetooth A2DP Source/AVRCP Target Demo %s ---\n", bd_addr_to_str(iut_address));
488     printf("b      - AVDTP Source create  connection to addr %s\n", device_addr_string);
489     printf("B      - AVDTP Source disconnect\n");
490     printf("c      - AVRCP Target create connection to addr %s\n", device_addr_string);
491     printf("C      - AVRCP Target disconnect\n");
492 
493     printf("x      - start streaming sine\n");
494     if (hxcmod_initialized){
495         printf("z      - start streaming '%s'\n", mod_name);
496     }
497     printf("p      - pause streaming\n");
498 
499     printf("\n--- Bluetooth  AVRCP Target Commands %s ---\n", bd_addr_to_str(iut_address));
500     printf("---\n");
501 }
502 
503 static void stdin_process(char cmd){
504     uint8_t status = ERROR_CODE_SUCCESS;
505     switch (cmd){
506         case 'b':
507             printf(" - Create AVDTP Source connection to addr %s.\n", bd_addr_to_str(device_addr));
508             status = a2dp_source_establish_stream(device_addr, media_tracker.local_seid, &media_tracker.a2dp_cid);
509             break;
510         case 'B':
511             printf(" - AVDTP Source Disconnect\n");
512             status = a2dp_source_disconnect(media_tracker.a2dp_cid);
513             break;
514         case 'c':
515             printf(" - Create AVRCP Target connection to addr %s.\n", bd_addr_to_str(device_addr));
516             status = avrcp_target_connect(device_addr, &avrcp_cid);
517             break;
518         case 'C':
519             printf(" - AVRCP Target disconnect\n");
520             status = avrcp_target_disconnect(avrcp_cid);
521             break;
522 
523         case '\n':
524         case '\r':
525             break;
526 
527         case 'x':
528             if (data_source == STREAM_SINE) {
529                 printf("Already playing sine.\n");
530                 return;
531             }
532             printf("Playing sine.\n");
533             data_source = STREAM_SINE;
534             status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
535             break;
536         case 'z':
537             if (data_source == STREAM_MOD) {
538                 printf("Already playing mode.\n");
539                 return;
540             }
541             printf("Playing mod.\n");
542             data_source = STREAM_MOD;
543             status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
544             break;
545         case 'p':
546             printf("Pause stream.\n");
547             status = a2dp_source_pause_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
548             break;
549 
550         default:
551             show_usage();
552             return;
553     }
554     if (status != ERROR_CODE_SUCCESS){
555         printf("Could not perform command, status 0x%2x\n", status);
556     }
557 }
558 #endif
559 
560 
561 int btstack_main(int argc, const char * argv[]);
562 int btstack_main(int argc, const char * argv[]){
563     UNUSED(argc);
564     (void)argv;
565 
566     // register for HCI events
567     hci_event_callback_registration.callback = &packet_handler;
568     hci_add_event_handler(&hci_event_callback_registration);
569 
570     l2cap_init();
571     // Initialize AVDTP Source
572     a2dp_source_init();
573     a2dp_source_register_packet_handler(&packet_handler);
574 
575     avdtp_stream_endpoint_t * local_stream_endpoint = a2dp_source_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));
576     if (!local_stream_endpoint){
577         printf("A2DP source demo: not enough memory to create local stream endpoint\n");
578         return 1;
579     }
580     media_tracker.local_seid = avdtp_local_seid(local_stream_endpoint);
581 
582     // Initialize AVRCP Target
583     avrcp_target_init();
584     avrcp_target_register_packet_handler(&avrcp_target_packet_handler);
585 
586     // Initialize SDP
587     sdp_init();
588     memset(sdp_a2dp_source_service_buffer, 0, sizeof(sdp_a2dp_source_service_buffer));
589     a2dp_source_create_sdp_record(sdp_a2dp_source_service_buffer, 0x10002, 1, NULL, NULL);
590     sdp_register_service(sdp_a2dp_source_service_buffer);
591 
592     gap_set_local_name(device_name);
593     gap_discoverable_control(1);
594     gap_set_class_of_device(0x200408);
595 
596     hxcmod_initialized = hxcmod_init(&mod_context);
597     if (hxcmod_initialized){
598         hxcmod_setcfg(&mod_context, A2DP_SAMPLE_RATE, 16, 1, 1, 1);
599         hxcmod_load(&mod_context, (void *) &mod_data, mod_len);
600         printf("loaded mod '%s', size %u\n", mod_name, mod_len);
601     }
602 
603     // For PTS test
604     memcpy(now_playing_info.title,  "Title  1", 8);
605     memcpy(now_playing_info.artist, "Artist 1", 8);
606     memcpy(now_playing_info.album,  "Album  1", 8);
607     memcpy(now_playing_info.genre,  "Genre  1", 8);
608     now_playing_info.track_nr = 1;
609     now_playing_info.total_tracks = 10;
610     now_playing_info.song_length_ms = 3655;
611 
612     // parse human readable Bluetooth address
613     sscanf_bd_addr(device_addr_string, device_addr);
614 
615 #ifdef HAVE_BTSTACK_STDIN
616     btstack_stdin_setup(stdin_process);
617 #endif
618     // turn on!
619     hci_power_control(HCI_POWER_ON);
620     return 0;
621 }
622