Merged with trunk (painfully)
[ardour.git] / gtk2_ardour / fft_graph.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <iostream>
21
22 #include <glibmm.h>
23 #include <glibmm/refptr.h>
24
25 #include <gdkmm/gc.h>
26
27 #include <gtkmm/widget.h>
28 #include <gtkmm/style.h>
29 #include <gtkmm/treemodel.h>
30 #include <gtkmm/treepath.h>
31
32 #include <pbd/stl_delete.h>
33
34 #include <math.h>
35
36 #include "fft_graph.h"
37 #include "analysis_window.h"
38
39 using namespace std;
40 using namespace Gtk;
41 using namespace Gdk;
42
43 FFTGraph::FFTGraph(int windowSize)
44 {
45         _logScale = 0;
46         
47         _in       = 0;
48         _out      = 0;
49         _hanning  = 0;
50         _logScale = 0;
51
52         _a_window = 0;
53
54         setWindowSize(windowSize);
55 }
56
57 void
58 FFTGraph::setWindowSize(int windowSize)
59 {
60         if (_a_window) {
61                 Glib::Mutex::Lock lm  (_a_window->track_list_lock);
62                 setWindowSize_internal(windowSize);
63         } else {
64                 setWindowSize_internal(windowSize);
65         }
66 }
67
68 void
69 FFTGraph::setWindowSize_internal(int windowSize)
70 {
71         // remove old tracklist & graphs
72         if (_a_window) {
73                 _a_window->clear_tracklist();
74         }
75         
76         _windowSize = windowSize;
77         _dataSize = windowSize / 2;
78         if (_in != 0) {
79                 fftwf_destroy_plan(_plan);
80                 free(_in);
81                 _in = 0;
82         }
83         
84         if (_out != 0) {
85                 free(_out);
86                 _out = 0;
87         }
88         
89         if (_hanning != 0) {
90                 free(_hanning);
91                 _hanning = 0;
92         }
93
94         if (_logScale != 0) {
95                 free(_logScale);
96                 _logScale = 0;
97         }
98
99         // When destroying, window size is set to zero to free up memory
100         if (windowSize == 0)
101                 return;
102
103         // FFT input & output buffers
104         _in      = (float *) fftwf_malloc(sizeof(float) * _windowSize);
105         _out     = (float *) fftwf_malloc(sizeof(float) * _windowSize);
106
107         // Hanning window
108         _hanning = (float *) malloc(sizeof(float) * _windowSize);
109
110
111         // normalize the window
112         double sum = 0.0;
113         
114         for (int i=0; i < _windowSize; i++) {
115                 _hanning[i]=0.81f * ( 0.5f - (0.5f * (float) cos(2.0f * M_PI * (float)i / (float)(_windowSize))));
116                 sum += _hanning[i];
117         }
118
119         double isum = 1.0 / sum;
120         
121         for (int i=0; i < _windowSize; i++) {
122                 _hanning[i] *= isum;
123         }
124         
125         _logScale = (int *) malloc(sizeof(int) * _dataSize);
126         for (int i = 0; i < _dataSize; i++) {
127                 _logScale[i] = (int)floor(log10( 1.0 + i * 9.0 / (double)_dataSize) * (double)scaleWidth);
128         }
129         _plan = fftwf_plan_r2r_1d(_windowSize, _in, _out, FFTW_R2HC, FFTW_ESTIMATE);
130 }
131
132 FFTGraph::~FFTGraph()
133 {
134         // This will free everything
135         setWindowSize(0);
136 }
137
138 bool
139 FFTGraph::on_expose_event (GdkEventExpose* event)
140 {
141         redraw();
142         return true;
143 }
144
145 FFTResult *
146 FFTGraph::prepareResult(Gdk::Color color, string trackname)
147 {
148         FFTResult *res = new FFTResult(this, color, trackname);
149
150         return res;
151 }
152
153 void
154 FFTGraph::analyze(float *window, float *composite)
155 {       
156         int i;
157         // Copy the data and apply the hanning window
158         for (i = 0; i < _windowSize; i++) {
159                 _in[i] = window[ i ] * _hanning[ i ];
160         }
161
162         fftwf_execute(_plan);
163
164         composite[0] += (_out[0] * _out[0]);
165         
166         for (i=1; i < _dataSize - 1; i++) { // TODO: check with Jesse whether this is really correct
167                 composite[i] += (_out[i] * _out[i]) + (_out[_windowSize-i] * _out[_windowSize-i]);
168         }
169 }
170
171 void
172 FFTGraph::set_analysis_window(AnalysisWindow *a_window)
173 {
174         _a_window = a_window;
175 }
176
177 void
178 FFTGraph::draw_scales(Glib::RefPtr<Gdk::Window> window)
179 {
180         
181         Glib::RefPtr<Gtk::Style> style = get_style();
182         Glib::RefPtr<Gdk::GC> black = style->get_black_gc();
183         Glib::RefPtr<Gdk::GC> white = style->get_white_gc();
184         
185         window->draw_rectangle(black, true, 0, 0, width, height);
186         
187         /**
188          *  4          5
189          *  _          _
190          *   |        |
191          * 1 |        | 2
192          *   |________|
193          *        3
194          **/
195
196         // Line 1
197         window->draw_line(white, h_margin, v_margin, h_margin, height - v_margin );
198
199         // Line 2
200         window->draw_line(white, width - h_margin, v_margin, width - h_margin, height - v_margin );
201
202         // Line 3
203         window->draw_line(white, h_margin, height - v_margin, width - h_margin, height - v_margin );
204
205 #define DB_METRIC_LENGTH 8
206         // Line 5
207         window->draw_line(white, h_margin - DB_METRIC_LENGTH, v_margin, h_margin, v_margin );
208         
209         // Line 6
210         window->draw_line(white, width - h_margin, v_margin, width - h_margin + DB_METRIC_LENGTH, v_margin );
211
212
213         if (graph_gc == 0) {
214                 graph_gc = GC::create( get_window() );
215         }
216
217         Color grey;
218
219         grey.set_rgb_p(0.2, 0.2, 0.2);
220         
221         graph_gc->set_rgb_fg_color( grey );
222
223         if (layout == 0) {
224                 layout = create_pango_layout ("");
225                 layout->set_font_description (get_style()->get_font());
226         }
227
228         // Draw logscale
229         int logscale_pos = 0;
230         int position_on_scale;
231         for (int x = 1; x < 8; x++) {
232                 position_on_scale = (int)floor( (double)scaleWidth*(double)x/8.0);
233
234                 while (_logScale[logscale_pos] < position_on_scale)
235                         logscale_pos++;
236                 
237                 int coord = v_margin + 1.0 + position_on_scale;
238                 
239                 int SR = 44100;
240
241                 int rate_at_pos = (double)(SR/2) * (double)logscale_pos / (double)_dataSize;
242                 
243                 char buf[32];
244                 snprintf(buf,32,"%dhz",rate_at_pos);
245                 
246                 std::string label = buf;
247                 
248                 layout->set_text(label);
249                 
250                 window->draw_line(graph_gc, coord, v_margin, coord, height - v_margin);
251
252                 int width, height;
253                 layout->get_pixel_size (width, height);
254                 
255                 window->draw_layout(white, coord - width / 2, v_margin / 2, layout);
256                 
257         }
258
259 }
260
261 void
262 FFTGraph::redraw()
263 {       
264         Glib::Mutex::Lock lm  (_a_window->track_list_lock);
265
266         draw_scales(get_window());
267         
268         if (_a_window == 0)
269                 return;
270
271         if (!_a_window->track_list_ready)
272                 return;
273         
274         
275         // Find "session wide" min & max
276         float min =  1000000000000.0;
277         float max = -1000000000000.0;
278         
279         TreeNodeChildren track_rows = _a_window->track_list.get_model()->children();
280         
281         for (TreeIter i = track_rows.begin(); i != track_rows.end(); i++) {
282                 
283                 TreeModel::Row row = *i;
284                 FFTResult *res = row[_a_window->tlcols.graph];
285
286                 // disregard fft analysis from empty signals
287                 if (res->minimum() == res->maximum()) {
288                         continue;
289                 }
290                 
291                 if ( res->minimum() < min) {
292                         min = res->minimum();
293                 }
294
295                 if ( res->maximum() > max) {
296                         max = res->maximum();
297                 }
298         }
299         
300         int graph_height = height - 2 * h_margin;
301
302         if (graph_gc == 0) {
303                 graph_gc = GC::create( get_window() );
304         }
305         
306         
307         double pixels_per_db = (double)graph_height / (double)(max - min);
308         
309         
310         for (TreeIter i = track_rows.begin(); i != track_rows.end(); i++) {
311                 
312                 TreeModel::Row row = *i;
313
314                 // don't show graphs for tracks which are deselected
315                 if (!row[_a_window->tlcols.visible]) {
316                         continue;
317                 }
318                 
319                 FFTResult *res = row[_a_window->tlcols.graph];
320
321                 // don't show graphs for empty signals
322                 if (res->minimum() == res->maximum()) {
323                         continue;
324                 }
325                 
326                 std::string name = row[_a_window->tlcols.trackname];
327
328                 // Set color from track
329                 graph_gc->set_rgb_fg_color( res->get_color() );
330
331                 float mpp = -1000000.0;
332                 int prevx = 0;
333                 float prevSample = min;
334                 
335                 for (int x = 0; x < res->length() - 1; x++) {
336                         
337                         if (res->sampleAt(x) > mpp)
338                                 mpp = res->sampleAt(x);
339                         
340                         // If the next point on the log scale is at the same location,
341                         // don't draw yet
342                         if (x + 1 < res->length() && 
343                                 _logScale[x] == _logScale[x + 1]) {
344                                 continue;
345                         }
346
347                         get_window()->draw_line(
348                                         graph_gc,
349                                         v_margin + 1 + prevx,
350                                         graph_height - (int)floor( (prevSample - min) * pixels_per_db) + h_margin - 1,
351                                         v_margin + 1 + _logScale[x],
352                                         graph_height - (int)floor( (mpp        - min) * pixels_per_db) + h_margin - 1);
353                         
354                         prevx = _logScale[x];
355                         prevSample = mpp;
356                         
357
358                         mpp = -1000000.0;
359                         
360                 }
361         }
362
363 }
364
365 void
366 FFTGraph::on_size_request(Gtk::Requisition* requisition)
367 {
368         width  = scaleWidth  + h_margin * 2;
369         height = scaleHeight + 2 + v_margin * 2;
370
371         if (_logScale != 0) {
372                 free(_logScale);
373         }
374
375         _logScale = (int *) malloc(sizeof(int) * _dataSize);
376         //cerr << "LogScale: " << endl;
377         for (int i = 0; i < _dataSize; i++) {
378                 _logScale[i] = (int)floor(log10( 1.0 + i * 9.0 / (double)_dataSize) * (double)scaleWidth);
379                 //cerr << i << ":\t" << _logScale[i] << endl;
380         }
381
382         requisition->width  = width;;
383         requisition->height = height;
384 }
385
386 void
387 FFTGraph::on_size_allocate(Gtk::Allocation alloc)
388 {
389         width = alloc.get_width();
390         height = alloc.get_height();
391         
392         DrawingArea::on_size_allocate (alloc);
393
394 }
395