]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_silencedetect.c
lavu: introduce av_parse_ratio() and use it in ffmpeg and lavfi/aspect
[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 "avfilter.h"
28
29 typedef struct {
30     const AVClass *class;
31     char *noise_str;            ///< noise option string
32     double noise;               ///< noise amplitude ratio
33     int duration;               ///< minimum duration of silence until notification
34     int64_t nb_null_samples;    ///< current number of continuous zero samples
35     double start;               ///< if silence is detected, this value contains the time of the first zero sample
36     int last_sample_rate;       ///< last sample rate to check for sample rate changes
37 } SilenceDetectContext;
38
39 #define OFFSET(x) offsetof(SilenceDetectContext, x)
40 static const AVOption silencedetect_options[] = {
41     { "n",         "set noise tolerance",              OFFSET(noise_str), AV_OPT_TYPE_STRING, {.str="-60dB"}, CHAR_MIN, CHAR_MAX },
42     { "noise",     "set noise tolerance",              OFFSET(noise_str), AV_OPT_TYPE_STRING, {.str="-60dB"}, CHAR_MIN, CHAR_MAX },
43     { "d",         "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_INT,    {.dbl=2},    0, INT_MAX},
44     { "duration",  "set minimum duration in seconds",  OFFSET(duration),  AV_OPT_TYPE_INT,    {.dbl=2},    0, INT_MAX},
45     { NULL },
46 };
47
48 static const char *silencedetect_get_name(void *ctx)
49 {
50     return "silencedetect";
51 }
52
53 static const AVClass silencedetect_class = {
54     .class_name = "SilenceDetectContext",
55     .item_name  = silencedetect_get_name,
56     .option     = silencedetect_options,
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 * av_q2d(inlink->time_base) - silence->duration;
110                         av_log(silence, AV_LOG_INFO,
111                                "silence_start: %f\n", silence->start);
112                     }
113                 }
114             } else {
115                 if (silence->start) {
116                     double end = insamples->pts * av_q2d(inlink->time_base);
117                     av_log(silence, AV_LOG_INFO,
118                            "silence_end: %f | silence_duration: %f\n",
119                            end, end - silence->start);
120                 }
121                 silence->nb_null_samples = silence->start = 0;
122             }
123         }
124     }
125
126     avfilter_filter_samples(inlink->dst->outputs[0], insamples);
127 }
128
129 static int query_formats(AVFilterContext *ctx)
130 {
131     AVFilterFormats *formats = NULL;
132     enum AVSampleFormat sample_fmts[] = {
133         AV_SAMPLE_FMT_DBL,
134         AV_SAMPLE_FMT_NONE
135     };
136     int packing_fmts[] = { AVFILTER_PACKED, -1 };
137
138     formats = avfilter_make_all_channel_layouts();
139     if (!formats)
140         return AVERROR(ENOMEM);
141     avfilter_set_common_channel_layouts(ctx, formats);
142
143     formats = avfilter_make_format_list(sample_fmts);
144     if (!formats)
145         return AVERROR(ENOMEM);
146     avfilter_set_common_sample_formats(ctx, formats);
147
148     formats = avfilter_make_format_list(packing_fmts);
149     if (!formats)
150         return AVERROR(ENOMEM);
151     avfilter_set_common_packing_formats(ctx, formats);
152
153     return 0;
154 }
155
156 AVFilter avfilter_af_silencedetect = {
157     .name          = "silencedetect",
158     .description   = NULL_IF_CONFIG_SMALL("Detect silence."),
159     .priv_size     = sizeof(SilenceDetectContext),
160     .init          = init,
161     .query_formats = query_formats,
162
163     .inputs = (const AVFilterPad[]) {
164         { .name             = "default",
165           .type             = AVMEDIA_TYPE_AUDIO,
166           .get_audio_buffer = avfilter_null_get_audio_buffer,
167           .filter_samples   = filter_samples, },
168         { .name = NULL }
169     },
170     .outputs = (const AVFilterPad[]) {
171         { .name = "default",
172           .type = AVMEDIA_TYPE_AUDIO, },
173         { .name = NULL }
174     },
175 };