f25ae4cb64cb1c8517c13605aa15181971778677
[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         if (!_analysis || _analysis->channels() == 0) {
164                 gc->SetFont (gc->CreateFont (*wxNORMAL_FONT));
165                 gc->DrawText (_message, 32, 32);
166                 delete gc;
167                 return;
168         }
169
170         auto h_grid = gc->CreatePath ();
171         gc->SetFont (gc->CreateFont (*wxSMALL_FONT));
172         wxDouble db_label_height;
173         wxDouble db_label_descent;
174         wxDouble db_label_leading;
175         Metrics metrics;
176         gc->GetTextExtent (wxT ("-80dB"), &metrics.db_label_width, &db_label_height, &db_label_descent, &db_label_leading);
177
178         metrics.db_label_width += 8;
179
180         int const data_width = GetSize().GetWidth() - metrics.db_label_width;
181         /* Assume all channels have the same number of points */
182         metrics.x_scale = data_width / float (_analysis->points (0));
183         metrics.height = GetSize().GetHeight ();
184         metrics.y_origin = 32;
185         metrics.y_scale = (metrics.height - metrics.y_origin) / -_minimum;
186
187         for (int i = _minimum; i <= 0; i += 10) {
188                 int const y = (metrics.height - (i - _minimum) * metrics.y_scale) - metrics.y_origin;
189                 h_grid.MoveToPoint (metrics.db_label_width - 4, y);
190                 h_grid.AddLineToPoint (metrics.db_label_width + data_width, y);
191                 gc->DrawText (std_to_wx (String::compose ("%1dB", i)), 0, y - (db_label_height / 2));
192         }
193
194         gc->SetPen (wxPen (wxColour (200, 200, 200)));
195         gc->StrokePath (h_grid);
196
197         /* Draw an x axis with marks */
198
199         auto v_grid = gc->CreatePath ();
200
201         DCPOMATIC_ASSERT (_analysis->samples_per_point() != 0.0);
202         double const pps = _analysis->sample_rate() * metrics.x_scale / _analysis->samples_per_point();
203
204         gc->SetPen (*wxThePenList->FindOrCreatePen (wxColour (0, 0, 0), 1, wxPENSTYLE_SOLID));
205
206         double const mark_interval = calculate_mark_interval (rint (128 / pps));
207
208         auto t = DCPTime::from_seconds (mark_interval);
209         while ((t.seconds() * pps) < data_width) {
210                 double tc = t.seconds ();
211                 int const h = tc / 3600;
212                 tc -= h * 3600;
213                 int const m = tc / 60;
214                 tc -= m * 60;
215                 int const s = tc;
216
217                 auto str = wxString::Format (wxT ("%02d:%02d:%02d"), h, m, s);
218                 wxDouble str_width;
219                 wxDouble str_height;
220                 wxDouble str_descent;
221                 wxDouble str_leading;
222                 gc->GetTextExtent (str, &str_width, &str_height, &str_descent, &str_leading);
223
224                 int const tx = llrintf (metrics.db_label_width + t.seconds() * pps);
225                 gc->DrawText (str, tx - str_width / 2, metrics.height - metrics.y_origin + db_label_height);
226
227                 v_grid.MoveToPoint (tx, metrics.height - metrics.y_origin + 4);
228                 v_grid.AddLineToPoint (tx, metrics.y_origin);
229
230                 t += DCPTime::from_seconds (mark_interval);
231         }
232
233         gc->SetPen (wxPen (wxColour (200, 200, 200)));
234         gc->StrokePath (v_grid);
235
236         if (_type_visible[AudioPoint::PEAK]) {
237                 for (int c = 0; c < MAX_DCP_AUDIO_CHANNELS; ++c) {
238                         auto p = gc->CreatePath ();
239                         if (_channel_visible[c] && c < _analysis->channels()) {
240                                 plot_peak (p, c, metrics);
241                         }
242                         auto const col = _colours[c];
243                         gc->SetPen (wxPen (wxColour (col.Red(), col.Green(), col.Blue(), col.Alpha() / 2), 1, wxPENSTYLE_SOLID));
244                         gc->StrokePath (p);
245                 }
246         }
247
248         if (_type_visible[AudioPoint::RMS]) {
249                 for (int c = 0; c < MAX_DCP_AUDIO_CHANNELS; ++c) {
250                         auto p = gc->CreatePath ();
251                         if (_channel_visible[c] && c < _analysis->channels()) {
252                                 plot_rms (p, c, metrics);
253                         }
254                         auto const col = _colours[c];
255                         gc->SetPen (wxPen (col, 1, wxPENSTYLE_SOLID));
256                         gc->StrokePath (p);
257                 }
258         }
259
260         auto axes = gc->CreatePath ();
261         axes.MoveToPoint (metrics.db_label_width, 0);
262         axes.AddLineToPoint (metrics.db_label_width, metrics.height - metrics.y_origin);
263         axes.AddLineToPoint (metrics.db_label_width + data_width, metrics.height - metrics.y_origin);
264         gc->SetPen (wxPen (wxColour (0, 0, 0)));
265         gc->StrokePath (axes);
266
267         if (_cursor) {
268                 auto cursor = gc->CreatePath ();
269                 cursor.MoveToPoint (_cursor->draw.x - _cursor_size / 2, _cursor->draw.y - _cursor_size / 2);
270                 cursor.AddLineToPoint (_cursor->draw.x + _cursor_size / 2, _cursor->draw.y + _cursor_size / 2);
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                 gc->StrokePath (cursor);
274         }
275
276         delete gc;
277 }
278
279
280 float
281 AudioPlot::y_for_linear (float p, Metrics const & metrics) const
282 {
283         if (p < 1e-4) {
284                 p = 1e-4;
285         }
286
287         return metrics.height - (linear_to_db(p) - _minimum) * metrics.y_scale - metrics.y_origin;
288 }
289
290
291 void
292 AudioPlot::plot_peak (wxGraphicsPath& path, int channel, Metrics const & metrics) const
293 {
294         if (_analysis->points (channel) == 0) {
295                 return;
296         }
297
298         _peak[channel] = PointList ();
299
300         float peak = 0;
301         int const N = _analysis->points(channel);
302         for (int i = 0; i < N; ++i) {
303                 float const p = get_point(channel, i)[AudioPoint::PEAK];
304                 peak -= 0.01f * (1 - log10 (_smoothing) / log10 (max_smoothing));
305                 if (p > peak) {
306                         peak = p;
307                 } else if (peak < 0) {
308                         peak = 0;
309                 }
310
311                 _peak[channel].push_back (
312                         Point (
313                                 wxPoint (metrics.db_label_width + i * metrics.x_scale, y_for_linear (peak, metrics)),
314                                 DCPTime::from_frames (i * _analysis->samples_per_point(), _analysis->sample_rate()),
315                                 linear_to_db(peak)
316                                 )
317                         );
318         }
319
320         DCPOMATIC_ASSERT (_peak.find(channel) != _peak.end());
321
322         path.MoveToPoint (_peak[channel][0].draw);
323         for (auto const& i: _peak[channel]) {
324                 path.AddLineToPoint (i.draw);
325         }
326 }
327
328
329 void
330 AudioPlot::plot_rms (wxGraphicsPath& path, int channel, Metrics const & metrics) const
331 {
332         if (_analysis->points (channel) == 0) {
333                 return;
334         }
335
336         _rms[channel] = PointList();
337
338         list<float> smoothing;
339
340         int const N = _analysis->points(channel);
341
342         float const first = get_point(channel, 0)[AudioPoint::RMS];
343         float const last = get_point(channel, N - 1)[AudioPoint::RMS];
344
345         int const before = _smoothing / 2;
346         int const after = _smoothing - before;
347
348         /* Pre-load the smoothing list */
349         for (int i = 0; i < before; ++i) {
350                 smoothing.push_back (first);
351         }
352         for (int i = 0; i < after; ++i) {
353                 if (i < N) {
354                         smoothing.push_back (get_point(channel, i)[AudioPoint::RMS]);
355                 } else {
356                         smoothing.push_back (last);
357                 }
358         }
359
360         for (int i = 0; i < N; ++i) {
361
362                 int const next_for_window = i + after;
363
364                 if (next_for_window < N) {
365                         smoothing.push_back (get_point(channel, i)[AudioPoint::RMS]);
366                 } else {
367                         smoothing.push_back (last);
368                 }
369
370                 smoothing.pop_front ();
371
372                 float p = 0;
373                 for (list<float>::const_iterator j = smoothing.begin(); j != smoothing.end(); ++j) {
374                         p += pow (*j, 2);
375                 }
376
377                 if (!smoothing.empty ()) {
378                         p = sqrt (p / smoothing.size ());
379                 }
380
381                 _rms[channel].push_back (
382                         Point (
383                                 wxPoint (metrics.db_label_width + i * metrics.x_scale, y_for_linear (p, metrics)),
384                                 DCPTime::from_frames (i * _analysis->samples_per_point(), _analysis->sample_rate()),
385                                 linear_to_db(p)
386                                 )
387                         );
388         }
389
390         DCPOMATIC_ASSERT (_rms.find(channel) != _rms.end());
391
392         path.MoveToPoint (_rms[channel][0].draw);
393         for (auto const& i: _rms[channel]) {
394                 path.AddLineToPoint (i.draw);
395         }
396 }
397
398
399 void
400 AudioPlot::set_smoothing (int s)
401 {
402         _smoothing = s;
403         _rms.clear ();
404         _peak.clear ();
405         Refresh ();
406 }
407
408
409 void
410 AudioPlot::set_gain_correction (double gain)
411 {
412         _gain_correction = gain;
413         Refresh ();
414 }
415
416
417 AudioPoint
418 AudioPlot::get_point (int channel, int point) const
419 {
420         auto p = _analysis->get_point (channel, point);
421         for (int i = 0; i < AudioPoint::COUNT; ++i) {
422                 p[i] *= db_to_linear(_gain_correction);
423         }
424
425         return p;
426 }
427
428
429 /** @param n Channel index.
430  *  @return Colour used by that channel in the plot.
431  */
432 wxColour
433 AudioPlot::colour (int n) const
434 {
435         DCPOMATIC_ASSERT (n < int(_colours.size()));
436         return _colours[n];
437 }
438
439
440 void
441 AudioPlot::search (map<int, PointList> const & search, wxMouseEvent const & ev, double& min_dist, Point& min_point) const
442 {
443         for (auto const& i: search) {
444                 for (auto const& j: i.second) {
445                         double const dist = pow(ev.GetX() - j.draw.x, 2) + pow(ev.GetY() - j.draw.y, 2);
446                         if (dist < min_dist) {
447                                 min_dist = dist;
448                                 min_point = j;
449                         }
450                 }
451         }
452 }
453
454
455 void
456 AudioPlot::left_down ()
457 {
458         if (_cursor) {
459                 if (auto fv = _viewer.lock()) {
460                         fv->seek (_cursor->time, true);
461                 }
462         }
463 }
464
465
466 void
467 AudioPlot::mouse_moved (wxMouseEvent& ev)
468 {
469         double min_dist = DBL_MAX;
470         Point min_point;
471
472         search (_rms, ev, min_dist, min_point);
473         search (_peak, ev, min_dist, min_point);
474
475         _cursor = {};
476
477         if (min_dist < DBL_MAX) {
478                 wxRect before (min_point.draw.x - _cursor_size / 2, min_point.draw.y - _cursor_size / 2, _cursor_size, _cursor_size);
479                 GetParent()->Refresh (true, &before);
480                 _cursor = min_point;
481                 wxRect after (min_point.draw.x - _cursor_size / 2, min_point.draw.y - _cursor_size / 2, _cursor_size, _cursor_size);
482                 GetParent()->Refresh (true, &after);
483                 Cursor (min_point.time, min_point.db);
484         }
485 }
486
487
488 void
489 AudioPlot::mouse_leave (wxMouseEvent &)
490 {
491         _cursor = {};
492         Refresh ();
493         Cursor (optional<DCPTime>(), optional<float>());
494 }