audiod: Fix time diff log message.
[paraslash.git] / alsa_write.c
index 0bb3de3..3c8d063 100644 (file)
  * based on the vplay program by Michael Beck.
  */
 
+#include <regex.h>
 #include <sys/types.h>
 #include <dirent.h>
 #include <alsa/asoundlib.h>
+#include <sys/time.h>
+#include <stdbool.h>
 
 #include "para.h"
 #include "fd.h"
@@ -22,7 +25,9 @@
 #include "list.h"
 #include "sched.h"
 #include "ggo.h"
+#include "buffer_tree.h"
 #include "write.h"
+#include "write_common.h"
 #include "alsa_write.cmdline.h"
 #include "error.h"
 
@@ -35,10 +40,10 @@ struct private_alsa_write_data {
        snd_pcm_t *handle;
        /** Determined and set by alsa_open(). */
        int bytes_per_frame;
-       /** Don't write anything until this time. */
-       struct timeval next_chunk;
        /** The approximate maximum buffer duration in us. */
        unsigned buffer_time;
+       /* Number of frames that fit into the buffer. */
+       snd_pcm_uframes_t buffer_frames;
        /**
         * The samplerate given by command line option or the decoder
         * of the writer node group.
@@ -49,6 +54,7 @@ struct private_alsa_write_data {
         * decoder of the writer node group.
         */
        unsigned channels;
+       struct timeval drain_barrier;
 };
 
 /* Install PCM software and hardware configuration. */
@@ -57,10 +63,11 @@ static int alsa_init(struct private_alsa_write_data *pad,
 {
        snd_pcm_hw_params_t *hwparams;
        snd_pcm_sw_params_t *swparams;
-       snd_pcm_uframes_t buffer_size, start_threshold, stop_threshold;
+       snd_pcm_uframes_t start_threshold, stop_threshold;
        snd_pcm_uframes_t period_size;
        int err;
 
+       PARA_INFO_LOG("opening %s\n", conf->device_arg);
        err = snd_pcm_open(&pad->handle, conf->device_arg,
                SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
        if (err < 0)
@@ -79,34 +86,35 @@ static int alsa_init(struct private_alsa_write_data *pad,
                        pad->channels) < 0)
                return -E_CHANNEL_COUNT;
        if (snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
-                       &pad->samplerate, 0) < 0)
+                       &pad->samplerate, NULL) < 0)
                return -E_SET_RATE;
-       err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &pad->buffer_time, 0);
+       err = snd_pcm_hw_params_get_buffer_time_max(hwparams,
+               &pad->buffer_time, NULL);
        if (err < 0 || !pad->buffer_time)
                return -E_GET_BUFFER_TIME;
        PARA_INFO_LOG("buffer time: %d\n", pad->buffer_time);
        if (snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
-                       &pad->buffer_time, 0) < 0)
+                       &pad->buffer_time, NULL) < 0)
                return -E_SET_BUFFER_TIME;
        if (snd_pcm_hw_params(pad->handle, hwparams) < 0)
                return -E_HW_PARAMS;
-       snd_pcm_hw_params_get_period_size(hwparams, &period_size, 0);
-       snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
-       PARA_INFO_LOG("buffer size: %lu, period_size: %lu\n", buffer_size,
+       snd_pcm_hw_params_get_period_size(hwparams, &period_size, NULL);
+       snd_pcm_hw_params_get_buffer_size(hwparams, &pad->buffer_frames);
+       PARA_INFO_LOG("buffer size: %lu, period_size: %lu\n", pad->buffer_frames,
                period_size);
-       if (period_size == buffer_size)
+       if (period_size == pad->buffer_frames)
                return -E_BAD_PERIOD;
        snd_pcm_sw_params_current(pad->handle, swparams);
        snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
-       if (buffer_size < 1)
+       if (pad->buffer_frames < 1)
                start_threshold = 1;
        else
-               start_threshold = PARA_MIN(buffer_size,
+               start_threshold = PARA_MIN(pad->buffer_frames,
                        (snd_pcm_uframes_t)pad->samplerate);
        if (snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
                        start_threshold) < 0)
                return -E_START_THRESHOLD;
-       stop_threshold = buffer_size;
+       stop_threshold = pad->buffer_frames;
        if (snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
                        stop_threshold) < 0)
                return -E_STOP_THRESHOLD;
@@ -116,7 +124,7 @@ static int alsa_init(struct private_alsa_write_data *pad,
                * pad->channels / 8;
        if (pad->bytes_per_frame <= 0)
                return -E_PHYSICAL_WIDTH;
-       PARA_INFO_LOG("bytes per frame: %zu\n", pad->bytes_per_frame);
+       PARA_INFO_LOG("bytes per frame: %d\n", pad->bytes_per_frame);
        if (snd_pcm_nonblock(pad->handle, 1))
                PARA_ERROR_LOG("failed to set nonblock mode\n");
        return 1;
@@ -125,91 +133,63 @@ static int alsa_init(struct private_alsa_write_data *pad,
 /* Open an instance of the alsa writer. */
 static int alsa_open(struct writer_node *wn)
 {
-       struct alsa_write_args_info *conf = wn->conf;
-       struct writer_node_group *wng = wn->wng;
-       struct private_alsa_write_data *pad = para_calloc(sizeof(*pad));
-
-       wn->private_data = pad;
-       if (!conf->samplerate_given && wng->samplerate)
-               pad->samplerate = *wng->samplerate;
-       else
-               pad->samplerate = conf->samplerate_arg;
-       if (!conf->channels_given && wng->channels)
-               pad->channels = *wng->channels;
-       else
-               pad->channels = conf->channels_arg;
-       PARA_INFO_LOG("%d channel(s), %dHz\n", pad->channels, pad->samplerate);
-       tv_add(now, &(struct timeval){0, 100 * 1000}, &pad->next_chunk);
+       wn->private_data = para_calloc(sizeof(struct private_alsa_write_data));
        return 1;
 }
 
-static int alsa_write_pre_select(struct sched *s, struct writer_node *wn)
+static void alsa_write_pre_select(struct sched *s, struct task *t)
 {
+       struct writer_node *wn = container_of(t, struct writer_node, task);
        struct private_alsa_write_data *pad = wn->private_data;
-       struct writer_node_group *wng = wn->wng;
-       struct timeval diff;
+       struct timeval tv;
+       snd_pcm_sframes_t avail, underrun;
+       int ret;
 
-       if (!*wng->loaded)
-               return 1;
-       if (tv_diff(now, &pad->next_chunk, &diff) < 0) {
-               if (tv_diff(&s->timeout, &diff, NULL) > 0)
-                       s->timeout = diff;
-       } else {
-               s->timeout.tv_sec = 0;
-               s->timeout.tv_usec = 1;
-       }
-       return 1;
+       if (!pad->handle)
+               return;
+       ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
+       if (ret < 0)
+               sched_request_timeout_ms(20, s);
+       if (ret <= 0)
+               return;
+       /*
+        * Data is available to be written to the alsa handle.  Compute number
+        * of milliseconds until next buffer underrun would occur.
+        *
+        * snd_pcm_avail_update() updates the current available count of
+        * samples for writing.  It is a light method to obtain current stream
+        * position, because it does not require the user <-> kernel context
+        * switch, but the value is less accurate, because ring buffer pointers
+        * are updated in kernel drivers only when an interrupt occurs.
+        */
+       avail = snd_pcm_avail_update(pad->handle);
+       if (avail < 0)
+               avail = 0;
+       underrun = (pad->buffer_frames - avail) * pad->buffer_time
+               / pad->buffer_frames / 1000;
+       if (underrun < 50)
+               underrun = 50;
+       underrun -= 50;
+       ms2tv(underrun, &tv);
+       if (tv_diff(&s->timeout, &tv, NULL) > 0)
+               s->timeout = tv;
 }
 
-static int alsa_write_post_select(__a_unused struct sched *s,
-               struct writer_node *wn)
+static void xrun(snd_pcm_t *handle)
 {
-       struct private_alsa_write_data *pad = wn->private_data;
-       struct writer_node_group *wng = wn->wng;
-       size_t frames, bytes = *wng->loaded - wn->written;
-       unsigned char *data = (unsigned char*)wng->buf + wn->written;
-       struct timeval tv;
-       snd_pcm_sframes_t ret;
+       snd_pcm_status_t *status;
+       int ret;
+       struct timeval tv, diff;
 
-       if (*wng->input_error < 0 && (!pad->handle || bytes < pad->bytes_per_frame)) {
-               wn->written = *wng->loaded;
-               return *wng->input_error;
-       }
-       if (!bytes) /* no data available */
-               goto out;
-       if (tv_diff(now, &pad->next_chunk, NULL) < 0)
-               goto out;
-       if (!pad->handle) {
-               int err = alsa_init(pad, wn->conf);
-               if (err < 0)
-                       return err;
-       }
-       frames = bytes / pad->bytes_per_frame;
-       if (!frames) /* less than a single frame available */
-               goto out;
-       ret = snd_pcm_writei(pad->handle, data, frames);
-       if (ret == -EPIPE) {
-               PARA_WARNING_LOG("EPIPE\n");
-               snd_pcm_prepare(pad->handle);
-               return 1;
-       }
-       if (ret < 0 && ret != -EAGAIN) {
-               PARA_WARNING_LOG("alsa error (%zu frames, ret = %d\n",
-                       frames, (int)ret);
-               return -E_ALSA_WRITE;
-       }
-       if (ret == -EAGAIN)
-               PARA_DEBUG_LOG("EAGAIN\n");
-       else
-               wn->written += ret * pad->bytes_per_frame;
-       if (ret == frames) /* we wrote everything, try again immediately */
-               pad->next_chunk = *now;
-       else { /* wait until 50% buffer space is available */
-               ms2tv(pad->buffer_time / 2000, &tv);
-               tv_add(now, &tv, &pad->next_chunk);
-       }
-out:
-       return 1;
+       snd_pcm_status_alloca(&status);
+       ret = snd_pcm_status(handle, status);
+       if (ret < 0)
+               return;
+       if (snd_pcm_status_get_state(status) != SND_PCM_STATE_XRUN)
+               return;
+       snd_pcm_status_get_trigger_tstamp(status, &tv);
+       tv_diff(now, &tv, &diff);
+       PARA_WARNING_LOG("underrun: %lums\n", tv2ms(&diff));
 }
 
 static void alsa_close(struct writer_node *wn)
@@ -218,6 +198,11 @@ static void alsa_close(struct writer_node *wn)
        PARA_INFO_LOG("closing writer node %p\n", wn);
 
        if (pad->handle) {
+               /*
+                * It's OK to have a blocking operation here because we already
+                * made sure that the PCM output buffer is (nearly) empty.
+                */
+               snd_pcm_nonblock(pad->handle, 0);
                snd_pcm_drain(pad->handle);
                snd_pcm_close(pad->handle);
                snd_config_update_free_global();
@@ -225,6 +210,84 @@ static void alsa_close(struct writer_node *wn)
        free(pad);
 }
 
+static void alsa_write_post_select(__a_unused struct sched *s,
+               struct task *t)
+{
+       struct writer_node *wn = container_of(t, struct writer_node, task);
+       struct private_alsa_write_data *pad = wn->private_data;
+       struct btr_node *btrn = wn->btrn;
+       char *data;
+       size_t bytes;
+       snd_pcm_sframes_t frames;
+       int ret;
+
+again:
+       t->error = 0;
+       ret = btr_node_status(btrn, wn->min_iqs, BTR_NT_LEAF);
+       if (ret == 0)
+               return;
+       btr_merge(btrn, wn->min_iqs);
+       bytes = btr_next_buffer(btrn, &data);
+       if (ret < 0 || bytes < pad->bytes_per_frame) { /* eof */
+               assert(btr_no_parent(btrn));
+               ret = -E_ALSA_EOF;
+               if (!pad->handle)
+                       goto err;
+               /* wait until pending frames are played */
+               if (pad->drain_barrier.tv_sec == 0) {
+                       PARA_DEBUG_LOG("waiting for device to drain\n");
+                       tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
+                               &pad->drain_barrier);
+                       return;
+               }
+               if (tv_diff(now, &pad->drain_barrier, NULL) > 0)
+                       goto err;
+               return;
+       }
+       if (!pad->handle) {
+               struct alsa_write_args_info *conf = wn->conf;
+               if (bytes == 0) /* no data available */
+                       return;
+               /* defaults */
+               pad->samplerate = conf->samplerate_arg;
+               pad->channels = conf->channels_arg;
+               if (!conf->samplerate_given) { /* config option trumps btr_exec */
+                       int32_t rate;
+                       if (get_btr_samplerate(btrn, &rate) >= 0)
+                               pad->samplerate = rate;
+               }
+               if (!conf->channels_given) {
+                       int32_t ch;
+                       if (get_btr_channels(btrn, &ch) >= 0)
+                               pad->channels = ch;
+               }
+               PARA_INFO_LOG("%d channel(s), %dHz\n", pad->channels, pad->samplerate);
+               ret = alsa_init(pad, wn->conf);
+               if (ret < 0)
+                       goto err;
+               wn->min_iqs = pad->bytes_per_frame;
+       }
+       frames = bytes / pad->bytes_per_frame;
+       frames = snd_pcm_writei(pad->handle, data, frames);
+       if (frames >= 0) {
+               btr_consume(btrn, frames * pad->bytes_per_frame);
+               goto again;
+       }
+       if (frames == -EPIPE) {
+               xrun(pad->handle);
+               snd_pcm_prepare(pad->handle);
+               return;
+       }
+       if (frames == -EAGAIN)
+               return;
+       PARA_WARNING_LOG("%s\n", snd_strerror(-frames));
+       ret = -E_ALSA_WRITE;
+err:
+       assert(ret < 0);
+       btr_remove_node(btrn);
+       t->error = ret;
+}
+
 __malloc static void *alsa_parse_config(const char *options)
 {
        int ret;
@@ -242,12 +305,17 @@ err_out:
        return NULL;
 }
 
+static void alsa_free_config(void *conf)
+{
+       alsa_cmdline_parser_free(conf);
+}
+
 /**
- * the init function of the alsa writer
+ * The init function of the alsa writer.
  *
- * \param w pointer to the writer to initialize
+ * \param w Pointer to the writer to initialize.
  *
- * \sa struct writer
+ * \sa \ref struct writer.
  */
 void alsa_write_init(struct writer *w)
 {
@@ -260,8 +328,10 @@ void alsa_write_init(struct writer *w)
        w->post_select = alsa_write_post_select;
        w->parse_config = alsa_parse_config;
        w->shutdown = NULL; /* nothing to do */
+       w->free_config = alsa_free_config;
        w->help = (struct ggo_help) {
                .short_help = alsa_write_args_info_help,
                .detailed_help = alsa_write_args_info_detailed_help
        };
+       alsa_cmdline_parser_free(&dummy);
 }