+static void alsa_write_post_select_btr(__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;
+ char *data;
+ size_t bytes;
+ snd_pcm_sframes_t frames, avail;
+ int ret;
+
+again:
+ bytes = btr_next_buffer(wn->btrn, &data);
+ //PARA_CRIT_LOG("have: %zu\n", bytes);
+ t->error = 0;
+ ret = -E_ALSA_ORPHAN;
+ if (btr_no_parent(wn->btrn) && (!pad->handle || bytes < pad->bytes_per_frame))
+ goto err;
+ if (!pad->handle) {
+ char *buf;
+ struct alsa_write_args_info *conf = wn->conf;
+ if (bytes == 0) /* no data available */
+ return;
+ PARA_CRIT_LOG("alsa init\n");
+ /* defaults */
+ pad->samplerate = conf->samplerate_arg;
+ pad->channels = conf->channels_arg;
+ if (!conf->samplerate_given) { /* config option trumps btr_exec */
+ /* ask parent btr nodes */
+ buf = NULL;
+ ret = btr_exec_up(wn->btrn, "samplerate", &buf);
+ PARA_CRIT_LOG("ret: %d\n", ret);
+ if (ret >= 0) {
+ int32_t rate;
+
+ ret = para_atoi32(buf, &rate);
+ free(buf);
+ if (ret < 0) /* should not happen */
+ goto err;
+ pad->samplerate = rate;
+ }
+ }
+ if (!conf->channels_given) {
+ buf = NULL;
+ ret = btr_exec_up(wn->btrn, "channels", &buf);
+ if (ret >= 0) {
+ int32_t ch;
+
+ ret = para_atoi32(buf, &ch);
+ freep(&buf);
+ if (ret < 0)
+ goto err;
+ pad->channels = ch;
+ }
+ }
+ PARA_INFO_LOG("%d channel(s), %dHz\n", pad->channels, pad->samplerate);
+ ret = 1;
+ ret = alsa_init(pad, wn->conf);
+ if (ret < 0)
+ goto err;
+ }
+ for (;;) {
+ if (bytes == 0)
+ return;
+ if (bytes >= pad->bytes_per_frame)
+ break;
+ /* should not be possible to reach this */
+ PARA_CRIT_LOG("dropping %zu byte buffer\n", bytes);
+ btr_consume(wn->btrn, bytes);
+ bytes = btr_next_buffer(wn->btrn, &data);
+ }
+ frames = bytes / pad->bytes_per_frame;
+ avail = snd_pcm_avail_update(pad->handle);
+ if (avail <= 0)
+ return;
+ frames = PARA_MIN(frames, avail);
+ //PARA_CRIT_LOG("writing %ld frames\n", frames);
+ frames = snd_pcm_writei(pad->handle, data, frames);
+ if (frames >= 0) {
+ btr_consume(wn->btrn, frames * pad->bytes_per_frame);
+ goto again;
+ }
+ if (frames == -EPIPE) {
+ xrun(pad->handle);
+ snd_pcm_prepare(pad->handle);
+ return;
+ }
+ PARA_WARNING_LOG("%s\n", snd_strerror(-frames));
+ if (frames == -EAGAIN)
+ return;
+ ret = -E_ALSA_WRITE;
+err:
+ assert(ret < 0);
+ alsa_close(wn);
+ btr_del_node(wn->btrn);
+ wn->btrn = NULL;
+ t->error = ret;
+}
+