Add btr support to the oggdec filter.
[paraslash.git] / write.c
diff --git a/write.c b/write.c
index 79aaef3112931579fca863dd4484e1dc460817f1..def31334e5f89c0efc46055b8b28171a6107f614 100644 (file)
--- a/write.c
+++ b/write.c
 /*
- * Copyright (C) 2005-2006 Andre Noll <maan@systemlinux.org>
+ * Copyright (C) 2005-2009 Andre Noll <maan@systemlinux.org>
  *
- *     This program is free software; you can redistribute it and/or modify
- *     it under the terms of the GNU General Public License as published by
- *     the Free Software Foundation; either version 2 of the License, or
- *     (at your option) any later version.
- *
- *     This program is distributed in the hope that it will be useful,
- *     but WITHOUT ANY WARRANTY; without even the implied warranty of
- *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *     GNU General Public License for more details.
- *
- *     You should have received a copy of the GNU General Public License
- *     along with this program; if not, write to the Free Software
- *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
+ * Licensed under the GPL v2. For licencing details see COPYING.
  */
 
+/** \file write.c Paraslash's standalone wav/raw player. */
+
+#include <regex.h>
+#include <sys/types.h>
+#include <dirent.h>
+#include <stdbool.h>
+
 #include "para.h"
 #include "string.h"
 #include "write.cmdline.h"
+#include "list.h"
+#include "sched.h"
+#include "ggo.h"
+#include "stdin.h"
+#include "buffer_tree.h"
 #include "write.h"
 #include "write_common.h"
 #include "fd.h"
+#include "error.h"
 
-#include <sys/time.h> /* gettimeofday */
+INIT_WRITE_ERRLISTS;
 
-#include "error.h"
+/** Check if given buffer contains a valid wave header. */
+struct check_wav_task {
+       /** The buffer to check. */
+       char *buf;
+       /** Number of bytes loaded in \a buf. */
+       size_t *loaded;
+       /** Non-zero if an error occurred or end of file was reached. */
+       int *input_error;
+       /** Number of channels specified in wav header given by \a buf. */
+       unsigned channels;
+       /** Sample rate specified in wav header given by \a buf. */
+       unsigned samplerate;
+       /** The task structure used by the scheduler. */
+       struct task task;
+};
 
-#define WAV_HEADER_LEN 44
+enum check_wav_state {
+       CWS_NEED_HEADER,
+       CWS_HAVE_HEADER,
+       CWS_NO_HEADER,
+};
 
-static unsigned char *audiobuf;
-static struct timeval *start_time;
-struct gengetopt_args_info conf;
+struct check_wav_task_btr {
+       int state;
+       /** Number of channels specified in wav header given by \a buf. */
+       unsigned channels;
+       /** Sample rate specified in wav header given by \a buf. */
+       unsigned samplerate;
+       /** The task structure used by the scheduler. */
+       struct task task;
+       struct btr_node *btrn;
+};
 
-INIT_WRITE_ERRLISTS;
+/** Delay writing until given time. */
+struct initial_delay_task {
+       /** The time the first data should be written out. */
+       struct timeval start_time;
+       /** The task structure for this task. */
+       struct task task;
+};
 
-void para_log(int ll, const char* fmt,...)
-{
-       va_list argp;
+static struct write_args_info conf;
 
-       if (ll < conf.loglevel_arg)
-               return;
-       va_start(argp, fmt);
-       vfprintf(stderr, fmt, argp);
-       va_end(argp);
-}
+static struct stdin_task sit;
+
+static struct check_wav_task the_check_wav_task;
+static struct initial_delay_task the_initial_delay_task;
+
+static struct writer_node_group *wng;
+
+/** Length of a standard wav header. */
+#define WAV_HEADER_LEN 44
 
 /**
- * read WAV_HEADER_LEN bytes from stdin to audio buffer
+ * Test if audio buffer contains a valid wave header.
  *
- * \return -E_READ_HDR on errors and on eof before WAV_HEADER_LEN could be
- * read. A positive return value indicates success.
+ * \return If not, return -E_NO_WAV_HEADER, otherwise, return zero. If
+ * there is less than WAV_HEADER_LEN bytes available, return one.
  */
-static int read_wav_header(void)
+static void check_wav_pre_select(__a_unused struct sched *s, struct task *t)
 {
-       ssize_t ret, count = 0;
+       struct check_wav_task *cwt = container_of(t, struct check_wav_task, task);
+       unsigned char *a;
+       int ret;
 
-       while (count < WAV_HEADER_LEN) {
-               ret = read(STDIN_FILENO, audiobuf + count, WAV_HEADER_LEN - count);
-               if (ret <= 0)
-                       return -E_READ_HDR;
-               count += ret;
+       if (*cwt->loaded < WAV_HEADER_LEN) {
+               if (*cwt->input_error < 0)
+                       t->error = *cwt->input_error;
+               return;
+       }
+       cwt->channels = 2;
+       cwt->samplerate = 44100;
+       a = (unsigned char*)cwt->buf;
+       if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F') {
+               PARA_NOTICE_LOG("wav header not found\n");
+               t->error = -E_NO_WAV_HEADER;
+               goto out;
        }
-       return 1;
+       cwt->channels = (unsigned) a[22];
+       cwt->samplerate = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
+       *cwt->loaded -= WAV_HEADER_LEN;
+       memmove(cwt->buf, cwt->buf + WAV_HEADER_LEN, *cwt->loaded);
+       t->error = -E_WAV_HEADER_SUCCESS;
+       PARA_INFO_LOG("channels: %d, sample rate: %d\n", cwt->channels, cwt->samplerate);
+out:
+       wng->channels = &cwt->channels;
+       wng->samplerate = &cwt->samplerate;
+       ret = wng_open(wng);
+       if (ret < 0)
+               t->error = ret;
+       s->timeout.tv_sec = 0;
+       s->timeout.tv_usec = 1;
 }
 
-/**
- * check if current time is later than start_time
- * \param diff pointer to write remaining time to
- *
- * If start_time was not given, or current time is later than given
- * start_time, return 0. Otherwise, return 1 and write the time
- * difference between current time and start_time to diff. diff may be
- * NULL.
- *
- */
-static int start_time_in_future(struct timeval *diff)
+static void check_wav_pre_select_btr(__a_unused struct sched *s, struct task *t)
 {
-       struct timeval now;
+       struct check_wav_task_btr *cwt = container_of(t, struct check_wav_task_btr, task);
 
-       if (!conf.start_time_given)
-               return 0;
-       gettimeofday(&now, NULL);
-       return tv_diff(start_time, &now, diff) > 0? 1 : 0;
+       if (btr_get_input_queue_size(cwt->btrn) < WAV_HEADER_LEN)
+               return;
+       s->timeout.tv_sec = 0;
+       s->timeout.tv_usec = 1;
 }
 
-/**
- * sleep until time given at command line
- *
- * This is called if the initial buffer is filled. It returns
- * immediately if no start_time was given at the command line
- * or if the given start time is in the past.
- *
- */
-static void do_initial_delay(struct timeval *delay)
+static int check_wav_exec(struct btr_node *btrn, const char *cmd, char **result)
 {
-       do
-               para_select(1, NULL, NULL, delay);
-       while (start_time_in_future(delay));
+       struct check_wav_task_btr *cwt = btr_context(btrn);
+
+       if (!strcmp(cmd, "samplerate")) {
+               if (cwt->state != CWS_HAVE_HEADER)
+                       return -ERRNO_TO_PARA_ERROR(ENAVAIL);
+               *result = make_message("%d", cwt->samplerate);
+               return 1;
+       }
+       if (!strcmp(cmd, "channels")) {
+               if (cwt->state != CWS_HAVE_HEADER)
+                       return -ERRNO_TO_PARA_ERROR(ENAVAIL);
+               *result = make_message("%d", cwt->samplerate);
+               return 1;
+       }
+       return -ERRNO_TO_PARA_ERROR(ENOTSUP);
 }
 
-static int read_stdin(char *buf, size_t bytes_to_load, size_t *loaded)
+static void check_wav_post_select_btr(__a_unused struct sched *s, struct task *t)
 {
-       ssize_t ret;
-
-       while (*loaded < bytes_to_load) {
-               ret = read(STDIN_FILENO, buf + *loaded, bytes_to_load - *loaded);
-               if (ret <= 0) {
-                       if (ret < 0)
-                               ret = -E_READ_STDIN;
-                       return ret;
+       struct check_wav_task_btr *cwt = container_of(t, struct check_wav_task_btr, task);
+       unsigned char *a;
+       size_t sz = btr_get_input_queue_size(cwt->btrn);
+
+       t->error = 0;
+       if (cwt->state != CWS_NEED_HEADER)
+               goto out;
+       if (sz < WAV_HEADER_LEN) {
+               if (!btr_no_parent(cwt->btrn))
+                       return;
+               if (sz != 0) {
+                       cwt->state = CWS_NO_HEADER;
+                       goto out;
                }
-               *loaded += ret;
+               t->error = -E_WRITE_EOF;
+               goto err;
+       }
+       cwt->channels = 2;
+       cwt->samplerate = 44100;
+       btr_next_buffer(cwt->btrn, (char **)&a);
+       if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F') {
+               PARA_NOTICE_LOG("wav header not found\n");
+               cwt->state = CWS_NO_HEADER;
+               sprintf(t->status, "check wav: no header");
+               goto consume;
        }
-       return 1;
+       PARA_INFO_LOG("found wav header\n");
+       cwt->state = CWS_HAVE_HEADER;
+       sprintf(t->status, "check wav: have header");
+       cwt->channels = (unsigned) a[22];
+       cwt->samplerate = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
+consume:
+       PARA_INFO_LOG("channels: %d, sample rate: %d\n", cwt->channels, cwt->samplerate);
+       btr_consume(cwt->btrn, WAV_HEADER_LEN);
+out:
+       if (sz) {
+               btr_pushdown(cwt->btrn);
+               s->timeout.tv_sec = 0;
+               s->timeout.tv_usec = 1;
+       } else {
+               if (btr_no_parent(cwt->btrn))
+                       t->error = -E_WRITE_EOF;
+       }
+err:
+       if (t->error < 0)
+               btr_del_node(cwt->btrn);
 }
-/**
- * play raw pcm data
- * \param loaded number of bytes already loaded
- *
- * If start_time was given, prebuffer data until buffer is full or
- * start_time is reached. In any case, do not start playing before
- * start_time.
- *
- * \return positive on success, negative on errors.
- */
-static int pcm_write(struct writer_node_group *wng, size_t loaded)
+
+static void initial_delay_pre_select(struct sched *s, struct task *t)
 {
-       size_t bufsize, prebuf_size, bytes_to_load;
-       struct timeval delay;
-       int ret, not_yet_started = 1;
+       struct initial_delay_task *idt = container_of(t, struct initial_delay_task, task);
+       struct timeval diff;
 
-       ret = wng_open(wng);
-       if (ret < 0)
-               goto out;
-       PARA_INFO_LOG("max chunk_bytes: %d\n", wng->max_chunk_bytes);
-       bufsize = (conf.bufsize_arg * 1024 / wng->max_chunk_bytes)
-               * wng->max_chunk_bytes;
-       audiobuf = para_realloc(audiobuf, bufsize);
-       prebuf_size = conf.prebuffer_arg * bufsize / 100;
-       bytes_to_load =  PARA_MAX(prebuf_size, wng->max_chunk_bytes);
-       ret = read_stdin(audiobuf, bytes_to_load, &loaded);
-       if (ret <= 0 || loaded < bytes_to_load) {
-               if (ret >= 0)
-                       ret = -E_PREMATURE_END;
-               goto out;
+       if (!idt->start_time.tv_sec && !idt->start_time.tv_usec) {
+               t->error = -E_NO_DELAY;
+               goto register_check_wav;
        }
-       if (not_yet_started && start_time && start_time_in_future(&delay))
-               do_initial_delay(&delay);
-       not_yet_started = 0;
-again:
-       ret = wng_write(wng, audiobuf, &loaded);
-       if (ret <= 0)
-               goto out;
-       ret = -E_WRITE_OVERRUN;
-       if (loaded >= bufsize)
-               goto out;
-       bytes_to_load = PARA_MIN(wng->max_chunk_bytes, bufsize);
-       ret = read_stdin(audiobuf, bytes_to_load, &loaded);
-       if (ret < 0)
-               goto out;
-       if (!ret)
-               wng->eof = 1;
-       goto again;
-out:
-       wng_close(wng);
-       return ret;
+       if (tv_diff(now, &idt->start_time, &diff) > 0) {
+               t->error = -E_DELAY_TIMEOUT;
+               goto register_check_wav;
+       }
+       if (tv_diff(&s->timeout , &diff, NULL) > 0)
+               s->timeout = diff;
+       return;
+register_check_wav:
+       register_task(&the_check_wav_task.task);
+       s->timeout.tv_sec = 0;
+       s->timeout.tv_usec = 1;
 }
 
+static int loglevel;
+INIT_STDERR_LOGGING(loglevel)
+
 static struct writer_node_group *check_args(void)
 {
        int i, ret = -E_WRITE_SYNTAX;
-       static struct timeval tv;
-       struct writer_node_group *wng = NULL;
-
-       if (conf.list_writers_given) {
-               char *msg = NULL;
-               FOR_EACH_WRITER(i) {
-                       char *tmp = make_message("%s%s%s",
-                               i? msg : "",
-                               i? " " : "",
-                               writer_names[i]);
-                       free(msg);
-                       msg = tmp;
-               }
-               fprintf(stderr, "%s\n", msg);
-               free(msg);
-               exit(EXIT_SUCCESS);
-       }
-       if (conf.prebuffer_arg < 0 || conf.prebuffer_arg > 100)
-               goto out;
+       struct writer_node_group *g = NULL;
+       struct initial_delay_task *idt = &the_initial_delay_task;
+
+       loglevel = get_loglevel_by_name(conf.loglevel_arg);
        if (conf.start_time_given) {
                long unsigned sec, usec;
                if (sscanf(conf.start_time_arg, "%lu:%lu",
                                &sec, &usec) != 2)
                        goto out;
-               tv.tv_sec = sec;
-               tv.tv_usec = usec;
-               start_time = &tv;
+               idt->start_time.tv_sec = sec;
+               idt->start_time.tv_usec = usec;
        }
        if (!conf.writer_given) {
-               wng = setup_default_wng();
+               g = setup_default_wng();
                ret = 1;
                goto out;
        }
-       wng = wng_new(conf.writer_given);
+       g = wng_new(conf.writer_given);
+       ret = -E_WRITE_SYNTAX;
        for (i = 0; i < conf.writer_given; i++) {
-               ret = check_writer_arg(conf.writer_arg[i]);
-               if (ret < 0)
+               int writer_num;
+               g->writer_nodes[i].conf = check_writer_arg(
+                       conf.writer_arg[i], &writer_num);
+               if (!g->writer_nodes[i].conf)
                        goto out;
-               wng->writer_nodes[i].writer = &writers[ret];
+               g->writer_nodes[i].writer_num = writer_num;
        }
        ret = 1;
 out:
        if (ret > 0)
-               return wng;
-       free(wng);
+               return g;
+       free(g);
        return NULL;
 }
 
-/**
- * test if audio buffer contains a valid wave header
- *
- * \return If not, return 0, otherwise, store number of channels and sample rate
- * in struct conf and return WAV_HEADER_LEN.
+__noreturn static void print_help_and_die(void)
+{
+       int d = conf.detailed_help_given;
+       const char **p = d? write_args_info_detailed_help
+               : write_args_info_help;
+
+       printf_or_die("%s\n\n", WRITE_CMDLINE_PARSER_PACKAGE "-"
+               WRITE_CMDLINE_PARSER_VERSION);
+       printf_or_die("%s\n\n", write_args_info_usage);
+       for (; *p; p++)
+               printf_or_die("%s\n", *p);
+       print_writer_helps(d);
+       exit(0);
+}
+
+/*
+ TODO: check wav, initial delay, multiple writers, non-default writers
  */
-static size_t check_wave(void)
+static int main_btr(struct sched *s)
 {
-       unsigned char *a = audiobuf;
-       if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F')
-               return WAV_HEADER_LEN;
-       conf.channels_arg = (unsigned) a[22];
-       conf.sample_rate_arg = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
-       return 0;
+       int i, ret;
+       struct check_wav_task_btr _cwt, *cwt = &_cwt;
+       struct writer_node **wns;
+
+       sit.btrn = btr_new_node("stdin", NULL /* stdin has no parent */, NULL, NULL);
+       stdin_set_defaults(&sit);
+       register_task(&sit.task);
+
+       cwt->state = CWS_NEED_HEADER;
+       cwt->btrn = btr_new_node("check wav", sit.btrn, check_wav_exec, cwt);
+       sprintf(cwt->task.status, "check wav");
+       cwt->task.pre_select = check_wav_pre_select_btr;
+       cwt->task.post_select = check_wav_post_select_btr;
+       cwt->task.error = 0;
+       register_task(&cwt->task);
+
+       wns = para_malloc(conf.writer_given * sizeof(*wns));
+
+       for (i = 0; i < conf.writer_given; i++) {
+               struct writer_node *wn = para_calloc(sizeof(*wn));
+               struct writer *w;
+               const char *name;
+
+               ret = -E_WRITE_SYNTAX;
+               wn->conf = check_writer_arg(conf.writer_arg[i],
+                       &wn->writer_num);
+               if (!wn->conf)
+                       goto out;
+               w = writers + wn->writer_num;
+               name = writer_names[wn->writer_num];
+               wn->btrn = btr_new_node(name, cwt->btrn, w->execute, wn);
+               sprintf(wn->task.status, "%s", name);
+               w->open(wn);
+               wn->task.post_select = w->post_select_btr;
+               wn->task.pre_select = w->pre_select_btr;
+               register_task(&wn->task);
+               wns[i] = wn;
+       }
+       i--;
+
+       s->default_timeout.tv_sec = 10;
+       s->default_timeout.tv_usec = 50000;
+       ret = schedule(s);
+out:
+       for (; i >= 0; i--) {
+               struct writer_node *wn = wns[i];
+               free(wn->conf);
+               free(wn);
+       }
+       free(wns);
+       return ret;
 }
 
+/**
+ * Para_write's main function.
+ *
+ * \param argc The usual argument counter.
+ * \param argv The usual argument vector.
+ *
+ * It registers the stdin task, the check_wav_task, the task for initial delay
+ * and all tasks for actually writing out the stream.
+ *
+ * \return \p EXIT_SUCCESS or EXIT_FAILURE
+ */
 int main(int argc, char *argv[])
 {
        int ret = -E_WRITE_SYNTAX;
-       struct writer_node_group *wng = NULL;
+       static struct sched s;
+       struct check_wav_task *cwt = &the_check_wav_task;
+       struct initial_delay_task *idt = &the_initial_delay_task;
+
+       writer_init();
+       write_cmdline_parser(argc, argv, &conf);
+       HANDLE_VERSION_FLAG("write", conf);
+       if (conf.help_given || conf.detailed_help_given)
+               print_help_and_die();
 
-       cmdline_parser(argc, argv, &conf);
+       if (conf.buffer_tree_given) {
+               ret = main_btr(&s);
+               goto out;
+       }
        wng = check_args();
        if (!wng)
                goto out;
-       init_supported_writers();
-       audiobuf = para_malloc(WAV_HEADER_LEN);
-       ret = read_wav_header();
-       if (ret < 0)
+       stdin_set_defaults(&sit);
+       ret = -ERRNO_TO_PARA_ERROR(EINVAL);
+       if (conf.bufsize_arg < 0)
+               goto out;
+       if (conf.bufsize_arg >= INT_MAX / 1024)
                goto out;
-       ret = pcm_write(wng, check_wave());
+       sit.bufsize = conf.bufsize_arg * 1024;
+       sit.buf = para_malloc(sit.bufsize);
+
+       wng->bufp = &sit.buf;
+       wng->loaded = &sit.loaded;
+       wng->input_error = &sit.task.error;
+
+       register_task(&sit.task);
+
+       cwt->buf = sit.buf;
+       cwt->loaded = &sit.loaded;
+       cwt->input_error = &sit.task.error;
+       sprintf(cwt->task.status, "check wav");
+       cwt->task.pre_select = check_wav_pre_select;
+
+       idt->task.pre_select = initial_delay_pre_select;
+       sprintf(idt->task.status, "initial_delay");
+       register_task(&idt->task);
+
+       s.default_timeout.tv_sec = 10;
+       s.default_timeout.tv_usec = 0;
+       ret = schedule(&s);
+       wng_close(wng);
 out:
-       wng_destroy(wng);
-       free(audiobuf);
-       if (ret < 0)
-               PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
-       return ret;
+       if (ret < 0) {
+               PARA_ERROR_LOG("%s\n", para_strerror(-ret));
+               exit(EXIT_FAILURE);
+       }
+       exit(EXIT_SUCCESS);
 }