]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_silenceremove.c
avfilter/af_silenceremove: add peak detector
[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 sum;
69
70     int leave_silence;
71     int restart;
72     int64_t next_pts;
73
74     int detection;
75     void (*update)(struct SilenceRemoveContext *s, double sample);
76     double(*compute)(struct SilenceRemoveContext *s, double sample);
77 } SilenceRemoveContext;
78
79 #define OFFSET(x) offsetof(SilenceRemoveContext, x)
80 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
81 static const AVOption silenceremove_options[] = {
82     { "start_periods",   NULL, OFFSET(start_periods),   AV_OPT_TYPE_INT,      {.i64=0},     0,    9000, FLAGS },
83     { "start_duration",  NULL, OFFSET(start_duration),  AV_OPT_TYPE_DURATION, {.i64=0},     0,    9000, FLAGS },
84     { "start_threshold", NULL, OFFSET(start_threshold), AV_OPT_TYPE_DOUBLE,   {.dbl=0},     0, DBL_MAX, FLAGS },
85     { "stop_periods",    NULL, OFFSET(stop_periods),    AV_OPT_TYPE_INT,      {.i64=0}, -9000,    9000, FLAGS },
86     { "stop_duration",   NULL, OFFSET(stop_duration),   AV_OPT_TYPE_DURATION, {.i64=0},     0,    9000, FLAGS },
87     { "stop_threshold",  NULL, OFFSET(stop_threshold),  AV_OPT_TYPE_DOUBLE,   {.dbl=0},     0, DBL_MAX, FLAGS },
88     { "leave_silence",   NULL, OFFSET(leave_silence),   AV_OPT_TYPE_BOOL,     {.i64=0},     0,       1, FLAGS },
89     { "detection",       NULL, OFFSET(detection),       AV_OPT_TYPE_INT,      {.i64=1},     0,       1, FLAGS, "detection" },
90     {   "peak",          0,    0,                       AV_OPT_TYPE_CONST,    {.i64=0},     0,       0, FLAGS, "detection" },
91     {   "rms",           0,    0,                       AV_OPT_TYPE_CONST,    {.i64=1},     0,       0, FLAGS, "detection" },
92     { NULL }
93 };
94
95 AVFILTER_DEFINE_CLASS(silenceremove);
96
97 static double compute_peak(SilenceRemoveContext *s, double sample)
98 {
99     double new_sum;
100
101     new_sum  = s->sum;
102     new_sum -= *s->window_current;
103     new_sum += fabs(sample);
104
105     return new_sum / s->window_size;
106 }
107
108 static void update_peak(SilenceRemoveContext *s, double sample)
109 {
110     s->sum -= *s->window_current;
111     *s->window_current = fabs(sample);
112     s->sum += *s->window_current;
113
114     s->window_current++;
115     if (s->window_current >= s->window_end)
116         s->window_current = s->window;
117 }
118
119 static double compute_rms(SilenceRemoveContext *s, double sample)
120 {
121     double new_sum;
122
123     new_sum  = s->sum;
124     new_sum -= *s->window_current;
125     new_sum += sample * sample;
126
127     return sqrt(new_sum / s->window_size);
128 }
129
130 static void update_rms(SilenceRemoveContext *s, double sample)
131 {
132     s->sum -= *s->window_current;
133     *s->window_current = sample * sample;
134     s->sum += *s->window_current;
135
136     s->window_current++;
137     if (s->window_current >= s->window_end)
138         s->window_current = s->window;
139 }
140
141 static av_cold int init(AVFilterContext *ctx)
142 {
143     SilenceRemoveContext *s = ctx->priv;
144
145     if (s->stop_periods < 0) {
146         s->stop_periods = -s->stop_periods;
147         s->restart = 1;
148     }
149
150     switch (s->detection) {
151     case 0:
152         s->update = update_peak;
153         s->compute = compute_peak;
154         break;
155     case 1:
156         s->update = update_rms;
157         s->compute = compute_rms;
158         break;
159     };
160
161     return 0;
162 }
163
164 static void clear_window(SilenceRemoveContext *s)
165 {
166     memset(s->window, 0, s->window_size * sizeof(*s->window));
167
168     s->window_current = s->window;
169     s->window_end = s->window + s->window_size;
170     s->sum = 0;
171 }
172
173 static int config_input(AVFilterLink *inlink)
174 {
175     AVFilterContext *ctx = inlink->dst;
176     SilenceRemoveContext *s = ctx->priv;
177
178     s->window_size = (inlink->sample_rate / 50) * inlink->channels;
179     s->window = av_malloc_array(s->window_size, sizeof(*s->window));
180     if (!s->window)
181         return AVERROR(ENOMEM);
182
183     clear_window(s);
184
185     s->start_duration = av_rescale(s->start_duration, inlink->sample_rate,
186                                    AV_TIME_BASE);
187     s->stop_duration  = av_rescale(s->stop_duration, inlink->sample_rate,
188                                    AV_TIME_BASE);
189
190     s->start_holdoff = av_malloc_array(FFMAX(s->start_duration, 1),
191                                        sizeof(*s->start_holdoff) *
192                                        inlink->channels);
193     if (!s->start_holdoff)
194         return AVERROR(ENOMEM);
195
196     s->start_holdoff_offset = 0;
197     s->start_holdoff_end    = 0;
198     s->start_found_periods  = 0;
199
200     s->stop_holdoff = av_malloc_array(FFMAX(s->stop_duration, 1),
201                                       sizeof(*s->stop_holdoff) *
202                                       inlink->channels);
203     if (!s->stop_holdoff)
204         return AVERROR(ENOMEM);
205
206     s->stop_holdoff_offset = 0;
207     s->stop_holdoff_end    = 0;
208     s->stop_found_periods  = 0;
209
210     if (s->start_periods)
211         s->mode = SILENCE_TRIM;
212     else
213         s->mode = SILENCE_COPY;
214
215     return 0;
216 }
217
218 static void flush(AVFrame *out, AVFilterLink *outlink,
219                   int *nb_samples_written, int *ret)
220 {
221     if (*nb_samples_written) {
222         out->nb_samples = *nb_samples_written / outlink->channels;
223         *ret = ff_filter_frame(outlink, out);
224         *nb_samples_written = 0;
225     } else {
226         av_frame_free(&out);
227     }
228 }
229
230 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
231 {
232     AVFilterContext *ctx = inlink->dst;
233     AVFilterLink *outlink = ctx->outputs[0];
234     SilenceRemoveContext *s = ctx->priv;
235     int i, j, threshold, ret = 0;
236     int nbs, nb_samples_read, nb_samples_written;
237     double *obuf, *ibuf = (double *)in->data[0];
238     AVFrame *out;
239
240     nb_samples_read = nb_samples_written = 0;
241
242     switch (s->mode) {
243     case SILENCE_TRIM:
244 silence_trim:
245         nbs = in->nb_samples - nb_samples_read / inlink->channels;
246         if (!nbs)
247             break;
248
249         for (i = 0; i < nbs; i++) {
250             threshold = 0;
251             for (j = 0; j < inlink->channels; j++) {
252                 threshold |= s->compute(s, ibuf[j]) > s->start_threshold;
253             }
254
255             if (threshold) {
256                 for (j = 0; j < inlink->channels; j++) {
257                     s->update(s, *ibuf);
258                     s->start_holdoff[s->start_holdoff_end++] = *ibuf++;
259                     nb_samples_read++;
260                 }
261
262                 if (s->start_holdoff_end >= s->start_duration * inlink->channels) {
263                     if (++s->start_found_periods >= s->start_periods) {
264                         s->mode = SILENCE_TRIM_FLUSH;
265                         goto silence_trim_flush;
266                     }
267
268                     s->start_holdoff_offset = 0;
269                     s->start_holdoff_end = 0;
270                 }
271             } else {
272                 s->start_holdoff_end = 0;
273
274                 for (j = 0; j < inlink->channels; j++)
275                     s->update(s, ibuf[j]);
276
277                 ibuf += inlink->channels;
278                 nb_samples_read += inlink->channels;
279             }
280         }
281         break;
282
283     case SILENCE_TRIM_FLUSH:
284 silence_trim_flush:
285         nbs  = s->start_holdoff_end - s->start_holdoff_offset;
286         nbs -= nbs % inlink->channels;
287         if (!nbs)
288             break;
289
290         out = ff_get_audio_buffer(inlink, nbs / inlink->channels);
291         if (!out) {
292             av_frame_free(&in);
293             return AVERROR(ENOMEM);
294         }
295
296         memcpy(out->data[0], &s->start_holdoff[s->start_holdoff_offset],
297                nbs * sizeof(double));
298         s->start_holdoff_offset += nbs;
299
300         ret = ff_filter_frame(outlink, out);
301
302         if (s->start_holdoff_offset == s->start_holdoff_end) {
303             s->start_holdoff_offset = 0;
304             s->start_holdoff_end = 0;
305             s->mode = SILENCE_COPY;
306             goto silence_copy;
307         }
308         break;
309
310     case SILENCE_COPY:
311 silence_copy:
312         nbs = in->nb_samples - nb_samples_read / inlink->channels;
313         if (!nbs)
314             break;
315
316         out = ff_get_audio_buffer(inlink, nbs);
317         if (!out) {
318             av_frame_free(&in);
319             return AVERROR(ENOMEM);
320         }
321         obuf = (double *)out->data[0];
322
323         if (s->stop_periods) {
324             for (i = 0; i < nbs; i++) {
325                 threshold = 1;
326                 for (j = 0; j < inlink->channels; j++)
327                     threshold &= s->compute(s, ibuf[j]) > s->stop_threshold;
328
329                 if (threshold && s->stop_holdoff_end && !s->leave_silence) {
330                     s->mode = SILENCE_COPY_FLUSH;
331                     flush(out, outlink, &nb_samples_written, &ret);
332                     goto silence_copy_flush;
333                 } else if (threshold) {
334                     for (j = 0; j < inlink->channels; j++) {
335                         s->update(s, *ibuf);
336                         *obuf++ = *ibuf++;
337                         nb_samples_read++;
338                         nb_samples_written++;
339                     }
340                 } else if (!threshold) {
341                     for (j = 0; j < inlink->channels; j++) {
342                         s->update(s, *ibuf);
343                         if (s->leave_silence) {
344                             *obuf++ = *ibuf;
345                             nb_samples_written++;
346                         }
347
348                         s->stop_holdoff[s->stop_holdoff_end++] = *ibuf++;
349                         nb_samples_read++;
350                     }
351
352                     if (s->stop_holdoff_end >= s->stop_duration * inlink->channels) {
353                         if (++s->stop_found_periods >= s->stop_periods) {
354                             s->stop_holdoff_offset = 0;
355                             s->stop_holdoff_end = 0;
356
357                             if (!s->restart) {
358                                 s->mode = SILENCE_STOP;
359                                 flush(out, outlink, &nb_samples_written, &ret);
360                                 goto silence_stop;
361                             } else {
362                                 s->stop_found_periods = 0;
363                                 s->start_found_periods = 0;
364                                 s->start_holdoff_offset = 0;
365                                 s->start_holdoff_end = 0;
366                                 clear_window(s);
367                                 s->mode = SILENCE_TRIM;
368                                 flush(out, outlink, &nb_samples_written, &ret);
369                                 goto silence_trim;
370                             }
371                         }
372                         s->mode = SILENCE_COPY_FLUSH;
373                         flush(out, outlink, &nb_samples_written, &ret);
374                         goto silence_copy_flush;
375                     }
376                 }
377             }
378             flush(out, outlink, &nb_samples_written, &ret);
379         } else {
380             memcpy(obuf, ibuf, sizeof(double) * nbs * inlink->channels);
381             ret = ff_filter_frame(outlink, out);
382         }
383         break;
384
385     case SILENCE_COPY_FLUSH:
386 silence_copy_flush:
387         nbs  = s->stop_holdoff_end - s->stop_holdoff_offset;
388         nbs -= nbs % inlink->channels;
389         if (!nbs)
390             break;
391
392         out = ff_get_audio_buffer(inlink, nbs / inlink->channels);
393         if (!out) {
394             av_frame_free(&in);
395             return AVERROR(ENOMEM);
396         }
397
398         memcpy(out->data[0], &s->stop_holdoff[s->stop_holdoff_offset],
399                nbs * sizeof(double));
400         s->stop_holdoff_offset += nbs;
401
402         ret = ff_filter_frame(outlink, out);
403
404         if (s->stop_holdoff_offset == s->stop_holdoff_end) {
405             s->stop_holdoff_offset = 0;
406             s->stop_holdoff_end = 0;
407             s->mode = SILENCE_COPY;
408             goto silence_copy;
409         }
410         break;
411     case SILENCE_STOP:
412 silence_stop:
413         break;
414     }
415
416     av_frame_free(&in);
417
418     return ret;
419 }
420
421 static int request_frame(AVFilterLink *outlink)
422 {
423     AVFilterContext *ctx = outlink->src;
424     SilenceRemoveContext *s = ctx->priv;
425     int ret;
426
427     ret = ff_request_frame(ctx->inputs[0]);
428     if (ret == AVERROR_EOF && (s->mode == SILENCE_COPY_FLUSH ||
429                                s->mode == SILENCE_COPY)) {
430         int nbs = s->stop_holdoff_end - s->stop_holdoff_offset;
431         if (nbs) {
432             AVFrame *frame;
433
434             frame = ff_get_audio_buffer(outlink, nbs / outlink->channels);
435             if (!frame)
436                 return AVERROR(ENOMEM);
437
438             memcpy(frame->data[0], &s->stop_holdoff[s->stop_holdoff_offset],
439                    nbs * sizeof(double));
440             ret = ff_filter_frame(ctx->inputs[0], frame);
441         }
442         s->mode = SILENCE_STOP;
443     }
444     return ret;
445 }
446
447 static int query_formats(AVFilterContext *ctx)
448 {
449     AVFilterFormats *formats = NULL;
450     AVFilterChannelLayouts *layouts = NULL;
451     static const enum AVSampleFormat sample_fmts[] = {
452         AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_NONE
453     };
454     int ret;
455
456     layouts = ff_all_channel_counts();
457     if (!layouts)
458         return AVERROR(ENOMEM);
459     ret = ff_set_common_channel_layouts(ctx, layouts);
460     if (ret < 0)
461         return ret;
462
463     formats = ff_make_format_list(sample_fmts);
464     if (!formats)
465         return AVERROR(ENOMEM);
466     ret = ff_set_common_formats(ctx, formats);
467     if (ret < 0)
468         return ret;
469
470     formats = ff_all_samplerates();
471     if (!formats)
472         return AVERROR(ENOMEM);
473     return ff_set_common_samplerates(ctx, formats);
474 }
475
476 static av_cold void uninit(AVFilterContext *ctx)
477 {
478     SilenceRemoveContext *s = ctx->priv;
479
480     av_freep(&s->start_holdoff);
481     av_freep(&s->stop_holdoff);
482     av_freep(&s->window);
483 }
484
485 static const AVFilterPad silenceremove_inputs[] = {
486     {
487         .name         = "default",
488         .type         = AVMEDIA_TYPE_AUDIO,
489         .config_props = config_input,
490         .filter_frame = filter_frame,
491     },
492     { NULL }
493 };
494
495 static const AVFilterPad silenceremove_outputs[] = {
496     {
497         .name          = "default",
498         .type          = AVMEDIA_TYPE_AUDIO,
499         .request_frame = request_frame,
500     },
501     { NULL }
502 };
503
504 AVFilter ff_af_silenceremove = {
505     .name          = "silenceremove",
506     .description   = NULL_IF_CONFIG_SMALL("Remove silence."),
507     .priv_size     = sizeof(SilenceRemoveContext),
508     .priv_class    = &silenceremove_class,
509     .init          = init,
510     .uninit        = uninit,
511     .query_formats = query_formats,
512     .inputs        = silenceremove_inputs,
513     .outputs       = silenceremove_outputs,
514 };