Bump audio analysis file version and cache drawn points in the audio plot.
[dcpomatic.git] / src / wx / audio_plot.cc
1 /*
2     Copyright (C) 2013-2015 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "audio_plot.h"
22 #include "lib/audio_decoder.h"
23 #include "lib/audio_analysis.h"
24 #include "lib/compose.hpp"
25 #include "wx/wx_util.h"
26 #include <wx/graphics.h>
27 #include <boost/bind.hpp>
28 #include <iostream>
29
30 using std::cout;
31 using std::vector;
32 using std::list;
33 using std::max;
34 using std::min;
35 using boost::bind;
36 using boost::shared_ptr;
37
38 int const AudioPlot::_minimum = -70;
39 int const AudioPlot::max_smoothing = 128;
40
41 AudioPlot::AudioPlot (wxWindow* parent)
42         : wxPanel (parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE)
43         , _smoothing (max_smoothing / 2)
44         , _gain_correction (0)
45 {
46 #ifndef __WXOSX__
47         SetDoubleBuffered (true);
48 #endif
49
50         for (int i = 0; i < MAX_DCP_AUDIO_CHANNELS; ++i) {
51                 _channel_visible[i] = false;
52         }
53
54         for (int i = 0; i < AudioPoint::COUNT; ++i) {
55                 _type_visible[i] = false;
56         }
57
58         _colours.push_back (wxColour (  0,   0,   0));
59         _colours.push_back (wxColour (255,   0,   0));
60         _colours.push_back (wxColour (  0, 255,   0));
61         _colours.push_back (wxColour (139,   0, 204));
62         _colours.push_back (wxColour (  0,   0, 255));
63         _colours.push_back (wxColour (  0, 139,   0));
64         _colours.push_back (wxColour (  0,   0, 139));
65         _colours.push_back (wxColour (255, 255,   0));
66         _colours.push_back (wxColour (  0, 255, 255));
67         _colours.push_back (wxColour (255,   0, 255));
68         _colours.push_back (wxColour (255,   0, 139));
69         _colours.push_back (wxColour (139,   0, 255));
70
71         _colours.push_back (wxColour (139, 139, 255));
72         _colours.push_back (wxColour (  0, 139, 255));
73         _colours.push_back (wxColour (255, 139, 139));
74         _colours.push_back (wxColour (255, 139,   0));
75
76         set_analysis (shared_ptr<AudioAnalysis> ());
77
78 #if MAX_DCP_AUDIO_CHANNELS != 16
79 #warning AudioPlot::AudioPlot is expecting the wrong MAX_DCP_AUDIO_CHANNELS
80 #endif
81
82         Bind (wxEVT_PAINT, boost::bind (&AudioPlot::paint, this));
83
84         SetMinSize (wxSize (640, 512));
85 }
86
87 void
88 AudioPlot::set_analysis (shared_ptr<AudioAnalysis> a)
89 {
90         _analysis = a;
91
92         if (!a) {
93                 _message = _("Please wait; audio is being analysed...");
94         }
95
96         Refresh ();
97 }
98
99 void
100 AudioPlot::set_channel_visible (int c, bool v)
101 {
102         _channel_visible[c] = v;
103         Refresh ();
104 }
105
106 void
107 AudioPlot::set_type_visible (int t, bool v)
108 {
109         _type_visible[t] = v;
110         Refresh ();
111 }
112
113 void
114 AudioPlot::set_message (wxString s)
115 {
116         _message = s;
117         Refresh ();
118 }
119
120 struct Metrics
121 {
122         double db_label_width;
123         int height;
124         int y_origin;
125         float x_scale; ///< pixels per data point
126         float y_scale;
127 };
128
129 void
130 AudioPlot::paint ()
131 {
132         wxPaintDC dc (this);
133
134         wxGraphicsContext* gc = wxGraphicsContext::Create (dc);
135         if (!gc) {
136                 return;
137         }
138
139         if (!_analysis || _analysis->channels() == 0) {
140                 gc->SetFont (gc->CreateFont (*wxNORMAL_FONT));
141                 gc->DrawText (_message, 32, 32);
142                 return;
143         }
144
145         wxGraphicsPath h_grid = gc->CreatePath ();
146         gc->SetFont (gc->CreateFont (*wxSMALL_FONT));
147         wxDouble db_label_height;
148         wxDouble db_label_descent;
149         wxDouble db_label_leading;
150         Metrics metrics;
151         gc->GetTextExtent (wxT ("-80dB"), &metrics.db_label_width, &db_label_height, &db_label_descent, &db_label_leading);
152
153         metrics.db_label_width += 8;
154
155         int const data_width = GetSize().GetWidth() - metrics.db_label_width;
156         /* Assume all channels have the same number of points */
157         metrics.x_scale = data_width / float (_analysis->points (0));
158         metrics.height = GetSize().GetHeight ();
159         metrics.y_origin = 32;
160         metrics.y_scale = (metrics.height - metrics.y_origin) / -_minimum;
161
162         for (int i = _minimum; i <= 0; i += 10) {
163                 int const y = (metrics.height - (i - _minimum) * metrics.y_scale) - metrics.y_origin;
164                 h_grid.MoveToPoint (metrics.db_label_width - 4, y);
165                 h_grid.AddLineToPoint (metrics.db_label_width + data_width, y);
166                 gc->DrawText (std_to_wx (String::compose ("%1dB", i)), 0, y - (db_label_height / 2));
167         }
168
169         gc->SetPen (wxPen (wxColour (200, 200, 200)));
170         gc->StrokePath (h_grid);
171
172         /* Draw an x axis with marks */
173
174         wxGraphicsPath v_grid = gc->CreatePath ();
175
176         DCPOMATIC_ASSERT (_analysis->samples_per_point() != 0.0);
177         double const pps = _analysis->sample_rate() * metrics.x_scale / _analysis->samples_per_point();
178
179         gc->SetPen (*wxThePenList->FindOrCreatePen (wxColour (0, 0, 0), 1, wxPENSTYLE_SOLID));
180
181         double const mark_interval = calculate_mark_interval (rint (128 / pps));
182
183         DCPTime t = DCPTime::from_seconds (mark_interval);
184         while ((t.seconds() * pps) < data_width) {
185                 double tc = t.seconds ();
186                 int const h = tc / 3600;
187                 tc -= h * 3600;
188                 int const m = tc / 60;
189                 tc -= m * 60;
190                 int const s = tc;
191
192                 wxString str = wxString::Format (wxT ("%02d:%02d:%02d"), h, m, s);
193                 wxDouble str_width;
194                 wxDouble str_height;
195                 wxDouble str_descent;
196                 wxDouble str_leading;
197                 gc->GetTextExtent (str, &str_width, &str_height, &str_descent, &str_leading);
198
199                 int const tx = llrintf (metrics.db_label_width + t.seconds() * pps);
200                 gc->DrawText (str, tx - str_width / 2, metrics.height - metrics.y_origin + db_label_height);
201
202                 v_grid.MoveToPoint (tx, metrics.height - metrics.y_origin + 4);
203                 v_grid.AddLineToPoint (tx, metrics.y_origin);
204
205                 t += DCPTime::from_seconds (mark_interval);
206         }
207
208         gc->SetPen (wxPen (wxColour (200, 200, 200)));
209         gc->StrokePath (v_grid);
210
211         if (_type_visible[AudioPoint::PEAK]) {
212                 for (int c = 0; c < MAX_DCP_AUDIO_CHANNELS; ++c) {
213                         wxGraphicsPath p = gc->CreatePath ();
214                         if (_channel_visible[c] && c < _analysis->channels()) {
215                                 plot_peak (p, c, metrics);
216                         }
217                         wxColour const col = _colours[c];
218                         gc->SetPen (wxPen (wxColour (col.Red(), col.Green(), col.Blue(), col.Alpha() / 2), 1, wxPENSTYLE_SOLID));
219                         gc->StrokePath (p);
220                 }
221         }
222
223         if (_type_visible[AudioPoint::RMS]) {
224                 for (int c = 0; c < MAX_DCP_AUDIO_CHANNELS; ++c) {
225                         wxGraphicsPath p = gc->CreatePath ();
226                         if (_channel_visible[c] && c < _analysis->channels()) {
227                                 plot_rms (p, c, metrics);
228                         }
229                         wxColour const col = _colours[c];
230                         gc->SetPen (wxPen (col, 1, wxPENSTYLE_SOLID));
231                         gc->StrokePath (p);
232                 }
233         }
234
235         wxGraphicsPath axes = gc->CreatePath ();
236         axes.MoveToPoint (metrics.db_label_width, 0);
237         axes.AddLineToPoint (metrics.db_label_width, metrics.height - metrics.y_origin);
238         axes.AddLineToPoint (metrics.db_label_width + data_width, metrics.height - metrics.y_origin);
239         gc->SetPen (wxPen (wxColour (0, 0, 0)));
240         gc->StrokePath (axes);
241
242         delete gc;
243 }
244
245 float
246 AudioPlot::y_for_linear (float p, Metrics const & metrics) const
247 {
248         if (p < 1e-4) {
249                 p = 1e-4;
250         }
251
252         return metrics.height - (20 * log10(p) - _minimum) * metrics.y_scale - metrics.y_origin;
253 }
254
255 void
256 AudioPlot::plot_peak (wxGraphicsPath& path, int channel, Metrics const & metrics) const
257 {
258         if (_analysis->points (channel) == 0) {
259                 return;
260         }
261
262         _peak[channel] = PointList ();
263
264         float peak = 0;
265         int const N = _analysis->points(channel);
266         for (int i = 0; i < N; ++i) {
267                 float const p = get_point(channel, i)[AudioPoint::PEAK];
268                 peak -= 0.01f * (1 - log10 (_smoothing) / log10 (max_smoothing));
269                 if (p > peak) {
270                         peak = p;
271                 } else if (peak < 0) {
272                         peak = 0;
273                 }
274
275                 _peak[channel].push_back (
276                         Point (
277                                 wxPoint (metrics.db_label_width + i * metrics.x_scale, y_for_linear (peak, metrics)),
278                                 DCPTime::from_frames (i * _analysis->samples_per_point(), _analysis->sample_rate()),
279                                 peak
280                                 )
281                         );
282         }
283
284         DCPOMATIC_ASSERT (_peak.find(channel) != _peak.end());
285
286         path.MoveToPoint (_peak[channel][0].draw);
287         BOOST_FOREACH (Point const & i, _peak[channel]) {
288                 path.AddLineToPoint (i.draw);
289         }
290 }
291
292 void
293 AudioPlot::plot_rms (wxGraphicsPath& path, int channel, Metrics const & metrics) const
294 {
295         if (_analysis->points (channel) == 0) {
296                 return;
297         }
298
299         _rms[channel] = PointList();
300
301         list<float> smoothing;
302
303         int const N = _analysis->points(channel);
304
305         float const first = get_point(channel, 0)[AudioPoint::RMS];
306         float const last = get_point(channel, N - 1)[AudioPoint::RMS];
307
308         int const before = _smoothing / 2;
309         int const after = _smoothing - before;
310
311         /* Pre-load the smoothing list */
312         for (int i = 0; i < before; ++i) {
313                 smoothing.push_back (first);
314         }
315         for (int i = 0; i < after; ++i) {
316                 if (i < N) {
317                         smoothing.push_back (get_point(channel, i)[AudioPoint::RMS]);
318                 } else {
319                         smoothing.push_back (last);
320                 }
321         }
322
323         for (int i = 0; i < N; ++i) {
324
325                 int const next_for_window = i + after;
326
327                 if (next_for_window < N) {
328                         smoothing.push_back (get_point(channel, i)[AudioPoint::RMS]);
329                 } else {
330                         smoothing.push_back (last);
331                 }
332
333                 smoothing.pop_front ();
334
335                 float p = 0;
336                 for (list<float>::const_iterator j = smoothing.begin(); j != smoothing.end(); ++j) {
337                         p += pow (*j, 2);
338                 }
339
340                 if (!smoothing.empty ()) {
341                         p = sqrt (p / smoothing.size ());
342                 }
343
344                 _rms[channel].push_back (
345                         Point (
346                                 wxPoint (metrics.db_label_width + i * metrics.x_scale, y_for_linear (p, metrics)),
347                                 DCPTime::from_frames (i * _analysis->samples_per_point(), _analysis->sample_rate()),
348                                 p
349                                 )
350                         );
351         }
352
353         DCPOMATIC_ASSERT (_rms.find(channel) != _rms.end());
354
355         path.MoveToPoint (_rms[channel][0].draw);
356         BOOST_FOREACH (Point const & i, _rms[channel]) {
357                 path.AddLineToPoint (i.draw);
358         }
359 }
360
361 void
362 AudioPlot::set_smoothing (int s)
363 {
364         _smoothing = s;
365         _rms.clear ();
366         _peak.clear ();
367         Refresh ();
368 }
369
370 void
371 AudioPlot::set_gain_correction (double gain)
372 {
373         _gain_correction = gain;
374         Refresh ();
375 }
376
377 AudioPoint
378 AudioPlot::get_point (int channel, int point) const
379 {
380         AudioPoint p = _analysis->get_point (channel, point);
381         for (int i = 0; i < AudioPoint::COUNT; ++i) {
382                 p[i] *= pow (10, _gain_correction / 20);
383         }
384
385         return p;
386 }
387
388 /** @param n Channel index.
389  *  @return Colour used by that channel in the plot.
390  */
391 wxColour
392 AudioPlot::colour (int n) const
393 {
394         DCPOMATIC_ASSERT (n < int(_colours.size()));
395         return _colours[n];
396 }