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