Consolidate decoder code by introducing prepare_filter_node().
[paraslash.git] / mp3dec_filter.c
1 /*
2  * Copyright (C) 2005-2009 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file mp3dec_filter.c Paraslash's mp3 decoder. */
8
9 #include <mad.h>
10 #include <regex.h>
11 #include <stdbool.h>
12
13 #include "para.h"
14 #include "mp3dec_filter.cmdline.h"
15 #include "list.h"
16 #include "sched.h"
17 #include "ggo.h"
18 #include "buffer_tree.h"
19 #include "filter.h"
20 #include "error.h"
21 #include "string.h"
22
23 /** Convert a sample value from libmad to a signed short. */
24 #define MAD_TO_SHORT(f) (f) >= MAD_F_ONE? SHRT_MAX :\
25         (f) <= -MAD_F_ONE? -SHRT_MAX : (signed short) ((f) >> (MAD_F_FRACBITS - 15))
26
27 /** State of the decoding process. */
28 enum mp3dec_flags {
29         /** Bad main_data_begin pointer encounterd. */
30         MP3DEC_FLAG_BAD_DATA = 1,
31         /** Some output has already been produced. */
32         MP3DEC_FLAG_DECODE_STARTED = 2,
33         MP3DEC_FLAG_NEED_MORE = 4,
34 };
35
36 /** Data specific to the mp3dec filter. */
37 struct private_mp3dec_data {
38         /** Information on the current mp3 stream. */
39         struct mad_stream stream;
40         /** Information about the frame which is currently decoded. */
41         struct mad_frame frame;
42         /** Contains the PCM output. */
43         struct mad_synth synth;
44         /** See \ref mp3dec_flags. */
45         unsigned flags;
46         /** Defer decoding until this time. */
47         struct timeval stream_start_barrier;
48         /** Wait until this many input bytes are available. */
49         size_t input_len_barrier;
50         /** The number of channels of the current stream. */
51         unsigned int channels;
52         /** Current sample rate in Hz. */
53         unsigned int samplerate;
54 };
55
56 static int need_bad_data_delay(struct private_mp3dec_data *pmd,
57                 size_t bytes_available)
58 {
59         if (!(pmd->flags & MP3DEC_FLAG_BAD_DATA))
60                 return 0;
61         if (pmd->flags & MP3DEC_FLAG_DECODE_STARTED)
62                 return 0;
63         if (bytes_available >= pmd->input_len_barrier)
64                 return 0;
65         if (tv_diff(now, &pmd->stream_start_barrier, NULL) > 0)
66                 return 0;
67         return 1;
68 }
69
70 /*
71  * Returns negative on serious errors, zero if the error should be ignored and
72  * positive on bad data pointer errors at stream start.
73  */
74 static int handle_decode_error(struct private_mp3dec_data *pmd, size_t len)
75 {
76         const struct timeval delay = {0, 60 * 1000};
77         if (!MAD_RECOVERABLE(pmd->stream.error)
78                         && pmd->stream.error != MAD_ERROR_BUFLEN) {
79                 PARA_ERROR_LOG("%s\n", mad_stream_errorstr(&pmd->stream));
80                 return -E_MAD_FRAME_DECODE;
81         }
82         PARA_DEBUG_LOG("%s\n", mad_stream_errorstr(&pmd->stream));
83         if (pmd->stream.error != MAD_ERROR_BADDATAPTR)
84                 return 0;
85         if (pmd->flags & MP3DEC_FLAG_DECODE_STARTED)
86                 return 0;
87         /*
88          * Bad data pointer at stream start. Defer decoding until the amount of
89          * data we are about to skip is available again, but wait at most 60ms.
90          */
91         pmd->flags |= MP3DEC_FLAG_BAD_DATA;
92         pmd->input_len_barrier = len;
93         tv_add(now, &delay, &pmd->stream_start_barrier);
94         return 1;
95 }
96
97 /** 640K ought to be enough for everybody ;) */
98 #define MP3DEC_MAX_PENDING (640 * 1024)
99
100 static void mp3dec_pre_select(struct sched *s, struct task *t)
101 {
102         struct filter_node *fn = container_of(t, struct filter_node, task);
103         size_t iqs = btr_get_input_queue_size(fn->btrn);
104         struct private_mp3dec_data *pmd = fn->private_data;
105
106         t->error = 0;
107         if (iqs <= pmd->input_len_barrier)
108                 return;
109         if (btr_bytes_pending(fn->btrn) > MP3DEC_MAX_PENDING)
110                 return; /* FIXME, should use reasonable bound on timeout */
111         s->timeout.tv_sec = 0;
112         s->timeout.tv_usec = 1;
113 }
114
115 static ssize_t mp3dec(char *inbuffer, size_t len, struct filter_node *fn)
116 {
117         int i, ret;
118         struct private_mp3dec_data *pmd = fn->private_data;
119         size_t copy = PARA_MIN(len, (size_t)4096);
120
121         if (fn->loaded + 16384 > fn->bufsize)
122                 return 0;
123         if (need_bad_data_delay(pmd, len))
124                 return 0;
125         mad_stream_buffer(&pmd->stream, (unsigned char *) inbuffer, copy);
126         pmd->stream.error = 0;
127 next_frame:
128         ret = mad_header_decode(&pmd->frame.header, &pmd->stream);
129         if (ret < 0) {
130                 if (pmd->stream.error != MAD_ERROR_BUFLEN &&
131                         pmd->stream.error != MAD_ERROR_LOSTSYNC)
132                         PARA_DEBUG_LOG("header decode: %s\n",
133                                 mad_stream_errorstr(&pmd->stream));
134                 goto out;
135         }
136         fn->fc->samplerate = pmd->frame.header.samplerate;
137         fn->fc->channels = MAD_NCHANNELS(&pmd->frame.header);
138         ret = mad_frame_decode(&pmd->frame, &pmd->stream);
139         if (ret != 0) {
140                 ret = handle_decode_error(pmd, len);
141                 if (ret < 0)
142                         return ret;
143                 if (ret == 0)
144                         goto out;
145                 ret = copy - (pmd->stream.bufend - pmd->stream.next_frame);
146                 PARA_NOTICE_LOG("skipping %d input bytes\n", ret);
147                 return ret;
148         }
149         mad_synth_frame(&pmd->synth, &pmd->frame);
150         pmd->flags |= MP3DEC_FLAG_DECODE_STARTED;
151
152         for (i = 0; i < pmd->synth.pcm.length; i++) {
153                 int s = MAD_TO_SHORT(pmd->synth.pcm.samples[0][i]);
154                 write_int16_host_endian(fn->buf + fn->loaded, s);
155                 fn->loaded += 2;
156                 if (MAD_NCHANNELS(&pmd->frame.header) == 2) { /* stereo */
157                         s = MAD_TO_SHORT(pmd->synth.pcm.samples[1][i]);
158                         write_int16_host_endian(fn->buf + fn->loaded, s);
159                         fn->loaded += 2;
160                 }
161                 if (fn->loaded != fn->bufsize) /* output buffer not full */
162                         continue;
163                 PARA_ERROR_LOG("output buffer full: %zd\n", fn->loaded);
164                         return -E_MP3DEC_OVERRUN;
165         }
166         if (fn->loaded + 16384 <= fn->bufsize)
167                 goto next_frame;
168 out:
169         if (pmd->stream.next_frame) { /* we still have some data */
170                 size_t off = pmd->stream.bufend - pmd->stream.next_frame;
171                 if (fn->loaded + 16384 <= fn->bufsize && off > 2048)
172                         goto next_frame;
173                 return copy - off;
174         }
175         return copy;
176 }
177
178 static size_t used_mad_buffer_bytes(struct mad_stream *s, size_t max)
179 {
180         size_t rv;
181
182         if (!s->next_frame)
183                 return max;
184         /* we still have some data */
185         rv = s->next_frame - s->buffer;
186         assert(rv <= max);
187         return rv;
188 }
189
190 static void mp3dec_close(struct filter_node *fn)
191 {
192         struct private_mp3dec_data *pmd = fn->private_data;
193
194         mad_synth_finish(&pmd->synth);
195         mad_frame_finish(&pmd->frame);
196         mad_stream_finish(&pmd->stream);
197
198         free(fn->buf);
199         fn->buf = NULL;
200         free(pmd);
201         fn->private_data = NULL;
202 }
203
204 static void mp3dec_post_select(__a_unused struct sched *s, struct task *t)
205 {
206         struct filter_node *fn = container_of(t, struct filter_node, task);
207         int i, ret;
208         struct private_mp3dec_data *pmd = fn->private_data;
209         struct btr_node *btrn = fn->btrn;
210         size_t loaded, used, len, iqs;
211         char *inbuffer, *outbuffer;
212
213 next_buffer:
214         pmd->stream.error = 0;
215         t->error = 0;
216         iqs = btr_get_input_queue_size(btrn);
217         if (need_bad_data_delay(pmd, iqs))
218                 return;
219         ret = prepare_filter_node(btrn, pmd->input_len_barrier);
220         if (ret < 0)
221                 goto err;
222         if (ret == 0)
223                 return;
224         len = btr_next_buffer(btrn, &inbuffer);
225         mad_stream_buffer(&pmd->stream, (unsigned char *)inbuffer, len);
226 next_frame:
227         ret = mad_header_decode(&pmd->frame.header, &pmd->stream);
228         if (ret < 0) {
229                 used = used_mad_buffer_bytes(&pmd->stream, len);
230                 btr_consume(btrn, used);
231                 if (pmd->stream.error == MAD_ERROR_BUFLEN) {
232                         if (len == iqs && btr_no_parent(btrn)) {
233                                 ret = -E_MP3DEC_EOF;
234                                 goto err;
235                         }
236                         pmd->input_len_barrier += 100;
237                         goto next_buffer;
238                 } else if (pmd->stream.error != MAD_ERROR_LOSTSYNC)
239                         PARA_DEBUG_LOG("header decode: %s\n",
240                                 mad_stream_errorstr(&pmd->stream));
241                 goto next_buffer;
242         }
243         pmd->input_len_barrier = 0;
244         pmd->samplerate = pmd->frame.header.samplerate;
245         pmd->channels = MAD_NCHANNELS(&pmd->frame.header);
246         ret = mad_frame_decode(&pmd->frame, &pmd->stream);
247         if (ret != 0) {
248                 PARA_CRIT_LOG("frame decode: %d\n", ret);
249                 used = used_mad_buffer_bytes(&pmd->stream, len);
250                 ret = handle_decode_error(pmd, used);
251                 btr_consume(btrn, used);
252                 if (ret < 0)
253                         goto err;
254                 if (ret == 0)
255                         goto next_buffer;
256                 return;
257         }
258         mad_synth_frame(&pmd->synth, &pmd->frame);
259         pmd->flags |= MP3DEC_FLAG_DECODE_STARTED;
260
261         outbuffer = para_malloc(pmd->synth.pcm.length * 4);
262         loaded = 0;
263         for (i = 0; i < pmd->synth.pcm.length; i++) {
264                 int sample = MAD_TO_SHORT(pmd->synth.pcm.samples[0][i]);
265                 write_int16_host_endian(outbuffer + loaded, sample);
266                 loaded += 2;
267                 if (MAD_NCHANNELS(&pmd->frame.header) == 2) { /* stereo */
268                         sample = MAD_TO_SHORT(pmd->synth.pcm.samples[1][i]);
269                         write_int16_host_endian(outbuffer + loaded, sample);
270                         loaded += 2;
271                 }
272         }
273         btr_add_output(outbuffer, loaded, btrn);
274         goto next_frame;
275 err:
276         assert(ret < 0);
277         mp3dec_close(fn);
278         t->error = ret;
279         btr_del_node(btrn);
280 }
281
282 static void mp3dec_open(struct filter_node *fn)
283 {
284         struct private_mp3dec_data *pmd = para_calloc(sizeof(*pmd));
285         struct mp3dec_filter_args_info *mp3_conf = fn->conf;
286
287         fn->private_data = pmd;
288         mad_stream_init(&pmd->stream);
289         mad_frame_init(&pmd->frame);
290         mad_synth_init(&pmd->synth);
291         fn->loaded = 0;
292         fn->bufsize = mp3_conf->bufsize_arg * 1024;
293         fn->buf = para_calloc(fn->bufsize);
294         if (mp3_conf->ignore_crc_given)
295                 mad_stream_options(&pmd->stream, MAD_OPTION_IGNORECRC);
296 }
297
298 static int mp3dec_parse_config(int argc, char **argv, void **config)
299 {
300         int ret;
301         struct mp3dec_filter_args_info *mp3_conf;
302
303         mp3_conf = para_calloc(sizeof(*mp3_conf));
304         ret = -E_MP3DEC_SYNTAX;
305         if (mp3dec_cmdline_parser(argc, argv, mp3_conf))
306                 goto err;
307         ret = -ERRNO_TO_PARA_ERROR(EINVAL);
308         if (mp3_conf->bufsize_arg < 32)
309                 goto err;
310         if (mp3_conf->bufsize_arg >= INT_MAX / 1024)
311                 goto err;
312         *config = mp3_conf;
313         return 1;
314 err:
315         free(mp3_conf);
316         return ret;
317 }
318
319 static int mp3dec_execute(struct btr_node *btrn, const char *cmd, char **result)
320 {
321         struct filter_node *fn = btr_context(btrn);
322         struct private_mp3dec_data *pmd = fn->private_data;
323
324         if (!strcmp(cmd, "samplerate")) {
325                 if (pmd->samplerate == 0)
326                         return -ERRNO_TO_PARA_ERROR(ENAVAIL);
327                 *result = make_message("%u", pmd->samplerate);
328                 return 1;
329         }
330         if (!strcmp(cmd, "channels")) {
331                 if (pmd->channels == 0)
332                         return -ERRNO_TO_PARA_ERROR(ENAVAIL);
333                 *result = make_message("%u", pmd->channels);
334                 return 1;
335         }
336         return -ERRNO_TO_PARA_ERROR(ENOTSUP);
337 }
338 /**
339  * The init function of the mp3dec filter.
340  *
341  * \param f Pointer to the filter struct to initialize.
342  *
343  * \sa filter::init.
344  */
345 void mp3dec_filter_init(struct filter *f)
346 {
347         struct mp3dec_filter_args_info dummy;
348
349         mp3dec_cmdline_parser_init(&dummy);
350         f->open = mp3dec_open;
351         f->convert = mp3dec;
352         f->close = mp3dec_close;
353         f->parse_config = mp3dec_parse_config;
354         f->pre_select = mp3dec_pre_select;
355         f->post_select = mp3dec_post_select;
356         f->execute = mp3dec_execute;
357         f->help = (struct ggo_help) {
358                 .short_help = mp3dec_filter_args_info_help,
359                 .detailed_help = mp3dec_filter_args_info_detailed_help
360         };
361 }