]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_silencedetect.c
8973049fe5e9413e86e49af4234fcb0f11c714b0
[ffmpeg] / libavfilter / af_silencedetect.c
1 /*
2  * Copyright (c) 2012 Clément Bœsch <u pkh me>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg 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 GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * Audio silence detector
24  */
25
26 #include <float.h> /* DBL_MAX */
27
28 #include "libavutil/opt.h"
29 #include "libavutil/timestamp.h"
30 #include "audio.h"
31 #include "formats.h"
32 #include "avfilter.h"
33 #include "internal.h"
34
35 typedef struct SilenceDetectContext {
36     const AVClass *class;
37     double noise;               ///< noise amplitude ratio
38     double duration;            ///< minimum duration of silence until notification
39     int mono;                   ///< mono mode : check each channel separately (default = check when ALL channels are silent)
40     int channels;               ///< number of channels
41     int independant_channels;   ///< number of entries in following arrays (always 1 in mono mode)
42     int64_t *nb_null_samples;   ///< (array) current number of continuous zero samples
43     int64_t *start;             ///< (array) if silence is detected, this value contains the time of the first zero sample (default/unset = INT64_MIN)
44     int last_sample_rate;       ///< last sample rate to check for sample rate changes
45
46     void (*silencedetect)(struct SilenceDetectContext *s, AVFrame *insamples,
47                           int nb_samples, int64_t nb_samples_notify,
48                           AVRational time_base);
49 } SilenceDetectContext;
50
51 #define OFFSET(x) offsetof(SilenceDetectContext, x)
52 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
53 static const AVOption silencedetect_options[] = {
54     { "n",         "set noise tolerance",              OFFSET(noise),     AV_OPT_TYPE_DOUBLE, {.dbl=0.001},          0, DBL_MAX,  FLAGS },
55     { "noise",     "set noise tolerance",              OFFSET(noise),     AV_OPT_TYPE_DOUBLE, {.dbl=0.001},          0, DBL_MAX,  FLAGS },
56     { "d",         "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_DOUBLE, {.dbl=2.},             0, 24*60*60, FLAGS },
57     { "duration",  "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_DOUBLE, {.dbl=2.},             0, 24*60*60, FLAGS },
58     { "mono",      "check each channel separately",    OFFSET(mono),      AV_OPT_TYPE_BOOL,   {.i64=0.},             0, 1, FLAGS },
59     { NULL }
60 };
61
62 AVFILTER_DEFINE_CLASS(silencedetect);
63
64 static void set_meta(AVFrame *insamples, int channel, const char *key, char *value)
65 {
66     char key2[128];
67
68     if (channel)
69         snprintf(key2, sizeof(key2), "lavfi.%s.%d", key, channel);
70     else
71         snprintf(key2, sizeof(key2), "lavfi.%s", key);
72     av_dict_set(&insamples->metadata, key2, value, 0);
73 }
74 static av_always_inline void update(SilenceDetectContext *s, AVFrame *insamples,
75                                     int is_silence, int current_sample, int64_t nb_samples_notify,
76                                     AVRational time_base)
77 {
78     int channel = current_sample % s->independant_channels;
79     if (is_silence) {
80         if (s->start[channel] == INT64_MIN) {
81             s->nb_null_samples[channel]++;
82             if (s->nb_null_samples[channel] >= nb_samples_notify) {
83                 s->start[channel] = insamples->pts + av_rescale_q(current_sample / s->channels + 1 - nb_samples_notify * s->independant_channels / s->channels,
84                         (AVRational){ 1, s->last_sample_rate }, time_base);
85                 set_meta(insamples, s->mono ? channel + 1 : 0, "silence_start",
86                         av_ts2timestr(s->start[channel], &time_base));
87                 if (s->mono)
88                     av_log(s, AV_LOG_INFO, "channel: %d | ", channel);
89                 av_log(s, AV_LOG_INFO, "silence_start: %s\n",
90                         av_ts2timestr(s->start[channel], &time_base));
91             }
92         }
93     } else {
94         if (s->start[channel] > INT64_MIN) {
95             int64_t end_pts = insamples->pts + av_rescale_q(current_sample / s->channels,
96                     (AVRational){ 1, s->last_sample_rate }, time_base);
97             int64_t duration_ts = end_pts - s->start[channel];
98             set_meta(insamples, s->mono ? channel + 1 : 0, "silence_end",
99                     av_ts2timestr(end_pts, &time_base));
100             set_meta(insamples, s->mono ? channel + 1 : 0, "silence_duration",
101                     av_ts2timestr(duration_ts, &time_base));
102             if (s->mono)
103                 av_log(s, AV_LOG_INFO, "channel: %d | ", channel);
104             av_log(s, AV_LOG_INFO, "silence_end: %s | silence_duration: %s\n",
105                     av_ts2timestr(end_pts, &time_base),
106                     av_ts2timestr(duration_ts, &time_base));
107         }
108         s->nb_null_samples[channel] = 0;
109         s->start[channel] = INT64_MIN;
110     }
111 }
112
113 #define SILENCE_DETECT(name, type)                                               \
114 static void silencedetect_##name(SilenceDetectContext *s, AVFrame *insamples,    \
115                                  int nb_samples, int64_t nb_samples_notify,      \
116                                  AVRational time_base)                           \
117 {                                                                                \
118     const type *p = (const type *)insamples->data[0];                            \
119     const type noise = s->noise;                                                 \
120     int i;                                                                       \
121                                                                                  \
122     for (i = 0; i < nb_samples; i++, p++)                                        \
123         update(s, insamples, *p < noise && *p > -noise, i,                       \
124                nb_samples_notify, time_base);                                    \
125 }
126
127 SILENCE_DETECT(dbl, double)
128 SILENCE_DETECT(flt, float)
129 SILENCE_DETECT(s32, int32_t)
130 SILENCE_DETECT(s16, int16_t)
131
132 static int config_input(AVFilterLink *inlink)
133 {
134     AVFilterContext *ctx = inlink->dst;
135     SilenceDetectContext *s = ctx->priv;
136     int c;
137
138     s->channels = inlink->channels;
139     s->independant_channels = s->mono ? s->channels : 1;
140     s->nb_null_samples = av_mallocz_array(sizeof(*s->nb_null_samples), s->independant_channels);
141     if (!s->nb_null_samples)
142         return AVERROR(ENOMEM);
143     s->start = av_malloc_array(sizeof(*s->start), s->independant_channels);
144     if (!s->start)
145         return AVERROR(ENOMEM);
146     for (c = 0; c < s->independant_channels; c++)
147         s->start[c] = INT64_MIN;
148
149     switch (inlink->format) {
150     case AV_SAMPLE_FMT_DBL: s->silencedetect = silencedetect_dbl; break;
151     case AV_SAMPLE_FMT_FLT: s->silencedetect = silencedetect_flt; break;
152     case AV_SAMPLE_FMT_S32:
153         s->noise *= INT32_MAX;
154         s->silencedetect = silencedetect_s32;
155         break;
156     case AV_SAMPLE_FMT_S16:
157         s->noise *= INT16_MAX;
158         s->silencedetect = silencedetect_s16;
159         break;
160     }
161
162     return 0;
163 }
164
165 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
166 {
167     SilenceDetectContext *s         = inlink->dst->priv;
168     const int nb_channels           = inlink->channels;
169     const int srate                 = inlink->sample_rate;
170     const int nb_samples            = insamples->nb_samples     * nb_channels;
171     const int64_t nb_samples_notify = srate * s->duration * (s->mono ? 1 : nb_channels);
172     int c;
173
174     // scale number of null samples to the new sample rate
175     if (s->last_sample_rate && s->last_sample_rate != srate)
176         for (c = 0; c < s->independant_channels; c++) {
177             s->nb_null_samples[c] = srate * s->nb_null_samples[c] / s->last_sample_rate;
178         }
179     s->last_sample_rate = srate;
180
181     // TODO: document metadata
182     s->silencedetect(s, insamples, nb_samples, nb_samples_notify,
183                      inlink->time_base);
184
185     return ff_filter_frame(inlink->dst->outputs[0], insamples);
186 }
187
188 static int query_formats(AVFilterContext *ctx)
189 {
190     AVFilterFormats *formats = NULL;
191     AVFilterChannelLayouts *layouts = NULL;
192     static const enum AVSampleFormat sample_fmts[] = {
193         AV_SAMPLE_FMT_DBL,
194         AV_SAMPLE_FMT_FLT,
195         AV_SAMPLE_FMT_S32,
196         AV_SAMPLE_FMT_S16,
197         AV_SAMPLE_FMT_NONE
198     };
199     int ret;
200
201     layouts = ff_all_channel_layouts();
202     if (!layouts)
203         return AVERROR(ENOMEM);
204     ret = ff_set_common_channel_layouts(ctx, layouts);
205     if (ret < 0)
206         return ret;
207
208     formats = ff_make_format_list(sample_fmts);
209     if (!formats)
210         return AVERROR(ENOMEM);
211     ret = ff_set_common_formats(ctx, formats);
212     if (ret < 0)
213         return ret;
214
215     formats = ff_all_samplerates();
216     if (!formats)
217         return AVERROR(ENOMEM);
218     return ff_set_common_samplerates(ctx, formats);
219 }
220
221 static const AVFilterPad silencedetect_inputs[] = {
222     {
223         .name         = "default",
224         .type         = AVMEDIA_TYPE_AUDIO,
225         .config_props = config_input,
226         .filter_frame = filter_frame,
227     },
228     { NULL }
229 };
230
231 static const AVFilterPad silencedetect_outputs[] = {
232     {
233         .name = "default",
234         .type = AVMEDIA_TYPE_AUDIO,
235     },
236     { NULL }
237 };
238
239 AVFilter ff_af_silencedetect = {
240     .name          = "silencedetect",
241     .description   = NULL_IF_CONFIG_SMALL("Detect silence."),
242     .priv_size     = sizeof(SilenceDetectContext),
243     .query_formats = query_formats,
244     .inputs        = silencedetect_inputs,
245     .outputs       = silencedetect_outputs,
246     .priv_class    = &silencedetect_class,
247 };