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