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