Introduce filter_node->min_iqs.
[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
105 t->error = 0;
106 if (iqs <= fn->min_iqs)
107 return;
108 if (btr_bytes_pending(fn->btrn) > MP3DEC_MAX_PENDING)
109 return; /* FIXME, should use reasonable bound on timeout */
110 s->timeout.tv_sec = 0;
111 s->timeout.tv_usec = 1;
112 }
113
114 static ssize_t mp3dec(char *inbuffer, size_t len, struct filter_node *fn)
115 {
116 int i, ret;
117 struct private_mp3dec_data *pmd = fn->private_data;
118 size_t copy = PARA_MIN(len, (size_t)4096);
119
120 if (fn->loaded + 16384 > fn->bufsize)
121 return 0;
122 if (need_bad_data_delay(pmd, len))
123 return 0;
124 mad_stream_buffer(&pmd->stream, (unsigned char *) inbuffer, copy);
125 pmd->stream.error = 0;
126 next_frame:
127 ret = mad_header_decode(&pmd->frame.header, &pmd->stream);
128 if (ret < 0) {
129 if (pmd->stream.error != MAD_ERROR_BUFLEN &&
130 pmd->stream.error != MAD_ERROR_LOSTSYNC)
131 PARA_DEBUG_LOG("header decode: %s\n",
132 mad_stream_errorstr(&pmd->stream));
133 goto out;
134 }
135 fn->fc->samplerate = pmd->frame.header.samplerate;
136 fn->fc->channels = MAD_NCHANNELS(&pmd->frame.header);
137 ret = mad_frame_decode(&pmd->frame, &pmd->stream);
138 if (ret != 0) {
139 ret = handle_decode_error(pmd, len);
140 if (ret < 0)
141 return ret;
142 if (ret == 0)
143 goto out;
144 ret = copy - (pmd->stream.bufend - pmd->stream.next_frame);
145 PARA_NOTICE_LOG("skipping %d input bytes\n", ret);
146 return ret;
147 }
148 mad_synth_frame(&pmd->synth, &pmd->frame);
149 pmd->flags |= MP3DEC_FLAG_DECODE_STARTED;
150
151 for (i = 0; i < pmd->synth.pcm.length; i++) {
152 int s = MAD_TO_SHORT(pmd->synth.pcm.samples[0][i]);
153 write_int16_host_endian(fn->buf + fn->loaded, s);
154 fn->loaded += 2;
155 if (MAD_NCHANNELS(&pmd->frame.header) == 2) { /* stereo */
156 s = MAD_TO_SHORT(pmd->synth.pcm.samples[1][i]);
157 write_int16_host_endian(fn->buf + fn->loaded, s);
158 fn->loaded += 2;
159 }
160 if (fn->loaded != fn->bufsize) /* output buffer not full */
161 continue;
162 PARA_ERROR_LOG("output buffer full: %zd\n", fn->loaded);
163 return -E_MP3DEC_OVERRUN;
164 }
165 if (fn->loaded + 16384 <= fn->bufsize)
166 goto next_frame;
167 out:
168 if (pmd->stream.next_frame) { /* we still have some data */
169 size_t off = pmd->stream.bufend - pmd->stream.next_frame;
170 if (fn->loaded + 16384 <= fn->bufsize && off > 2048)
171 goto next_frame;
172 return copy - off;
173 }
174 return copy;
175 }
176
177 static size_t used_mad_buffer_bytes(struct mad_stream *s, size_t max)
178 {
179 size_t rv;
180
181 if (!s->next_frame)
182 return max;
183 /* we still have some data */
184 rv = s->next_frame - s->buffer;
185 assert(rv <= max);
186 return rv;
187 }
188
189 static void mp3dec_close(struct filter_node *fn)
190 {
191 struct private_mp3dec_data *pmd = fn->private_data;
192
193 mad_synth_finish(&pmd->synth);
194 mad_frame_finish(&pmd->frame);
195 mad_stream_finish(&pmd->stream);
196
197 free(fn->buf);
198 fn->buf = NULL;
199 free(pmd);
200 fn->private_data = NULL;
201 }
202
203 static void mp3dec_post_select(__a_unused struct sched *s, struct task *t)
204 {
205 struct filter_node *fn = container_of(t, struct filter_node, task);
206 int i, ret;
207 struct private_mp3dec_data *pmd = fn->private_data;
208 struct btr_node *btrn = fn->btrn;
209 size_t loaded, used, len, iqs;
210 char *inbuffer, *outbuffer;
211
212 next_buffer:
213 pmd->stream.error = 0;
214 t->error = 0;
215 iqs = btr_get_input_queue_size(btrn);
216 if (need_bad_data_delay(pmd, iqs))
217 return;
218 ret = prepare_filter_node(btrn, fn->min_iqs);
219 if (ret < 0)
220 goto err;
221 if (ret == 0)
222 return;
223 len = btr_next_buffer(btrn, &inbuffer);
224 mad_stream_buffer(&pmd->stream, (unsigned char *)inbuffer, len);
225 next_frame:
226 ret = mad_header_decode(&pmd->frame.header, &pmd->stream);
227 if (ret < 0) {
228 used = used_mad_buffer_bytes(&pmd->stream, len);
229 btr_consume(btrn, used);
230 if (pmd->stream.error == MAD_ERROR_BUFLEN) {
231 if (len == iqs && btr_no_parent(btrn)) {
232 ret = -E_MP3DEC_EOF;
233 goto err;
234 }
235 fn->min_iqs += 100;
236 goto next_buffer;
237 } else if (pmd->stream.error != MAD_ERROR_LOSTSYNC)
238 PARA_DEBUG_LOG("header decode: %s\n",
239 mad_stream_errorstr(&pmd->stream));
240 goto next_buffer;
241 }
242 fn->min_iqs = 0;
243 pmd->samplerate = pmd->frame.header.samplerate;
244 pmd->channels = MAD_NCHANNELS(&pmd->frame.header);
245 ret = mad_frame_decode(&pmd->frame, &pmd->stream);
246 if (ret != 0) {
247 PARA_CRIT_LOG("frame decode: %d\n", ret);
248 used = used_mad_buffer_bytes(&pmd->stream, len);
249 ret = handle_decode_error(pmd, used);
250 btr_consume(btrn, used);
251 if (ret < 0)
252 goto err;
253 if (ret == 0)
254 goto next_buffer;
255 return;
256 }
257 mad_synth_frame(&pmd->synth, &pmd->frame);
258 pmd->flags |= MP3DEC_FLAG_DECODE_STARTED;
259
260 outbuffer = para_malloc(pmd->synth.pcm.length * 4);
261 loaded = 0;
262 for (i = 0; i < pmd->synth.pcm.length; i++) {
263 int sample = MAD_TO_SHORT(pmd->synth.pcm.samples[0][i]);
264 write_int16_host_endian(outbuffer + loaded, sample);
265 loaded += 2;
266 if (MAD_NCHANNELS(&pmd->frame.header) == 2) { /* stereo */
267 sample = MAD_TO_SHORT(pmd->synth.pcm.samples[1][i]);
268 write_int16_host_endian(outbuffer + loaded, sample);
269 loaded += 2;
270 }
271 }
272 btr_add_output(outbuffer, loaded, btrn);
273 goto next_frame;
274 err:
275 assert(ret < 0);
276 mp3dec_close(fn);
277 t->error = ret;
278 btr_del_node(btrn);
279 }
280
281 static void mp3dec_open(struct filter_node *fn)
282 {
283 struct private_mp3dec_data *pmd = para_calloc(sizeof(*pmd));
284 struct mp3dec_filter_args_info *mp3_conf = fn->conf;
285
286 fn->private_data = pmd;
287 mad_stream_init(&pmd->stream);
288 mad_frame_init(&pmd->frame);
289 mad_synth_init(&pmd->synth);
290 fn->loaded = 0;
291 fn->bufsize = mp3_conf->bufsize_arg * 1024;
292 fn->buf = para_calloc(fn->bufsize);
293 if (mp3_conf->ignore_crc_given)
294 mad_stream_options(&pmd->stream, MAD_OPTION_IGNORECRC);
295 }
296
297 static int mp3dec_parse_config(int argc, char **argv, void **config)
298 {
299 int ret;
300 struct mp3dec_filter_args_info *mp3_conf;
301
302 mp3_conf = para_calloc(sizeof(*mp3_conf));
303 ret = -E_MP3DEC_SYNTAX;
304 if (mp3dec_cmdline_parser(argc, argv, mp3_conf))
305 goto err;
306 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
307 if (mp3_conf->bufsize_arg < 32)
308 goto err;
309 if (mp3_conf->bufsize_arg >= INT_MAX / 1024)
310 goto err;
311 *config = mp3_conf;
312 return 1;
313 err:
314 free(mp3_conf);
315 return ret;
316 }
317
318 static int mp3dec_execute(struct btr_node *btrn, const char *cmd, char **result)
319 {
320 struct filter_node *fn = btr_context(btrn);
321 struct private_mp3dec_data *pmd = fn->private_data;
322
323 if (!strcmp(cmd, "samplerate")) {
324 if (pmd->samplerate == 0)
325 return -ERRNO_TO_PARA_ERROR(ENAVAIL);
326 *result = make_message("%u", pmd->samplerate);
327 return 1;
328 }
329 if (!strcmp(cmd, "channels")) {
330 if (pmd->channels == 0)
331 return -ERRNO_TO_PARA_ERROR(ENAVAIL);
332 *result = make_message("%u", pmd->channels);
333 return 1;
334 }
335 return -ERRNO_TO_PARA_ERROR(ENOTSUP);
336 }
337 /**
338 * The init function of the mp3dec filter.
339 *
340 * \param f Pointer to the filter struct to initialize.
341 *
342 * \sa filter::init.
343 */
344 void mp3dec_filter_init(struct filter *f)
345 {
346 struct mp3dec_filter_args_info dummy;
347
348 mp3dec_cmdline_parser_init(&dummy);
349 f->open = mp3dec_open;
350 f->convert = mp3dec;
351 f->close = mp3dec_close;
352 f->parse_config = mp3dec_parse_config;
353 f->pre_select = mp3dec_pre_select;
354 f->post_select = mp3dec_post_select;
355 f->execute = mp3dec_execute;
356 f->help = (struct ggo_help) {
357 .short_help = mp3dec_filter_args_info_help,
358 .detailed_help = mp3dec_filter_args_info_detailed_help
359 };
360 }