9d0882b3ad22b3061f243d53ae78f91146042d3d
[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 "film.h"
27 #include "player.h"
28 #include "playlist.h"
29 #include "filter.h"
30 #include "audio_filter_graph.h"
31 #include "config.h"
32 extern "C" {
33 #include <libavutil/channel_layout.h>
34 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
35 #include <libavfilter/f_ebur128.h>
36 #endif
37 }
38 #include <boost/foreach.hpp>
39 #include <iostream>
40
41 #include "i18n.h"
42
43 using std::string;
44 using std::vector;
45 using std::max;
46 using std::min;
47 using std::cout;
48 using boost::shared_ptr;
49 using boost::dynamic_pointer_cast;
50 using namespace dcpomatic;
51
52 int const AnalyseAudioJob::_num_points = 1024;
53
54 /** @param from_zero true to analyse audio from time 0 in the playlist, otherwise begin at Playlist::start */
55 AnalyseAudioJob::AnalyseAudioJob (shared_ptr<const Film> film, shared_ptr<const Playlist> playlist, bool from_zero)
56         : Job (film)
57         , _playlist (playlist)
58         , _path (film->audio_analysis_path(playlist))
59         , _from_zero (from_zero)
60         , _done (0)
61         , _samples_per_point (1)
62         , _current (0)
63         , _sample_peak (new float[film->audio_channels()])
64         , _sample_peak_frame (new Frame[film->audio_channels()])
65 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
66         , _ebur128 (new AudioFilterGraph (film->audio_frame_rate(), film->audio_channels()))
67 #endif
68 {
69 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
70         _filters.push_back (new Filter ("ebur128", "ebur128", "audio", "ebur128=peak=true"));
71         _ebur128->setup (_filters);
72 #endif
73
74         for (int i = 0; i < film->audio_channels(); ++i) {
75                 _sample_peak[i] = 0;
76                 _sample_peak_frame[i] = 0;
77         }
78
79         if (!_from_zero) {
80                 _start = _playlist->start().get_value_or(DCPTime());
81         }
82 }
83
84 AnalyseAudioJob::~AnalyseAudioJob ()
85 {
86         BOOST_FOREACH (Filter const * i, _filters) {
87                 delete const_cast<Filter*> (i);
88         }
89         delete[] _current;
90         delete[] _sample_peak;
91         delete[] _sample_peak_frame;
92 }
93
94 string
95 AnalyseAudioJob::name () const
96 {
97         return _("Analysing audio");
98 }
99
100 string
101 AnalyseAudioJob::json_name () const
102 {
103         return N_("analyse_audio");
104 }
105
106 void
107 AnalyseAudioJob::run ()
108 {
109         shared_ptr<Player> player (new Player (_film, _playlist));
110         player->set_ignore_video ();
111         player->set_ignore_text ();
112         player->set_fast ();
113         player->set_play_referenced ();
114         player->Audio.connect (bind (&AnalyseAudioJob::analyse, this, _1, _2));
115
116         DCPTime const length = _playlist->length (_film);
117
118         Frame const len = DCPTime (length - _start).frames_round (_film->audio_frame_rate());
119         _samples_per_point = max (int64_t (1), len / _num_points);
120
121         delete[] _current;
122         _current = new AudioPoint[_film->audio_channels ()];
123         _analysis.reset (new AudioAnalysis (_film->audio_channels ()));
124
125         bool has_any_audio = false;
126         BOOST_FOREACH (shared_ptr<Content> c, _playlist->content ()) {
127                 if (c->audio) {
128                         has_any_audio = true;
129                 }
130         }
131
132         if (has_any_audio) {
133                 player->seek (_start, true);
134                 _done = 0;
135                 while (!player->pass ()) {}
136         }
137
138         vector<AudioAnalysis::PeakTime> sample_peak;
139         for (int i = 0; i < _film->audio_channels(); ++i) {
140                 sample_peak.push_back (
141                         AudioAnalysis::PeakTime (_sample_peak[i], DCPTime::from_frames (_sample_peak_frame[i], _film->audio_frame_rate ()))
142                         );
143         }
144         _analysis->set_sample_peak (sample_peak);
145
146 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
147         if (Config::instance()->analyse_ebur128 ()) {
148                 void* eb = _ebur128->get("Parsed_ebur128_0")->priv;
149                 vector<float> true_peak;
150                 for (int i = 0; i < _film->audio_channels(); ++i) {
151                         true_peak.push_back (av_ebur128_get_true_peaks(eb)[i]);
152                 }
153                 _analysis->set_true_peak (true_peak);
154                 _analysis->set_integrated_loudness (av_ebur128_get_integrated_loudness(eb));
155                 _analysis->set_loudness_range (av_ebur128_get_loudness_range(eb));
156         }
157 #endif
158
159         if (_playlist->content().size() == 1) {
160                 /* If there was only one piece of content in this analysis we may later need to know what its
161                    gain was when we analysed it.
162                 */
163                 shared_ptr<const AudioContent> ac = _playlist->content().front()->audio;
164                 if (ac) {
165                         _analysis->set_analysis_gain (ac->gain());
166                 }
167         }
168
169         _analysis->set_samples_per_point (_samples_per_point);
170         _analysis->set_sample_rate (_film->audio_frame_rate ());
171         _analysis->write (_path);
172
173         set_progress (1);
174         set_state (FINISHED_OK);
175 }
176
177 void
178 AnalyseAudioJob::analyse (shared_ptr<const AudioBuffers> b, DCPTime time)
179 {
180         DCPOMATIC_ASSERT (time >= _start);
181
182 #ifdef DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG
183         if (Config::instance()->analyse_ebur128 ()) {
184                 _ebur128->process (b);
185         }
186 #endif
187
188         int const frames = b->frames ();
189         int const channels = b->channels ();
190
191         for (int j = 0; j < channels; ++j) {
192                 float* data = b->data(j);
193                 for (int i = 0; i < frames; ++i) {
194                         float s = data[i];
195                         float as = fabsf (s);
196                         if (as < 10e-7) {
197                                 /* We may struggle to serialise and recover inf or -inf, so prevent such
198                                    values by replacing with this (140dB down) */
199                                 s = as = 10e-7;
200                         }
201                         _current[j][AudioPoint::RMS] += pow (s, 2);
202                         _current[j][AudioPoint::PEAK] = max (_current[j][AudioPoint::PEAK], as);
203
204                         if (as > _sample_peak[j]) {
205                                 _sample_peak[j] = as;
206                                 _sample_peak_frame[j] = _done + i;
207                         }
208
209                         if (((_done + i) % _samples_per_point) == 0) {
210                                 _current[j][AudioPoint::RMS] = sqrt (_current[j][AudioPoint::RMS] / _samples_per_point);
211                                 _analysis->add_point (j, _current[j]);
212                                 _current[j] = AudioPoint ();
213                         }
214                 }
215         }
216
217         _done += frames;
218
219         DCPTime const length = _playlist->length (_film);
220         set_progress ((time.seconds() - _start.seconds()) / (length.seconds() - _start.seconds()));
221 }