Add and use dB/linear conversion functions.
[dcpomatic.git] / src / wx / audio_plot.cc
1 /*
2     Copyright (C) 2013-2018 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 #include <cfloat>
30
31 using std::cout;
32 using std::vector;
33 using std::list;
34 using std::max;
35 using std::min;
36 using std::map;
37 using boost::bind;
38 using boost::optional;
39 using boost::shared_ptr;
40 using namespace dcpomatic;
41
42 int const AudioPlot::_minimum = -70;
43 int const AudioPlot::_cursor_size = 8;
44 int const AudioPlot::max_smoothing = 128;
45
46 AudioPlot::AudioPlot (wxWindow* parent)
47         : wxPanel (parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE)
48         , _smoothing (max_smoothing / 2)
49         , _gain_correction (0)
50 {
51 #ifndef __WXOSX__
52         SetDoubleBuffered (true);
53 #endif
54
55         for (int i = 0; i < MAX_DCP_AUDIO_CHANNELS; ++i) {
56                 _channel_visible[i] = false;
57         }
58
59         for (int i = 0; i < AudioPoint::COUNT; ++i) {
60                 _type_visible[i] = false;
61         }
62
63         _colours.push_back (wxColour (  0,   0,   0));
64         _colours.push_back (wxColour (255,   0,   0));
65         _colours.push_back (wxColour (  0, 255,   0));
66         _colours.push_back (wxColour (139,   0, 204));
67         _colours.push_back (wxColour (  0,   0, 255));
68         _colours.push_back (wxColour (  0, 139,   0));
69         _colours.push_back (wxColour (  0,   0, 139));
70         _colours.push_back (wxColour (255, 255,   0));
71         _colours.push_back (wxColour (  0, 255, 255));
72         _colours.push_back (wxColour (255,   0, 255));
73         _colours.push_back (wxColour (255,   0, 139));
74         _colours.push_back (wxColour (139,   0, 255));
75
76         _colours.push_back (wxColour (139, 139, 255));
77         _colours.push_back (wxColour (  0, 139, 255));
78         _colours.push_back (wxColour (255, 139, 139));
79         _colours.push_back (wxColour (255, 139,   0));
80
81         set_analysis (shared_ptr<AudioAnalysis> ());
82
83 #if MAX_DCP_AUDIO_CHANNELS != 16
84 #warning AudioPlot::AudioPlot is expecting the wrong MAX_DCP_AUDIO_CHANNELS
85 #endif
86
87         Bind (wxEVT_PAINT, boost::bind (&AudioPlot::paint, this));
88         Bind (wxEVT_MOTION, boost::bind (&AudioPlot::mouse_moved, this, _1));
89         Bind (wxEVT_LEAVE_WINDOW, boost::bind (&AudioPlot::mouse_leave, this, _1));
90
91         SetMinSize (wxSize (640, 512));
92 }
93
94 void
95 AudioPlot::set_analysis (shared_ptr<AudioAnalysis> a)
96 {
97         _analysis = a;
98
99         if (!a) {
100                 _message = _("Please wait; audio is being analysed...");
101         }
102
103         Refresh ();
104 }
105
106 void
107 AudioPlot::set_channel_visible (int c, bool v)
108 {
109         _channel_visible[c] = v;
110         Refresh ();
111 }
112
113 void
114 AudioPlot::set_type_visible (int t, bool v)
115 {
116         _type_visible[t] = v;
117         Refresh ();
118 }
119
120 void
121 AudioPlot::set_message (wxString s)
122 {
123         _message = s;
124         Refresh ();
125 }
126
127 struct Metrics
128 {
129         double db_label_width;
130         int height;
131         int y_origin;
132         float x_scale; ///< pixels per data point
133         float y_scale;
134 };
135
136 void
137 AudioPlot::paint ()
138 {
139         wxPaintDC dc (this);
140
141         wxGraphicsContext* gc = wxGraphicsContext::Create (dc);
142         if (!gc) {
143                 return;
144         }
145
146         if (!_analysis || _analysis->channels() == 0) {
147                 gc->SetFont (gc->CreateFont (*wxNORMAL_FONT));
148                 gc->DrawText (_message, 32, 32);
149                 return;
150         }
151
152         wxGraphicsPath h_grid = gc->CreatePath ();
153         gc->SetFont (gc->CreateFont (*wxSMALL_FONT));
154         wxDouble db_label_height;
155         wxDouble db_label_descent;
156         wxDouble db_label_leading;
157         Metrics metrics;
158         gc->GetTextExtent (wxT ("-80dB"), &metrics.db_label_width, &db_label_height, &db_label_descent, &db_label_leading);
159
160         metrics.db_label_width += 8;
161
162         int const data_width = GetSize().GetWidth() - metrics.db_label_width;
163         /* Assume all channels have the same number of points */
164         metrics.x_scale = data_width / float (_analysis->points (0));
165         metrics.height = GetSize().GetHeight ();
166         metrics.y_origin = 32;
167         metrics.y_scale = (metrics.height - metrics.y_origin) / -_minimum;
168
169         for (int i = _minimum; i <= 0; i += 10) {
170                 int const y = (metrics.height - (i - _minimum) * metrics.y_scale) - metrics.y_origin;
171                 h_grid.MoveToPoint (metrics.db_label_width - 4, y);
172                 h_grid.AddLineToPoint (metrics.db_label_width + data_width, y);
173                 gc->DrawText (std_to_wx (String::compose ("%1dB", i)), 0, y - (db_label_height / 2));
174         }
175
176         gc->SetPen (wxPen (wxColour (200, 200, 200)));
177         gc->StrokePath (h_grid);
178
179         /* Draw an x axis with marks */
180
181         wxGraphicsPath v_grid = gc->CreatePath ();
182
183         DCPOMATIC_ASSERT (_analysis->samples_per_point() != 0.0);
184         double const pps = _analysis->sample_rate() * metrics.x_scale / _analysis->samples_per_point();
185
186         gc->SetPen (*wxThePenList->FindOrCreatePen (wxColour (0, 0, 0), 1, wxPENSTYLE_SOLID));
187
188         double const mark_interval = calculate_mark_interval (rint (128 / pps));
189
190         DCPTime t = DCPTime::from_seconds (mark_interval);
191         while ((t.seconds() * pps) < data_width) {
192                 double tc = t.seconds ();
193                 int const h = tc / 3600;
194                 tc -= h * 3600;
195                 int const m = tc / 60;
196                 tc -= m * 60;
197                 int const s = tc;
198
199                 wxString str = wxString::Format (wxT ("%02d:%02d:%02d"), h, m, s);
200                 wxDouble str_width;
201                 wxDouble str_height;
202                 wxDouble str_descent;
203                 wxDouble str_leading;
204                 gc->GetTextExtent (str, &str_width, &str_height, &str_descent, &str_leading);
205
206                 int const tx = llrintf (metrics.db_label_width + t.seconds() * pps);
207                 gc->DrawText (str, tx - str_width / 2, metrics.height - metrics.y_origin + db_label_height);
208
209                 v_grid.MoveToPoint (tx, metrics.height - metrics.y_origin + 4);
210                 v_grid.AddLineToPoint (tx, metrics.y_origin);
211
212                 t += DCPTime::from_seconds (mark_interval);
213         }
214
215         gc->SetPen (wxPen (wxColour (200, 200, 200)));
216         gc->StrokePath (v_grid);
217
218         if (_type_visible[AudioPoint::PEAK]) {
219                 for (int c = 0; c < MAX_DCP_AUDIO_CHANNELS; ++c) {
220                         wxGraphicsPath p = gc->CreatePath ();
221                         if (_channel_visible[c] && c < _analysis->channels()) {
222                                 plot_peak (p, c, metrics);
223                         }
224                         wxColour const col = _colours[c];
225                         gc->SetPen (wxPen (wxColour (col.Red(), col.Green(), col.Blue(), col.Alpha() / 2), 1, wxPENSTYLE_SOLID));
226                         gc->StrokePath (p);
227                 }
228         }
229
230         if (_type_visible[AudioPoint::RMS]) {
231                 for (int c = 0; c < MAX_DCP_AUDIO_CHANNELS; ++c) {
232                         wxGraphicsPath p = gc->CreatePath ();
233                         if (_channel_visible[c] && c < _analysis->channels()) {
234                                 plot_rms (p, c, metrics);
235                         }
236                         wxColour const col = _colours[c];
237                         gc->SetPen (wxPen (col, 1, wxPENSTYLE_SOLID));
238                         gc->StrokePath (p);
239                 }
240         }
241
242         wxGraphicsPath axes = gc->CreatePath ();
243         axes.MoveToPoint (metrics.db_label_width, 0);
244         axes.AddLineToPoint (metrics.db_label_width, metrics.height - metrics.y_origin);
245         axes.AddLineToPoint (metrics.db_label_width + data_width, metrics.height - metrics.y_origin);
246         gc->SetPen (wxPen (wxColour (0, 0, 0)));
247         gc->StrokePath (axes);
248
249         if (_cursor) {
250                 wxGraphicsPath cursor = gc->CreatePath ();
251                 cursor.MoveToPoint (_cursor->draw.x - _cursor_size / 2, _cursor->draw.y - _cursor_size / 2);
252                 cursor.AddLineToPoint (_cursor->draw.x + _cursor_size / 2, _cursor->draw.y + _cursor_size / 2);
253                 cursor.MoveToPoint (_cursor->draw.x + _cursor_size / 2, _cursor->draw.y - _cursor_size / 2);
254                 cursor.AddLineToPoint (_cursor->draw.x - _cursor_size / 2, _cursor->draw.y + _cursor_size / 2);
255                 gc->StrokePath (cursor);
256
257
258         }
259
260         delete gc;
261 }
262
263 float
264 AudioPlot::y_for_linear (float p, Metrics const & metrics) const
265 {
266         if (p < 1e-4) {
267                 p = 1e-4;
268         }
269
270         return metrics.height - (linear_to_db(p) - _minimum) * metrics.y_scale - metrics.y_origin;
271 }
272
273 void
274 AudioPlot::plot_peak (wxGraphicsPath& path, int channel, Metrics const & metrics) const
275 {
276         if (_analysis->points (channel) == 0) {
277                 return;
278         }
279
280         _peak[channel] = PointList ();
281
282         float peak = 0;
283         int const N = _analysis->points(channel);
284         for (int i = 0; i < N; ++i) {
285                 float const p = get_point(channel, i)[AudioPoint::PEAK];
286                 peak -= 0.01f * (1 - log10 (_smoothing) / log10 (max_smoothing));
287                 if (p > peak) {
288                         peak = p;
289                 } else if (peak < 0) {
290                         peak = 0;
291                 }
292
293                 _peak[channel].push_back (
294                         Point (
295                                 wxPoint (metrics.db_label_width + i * metrics.x_scale, y_for_linear (peak, metrics)),
296                                 DCPTime::from_frames (i * _analysis->samples_per_point(), _analysis->sample_rate()),
297                                 linear_to_db(peak)
298                                 )
299                         );
300         }
301
302         DCPOMATIC_ASSERT (_peak.find(channel) != _peak.end());
303
304         path.MoveToPoint (_peak[channel][0].draw);
305         BOOST_FOREACH (Point const & i, _peak[channel]) {
306                 path.AddLineToPoint (i.draw);
307         }
308 }
309
310 void
311 AudioPlot::plot_rms (wxGraphicsPath& path, int channel, Metrics const & metrics) const
312 {
313         if (_analysis->points (channel) == 0) {
314                 return;
315         }
316
317         _rms[channel] = PointList();
318
319         list<float> smoothing;
320
321         int const N = _analysis->points(channel);
322
323         float const first = get_point(channel, 0)[AudioPoint::RMS];
324         float const last = get_point(channel, N - 1)[AudioPoint::RMS];
325
326         int const before = _smoothing / 2;
327         int const after = _smoothing - before;
328
329         /* Pre-load the smoothing list */
330         for (int i = 0; i < before; ++i) {
331                 smoothing.push_back (first);
332         }
333         for (int i = 0; i < after; ++i) {
334                 if (i < N) {
335                         smoothing.push_back (get_point(channel, i)[AudioPoint::RMS]);
336                 } else {
337                         smoothing.push_back (last);
338                 }
339         }
340
341         for (int i = 0; i < N; ++i) {
342
343                 int const next_for_window = i + after;
344
345                 if (next_for_window < N) {
346                         smoothing.push_back (get_point(channel, i)[AudioPoint::RMS]);
347                 } else {
348                         smoothing.push_back (last);
349                 }
350
351                 smoothing.pop_front ();
352
353                 float p = 0;
354                 for (list<float>::const_iterator j = smoothing.begin(); j != smoothing.end(); ++j) {
355                         p += pow (*j, 2);
356                 }
357
358                 if (!smoothing.empty ()) {
359                         p = sqrt (p / smoothing.size ());
360                 }
361
362                 _rms[channel].push_back (
363                         Point (
364                                 wxPoint (metrics.db_label_width + i * metrics.x_scale, y_for_linear (p, metrics)),
365                                 DCPTime::from_frames (i * _analysis->samples_per_point(), _analysis->sample_rate()),
366                                 linear_to_db(p)
367                                 )
368                         );
369         }
370
371         DCPOMATIC_ASSERT (_rms.find(channel) != _rms.end());
372
373         path.MoveToPoint (_rms[channel][0].draw);
374         BOOST_FOREACH (Point const & i, _rms[channel]) {
375                 path.AddLineToPoint (i.draw);
376         }
377 }
378
379 void
380 AudioPlot::set_smoothing (int s)
381 {
382         _smoothing = s;
383         _rms.clear ();
384         _peak.clear ();
385         Refresh ();
386 }
387
388 void
389 AudioPlot::set_gain_correction (double gain)
390 {
391         _gain_correction = gain;
392         Refresh ();
393 }
394
395 AudioPoint
396 AudioPlot::get_point (int channel, int point) const
397 {
398         AudioPoint p = _analysis->get_point (channel, point);
399         for (int i = 0; i < AudioPoint::COUNT; ++i) {
400                 p[i] *= db_to_linear(_gain_correction);
401         }
402
403         return p;
404 }
405
406 /** @param n Channel index.
407  *  @return Colour used by that channel in the plot.
408  */
409 wxColour
410 AudioPlot::colour (int n) const
411 {
412         DCPOMATIC_ASSERT (n < int(_colours.size()));
413         return _colours[n];
414 }
415
416 void
417 AudioPlot::search (map<int, PointList> const & search, wxMouseEvent const & ev, double& min_dist, Point& min_point) const
418 {
419         for (map<int, PointList>::const_iterator i = search.begin(); i != search.end(); ++i) {
420                 BOOST_FOREACH (Point const & j, i->second) {
421                         double const dist = pow(ev.GetX() - j.draw.x, 2) + pow(ev.GetY() - j.draw.y, 2);
422                         if (dist < min_dist) {
423                                 min_dist = dist;
424                                 min_point = j;
425                         }
426                 }
427         }
428 }
429
430 void
431 AudioPlot::mouse_moved (wxMouseEvent& ev)
432 {
433         double min_dist = DBL_MAX;
434         Point min_point;
435
436         search (_rms, ev, min_dist, min_point);
437         search (_peak, ev, min_dist, min_point);
438
439         _cursor = optional<Point> ();
440
441         if (min_dist < DBL_MAX) {
442                 wxRect before (min_point.draw.x - _cursor_size / 2, min_point.draw.y - _cursor_size / 2, _cursor_size, _cursor_size);
443                 GetParent()->Refresh (true, &before);
444                 _cursor = min_point;
445                 wxRect after (min_point.draw.x - _cursor_size / 2, min_point.draw.y - _cursor_size / 2, _cursor_size, _cursor_size);
446                 GetParent()->Refresh (true, &after);
447                 Cursor (min_point.time, min_point.db);
448         }
449 }
450
451 void
452 AudioPlot::mouse_leave (wxMouseEvent &)
453 {
454         _cursor = optional<Point> ();
455         Refresh ();
456         Cursor (optional<DCPTime>(), optional<float>());
457 }