Add and use dB/linear conversion functions.
[dcpomatic.git] / src / wx / audio_dialog.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_dialog.h"
22 #include "audio_plot.h"
23 #include "wx_util.h"
24 #include "static_text.h"
25 #include "check_box.h"
26 #include "lib/audio_analysis.h"
27 #include "lib/film.h"
28 #include "lib/analyse_audio_job.h"
29 #include "lib/audio_content.h"
30 #include "lib/job_manager.h"
31 #include <libxml++/libxml++.h>
32 #include <boost/filesystem.hpp>
33 #include <boost/foreach.hpp>
34 #include <iostream>
35
36 using std::cout;
37 using std::list;
38 using std::vector;
39 using std::pair;
40 using boost::shared_ptr;
41 using boost::bind;
42 using boost::optional;
43 using boost::const_pointer_cast;
44 using boost::dynamic_pointer_cast;
45 using namespace dcpomatic;
46
47 /** @param parent Parent window.
48  *  @param film Film we are using.
49  *  @param content Content to analyse, or 0 to analyse all of the film's audio.
50  */
51 AudioDialog::AudioDialog (wxWindow* parent, shared_ptr<Film> film, shared_ptr<Content> content)
52         : wxDialog (
53                 parent,
54                 wxID_ANY,
55                 _("Audio"),
56                 wxDefaultPosition,
57                 wxSize (640, 512),
58 #ifdef DCPOMATIC_OSX
59                 /* I can't get wxFRAME_FLOAT_ON_PARENT to work on OS X, and although wxSTAY_ON_TOP keeps
60                    the window above all others (and not just our own) it's better than nothing for now.
61                 */
62                 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxFULL_REPAINT_ON_RESIZE | wxSTAY_ON_TOP
63 #else
64                 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxFULL_REPAINT_ON_RESIZE | wxFRAME_FLOAT_ON_PARENT
65 #endif
66                 )
67         , _film (film)
68         , _content (content)
69         , _channels (film->audio_channels ())
70         , _plot (0)
71 {
72         wxFont subheading_font (*wxNORMAL_FONT);
73         subheading_font.SetWeight (wxFONTWEIGHT_BOLD);
74
75         wxBoxSizer* overall_sizer = new wxBoxSizer (wxVERTICAL);
76         wxBoxSizer* lr_sizer = new wxBoxSizer (wxHORIZONTAL);
77
78         wxBoxSizer* left = new wxBoxSizer (wxVERTICAL);
79
80         _cursor = new StaticText (this, wxT("Cursor: none"));
81         left->Add (_cursor, 0, wxTOP, DCPOMATIC_SIZER_Y_GAP);
82         _plot = new AudioPlot (this);
83         left->Add (_plot, 1, wxTOP | wxEXPAND, 12);
84         _sample_peak = new StaticText (this, wxT (""));
85         left->Add (_sample_peak, 0, wxTOP, DCPOMATIC_SIZER_Y_GAP);
86         _true_peak = new StaticText (this, wxT (""));
87         left->Add (_true_peak, 0, wxTOP, DCPOMATIC_SIZER_Y_GAP);
88         _integrated_loudness = new StaticText (this, wxT (""));
89         left->Add (_integrated_loudness, 0, wxTOP, DCPOMATIC_SIZER_Y_GAP);
90         _loudness_range = new StaticText (this, wxT (""));
91         left->Add (_loudness_range, 0, wxTOP, DCPOMATIC_SIZER_Y_GAP);
92
93         lr_sizer->Add (left, 1, wxALL | wxEXPAND, 12);
94
95         wxBoxSizer* right = new wxBoxSizer (wxVERTICAL);
96
97         {
98                 wxStaticText* m = new StaticText (this, _("Channels"));
99                 m->SetFont (subheading_font);
100                 right->Add (m, 1, wxALIGN_CENTER_VERTICAL | wxTOP | wxBOTTOM, 16);
101         }
102
103         for (int i = 0; i < MAX_DCP_AUDIO_CHANNELS; ++i) {
104                 _channel_checkbox[i] = new CheckBox (this, std_to_wx(audio_channel_name(i)));
105                 _channel_checkbox[i]->SetForegroundColour(wxColour(_plot->colour(i)));
106                 right->Add (_channel_checkbox[i], 0, wxEXPAND | wxALL, 3);
107                 _channel_checkbox[i]->Bind (wxEVT_CHECKBOX, boost::bind (&AudioDialog::channel_clicked, this, _1));
108         }
109
110         {
111                 wxStaticText* m = new StaticText (this, _("Type"));
112                 m->SetFont (subheading_font);
113                 right->Add (m, 1, wxALIGN_CENTER_VERTICAL | wxTOP, 16);
114         }
115
116         wxString const types[] = {
117                 _("Peak"),
118                 _("RMS")
119         };
120
121         for (int i = 0; i < AudioPoint::COUNT; ++i) {
122                 _type_checkbox[i] = new CheckBox (this, types[i]);
123                 right->Add (_type_checkbox[i], 0, wxEXPAND | wxALL, 3);
124                 _type_checkbox[i]->Bind (wxEVT_CHECKBOX, boost::bind (&AudioDialog::type_clicked, this, _1));
125         }
126
127         {
128                 wxStaticText* m = new StaticText (this, _("Smoothing"));
129                 m->SetFont (subheading_font);
130                 right->Add (m, 1, wxALIGN_CENTER_VERTICAL | wxTOP, 16);
131         }
132
133         _smoothing = new wxSlider (this, wxID_ANY, AudioPlot::max_smoothing / 2, 1, AudioPlot::max_smoothing);
134         _smoothing->Bind (wxEVT_SCROLL_THUMBTRACK, boost::bind (&AudioDialog::smoothing_changed, this));
135         right->Add (_smoothing, 0, wxEXPAND);
136
137         lr_sizer->Add (right, 0, wxALL, 12);
138
139         overall_sizer->Add (lr_sizer, 0, wxEXPAND);
140
141 #ifdef DCPOMATIC_LINUX
142         wxSizer* buttons = CreateSeparatedButtonSizer (wxCLOSE);
143         if (buttons) {
144                 overall_sizer->Add (buttons, wxSizerFlags().Expand().DoubleBorder());
145         }
146 #endif
147
148         SetSizer (overall_sizer);
149         overall_sizer->Layout ();
150         overall_sizer->SetSizeHints (this);
151
152         _film_connection = film->Change.connect (boost::bind(&AudioDialog::film_change, this, _1, _2));
153         _film_content_connection = film->ContentChange.connect (boost::bind (&AudioDialog::content_change, this, _1, _3));
154         DCPOMATIC_ASSERT (film->directory());
155         SetTitle(wxString::Format(_("DCP-o-matic audio - %s"), std_to_wx(film->directory().get().string())));
156
157         if (content) {
158                 _playlist.reset (new Playlist ());
159                 const_pointer_cast<Playlist>(_playlist)->add(film, content);
160         } else {
161                 _playlist = film->playlist ();
162         }
163
164         _plot->Cursor.connect (bind (&AudioDialog::set_cursor, this, _1, _2));
165 }
166
167 void
168 AudioDialog::try_to_load_analysis ()
169 {
170         if (!IsShown ()) {
171                 return;
172         }
173
174         shared_ptr<const Film> film = _film.lock ();
175         DCPOMATIC_ASSERT (film);
176
177         shared_ptr<Content> check = _content.lock();
178
179         boost::filesystem::path const path = film->audio_analysis_path (_playlist);
180         if (!boost::filesystem::exists (path)) {
181                 _plot->set_analysis (shared_ptr<AudioAnalysis> ());
182                 _analysis.reset ();
183
184                 BOOST_FOREACH (shared_ptr<Job> i, JobManager::instance()->get()) {
185                         if (dynamic_pointer_cast<AnalyseAudioJob>(i)) {
186                                 i->cancel ();
187                         }
188                 }
189
190                 JobManager::instance()->analyse_audio (
191                         film, _playlist, !static_cast<bool>(check), _analysis_finished_connection, bind (&AudioDialog::analysis_finished, this)
192                         );
193                 return;
194         }
195
196         try {
197                 _analysis.reset (new AudioAnalysis (path));
198         } catch (OldFormatError& e) {
199                 /* An old analysis file: recreate it */
200                 JobManager::instance()->analyse_audio (
201                         film, _playlist, !static_cast<bool>(check), _analysis_finished_connection, bind (&AudioDialog::analysis_finished, this)
202                         );
203                 return;
204         } catch (xmlpp::exception& e) {
205                 /* Probably a (very) old-style analysis file: recreate it */
206                 JobManager::instance()->analyse_audio (
207                         film, _playlist, !static_cast<bool>(check), _analysis_finished_connection, bind (&AudioDialog::analysis_finished, this)
208                         );
209                 return;
210         }
211
212         _plot->set_analysis (_analysis);
213         _plot->set_gain_correction (_analysis->gain_correction (_playlist));
214         setup_statistics ();
215
216         for (int i = 0; i < _channels; ++i) {
217                 _channel_checkbox[i]->Show ();
218         }
219
220         for (int i = _channels; i < MAX_DCP_AUDIO_CHANNELS; ++i) {
221                 _channel_checkbox[i]->Hide ();
222         }
223
224         /* Set up some defaults if no check boxes are checked */
225
226         int i = 0;
227         while (i < _channels && (!_channel_checkbox[i] || !_channel_checkbox[i]->GetValue ())) {
228                 ++i;
229         }
230
231         if (i == _channels) {
232                 /* Nothing checked; check mapped ones */
233
234                 list<int> mapped;
235                 shared_ptr<Content> content = _content.lock ();
236
237                 if (content) {
238                         mapped = content->audio->mapping().mapped_output_channels ();
239                 } else {
240                         mapped = film->mapped_audio_channels ();
241                 }
242
243                 BOOST_FOREACH (int i, mapped) {
244                         if (_channel_checkbox[i]) {
245                                 _channel_checkbox[i]->SetValue (true);
246                                 _plot->set_channel_visible (i, true);
247                         }
248                 }
249         }
250
251         i = 0;
252         while (i < AudioPoint::COUNT && !_type_checkbox[i]->GetValue ()) {
253                 i++;
254         }
255
256         if (i == AudioPoint::COUNT) {
257                 for (int i = 0; i < AudioPoint::COUNT; ++i) {
258                         _type_checkbox[i]->SetValue (true);
259                         _plot->set_type_visible (i, true);
260                 }
261         }
262
263         Refresh ();
264 }
265
266 void
267 AudioDialog::analysis_finished ()
268 {
269         shared_ptr<const Film> film = _film.lock ();
270         if (!film) {
271                 /* This should not happen, but if it does we should just give up quietly */
272                 return;
273         }
274
275         if (!boost::filesystem::exists (film->audio_analysis_path (_playlist))) {
276                 /* We analysed and still nothing showed up, so maybe it was cancelled or it failed.
277                    Give up.
278                 */
279                 _plot->set_message (_("Could not analyse audio."));
280                 return;
281         }
282
283         try_to_load_analysis ();
284 }
285
286 void
287 AudioDialog::channel_clicked (wxCommandEvent& ev)
288 {
289         int c = 0;
290         while (c < _channels && ev.GetEventObject() != _channel_checkbox[c]) {
291                 ++c;
292         }
293
294         DCPOMATIC_ASSERT (c < _channels);
295
296         _plot->set_channel_visible (c, _channel_checkbox[c]->GetValue ());
297 }
298
299 void
300 AudioDialog::film_change (ChangeType type, int p)
301 {
302         if (type != CHANGE_TYPE_DONE) {
303                 return;
304         }
305
306         if (p == Film::AUDIO_CHANNELS) {
307                 shared_ptr<Film> film = _film.lock ();
308                 if (film) {
309                         _channels = film->audio_channels ();
310                         try_to_load_analysis ();
311                 }
312         }
313 }
314
315 void
316 AudioDialog::content_change (ChangeType type, int p)
317 {
318         if (type != CHANGE_TYPE_DONE) {
319                 return;
320         }
321
322         if (p == AudioContentProperty::STREAMS) {
323                 try_to_load_analysis ();
324         } else if (p == AudioContentProperty::GAIN) {
325                 if (_playlist->content().size() == 1 && _analysis) {
326                         /* We can use a short-cut to render the effect of this
327                            change, rather than recalculating everything.
328                         */
329                         _plot->set_gain_correction (_analysis->gain_correction (_playlist));
330                         setup_statistics ();
331                 } else {
332                         try_to_load_analysis ();
333                 }
334         }
335 }
336
337 void
338 AudioDialog::type_clicked (wxCommandEvent& ev)
339 {
340         int t = 0;
341         while (t < AudioPoint::COUNT && ev.GetEventObject() != _type_checkbox[t]) {
342                 ++t;
343         }
344
345         DCPOMATIC_ASSERT (t < AudioPoint::COUNT);
346
347         _plot->set_type_visible (t, _type_checkbox[t]->GetValue ());
348 }
349
350 void
351 AudioDialog::smoothing_changed ()
352 {
353         _plot->set_smoothing (_smoothing->GetValue ());
354 }
355
356 void
357 AudioDialog::setup_statistics ()
358 {
359         if (!_analysis) {
360                 return;
361         }
362
363         shared_ptr<Film> film = _film.lock ();
364         if (!film) {
365                 return;
366         }
367
368         pair<AudioAnalysis::PeakTime, int> const peak = _analysis->overall_sample_peak ();
369         float const peak_dB = linear_to_db(peak.first.peak) + _analysis->gain_correction(_playlist);
370         _sample_peak->SetLabel (
371                 wxString::Format (
372                         _("Sample peak is %.2fdB at %s on %s"),
373                         peak_dB,
374                         time_to_timecode (peak.first.time, film->video_frame_rate ()).data (),
375                         std_to_wx (short_audio_channel_name (peak.second)).data ()
376                         )
377                 );
378
379         if (peak_dB > -3) {
380                 _sample_peak->SetForegroundColour (wxColour (255, 0, 0));
381         } else {
382                 _sample_peak->SetForegroundColour (wxColour (0, 0, 0));
383         }
384
385         if (_analysis->overall_true_peak()) {
386                 float const peak = _analysis->overall_true_peak().get();
387                 float const peak_dB = linear_to_db(peak) + _analysis->gain_correction(_playlist);
388
389                 _true_peak->SetLabel (wxString::Format (_("True peak is %.2fdB"), peak_dB));
390
391                 if (peak_dB > -3) {
392                         _true_peak->SetForegroundColour (wxColour (255, 0, 0));
393                 } else {
394                         _true_peak->SetForegroundColour (wxColour (0, 0, 0));
395                 }
396         }
397
398         /* XXX: check whether it's ok to add dB gain to these quantities */
399
400         if (static_cast<bool>(_analysis->integrated_loudness ())) {
401                 _integrated_loudness->SetLabel (
402                         wxString::Format (
403                                 _("Integrated loudness %.2f LUFS"),
404                                 _analysis->integrated_loudness().get() + _analysis->gain_correction (_playlist)
405                                 )
406                         );
407         }
408
409         if (static_cast<bool>(_analysis->loudness_range ())) {
410                 _loudness_range->SetLabel (
411                         wxString::Format (
412                                 _("Loudness range %.2f LU"),
413                                 _analysis->loudness_range().get() + _analysis->gain_correction (_playlist)
414                                 )
415                         );
416         }
417 }
418
419 bool
420 AudioDialog::Show (bool show)
421 {
422         bool const r = wxDialog::Show (show);
423         try_to_load_analysis ();
424         return r;
425 }
426
427 void
428 AudioDialog::set_cursor (optional<DCPTime> time, optional<float> db)
429 {
430         if (!time || !db) {
431                 _cursor->SetLabel (_("Cursor: none"));
432                 return;
433         }
434
435         shared_ptr<Film> film = _film.lock();
436         DCPOMATIC_ASSERT (film);
437         _cursor->SetLabel (wxString::Format (_("Cursor: %.1fdB at %s"), *db, time->timecode(film->video_frame_rate())));
438 }