fade: Generate fade.ggo from m4 template.
[paraslash.git] / flacdec_filter.c
1 /*
2  * Copyright (C) 2011-2012 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file flacdec_filter.c The flac decoder. */
8
9 #include <regex.h>
10 #include <FLAC/stream_decoder.h>
11
12 #include "para.h"
13 #include "list.h"
14 #include "sched.h"
15 #include "ggo.h"
16 #include "buffer_tree.h"
17 #include "filter.h"
18 #include "error.h"
19 #include "string.h"
20
21 struct private_flacdec_data {
22         FLAC__StreamDecoder *decoder;
23         bool have_more;
24         /*
25          * We can not consume directly what was copied by the read callback
26          * because we might need to feed unconsumend bytes to the decoder again
27          * after the read callback ran out of data and returned ABORT. So we
28          * track how many bytes are unconsumed so far.
29          */
30         size_t unconsumed;
31 };
32
33 static FLAC__StreamDecoderReadStatus read_cb(
34                 __a_unused const FLAC__StreamDecoder *decoder,
35                 FLAC__byte buffer[], size_t *bytes, void *client_data)
36 {
37         struct filter_node *fn = client_data;
38         struct private_flacdec_data *pfd = fn->private_data;
39         struct btr_node *btrn = fn->btrn;
40         char *btr_buf;
41         size_t copy, want = *bytes, have;
42         int ns;
43
44         *bytes = 0;
45         assert(want > 0);
46         ns = btr_node_status(btrn, fn->min_iqs, BTR_NT_INTERNAL);
47         if (ns < 0)
48                 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
49         for (;;) {
50                 have = btr_next_buffer_omit(btrn, pfd->unconsumed, &btr_buf);
51                 if (have == 0)
52                         break;
53                 copy = PARA_MIN(want, have);
54                 //PARA_CRIT_LOG("want: %zu, have: %zu, unconsumed %zu\n",
55                 //      want, have, pfd->unconsumed);
56                 memcpy(buffer, btr_buf, copy);
57                 pfd->unconsumed += copy;
58                 *bytes += copy;
59                 buffer += copy;
60                 want -= copy;
61                 if (want == 0)
62                         break;
63         }
64         if (*bytes > 0)
65                 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
66         /*
67          * We are kind of screwed here. Returning CONTINUE with a byte count of
68          * zero leads to an endless loop, so we must return either EOF or
69          * ABORT. Unfortunately, both options require to flush the decoder
70          * afterwards because libFLAC refuses to resume decoding if the decoder
71          * is in EOF or ABORT state. But flushing implies dropping the decoder
72          * input queue, so buffered data is lost.
73          *
74          * We work around this shortcoming by remembering the number of
75          * unconsumed bytes in pfd->unconsumed. In the write/meta callbacks,
76          * this number is decreased whenever a frame has been decoded
77          * successfully and btr_consume() has been called to consume the bytes
78          * corresponding to the decoded frame.  After returning ABORT here, the
79          * decoder can be flushed, and we will feed the unconsumed bytes again.
80          */
81         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
82 }
83
84 /*
85  * The exact value does not really matter. It just has to be larger than the
86  * size of the input buffer of the bitstream reader of libflac.
87  */
88 #define TELL_CB_DUMMY_VAL 1000000
89
90 /*
91  * FLAC__stream_decoder_get_decode_position() invokes this callback. The flac
92  * library then gets the number of unconsumed bytes from the bitstream reader,
93  * subtracts this number from the offset returned here and returns the
94  * difference as the decode position.
95  */
96 static FLAC__StreamDecoderTellStatus tell_cb(__a_unused const FLAC__StreamDecoder *decoder,
97                 FLAC__uint64 *absolute_byte_offset, __a_unused void *client_data)
98 {
99         *absolute_byte_offset = TELL_CB_DUMMY_VAL;
100         return FLAC__STREAM_DECODER_TELL_STATUS_OK;
101 }
102
103 /*
104  * There is no API function that returns the number of unconsumed bytes
105  * directly. The trick is to define a tell callback which always returns a
106  * fixed dummy value and compute the number of unconsumed bytes from the return
107  * value of FLAC__stream_decoder_get_decode_position().
108  */
109 static void flac_consume(struct filter_node *fn)
110 {
111         struct private_flacdec_data *pfd = fn->private_data;
112         struct btr_node *btrn = fn->btrn;
113         FLAC__uint64 x;
114
115         FLAC__stream_decoder_get_decode_position(pfd->decoder, &x);
116         assert(x <= TELL_CB_DUMMY_VAL);
117         x = TELL_CB_DUMMY_VAL - x; /* number of unconsumed bytes */
118         assert(x <= pfd->unconsumed);
119         btr_consume(btrn, pfd->unconsumed - x);
120         pfd->unconsumed = x;
121 }
122
123 static FLAC__StreamDecoderWriteStatus write_cb(
124                 const FLAC__StreamDecoder *decoder,
125                 const FLAC__Frame *frame,
126                 const FLAC__int32 *const buffer[],
127                 void *client_data)
128 {
129         struct filter_node *fn = client_data;
130         struct btr_node *btrn = fn->btrn;
131         size_t k, n = frame->header.blocksize;
132         unsigned channels = FLAC__stream_decoder_get_channels(decoder);
133         char *outbuffer = para_malloc(n * channels * 2);
134
135         if (channels == 1) {
136                 for (k = 0; k < n; k++) {
137                         int sample = buffer[0][k];
138                         write_int16_host_endian(outbuffer + 2 * k, sample);
139                 }
140         } else {
141                 for (k = 0; k < n; k++) {
142                         int left = buffer[0][k], right = buffer[1][k];
143                         write_int16_host_endian(outbuffer + 4 * k, left);
144                         write_int16_host_endian(outbuffer + 4 * k + 2, right);
145                 }
146         }
147         btr_add_output(outbuffer, n * 4, btrn);
148         flac_consume(fn);
149         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
150 }
151
152 static void meta_cb (__a_unused const FLAC__StreamDecoder *decoder,
153                 __a_unused const FLAC__StreamMetadata *metadata,
154                 void *client_data)
155 {
156         flac_consume(client_data);
157 }
158
159 static void error_cb( __a_unused const FLAC__StreamDecoder *decoder,
160                 FLAC__StreamDecoderErrorStatus status,
161                 __a_unused void *client_data)
162 {
163         PARA_ERROR_LOG("%s\n", FLAC__StreamDecoderErrorStatusString[status]);
164 }
165
166 static int flacdec_init(struct filter_node *fn)
167 {
168         struct private_flacdec_data *pfd = fn->private_data;
169         FLAC__StreamDecoderInitStatus init_status;
170
171         PARA_INFO_LOG("initializing flac decoder\n");
172         pfd->decoder = FLAC__stream_decoder_new();
173         if (!pfd->decoder)
174                 return -E_FLACDEC_DECODER_ALLOC;
175         FLAC__stream_decoder_set_metadata_respond_all(pfd->decoder);
176         init_status = FLAC__stream_decoder_init_stream(pfd->decoder, read_cb,
177                 NULL /* seek */, tell_cb, NULL /* length_cb */, NULL /* eof_cb */,
178                 write_cb, meta_cb, error_cb, fn);
179         if (init_status == FLAC__STREAM_DECODER_INIT_STATUS_OK)
180                 return 1;
181         FLAC__stream_decoder_delete(pfd->decoder);
182         return -E_FLACDEC_DECODER_INIT;
183 }
184
185 static int flacdec_execute(struct btr_node *btrn, const char *cmd,
186                 char **result)
187 {
188         struct filter_node *fn = btr_context(btrn);
189         struct private_flacdec_data *pfd = fn->private_data;
190         unsigned sample_rate = FLAC__stream_decoder_get_sample_rate(pfd->decoder);
191         unsigned channels = FLAC__stream_decoder_get_channels(pfd->decoder);
192
193         return decoder_execute(cmd, sample_rate, channels, result);
194 }
195
196 #define FLACDEC_MAX_OUTPUT_SIZE (640 * 1024)
197
198 static bool output_queue_full(struct btr_node *btrn)
199 {
200         return btr_get_output_queue_size(btrn) > FLACDEC_MAX_OUTPUT_SIZE;
201 }
202
203 static void flacdec_pre_select(struct sched *s, struct task *t)
204 {
205         struct filter_node *fn = container_of(t, struct filter_node, task);
206         struct private_flacdec_data *pfd = fn->private_data;
207         struct btr_node *btrn = fn->btrn;
208         int ret;
209
210         ret = btr_node_status(btrn, fn->min_iqs, BTR_NT_INTERNAL);
211         if (ret < 0)
212                 return sched_min_delay(s);
213         if (output_queue_full(btrn))
214                 return sched_request_timeout_ms(30, s);
215         if (ret > 0 || pfd->have_more)
216                 return sched_min_delay(s);
217 }
218
219 static void flacdec_post_select(__a_unused struct sched *s, struct task *t)
220 {
221         struct filter_node *fn = container_of(t, struct filter_node, task);
222         struct private_flacdec_data *pfd = fn->private_data;
223         struct btr_node *btrn = fn->btrn;
224         int ret;
225
226         if (output_queue_full(btrn))
227                 return;
228         ret = btr_node_status(btrn, fn->min_iqs, BTR_NT_INTERNAL);
229         if (ret < 0 && ret != -E_BTR_EOF) /* fatal error */
230                 goto out;
231         if (ret <= 0 && !pfd->have_more) /* nothing to do */
232                 goto out;
233         if (!pfd->decoder) {
234                 ret = flacdec_init(fn);
235                 goto out;
236         }
237         if (output_queue_full(btrn)) {
238                 pfd->have_more = true;
239                 ret = 1;
240                 goto out;
241         }
242         pfd->have_more = false;
243         FLAC__StreamDecoderState state;
244         FLAC__stream_decoder_process_single(pfd->decoder);
245         state = FLAC__stream_decoder_get_state(pfd->decoder);
246         ret = -E_FLACDEC_EOF;
247         if (state == FLAC__STREAM_DECODER_END_OF_STREAM)
248                 goto out;
249         if (state == FLAC__STREAM_DECODER_ABORTED) {
250                 FLAC__stream_decoder_flush(pfd->decoder);
251                 fn->min_iqs = pfd->unconsumed + 1;
252                 ret = 1;
253                 goto out;
254         }
255         fn->min_iqs = 0;
256         ret = 1;
257 out:
258         t->error = ret;
259         if (ret < 0)
260                 btr_remove_node(&fn->btrn);
261 }
262
263 static void flacdec_close(struct filter_node *fn)
264 {
265         struct private_flacdec_data *pfd;
266
267         if (!fn)
268                 return;
269         pfd = fn->private_data;
270         if (!pfd)
271                 return;
272         if (pfd->decoder) {
273                 FLAC__stream_decoder_finish(pfd->decoder);
274                 FLAC__stream_decoder_delete(pfd->decoder);
275         }
276         free(pfd);
277         fn->private_data = NULL;
278 }
279
280 static void flacdec_open(struct filter_node *fn)
281 {
282         struct private_flacdec_data *pfd = para_calloc(sizeof(*pfd));
283         fn->private_data = pfd;
284         fn->min_iqs = 0;
285 }
286
287 /**
288  * The init function of the flacdec filter.
289  *
290  * \param f Pointer to the filter struct to initialize.
291  *
292  * \sa filter::init.
293  */
294 void flacdec_filter_init(struct filter *f)
295 {
296         f->open = flacdec_open;
297         f->close = flacdec_close;
298         f->pre_select = flacdec_pre_select;
299         f->post_select = flacdec_post_select;
300         f->execute = flacdec_execute;
301 }