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