summaryrefslogtreecommitdiffstats
path: root/pipewire-alsa/alsa-plugins
diff options
context:
space:
mode:
Diffstat (limited to 'pipewire-alsa/alsa-plugins')
-rw-r--r--pipewire-alsa/alsa-plugins/ctl_pipewire.c1496
-rw-r--r--pipewire-alsa/alsa-plugins/meson.build27
-rw-r--r--pipewire-alsa/alsa-plugins/pcm_pipewire.c1333
3 files changed, 2856 insertions, 0 deletions
diff --git a/pipewire-alsa/alsa-plugins/ctl_pipewire.c b/pipewire-alsa/alsa-plugins/ctl_pipewire.c
new file mode 100644
index 0000000..61394e2
--- /dev/null
+++ b/pipewire-alsa/alsa-plugins/ctl_pipewire.c
@@ -0,0 +1,1496 @@
+/* CTL - PipeWire plugin
+ *
+ * Copyright © 2020 Wim Taymans
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#include <alsa/asoundlib.h>
+#include <alsa/control_external.h>
+
+#include <spa/utils/result.h>
+#include <spa/utils/string.h>
+#include <spa/utils/json.h>
+#include <spa/param/props.h>
+#include <spa/param/audio/format-utils.h>
+
+#include <pipewire/pipewire.h>
+#include <pipewire/extensions/metadata.h>
+
+PW_LOG_TOPIC_STATIC(alsa_log_topic, "alsa.ctl");
+#define PW_LOG_TOPIC_DEFAULT alsa_log_topic
+
+#define DEFAULT_VOLUME_METHOD "cubic"
+
+#define VOLUME_MIN ((uint32_t) 0U)
+#define VOLUME_MAX ((uint32_t) 0x10000U)
+
+struct volume {
+ uint32_t channels;
+ long values[SPA_AUDIO_MAX_CHANNELS];
+};
+
+typedef struct {
+ snd_ctl_ext_t ext;
+
+ struct pw_properties *props;
+
+ struct spa_system *system;
+ struct pw_thread_loop *mainloop;
+
+ struct pw_context *context;
+ struct pw_core *core;
+ struct spa_hook core_listener;
+
+ struct pw_registry *registry;
+ struct spa_hook registry_listener;
+
+ struct pw_metadata *metadata;
+ struct spa_hook metadata_listener;
+
+ int fd;
+ int last_seq;
+ int pending_seq;
+ int error;
+
+ char default_sink[1024];
+ int sink_muted;
+ struct volume sink_volume;
+
+ char default_source[1024];
+ int source_muted;
+ struct volume source_volume;
+
+ int subscribed;
+#define VOLUME_METHOD_LINEAR (0)
+#define VOLUME_METHOD_CUBIC (1)
+ int volume_method;
+
+#define UPDATE_SINK_VOL (1<<0)
+#define UPDATE_SINK_MUTE (1<<1)
+#define UPDATE_SOURCE_VOL (1<<2)
+#define UPDATE_SOURCE_MUTE (1<<3)
+ int updated;
+
+ struct spa_list globals;
+} snd_ctl_pipewire_t;
+
+static inline uint32_t volume_from_linear(float vol, int method)
+{
+ if (vol <= 0.0f)
+ vol = 0.0f;
+
+ switch (method) {
+ case VOLUME_METHOD_CUBIC:
+ vol = cbrtf(vol);
+ break;
+ }
+ return SPA_CLAMP((uint64_t)lroundf(vol * VOLUME_MAX),
+ VOLUME_MIN, VOLUME_MAX);
+}
+
+static inline float volume_to_linear(uint32_t vol, int method)
+{
+ float v = ((float)vol) / VOLUME_MAX;
+
+ switch (method) {
+ case VOLUME_METHOD_CUBIC:
+ v = v * v * v;
+ break;
+ }
+ return v;
+}
+
+struct global;
+
+struct global_info {
+ const char *type;
+ uint32_t version;
+ const void *events;
+ pw_destroy_t destroy;
+ int (*init) (struct global *g);
+};
+
+struct global {
+ struct spa_list link;
+
+ snd_ctl_pipewire_t *ctl;
+
+ const struct global_info *ginfo;
+
+ uint32_t id;
+ uint32_t permissions;
+ struct pw_properties *props;
+
+ struct pw_proxy *proxy;
+ struct spa_hook proxy_listener;
+ struct spa_hook object_listener;
+
+ union {
+ struct {
+#define NODE_FLAG_SINK (1<<0)
+#define NODE_FLAG_SOURCE (1<<1)
+#define NODE_FLAG_DEVICE_VOLUME (1<<2)
+#define NODE_FLAG_DEVICE_MUTE (1<<3)
+ uint32_t flags;
+ uint32_t device_id;
+ uint32_t profile_device_id;
+ int priority;
+ float volume;
+ bool mute;
+ struct volume channel_volume;
+ } node;
+ struct {
+ uint32_t active_route_output;
+ uint32_t active_route_input;
+ } device;
+ };
+};
+
+#define SOURCE_VOL_NAME "Capture Volume"
+#define SOURCE_MUTE_NAME "Capture Switch"
+#define SINK_VOL_NAME "Master Playback Volume"
+#define SINK_MUTE_NAME "Master Playback Switch"
+
+static void do_resync(snd_ctl_pipewire_t *ctl)
+{
+ ctl->pending_seq = pw_core_sync(ctl->core, PW_ID_CORE, ctl->pending_seq);
+}
+
+static int wait_resync(snd_ctl_pipewire_t *ctl)
+{
+ int res;
+ do_resync(ctl);
+
+ while (true) {
+ pw_thread_loop_wait(ctl->mainloop);
+
+ res = ctl->error;
+ if (res < 0) {
+ ctl->error = 0;
+ return res;
+ }
+
+ if (ctl->pending_seq == ctl->last_seq)
+ break;
+ }
+ return 0;
+}
+
+static struct global *find_global(snd_ctl_pipewire_t *ctl, uint32_t id,
+ const char *name, const char *type)
+{
+ struct global *g;
+ uint32_t name_id = name ? (uint32_t)atoi(name) : SPA_ID_INVALID;
+ const char *str;
+
+ spa_list_for_each(g, &ctl->globals, link) {
+ if ((g->id == id || g->id == name_id) &&
+ (type == NULL || spa_streq(g->ginfo->type, type)))
+ return g;
+ if (name != NULL && name[0] != '\0' &&
+ (str = pw_properties_get(g->props, PW_KEY_NODE_NAME)) != NULL &&
+ spa_streq(name, str))
+ return g;
+ }
+ return NULL;
+}
+
+static struct global *find_best_node(snd_ctl_pipewire_t *ctl, uint32_t flags)
+{
+ struct global *g, *best = NULL;
+ spa_list_for_each(g, &ctl->globals, link) {
+ if ((spa_streq(g->ginfo->type, PW_TYPE_INTERFACE_Node)) &&
+ (flags == 0 || (g->node.flags & flags) == flags) &&
+ (best == NULL || best->node.priority < g->node.priority))
+ best = g;
+ }
+ return best;
+}
+
+static inline int poll_activate(snd_ctl_pipewire_t *ctl)
+{
+ spa_system_eventfd_write(ctl->system, ctl->fd, 1);
+ return 1;
+}
+
+static inline int poll_deactivate(snd_ctl_pipewire_t *ctl)
+{
+ uint64_t val;
+ spa_system_eventfd_read(ctl->system, ctl->fd, &val);
+ return 1;
+}
+
+static bool volume_equal(struct volume *a, struct volume *b)
+{
+ if (a == b)
+ return true;
+ if (a->channels != b->channels)
+ return false;
+ return memcmp(a->values, b->values, sizeof(float) * a->channels) == 0;
+}
+
+static int pipewire_update_volume(snd_ctl_pipewire_t * ctl)
+{
+ bool changed = false;
+ struct global *g;
+
+ if (ctl->default_sink[0] == '\0')
+ g = find_best_node(ctl, NODE_FLAG_SINK);
+ else
+ g = find_global(ctl, SPA_ID_INVALID, ctl->default_sink,
+ PW_TYPE_INTERFACE_Node);
+
+ if (g) {
+ if (!!ctl->sink_muted != !!g->node.mute) {
+ ctl->sink_muted = g->node.mute;
+ ctl->updated |= UPDATE_SINK_MUTE;
+ changed = true;
+ }
+ if (!volume_equal(&ctl->sink_volume, &g->node.channel_volume)) {
+ ctl->sink_volume = g->node.channel_volume;
+ ctl->updated |= UPDATE_SINK_VOL;
+ changed = true;
+ }
+ }
+
+ if (ctl->default_source[0] == '\0')
+ g = find_best_node(ctl, NODE_FLAG_SOURCE);
+ else
+ g = find_global(ctl, SPA_ID_INVALID, ctl->default_source,
+ PW_TYPE_INTERFACE_Node);
+
+ if (g) {
+ if (!!ctl->source_muted != !!g->node.mute) {
+ ctl->source_muted = g->node.mute;
+ ctl->updated |= UPDATE_SOURCE_MUTE;
+ changed = true;
+ }
+ if (!volume_equal(&ctl->source_volume, &g->node.channel_volume)) {
+ ctl->source_volume = g->node.channel_volume;
+ ctl->updated |= UPDATE_SOURCE_VOL;
+ changed = true;
+ }
+ }
+
+ if (changed)
+ poll_activate(ctl);
+
+ return 0;
+}
+
+static int pipewire_elem_count(snd_ctl_ext_t * ext)
+{
+ snd_ctl_pipewire_t *ctl = ext->private_data;
+ int count = 0, err;
+
+ assert(ctl);
+
+ if (!ctl->mainloop)
+ return -EBADFD;
+
+ pw_thread_loop_lock(ctl->mainloop);
+
+ err = ctl->error;
+ if (err < 0) {
+ ctl->error = 0;
+ count = err;
+ goto finish;
+ }
+ err = pipewire_update_volume(ctl);
+ if (err < 0) {
+ count = err;
+ goto finish;
+ }
+
+ if (ctl->default_source[0] != '\0')
+ count += 2;
+ if (ctl->default_sink[0] != '\0')
+ count += 2;
+
+finish:
+ pw_thread_loop_unlock(ctl->mainloop);
+
+ return count;
+}
+
+static int pipewire_elem_list(snd_ctl_ext_t * ext, unsigned int offset,
+ snd_ctl_elem_id_t * id)
+{
+ snd_ctl_pipewire_t *ctl = ext->private_data;
+ int err;
+
+ assert(ctl);
+
+ if (!ctl->mainloop)
+ return -EBADFD;
+
+ snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER);
+
+ pw_thread_loop_lock(ctl->mainloop);
+
+ err = ctl->error;
+ if (err < 0) {
+ ctl->error = 0;
+ goto finish;
+ }
+
+ if (ctl->default_source[0] != '\0') {
+ if (offset == 0)
+ snd_ctl_elem_id_set_name(id, SOURCE_VOL_NAME);
+ else if (offset == 1)
+ snd_ctl_elem_id_set_name(id, SOURCE_MUTE_NAME);
+ } else
+ offset += 2;
+
+ err = 0;
+finish:
+ pw_thread_loop_unlock(ctl->mainloop);
+
+ if (err >= 0) {
+ if (offset == 2)
+ snd_ctl_elem_id_set_name(id, SINK_VOL_NAME);
+ else if (offset == 3)
+ snd_ctl_elem_id_set_name(id, SINK_MUTE_NAME);
+ }
+
+ return err;
+}
+
+static snd_ctl_ext_key_t pipewire_find_elem(snd_ctl_ext_t * ext,
+ const snd_ctl_elem_id_t * id)
+{
+ const char *name;
+ unsigned int numid;
+
+ numid = snd_ctl_elem_id_get_numid(id);
+ if (numid > 0 && numid <= 4)
+ return numid - 1;
+
+ name = snd_ctl_elem_id_get_name(id);
+
+ if (spa_streq(name, SOURCE_VOL_NAME))
+ return 0;
+ if (spa_streq(name, SOURCE_MUTE_NAME))
+ return 1;
+ if (spa_streq(name, SINK_VOL_NAME))
+ return 2;
+ if (spa_streq(name, SINK_MUTE_NAME))
+ return 3;
+
+ return SND_CTL_EXT_KEY_NOT_FOUND;
+}
+
+static int pipewire_get_attribute(snd_ctl_ext_t * ext, snd_ctl_ext_key_t key,
+ int *type, unsigned int *acc,
+ unsigned int *count)
+{
+ snd_ctl_pipewire_t *ctl = ext->private_data;
+ int err = 0;
+
+ if (key > 3)
+ return -EINVAL;
+
+ assert(ctl);
+
+ if (!ctl->mainloop)
+ return -EBADFD;
+
+ pw_thread_loop_lock(ctl->mainloop);
+
+ err = ctl->error;
+ if (err < 0) {
+ ctl->error = 0;
+ goto finish;
+ }
+
+ err = pipewire_update_volume(ctl);
+ if (err < 0)
+ goto finish;
+
+ if (key & 1)
+ *type = SND_CTL_ELEM_TYPE_BOOLEAN;
+ else
+ *type = SND_CTL_ELEM_TYPE_INTEGER;
+
+ *acc = SND_CTL_EXT_ACCESS_READWRITE;
+
+ if (key == 0)
+ *count = ctl->source_volume.channels;
+ else if (key == 2)
+ *count = ctl->sink_volume.channels;
+ else
+ *count = 1;
+
+finish:
+ pw_thread_loop_unlock(ctl->mainloop);
+
+ return err;
+}
+
+static int pipewire_get_integer_info(snd_ctl_ext_t * ext,
+ snd_ctl_ext_key_t key, long *imin,
+ long *imax, long *istep)
+{
+ *istep = 1;
+ *imin = VOLUME_MIN;
+ *imax = VOLUME_MAX;
+
+ return 0;
+}
+
+static int pipewire_read_integer(snd_ctl_ext_t * ext, snd_ctl_ext_key_t key,
+ long *value)
+{
+ snd_ctl_pipewire_t *ctl = ext->private_data;
+ int err = 0;
+ uint32_t i;
+ struct volume *vol = NULL;
+
+ assert(ctl);
+
+ if (!ctl->mainloop)
+ return -EBADFD;
+
+ pw_thread_loop_lock(ctl->mainloop);
+
+ err = ctl->error;
+ if (err < 0) {
+ ctl->error = 0;
+ goto finish;
+ }
+
+ err = pipewire_update_volume(ctl);
+ if (err < 0)
+ goto finish;
+
+ switch (key) {
+ case 0:
+ vol = &ctl->source_volume;
+ break;
+ case 1:
+ *value = !ctl->source_muted;
+ break;
+ case 2:
+ vol = &ctl->sink_volume;
+ break;
+ case 3:
+ *value = !ctl->sink_muted;
+ break;
+ default:
+ err = -EINVAL;
+ goto finish;
+ }
+
+ if (vol) {
+ for (i = 0; i < vol->channels; i++)
+ value[i] = vol->values[i];
+ }
+
+finish:
+ pw_thread_loop_unlock(ctl->mainloop);
+
+ return err;
+}
+
+static struct spa_pod *build_volume_mute(struct spa_pod_builder *b, struct volume *volume,
+ int *mute, int volume_method)
+{
+ struct spa_pod_frame f[1];
+
+ spa_pod_builder_push_object(b, &f[0],
+ SPA_TYPE_OBJECT_Props, SPA_PARAM_Props);
+ if (volume) {
+ float volumes[SPA_AUDIO_MAX_CHANNELS];
+ uint32_t i, n_volumes = 0;
+
+ n_volumes = volume->channels;
+ for (i = 0; i < n_volumes; i++)
+ volumes[i] = volume_to_linear(volume->values[i], volume_method);
+
+ spa_pod_builder_prop(b, SPA_PROP_channelVolumes, 0);
+ spa_pod_builder_array(b, sizeof(float),
+ SPA_TYPE_Float, n_volumes, volumes);
+ }
+ if (mute) {
+ spa_pod_builder_prop(b, SPA_PROP_mute, 0);
+ spa_pod_builder_bool(b, *mute ? true : false);
+ }
+ return spa_pod_builder_pop(b, &f[0]);
+}
+
+static int set_volume_mute(snd_ctl_pipewire_t *ctl, const char *name, struct volume *volume, int *mute)
+{
+ struct global *g, *dg = NULL;
+ uint32_t id = SPA_ID_INVALID, device_id = SPA_ID_INVALID;
+ char buf[1024];
+ struct spa_pod_builder b = SPA_POD_BUILDER_INIT(buf, sizeof(buf));
+ struct spa_pod_frame f[2];
+ struct spa_pod *param;
+
+ g = find_global(ctl, SPA_ID_INVALID, name, PW_TYPE_INTERFACE_Node);
+ if (g == NULL)
+ return -EINVAL;
+
+ if (SPA_FLAG_IS_SET(g->node.flags, NODE_FLAG_DEVICE_VOLUME) &&
+ (dg = find_global(ctl, g->node.device_id, NULL, PW_TYPE_INTERFACE_Device)) != NULL) {
+ if (g->node.flags & NODE_FLAG_SINK)
+ id = dg->device.active_route_output;
+ else if (g->node.flags & NODE_FLAG_SOURCE)
+ id = dg->device.active_route_input;
+ device_id = g->node.profile_device_id;
+ }
+ pw_log_debug("id %d device_id %d flags:%08x", id, device_id, g->node.flags);
+ if (id != SPA_ID_INVALID && device_id != SPA_ID_INVALID && dg != NULL) {
+ if (!SPA_FLAG_IS_SET(dg->permissions, PW_PERM_W | PW_PERM_X))
+ return -EPERM;
+
+ spa_pod_builder_push_object(&b, &f[0],
+ SPA_TYPE_OBJECT_ParamRoute, SPA_PARAM_Route);
+ spa_pod_builder_add(&b,
+ SPA_PARAM_ROUTE_index, SPA_POD_Int(id),
+ SPA_PARAM_ROUTE_device, SPA_POD_Int(device_id),
+ SPA_PARAM_ROUTE_save, SPA_POD_Bool(true),
+ 0);
+
+ spa_pod_builder_prop(&b, SPA_PARAM_ROUTE_props, 0);
+ build_volume_mute(&b, volume, mute, ctl->volume_method);
+ param = spa_pod_builder_pop(&b, &f[0]);
+
+ pw_log_debug("set device %d mute/volume for node %d", dg->id, g->id);
+ pw_device_set_param((struct pw_node*)dg->proxy,
+ SPA_PARAM_Route, 0, param);
+ } else {
+ if (!SPA_FLAG_IS_SET(g->permissions, PW_PERM_W | PW_PERM_X))
+ return -EPERM;
+
+ param = build_volume_mute(&b, volume, mute, ctl->volume_method);
+
+ pw_log_debug("set node %d mute/volume", g->id);
+ pw_node_set_param((struct pw_node*)g->proxy,
+ SPA_PARAM_Props, 0, param);
+ }
+ return 0;
+}
+
+static int pipewire_write_integer(snd_ctl_ext_t * ext, snd_ctl_ext_key_t key,
+ long *value)
+{
+ snd_ctl_pipewire_t *ctl = ext->private_data;
+ int err = 0;
+ uint32_t i;
+ struct volume *vol = NULL;
+
+ assert(ctl);
+
+ if (!ctl->mainloop)
+ return -EBADFD;
+
+ pw_thread_loop_lock(ctl->mainloop);
+
+ err = ctl->error;
+ if (err < 0) {
+ ctl->error = 0;
+ goto finish;
+ }
+
+ err = pipewire_update_volume(ctl);
+ if (err < 0)
+ goto finish;
+
+ switch (key) {
+ case 0:
+ vol = &ctl->source_volume;
+ break;
+ case 1:
+ if (!!ctl->source_muted == !*value)
+ goto finish;
+ ctl->source_muted = !*value;
+ break;
+ case 2:
+ vol = &ctl->sink_volume;
+ break;
+ case 3:
+ if (!!ctl->sink_muted == !*value)
+ goto finish;
+ ctl->sink_muted = !*value;
+ break;
+ default:
+ err = -EINVAL;
+ goto finish;
+ }
+
+ if (vol) {
+ for (i = 0; i < vol->channels; i++)
+ if (value[i] != vol->values[i])
+ break;
+
+ if (i == vol->channels)
+ goto finish;
+
+ for (i = 0; i < vol->channels; i++)
+ vol->values[i] = value[i];
+
+ if (key == 0)
+ err = set_volume_mute(ctl, ctl->default_source, vol, NULL);
+ else
+ err = set_volume_mute(ctl, ctl->default_sink, vol, NULL);
+ } else {
+ if (key == 1)
+ err = set_volume_mute(ctl, ctl->default_source, NULL, &ctl->source_muted);
+ else
+ err = set_volume_mute(ctl, ctl->default_sink, NULL, &ctl->sink_muted);
+ }
+ if (err < 0)
+ goto finish;
+
+ err = wait_resync(ctl);
+
+ if (err < 0)
+ goto finish;
+
+ err = 1;
+
+finish:
+ pw_thread_loop_unlock(ctl->mainloop);
+
+ return err;
+}
+
+static void pipewire_subscribe_events(snd_ctl_ext_t * ext, int subscribe)
+{
+ snd_ctl_pipewire_t *ctl = ext->private_data;
+
+ assert(ctl);
+
+ if (!ctl->mainloop)
+ return;
+
+ pw_thread_loop_lock(ctl->mainloop);
+
+ ctl->subscribed = !!(subscribe & SND_CTL_EVENT_MASK_VALUE);
+
+ pw_thread_loop_unlock(ctl->mainloop);
+}
+
+static int pipewire_read_event(snd_ctl_ext_t * ext, snd_ctl_elem_id_t * id,
+ unsigned int *event_mask)
+{
+ snd_ctl_pipewire_t *ctl = ext->private_data;
+ int offset;
+ int err;
+
+ assert(ctl);
+
+ if (!ctl->mainloop)
+ return -EBADFD;
+
+ pw_thread_loop_lock(ctl->mainloop);
+
+ err = ctl->error;
+ if (err < 0) {
+ ctl->error = 0;
+ goto finish;
+ }
+
+ if (!ctl->updated || !ctl->subscribed) {
+ err = -EAGAIN;
+ goto finish;
+ }
+
+ if (ctl->default_source[0] != '\0')
+ offset = 2;
+ else
+ offset = 0;
+
+ if (ctl->updated & UPDATE_SOURCE_VOL) {
+ pipewire_elem_list(ext, 0, id);
+ ctl->updated &= ~UPDATE_SOURCE_VOL;
+ } else if (ctl->updated & UPDATE_SOURCE_MUTE) {
+ pipewire_elem_list(ext, 1, id);
+ ctl->updated &= ~UPDATE_SOURCE_MUTE;
+ } else if (ctl->updated & UPDATE_SINK_VOL) {
+ pipewire_elem_list(ext, offset + 0, id);
+ ctl->updated &= ~UPDATE_SINK_VOL;
+ } else if (ctl->updated & UPDATE_SINK_MUTE) {
+ pipewire_elem_list(ext, offset + 1, id);
+ ctl->updated &= ~UPDATE_SINK_MUTE;
+ }
+
+ *event_mask = SND_CTL_EVENT_MASK_VALUE;
+
+ err = 1;
+
+finish:
+ if (!ctl->updated)
+ poll_deactivate(ctl);
+
+ pw_thread_loop_unlock(ctl->mainloop);
+
+ return err;
+}
+
+static int pipewire_ctl_poll_revents(snd_ctl_ext_t * ext, struct pollfd *pfd,
+ unsigned int nfds,
+ unsigned short *revents)
+{
+ snd_ctl_pipewire_t *ctl = ext->private_data;
+ int err = 0;
+
+ assert(ctl);
+
+ if (!ctl->mainloop)
+ return -EBADFD;
+
+ pw_thread_loop_lock(ctl->mainloop);
+
+ err = ctl->error;
+ if (err < 0) {
+ ctl->error = 0;
+ goto finish;
+ }
+
+ if (ctl->updated)
+ *revents = POLLIN;
+ else
+ *revents = 0;
+
+ err = 0;
+
+finish:
+ pw_thread_loop_unlock(ctl->mainloop);
+
+ return err;
+}
+
+static void snd_ctl_pipewire_free(snd_ctl_pipewire_t *ctl)
+{
+ if (ctl == NULL)
+ return;
+
+ pw_log_debug("%p:", ctl);
+ if (ctl->mainloop)
+ pw_thread_loop_stop(ctl->mainloop);
+ if (ctl->registry)
+ pw_proxy_destroy((struct pw_proxy*)ctl->registry);
+ if (ctl->context)
+ pw_context_destroy(ctl->context);
+ if (ctl->fd >= 0)
+ spa_system_close(ctl->system, ctl->fd);
+ if (ctl->mainloop)
+ pw_thread_loop_destroy(ctl->mainloop);
+ pw_properties_free(ctl->props);
+ free(ctl);
+}
+
+static void pipewire_close(snd_ctl_ext_t * ext)
+{
+ snd_ctl_pipewire_t *ctl = ext->private_data;
+ snd_ctl_pipewire_free(ctl);
+}
+
+static const snd_ctl_ext_callback_t pipewire_ext_callback = {
+ .elem_count = pipewire_elem_count,
+ .elem_list = pipewire_elem_list,
+ .find_elem = pipewire_find_elem,
+ .get_attribute = pipewire_get_attribute,
+ .get_integer_info = pipewire_get_integer_info,
+ .read_integer = pipewire_read_integer,
+ .write_integer = pipewire_write_integer,
+ .subscribe_events = pipewire_subscribe_events,
+ .read_event = pipewire_read_event,
+ .poll_revents = pipewire_ctl_poll_revents,
+ .close = pipewire_close,
+};
+
+/** device */
+static void device_event_info(void *data, const struct pw_device_info *info)
+{
+ struct global *g = data;
+ snd_ctl_pipewire_t *ctl = g->ctl;
+ uint32_t n;
+
+ pw_log_debug("info");
+
+ if (info->change_mask & PW_DEVICE_CHANGE_MASK_PARAMS) {
+ for (n = 0; n < info->n_params; n++) {
+ if (!(info->params[n].flags & SPA_PARAM_INFO_READ))
+ continue;
+
+ switch (info->params[n].id) {
+ case SPA_PARAM_Route:
+ pw_device_enum_params((struct pw_device*)g->proxy,
+ 0, info->params[n].id, 0, -1, NULL);
+ break;
+ default:
+ break;
+ }
+ }
+
+ }
+ do_resync(ctl);
+}
+
+static void parse_props(struct global *g, const struct spa_pod *param, bool device)
+{
+ struct spa_pod_prop *prop;
+ struct spa_pod_object *obj = (struct spa_pod_object *) param;
+ snd_ctl_pipewire_t *ctl = g->ctl;
+
+ SPA_POD_OBJECT_FOREACH(obj, prop) {
+ switch (prop->key) {
+ case SPA_PROP_volume:
+ if (spa_pod_get_float(&prop->value, &g->node.volume) < 0)
+ continue;
+ pw_log_debug("update node %d volume", g->id);
+ SPA_FLAG_UPDATE(g->node.flags, NODE_FLAG_DEVICE_VOLUME, device);
+ break;
+ case SPA_PROP_mute:
+ if (spa_pod_get_bool(&prop->value, &g->node.mute) < 0)
+ continue;
+ SPA_FLAG_UPDATE(g->node.flags, NODE_FLAG_DEVICE_MUTE, device);
+ pw_log_debug("update node %d mute", g->id);
+ break;
+ case SPA_PROP_channelVolumes:
+ {
+ float volumes[SPA_AUDIO_MAX_CHANNELS];
+ uint32_t n_volumes, i;
+
+ n_volumes = spa_pod_copy_array(&prop->value, SPA_TYPE_Float,
+ volumes, SPA_AUDIO_MAX_CHANNELS);
+
+ g->node.channel_volume.channels = n_volumes;
+ for (i = 0; i < n_volumes; i++)
+ g->node.channel_volume.values[i] =
+ volume_from_linear(volumes[i], ctl->volume_method);
+
+ SPA_FLAG_UPDATE(g->node.flags, NODE_FLAG_DEVICE_VOLUME, device);
+ pw_log_debug("update node %d channelVolumes", g->id);
+ break;
+ }
+ default:
+ break;
+ }
+ }
+}
+
+static struct global *find_node_for_route(snd_ctl_pipewire_t *ctl, uint32_t card, uint32_t device)
+{
+ struct global *n;
+ spa_list_for_each(n, &ctl->globals, link) {
+ if (spa_streq(n->ginfo->type, PW_TYPE_INTERFACE_Node) &&
+ (n->node.device_id == card) &&
+ (n->node.profile_device_id == device))
+ return n;
+ }
+ return NULL;
+}
+
+static void device_event_param(void *data, int seq,
+ uint32_t id, uint32_t index, uint32_t next,
+ const struct spa_pod *param)
+{
+ struct global *g = data;
+ snd_ctl_pipewire_t *ctl = g->ctl;
+
+ pw_log_debug("param %d", id);
+
+ switch (id) {
+ case SPA_PARAM_Route:
+ {
+ uint32_t idx, device;
+ enum spa_direction direction;
+ struct spa_pod *props = NULL;
+ struct global *ng;
+
+ if (spa_pod_parse_object(param,
+ SPA_TYPE_OBJECT_ParamRoute, NULL,
+ SPA_PARAM_ROUTE_index, SPA_POD_Int(&idx),
+ SPA_PARAM_ROUTE_direction, SPA_POD_Id(&direction),
+ SPA_PARAM_ROUTE_device, SPA_POD_Int(&device),
+ SPA_PARAM_ROUTE_props, SPA_POD_OPT_Pod(&props)) < 0) {
+ pw_log_warn("device %d: can't parse route", g->id);
+ return;
+ }
+ if (direction == SPA_DIRECTION_OUTPUT)
+ g->device.active_route_output = idx;
+ else
+ g->device.active_route_input = idx;
+
+ pw_log_debug("device %d: active %s route %d", g->id,
+ direction == SPA_DIRECTION_OUTPUT ? "output" : "input",
+ idx);
+
+ ng = find_node_for_route(ctl, g->id, device);
+ if (props && ng)
+ parse_props(ng, props, true);
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+static const struct pw_device_events device_events = {
+ PW_VERSION_DEVICE_EVENTS,
+ .info = device_event_info,
+ .param = device_event_param,
+};
+
+static const struct global_info device_info = {
+ .type = PW_TYPE_INTERFACE_Device,
+ .version = PW_VERSION_DEVICE,
+ .events = &device_events,
+};
+
+/** node */
+static void node_event_info(void *data, const struct pw_node_info *info)
+{
+ struct global *g = data;
+ snd_ctl_pipewire_t *ctl = g->ctl;
+ const char *str;
+ uint32_t i;
+
+ pw_log_debug("update %d %"PRIu64, g->id, info->change_mask);
+
+ if (info->change_mask & PW_NODE_CHANGE_MASK_PROPS && info->props) {
+ if ((str = spa_dict_lookup(info->props, "card.profile.device")))
+ g->node.profile_device_id = atoi(str);
+ else
+ g->node.profile_device_id = SPA_ID_INVALID;
+
+ if ((str = spa_dict_lookup(info->props, PW_KEY_DEVICE_ID)))
+ g->node.device_id = atoi(str);
+ else
+ g->node.device_id = SPA_ID_INVALID;
+
+ if ((str = spa_dict_lookup(info->props, PW_KEY_PRIORITY_SESSION)))
+ g->node.priority = atoi(str);
+ if ((str = spa_dict_lookup(info->props, PW_KEY_MEDIA_CLASS))) {
+ if (spa_streq(str, "Audio/Sink"))
+ g->node.flags |= NODE_FLAG_SINK;
+ else if (spa_streq(str, "Audio/Source"))
+ g->node.flags |= NODE_FLAG_SOURCE;
+ }
+ }
+ if (info->change_mask & PW_NODE_CHANGE_MASK_PARAMS) {
+ for (i = 0; i < info->n_params; i++) {
+ if (!(info->params[i].flags & SPA_PARAM_INFO_READ))
+ continue;
+
+ switch (info->params[i].id) {
+ case SPA_PARAM_Props:
+ pw_node_enum_params((struct pw_node*)g->proxy,
+ 0, info->params[i].id, 0, -1, NULL);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ do_resync(ctl);
+}
+
+
+static void node_event_param(void *data, int seq,
+ uint32_t id, uint32_t index, uint32_t next,
+ const struct spa_pod *param)
+{
+ struct global *g = data;
+ pw_log_debug("update param %d %d", g->id, id);
+
+ switch (id) {
+ case SPA_PARAM_Props:
+ if (!SPA_FLAG_IS_SET(g->node.flags, NODE_FLAG_DEVICE_VOLUME | NODE_FLAG_DEVICE_MUTE))
+ parse_props(g, param, false);
+ break;
+ default:
+ break;
+ }
+}
+
+static const struct pw_node_events node_events = {
+ PW_VERSION_NODE_EVENTS,
+ .info = node_event_info,
+ .param = node_event_param,
+};
+
+static const struct global_info node_info = {
+ .type = PW_TYPE_INTERFACE_Node,
+ .version = PW_VERSION_NODE,
+ .events = &node_events,
+};
+
+/** metadata */
+static int json_object_find(const char *obj, const char *key, char *value, size_t len)
+{
+ struct spa_json it[2];
+ const char *v;
+ char k[128];
+
+ spa_json_init(&it[0], obj, strlen(obj));
+ if (spa_json_enter_object(&it[0], &it[1]) <= 0)
+ return -EINVAL;
+
+ while (spa_json_get_string(&it[1], k, sizeof(k)) > 0) {
+ if (spa_streq(k, key)) {
+ if (spa_json_get_string(&it[1], value, len) <= 0)
+ continue;
+ return 0;
+ } else {
+ if (spa_json_next(&it[1], &v) <= 0)
+ break;
+ }
+ }
+ return -ENOENT;
+}
+
+static int metadata_property(void *data,
+ uint32_t subject,
+ const char *key,
+ const char *type,
+ const char *value)
+{
+ struct global *g = data;
+ snd_ctl_pipewire_t *ctl = g->ctl;
+
+ if (subject == PW_ID_CORE) {
+ if (key == NULL || spa_streq(key, "default.audio.sink")) {
+ if (value == NULL ||
+ json_object_find(value, "name",
+ ctl->default_sink, sizeof(ctl->default_sink)) < 0)
+ ctl->default_sink[0] = '\0';
+ pw_log_debug("found default sink: %s", ctl->default_sink);
+ }
+ if (key == NULL || spa_streq(key, "default.audio.source")) {
+ if (value == NULL ||
+ json_object_find(value, "name",
+ ctl->default_source, sizeof(ctl->default_source)) < 0)
+ ctl->default_source[0] = '\0';
+ pw_log_debug("found default source: %s", ctl->default_source);
+ }
+ }
+ return 0;
+}
+
+static int metadata_init(struct global *g)
+{
+ snd_ctl_pipewire_t *ctl = g->ctl;
+ ctl->metadata = (struct pw_metadata*)g->proxy;
+ return 0;
+}
+
+static const struct pw_metadata_events metadata_events = {
+ PW_VERSION_METADATA_EVENTS,
+ .property = metadata_property,
+};
+
+static const struct global_info metadata_info = {
+ .type = PW_TYPE_INTERFACE_Metadata,
+ .version = PW_VERSION_METADATA,
+ .events = &metadata_events,
+ .init = metadata_init
+};
+
+/** proxy */
+static void proxy_removed(void *data)
+{
+ struct global *g = data;
+ pw_proxy_destroy(g->proxy);
+}
+
+static void proxy_destroy(void *data)
+{
+ struct global *g = data;
+ spa_list_remove(&g->link);
+ g->proxy = NULL;
+ pw_properties_free(g->props);
+}
+
+static const struct pw_proxy_events proxy_events = {
+ PW_VERSION_PROXY_EVENTS,
+ .removed = proxy_removed,
+ .destroy = proxy_destroy
+};
+
+static void registry_event_global(void *data, uint32_t id,
+ uint32_t permissions, const char *type, uint32_t version,
+ const struct spa_dict *props)
+{
+ snd_ctl_pipewire_t *ctl = data;
+ const struct global_info *info = NULL;
+ struct pw_proxy *proxy;
+ const char *str;
+
+ pw_log_debug("got %d %s", id, type);
+
+ if (spa_streq(type, PW_TYPE_INTERFACE_Device)) {
+ if (props == NULL ||
+ ((str = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS)) == NULL) ||
+ (!spa_streq(str, "Audio/Device")))
+ return;
+
+ pw_log_debug("found device %d", id);
+ info = &device_info;
+ } else if (spa_streq(type, PW_TYPE_INTERFACE_Node)) {
+ if (props == NULL ||
+ ((str = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS)) == NULL) ||
+ ((!spa_streq(str, "Audio/Sink")) &&
+ (!spa_streq(str, "Audio/Source"))))
+ return;
+
+ pw_log_debug("found node %d type:%s", id, str);
+ info = &node_info;
+ } else if (spa_streq(type, PW_TYPE_INTERFACE_Metadata)) {
+ if (props == NULL ||
+ ((str = spa_dict_lookup(props, PW_KEY_METADATA_NAME)) == NULL) ||
+ (!spa_streq(str, "default")))
+ return;
+ if (ctl->metadata != NULL)
+ return;
+ info = &metadata_info;
+ }
+ if (info) {
+ struct global *g;
+
+ proxy = pw_registry_bind(ctl->registry,
+ id, info->type, info->version,
+ sizeof(struct global));
+
+ g = pw_proxy_get_user_data(proxy);
+ g->ctl = ctl;
+ g->ginfo = info;
+ g->id = id;
+ g->permissions = permissions;
+ g->props = props ? pw_properties_new_dict(props) : NULL;
+ g->proxy = proxy;
+ spa_list_append(&ctl->globals, &g->link);
+
+ pw_proxy_add_listener(proxy,
+ &g->proxy_listener,
+ &proxy_events, g);
+
+ if (info->events) {
+ pw_proxy_add_object_listener(proxy,
+ &g->object_listener,
+ info->events, g);
+ }
+ if (info->init)
+ info->init(g);
+
+ do_resync(ctl);
+ }
+}
+
+static void registry_event_global_remove(void *data, uint32_t id)
+{
+ snd_ctl_pipewire_t *ctl = data;
+ struct global *g;
+ const char *name;
+
+ if ((g = find_global(ctl, id, NULL, NULL)) == NULL)
+ return;
+
+ if (spa_streq(g->ginfo->type, PW_TYPE_INTERFACE_Node)) {
+ if ((name = pw_properties_get(g->props, PW_KEY_NODE_NAME)) == NULL)
+ return;
+
+ if (spa_streq(name, ctl->default_sink))
+ ctl->default_sink[0] = '\0';
+ if (spa_streq(name, ctl->default_source))
+ ctl->default_source[0] = '\0';
+ }
+ pw_proxy_destroy(g->proxy);
+}
+
+static const struct pw_registry_events registry_events = {
+ PW_VERSION_REGISTRY_EVENTS,
+ .global = registry_event_global,
+ .global_remove = registry_event_global_remove,
+};
+
+static void on_core_error(void *data, uint32_t id, int seq, int res, const char *message)
+{
+ snd_ctl_pipewire_t *ctl = data;
+
+ pw_log_warn("%p: error id:%u seq:%d res:%d (%s): %s", ctl,
+ id, seq, res, spa_strerror(res), message);
+
+ if (id == PW_ID_CORE) {
+ switch (res) {
+ case -ENOENT:
+ break;
+ default:
+ ctl->error = res;
+ if (ctl->fd != -1)
+ poll_activate(ctl);
+ }
+ }
+ pw_thread_loop_signal(ctl->mainloop, false);
+}
+
+static void on_core_done(void *data, uint32_t id, int seq)
+{
+ snd_ctl_pipewire_t *ctl = data;
+
+ pw_log_debug("done %d %d %d", id, seq, ctl->pending_seq);
+
+ if (id != PW_ID_CORE)
+ return;
+
+ ctl->last_seq = seq;
+ if (seq == ctl->pending_seq) {
+ pipewire_update_volume(ctl);
+ pw_thread_loop_signal(ctl->mainloop, false);
+ }
+}
+
+static const struct pw_core_events core_events = {
+ PW_VERSION_CORE_EVENTS,
+ .error = on_core_error,
+ .done = on_core_done,
+};
+
+static int execute_match(void *data, const char *location, const char *action,
+ const char *val, size_t len)
+{
+ snd_ctl_pipewire_t *ctl = data;
+ if (spa_streq(action, "update-props"))
+ pw_properties_update_string(ctl->props, val, len);
+ return 1;
+}
+
+SPA_EXPORT
+SND_CTL_PLUGIN_DEFINE_FUNC(pipewire)
+{
+ snd_config_iterator_t i, next;
+ const char *server = NULL;
+ const char *device = NULL;
+ const char *source = NULL;
+ const char *sink = NULL;
+ const char *fallback_name = NULL;
+ int err;
+ const char *str;
+ snd_ctl_pipewire_t *ctl;
+ struct pw_loop *loop;
+
+ pw_init(NULL, NULL);
+
+ PW_LOG_TOPIC_INIT(alsa_log_topic);
+
+ snd_config_for_each(i, next, conf) {
+ snd_config_t *n = snd_config_iterator_entry(i);
+ const char *id;
+ if (snd_config_get_id(n, &id) < 0)
+ continue;
+ if (spa_streq(id, "comment") || spa_streq(id, "type")
+ || spa_streq(id, "hint"))
+ continue;
+ if (spa_streq(id, "server")) {
+ if (snd_config_get_string(n, &server) < 0) {
+ SNDERR("Invalid type for %s", id);
+ return -EINVAL;
+ } else if (!*server) {
+ server = NULL;
+ }
+ continue;
+ }
+ if (spa_streq(id, "device")) {
+ if (snd_config_get_string(n, &device) < 0) {
+ SNDERR("Invalid type for %s", id);
+ return -EINVAL;
+ } else if (!*device) {
+ device = NULL;
+ }
+ continue;
+ }
+ if (spa_streq(id, "source")) {
+ if (snd_config_get_string(n, &source) < 0) {
+ SNDERR("Invalid type for %s", id);
+ return -EINVAL;
+ } else if (!*source) {
+ source = NULL;
+ }
+ continue;
+ }
+ if (spa_streq(id, "sink")) {
+ if (snd_config_get_string(n, &sink) < 0) {
+ SNDERR("Invalid type for %s", id);
+ return -EINVAL;
+ } else if (!*sink) {
+ sink = NULL;
+ }
+ continue;
+ }
+ if (spa_streq(id, "fallback")) {
+ if (snd_config_get_string(n, &fallback_name) < 0) {
+ SNDERR("Invalid value for %s", id);
+ return -EINVAL;
+ }
+ continue;
+ }
+ SNDERR("Unknown field %s", id);
+ return -EINVAL;
+ }
+
+ if (fallback_name && name && spa_streq(name, fallback_name))
+ fallback_name = NULL; /* no fallback for the same name */
+
+ ctl = calloc(1, sizeof(*ctl));
+ if (!ctl)
+ return -ENOMEM;
+
+ spa_list_init(&ctl->globals);
+
+ if (source == NULL)
+ source = device;
+ if (source != NULL)
+ snprintf(ctl->default_source, sizeof(ctl->default_source),
+ "%s", source);
+ if (sink == NULL)
+ sink = device;
+ if (sink != NULL)
+ snprintf(ctl->default_sink, sizeof(ctl->default_sink),
+ "%s", sink);
+
+ ctl->mainloop = pw_thread_loop_new("alsa-pipewire", NULL);
+ if (ctl->mainloop == NULL) {
+ err = -errno;
+ goto error;
+ }
+ loop = pw_thread_loop_get_loop(ctl->mainloop);
+
+ ctl->system = loop->system;
+ ctl->fd = spa_system_eventfd_create(ctl->system, SPA_FD_CLOEXEC | SPA_FD_NONBLOCK);
+ if (ctl->fd == -1) {
+ err = -errno;
+ goto error;
+ }
+
+ ctl->context = pw_context_new(loop,
+ pw_properties_new(
+ PW_KEY_CLIENT_API, "alsa",
+ PW_KEY_CONFIG_NAME, "client-rt.conf",
+ NULL),
+ 0);
+ if (ctl->context == NULL) {
+ err = -errno;
+ goto error;
+ }
+
+ ctl->props = pw_properties_new(NULL, NULL);
+ if (ctl->props == NULL) {
+ err = -errno;
+ goto error;
+ }
+
+ if (server)
+ pw_properties_set(ctl->props, PW_KEY_REMOTE_NAME, server);
+
+ pw_context_conf_update_props(ctl->context, "alsa.properties", ctl->props);
+
+ pw_context_conf_section_match_rules(ctl->context, "alsa.rules",
+ &pw_context_get_properties(ctl->context)->dict,
+ execute_match, ctl);
+
+ if (pw_properties_get(ctl->props, PW_KEY_APP_NAME) == NULL)
+ pw_properties_setf(ctl->props, PW_KEY_APP_NAME, "PipeWire ALSA [%s]",
+ pw_get_prgname());
+
+ str = getenv("PIPEWIRE_ALSA");
+ if (str != NULL)
+ pw_properties_update_string(ctl->props, str, strlen(str));
+
+ if ((str = pw_properties_get(ctl->props, "alsa.volume-method")) == NULL)
+ str = DEFAULT_VOLUME_METHOD;
+
+ if (spa_streq(str, "cubic"))
+ ctl->volume_method = VOLUME_METHOD_CUBIC;
+ else if (spa_streq(str, "linear"))
+ ctl->volume_method = VOLUME_METHOD_LINEAR;
+ else {
+ ctl->volume_method = VOLUME_METHOD_CUBIC;
+ SNDERR("unknown alsa.volume-method %s, using cubic", str);
+ }
+
+ if ((err = pw_thread_loop_start(ctl->mainloop)) < 0)
+ goto error;
+
+ pw_thread_loop_lock(ctl->mainloop);
+ ctl->core = pw_context_connect(ctl->context, pw_properties_copy(ctl->props), 0);
+ if (ctl->core == NULL) {
+ err = -errno;
+ goto error_unlock;
+ }
+ pw_core_add_listener(ctl->core,
+ &ctl->core_listener,
+ &core_events, ctl);
+
+ ctl->registry = pw_core_get_registry(ctl->core, PW_VERSION_REGISTRY, 0);
+ if (ctl->registry == NULL) {
+ err = -errno;
+ goto error_unlock;
+ }
+
+ pw_registry_add_listener(ctl->registry,
+ &ctl->registry_listener,
+ &registry_events, ctl);
+
+ err = wait_resync(ctl);
+ if (err < 0)
+ goto error_unlock;
+
+ pw_thread_loop_unlock(ctl->mainloop);
+
+ ctl->ext.version = SND_CTL_EXT_VERSION;
+ ctl->ext.card_idx = 0;
+ strncpy(ctl->ext.id, "pipewire", sizeof(ctl->ext.id) - 1);
+ strncpy(ctl->ext.driver, "PW plugin", sizeof(ctl->ext.driver) - 1);
+ strncpy(ctl->ext.name, "PipeWire", sizeof(ctl->ext.name) - 1);
+ strncpy(ctl->ext.longname, "PipeWire", sizeof(ctl->ext.longname) - 1);
+ strncpy(ctl->ext.mixername, "PipeWire", sizeof(ctl->ext.mixername) - 1);
+ ctl->ext.poll_fd = ctl->fd;
+
+ ctl->ext.callback = &pipewire_ext_callback;
+ ctl->ext.private_data = ctl;
+
+ err = snd_ctl_ext_create(&ctl->ext, name, mode);
+ if (err < 0)
+ goto error;
+
+ *handlep = ctl->ext.handle;
+
+ return 0;
+
+error_unlock:
+ pw_thread_loop_unlock(ctl->mainloop);
+error:
+ snd_ctl_pipewire_free(ctl);
+ pw_log_error("error %d (%s)", err, spa_strerror(err));
+
+ if (fallback_name)
+ return snd_ctl_open_fallback(handlep, root,
+ fallback_name, name, mode);
+
+ return err;
+}
+
+SPA_EXPORT
+SND_CTL_PLUGIN_SYMBOL(pipewire);
diff --git a/pipewire-alsa/alsa-plugins/meson.build b/pipewire-alsa/alsa-plugins/meson.build
new file mode 100644
index 0000000..cbc34ad
--- /dev/null
+++ b/pipewire-alsa/alsa-plugins/meson.build
@@ -0,0 +1,27 @@
+pipewire_alsa_plugin_pcm_sources = [
+ 'pcm_pipewire.c',
+]
+pipewire_alsa_plugin_ctl_sources = [
+ 'ctl_pipewire.c',
+]
+
+pipewire_alsa_plugin_c_args = [
+ '-DPIC',
+]
+
+pipewire_alsa_pcm_plugin = shared_library('asound_module_pcm_pipewire',
+ pipewire_alsa_plugin_pcm_sources,
+ c_args : pipewire_alsa_plugin_c_args,
+ include_directories : [configinc],
+ dependencies : [pipewire_dep, alsa_dep],
+ install : true,
+ install_dir : pipewire_libdir / 'alsa-lib',
+)
+pipewire_alsa_ctl_plugin = shared_library('asound_module_ctl_pipewire',
+ pipewire_alsa_plugin_ctl_sources,
+ c_args : pipewire_alsa_plugin_c_args,
+ include_directories : [configinc],
+ dependencies : [pipewire_dep, alsa_dep, mathlib],
+ install : true,
+ install_dir : pipewire_libdir / 'alsa-lib',
+)
diff --git a/pipewire-alsa/alsa-plugins/pcm_pipewire.c b/pipewire-alsa/alsa-plugins/pcm_pipewire.c
new file mode 100644
index 0000000..dc0cd81
--- /dev/null
+++ b/pipewire-alsa/alsa-plugins/pcm_pipewire.c
@@ -0,0 +1,1333 @@
+/* PCM - PipeWire plugin
+ *
+ * Copyright © 2017 Wim Taymans
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#define __USE_GNU
+
+#include <limits.h>
+#if !defined(__FreeBSD__) && !defined(__MidnightBSD__)
+#include <byteswap.h>
+#endif
+#include <sys/shm.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/mman.h>
+
+#include <alsa/asoundlib.h>
+#include <alsa/pcm_external.h>
+
+#include <spa/param/audio/format-utils.h>
+#include <spa/debug/types.h>
+#include <spa/param/props.h>
+#include <spa/utils/result.h>
+#include <spa/utils/string.h>
+
+#include <pipewire/pipewire.h>
+
+#define ATOMIC_INC(s) __atomic_add_fetch(&(s), 1, __ATOMIC_SEQ_CST)
+#define ATOMIC_LOAD(s) __atomic_load_n(&(s), __ATOMIC_SEQ_CST)
+
+#define SEQ_WRITE(s) ATOMIC_INC(s)
+#define SEQ_WRITE_SUCCESS(s1,s2) ((s1) + 1 == (s2) && ((s2) & 1) == 0)
+
+#define SEQ_READ(s) ATOMIC_LOAD(s)
+#define SEQ_READ_SUCCESS(s1,s2) ((s1) == (s2) && ((s2) & 1) == 0)
+
+PW_LOG_TOPIC_STATIC(alsa_log_topic, "alsa.pcm");
+#define PW_LOG_TOPIC_DEFAULT alsa_log_topic
+
+#define MIN_BUFFERS 2u
+#define MAX_BUFFERS 64u
+
+#define MAX_CHANNELS 64
+#define MAX_RATE (48000*8)
+
+#define MIN_PERIOD 64
+
+#define MIN_PERIOD_BYTES (128)
+#define MAX_PERIOD_BYTES (2*1024*1024)
+
+#define MIN_BUFFER_BYTES (2*MIN_PERIOD_BYTES)
+#define MAX_BUFFER_BYTES (2*MAX_PERIOD_BYTES)
+
+typedef struct {
+ snd_pcm_ioplug_t io;
+
+ snd_output_t *output;
+ FILE *log_file;
+
+ int fd;
+ int error;
+ unsigned int activated:1; /* PipeWire is activated? */
+ unsigned int drained:1;
+ unsigned int draining:1;
+ unsigned int xrun_detected:1;
+ unsigned int hw_params_changed:1;
+ unsigned int active:1;
+
+ snd_pcm_uframes_t hw_ptr;
+ snd_pcm_uframes_t boundary;
+ snd_pcm_uframes_t min_avail;
+ unsigned int sample_bits;
+ uint32_t blocks;
+ uint32_t stride;
+
+ struct spa_system *system;
+ struct pw_thread_loop *main_loop;
+
+ struct pw_properties *props;
+ struct pw_context *context;
+
+ struct pw_core *core;
+ struct spa_hook core_listener;
+
+ struct pw_stream *stream;
+ struct spa_hook stream_listener;
+
+ int64_t delay;
+ uint64_t transfered;
+ uint64_t buffered;
+ int64_t now;
+ uintptr_t seq;
+
+ struct spa_audio_info_raw format;
+} snd_pcm_pipewire_t;
+
+static int snd_pcm_pipewire_stop(snd_pcm_ioplug_t *io);
+
+static int check_active(snd_pcm_ioplug_t *io)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ snd_pcm_sframes_t avail;
+ bool active;
+
+ avail = snd_pcm_ioplug_avail(io, pw->hw_ptr, io->appl_ptr);
+
+ if (io->state == SND_PCM_STATE_DRAINING) {
+ active = pw->drained;
+ }
+ else if (avail >= 0 && avail < (snd_pcm_sframes_t)pw->min_avail) {
+ active = false;
+ }
+ else if (avail >= (snd_pcm_sframes_t)pw->min_avail) {
+ active = true;
+ } else {
+ active = false;
+ }
+ if (pw->active != active) {
+ pw_log_trace("%p: avail:%lu min-avail:%lu state:%s hw:%lu appl:%lu active:%d->%d state:%s",
+ pw, avail, pw->min_avail, snd_pcm_state_name(io->state),
+ pw->hw_ptr, io->appl_ptr, pw->active, active,
+ snd_pcm_state_name(io->state));
+ }
+ return active;
+}
+
+
+static int update_active(snd_pcm_ioplug_t *io)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ pw->active = check_active(io);
+ uint64_t val;
+
+ if (pw->active || pw->error < 0)
+ spa_system_eventfd_write(pw->system, io->poll_fd, 1);
+ else
+ spa_system_eventfd_read(pw->system, io->poll_fd, &val);
+
+ return pw->active;
+}
+
+static void snd_pcm_pipewire_free(snd_pcm_pipewire_t *pw)
+{
+ if (pw == NULL)
+ return;
+
+ pw_log_debug("%p: free", pw);
+ if (pw->main_loop)
+ pw_thread_loop_stop(pw->main_loop);
+ if (pw->stream)
+ pw_stream_destroy(pw->stream);
+ if (pw->context)
+ pw_context_destroy(pw->context);
+ if (pw->fd >= 0)
+ spa_system_close(pw->system, pw->fd);
+ if (pw->main_loop)
+ pw_thread_loop_destroy(pw->main_loop);
+ pw_properties_free(pw->props);
+ snd_output_close(pw->output);
+ fclose(pw->log_file);
+ free(pw);
+}
+
+static int snd_pcm_pipewire_close(snd_pcm_ioplug_t *io)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ pw_log_debug("%p: close", pw);
+ snd_pcm_pipewire_free(pw);
+ return 0;
+}
+
+static int snd_pcm_pipewire_poll_descriptors(snd_pcm_ioplug_t *io, struct pollfd *pfds, unsigned int space)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ update_active(io);
+ pfds->fd = pw->fd;
+ pfds->events = POLLIN | POLLERR | POLLNVAL;
+ return 1;
+}
+
+static int snd_pcm_pipewire_poll_revents(snd_pcm_ioplug_t *io,
+ struct pollfd *pfds, unsigned int nfds,
+ unsigned short *revents)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+
+ assert(pfds && nfds == 1 && revents);
+
+ if (pw->error < 0)
+ return pw->error;
+
+ *revents = pfds[0].revents & ~(POLLIN | POLLOUT);
+ if (pfds[0].revents & POLLIN && check_active(io)) {
+ *revents |= (io->stream == SND_PCM_STREAM_PLAYBACK) ? POLLOUT : POLLIN;
+ update_active(io);
+ }
+
+ return 0;
+}
+
+static snd_pcm_sframes_t snd_pcm_pipewire_pointer(snd_pcm_ioplug_t *io)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ if (pw->xrun_detected)
+ return -EPIPE;
+ if (pw->error < 0)
+ return pw->error;
+ if (io->buffer_size == 0)
+ return 0;
+#ifdef SND_PCM_IOPLUG_FLAG_BOUNDARY_WA
+ return pw->hw_ptr;
+#else
+ return pw->hw_ptr % io->buffer_size;
+#endif
+}
+
+static int snd_pcm_pipewire_delay(snd_pcm_ioplug_t *io, snd_pcm_sframes_t *delayp)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ uintptr_t seq1, seq2;
+ int64_t elapsed = 0, delay, now, avail;
+ struct timespec ts;
+ int64_t diff;
+
+ do {
+ seq1 = SEQ_READ(pw->seq);
+
+ delay = pw->delay + pw->transfered;
+ now = pw->now;
+ if (io->stream == SND_PCM_STREAM_PLAYBACK)
+ avail = snd_pcm_ioplug_hw_avail(io, pw->hw_ptr, io->appl_ptr);
+ else
+ avail = snd_pcm_ioplug_avail(io, pw->hw_ptr, io->appl_ptr);
+
+ seq2 = SEQ_READ(pw->seq);
+ } while (!SEQ_READ_SUCCESS(seq1, seq2));
+
+ if (now != 0 && (io->state == SND_PCM_STATE_RUNNING ||
+ io->state == SND_PCM_STATE_DRAINING)) {
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ diff = SPA_TIMESPEC_TO_NSEC(&ts) - now;
+ elapsed = (io->rate * diff) / SPA_NSEC_PER_SEC;
+
+ if (io->stream == SND_PCM_STREAM_PLAYBACK)
+ delay -= SPA_MIN(elapsed, delay);
+ else
+ delay += SPA_MIN(elapsed, (int64_t)io->buffer_size);
+ }
+
+ *delayp = delay + avail;
+
+ pw_log_trace("avail:%"PRIi64" filled %"PRIi64" elapsed:%"PRIi64" delay:%ld hw:%lu appl:%lu",
+ avail, delay, elapsed, *delayp, pw->hw_ptr, io->appl_ptr);
+
+ return 0;
+}
+
+static snd_pcm_uframes_t
+snd_pcm_pipewire_process(snd_pcm_pipewire_t *pw, struct pw_buffer *b,
+ snd_pcm_uframes_t *hw_avail,snd_pcm_uframes_t want)
+{
+ snd_pcm_ioplug_t *io = &pw->io;
+ snd_pcm_channel_area_t *pwareas;
+ snd_pcm_uframes_t xfer = 0;
+ snd_pcm_uframes_t nframes;
+ unsigned int channel;
+ struct spa_data *d;
+ void *ptr;
+ uint32_t bl, offset, size;
+
+ d = b->buffer->datas;
+ pwareas = alloca(io->channels * sizeof(snd_pcm_channel_area_t));
+
+ for (bl = 0; bl < pw->blocks; bl++) {
+ if (io->stream == SND_PCM_STREAM_PLAYBACK) {
+ size = SPA_MIN(d[bl].maxsize, pw->min_avail * pw->stride);
+ } else {
+ offset = SPA_MIN(d[bl].chunk->offset, d[bl].maxsize);
+ size = SPA_MIN(d[bl].chunk->size, d[bl].maxsize - offset);
+ }
+ want = SPA_MIN(want, size / pw->stride);
+ }
+ nframes = SPA_MIN(want, *hw_avail);
+
+ if (pw->blocks == 1) {
+ if (io->stream == SND_PCM_STREAM_PLAYBACK) {
+ d[0].chunk->size = want * pw->stride;
+ d[0].chunk->offset = offset = 0;
+ } else {
+ offset = SPA_MIN(d[0].chunk->offset, d[0].maxsize);
+ }
+ ptr = SPA_PTROFF(d[0].data, offset, void);
+ for (channel = 0; channel < io->channels; channel++) {
+ pwareas[channel].addr = ptr;
+ pwareas[channel].first = channel * pw->sample_bits;
+ pwareas[channel].step = io->channels * pw->sample_bits;
+ }
+ } else {
+ for (channel = 0; channel < io->channels; channel++) {
+ if (io->stream == SND_PCM_STREAM_PLAYBACK) {
+ d[channel].chunk->size = want * pw->stride;
+ d[channel].chunk->offset = offset = 0;
+ } else {
+ offset = SPA_MIN(d[channel].chunk->offset, d[channel].maxsize);
+ }
+ ptr = SPA_PTROFF(d[channel].data, offset, void);
+ pwareas[channel].addr = ptr;
+ pwareas[channel].first = 0;
+ pwareas[channel].step = pw->sample_bits;
+ }
+ }
+
+ if (io->state == SND_PCM_STATE_RUNNING ||
+ io->state == SND_PCM_STATE_DRAINING) {
+ snd_pcm_uframes_t hw_ptr = pw->hw_ptr;
+ xfer = nframes;
+ if (xfer > 0) {
+ const snd_pcm_channel_area_t *areas = snd_pcm_ioplug_mmap_areas(io);
+ const snd_pcm_uframes_t offset = hw_ptr % io->buffer_size;
+
+ if (io->stream == SND_PCM_STREAM_PLAYBACK)
+ snd_pcm_areas_copy_wrap(pwareas, 0, nframes,
+ areas, offset,
+ io->buffer_size,
+ io->channels, xfer,
+ io->format);
+ else
+ snd_pcm_areas_copy_wrap(areas, offset,
+ io->buffer_size,
+ pwareas, 0, nframes,
+ io->channels, xfer,
+ io->format);
+
+ hw_ptr += xfer;
+ if (hw_ptr >= pw->boundary)
+ hw_ptr -= pw->boundary;
+ pw->hw_ptr = hw_ptr;
+ *hw_avail -= xfer;
+ }
+ }
+ /* check if requested frames were copied */
+ if (xfer < want) {
+ /* always fill the not yet written PipeWire buffer with silence */
+ if (io->stream == SND_PCM_STREAM_PLAYBACK) {
+ const snd_pcm_uframes_t frames = want - xfer;
+
+ snd_pcm_areas_silence(pwareas, xfer, io->channels,
+ frames, io->format);
+ xfer += frames;
+ }
+ if (io->state == SND_PCM_STATE_RUNNING ||
+ io->state == SND_PCM_STATE_DRAINING) {
+ /* report Xrun to user application */
+ pw->xrun_detected = true;
+ }
+ }
+ return xfer;
+}
+
+static void on_stream_param_changed(void *data, uint32_t id, const struct spa_pod *param)
+{
+ snd_pcm_pipewire_t *pw = data;
+ snd_pcm_ioplug_t *io = &pw->io;
+ const struct spa_pod *params[4];
+ uint32_t n_params = 0;
+ uint8_t buffer[4096];
+ struct spa_pod_builder b = SPA_POD_BUILDER_INIT(buffer, sizeof(buffer));
+ uint32_t buffers, size;
+
+ if (param == NULL || id != SPA_PARAM_Format)
+ return;
+
+ io->period_size = pw->min_avail;
+
+ buffers = SPA_CLAMP(io->buffer_size / io->period_size, MIN_BUFFERS, MAX_BUFFERS);
+ size = io->period_size * pw->stride;
+
+ pw_log_info("%p: buffer_size:%lu period_size:%lu buffers:%u size:%u min_avail:%lu",
+ pw, io->buffer_size, io->period_size, buffers, size, pw->min_avail);
+
+ params[n_params++] = spa_pod_builder_add_object(&b,
+ SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers,
+ SPA_PARAM_BUFFERS_buffers, SPA_POD_CHOICE_RANGE_Int(buffers, MIN_BUFFERS, MAX_BUFFERS),
+ SPA_PARAM_BUFFERS_blocks, SPA_POD_Int(pw->blocks),
+ SPA_PARAM_BUFFERS_size, SPA_POD_CHOICE_RANGE_Int(size, size, INT_MAX),
+ SPA_PARAM_BUFFERS_stride, SPA_POD_Int(pw->stride));
+
+ pw_stream_update_params(pw->stream, params, n_params);
+}
+
+static void on_stream_drained(void *data)
+{
+ snd_pcm_pipewire_t *pw = data;
+ pw->drained = true;
+ pw->draining = false;
+ pw_log_debug("%p: drained", pw);
+ pw_thread_loop_signal(pw->main_loop, false);
+}
+
+static void on_stream_process(void *data)
+{
+ snd_pcm_pipewire_t *pw = data;
+ snd_pcm_ioplug_t *io = &pw->io;
+ struct pw_buffer *b;
+ snd_pcm_uframes_t hw_avail, before, want, xfer;
+ struct pw_time pwt;
+ int64_t delay;
+
+ pw_stream_get_time_n(pw->stream, &pwt, sizeof(pwt));
+
+ delay = pwt.delay;
+ if (pwt.rate.num != 0)
+ delay = delay * io->rate * pwt.rate.num / pwt.rate.denom;
+
+ before = hw_avail = snd_pcm_ioplug_hw_avail(io, pw->hw_ptr, io->appl_ptr);
+
+ if (pw->drained)
+ goto done;
+
+ b = pw_stream_dequeue_buffer(pw->stream);
+ if (b == NULL)
+ return;
+
+ want = b->requested ? b->requested : hw_avail;
+
+ SEQ_WRITE(pw->seq);
+
+ if (pw->now != pwt.now) {
+ pw->transfered = pw->buffered;
+ pw->buffered = 0;
+ }
+
+ xfer = snd_pcm_pipewire_process(pw, b, &hw_avail, want);
+
+ pw->delay = delay;
+ /* the buffer is now queued in the stream and consumed */
+ if (io->stream == SND_PCM_STREAM_PLAYBACK)
+ pw->transfered += xfer;
+
+ /* more then requested data transfered, use them in next iteration */
+ pw->buffered = (want == 0 || pw->transfered < want) ? 0 : (pw->transfered % want);
+
+ pw->now = pwt.now;
+ SEQ_WRITE(pw->seq);
+
+ pw_log_trace("%p: avail-before:%lu avail:%lu want:%lu xfer:%lu hw:%lu appl:%lu",
+ pw, before, hw_avail, want, xfer, pw->hw_ptr, io->appl_ptr);
+
+ pw_stream_queue_buffer(pw->stream, b);
+
+ if (io->state == SND_PCM_STATE_DRAINING && !pw->draining && hw_avail == 0) {
+ if (io->stream == SND_PCM_STREAM_CAPTURE) {
+ on_stream_drained (pw); /* since pw_stream does not call drained() for capture */
+ } else {
+ pw_stream_flush(pw->stream, true);
+ pw->draining = true;
+ pw->drained = false;
+ }
+ }
+done:
+ update_active(io);
+}
+
+static const struct pw_stream_events stream_events = {
+ PW_VERSION_STREAM_EVENTS,
+ .param_changed = on_stream_param_changed,
+ .process = on_stream_process,
+ .drained = on_stream_drained,
+};
+
+static int pipewire_start(snd_pcm_pipewire_t *pw)
+{
+ if (!pw->activated && pw->stream != NULL) {
+ pw_stream_set_active(pw->stream, true);
+ pw->activated = true;
+ }
+ return 0;
+}
+
+static int snd_pcm_pipewire_drain(snd_pcm_ioplug_t *io)
+{
+ int res;
+ snd_pcm_pipewire_t *pw = io->private_data;
+
+ pw_thread_loop_lock(pw->main_loop);
+ pw_log_debug("%p: drain", pw);
+ pw->drained = false;
+ pw->draining = false;
+ pipewire_start(pw);
+ while (!pw->drained && pw->error >= 0 && pw->activated) {
+ pw_thread_loop_wait(pw->main_loop);
+ }
+ res = pw->error;
+ pw_thread_loop_unlock(pw->main_loop);
+ return res;
+}
+
+static int snd_pcm_pipewire_prepare(snd_pcm_ioplug_t *io)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ snd_pcm_sw_params_t *swparams;
+ const struct spa_pod *params[1];
+ uint8_t buffer[1024];
+ struct spa_pod_builder b = SPA_POD_BUILDER_INIT(buffer, sizeof(buffer));
+ uint32_t min_period;
+
+ pw_thread_loop_lock(pw->main_loop);
+
+ snd_pcm_sw_params_alloca(&swparams);
+ if (snd_pcm_sw_params_current(io->pcm, swparams) == 0) {
+ snd_pcm_sw_params_get_avail_min(swparams, &pw->min_avail);
+ snd_pcm_sw_params_get_boundary(swparams, &pw->boundary);
+ snd_pcm_sw_params_dump(swparams, pw->output);
+ fflush(pw->log_file);
+ } else {
+ pw->min_avail = io->period_size;
+ pw->boundary = io->buffer_size;
+ }
+
+ min_period = (MIN_PERIOD * io->rate / 48000);
+ pw->min_avail = SPA_MAX(pw->min_avail, min_period);
+
+ pw_log_debug("%p: prepare error:%d stream:%p buffer-size:%lu "
+ "period-size:%lu min-avail:%ld", pw, pw->error,
+ pw->stream, io->buffer_size, io->period_size, pw->min_avail);
+
+ if (pw->error >= 0 && pw->stream != NULL && !pw->hw_params_changed)
+ goto done;
+ pw->hw_params_changed = false;
+
+ pw_properties_setf(pw->props, PW_KEY_NODE_LATENCY, "%lu/%u", pw->min_avail, io->rate);
+ pw_properties_setf(pw->props, PW_KEY_NODE_RATE, "1/%u", io->rate);
+
+ params[0] = spa_format_audio_raw_build(&b, SPA_PARAM_EnumFormat, &pw->format);
+
+ if (pw->stream != NULL) {
+ pw_stream_update_properties(pw->stream, &pw->props->dict);
+ pw_stream_update_params(pw->stream, params, 1);
+ goto done;
+ }
+
+ pw->stream = pw_stream_new(pw->core, NULL, pw_properties_copy(pw->props));
+ if (pw->stream == NULL)
+ goto error;
+
+ pw_stream_add_listener(pw->stream, &pw->stream_listener, &stream_events, pw);
+
+ pw->error = 0;
+
+ pw_stream_connect(pw->stream,
+ io->stream == SND_PCM_STREAM_PLAYBACK ?
+ PW_DIRECTION_OUTPUT :
+ PW_DIRECTION_INPUT,
+ PW_ID_ANY,
+ PW_STREAM_FLAG_AUTOCONNECT |
+ PW_STREAM_FLAG_MAP_BUFFERS |
+ PW_STREAM_FLAG_RT_PROCESS,
+ params, 1);
+
+done:
+ pw->hw_ptr = 0;
+ pw->now = 0;
+ pw->xrun_detected = false;
+ pw->drained = false;
+ pw->draining = false;
+
+ pw_thread_loop_unlock(pw->main_loop);
+
+ return 0;
+
+error:
+ pw_thread_loop_unlock(pw->main_loop);
+ return -ENOMEM;
+}
+
+static int snd_pcm_pipewire_start(snd_pcm_ioplug_t *io)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+
+ pw_thread_loop_lock(pw->main_loop);
+ pw_log_debug("%p: start", pw);
+ pipewire_start(pw);
+ pw_thread_loop_unlock(pw->main_loop);
+ return 0;
+}
+
+static int snd_pcm_pipewire_stop(snd_pcm_ioplug_t *io)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+
+ pw_log_debug("%p: stop", pw);
+ update_active(io);
+
+ pw_thread_loop_lock(pw->main_loop);
+ if (pw->activated && pw->stream != NULL) {
+ pw_stream_set_active(pw->stream, false);
+ pw->activated = false;
+ }
+ pw_thread_loop_unlock(pw->main_loop);
+ return 0;
+}
+
+static int snd_pcm_pipewire_pause(snd_pcm_ioplug_t * io, int enable)
+{
+ pw_log_debug("%p: pause", io);
+
+ if (enable)
+ snd_pcm_pipewire_stop(io);
+ else
+ snd_pcm_pipewire_start(io);
+
+ return 0;
+}
+
+#if __BYTE_ORDER == __BIG_ENDIAN
+#define _FORMAT_LE(p, fmt) p ? SPA_AUDIO_FORMAT_UNKNOWN : SPA_AUDIO_FORMAT_ ## fmt ## _OE
+#define _FORMAT_BE(p, fmt) p ? SPA_AUDIO_FORMAT_ ## fmt ## P : SPA_AUDIO_FORMAT_ ## fmt
+#elif __BYTE_ORDER == __LITTLE_ENDIAN
+#define _FORMAT_LE(p, fmt) p ? SPA_AUDIO_FORMAT_ ## fmt ## P : SPA_AUDIO_FORMAT_ ## fmt
+#define _FORMAT_BE(p, fmt) p ? SPA_AUDIO_FORMAT_UNKNOWN : SPA_AUDIO_FORMAT_ ## fmt ## _OE
+#endif
+
+static int set_default_channels(struct spa_audio_info_raw *info)
+{
+ switch (info->channels) {
+ case 8:
+ info->position[6] = SPA_AUDIO_CHANNEL_SL;
+ info->position[7] = SPA_AUDIO_CHANNEL_SR;
+ SPA_FALLTHROUGH
+ case 6:
+ info->position[5] = SPA_AUDIO_CHANNEL_LFE;
+ SPA_FALLTHROUGH
+ case 5:
+ info->position[4] = SPA_AUDIO_CHANNEL_FC;
+ SPA_FALLTHROUGH
+ case 4:
+ info->position[2] = SPA_AUDIO_CHANNEL_RL;
+ info->position[3] = SPA_AUDIO_CHANNEL_RR;
+ SPA_FALLTHROUGH
+ case 2:
+ info->position[0] = SPA_AUDIO_CHANNEL_FL;
+ info->position[1] = SPA_AUDIO_CHANNEL_FR;
+ return 1;
+ case 1:
+ info->position[0] = SPA_AUDIO_CHANNEL_MONO;
+ return 1;
+ default:
+ return 0;
+ }
+}
+
+static int snd_pcm_pipewire_hw_params(snd_pcm_ioplug_t * io,
+ snd_pcm_hw_params_t * params)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ bool planar;
+
+ snd_pcm_hw_params_dump(params, pw->output);
+ fflush(pw->log_file);
+
+ pw_log_debug("%p: hw_params buffer_size:%lu period_size:%lu", pw, io->buffer_size, io->period_size);
+
+ switch(io->access) {
+ case SND_PCM_ACCESS_MMAP_INTERLEAVED:
+ case SND_PCM_ACCESS_RW_INTERLEAVED:
+ planar = false;
+ break;
+ case SND_PCM_ACCESS_MMAP_NONINTERLEAVED:
+ case SND_PCM_ACCESS_RW_NONINTERLEAVED:
+ planar = true;
+ break;
+ default:
+ SNDERR("PipeWire: invalid access: %d\n", io->access);
+ return -EINVAL;
+ }
+
+ switch(io->format) {
+ case SND_PCM_FORMAT_U8:
+ pw->format.format = planar ? SPA_AUDIO_FORMAT_U8P : SPA_AUDIO_FORMAT_U8;
+ break;
+ case SND_PCM_FORMAT_S16_LE:
+ pw->format.format = _FORMAT_LE(planar, S16);
+ break;
+ case SND_PCM_FORMAT_S16_BE:
+ pw->format.format = _FORMAT_BE(planar, S16);
+ break;
+ case SND_PCM_FORMAT_S24_LE:
+ pw->format.format = _FORMAT_LE(planar, S24_32);
+ break;
+ case SND_PCM_FORMAT_S24_BE:
+ pw->format.format = _FORMAT_BE(planar, S24_32);
+ break;
+ case SND_PCM_FORMAT_S32_LE:
+ pw->format.format = _FORMAT_LE(planar, S32);
+ break;
+ case SND_PCM_FORMAT_S32_BE:
+ pw->format.format = _FORMAT_BE(planar, S32);
+ break;
+ case SND_PCM_FORMAT_S24_3LE:
+ pw->format.format = _FORMAT_LE(planar, S24);
+ break;
+ case SND_PCM_FORMAT_S24_3BE:
+ pw->format.format = _FORMAT_BE(planar, S24);
+ break;
+ case SND_PCM_FORMAT_FLOAT_LE:
+ pw->format.format = _FORMAT_LE(planar, F32);
+ break;
+ case SND_PCM_FORMAT_FLOAT_BE:
+ pw->format.format = _FORMAT_BE(planar, F32);
+ break;
+ default:
+ SNDERR("PipeWire: invalid format: %d\n", io->format);
+ return -EINVAL;
+ }
+ pw->format.channels = io->channels;
+ pw->format.rate = io->rate;
+
+ set_default_channels(&pw->format);
+
+ pw->sample_bits = snd_pcm_format_physical_width(io->format);
+ if (planar) {
+ pw->blocks = io->channels;
+ pw->stride = pw->sample_bits / 8;
+ } else {
+ pw->blocks = 1;
+ pw->stride = (io->channels * pw->sample_bits) / 8;
+ }
+ pw->hw_params_changed = true;
+ pw_log_info("%p: format:%s channels:%d rate:%d stride:%d blocks:%d", pw,
+ spa_debug_type_find_name(spa_type_audio_format, pw->format.format),
+ io->channels, io->rate, pw->stride, pw->blocks);
+
+ return 0;
+}
+
+static int snd_pcm_pipewire_sw_params(snd_pcm_ioplug_t * io,
+ snd_pcm_sw_params_t * sw_params)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+
+ pw_thread_loop_lock(pw->main_loop);
+ if (pw->stream) {
+ snd_pcm_uframes_t min_avail;
+ snd_pcm_sw_params_get_avail_min( sw_params, &min_avail);
+ snd_pcm_sw_params_get_boundary(sw_params, &pw->boundary);
+ if (min_avail != pw->min_avail) {
+ char latency[64];
+ struct spa_dict_item item[1];
+ uint32_t min_period = (MIN_PERIOD * io->rate / 48000);
+
+ pw->min_avail = SPA_MAX(min_avail, min_period);
+
+ spa_scnprintf(latency, sizeof(latency), "%lu/%u", pw->min_avail, io->rate);
+ item[0] = SPA_DICT_ITEM_INIT(PW_KEY_NODE_LATENCY, latency);
+
+ pw_log_debug("%p: sw_params update props %p %ld", pw, pw->stream, pw->min_avail);
+ pw_stream_update_properties(pw->stream, &SPA_DICT_INIT(item, 1));
+ }
+ } else {
+ pw_log_debug("%p: sw_params pre-prepare noop", pw);
+ }
+ pw_thread_loop_unlock(pw->main_loop);
+
+ return 0;
+}
+
+struct chmap_info {
+ enum snd_pcm_chmap_position pos;
+ enum spa_audio_channel channel;
+};
+
+static const struct chmap_info chmap_info[] = {
+ [SND_CHMAP_UNKNOWN] = { SND_CHMAP_UNKNOWN, SPA_AUDIO_CHANNEL_UNKNOWN },
+ [SND_CHMAP_NA] = { SND_CHMAP_NA, SPA_AUDIO_CHANNEL_NA },
+ [SND_CHMAP_MONO] = { SND_CHMAP_MONO, SPA_AUDIO_CHANNEL_MONO },
+ [SND_CHMAP_FL] = { SND_CHMAP_FL, SPA_AUDIO_CHANNEL_FL },
+ [SND_CHMAP_FR] = { SND_CHMAP_FR, SPA_AUDIO_CHANNEL_FR },
+ [SND_CHMAP_RL] = { SND_CHMAP_RL, SPA_AUDIO_CHANNEL_RL },
+ [SND_CHMAP_RR] = { SND_CHMAP_RR, SPA_AUDIO_CHANNEL_RR },
+ [SND_CHMAP_FC] = { SND_CHMAP_FC, SPA_AUDIO_CHANNEL_FC },
+ [SND_CHMAP_LFE] = { SND_CHMAP_LFE, SPA_AUDIO_CHANNEL_LFE },
+ [SND_CHMAP_SL] = { SND_CHMAP_SL, SPA_AUDIO_CHANNEL_SL },
+ [SND_CHMAP_SR] = { SND_CHMAP_SR, SPA_AUDIO_CHANNEL_SR },
+ [SND_CHMAP_RC] = { SND_CHMAP_RC, SPA_AUDIO_CHANNEL_RC },
+ [SND_CHMAP_FLC] = { SND_CHMAP_FLC, SPA_AUDIO_CHANNEL_FLC },
+ [SND_CHMAP_FRC] = { SND_CHMAP_FRC, SPA_AUDIO_CHANNEL_FRC },
+ [SND_CHMAP_RLC] = { SND_CHMAP_RLC, SPA_AUDIO_CHANNEL_RLC },
+ [SND_CHMAP_RRC] = { SND_CHMAP_RRC, SPA_AUDIO_CHANNEL_RRC },
+ [SND_CHMAP_FLW] = { SND_CHMAP_FLW, SPA_AUDIO_CHANNEL_FLW },
+ [SND_CHMAP_FRW] = { SND_CHMAP_FRW, SPA_AUDIO_CHANNEL_FRW },
+ [SND_CHMAP_FLH] = { SND_CHMAP_FLH, SPA_AUDIO_CHANNEL_FLH },
+ [SND_CHMAP_FCH] = { SND_CHMAP_FCH, SPA_AUDIO_CHANNEL_FCH },
+ [SND_CHMAP_FRH] = { SND_CHMAP_FRH, SPA_AUDIO_CHANNEL_FRH },
+ [SND_CHMAP_TC] = { SND_CHMAP_TC, SPA_AUDIO_CHANNEL_TC },
+ [SND_CHMAP_TFL] = { SND_CHMAP_TFL, SPA_AUDIO_CHANNEL_TFL },
+ [SND_CHMAP_TFR] = { SND_CHMAP_TFR, SPA_AUDIO_CHANNEL_TFR },
+ [SND_CHMAP_TFC] = { SND_CHMAP_TFC, SPA_AUDIO_CHANNEL_TFC },
+ [SND_CHMAP_TRL] = { SND_CHMAP_TRL, SPA_AUDIO_CHANNEL_TRL },
+ [SND_CHMAP_TRR] = { SND_CHMAP_TRR, SPA_AUDIO_CHANNEL_TRR },
+ [SND_CHMAP_TRC] = { SND_CHMAP_TRC, SPA_AUDIO_CHANNEL_TRC },
+ [SND_CHMAP_TFLC] = { SND_CHMAP_TFLC, SPA_AUDIO_CHANNEL_TFLC },
+ [SND_CHMAP_TFRC] = { SND_CHMAP_TFRC, SPA_AUDIO_CHANNEL_TFRC },
+ [SND_CHMAP_TSL] = { SND_CHMAP_TSL, SPA_AUDIO_CHANNEL_TSL },
+ [SND_CHMAP_TSR] = { SND_CHMAP_TSR, SPA_AUDIO_CHANNEL_TSR },
+ [SND_CHMAP_LLFE] = { SND_CHMAP_LLFE, SPA_AUDIO_CHANNEL_LLFE },
+ [SND_CHMAP_RLFE] = { SND_CHMAP_RLFE, SPA_AUDIO_CHANNEL_RLFE },
+ [SND_CHMAP_BC] = { SND_CHMAP_BC, SPA_AUDIO_CHANNEL_BC },
+ [SND_CHMAP_BLC] = { SND_CHMAP_BLC, SPA_AUDIO_CHANNEL_BLC },
+ [SND_CHMAP_BRC] = { SND_CHMAP_BRC, SPA_AUDIO_CHANNEL_BRC },
+};
+
+static enum snd_pcm_chmap_position channel_to_chmap(enum spa_audio_channel channel)
+{
+ SPA_FOR_EACH_ELEMENT_VAR(chmap_info, info)
+ if (info->channel == channel)
+ return info->pos;
+ return SND_CHMAP_UNKNOWN;
+}
+
+static enum spa_audio_channel chmap_to_channel(enum snd_pcm_chmap_position pos)
+{
+ if (pos >= SPA_N_ELEMENTS(chmap_info))
+ return SPA_AUDIO_CHANNEL_UNKNOWN;
+ return chmap_info[pos].channel;
+}
+
+static int snd_pcm_pipewire_set_chmap(snd_pcm_ioplug_t * io,
+ const snd_pcm_chmap_t * map)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ unsigned int i;
+
+ pw->format.channels = map->channels;
+ for (i = 0; i < map->channels; i++) {
+ pw->format.position[i] = chmap_to_channel(map->pos[i]);
+ pw_log_debug("map %d: %s / %s", i,
+ snd_pcm_chmap_name(map->pos[i]),
+ spa_debug_type_find_short_name(spa_type_audio_channel,
+ pw->format.position[i]));
+ }
+ return 1;
+}
+
+static snd_pcm_chmap_t * snd_pcm_pipewire_get_chmap(snd_pcm_ioplug_t * io)
+{
+ snd_pcm_pipewire_t *pw = io->private_data;
+ snd_pcm_chmap_t *map;
+ uint32_t i;
+
+ map = calloc(1, sizeof(snd_pcm_chmap_t) +
+ pw->format.channels * sizeof(unsigned int));
+ map->channels = pw->format.channels;
+ for (i = 0; i < pw->format.channels; i++)
+ map->pos[i] = channel_to_chmap(pw->format.position[i]);
+
+ return map;
+}
+
+static void make_map(snd_pcm_chmap_query_t **maps, int index, int channels, ...)
+{
+ va_list args;
+ int i;
+
+ maps[index] = malloc(sizeof(snd_pcm_chmap_query_t) + (channels * sizeof(unsigned int)));
+ maps[index]->type = SND_CHMAP_TYPE_FIXED;
+ maps[index]->map.channels = channels;
+ va_start(args, channels);
+ for (i = 0; i < channels; i++)
+ maps[index]->map.pos[i] = va_arg(args, int);
+ va_end(args);
+}
+
+static snd_pcm_chmap_query_t **snd_pcm_pipewire_query_chmaps(snd_pcm_ioplug_t *io)
+{
+ snd_pcm_chmap_query_t **maps;
+
+ maps = calloc(7, sizeof(*maps));
+ make_map(maps, 0, 1, SND_CHMAP_MONO);
+ make_map(maps, 1, 2, SND_CHMAP_FL, SND_CHMAP_FR);
+ make_map(maps, 2, 4, SND_CHMAP_FL, SND_CHMAP_FR, SND_CHMAP_RL, SND_CHMAP_RR);
+ make_map(maps, 3, 5, SND_CHMAP_FL, SND_CHMAP_FR, SND_CHMAP_RL, SND_CHMAP_RR,
+ SND_CHMAP_FC);
+ make_map(maps, 4, 6, SND_CHMAP_FL, SND_CHMAP_FR, SND_CHMAP_RL, SND_CHMAP_RR,
+ SND_CHMAP_FC, SND_CHMAP_LFE);
+ make_map(maps, 5, 8, SND_CHMAP_FL, SND_CHMAP_FR, SND_CHMAP_RL, SND_CHMAP_RR,
+ SND_CHMAP_FC, SND_CHMAP_LFE, SND_CHMAP_SL, SND_CHMAP_SR);
+
+ return maps;
+}
+
+static snd_pcm_ioplug_callback_t pipewire_pcm_callback = {
+ .close = snd_pcm_pipewire_close,
+ .start = snd_pcm_pipewire_start,
+ .stop = snd_pcm_pipewire_stop,
+ .pause = snd_pcm_pipewire_pause,
+ .pointer = snd_pcm_pipewire_pointer,
+ .delay = snd_pcm_pipewire_delay,
+ .drain = snd_pcm_pipewire_drain,
+ .prepare = snd_pcm_pipewire_prepare,
+ .poll_descriptors = snd_pcm_pipewire_poll_descriptors,
+ .poll_revents = snd_pcm_pipewire_poll_revents,
+ .hw_params = snd_pcm_pipewire_hw_params,
+ .sw_params = snd_pcm_pipewire_sw_params,
+ .set_chmap = snd_pcm_pipewire_set_chmap,
+ .get_chmap = snd_pcm_pipewire_get_chmap,
+ .query_chmaps = snd_pcm_pipewire_query_chmaps,
+};
+
+static int pipewire_set_hw_constraint(snd_pcm_pipewire_t *pw)
+{
+ unsigned int access_list[] = {
+ SND_PCM_ACCESS_MMAP_INTERLEAVED,
+ SND_PCM_ACCESS_MMAP_NONINTERLEAVED,
+ SND_PCM_ACCESS_RW_INTERLEAVED,
+ SND_PCM_ACCESS_RW_NONINTERLEAVED
+ };
+ unsigned int format_list[] = {
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+ SND_PCM_FORMAT_FLOAT_LE,
+ SND_PCM_FORMAT_S32_LE,
+ SND_PCM_FORMAT_S24_LE,
+ SND_PCM_FORMAT_S24_3LE,
+ SND_PCM_FORMAT_S24_3BE,
+ SND_PCM_FORMAT_S16_LE,
+#elif __BYTE_ORDER == __BIG_ENDIAN
+ SND_PCM_FORMAT_FLOAT_BE,
+ SND_PCM_FORMAT_S32_BE,
+ SND_PCM_FORMAT_S24_BE,
+ SND_PCM_FORMAT_S24_3LE,
+ SND_PCM_FORMAT_S24_3BE,
+ SND_PCM_FORMAT_S16_BE,
+#endif
+ SND_PCM_FORMAT_U8,
+ };
+ int val;
+ int min_rate;
+ int max_rate;
+ int min_channels;
+ int max_channels;
+ int min_period_bytes;
+ int max_period_bytes;
+ int min_buffer_bytes;
+ int max_buffer_bytes;
+ const char *str;
+ snd_pcm_format_t format;
+ int err;
+
+ val = pw_properties_get_uint32(pw->props, "alsa.rate", 0);
+ if (val > 0) {
+ min_rate = max_rate = SPA_CLAMP(val, 1, MAX_RATE);
+ } else {
+ min_rate = 1;
+ max_rate = MAX_RATE;
+ }
+ val = pw_properties_get_uint32(pw->props, "alsa.channels", 0);
+ if (val > 0) {
+ min_channels = max_channels = SPA_CLAMP(val, 1, MAX_CHANNELS);
+ } else {
+ min_channels = 1;
+ max_channels = MAX_CHANNELS;
+ }
+ val = pw_properties_get_uint32(pw->props, "alsa.period-bytes", 0);
+ if (val > 0) {
+ min_period_bytes = max_period_bytes = SPA_CLAMP(val,
+ MIN_PERIOD_BYTES, MAX_PERIOD_BYTES);
+ } else {
+ min_period_bytes = MIN_PERIOD_BYTES;
+ max_period_bytes = MAX_PERIOD_BYTES;
+ }
+ val = pw_properties_get_uint32(pw->props, "alsa.buffer-bytes", 0);
+ if (val > 0) {
+ min_buffer_bytes = max_buffer_bytes = SPA_CLAMP(val,
+ MIN_BUFFER_BYTES, MAX_BUFFER_BYTES);
+ } else {
+ min_buffer_bytes = MIN_BUFFER_BYTES;
+ max_buffer_bytes = MAX_BUFFER_BYTES;
+ }
+ if (min_period_bytes * 2 > max_buffer_bytes)
+ min_period_bytes = max_period_bytes = max_buffer_bytes / 2;
+
+ if ((err = snd_pcm_ioplug_set_param_list(&pw->io, SND_PCM_IOPLUG_HW_ACCESS,
+ SPA_N_ELEMENTS(access_list), access_list)) < 0 ||
+ (err = snd_pcm_ioplug_set_param_minmax(&pw->io, SND_PCM_IOPLUG_HW_CHANNELS,
+ min_channels, max_channels)) < 0 ||
+ (err = snd_pcm_ioplug_set_param_minmax(&pw->io, SND_PCM_IOPLUG_HW_RATE,
+ min_rate, max_rate)) < 0 ||
+ (err = snd_pcm_ioplug_set_param_minmax(&pw->io, SND_PCM_IOPLUG_HW_BUFFER_BYTES,
+ min_buffer_bytes,
+ max_buffer_bytes)) < 0 ||
+ (err = snd_pcm_ioplug_set_param_minmax(&pw->io,
+ SND_PCM_IOPLUG_HW_PERIOD_BYTES,
+ min_period_bytes,
+ max_period_bytes)) < 0 ||
+ (err = snd_pcm_ioplug_set_param_minmax(&pw->io, SND_PCM_IOPLUG_HW_PERIODS,
+ MIN_BUFFERS, 1024)) < 0) {
+ pw_log_warn("Can't set param list: %s", snd_strerror(err));
+ return err;
+ }
+ format = SND_PCM_FORMAT_UNKNOWN;
+ if ((str = pw_properties_get(pw->props, "alsa.format")))
+ format = snd_pcm_format_value(str);
+
+ if (format != SND_PCM_FORMAT_UNKNOWN) {
+ err = snd_pcm_ioplug_set_param_list(&pw->io,
+ SND_PCM_IOPLUG_HW_FORMAT,
+ 1, (unsigned int *)&format);
+ if (err < 0) {
+ pw_log_warn("Can't set param list: %s", snd_strerror(err));
+ return err;
+ }
+ } else {
+ err = snd_pcm_ioplug_set_param_list(&pw->io,
+ SND_PCM_IOPLUG_HW_FORMAT,
+ SPA_N_ELEMENTS(format_list),
+ format_list);
+ if (err < 0) {
+ pw_log_warn("Can't set param list: %s", snd_strerror(err));
+ return err;
+ }
+ }
+ return 0;
+}
+
+static void on_core_error(void *data, uint32_t id, int seq, int res, const char *message)
+{
+ snd_pcm_pipewire_t *pw = data;
+
+ pw_log_warn("%p: error id:%u seq:%d res:%d (%s): %s", pw,
+ id, seq, res, spa_strerror(res), message);
+
+ if (id == PW_ID_CORE) {
+ pw->error = res;
+ if (pw->fd != -1)
+ update_active(&pw->io);
+ }
+ pw_thread_loop_signal(pw->main_loop, false);
+}
+
+static const struct pw_core_events core_events = {
+ PW_VERSION_CORE_EVENTS,
+ .error = on_core_error,
+};
+
+
+static ssize_t log_write(void *cookie, const char *buf, size_t size)
+{
+ int len;
+
+ while (size > 0) {
+ len = strcspn(buf, "\n");
+ if (len > 0)
+ pw_log_debug("%.*s", (int)len, buf);
+ buf += len + 1;
+ size -= len + 1;
+ }
+ return size;
+}
+
+static cookie_io_functions_t io_funcs = {
+ .write = log_write,
+};
+
+static int execute_match(void *data, const char *location, const char *action,
+ const char *val, size_t len)
+{
+ snd_pcm_pipewire_t *pw = data;
+ if (spa_streq(action, "update-props"))
+ pw_properties_update_string(pw->props, val, len);
+ return 1;
+}
+
+static int snd_pcm_pipewire_open(snd_pcm_t **pcmp,
+ struct pw_properties *props, snd_pcm_stream_t stream, int mode)
+{
+ snd_pcm_pipewire_t *pw;
+ int err;
+ const char *str, *node_name = NULL;
+ struct pw_loop *loop;
+
+ assert(pcmp);
+ pw = calloc(1, sizeof(*pw));
+ if (!pw)
+ return -ENOMEM;
+
+ pw->props = props;
+ pw->fd = -1;
+ pw->io.poll_fd = -1;
+ pw->log_file = fopencookie(pw, "w", io_funcs);
+ if (pw->log_file == NULL) {
+ pw_log_error("can't create log file: %m");
+ err = -errno;
+ goto error;
+ }
+ if ((err = snd_output_stdio_attach(&pw->output, pw->log_file, 0)) < 0) {
+ pw_log_error("can't attach log file: %s", snd_strerror(err));
+ goto error;
+ }
+
+ pw->main_loop = pw_thread_loop_new("alsa-pipewire", NULL);
+ if (pw->main_loop == NULL) {
+ err = -errno;
+ goto error;
+ }
+ loop = pw_thread_loop_get_loop(pw->main_loop);
+ pw->system = loop->system;
+ if ((pw->context = pw_context_new(loop,
+ pw_properties_new(
+ PW_KEY_CONFIG_NAME, "client-rt.conf",
+ PW_KEY_CLIENT_API, "alsa",
+ NULL),
+ 0)) == NULL) {
+ err = -errno;
+ goto error;
+ }
+
+ pw_context_conf_update_props(pw->context, "alsa.properties", pw->props);
+
+ pw_context_conf_section_match_rules(pw->context, "alsa.rules",
+ &pw_context_get_properties(pw->context)->dict, execute_match, pw);
+
+ if (pw_properties_get(pw->props, PW_KEY_APP_NAME) == NULL)
+ pw_properties_setf(pw->props, PW_KEY_APP_NAME, "PipeWire ALSA [%s]",
+ pw_get_prgname());
+ if (pw_properties_get(pw->props, PW_KEY_NODE_NAME) == NULL)
+ pw_properties_setf(pw->props, PW_KEY_NODE_NAME, "ALSA %s",
+ stream == SND_PCM_STREAM_PLAYBACK ? "Playback" : "Capture");
+ if (pw_properties_get(pw->props, PW_KEY_MEDIA_TYPE) == NULL)
+ pw_properties_set(pw->props, PW_KEY_MEDIA_TYPE, "Audio");
+ if (pw_properties_get(pw->props, PW_KEY_MEDIA_CATEGORY) == NULL)
+ pw_properties_set(pw->props, PW_KEY_MEDIA_CATEGORY,
+ stream == SND_PCM_STREAM_PLAYBACK ?
+ "Playback" : "Capture");
+
+ str = getenv("PIPEWIRE_ALSA");
+ if (str != NULL)
+ pw_properties_update_string(pw->props, str, strlen(str));
+
+ str = getenv("PIPEWIRE_NODE");
+ if (str != NULL && str[0])
+ pw_properties_set(pw->props, PW_KEY_TARGET_OBJECT, str);
+
+ node_name = pw_properties_get(pw->props, PW_KEY_NODE_NAME);
+ if (pw_properties_get(pw->props, PW_KEY_MEDIA_NAME) == NULL)
+ pw_properties_set(pw->props, PW_KEY_MEDIA_NAME, node_name);
+
+ if ((err = pw_thread_loop_start(pw->main_loop)) < 0)
+ goto error;
+
+ pw_thread_loop_lock(pw->main_loop);
+ pw->core = pw_context_connect(pw->context, pw_properties_copy(pw->props), 0);
+ if (pw->core == NULL) {
+ err = -errno;
+ pw_thread_loop_unlock(pw->main_loop);
+ goto error;
+ }
+ pw_core_add_listener(pw->core, &pw->core_listener, &core_events, pw);
+ pw_thread_loop_unlock(pw->main_loop);
+
+ pw->fd = spa_system_eventfd_create(pw->system, SPA_FD_CLOEXEC | SPA_FD_NONBLOCK);
+
+ pw->io.version = SND_PCM_IOPLUG_VERSION;
+ pw->io.name = "ALSA <-> PipeWire PCM I/O Plugin";
+ pw->io.callback = &pipewire_pcm_callback;
+ pw->io.private_data = pw;
+ pw->io.poll_fd = pw->fd;
+ pw->io.poll_events = POLLIN;
+ pw->io.mmap_rw = 1;
+#ifdef SND_PCM_IOPLUG_FLAG_BOUNDARY_WA
+ pw->io.flags = SND_PCM_IOPLUG_FLAG_BOUNDARY_WA;
+#else
+#warning hw_ptr updates of buffer_size will not be recognized by the ALSA library. Consider to update your ALSA library.
+#endif
+ pw->io.flags |= SND_PCM_IOPLUG_FLAG_MONOTONIC;
+
+ if ((err = snd_pcm_ioplug_create(&pw->io, node_name, stream, mode)) < 0)
+ goto error;
+
+ if ((err = pipewire_set_hw_constraint(pw)) < 0)
+ goto error;
+
+ pw_log_debug("%p: opened name:%s stream:%s mode:%d", pw, node_name,
+ snd_pcm_stream_name(pw->io.stream), mode);
+
+ *pcmp = pw->io.pcm;
+
+ return 0;
+
+error:
+ pw_log_debug("%p: failed to open %s :%s", pw, node_name, spa_strerror(err));
+ snd_pcm_pipewire_free(pw);
+ return err;
+}
+
+
+SPA_EXPORT
+SND_PCM_PLUGIN_DEFINE_FUNC(pipewire)
+{
+ snd_config_iterator_t i, next;
+ struct pw_properties *props;
+ const char *str;
+ long val;
+ int err;
+
+ pw_init(NULL, NULL);
+ if (strstr(pw_get_library_version(), "0.2") != NULL)
+ return -ENOTSUP;
+
+ props = pw_properties_new(NULL, NULL);
+ if (props == NULL)
+ return -errno;
+
+ PW_LOG_TOPIC_INIT(alsa_log_topic);
+
+ snd_config_for_each(i, next, conf) {
+ snd_config_t *n = snd_config_iterator_entry(i);
+ const char *id;
+ if (snd_config_get_id(n, &id) < 0)
+ continue;
+ if (spa_streq(id, "comment") || spa_streq(id, "type") || spa_streq(id, "hint"))
+ continue;
+ if (spa_streq(id, "name")) {
+ if (snd_config_get_string(n, &str) == 0)
+ pw_properties_set(props, PW_KEY_NODE_NAME, str);
+ continue;
+ }
+ if (spa_streq(id, "server")) {
+ if (snd_config_get_string(n, &str) == 0)
+ pw_properties_set(props, PW_KEY_REMOTE_NAME, str);
+ continue;
+ }
+ if (spa_streq(id, "playback_node")) {
+ if (stream == SND_PCM_STREAM_PLAYBACK &&
+ snd_config_get_string(n, &str) == 0)
+ if (str != NULL && !spa_streq(str, "-1"))
+ pw_properties_set(props, PW_KEY_TARGET_OBJECT, str);
+ continue;
+ }
+ if (spa_streq(id, "capture_node")) {
+ if (stream == SND_PCM_STREAM_CAPTURE &&
+ snd_config_get_string(n, &str) == 0)
+ if (str != NULL && !spa_streq(str, "-1"))
+ pw_properties_set(props, PW_KEY_TARGET_OBJECT, str);
+ continue;
+ }
+ if (spa_streq(id, "role")) {
+ if (snd_config_get_string(n, &str) == 0)
+ if (str != NULL && *str)
+ pw_properties_set(props, PW_KEY_MEDIA_ROLE, str);
+ continue;
+ }
+ if (spa_streq(id, "exclusive")) {
+ if (snd_config_get_bool(n))
+ pw_properties_set(props, PW_KEY_NODE_EXCLUSIVE, "true");
+ continue;
+ }
+ if (spa_streq(id, "rate")) {
+ if (snd_config_get_integer(n, &val) == 0) {
+ if (val != 0)
+ pw_properties_setf(props, "alsa.rate", "%ld", val);
+ } else {
+ SNDERR("%s: invalid type", id);
+ }
+ continue;
+ }
+ if (spa_streq(id, "format")) {
+ if (snd_config_get_string(n, &str) == 0) {
+ if (str != NULL && *str)
+ pw_properties_set(props, "alsa.format", str);
+ } else {
+ SNDERR("%s: invalid type", id);
+ }
+ continue;
+ }
+ if (spa_streq(id, "channels")) {
+ if (snd_config_get_integer(n, &val) == 0) {
+ if (val != 0)
+ pw_properties_setf(props, "alsa.channels", "%ld", val);
+ } else {
+ SNDERR("%s: invalid type", id);
+ }
+ continue;
+ }
+ if (spa_streq(id, "period_bytes")) {
+ if (snd_config_get_integer(n, &val) == 0) {
+ if (val != 0)
+ pw_properties_setf(props, "alsa.period-bytes", "%ld", val);
+ } else {
+ SNDERR("%s: invalid type", id);
+ }
+ continue;
+ }
+ if (spa_streq(id, "buffer_bytes")) {
+ long val;
+
+ if (snd_config_get_integer(n, &val) == 0) {
+ if (val != 0)
+ pw_properties_setf(props, "alsa.buffer-bytes", "%ld", val);
+ } else {
+ SNDERR("%s: invalid type", id);
+ }
+ continue;
+ }
+ SNDERR("Unknown field %s", id);
+ pw_properties_free(props);
+ return -EINVAL;
+ }
+
+ err = snd_pcm_pipewire_open(pcmp, props, stream, mode);
+
+ return err;
+}
+
+SPA_EXPORT
+SND_PCM_PLUGIN_SYMBOL(pipewire);