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