+#define MP3DEC_MAX_FRAME 8192
+
+static int mp3dec_post_select(__a_unused struct sched *s, struct task *t)
+{
+ struct filter_node *fn = container_of(t, struct filter_node, task);
+ int i, ret;
+ struct private_mp3dec_data *pmd = fn->private_data;
+ struct btr_node *btrn = fn->btrn;
+ size_t loaded = 0, len, iqs;
+ char *inbuffer, *outbuffer;
+
+next_buffer:
+ pmd->stream.error = 0;
+ iqs = btr_get_input_queue_size(btrn);
+ ret = btr_node_status(btrn, fn->min_iqs, BTR_NT_INTERNAL);
+ if (ret < 0)
+ goto err;
+ if (ret == 0)
+ return 0;
+ btr_merge(btrn, fn->min_iqs);
+ len = btr_next_buffer(btrn, &inbuffer);
+ /*
+ * Decode at most 8K in one go to give the post_select() functions of
+ * other buffer tree nodes a chance to run. This is necessary to avoid
+ * buffer underruns on slow machines.
+ */
+ len = PARA_MIN(len, (size_t)MP3DEC_MAX_FRAME);
+ mad_stream_buffer(&pmd->stream, (unsigned char *)inbuffer, len);
+next_frame:
+ ret = mad_header_decode(&pmd->frame.header, &pmd->stream);
+ if (ret < 0) {
+ mp3dec_consume(btrn, &pmd->stream, len);
+ if (pmd->stream.error == MAD_ERROR_BUFLEN) {
+ if (len == iqs && btr_no_parent(btrn)) {
+ ret = -E_MP3DEC_EOF;
+ goto err;
+ }
+ fn->min_iqs += 100;
+ ret = -E_MP3DEC_CORRUPT;
+ if (fn->min_iqs > MP3DEC_MAX_FRAME)
+ goto err;
+ }
+ if (loaded == 0)
+ goto next_buffer;
+ return 0;
+ }
+ pmd->sample_rate = pmd->frame.header.samplerate;
+ pmd->channels = MAD_NCHANNELS(&pmd->frame.header);
+decode:
+ ret = mad_frame_decode(&pmd->frame, &pmd->stream);
+ if (ret != 0) {
+ ret = handle_decode_error(pmd);
+ if (ret < 0)
+ goto err;
+ mad_stream_sync(&pmd->stream);
+ if (pmd->stream.error == MAD_ERROR_BUFLEN) {
+ ret = -E_MP3DEC_EOF;
+ if (len == iqs && btr_no_parent(btrn))
+ goto err;
+ fn->min_iqs += 100;
+ ret = -E_MP3DEC_CORRUPT;
+ if (fn->min_iqs > MP3DEC_MAX_FRAME)
+ goto err;
+ mp3dec_consume(btrn, &pmd->stream, len);
+ return 0;
+ }
+ if (pmd->stream.error != MAD_ERROR_BADDATAPTR)
+ goto decode;
+ mp3dec_consume(btrn, &pmd->stream, len);
+ return 0;
+ }
+ fn->min_iqs = 0;
+ mad_synth_frame(&pmd->synth, &pmd->frame);
+ outbuffer = para_malloc(pmd->synth.pcm.length * 2 * pmd->channels);
+ loaded = 0;
+ for (i = 0; i < pmd->synth.pcm.length; i++) {
+ int sample = MAD_TO_SHORT(pmd->synth.pcm.samples[0][i]);
+ write_int16_host_endian(outbuffer + loaded, sample);
+ loaded += 2;
+ if (pmd->channels == 2) { /* stereo */
+ sample = MAD_TO_SHORT(pmd->synth.pcm.samples[1][i]);
+ write_int16_host_endian(outbuffer + loaded, sample);
+ loaded += 2;
+ }
+ }
+ btr_add_output(outbuffer, loaded, btrn);
+ goto next_frame;
+err:
+ assert(ret < 0);
+ btr_remove_node(&fn->btrn);
+ return ret;
+}
+