35#define MIN_FILTER_SIZE 3
36#define MAX_FILTER_SIZE 301
38#define FF_BUFQUEUE_SIZE (MAX_FILTER_SIZE + 1)
126#define OFFSET(x) offsetof(DynamicAudioNormalizerContext, x)
127#define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
165 if (!(
s->filter_size & 1)) {
173static inline int frame_size(
int sample_rate,
int frame_len_msec)
268 for (
int i = 0;
i < side;
i++)
272 int count = (q->
size - new_size + 1) / 2;
283 double total_weight = 0.0;
284 const double sigma = (((
s->filter_size / 2.0) - 1.0) / 3.0) + (1.0 / 3.0);
288 const int offset =
s->filter_size / 2;
289 const double c1 = 1.0 / (sigma * sqrt(2.0 *
M_PI));
290 const double c2 = 2.0 * sigma * sigma;
293 for (
int i = 0;
i <
s->filter_size;
i++) {
297 total_weight +=
s->weights[
i];
301 adjust = 1.0 / total_weight;
302 for (
int i = 0;
i <
s->filter_size;
i++) {
315 for (
int c = 0;
c <
s->channels;
c++) {
316 if (
s->gain_history_original)
318 if (
s->gain_history_minimum)
320 if (
s->gain_history_smoothed)
322 if (
s->threshold_history)
332 s->is_enabled =
NULL;
355 if (
s->frame_len < 0)
368 if (!
s->prev_amplification_factor || !
s->dc_correction_value ||
369 !
s->compress_threshold ||
370 !
s->gain_history_original || !
s->gain_history_minimum ||
371 !
s->gain_history_smoothed || !
s->threshold_history ||
372 !
s->is_enabled || !
s->weights)
376 s->prev_amplification_factor[
c] = 1.0;
383 if (!
s->gain_history_original[
c] || !
s->gain_history_minimum[
c] ||
384 !
s->gain_history_smoothed[
c] || !
s->threshold_history[
c])
393 s->sample_advance =
FFMAX(1,
lrint(
s->frame_len * (1. -
s->overlap)));
404static inline double fade(
double prev,
double next,
int pos,
int length)
406 const double step_size = 1.0 / length;
407 const double f0 = 1.0 - (step_size * (
pos + 1.0));
408 const double f1 = 1.0 - f0;
409 return f0 * prev + f1 * next;
417static inline double bound(
const double threshold,
const double val)
419 const double CONST = 0.8862269254527580136490837416705725913987747280611935;
420 return erf(
CONST * (
val / threshold)) * threshold;
425 double max = DBL_EPSILON;
428 for (
int c = 0;
c <
frame->ch_layout.nb_channels;
c++) {
429 double *data_ptr = (
double *)
frame->extended_data[
c];
431 for (
int i = 0;
i <
frame->nb_samples;
i++)
435 double *data_ptr = (
double *)
frame->extended_data[
channel];
437 for (
int i = 0;
i <
frame->nb_samples;
i++)
446 double rms_value = 0.0;
449 for (
int c = 0;
c <
frame->ch_layout.nb_channels;
c++) {
450 const double *data_ptr = (
double *)
frame->extended_data[
c];
452 for (
int i = 0;
i <
frame->nb_samples;
i++) {
453 rms_value +=
pow_2(data_ptr[
i]);
457 rms_value /=
frame->nb_samples *
frame->ch_layout.nb_channels;
459 const double *data_ptr = (
double *)
frame->extended_data[
channel];
460 for (
int i = 0;
i <
frame->nb_samples;
i++) {
461 rms_value +=
pow_2(data_ptr[
i]);
464 rms_value /=
frame->nb_samples;
467 return fmax(sqrt(rms_value), DBL_EPSILON);
474 const double maximum_gain =
s->peak_value / peak_magnitude;
476 double target_gain = DBL_MAX;
482 memcpy(var_values,
s->var_values,
sizeof(var_values));
485 var_values[
VAR_P] = peak_magnitude;
487 target_gain =
av_expr_eval(
s->expr, var_values,
s) / peak_magnitude;
490 gain.
threshold = peak_magnitude >
s->threshold;
498 double min = DBL_MAX;
510 double result = 0.0, tsum = 0.0;
517 result += tq_item *
weights[
i] * q_item;
530 const int pre_fill_size =
s->filter_size / 2;
533 s->prev_amplification_factor[
channel] = initial_value;
547 const int pre_fill_size =
s->filter_size / 2;
548 double initial_value =
s->alt_boundary_mode ?
cqueue_peek(
s->gain_history_original[
channel], 0) : 1.0;
549 int input = pre_fill_size;
568 double smoothed,
limit;
589 for (
int c = start;
c < end;
c++)
595static inline double update_value(
double new,
double old,
double aggressiveness)
597 av_assert0((aggressiveness >= 0.0) && (aggressiveness <= 1.0));
598 return aggressiveness *
new + (1.0 - aggressiveness) * old;
610 const double diff = 1.0 /
frame->nb_samples;
611 int is_first_frame =
cqueue_empty(
s->gain_history_original[0]);
613 for (
int c = 0;
c <
s->channels;
c++) {
615 double *dst_ptr = (
double *)
frame->extended_data[
c];
616 double current_average_value = 0.0;
619 for (
int i = 0;
i <
frame->nb_samples;
i++)
620 current_average_value += dst_ptr[
i] *
diff;
622 prev_value = is_first_frame ? current_average_value :
s->dc_correction_value[
c];
623 s->dc_correction_value[
c] = is_first_frame ? current_average_value :
update_value(current_average_value,
s->dc_correction_value[
c], 0.1);
625 for (
int i = 0;
i <
frame->nb_samples && !bypass;
i++) {
626 dst_ptr[
i] -=
fade(prev_value,
s->dc_correction_value[
c],
i,
frame->nb_samples);
633 if ((threshold > DBL_EPSILON) && (threshold < (1.0 - DBL_EPSILON))) {
634 double current_threshold = threshold;
635 double step_size = 1.0;
637 while (step_size > DBL_EPSILON) {
638 while ((
llrint((current_threshold + step_size) * (UINT64_C(1) << 63)) >
639 llrint(current_threshold * (UINT64_C(1) << 63))) &&
640 (
bound(current_threshold + step_size, 1.0) <= threshold)) {
641 current_threshold += step_size;
647 return current_threshold;
656 double variance = 0.0;
659 for (
int c = 0;
c <
s->channels;
c++) {
660 const double *data_ptr = (
double *)
frame->extended_data[
c];
662 for (
int i = 0;
i <
frame->nb_samples;
i++) {
663 variance +=
pow_2(data_ptr[
i]);
666 variance /= (
s->channels *
frame->nb_samples) - 1;
668 const double *data_ptr = (
double *)
frame->extended_data[
channel];
670 for (
int i = 0;
i <
frame->nb_samples;
i++) {
671 variance +=
pow_2(data_ptr[
i]);
673 variance /=
frame->nb_samples - 1;
676 return fmax(sqrt(variance), DBL_EPSILON);
681 int is_first_frame =
cqueue_empty(
s->gain_history_original[0]);
683 if (
s->channels_coupled) {
685 const double current_threshold =
fmin(1.0,
s->compress_factor * standard_deviation);
687 const double prev_value = is_first_frame ? current_threshold :
s->compress_threshold[0];
688 double prev_actual_thresh, curr_actual_thresh;
689 s->compress_threshold[0] = is_first_frame ? current_threshold :
update_value(current_threshold,
s->compress_threshold[0], (1.0/3.0));
694 for (
int c = 0;
c <
s->channels;
c++) {
695 double *
const dst_ptr = (
double *)
frame->extended_data[
c];
701 for (
int i = 0;
i <
frame->nb_samples;
i++) {
702 const double localThresh =
fade(prev_actual_thresh, curr_actual_thresh,
i,
frame->nb_samples);
703 dst_ptr[
i] = copysign(
bound(localThresh,
fabs(dst_ptr[
i])), dst_ptr[
i]);
707 for (
int c = 0;
c <
s->channels;
c++) {
711 const double prev_value = is_first_frame ? current_threshold :
s->compress_threshold[
c];
712 double prev_actual_thresh, curr_actual_thresh;
715 s->compress_threshold[
c] = is_first_frame ? current_threshold :
update_value(current_threshold,
s->compress_threshold[
c], 1.0/3.0);
720 dst_ptr = (
double *)
frame->extended_data[
c];
721 for (
int i = 0;
i <
frame->nb_samples && !bypass;
i++) {
722 const double localThresh =
fade(prev_actual_thresh, curr_actual_thresh,
i,
frame->nb_samples);
723 dst_ptr[
i] = copysign(
bound(localThresh,
fabs(dst_ptr[
i])), dst_ptr[
i]);
735 if (
s->dc_correction ||
s->compress_factor > DBL_EPSILON) {
763 if (
s->dc_correction)
766 if (
s->compress_factor > DBL_EPSILON)
769 if (
s->frame_len !=
s->sample_advance) {
770 const int offset =
s->frame_len -
s->sample_advance;
772 for (
int c = 0;
c <
s->channels;
c++) {
773 double *
src = (
double *)
s->window->extended_data[
c];
775 memmove(
src, &
src[
s->sample_advance],
offset *
sizeof(
double));
776 memcpy(&
src[
offset], (*frame)->extended_data[
c], (*frame)->nb_samples *
sizeof(
double));
777 memset(&
src[
offset + (*frame)->nb_samples], 0, (
s->sample_advance - (*frame)->nb_samples) *
sizeof(
double));
783 FFMIN(
s->frame_len, (*frame)->nb_samples), (*frame)->ch_layout.nb_channels, (*frame)->format);
790 if (
s->channels_coupled) {
792 for (
int c = 0;
c <
s->channels;
c++)
807 double *dst_ptr = (
double *)
frame->extended_data[
c];
808 double current_amplification_factor;
812 for (
int i = 0;
i <
frame->nb_samples && enabled && !bypass;
i++) {
813 const double amplification_factor =
fade(
s->prev_amplification_factor[
c],
814 current_amplification_factor,
i,
817 dst_ptr[
i] = src_ptr[
i] * amplification_factor;
820 s->prev_amplification_factor[
c] = current_amplification_factor;
829 const int enabled = td->
enabled;
834 for (
int ch = start; ch < end; ch++)
848 while (((
s->queue.available >=
s->filter_size) ||
849 (
s->eof &&
s->queue.available)) &&
904 for (
int c = 0;
c <
s->channels;
c++) {
905 double *dst_ptr = (
double *)
out->extended_data[
c];
907 for (
int i = 0;
i <
out->nb_samples;
i++) {
908 dst_ptr[
i] =
s->alt_boundary_mode ? DBL_EPSILON : ((
s->target_rms > DBL_EPSILON) ?
fmin(
s->peak_value,
s->target_rms) :
s->peak_value);
909 if (
s->dc_correction) {
910 dst_ptr[
i] *= ((
i % 2) == 1) ? -1 : 1;
911 dst_ptr[
i] +=
s->dc_correction_value[
c];
926 for (
int c = 0;
c <
s->channels;
c++)
945 if (strcmp(
s->channels_to_filter,
"all"))
971 if (
s->eof &&
s->queue.available)
972 return flush(outlink);
974 if (
s->eof && !
s->queue.available) {
986 char *res,
int res_len,
int flags)
990 int prev_filter_size =
s->filter_size;
998 if (prev_filter_size !=
s->filter_size) {
1001 for (
int c = 0;
c <
s->channels;
c++) {
1011 if (frame_len !=
s->frame_len) {
1017 s->frame_len = frame_len;
1019 s->sample_advance =
FFMAX(1,
lrint(
s->frame_len * (1. -
s->overlap)));
1038 .p.name =
"dynaudnorm",
1040 .p.priv_class = &dynaudnorm_class,
static double val(void *priv, double ch)
static int config_input(AVFilterLink *inlink)
static int process_command(AVFilterContext *ctx, const char *cmd, const char *args, char *res, int res_len, int flags)
static int cqueue_pop(cqueue *q)
static void cqueue_resize(cqueue *q, int new_size)
static void amplify_channel(DynamicAudioNormalizerContext *s, AVFrame *in, AVFrame *frame, int enabled, int c)
static double bound(const double threshold, const double val)
static void perform_compression(DynamicAudioNormalizerContext *s, AVFrame *frame)
static int cqueue_empty(cqueue *q)
const FFFilter ff_af_dynaudnorm
static double update_value(double new, double old, double aggressiveness)
static double compute_frame_rms(AVFrame *frame, int channel)
static int flush_buffer(DynamicAudioNormalizerContext *s, AVFilterLink *inlink, AVFilterLink *outlink)
static cqueue * cqueue_create(int size, int max_size)
static int cqueue_enqueue(cqueue *q, double element)
static const AVOption dynaudnorm_options[]
static void perform_dc_correction(DynamicAudioNormalizerContext *s, AVFrame *frame)
static int update_gain_histories(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
static double setup_compress_thresh(double threshold)
static local_gain get_max_local_gain(DynamicAudioNormalizerContext *s, AVFrame *frame, int channel)
static double compute_frame_std_dev(DynamicAudioNormalizerContext *s, AVFrame *frame, int channel)
static int cqueue_size(cqueue *q)
static double minimum_filter(cqueue *q)
static double cqueue_peek(cqueue *q, int index)
static void update_gain_history(DynamicAudioNormalizerContext *s, int channel, local_gain gain)
static void cqueue_free(cqueue *q)
static double find_peak_magnitude(AVFrame *frame, int channel)
static int config_input(AVFilterLink *inlink)
static double pow_2(const double value)
static int bypass_channel(DynamicAudioNormalizerContext *s, AVFrame *frame, int ch)
static void init_gaussian_filter(DynamicAudioNormalizerContext *s)
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
static int analyze_frame(AVFilterContext *ctx, AVFilterLink *outlink, AVFrame **frame)
static int cqueue_dequeue(cqueue *q, double *element)
static int process_command(AVFilterContext *ctx, const char *cmd, const char *args, char *res, int res_len, int flags)
static int activate(AVFilterContext *ctx)
static av_cold void uninit(AVFilterContext *ctx)
static double fade(double prev, double next, int pos, int length)
static double gaussian_filter(DynamicAudioNormalizerContext *s, cqueue *q, cqueue *tq)
static int amplify_channels(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
static const AVFilterPad avfilter_af_dynaudnorm_inputs[]
static AVFormatContext * ctx
const AVFilterPad ff_audio_default_filterpad[1]
An AVFilterPad array whose only entry has name "default" and is of type AVMEDIA_TYPE_AUDIO.
AVFrame * ff_get_audio_buffer(AVFilterLink *link, int nb_samples)
Request an audio samples buffer with a specific set of permissions.
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert2(cond)
assert() equivalent, that does lie in speed critical code.
#define av_assert0(cond)
assert() equivalent, that is always enabled.
int ff_inlink_acknowledge_status(AVFilterLink *link, int *rstatus, int64_t *rpts)
Test and acknowledge the change of status on the link.
int ff_inlink_check_available_samples(AVFilterLink *link, unsigned min)
Test if enough samples are available on the link.
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
int ff_filter_process_command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
Generic processing of user supplied commands that are set in the same way as the filter options.
int ff_filter_execute(AVFilterContext *ctx, avfilter_action_func *func, void *arg, int *ret, int nb_jobs)
int ff_inlink_consume_samples(AVFilterLink *link, unsigned min, unsigned max, AVFrame **rframe)
Take samples from the link's FIFO and update the link's stats.
int ff_filter_get_nb_threads(AVFilterContext *ctx)
Get number of threads for current filter instance.
void ff_filter_set_ready(AVFilterContext *filter, unsigned priority)
Mark a filter ready and schedule it for activation.
Main libavfilter public API header.
static void ff_bufqueue_add(void *log, struct FFBufQueue *queue, AVFrame *buf)
Add a buffer to the queue.
static void ff_bufqueue_discard_all(struct FFBufQueue *queue)
Unref and remove all buffers from the queue.
static AVFrame * ff_bufqueue_get(struct FFBufQueue *queue)
Get the first buffer from the queue and remove it.
#define flags(name, subs,...)
#define i(width, name, range_min, range_max)
Public libavutil channel layout APIs header.
static __device__ float fabs(float a)
double fmin(double, double)
double fmax(double, double)
void(* flush)(AVBSFContext *ctx)
int(* init)(AVBSFContext *ctx)
channel
Use these values when setting the channel map with ebur128_set_channel().
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
int av_expr_parse(AVExpr **expr, const char *s, const char *const *const_names, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), int log_offset, void *log_ctx)
Parse an expression.
simple arithmetic expression evaluator
static SDL_Window * window
static const uint8_t frame_size[4]
@ AV_OPT_TYPE_INT
Underlying C type is int.
@ AV_OPT_TYPE_DOUBLE
Underlying C type is double.
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
#define AVFILTER_FLAG_SLICE_THREADS
The filter supports multithreading by splitting frames into multiple parts and processing them concur...
#define AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL
Same as AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, except that the filter will have its filter_frame() c...
int av_channel_layout_from_string(AVChannelLayout *channel_layout, const char *str)
Initialize a channel layout from a given string description.
int av_channel_layout_index_from_channel(const AVChannelLayout *channel_layout, enum AVChannel channel)
Get the index of a given channel in a channel layout.
enum AVChannel av_channel_layout_channel_from_index(const AVChannelLayout *channel_layout, unsigned int idx)
Get the channel with the given index in a channel layout.
void av_channel_layout_uninit(AVChannelLayout *channel_layout)
Free any allocated data in the channel layout and reset the channel count to 0.
int av_channel_layout_copy(AVChannelLayout *dst, const AVChannelLayout *src)
Make a copy of a channel layout.
#define AVERROR_EOF
End of file.
int av_frame_is_writable(AVFrame *frame)
Check if the frame data is writable.
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
int av_frame_copy_props(AVFrame *dst, const AVFrame *src)
Copy only "metadata" fields from src to dst.
int av_frame_copy(AVFrame *dst, const AVFrame *src)
Copy the frame data from src to dst.
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
#define AV_LOG_WARNING
Something somehow does not look correct.
static AVRational av_make_q(int num, int den)
Create an AVRational.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
@ AV_SAMPLE_FMT_DBLP
double, planar
int av_samples_copy(uint8_t *const *dst, uint8_t *const *src, int dst_offset, int src_offset, int nb_samples, int nb_channels, enum AVSampleFormat sample_fmt)
Copy samples from src to dst.
static const int weights[]
static av_cold void uninit(AVBitStreamFilterContext *ctx)
static int activate(AVBitStreamFilterContext *ctx)
#define FILTER_INPUTS(array)
#define FILTER_OUTPUTS(array)
static int ff_slice_pos(int total, int jobnr, int nb_jobs)
Compute the boundary index for a slice when work of size total is split into nb_jobs slices.
#define FF_FILTER_FORWARD_WANTED(outlink, inlink)
Forward the frame_wanted_out flag from an output link to an input link.
static void ff_outlink_set_status(AVFilterLink *link, int status, int64_t pts)
Set the status field of a link from the source filter.
#define FFERROR_NOT_READY
Filters implementation helper functions and internal structures.
#define FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink)
Forward the status on an output link to an input link.
static FilterLink * ff_filter_link(AVFilterLink *link)
#define FILTER_SINGLE_SAMPLEFMT(sample_fmt_)
#define AVFILTER_DEFINE_CLASS(fname)
#define CONST(name, help, val, u)
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
void * av_calloc(size_t nmemb, size_t size)
Memory handling functions.
static int adjust(int x, int size)
static const char *const var_names[]
An AVChannelLayout holds information about the channel layout of audio data.
int nb_channels
Number of channels in this layout.
Describe the class of an AVClass context structure.
A link between two filters.
AVFilterContext * src
source filter
AVRational time_base
Define the time base used by the PTS of the frames/samples which will pass through this link.
int sample_rate
samples per second
AVChannelLayout ch_layout
channel layout of current buffer (see libavutil/channel_layout.h)
AVFilterContext * dst
dest filter
A filter pad used for either input or output.
This structure describes decoded (raw) audio or video data.
int nb_samples
number of audio samples (per channel) described by this frame
uint8_t ** extended_data
pointers to the data planes/channels.
double var_values[VAR_VARS_NB]
cqueue ** gain_history_minimum
cqueue ** threshold_history
double * prev_amplification_factor
AVChannelLayout ch_layout
double * dc_correction_value
char * channels_to_filter
cqueue ** gain_history_smoothed
double * compress_threshold
cqueue ** gain_history_original
Structure holding the queue.
Link properties exposed to filter code, but not external callers.
int64_t sample_count_in
Number of past samples sent through the link.
Used for passing data between threads.
#define av_malloc_array(a, b)
static av_always_inline int diff(const struct color_info *a, const struct color_info *b, const int trans_thresh)
static double limit(double x)