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