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