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