+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) {
+ int32_t val;
+
+ if (bytes == 0) /* no data available */
+ return;
+ get_btr_sample_rate(btrn, &val);
+ pad->sample_rate = val;
+ get_btr_channels(btrn, &val);
+ pad->channels = val;
+ get_btr_sample_format(btrn, &val);
+ pad->sample_format = get_alsa_pcm_format(val);
+
+ PARA_INFO_LOG("%d channel(s), %dHz\n", pad->channels,
+ pad->sample_rate);
+ ret = alsa_init(pad, wn->conf);
+ if (ret < 0)
+ goto err;
+ wn->min_iqs = pad->bytes_per_frame;
+ goto again;
+ }
+ 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) {
+ PARA_WARNING_LOG("underrun (tried to write %zu bytes)\n", bytes);
+ 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;
+}
+