1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file compress_filter.c Paraslash's dynamic audio range compressor. */
6 * Uses ideas of AudioCompress, (C) 2002-2004 M. Hari Nezumi <magenta@trikuare.cx>
12 #include "filter_cmd.lsg.h"
16 #include "buffer_tree.h"
21 #define U32_OPTVAL(_opt, _lpr) (FILTER_CMD_OPT_UINT32_VAL(COMPRESS, _opt, _lpr))
23 /** Data specific to the compress filter. */
24 struct private_compress_data {
25 /** The current multiplier. */
26 unsigned current_gain;
27 /** Maximal admissible gain. */
29 /** Number of samples already seen. */
31 /** Absolute value of the maximal sample in the current block. */
35 static void compress_close(struct filter_node *fn)
37 free(fn->private_data);
40 static int compress_post_select(__a_unused struct sched *s, void *context)
42 struct filter_node *fn = context;
43 struct private_compress_data *pcd = fn->private_data;
44 struct btr_node *btrn = fn->btrn;
45 bool inplace = btr_inplace_ok(btrn);
50 uint32_t inertia = U32_OPTVAL(INERTIA, fn->lpr);
51 unsigned gain_shift = inertia + U32_OPTVAL(DAMP, fn->lpr),
52 mask = (1 << U32_OPTVAL(BLOCKSIZE, fn->lpr)) - 1;
55 ret = btr_node_status(btrn, fn->min_iqs, BTR_NT_INTERNAL);
60 btr_merge(btrn, fn->min_iqs);
61 length = btr_next_buffer(btrn, &inbuf) & ~(size_t)1;
62 if (length == 0) { /* eof and 1 byte available */
63 ret = -E_COMPRESS_EOF;
66 ip = (int16_t *)inbuf;
70 op = para_malloc(length);
71 for (i = 0; i < length / 2; i++) {
72 /* be careful in that heat, my dear */
80 sample *= pcd->current_gain;
81 sample >>= gain_shift;
82 if (sample > 32767) { /* clip */
84 pcd->current_gain = (3 * pcd->current_gain +
87 } else if (sample > pcd->peak)
89 op[i] = neg? -sample : sample;
90 if (++pcd->num_samples & mask)
92 // PARA_DEBUG_LOG("gain: %u, peak: %u\n", pcd->current_gain,
94 if (pcd->peak < U32_OPTVAL(TARGET_LEVEL, fn->lpr)) {
95 if (pcd->current_gain < pcd->max_gain)
98 pcd->current_gain = PARA_MAX(pcd->current_gain - 2,
103 btr_pushdown_one(btrn);
105 btr_consume(btrn, length);
106 btr_add_output((char *)op, length, btrn);
111 btr_remove_node(&fn->btrn);
115 static void compress_open(struct filter_node *fn)
117 struct private_compress_data *pcd = para_calloc(sizeof(*pcd));
118 uint32_t inertia = U32_OPTVAL(INERTIA, fn->lpr);
119 uint32_t aggressiveness = U32_OPTVAL(AGGRESSIVENESS, fn->lpr);
121 fn->private_data = pcd;
122 fn->min_iqs = 2; /* 16 bit audio */
123 pcd->current_gain = 1U << inertia;
124 pcd->max_gain = 1U << (inertia + aggressiveness);
127 const struct filter lsg_filter_cmd_com_compress_user_data = {
128 .open = compress_open,
129 .close = compress_close,
130 .pre_select = generic_filter_pre_select,
131 .post_select = compress_post_select,