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