file_write: Fix NULL pointer dereference.
[paraslash.git] / mp3dec_filter.c
index 90293f0..c2c15a3 100644 (file)
@@ -1,25 +1,38 @@
 /*
- * Copyright (C) 2005-2009 Andre Noll <maan@systemlinux.org>
+ * Copyright (C) 2005-2010 Andre Noll <maan@systemlinux.org>
  *
  * Licensed under the GPL v2. For licencing details see COPYING.
  */
 
 /** \file mp3dec_filter.c Paraslash's mp3 decoder. */
 
+#include <mad.h>
+#include <regex.h>
+#include <stdbool.h>
+
 #include "para.h"
 #include "mp3dec_filter.cmdline.h"
 #include "list.h"
 #include "sched.h"
 #include "ggo.h"
+#include "buffer_tree.h"
 #include "filter.h"
 #include "error.h"
-#include <mad.h>
 #include "string.h"
 
 /** Convert a sample value from libmad to a signed short. */
 #define MAD_TO_SHORT(f) (f) >= MAD_F_ONE? SHRT_MAX :\
        (f) <= -MAD_F_ONE? -SHRT_MAX : (signed short) ((f) >> (MAD_F_FRACBITS - 15))
 
+/** State of the decoding process. */
+enum mp3dec_flags {
+       /** Bad main_data_begin pointer encounterd. */
+       MP3DEC_FLAG_BAD_DATA = 1,
+       /** Some output has already been produced. */
+       MP3DEC_FLAG_DECODE_STARTED = 2,
+       MP3DEC_FLAG_NEED_MORE = 4,
+};
+
 /** Data specific to the mp3dec filter. */
 struct private_mp3dec_data {
        /** Information on the current mp3 stream. */
@@ -28,81 +41,165 @@ struct private_mp3dec_data {
        struct mad_frame frame;
        /** Contains the PCM output. */
        struct mad_synth synth;
+       /** See \ref mp3dec_flags. */
+       unsigned flags;
+       /** Defer decoding until this time. */
+       struct timeval stream_start_barrier;
+       /** Wait until this many input bytes are available. */
+       size_t input_len_barrier;
+       /** The number of channels of the current stream. */
+       unsigned int channels;
+       /** Current sample rate in Hz. */
+       unsigned int sample_rate;
 };
 
-static ssize_t mp3dec(char *inbuffer, size_t len, struct filter_node *fn)
+static int need_bad_data_delay(struct private_mp3dec_data *pmd,
+               size_t bytes_available)
+{
+       if (!(pmd->flags & MP3DEC_FLAG_BAD_DATA))
+               return 0;
+       if (pmd->flags & MP3DEC_FLAG_DECODE_STARTED)
+               return 0;
+       if (bytes_available >= pmd->input_len_barrier)
+               return 0;
+       if (tv_diff(now, &pmd->stream_start_barrier, NULL) > 0)
+               return 0;
+       return 1;
+}
+
+/*
+ * Returns negative on serious errors, zero if the error should be ignored and
+ * positive on bad data pointer errors at stream start.
+ */
+static int handle_decode_error(struct private_mp3dec_data *pmd, size_t len)
+{
+       const struct timeval delay = {0, 60 * 1000};
+       if (!MAD_RECOVERABLE(pmd->stream.error)
+                       && pmd->stream.error != MAD_ERROR_BUFLEN) {
+               PARA_ERROR_LOG("%s\n", mad_stream_errorstr(&pmd->stream));
+               return -E_MAD_FRAME_DECODE;
+       }
+       PARA_DEBUG_LOG("%s\n", mad_stream_errorstr(&pmd->stream));
+       if (pmd->stream.error != MAD_ERROR_BADDATAPTR)
+               return 0;
+       if (pmd->flags & MP3DEC_FLAG_DECODE_STARTED)
+               return 0;
+       /*
+        * Bad data pointer at stream start. Defer decoding until the amount of
+        * data we are about to skip is available again, but wait at most 60ms.
+        */
+       pmd->flags |= MP3DEC_FLAG_BAD_DATA;
+       pmd->input_len_barrier = len;
+       tv_add(now, &delay, &pmd->stream_start_barrier);
+       return 1;
+}
+
+static size_t used_mad_buffer_bytes(struct mad_stream *s, size_t max)
 {
+       size_t rv;
+
+       if (!s->next_frame)
+               return max;
+       /* we still have some data */
+       rv = s->next_frame - s->buffer;
+       assert(rv <= max);
+       return rv;
+}
+
+static void mp3dec_close(struct filter_node *fn)
+{
+       struct private_mp3dec_data *pmd = fn->private_data;
+
+       mad_synth_finish(&pmd->synth);
+       mad_frame_finish(&pmd->frame);
+       mad_stream_finish(&pmd->stream);
+
+       free(pmd);
+       fn->private_data = NULL;
+}
+
+static void 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;
-       size_t copy = PARA_MIN(len, (size_t)4096);
+       struct btr_node *btrn = fn->btrn;
+       size_t loaded, used, len, iqs;
+       char *inbuffer, *outbuffer;
 
-       if (fn->loaded + 16384 > fn->bufsize)
-               return 0;
-       mad_stream_buffer(&pmd->stream, (unsigned char *) inbuffer, copy);
+next_buffer:
        pmd->stream.error = 0;
+       t->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 (need_bad_data_delay(pmd, iqs))
+               return;
+       if (ret == 0)
+               return;
+       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)8192);
+       mad_stream_buffer(&pmd->stream, (unsigned char *)inbuffer, len);
 next_frame:
        ret = mad_header_decode(&pmd->frame.header, &pmd->stream);
        if (ret < 0) {
-               if (pmd->stream.error != MAD_ERROR_BUFLEN &&
-                       pmd->stream.error != MAD_ERROR_LOSTSYNC)
+               used = used_mad_buffer_bytes(&pmd->stream, len);
+               btr_consume(btrn, used);
+               if (pmd->stream.error == MAD_ERROR_BUFLEN) {
+                       if (len == iqs && btr_no_parent(btrn)) {
+                               ret = -E_MP3DEC_EOF;
+                               goto err;
+                       }
+                       fn->min_iqs += 100;
+                       goto next_buffer;
+               } else if (pmd->stream.error != MAD_ERROR_LOSTSYNC)
                        PARA_DEBUG_LOG("header decode: %s\n",
                                mad_stream_errorstr(&pmd->stream));
-               goto out;
+               goto next_buffer;
        }
-       fn->fc->samplerate = pmd->frame.header.samplerate;
-       fn->fc->channels = MAD_NCHANNELS(&pmd->frame.header);
+       fn->min_iqs = 0;
+       pmd->sample_rate = pmd->frame.header.samplerate;
+       pmd->channels = MAD_NCHANNELS(&pmd->frame.header);
        ret = mad_frame_decode(&pmd->frame, &pmd->stream);
-       if (ret) {
-               if (MAD_RECOVERABLE(pmd->stream.error) ||
-                       pmd->stream.error == MAD_ERROR_BUFLEN) {
-                       PARA_DEBUG_LOG("frame decode: %s\n",
-                               mad_stream_errorstr(&pmd->stream));
-                       goto out;
-               }
-               PARA_ERROR_LOG("frame decode: %s\n",
-                       mad_stream_errorstr(&pmd->stream));
-               return -E_MAD_FRAME_DECODE;
+       if (ret != 0) {
+               PARA_INFO_LOG("frame decode: %s\n", mad_stream_errorstr(&pmd->stream));
+               used = used_mad_buffer_bytes(&pmd->stream, len);
+               ret = handle_decode_error(pmd, used);
+               btr_consume(btrn, used);
+               if (ret < 0)
+                       goto err;
+               if (ret == 0)
+                       goto next_buffer;
+               return;
        }
        mad_synth_frame(&pmd->synth, &pmd->frame);
+       pmd->flags |= MP3DEC_FLAG_DECODE_STARTED;
 
+       outbuffer = para_malloc(pmd->synth.pcm.length * 4);
+       loaded = 0;
        for (i = 0; i < pmd->synth.pcm.length; i++) {
-               int s = MAD_TO_SHORT(pmd->synth.pcm.samples[0][i]);
-               write_int16_host_endian(fn->buf + fn->loaded, s);
-               fn->loaded += 2;
+               int sample = MAD_TO_SHORT(pmd->synth.pcm.samples[0][i]);
+               write_int16_host_endian(outbuffer + loaded, sample);
+               loaded += 2;
                if (MAD_NCHANNELS(&pmd->frame.header) == 2) { /* stereo */
-                       s = MAD_TO_SHORT(pmd->synth.pcm.samples[1][i]);
-                       write_int16_host_endian(fn->buf + fn->loaded, s);
-                       fn->loaded += 2;
+                       sample = MAD_TO_SHORT(pmd->synth.pcm.samples[1][i]);
+                       write_int16_host_endian(outbuffer + loaded, sample);
+                       loaded += 2;
                }
-               if (fn->loaded != fn->bufsize) /* output buffer not full */
-                       continue;
-               PARA_ERROR_LOG("output buffer full: %zd\n", fn->loaded);
-                       return -E_MP3DEC_OVERRUN;
-       }
-       if (fn->loaded + 16384 <= fn->bufsize)
-               goto next_frame;
-out:
-       if (pmd->stream.next_frame) { /* we still have some data */
-               size_t off = pmd->stream.bufend - pmd->stream.next_frame;
-//             PARA_INFO_LOG("off: %zd, rate: %u, returning %zd\n", off,
-//                     fn->fc->samplerate, copy - off);
-               return copy - off;
        }
-       return copy;
-}
-
-static void mp3dec_close(struct filter_node *fn)
-{
-       struct private_mp3dec_data *pmd = fn->private_data;
-
-       mad_synth_finish(&pmd->synth);
-       mad_frame_finish(&pmd->frame);
-       mad_stream_finish(&pmd->stream);
-
-       free(fn->buf);
-       fn->buf = NULL;
-       free(pmd);
-       fn->private_data = NULL;
+       btr_add_output(outbuffer, loaded, btrn);
+       goto next_frame;
+err:
+       assert(ret < 0);
+       t->error = ret;
+       btr_remove_node(btrn);
 }
 
 static void mp3dec_open(struct filter_node *fn)
@@ -114,9 +211,6 @@ static void mp3dec_open(struct filter_node *fn)
        mad_stream_init(&pmd->stream);
        mad_frame_init(&pmd->frame);
        mad_synth_init(&pmd->synth);
-       fn->loaded = 0;
-       fn->bufsize = mp3_conf->bufsize_arg * 1024;
-       fn->buf = para_calloc(fn->bufsize);
        if (mp3_conf->ignore_crc_given)
                mad_stream_options(&pmd->stream, MAD_OPTION_IGNORECRC);
 }
@@ -130,11 +224,6 @@ static int mp3dec_parse_config(int argc, char **argv, void **config)
        ret = -E_MP3DEC_SYNTAX;
        if (mp3dec_cmdline_parser(argc, argv, mp3_conf))
                goto err;
-       ret = -ERRNO_TO_PARA_ERROR(EINVAL);
-       if (mp3_conf->bufsize_arg < 32)
-               goto err;
-       if (mp3_conf->bufsize_arg >= INT_MAX / 1024)
-               goto err;
        *config = mp3_conf;
        return 1;
 err:
@@ -142,6 +231,18 @@ err:
        return ret;
 }
 
+static int mp3dec_execute(struct btr_node *btrn, const char *cmd, char **result)
+{
+       struct filter_node *fn = btr_context(btrn);
+       struct private_mp3dec_data *pmd = fn->private_data;
+
+       return decoder_execute(cmd, pmd->sample_rate, pmd->channels, result);
+}
+
+static void mp3dec_free_config(void *conf)
+{
+       mp3dec_cmdline_parser_free(conf);
+}
 /**
  * The init function of the mp3dec filter.
  *
@@ -155,9 +256,12 @@ void mp3dec_filter_init(struct filter *f)
 
        mp3dec_cmdline_parser_init(&dummy);
        f->open = mp3dec_open;
-       f->convert = mp3dec;
        f->close = mp3dec_close;
        f->parse_config = mp3dec_parse_config;
+       f->free_config = mp3dec_free_config;
+       f->pre_select = generic_filter_pre_select;
+       f->post_select = mp3dec_post_select;
+       f->execute = mp3dec_execute;
        f->help = (struct ggo_help) {
                .short_help = mp3dec_filter_args_info_help,
                .detailed_help = mp3dec_filter_args_info_detailed_help