2 Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include "audio_analysis.h"
21 #include "analyse_audio_job.h"
22 #include "compose.hpp"
25 #include "decoder_factory.h"
26 #include "audio_decoder.h"
30 using boost::shared_ptr;
32 int const AnalyseAudioJob::_num_points = 1024;
34 AnalyseAudioJob::AnalyseAudioJob (shared_ptr<Film> f)
36 , _done_for_this_point (0)
38 , _samples_per_point (1)
44 AnalyseAudioJob::name () const
46 return String::compose ("Analyse audio of %1", _film->name());
50 AnalyseAudioJob::run ()
52 if (!_film->audio_stream () || !_film->length()) {
54 set_state (FINISHED_ERROR);
58 DecodeOptions options;
59 options.decode_video = false;
61 Decoders decoders = decoder_factory (_film, options);
62 assert (decoders.audio);
64 decoders.audio->set_audio_stream (_film->audio_stream ());
65 decoders.audio->Audio.connect (bind (&AnalyseAudioJob::audio, this, _1));
67 int64_t total_audio_frames = video_frames_to_audio_frames (_film->length().get(), _film->audio_stream()->sample_rate(), _film->frames_per_second());
68 _samples_per_point = total_audio_frames / _num_points;
70 _current.resize (_film->audio_stream()->channels ());
71 _analysis.reset (new AudioAnalysis (_film->audio_stream()->channels()));
73 while (!decoders.audio->pass()) {
74 set_progress (float (_done) / total_audio_frames);
77 _analysis->write (_film->audio_analysis_path ());
80 set_state (FINISHED_OK);
84 AnalyseAudioJob::audio (shared_ptr<AudioBuffers> b)
86 for (int i = 0; i < b->frames(); ++i) {
87 for (int j = 0; j < b->channels(); ++j) {
88 float s = b->data(j)[i];
89 if (fabsf (s) < 10e-7) {
90 /* stringstream can't serialise and recover inf or -inf, so prevent such
91 values by replacing with this (140dB down) */
94 _current[j][AudioPoint::RMS] += pow (s, 2);
95 _current[j][AudioPoint::PEAK] = max (_current[j][AudioPoint::PEAK], fabsf (s));
97 if (_done_for_this_point == _samples_per_point) {
98 _current[j][AudioPoint::RMS] = 20 * log10 (sqrt (_current[j][AudioPoint::RMS] / _samples_per_point));
99 _current[j][AudioPoint::PEAK] = 20 * log10 (_current[j][AudioPoint::PEAK]);
101 _analysis->add_point (j, _current[j]);
103 _done_for_this_point = 0;
104 _current[j] = AudioPoint ();
108 ++_done_for_this_point;
111 _done += b->frames ();