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