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