Add more logging and some missing prefs checkboxes for existing logging.
[dcpomatic.git] / src / lib / analyse_audio_job.cc
1 /*
2     Copyright (C) 2012-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_analysis.h"
22 #include "audio_buffers.h"
23 #include "analyse_audio_job.h"
24 #include "audio_content.h"
25 #include "compose.hpp"
26 #include "dcpomatic_log.h"
27 #include "film.h"
28 #include "player.h"
29 #include "playlist.h"
30 #include "filter.h"
31 #include "audio_filter_graph.h"
32 #include "config.h"
33 extern "C" {
34 #include <leqm_nrt.h>
35 #include <libavutil/channel_layout.h>
36 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
37 #include <libavfilter/f_ebur128.h>
38 #endif
39 }
40 #include <boost/foreach.hpp>
41 #include <iostream>
42
43 #include "i18n.h"
44
45 using std::string;
46 using std::vector;
47 using std::max;
48 using std::min;
49 using std::cout;
50 using boost::shared_ptr;
51 using boost::dynamic_pointer_cast;
52 using namespace dcpomatic;
53
54 int const AnalyseAudioJob::_num_points = 1024;
55
56 static void add_if_required(vector<double>& v, size_t i, double db)
57 {
58         if (v.size() > i) {
59                 v[i] = pow(10, db / 20);
60         }
61 }
62
63 /** @param from_zero true to analyse audio from time 0 in the playlist, otherwise begin at Playlist::start */
64 AnalyseAudioJob::AnalyseAudioJob (shared_ptr<const Film> film, shared_ptr<const Playlist> playlist, bool from_zero)
65         : Job (film)
66         , _playlist (playlist)
67         , _path (film->audio_analysis_path(playlist))
68         , _from_zero (from_zero)
69         , _done (0)
70         , _samples_per_point (1)
71         , _current (0)
72         , _sample_peak (new float[film->audio_channels()])
73         , _sample_peak_frame (new Frame[film->audio_channels()])
74 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
75         , _ebur128 (new AudioFilterGraph (film->audio_frame_rate(), film->audio_channels()))
76 #endif
77 {
78         LOG_DEBUG_AUDIO_ANALYSIS_NC("AnalyseAudioJob::AnalyseAudioJob");
79
80 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
81         _filters.push_back (new Filter ("ebur128", "ebur128", "audio", "ebur128=peak=true"));
82         _ebur128->setup (_filters);
83 #endif
84
85         for (int i = 0; i < film->audio_channels(); ++i) {
86                 _sample_peak[i] = 0;
87                 _sample_peak_frame[i] = 0;
88         }
89
90         if (!_from_zero) {
91                 _start = _playlist->start().get_value_or(DCPTime());
92         }
93
94         /* XXX: is this right?  Especially for more than 5.1? */
95         vector<double> channel_corrections(film->audio_channels(), 1);
96         add_if_required (channel_corrections,  4,   -3); // Ls
97         add_if_required (channel_corrections,  5,   -3); // Rs
98         add_if_required (channel_corrections,  6, -144); // HI
99         add_if_required (channel_corrections,  7, -144); // VI
100         add_if_required (channel_corrections,  8,   -3); // Lc
101         add_if_required (channel_corrections,  9,   -3); // Rc
102         add_if_required (channel_corrections, 10,   -3); // Lc
103         add_if_required (channel_corrections, 11,   -3); // Rc
104         add_if_required (channel_corrections, 12, -144); // DBox
105         add_if_required (channel_corrections, 13, -144); // Sync
106         add_if_required (channel_corrections, 14, -144); // Sign Language
107         add_if_required (channel_corrections, 15, -144); // Unused
108
109         _leqm.reset(new leqm_nrt::Calculator(
110                 film->audio_channels(),
111                 film->audio_frame_rate(),
112                 24,
113                 channel_corrections,
114                 850, // suggested by leqm_nrt CLI source
115                 64,  // suggested by leqm_nrt CLI source
116                 boost::thread::hardware_concurrency()
117                 ));
118 }
119
120 AnalyseAudioJob::~AnalyseAudioJob ()
121 {
122         stop_thread ();
123         BOOST_FOREACH (Filter const * i, _filters) {
124                 delete const_cast<Filter*> (i);
125         }
126         delete[] _current;
127         delete[] _sample_peak;
128         delete[] _sample_peak_frame;
129 }
130
131 string
132 AnalyseAudioJob::name () const
133 {
134         return _("Analysing audio");
135 }
136
137 string
138 AnalyseAudioJob::json_name () const
139 {
140         return N_("analyse_audio");
141 }
142
143 void
144 AnalyseAudioJob::run ()
145 {
146         LOG_DEBUG_AUDIO_ANALYSIS_NC("AnalyseAudioJob::run");
147
148         shared_ptr<Player> player (new Player(_film, _playlist));
149         player->set_ignore_video ();
150         player->set_ignore_text ();
151         player->set_fast ();
152         player->set_play_referenced ();
153         player->Audio.connect (bind (&AnalyseAudioJob::analyse, this, _1, _2));
154
155         DCPTime const length = _playlist->length (_film);
156
157         Frame const len = DCPTime (length - _start).frames_round (_film->audio_frame_rate());
158         _samples_per_point = max (int64_t (1), len / _num_points);
159
160         delete[] _current;
161         _current = new AudioPoint[_film->audio_channels ()];
162         _analysis.reset (new AudioAnalysis (_film->audio_channels ()));
163
164         bool has_any_audio = false;
165         BOOST_FOREACH (shared_ptr<Content> c, _playlist->content ()) {
166                 if (c->audio) {
167                         has_any_audio = true;
168                 }
169         }
170
171         if (has_any_audio) {
172                 LOG_DEBUG_AUDIO_ANALYSIS("Seeking to %1", to_string(_start));
173                 player->seek (_start, true);
174                 _done = 0;
175                 LOG_DEBUG_AUDIO_ANALYSIS("Starting loop for playlist of length %1", to_string(length));
176                 while (!player->pass ()) {}
177         }
178
179         LOG_DEBUG_AUDIO_ANALYSIS_NC("Loop complete");
180
181         vector<AudioAnalysis::PeakTime> sample_peak;
182         for (int i = 0; i < _film->audio_channels(); ++i) {
183                 sample_peak.push_back (
184                         AudioAnalysis::PeakTime (_sample_peak[i], DCPTime::from_frames (_sample_peak_frame[i], _film->audio_frame_rate ()))
185                         );
186         }
187         _analysis->set_sample_peak (sample_peak);
188
189 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
190         if (Config::instance()->analyse_ebur128 ()) {
191                 void* eb = _ebur128->get("Parsed_ebur128_0")->priv;
192                 vector<float> true_peak;
193                 for (int i = 0; i < _film->audio_channels(); ++i) {
194                         true_peak.push_back (av_ebur128_get_true_peaks(eb)[i]);
195                 }
196                 _analysis->set_true_peak (true_peak);
197                 _analysis->set_integrated_loudness (av_ebur128_get_integrated_loudness(eb));
198                 _analysis->set_loudness_range (av_ebur128_get_loudness_range(eb));
199         }
200 #endif
201
202         if (_playlist->content().size() == 1) {
203                 /* If there was only one piece of content in this analysis we may later need to know what its
204                    gain was when we analysed it.
205                 */
206                 shared_ptr<const AudioContent> ac = _playlist->content().front()->audio;
207                 if (ac) {
208                         _analysis->set_analysis_gain (ac->gain());
209                 }
210         }
211
212         _analysis->set_samples_per_point (_samples_per_point);
213         _analysis->set_sample_rate (_film->audio_frame_rate ());
214         _analysis->set_leqm (_leqm->leq_m());
215         _analysis->write (_path);
216
217         LOG_DEBUG_AUDIO_ANALYSIS_NC("Job finished");
218         set_progress (1);
219         set_state (FINISHED_OK);
220 }
221
222 void
223 AnalyseAudioJob::analyse (shared_ptr<const AudioBuffers> b, DCPTime time)
224 {
225         LOG_DEBUG_AUDIO_ANALYSIS("Received %1 frames at %2", b->frames(), to_string(time));
226         DCPOMATIC_ASSERT (time >= _start);
227
228 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
229         if (Config::instance()->analyse_ebur128 ()) {
230                 _ebur128->process (b);
231         }
232 #endif
233
234         int const frames = b->frames ();
235         int const channels = b->channels ();
236         vector<double> interleaved(frames * channels);
237
238         for (int j = 0; j < channels; ++j) {
239                 float* data = b->data(j);
240                 for (int i = 0; i < frames; ++i) {
241                         float s = data[i];
242
243                         interleaved[i * channels + j] = s;
244
245                         float as = fabsf (s);
246                         if (as < 10e-7) {
247                                 /* We may struggle to serialise and recover inf or -inf, so prevent such
248                                    values by replacing with this (140dB down) */
249                                 s = as = 10e-7;
250                         }
251                         _current[j][AudioPoint::RMS] += pow (s, 2);
252                         _current[j][AudioPoint::PEAK] = max (_current[j][AudioPoint::PEAK], as);
253
254                         if (as > _sample_peak[j]) {
255                                 _sample_peak[j] = as;
256                                 _sample_peak_frame[j] = _done + i;
257                         }
258
259                         if (((_done + i) % _samples_per_point) == 0) {
260                                 _current[j][AudioPoint::RMS] = sqrt (_current[j][AudioPoint::RMS] / _samples_per_point);
261                                 _analysis->add_point (j, _current[j]);
262                                 _current[j] = AudioPoint ();
263                         }
264                 }
265         }
266
267         _leqm->add(interleaved);
268
269         _done += frames;
270
271         DCPTime const length = _playlist->length (_film);
272         set_progress ((time.seconds() - _start.seconds()) / (length.seconds() - _start.seconds()));
273         LOG_DEBUG_AUDIO_ANALYSIS_NC("Frames processed");
274 }