FFmpeg
af_silencedetect.c
Go to the documentation of this file.
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 independent_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  int64_t frame_end; ///< pts of the end of the current frame (used to compute duration of silence at EOS)
45  int last_sample_rate; ///< last sample rate to check for sample rate changes
46  AVRational time_base; ///< time_base
47 
49  int nb_samples, int64_t nb_samples_notify,
52 
53 #define OFFSET(x) offsetof(SilenceDetectContext, x)
54 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
55 static const AVOption silencedetect_options[] = {
56  { "n", "set noise tolerance", OFFSET(noise), AV_OPT_TYPE_DOUBLE, {.dbl=0.001}, 0, DBL_MAX, FLAGS },
57  { "noise", "set noise tolerance", OFFSET(noise), AV_OPT_TYPE_DOUBLE, {.dbl=0.001}, 0, DBL_MAX, FLAGS },
58  { "d", "set minimum duration in seconds", OFFSET(duration), AV_OPT_TYPE_DOUBLE, {.dbl=2.}, 0, 24*60*60, FLAGS },
59  { "duration", "set minimum duration in seconds", OFFSET(duration), AV_OPT_TYPE_DOUBLE, {.dbl=2.}, 0, 24*60*60, FLAGS },
60  { "mono", "check each channel separately", OFFSET(mono), AV_OPT_TYPE_BOOL, {.i64=0.}, 0, 1, FLAGS },
61  { "m", "check each channel separately", OFFSET(mono), AV_OPT_TYPE_BOOL, {.i64=0.}, 0, 1, FLAGS },
62  { NULL }
63 };
64 
66 
67 static void set_meta(AVFrame *insamples, int channel, const char *key, char *value)
68 {
69  char key2[128];
70 
71  if (channel)
72  snprintf(key2, sizeof(key2), "lavfi.%s.%d", key, channel);
73  else
74  snprintf(key2, sizeof(key2), "lavfi.%s", key);
75  av_dict_set(&insamples->metadata, key2, value, 0);
76 }
78  int is_silence, int current_sample, int64_t nb_samples_notify,
80 {
81  int channel = current_sample % s->independent_channels;
82  if (is_silence) {
83  if (s->start[channel] == INT64_MIN) {
85  if (s->nb_null_samples[channel] >= nb_samples_notify) {
86  s->start[channel] = insamples->pts + av_rescale_q(current_sample / s->channels + 1 - nb_samples_notify * s->independent_channels / s->channels,
87  (AVRational){ 1, s->last_sample_rate }, time_base);
88  set_meta(insamples, s->mono ? channel + 1 : 0, "silence_start",
89  av_ts2timestr(s->start[channel], &time_base));
90  if (s->mono)
91  av_log(s, AV_LOG_INFO, "channel: %d | ", channel);
92  av_log(s, AV_LOG_INFO, "silence_start: %s\n",
93  av_ts2timestr(s->start[channel], &time_base));
94  }
95  }
96  } else {
97  if (s->start[channel] > INT64_MIN) {
98  int64_t end_pts = insamples ? insamples->pts + av_rescale_q(current_sample / s->channels,
99  (AVRational){ 1, s->last_sample_rate }, time_base)
100  : s->frame_end;
101  int64_t duration_ts = end_pts - s->start[channel];
102  if (insamples) {
103  set_meta(insamples, s->mono ? channel + 1 : 0, "silence_end",
104  av_ts2timestr(end_pts, &time_base));
105  set_meta(insamples, s->mono ? channel + 1 : 0, "silence_duration",
106  av_ts2timestr(duration_ts, &time_base));
107  }
108  if (s->mono)
109  av_log(s, AV_LOG_INFO, "channel: %d | ", channel);
110  av_log(s, AV_LOG_INFO, "silence_end: %s | silence_duration: %s\n",
111  av_ts2timestr(end_pts, &time_base),
112  av_ts2timestr(duration_ts, &time_base));
113  }
114  s->nb_null_samples[channel] = 0;
115  s->start[channel] = INT64_MIN;
116  }
117 }
118 
119 #define SILENCE_DETECT(name, type) \
120 static void silencedetect_##name(SilenceDetectContext *s, AVFrame *insamples, \
121  int nb_samples, int64_t nb_samples_notify, \
122  AVRational time_base) \
123 { \
124  const type *p = (const type *)insamples->data[0]; \
125  const type noise = s->noise; \
126  int i; \
127  \
128  for (i = 0; i < nb_samples; i++, p++) \
129  update(s, insamples, *p < noise && *p > -noise, i, \
130  nb_samples_notify, time_base); \
131 }
132 
133 SILENCE_DETECT(dbl, double)
134 SILENCE_DETECT(flt, float)
136 SILENCE_DETECT(s16, int16_t)
137 
139 {
140  AVFilterContext *ctx = inlink->dst;
141  SilenceDetectContext *s = ctx->priv;
142  int c;
143 
144  s->channels = inlink->channels;
145  s->independent_channels = s->mono ? s->channels : 1;
147  if (!s->nb_null_samples)
148  return AVERROR(ENOMEM);
149  s->start = av_malloc_array(sizeof(*s->start), s->independent_channels);
150  if (!s->start)
151  return AVERROR(ENOMEM);
152  for (c = 0; c < s->independent_channels; c++)
153  s->start[c] = INT64_MIN;
154 
155  switch (inlink->format) {
156  case AV_SAMPLE_FMT_DBL: s->silencedetect = silencedetect_dbl; break;
157  case AV_SAMPLE_FMT_FLT: s->silencedetect = silencedetect_flt; break;
158  case AV_SAMPLE_FMT_S32:
159  s->noise *= INT32_MAX;
160  s->silencedetect = silencedetect_s32;
161  break;
162  case AV_SAMPLE_FMT_S16:
163  s->noise *= INT16_MAX;
164  s->silencedetect = silencedetect_s16;
165  break;
166  }
167 
168  return 0;
169 }
170 
171 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
172 {
173  SilenceDetectContext *s = inlink->dst->priv;
174  const int nb_channels = inlink->channels;
175  const int srate = inlink->sample_rate;
176  const int nb_samples = insamples->nb_samples * nb_channels;
177  const int64_t nb_samples_notify = srate * s->duration * (s->mono ? 1 : nb_channels);
178  int c;
179 
180  // scale number of null samples to the new sample rate
181  if (s->last_sample_rate && s->last_sample_rate != srate)
182  for (c = 0; c < s->independent_channels; c++) {
183  s->nb_null_samples[c] = srate * s->nb_null_samples[c] / s->last_sample_rate;
184  }
185  s->last_sample_rate = srate;
186  s->time_base = inlink->time_base;
187  s->frame_end = insamples->pts + av_rescale_q(insamples->nb_samples,
188  (AVRational){ 1, s->last_sample_rate }, inlink->time_base);
189 
190  // TODO: document metadata
191  s->silencedetect(s, insamples, nb_samples, nb_samples_notify,
192  inlink->time_base);
193 
194  return ff_filter_frame(inlink->dst->outputs[0], insamples);
195 }
196 
198 {
201  static const enum AVSampleFormat sample_fmts[] = {
207  };
208  int ret;
209 
210  layouts = ff_all_channel_layouts();
211  if (!layouts)
212  return AVERROR(ENOMEM);
213  ret = ff_set_common_channel_layouts(ctx, layouts);
214  if (ret < 0)
215  return ret;
216 
217  formats = ff_make_format_list(sample_fmts);
218  if (!formats)
219  return AVERROR(ENOMEM);
220  ret = ff_set_common_formats(ctx, formats);
221  if (ret < 0)
222  return ret;
223 
224  formats = ff_all_samplerates();
225  if (!formats)
226  return AVERROR(ENOMEM);
227  return ff_set_common_samplerates(ctx, formats);
228 }
229 
231 {
232  SilenceDetectContext *s = ctx->priv;
233  int c;
234 
235  for (c = 0; c < s->independent_channels; c++)
236  if (s->start[c] > INT64_MIN)
237  update(s, NULL, 0, c, 0, s->time_base);
239  av_freep(&s->start);
240 }
241 
243  {
244  .name = "default",
245  .type = AVMEDIA_TYPE_AUDIO,
246  .config_props = config_input,
247  .filter_frame = filter_frame,
248  },
249  { NULL }
250 };
251 
253  {
254  .name = "default",
255  .type = AVMEDIA_TYPE_AUDIO,
256  },
257  { NULL }
258 };
259 
261  .name = "silencedetect",
262  .description = NULL_IF_CONFIG_SMALL("Detect silence."),
263  .priv_size = sizeof(SilenceDetectContext),
265  .uninit = uninit,
266  .inputs = silencedetect_inputs,
267  .outputs = silencedetect_outputs,
268  .priv_class = &silencedetect_class,
269 };
#define NULL
Definition: coverity.c:32
int ff_set_common_channel_layouts(AVFilterContext *ctx, AVFilterChannelLayouts *layouts)
A helper for query_formats() which sets all links to the same list of channel layouts/sample rates...
Definition: formats.c:549
This structure describes decoded (raw) audio or video data.
Definition: frame.h:295
AVOption.
Definition: opt.h:246
Main libavfilter public API header.
int64_t frame_end
pts of the end of the current frame (used to compute duration of silence at EOS)
const char * key
#define SILENCE_DETECT(name, type)
AVFilter ff_af_silencedetect
AVFilterFormats * ff_make_format_list(const int *fmts)
Create a list of supported formats.
Definition: formats.c:283
const char * name
Pad name.
Definition: internal.h:60
static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1080
#define av_cold
Definition: attributes.h:82
AVOptions.
timestamp utils, mostly useful for debugging/logging purposes
static const AVFilterPad silencedetect_inputs[]
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
double duration
minimum duration of silence until notification
GLsizei GLboolean const GLfloat * value
Definition: opengl_enc.c:108
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:388
#define OFFSET(x)
AVDictionary * metadata
metadata.
Definition: frame.h:581
signed 32 bits
Definition: samplefmt.h:62
#define av_log(a,...)
A filter pad used for either input or output.
Definition: internal.h:54
AVRational time_base
time_base
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
int ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
A helper for query_formats() which sets all links to the same list of formats.
Definition: formats.c:568
static const AVFilterPad silencedetect_outputs[]
static av_always_inline void update(SilenceDetectContext *s, AVFrame *insamples, int is_silence, int current_sample, int64_t nb_samples_notify, AVRational time_base)
#define FLAGS
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:76
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:186
void * priv
private data for use by the filter
Definition: avfilter.h:353
double noise
noise amplitude ratio
typedef void(APIENTRY *FF_PFNGLACTIVETEXTUREPROC)(GLenum texture)
static int config_input(AVFilterLink *inlink)
int32_t
AVFormatContext * ctx
Definition: movenc.c:48
#define s(width, name)
Definition: cbs_vp9.c:257
AVFilterChannelLayouts * ff_all_channel_layouts(void)
Construct an empty AVFilterChannelLayouts/AVFilterFormats struct – representing any channel layout (...
Definition: formats.c:401
static const AVFilterPad outputs[]
Definition: af_acontrast.c:203
A list of supported channel layouts.
Definition: formats.h:85
int channels
number of channels
void(* silencedetect)(struct SilenceDetectContext *s, AVFrame *insamples, int nb_samples, int64_t nb_samples_notify, AVRational time_base)
int independent_channels
number of entries in following arrays (always 1 in mono mode)
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
int64_t * nb_null_samples
(array) current number of continuous zero samples
AVSampleFormat
Audio sample formats.
Definition: samplefmt.h:58
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several inputs
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
AVFILTER_DEFINE_CLASS(silencedetect)
int mono
mono mode : check each channel separately (default = check when ALL channels are silent) ...
Describe the class of an AVClass context structure.
Definition: log.h:67
Filter definition.
Definition: avfilter.h:144
Rational number (pair of numerator and denominator).
Definition: rational.h:58
static int query_formats(AVFilterContext *ctx)
const char * name
Filter name.
Definition: avfilter.h:148
#define snprintf
Definition: snprintf.h:34
AVFilterLink ** outputs
array of pointers to output links
Definition: avfilter.h:350
enum MovChannelLayoutTag * layouts
Definition: mov_chan.c:434
AVFilterFormats * ff_all_samplerates(void)
Definition: formats.c:395
The exact code depends on how similar the blocks are and how related they are to the and needs to apply these operations to the correct inlink or outlink if there are several Macros are available to factor that when no extra processing is inlink
signed 16 bits
Definition: samplefmt.h:61
channel
Use these values when setting the channel map with ebur128_set_channel().
Definition: ebur128.h:39
static const AVOption silencedetect_options[]
static av_cold void uninit(AVFilterContext *ctx)
A list of supported formats for one end of a filter link.
Definition: formats.h:64
An instance of a filter.
Definition: avfilter.h:338
static enum AVSampleFormat sample_fmts[]
Definition: adpcmenc.c:701
#define av_freep(p)
#define av_always_inline
Definition: attributes.h:39
static void set_meta(AVFrame *insamples, int channel, const char *key, char *value)
#define av_malloc_array(a, b)
formats
Definition: signature.h:48
int nb_channels
int last_sample_rate
last sample rate to check for sample rate changes
internal API functions
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later.That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another.Frame references ownership and permissions
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:361
int64_t * start
(array) if silence is detected, this value contains the time of the first zero sample (default/unset ...
int ff_set_common_samplerates(AVFilterContext *ctx, AVFilterFormats *samplerates)
Definition: formats.c:556
void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.c:191