Make an SDL/OpenGL-frontend; might be more intuitive to read, although I'm not sure...
[pitch] / glpitch.cpp
1 #include <SDL.h>
2 #include <GL/gl.h>
3
4 #include "config.h"
5 #include "linux_audio.h"
6 #include "notes.h"
7 #include "pitchdetector.h"
8
9 #define MIN_X -40
10 #define MAX_X 5
11
12 double find_pos(double freq)
13 {
14         return 12.0 * log2(freq / BASE_PITCH) - 3.0;
15 }
16
17 int main(void)
18 {
19         PitchDetector pd(SAMPLE_RATE, FFT_LENGTH, PAD_FACTOR, OVERLAP);
20         int fd = get_dsp_fd(SAMPLE_RATE, FFT_LENGTH, OVERLAP);
21
22         SDL_Init(SDL_INIT_VIDEO);
23         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
24         SDL_SetVideoMode(1024, 200, 32, SDL_OPENGL);
25
26         glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
27         glClear(GL_COLOR_BUFFER_BIT);
28
29         for ( ;; ) {
30                 short buf[FFT_LENGTH / PAD_FACTOR / OVERLAP];
31                 read_chunk(fd, buf, FFT_LENGTH / PAD_FACTOR / OVERLAP);
32                 std::pair<double, double> peak = pd.detect_pitch(buf);
33
34                 glMatrixMode(GL_PROJECTION);
35                 glLoadIdentity();
36                 glOrtho(MIN_X, MAX_X, 1.0f, 0.0f, 0.0f, 1.0f);
37
38                 glMatrixMode(GL_MODELVIEW);
39                 glLoadIdentity();
40
41                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
42                 glEnable(GL_BLEND); 
43
44                 glBegin(GL_QUADS);      
45                 glColor4f(0.0, 0.0f, 0.0f, 0.05f);
46                 glVertex2f(MIN_X, 0.0f);
47                 glVertex2f(MIN_X, 1.0f);
48                 glVertex2f(MAX_X, 1.0f);
49                 glVertex2f(MAX_X, 0.0f);
50                 glEnd();
51
52                 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
53
54                 double peak_pos = find_pos(peak.first);
55
56                 glBegin(GL_QUADS);      
57                 glColor4f(0.0, 1.0f, 0.0f, 0.2f);
58                 glVertex2f(peak_pos - 0.1, 0.0f);
59                 glVertex2f(peak_pos - 0.1, 1.0f);
60                 glVertex2f(peak_pos + 0.1, 1.0f);
61                 glVertex2f(peak_pos + 0.1, 0.0f);
62                 glEnd();
63
64                 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
65                 glBegin(GL_LINES);
66
67                 for (int i = 0; i < 6; ++i) {
68                         double pos = find_pos(notes[i].freq);
69                         glVertex2f(pos, 0.0f);
70                         glVertex2f(pos, 1.0f);
71                 }
72                 glEnd();
73
74                 SDL_GL_SwapBuffers();
75         }
76 }