summaryrefslogtreecommitdiffstats
path: root/WasmAudio/main.c
blob: 6f1766bf770a2a2836d04229978ea10c3d4cb14c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//
//  main.c
//  WasmAudio
//
//  Created by Jacky Jack on 06/07/2021.
//

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <getopt.h>
#include <signal.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>



#if __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_audio.h>
#include <GLES2/gl2.h>
#else
    #include <SDL2/SDL.h>
    #include <SDL2/SDL_audio.h>
    #ifdef __APPLE__
    #include <SDL2_ttf/SDL_ttf.h>
    #else
    #include <SDL2/SDL_ttf.h>
    #endif
    //how to use on mac?
    //#include <GLES2/gl2.h>
#endif

#define SCREEN_WIDTH   320
#define SCREEN_WIDTH2  (SCREEN_WIDTH/2)
#define SCREEN_HEIGHT  320
#define SCREEN_HEIGHT2 (SCREEN_HEIGHT/2)

#define BUFSIZE 1536000

//Maximum recording time plus padding
#define RECORDING_BUFFER_SECONDS  (2)
//Maximum recording time
#define MAX_RECORDING_SECONDS (RECORDING_BUFFER_SECONDS+2)

int first_run=1;
static int quit=0;
static SDL_Window *window = NULL;
static SDL_Renderer *renderer = NULL;
//Audio device IDs
static SDL_AudioDeviceID recordingDeviceId = 0;
static SDL_AudioDeviceID playbackDeviceId = 0;
int audio_rec_buffer_size=-1;
int audio_rec_buffer_max_size=-1;
//int audio_play_buffer_size=-1;
//int audio_play_buffer_max_size=-1;
static uint8_t audio_rec_buffer_[BUFSIZE];
static double process_buf[BUFSIZE/4];
uint8_t *audio_rec_buffer=NULL;

int audio_buf_position=0;
//uint8_t *audio_play_buffer=NULL;
int current_state=0;


void audio_recording_callback(void *data, uint8_t *insamples, int len)
{
    //printf("record len=%d\n",len);
    if (audio_buf_position<audio_rec_buffer_size) {
        memcpy( audio_rec_buffer+audio_buf_position, insamples, len);
        audio_buf_position += len;
    }
    //memcpy(insamples, audio_rec_buffer+audio_buf_position, len);
    
    printf("rec_pos=%d\n",audio_buf_position);
}

void audio_playback_callback(void *data, uint8_t *outsamples, int len) {
    //printf("playback len=%d\n",len);
    //memcpy( audio_rec_buffer,outsamples, len);
    if (audio_buf_position<audio_rec_buffer_size) {
        memcpy( outsamples, audio_rec_buffer+audio_buf_position,len);
        audio_buf_position += len;
    }
    
}

//The various recording actions we can take
enum RecordingState
{
    SELECTING_DEVICE,
    STOPPED,
    RECORDING,
    RECORDED,
    PLAYBACK,
    ERROR
};

void convert_double_to_f32() {
    int i;
    for (i=0;i<audio_rec_buffer_size;i+=4) {
        float *f_ = (float *)&audio_rec_buffer[i];
        float f = *f_;
        process_buf[i/4] = (double)f;
    }
}

void convert_f32_to_double() {
    int i=0;
    for (i=0;i<audio_rec_buffer_size;i+=4) {
        double d = process_buf[i/4];
        float f = (float)d;
        float *f_ = (float *)audio_rec_buffer;
        f_[i/4] = (double)f;
    }
}


uint32_t tick_start, tick_end,tick_1sec;

#if __EMSCRIPTEN__
void main_tick() {
#else
int main_tick() {
#endif
    int i,j;
    int update_fractal=0;
    uint64_t perf_start, perf_end;
    
    perf_start = SDL_GetPerformanceCounter();
    tick_start = SDL_GetTicks();
    
    SDL_Event event;
    SDL_StartTextInput();
        while (SDL_PollEvent(&event) != 0)
        {
                    
            switch (event.type)
            {
                case SDL_QUIT:
                {
                    quit = 1;
                    break;
                }
                case SDL_KEYDOWN:
                {
                    switch (event.key.keysym.sym)
                    {

                    case 21:
                    case SDLK_r:
                            //record if stopped
                            if ((current_state == STOPPED) || (current_state == RECORDED)) {
                                audio_buf_position = 0;
                                SDL_PauseAudioDevice(recordingDeviceId, SDL_FALSE);
                                current_state = RECORDING;
                                printf("State: RECORDING\n");
                            }
                        break;
                    case 22:
                    case SDLK_s:
                            //play if recorded
                            if (current_state == RECORDED) {
                                audio_buf_position = 0;
                                SDL_PauseAudioDevice( playbackDeviceId, SDL_FALSE );
                                current_state = PLAYBACK;
                                printf("State: PLAYBACK\n");
                            } /*else if (current_state == PLAYBACK) {
                                current_state = STOPPED;
                            } else if (current_state == STOPPED) {
                                current_state = PLAYBACK;
                            }*/
                        break;
                    case 20:
                    case SDLK_q:
                            //process recorderd buffer with low pass filter
                            if (current_state == RECORDED) {
                                convert_f32_to_double();
                                convert_double_to_f32();
                            }
                        break;
                    default:
                        printf("Unknown key %d\n",event.key.keysym.sym);
                        update_fractal = 1;
                    }
                    break;
                }
            }
            //printf("Poll event\n");
            
        }
#if __EMSCRIPTEN__
        if (current_state == RECORDING) {
            SDL_LockAudioDevice( recordingDeviceId );
            printf("recording=%d\n",audio_buf_position);
            if( audio_buf_position > audio_rec_buffer_size )
            {
                //Stop recording audio
                SDL_PauseAudioDevice( recordingDeviceId, SDL_TRUE );
                current_state = RECORDED;
                printf("State: RECORDED\n");
            }
            
            SDL_UnlockAudioDevice( recordingDeviceId );
        } else if (current_state == PLAYBACK) {
            SDL_LockAudioDevice( playbackDeviceId );
            //Finished playback
            if( audio_buf_position > audio_rec_buffer_size )
            {
                //Stop playing audio
                SDL_PauseAudioDevice( playbackDeviceId, SDL_TRUE );
                current_state = RECORDED;
                printf("State: RECORDED\n");
            }
            //Unlock callback
            SDL_UnlockAudioDevice( playbackDeviceId );
        }
#endif
        

        //check for first ever run
        if (first_run == 1)
        {
            first_run = 0;
            update_fractal = 1;
        }

        if (update_fractal == 1)
        {

        }
        
        #ifndef __EMSCRIPTEN__
        if (update_fractal == 1)
        #endif
        {
            SDL_GL_SwapWindow( window );
        }
        update_fractal=0;
    
    tick_end = SDL_GetTicks();
    if ((tick_end-tick_1sec)>1000) {
        //perf_end = SDL_GetPerformanceCounter()-perf_start;
        //tick_end = SDL_GetTicks()-tick_start;
        //printf("FPS:%f\n",(1.0f/perf_end));
        printf("FPS:%f\n",1.0f/((tick_end-tick_start)/1000.0f));
        tick_1sec = tick_end;
    }
    

#if !__EMSCRIPTEN__
    return 0;
#endif
}


void main_loop()
{
    int i,count;
    tick_1sec = SDL_GetTicks();
#if __EMSCRIPTEN__
    emscripten_set_main_loop(main_tick, 25, 1);
#else
    while (0 == quit)
    {
        main_tick();
#if !__EMSCRIPTEN__
        if (current_state == RECORDING) {
            SDL_LockAudioDevice( recordingDeviceId );
            printf("recording=%d\n",audio_buf_position);
            if( audio_buf_position > audio_rec_buffer_size )
            {
                //Stop recording audio
                SDL_PauseAudioDevice( recordingDeviceId, SDL_TRUE );
                current_state = RECORDED;
                printf("State: RECORDED\n");
            }
            
            SDL_UnlockAudioDevice( recordingDeviceId );
        } else if (current_state == PLAYBACK) {
            SDL_LockAudioDevice( playbackDeviceId );
            //Finished playback
            if( audio_buf_position > audio_rec_buffer_size )
            {
                //Stop playing audio
                SDL_PauseAudioDevice( playbackDeviceId, SDL_TRUE );
                current_state = RECORDED;
                printf("State: RECORDED\n");
            }
            //Unlock callback
            SDL_UnlockAudioDevice( playbackDeviceId );
        }
#endif
    }
#endif
}

int main(int argc, const char * argv[]) {
    int i,count;
    // insert code here...
    printf("Hello, World2!\n");
    //if ( SDL_Init(SDL_INIT_EVERYTHING) < 0 )
    if ( SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO) < 0 )
    {
        fprintf(stderr, "EXIT:Unable to init SDL: %s\n", SDL_GetError());
        exit(1);
    }
    
    
    
    atexit(SDL_Quit);
    
    printf("Prepare SDL2 window\n");
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
    window = SDL_CreateWindow("KOH", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL|SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor(renderer, 0xff, 0xaa, 0xaa, 0xaa);
    SDL_GLContext gl_context = SDL_GL_CreateContext(window);
    SDL_GL_SetSwapInterval( 0 );

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    
    count  = SDL_GetNumAudioDevices(0);
    printf("Playback devices  %d\n",count);
    for (i=0;i<count;i++) {
        printf("Playback audio device %d: %s\n", i, SDL_GetAudioDeviceName(i, 0));
    }
    count  = SDL_GetNumAudioDevices(1);
    printf("Recording devices %d\n",count);
    for (i=0;i<count;i++) {
        printf("Recording audio device %d: %s\n", i, SDL_GetAudioDeviceName(i, 1));
    }
    
    //https://github.com/emscripten-core/emscripten/issues/3477
    //try whatever possible
    SDL_AudioSpec audio_rec_want, audio_rec_have;
    SDL_memset(&audio_rec_want, 0, sizeof(audio_rec_want)); /* or SDL_zero(want) */
    audio_rec_want.freq = 48000;
    audio_rec_want.format = AUDIO_F32;
    audio_rec_want.channels = 2;
    audio_rec_want.samples = 4096;
    audio_rec_want.callback = audio_recording_callback;
    recordingDeviceId = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(1, SDL_TRUE ), SDL_TRUE, &audio_rec_want, &audio_rec_have, SDL_AUDIO_ALLOW_FORMAT_CHANGE|SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
    
    if (audio_rec_want.freq != audio_rec_have.freq) {
        printf("Freq changed %d -> %d\n",audio_rec_want.freq,audio_rec_have.freq);
    }
    
    if (audio_rec_want.format != audio_rec_have.format) {
        printf("Format changed %d -> %d\n",audio_rec_want.format, audio_rec_have.format);
    }
    
    if (recordingDeviceId == 0) {
        printf("Failed to open recording device\n");
    } else {
        int byte_per_sample = audio_rec_have.channels * ( SDL_AUDIO_BITSIZE( audio_rec_have.format )/8);
        int byte_per_second = audio_rec_have.freq * byte_per_sample;
        printf("bytes per second %d\n",byte_per_second);
        audio_rec_buffer_size = byte_per_second*RECORDING_BUFFER_SECONDS;
        audio_rec_buffer_max_size = byte_per_second*MAX_RECORDING_SECONDS;
        //audio_rec_buffer = malloc(audio_rec_buffer_max_size);
        audio_rec_buffer = &audio_rec_buffer_[0];
        printf("buffsize_max=%d\n",audio_rec_buffer_max_size);
        printf("buffsize=%d\n",audio_rec_buffer_size);
        memset(audio_rec_buffer,0,audio_rec_buffer_max_size);
    }
    
    SDL_AudioSpec audio_play_want, audio_play_have;
    audio_play_want.freq = 48000;
    audio_play_want.format = AUDIO_F32;
    audio_play_want.channels = 2;
    audio_play_want.samples = 4096;
    audio_play_want.callback = audio_playback_callback;
    playbackDeviceId = SDL_OpenAudioDevice(NULL, SDL_FALSE, &audio_play_want, &audio_play_have, SDL_AUDIO_ALLOW_FORMAT_CHANGE|SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
    
    if (audio_play_want.freq != audio_play_have.freq) {
        printf("Freq changed %d -> %d\n",audio_rec_want.freq,audio_rec_have.freq);
    }
    
    if (audio_play_want.format != audio_play_have.format) {
        printf("Format changed %d -> %d\n",audio_play_want.format, audio_play_have.format);
    }
    current_state = STOPPED;
    printf("State: STOPED\n");
    
    
    
    
    
    //SDL_PauseAudioDevice(recordingDeviceId,0);
    //!SDL_LockAudioDevice(recordingDeviceId);
    //SDL_PauseAudioDevice(recordingDeviceId, 0);
    //SDL_PauseAudio(0);
    //SDL_Delay(4000);
    //!SDL_UnlockAudioDevice(recordingDeviceId);
    //!SDL_CloseAudio();
    //SDL_CloseAudioDevice(recordingDeviceId);
    /*
    if (SDL_OpenAudio(&audio_want, &audio_have) < 0) {
        SDL_Log("Failed to open audio: %s", SDL_GetError());
    } else {
        if (audio_have.format != audio_want.format) {
            SDL_Log("We didn't get Float32 audio format.");
        }
        SDL_PauseAudio(0);
        SDL_Delay(5000);
        SDL_CloseAudio();
    }
    */
    
    main_loop();
    
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_CloseAudio();//?
    SDL_VideoQuit();//?
    SDL_Quit();
    
    return 0;
}