]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_silencedetect.c
lavfi/blackdetect: switch to new ff_filter_frame() API
[ffmpeg] / libavfilter / af_silencedetect.c
1 /*
2  * Copyright (c) 2012 Clément Bœsch <ubitux@gmail.com>
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 "libavutil/channel_layout.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/timestamp.h"
29 #include "audio.h"
30 #include "formats.h"
31 #include "avfilter.h"
32 #include "internal.h"
33
34 typedef struct {
35     const AVClass *class;
36     char *noise_str;            ///< noise option string
37     double noise;               ///< noise amplitude ratio
38     double duration;            ///< minimum duration of silence until notification
39     int64_t nb_null_samples;    ///< current number of continuous zero samples
40     int64_t start;              ///< if silence is detected, this value contains the time of the first zero sample
41     int last_sample_rate;       ///< last sample rate to check for sample rate changes
42 } SilenceDetectContext;
43
44 #define OFFSET(x) offsetof(SilenceDetectContext, x)
45 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
46 static const AVOption silencedetect_options[] = {
47     { "n",         "set noise tolerance",              OFFSET(noise_str), AV_OPT_TYPE_STRING, {.str="-60dB"}, CHAR_MIN, CHAR_MAX, FLAGS },
48     { "noise",     "set noise tolerance",              OFFSET(noise_str), AV_OPT_TYPE_STRING, {.str="-60dB"}, CHAR_MIN, CHAR_MAX, FLAGS },
49     { "d",         "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_DOUBLE, {.dbl=2.},             0, 24*60*60, FLAGS },
50     { "duration",  "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_DOUBLE, {.dbl=2.},             0, 24*60*60, FLAGS },
51     { NULL },
52 };
53
54 AVFILTER_DEFINE_CLASS(silencedetect);
55
56 static av_cold int init(AVFilterContext *ctx, const char *args)
57 {
58     int ret;
59     char *tail;
60     SilenceDetectContext *silence = ctx->priv;
61
62     silence->class = &silencedetect_class;
63     av_opt_set_defaults(silence);
64
65     if ((ret = av_set_options_string(silence, args, "=", ":")) < 0)
66         return ret;
67
68     silence->noise = strtod(silence->noise_str, &tail);
69     if (!strcmp(tail, "dB")) {
70         silence->noise = pow(10, silence->noise/20);
71     } else if (*tail) {
72         av_log(ctx, AV_LOG_ERROR, "Invalid value '%s' for noise parameter.\n",
73                silence->noise_str);
74         return AVERROR(EINVAL);
75     }
76     av_opt_free(silence);
77
78     return 0;
79 }
80
81 static char *get_metadata_val(AVFilterBufferRef *insamples, const char *key)
82 {
83     AVDictionaryEntry *e = av_dict_get(insamples->metadata, key, NULL, 0);
84     return e && e->value ? e->value : NULL;
85 }
86
87 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
88 {
89     int i;
90     SilenceDetectContext *silence = inlink->dst->priv;
91     const int nb_channels           = av_get_channel_layout_nb_channels(inlink->channel_layout);
92     const int srate                 = inlink->sample_rate;
93     const int nb_samples            = insamples->audio->nb_samples * nb_channels;
94     const int64_t nb_samples_notify = srate * silence->duration    * nb_channels;
95
96     // scale number of null samples to the new sample rate
97     if (silence->last_sample_rate && silence->last_sample_rate != srate)
98         silence->nb_null_samples =
99             srate * silence->nb_null_samples / silence->last_sample_rate;
100     silence->last_sample_rate = srate;
101
102     // TODO: support more sample formats
103     // TODO: document metadata
104     if (insamples->format == AV_SAMPLE_FMT_DBL) {
105         double *p = (double *)insamples->data[0];
106
107         for (i = 0; i < nb_samples; i++, p++) {
108             if (*p < silence->noise && *p > -silence->noise) {
109                 if (!silence->start) {
110                     silence->nb_null_samples++;
111                     if (silence->nb_null_samples >= nb_samples_notify) {
112                         silence->start = insamples->pts - (int64_t)(silence->duration / av_q2d(inlink->time_base) + .5);
113                         av_dict_set(&insamples->metadata, "lavfi.silence_start",
114                                     av_ts2timestr(silence->start, &inlink->time_base), 0);
115                         av_log(silence, AV_LOG_INFO, "silence_start: %s\n",
116                                get_metadata_val(insamples, "lavfi.silence_start"));
117                     }
118                 }
119             } else {
120                 if (silence->start) {
121                     av_dict_set(&insamples->metadata, "lavfi.silence_end",
122                                 av_ts2timestr(insamples->pts, &inlink->time_base), 0);
123                     av_dict_set(&insamples->metadata, "lavfi.silence_duration",
124                                 av_ts2timestr(insamples->pts - silence->start, &inlink->time_base), 0);
125                     av_log(silence, AV_LOG_INFO,
126                            "silence_end: %s | silence_duration: %s\n",
127                            get_metadata_val(insamples, "lavfi.silence_end"),
128                            get_metadata_val(insamples, "lavfi.silence_duration"));
129                 }
130                 silence->nb_null_samples = silence->start = 0;
131             }
132         }
133     }
134
135     return ff_filter_frame(inlink->dst->outputs[0], insamples);
136 }
137
138 static int query_formats(AVFilterContext *ctx)
139 {
140     AVFilterFormats *formats = NULL;
141     AVFilterChannelLayouts *layouts = NULL;
142     enum AVSampleFormat sample_fmts[] = {
143         AV_SAMPLE_FMT_DBL,
144         AV_SAMPLE_FMT_NONE
145     };
146
147     layouts = ff_all_channel_layouts();
148     if (!layouts)
149         return AVERROR(ENOMEM);
150     ff_set_common_channel_layouts(ctx, layouts);
151
152     formats = ff_make_format_list(sample_fmts);
153     if (!formats)
154         return AVERROR(ENOMEM);
155     ff_set_common_formats(ctx, formats);
156
157     formats = ff_all_samplerates();
158     if (!formats)
159         return AVERROR(ENOMEM);
160     ff_set_common_samplerates(ctx, formats);
161
162     return 0;
163 }
164
165 static const AVFilterPad silencedetect_inputs[] = {
166     {
167         .name             = "default",
168         .type             = AVMEDIA_TYPE_AUDIO,
169         .get_audio_buffer = ff_null_get_audio_buffer,
170         .filter_frame     = filter_frame,
171     },
172     { NULL }
173 };
174
175 static const AVFilterPad silencedetect_outputs[] = {
176     {
177         .name = "default",
178         .type = AVMEDIA_TYPE_AUDIO,
179     },
180     { NULL }
181 };
182
183 AVFilter avfilter_af_silencedetect = {
184     .name          = "silencedetect",
185     .description   = NULL_IF_CONFIG_SMALL("Detect silence."),
186     .priv_size     = sizeof(SilenceDetectContext),
187     .init          = init,
188     .query_formats = query_formats,
189     .inputs        = silencedetect_inputs,
190     .outputs       = silencedetect_outputs,
191     .priv_class    = &silencedetect_class,
192 };