Merge branch 'refs/heads/t/blob'
[paraslash.git] / amp_filter.c
1 /* Copyright (C) 2009 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file amp_filter.c Paraslash's amplify filter. */
4
5 #include <regex.h>
6 #include <lopsub.h>
7
8 #include "filter_cmd.lsg.h"
9 #include "para.h"
10 #include "list.h"
11 #include "sched.h"
12 #include "buffer_tree.h"
13 #include "filter.h"
14 #include "string.h"
15 #include "error.h"
16
17 extern char *stat_item_values[NUM_STAT_ITEMS];
18
19 /** Data specific to the amplify filter. */
20 struct private_amp_data {
21 /** Amplification factor. */
22 unsigned amp;
23 };
24
25 static void amp_close(struct filter_node *fn)
26 {
27 free(fn->private_data);
28 }
29
30 static void amp_open(struct filter_node *fn)
31 {
32 struct private_amp_data *pad = para_calloc(sizeof(*pad));
33 unsigned given = FILTER_CMD_OPT_GIVEN(AMP, AMP, fn->lpr);
34 uint32_t amp_arg = FILTER_CMD_OPT_UINT32_VAL(AMP, AMP, fn->lpr);
35
36 fn->private_data = pad;
37 fn->min_iqs = 2;
38 if (!given && stat_item_values[SI_amplification])
39 sscanf(stat_item_values[SI_amplification], "%u", &pad->amp);
40 else
41 pad->amp = amp_arg;
42 PARA_INFO_LOG("amplification: %u (scaling factor: %1.2f)\n",
43 pad->amp, pad->amp / 64.0 + 1.0);
44 }
45
46 static int amp_post_select(__a_unused struct sched *s, void *context)
47 {
48 struct filter_node *fn = context;
49 struct private_amp_data *pad = fn->private_data;
50 struct btr_node *btrn = fn->btrn;
51 int ret, factor = 64 + pad->amp;
52 size_t i, in_bytes, len;
53 int16_t *in, *out;
54 bool inplace = btr_inplace_ok(btrn);
55
56 if (pad->amp == 0) { /* no amplification */
57 btr_splice_out_node(&fn->btrn);
58 return -E_AMP_ZERO_AMP;
59 }
60 next_buffer:
61 ret = btr_node_status(btrn, fn->min_iqs, BTR_NT_INTERNAL);
62 if (ret < 0)
63 goto err;
64 if (ret == 0)
65 return 0;
66 btr_merge(btrn, fn->min_iqs);
67 in_bytes = btr_next_buffer(btrn, (char **)&in);
68 len = in_bytes / 2;
69 if (len == 0) { /* eof and in_bytes == 1 */
70 ret = -E_AMP_EOF;
71 goto err;
72 }
73
74 if (inplace)
75 out = in;
76 else
77 out = para_malloc(len * 2);
78
79 for (i = 0; i < len; i++) {
80 int x = (in[i] * factor) >> 6;
81
82 out[i] = x;
83 if (out[i] != x) /* overflow, clip */
84 out[i] = (x >= 0)? 32767 : -32768;
85 }
86
87 if (inplace)
88 btr_pushdown_one(btrn);
89 else {
90 btr_consume(btrn, len * 2);
91 btr_add_output((char *)out, len * 2, btrn);
92 }
93 goto next_buffer;
94 err:
95 assert(ret < 0);
96 btr_remove_node(&fn->btrn);
97 return ret;
98 }
99
100 const struct filter lsg_filter_cmd_com_amp_user_data = {
101 .open = amp_open,
102 .close = amp_close,
103 .pre_select = generic_filter_pre_select,
104 .post_select = amp_post_select,
105 };