xref: /btstack/test/avdtp/sine_encode_decode_ring_buffer_test.c (revision db6cafabbb2f5855472a80ca7188b714a70d56bc)
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 #include <stdio.h>
39 #include <math.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <portaudio.h>
43 
44 #include "btstack_ring_buffer.h"
45 #include "classic/btstack_sbc.h"
46 #include "wav_util.h"
47 #include "classic/avdtp.h"
48 #include "classic/avdtp_source.h"
49 #include "btstack_stdin.h"
50 
51 #define NUM_CHANNELS        2
52 #define SAMPLE_RATE         44100
53 #define BYTES_PER_AUDIO_SAMPLE   (2*NUM_CHANNELS)
54 #define LATENCY             300 // ms
55 
56 #ifndef M_PI
57 #define M_PI  3.14159265
58 #endif
59 #define TABLE_SIZE_441HZ   100
60 
61 typedef struct {
62     int16_t source[TABLE_SIZE_441HZ];
63     int left_phase;
64     int right_phase;
65 } paTestData;
66 
67 static uint32_t fill_audio_ring_buffer_timeout = 50; //ms
68 static paTestData sin_data;
69 // static int total_num_samples = 0;
70 
71 static const char * output_wav_filename = "test_output_ring_sine.wav";
72 // static char * input_wav_filename = "test_input_sine.wav";
73 
74 static btstack_sbc_decoder_state_t state;
75 static btstack_sbc_mode_t mode = SBC_MODE_STANDARD;
76 
77 static avdtp_stream_endpoint_t * local_stream_endpoint;
78 
79 
handle_pcm_data(int16_t * data,int num_samples,int num_channels,int sample_rate,void * context)80 static void handle_pcm_data(int16_t * data, int num_samples, int num_channels, int sample_rate, void * context){
81     UNUSED(sample_rate);
82     UNUSED(context);
83     wav_writer_write_int16(num_samples*num_channels, data);
84 }
85 
86 
fill_audio_ring_buffer(void * userData,int num_samples_to_write,avdtp_stream_endpoint_t * stream_endpoint)87 static void fill_audio_ring_buffer(void *userData, int num_samples_to_write, avdtp_stream_endpoint_t * stream_endpoint){
88     paTestData *data = (paTestData*)userData;
89     int count = 0;
90     while (btstack_ring_buffer_bytes_free(&stream_endpoint->audio_ring_buffer) >= BYTES_PER_AUDIO_SAMPLE && count < num_samples_to_write){
91         uint8_t write_data[BYTES_PER_AUDIO_SAMPLE];
92         *(int16_t*)&write_data[0] = data->source[data->left_phase];
93         *(int16_t*)&write_data[2] = data->source[data->right_phase];
94 
95         btstack_ring_buffer_write(&stream_endpoint->audio_ring_buffer, write_data, BYTES_PER_AUDIO_SAMPLE);
96         count++;
97 
98         data->left_phase += 1;
99         if (data->left_phase >= TABLE_SIZE_441HZ){
100             data->left_phase -= TABLE_SIZE_441HZ;
101         }
102         data->right_phase += 1;
103         if (data->right_phase >= TABLE_SIZE_441HZ){
104             data->right_phase -= TABLE_SIZE_441HZ;
105         }
106     }
107 }
108 
store_sbc_frame_for_transmission(uint8_t * sbc_frame,int sbc_frame_size,avdtp_stream_endpoint_t * stream_endpoint)109 static void store_sbc_frame_for_transmission(uint8_t * sbc_frame, int sbc_frame_size, avdtp_stream_endpoint_t * stream_endpoint){
110     if (btstack_ring_buffer_bytes_free(&stream_endpoint->sbc_ring_buffer) >= (sbc_frame_size + 1)){
111         // printf("    store_sbc_frame_for_transmission\n");
112         uint8_t size_buffer = sbc_frame_size;
113         btstack_ring_buffer_write(&stream_endpoint->sbc_ring_buffer, &size_buffer, 1);
114         btstack_ring_buffer_write(&stream_endpoint->sbc_ring_buffer, sbc_frame, sbc_frame_size);
115     } else {
116         printf("No space in sbc buffer\n");
117     }
118 }
119 
120 
avdtp_source_stream_endpoint_run(avdtp_stream_endpoint_t * stream_endpoint)121 static void avdtp_source_stream_endpoint_run(avdtp_stream_endpoint_t * stream_endpoint){
122     // performe sbc encoding
123     int total_num_bytes_read = 0;
124     int num_audio_samples_to_read = btstack_sbc_encoder_num_audio_frames();
125     int audio_bytes_to_read = num_audio_samples_to_read * BYTES_PER_AUDIO_SAMPLE;
126 
127     printf("run: audio samples %u, audio_bytes_to_read: %d\n", num_audio_samples_to_read, audio_bytes_to_read);
128     printf("     audio buf, bytes available: %d\n", btstack_ring_buffer_bytes_available(&stream_endpoint->audio_ring_buffer));
129     printf("     sbc buf,   bytes free:      %d\n", btstack_ring_buffer_bytes_free(&stream_endpoint->sbc_ring_buffer));
130 
131     while (btstack_ring_buffer_bytes_available(&stream_endpoint->audio_ring_buffer) >= audio_bytes_to_read
132         && btstack_ring_buffer_bytes_free(&stream_endpoint->sbc_ring_buffer) >= 120){ // TODO use real value
133 
134         uint32_t number_of_bytes_read = 0;
135         uint8_t pcm_frame[256*BYTES_PER_AUDIO_SAMPLE];
136         btstack_ring_buffer_read(&stream_endpoint->audio_ring_buffer, pcm_frame, audio_bytes_to_read, &number_of_bytes_read);
137         // printf("     num audio bytes read %d\n", number_of_bytes_read);
138         btstack_sbc_encoder_process_data((int16_t *) pcm_frame);
139 
140         uint16_t sbc_frame_bytes = btstack_sbc_encoder_sbc_buffer_length();
141         printf("decode %d bytes\n", sbc_frame_bytes);
142         total_num_bytes_read += number_of_bytes_read;
143 
144         store_sbc_frame_for_transmission(btstack_sbc_encoder_sbc_buffer(), sbc_frame_bytes, stream_endpoint);
145         btstack_sbc_decoder_process_data(&state, 0, btstack_sbc_encoder_sbc_buffer(), sbc_frame_bytes);
146     }
147 }
148 
test_fill_audio_ring_buffer_timeout_handler(btstack_timer_source_t * timer)149 static void test_fill_audio_ring_buffer_timeout_handler(btstack_timer_source_t * timer){
150     avdtp_stream_endpoint_t * stream_endpoint = btstack_run_loop_get_timer_context(timer);
151     btstack_run_loop_set_timer(&stream_endpoint->fill_audio_ring_buffer_timer, fill_audio_ring_buffer_timeout); // 2 seconds timeout
152     btstack_run_loop_add_timer(&stream_endpoint->fill_audio_ring_buffer_timer);
153     uint32_t now = btstack_run_loop_get_time_ms();
154 
155     uint32_t update_period_ms = fill_audio_ring_buffer_timeout;
156     if (stream_endpoint->time_audio_data_sent > 0){
157         update_period_ms = now - stream_endpoint->time_audio_data_sent;
158     }
159     uint32_t num_samples = (update_period_ms * 44100) / 1000;
160     stream_endpoint->acc_num_missed_samples += (update_period_ms * 44100) % 1000;
161 
162     if (stream_endpoint->acc_num_missed_samples >= 1000){
163         num_samples++;
164         stream_endpoint->acc_num_missed_samples -= 1000;
165     }
166 
167     fill_audio_ring_buffer(&sin_data, num_samples, stream_endpoint);
168     stream_endpoint->time_audio_data_sent = now;
169 
170     avdtp_source_stream_endpoint_run(stream_endpoint);
171 }
172 
test_fill_audio_ring_buffer_timer_start(avdtp_stream_endpoint_t * stream_endpoint)173 static void test_fill_audio_ring_buffer_timer_start(avdtp_stream_endpoint_t * stream_endpoint){
174     btstack_run_loop_remove_timer(&stream_endpoint->fill_audio_ring_buffer_timer);
175     btstack_run_loop_set_timer_handler(&stream_endpoint->fill_audio_ring_buffer_timer, test_fill_audio_ring_buffer_timeout_handler);
176     btstack_run_loop_set_timer_context(&stream_endpoint->fill_audio_ring_buffer_timer, stream_endpoint);
177     btstack_run_loop_set_timer(&stream_endpoint->fill_audio_ring_buffer_timer, fill_audio_ring_buffer_timeout); // 50 ms timeout
178     btstack_run_loop_add_timer(&stream_endpoint->fill_audio_ring_buffer_timer);
179 }
180 
test_fill_audio_ring_buffer_timer_stop(avdtp_stream_endpoint_t * stream_endpoint)181 static void test_fill_audio_ring_buffer_timer_stop(avdtp_stream_endpoint_t * stream_endpoint){
182     btstack_run_loop_remove_timer(&stream_endpoint->fill_audio_ring_buffer_timer);
183 }
184 
stream_data_start(void)185 static void stream_data_start(void){
186     test_fill_audio_ring_buffer_timer_start(local_stream_endpoint);
187 }
188 
stream_data_stop(void)189 static void stream_data_stop(void){
190     test_fill_audio_ring_buffer_timer_stop(local_stream_endpoint);
191     wav_writer_close();
192 }
193 
show_usage(void)194 static void show_usage(void){
195     printf("\n--- Streaming with ring buffer Test Console ---\n");
196     printf("x      - start data stream\n");
197     printf("X      - stop  data stream\n");
198     printf("Ctrl-c - exit\n");
199     printf("---\n");
200 }
201 
stdin_process(char cmd)202 static void stdin_process(char cmd){
203     switch (cmd){
204         case 'x':
205             printf("start streaming sine\n");
206             stream_data_start();
207             break;
208         case 'X':
209             printf("stop streaming sine\n");
210             stream_data_stop();
211             break;
212 
213         case '\n':
214         case '\r':
215             break;
216         default:
217             show_usage();
218             break;
219     }
220 }
221 
222 int btstack_main(int argc, const char * argv[]);
btstack_main(int argc,const char * argv[])223 int btstack_main(int argc, const char * argv[]){
224     (void) argc;
225     (void) argv;
226     local_stream_endpoint = avdtp_source_create_stream_endpoint(AVDTP_SOURCE, AVDTP_AUDIO);
227     btstack_sbc_encoder_init(&(local_stream_endpoint->sbc_encoder_state), SBC_MODE_STANDARD, 16, 8, SBC_ALLOCATION_METHOD_LOUDNESS, 44100, 53, SBC_CHANNEL_MODE_STEREO);
228 
229     /* initialise sinusoidal wavetable */
230     int i;
231     for (i=0; i<TABLE_SIZE_441HZ; i++){
232         sin_data.source[i] = sin(((double)i/(double)TABLE_SIZE_441HZ) * M_PI * 2.)*32767;
233     }
234     sin_data.left_phase = sin_data.right_phase = 0;
235     // wav_writer_open(input_wav_filename, NUM_CHANNELS, SAMPLE_RATE);
236     printf("Outputfile: %s\n", output_wav_filename);
237     wav_writer_open(output_wav_filename, NUM_CHANNELS, SAMPLE_RATE);
238     btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL);
239     btstack_stdin_setup(stdin_process);
240     return 0;
241 }
242