r269@gandalf: fugalh | 2006-08-03 20:18:05 -0600
[ardour.git] / gtk2_ardour / fft_result.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3         Written by Sampo Savolainen
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <fft_result.h>
22 #include <fft_graph.h>
23 #include <cstdlib>
24 #include <string>
25 #include <cmath>
26
27 #include <iostream>
28
29 using namespace std;
30
31 FFTResult::FFTResult(FFTGraph *graph, Gdk::Color color, string trackname)
32 {
33         _graph = graph;
34         
35         _windowSize = _graph->windowSize();
36         _dataSize   = _windowSize / 2;
37
38         _averages = 0;
39
40         _data = (float *) malloc(sizeof(float) * _dataSize);
41         memset(_data,0,sizeof(float) * _dataSize);
42
43         _color     = color;
44         _trackname = trackname;
45 }
46
47 void
48 FFTResult::analyzeWindow(float *window)
49 {
50         _graph->analyze(window, _data);
51         _averages++;
52 }
53
54 void
55 FFTResult::finalize()
56 {
57         if (_averages == 0) {
58                 _minimum = 0.0;
59                 _maximum = 0.0;
60                 return;
61         }
62         
63         // Average & scale
64         for (int i = 0; i < _dataSize; i++) {
65                 _data[i] /= _averages;
66                 _data[i]  = 10.0f * log10f(_data[i]); 
67         }
68
69         // find min & max
70         _minimum = _maximum = _data[0];
71         
72         for (int i = 1; i < _dataSize; i++) {
73                 if (_data[i] < _minimum        && !isinf(_data[i])) {
74                         _minimum = _data[i];
75                 } else if (_data[i] > _maximum && !isinf(_data[i])) {
76                         _maximum = _data[i];
77                 }
78         }
79
80         _averages = 0;
81 }
82
83 FFTResult::~FFTResult()
84 {
85         free(_data);
86 }
87
88
89 float
90 FFTResult::sampleAt(int x)
91 {
92         if (x < 0 || x>= _dataSize)
93                 return 0.0f;
94
95         return _data[x];
96 }
97