]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_silenceremove.c
avfilter/vf_zscale: fix typo
[ffmpeg] / libavfilter / af_silenceremove.c
1 /*
2  * Copyright (c) 2001 Heikki Leinonen
3  * Copyright (c) 2001 Chris Bagwell
4  * Copyright (c) 2003 Donnie Smith
5  * Copyright (c) 2014 Paul B Mahol
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include <float.h> /* DBL_MAX */
25
26 #include "libavutil/opt.h"
27 #include "libavutil/timestamp.h"
28 #include "audio.h"
29 #include "formats.h"
30 #include "avfilter.h"
31 #include "internal.h"
32
33 enum SilenceMode {
34     SILENCE_TRIM,
35     SILENCE_TRIM_FLUSH,
36     SILENCE_COPY,
37     SILENCE_COPY_FLUSH,
38     SILENCE_STOP
39 };
40
41 typedef struct SilenceRemoveContext {
42     const AVClass *class;
43
44     enum SilenceMode mode;
45
46     int start_periods;
47     int64_t start_duration;
48     double start_threshold;
49
50     int stop_periods;
51     int64_t stop_duration;
52     double stop_threshold;
53
54     double *start_holdoff;
55     size_t start_holdoff_offset;
56     size_t start_holdoff_end;
57     int    start_found_periods;
58
59     double *stop_holdoff;
60     size_t stop_holdoff_offset;
61     size_t stop_holdoff_end;
62     int    stop_found_periods;
63
64     double *window;
65     double *window_current;
66     double *window_end;
67     int window_size;
68     double rms_sum;
69
70     int leave_silence;
71     int restart;
72     int64_t next_pts;
73 } SilenceRemoveContext;
74
75 #define OFFSET(x) offsetof(SilenceRemoveContext, x)
76 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
77 static const AVOption silenceremove_options[] = {
78     { "start_periods",   NULL, OFFSET(start_periods),   AV_OPT_TYPE_INT,      {.i64=0},     0,    9000, FLAGS },
79     { "start_duration",  NULL, OFFSET(start_duration),  AV_OPT_TYPE_DURATION, {.i64=0},     0,    9000, FLAGS },
80     { "start_threshold", NULL, OFFSET(start_threshold), AV_OPT_TYPE_DOUBLE,   {.dbl=0},     0, DBL_MAX, FLAGS },
81     { "stop_periods",    NULL, OFFSET(stop_periods),    AV_OPT_TYPE_INT,      {.i64=0}, -9000,    9000, FLAGS },
82     { "stop_duration",   NULL, OFFSET(stop_duration),   AV_OPT_TYPE_DURATION, {.i64=0},     0,    9000, FLAGS },
83     { "stop_threshold",  NULL, OFFSET(stop_threshold),  AV_OPT_TYPE_DOUBLE,   {.dbl=0},     0, DBL_MAX, FLAGS },
84     { "leave_silence",   NULL, OFFSET(leave_silence),   AV_OPT_TYPE_BOOL,     {.i64=0},     0,       1, FLAGS },
85     { NULL }
86 };
87
88 AVFILTER_DEFINE_CLASS(silenceremove);
89
90 static av_cold int init(AVFilterContext *ctx)
91 {
92     SilenceRemoveContext *s = ctx->priv;
93
94     if (s->stop_periods < 0) {
95         s->stop_periods = -s->stop_periods;
96         s->restart = 1;
97     }
98
99     return 0;
100 }
101
102 static void clear_rms(SilenceRemoveContext *s)
103 {
104     memset(s->window, 0, s->window_size * sizeof(*s->window));
105
106     s->window_current = s->window;
107     s->window_end = s->window + s->window_size;
108     s->rms_sum = 0;
109 }
110
111 static int config_input(AVFilterLink *inlink)
112 {
113     AVFilterContext *ctx = inlink->dst;
114     SilenceRemoveContext *s = ctx->priv;
115
116     s->window_size = (inlink->sample_rate / 50) * inlink->channels;
117     s->window = av_malloc_array(s->window_size, sizeof(*s->window));
118     if (!s->window)
119         return AVERROR(ENOMEM);
120
121     clear_rms(s);
122
123     s->start_duration = av_rescale(s->start_duration, inlink->sample_rate,
124                                    AV_TIME_BASE);
125     s->stop_duration  = av_rescale(s->stop_duration, inlink->sample_rate,
126                                    AV_TIME_BASE);
127
128     s->start_holdoff = av_malloc_array(FFMAX(s->start_duration, 1),
129                                        sizeof(*s->start_holdoff) *
130                                        inlink->channels);
131     if (!s->start_holdoff)
132         return AVERROR(ENOMEM);
133
134     s->start_holdoff_offset = 0;
135     s->start_holdoff_end    = 0;
136     s->start_found_periods  = 0;
137
138     s->stop_holdoff = av_malloc_array(FFMAX(s->stop_duration, 1),
139                                       sizeof(*s->stop_holdoff) *
140                                       inlink->channels);
141     if (!s->stop_holdoff)
142         return AVERROR(ENOMEM);
143
144     s->stop_holdoff_offset = 0;
145     s->stop_holdoff_end    = 0;
146     s->stop_found_periods  = 0;
147
148     if (s->start_periods)
149         s->mode = SILENCE_TRIM;
150     else
151         s->mode = SILENCE_COPY;
152
153     return 0;
154 }
155
156 static double compute_rms(SilenceRemoveContext *s, double sample)
157 {
158     double new_sum;
159
160     new_sum  = s->rms_sum;
161     new_sum -= *s->window_current;
162     new_sum += sample * sample;
163
164     return sqrt(new_sum / s->window_size);
165 }
166
167 static void update_rms(SilenceRemoveContext *s, double sample)
168 {
169     s->rms_sum -= *s->window_current;
170     *s->window_current = sample * sample;
171     s->rms_sum += *s->window_current;
172
173     s->window_current++;
174     if (s->window_current >= s->window_end)
175         s->window_current = s->window;
176 }
177
178 static void flush(AVFrame *out, AVFilterLink *outlink,
179                   int *nb_samples_written, int *ret)
180 {
181     if (*nb_samples_written) {
182         out->nb_samples = *nb_samples_written / outlink->channels;
183         *ret = ff_filter_frame(outlink, out);
184         *nb_samples_written = 0;
185     } else {
186         av_frame_free(&out);
187     }
188 }
189
190 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
191 {
192     AVFilterContext *ctx = inlink->dst;
193     AVFilterLink *outlink = ctx->outputs[0];
194     SilenceRemoveContext *s = ctx->priv;
195     int i, j, threshold, ret = 0;
196     int nbs, nb_samples_read, nb_samples_written;
197     double *obuf, *ibuf = (double *)in->data[0];
198     AVFrame *out;
199
200     nb_samples_read = nb_samples_written = 0;
201
202     switch (s->mode) {
203     case SILENCE_TRIM:
204 silence_trim:
205         nbs = in->nb_samples - nb_samples_read / inlink->channels;
206         if (!nbs)
207             break;
208
209         for (i = 0; i < nbs; i++) {
210             threshold = 0;
211             for (j = 0; j < inlink->channels; j++) {
212                 threshold |= compute_rms(s, ibuf[j]) > s->start_threshold;
213             }
214
215             if (threshold) {
216                 for (j = 0; j < inlink->channels; j++) {
217                     update_rms(s, *ibuf);
218                     s->start_holdoff[s->start_holdoff_end++] = *ibuf++;
219                     nb_samples_read++;
220                 }
221
222                 if (s->start_holdoff_end >= s->start_duration * inlink->channels) {
223                     if (++s->start_found_periods >= s->start_periods) {
224                         s->mode = SILENCE_TRIM_FLUSH;
225                         goto silence_trim_flush;
226                     }
227
228                     s->start_holdoff_offset = 0;
229                     s->start_holdoff_end = 0;
230                 }
231             } else {
232                 s->start_holdoff_end = 0;
233
234                 for (j = 0; j < inlink->channels; j++)
235                     update_rms(s, ibuf[j]);
236
237                 ibuf += inlink->channels;
238                 nb_samples_read += inlink->channels;
239             }
240         }
241         break;
242
243     case SILENCE_TRIM_FLUSH:
244 silence_trim_flush:
245         nbs  = s->start_holdoff_end - s->start_holdoff_offset;
246         nbs -= nbs % inlink->channels;
247         if (!nbs)
248             break;
249
250         out = ff_get_audio_buffer(inlink, nbs / inlink->channels);
251         if (!out) {
252             av_frame_free(&in);
253             return AVERROR(ENOMEM);
254         }
255
256         memcpy(out->data[0], &s->start_holdoff[s->start_holdoff_offset],
257                nbs * sizeof(double));
258         s->start_holdoff_offset += nbs;
259
260         ret = ff_filter_frame(outlink, out);
261
262         if (s->start_holdoff_offset == s->start_holdoff_end) {
263             s->start_holdoff_offset = 0;
264             s->start_holdoff_end = 0;
265             s->mode = SILENCE_COPY;
266             goto silence_copy;
267         }
268         break;
269
270     case SILENCE_COPY:
271 silence_copy:
272         nbs = in->nb_samples - nb_samples_read / inlink->channels;
273         if (!nbs)
274             break;
275
276         out = ff_get_audio_buffer(inlink, nbs);
277         if (!out) {
278             av_frame_free(&in);
279             return AVERROR(ENOMEM);
280         }
281         obuf = (double *)out->data[0];
282
283         if (s->stop_periods) {
284             for (i = 0; i < nbs; i++) {
285                 threshold = 1;
286                 for (j = 0; j < inlink->channels; j++)
287                     threshold &= compute_rms(s, ibuf[j]) > s->stop_threshold;
288
289                 if (threshold && s->stop_holdoff_end && !s->leave_silence) {
290                     s->mode = SILENCE_COPY_FLUSH;
291                     flush(out, outlink, &nb_samples_written, &ret);
292                     goto silence_copy_flush;
293                 } else if (threshold) {
294                     for (j = 0; j < inlink->channels; j++) {
295                         update_rms(s, *ibuf);
296                         *obuf++ = *ibuf++;
297                         nb_samples_read++;
298                         nb_samples_written++;
299                     }
300                 } else if (!threshold) {
301                     for (j = 0; j < inlink->channels; j++) {
302                         update_rms(s, *ibuf);
303                         if (s->leave_silence) {
304                             *obuf++ = *ibuf;
305                             nb_samples_written++;
306                         }
307
308                         s->stop_holdoff[s->stop_holdoff_end++] = *ibuf++;
309                         nb_samples_read++;
310                     }
311
312                     if (s->stop_holdoff_end >= s->stop_duration * inlink->channels) {
313                         if (++s->stop_found_periods >= s->stop_periods) {
314                             s->stop_holdoff_offset = 0;
315                             s->stop_holdoff_end = 0;
316
317                             if (!s->restart) {
318                                 s->mode = SILENCE_STOP;
319                                 flush(out, outlink, &nb_samples_written, &ret);
320                                 goto silence_stop;
321                             } else {
322                                 s->stop_found_periods = 0;
323                                 s->start_found_periods = 0;
324                                 s->start_holdoff_offset = 0;
325                                 s->start_holdoff_end = 0;
326                                 clear_rms(s);
327                                 s->mode = SILENCE_TRIM;
328                                 flush(out, outlink, &nb_samples_written, &ret);
329                                 goto silence_trim;
330                             }
331                         }
332                         s->mode = SILENCE_COPY_FLUSH;
333                         flush(out, outlink, &nb_samples_written, &ret);
334                         goto silence_copy_flush;
335                     }
336                 }
337             }
338             flush(out, outlink, &nb_samples_written, &ret);
339         } else {
340             memcpy(obuf, ibuf, sizeof(double) * nbs * inlink->channels);
341             ret = ff_filter_frame(outlink, out);
342         }
343         break;
344
345     case SILENCE_COPY_FLUSH:
346 silence_copy_flush:
347         nbs  = s->stop_holdoff_end - s->stop_holdoff_offset;
348         nbs -= nbs % inlink->channels;
349         if (!nbs)
350             break;
351
352         out = ff_get_audio_buffer(inlink, nbs / inlink->channels);
353         if (!out) {
354             av_frame_free(&in);
355             return AVERROR(ENOMEM);
356         }
357
358         memcpy(out->data[0], &s->stop_holdoff[s->stop_holdoff_offset],
359                nbs * sizeof(double));
360         s->stop_holdoff_offset += nbs;
361
362         ret = ff_filter_frame(outlink, out);
363
364         if (s->stop_holdoff_offset == s->stop_holdoff_end) {
365             s->stop_holdoff_offset = 0;
366             s->stop_holdoff_end = 0;
367             s->mode = SILENCE_COPY;
368             goto silence_copy;
369         }
370         break;
371     case SILENCE_STOP:
372 silence_stop:
373         break;
374     }
375
376     av_frame_free(&in);
377
378     return ret;
379 }
380
381 static int request_frame(AVFilterLink *outlink)
382 {
383     AVFilterContext *ctx = outlink->src;
384     SilenceRemoveContext *s = ctx->priv;
385     int ret;
386
387     ret = ff_request_frame(ctx->inputs[0]);
388     if (ret == AVERROR_EOF && (s->mode == SILENCE_COPY_FLUSH ||
389                                s->mode == SILENCE_COPY)) {
390         int nbs = s->stop_holdoff_end - s->stop_holdoff_offset;
391         if (nbs) {
392             AVFrame *frame;
393
394             frame = ff_get_audio_buffer(outlink, nbs / outlink->channels);
395             if (!frame)
396                 return AVERROR(ENOMEM);
397
398             memcpy(frame->data[0], &s->stop_holdoff[s->stop_holdoff_offset],
399                    nbs * sizeof(double));
400             ret = ff_filter_frame(ctx->inputs[0], frame);
401         }
402         s->mode = SILENCE_STOP;
403     }
404     return ret;
405 }
406
407 static int query_formats(AVFilterContext *ctx)
408 {
409     AVFilterFormats *formats = NULL;
410     AVFilterChannelLayouts *layouts = NULL;
411     static const enum AVSampleFormat sample_fmts[] = {
412         AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_NONE
413     };
414     int ret;
415
416     layouts = ff_all_channel_counts();
417     if (!layouts)
418         return AVERROR(ENOMEM);
419     ret = ff_set_common_channel_layouts(ctx, layouts);
420     if (ret < 0)
421         return ret;
422
423     formats = ff_make_format_list(sample_fmts);
424     if (!formats)
425         return AVERROR(ENOMEM);
426     ret = ff_set_common_formats(ctx, formats);
427     if (ret < 0)
428         return ret;
429
430     formats = ff_all_samplerates();
431     if (!formats)
432         return AVERROR(ENOMEM);
433     return ff_set_common_samplerates(ctx, formats);
434 }
435
436 static av_cold void uninit(AVFilterContext *ctx)
437 {
438     SilenceRemoveContext *s = ctx->priv;
439
440     av_freep(&s->start_holdoff);
441     av_freep(&s->stop_holdoff);
442     av_freep(&s->window);
443 }
444
445 static const AVFilterPad silenceremove_inputs[] = {
446     {
447         .name         = "default",
448         .type         = AVMEDIA_TYPE_AUDIO,
449         .config_props = config_input,
450         .filter_frame = filter_frame,
451     },
452     { NULL }
453 };
454
455 static const AVFilterPad silenceremove_outputs[] = {
456     {
457         .name          = "default",
458         .type          = AVMEDIA_TYPE_AUDIO,
459         .request_frame = request_frame,
460     },
461     { NULL }
462 };
463
464 AVFilter ff_af_silenceremove = {
465     .name          = "silenceremove",
466     .description   = NULL_IF_CONFIG_SMALL("Remove silence."),
467     .priv_size     = sizeof(SilenceRemoveContext),
468     .priv_class    = &silenceremove_class,
469     .init          = init,
470     .uninit        = uninit,
471     .query_formats = query_formats,
472     .inputs        = silenceremove_inputs,
473     .outputs       = silenceremove_outputs,
474 };