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