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