+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;
+}
+