From 818fb9e904a3ea43ba313994e404f1b63833c548 Mon Sep 17 00:00:00 2001 From: Wim Taymans Date: Thu, 19 Sep 2019 16:57:00 +0200 Subject: [PATCH] alsa: add midi bridge Add a node that exposes all midi input and output ports and converts to and from PipeWire control streams. --- spa/include/spa/utils/names.h | 2 + spa/plugins/alsa/alsa-seq-source.c | 939 +++++++++++++++++++++++++++++ spa/plugins/alsa/alsa-seq.c | 773 ++++++++++++++++++++++++ spa/plugins/alsa/alsa-seq.h | 174 ++++++ spa/plugins/alsa/alsa.c | 4 + spa/plugins/alsa/meson.build | 2 + src/daemon/pipewire.conf.in | 1 + 7 files changed, 1895 insertions(+) create mode 100644 spa/plugins/alsa/alsa-seq-source.c create mode 100644 spa/plugins/alsa/alsa-seq.c create mode 100644 spa/plugins/alsa/alsa-seq.h diff --git a/spa/include/spa/utils/names.h b/spa/include/spa/utils/names.h index ff4cb77c0..43cbb808b 100644 --- a/spa/include/spa/utils/names.h +++ b/spa/include/spa/utils/names.h @@ -83,6 +83,8 @@ extern "C" { * capturing PCM */ #define SPA_NAME_API_ALSA_PCM_SINK "api.alsa.pcm.sink" /**< an alsa Node interface for * playback PCM */ +#define SPA_NAME_API_ALSA_MIDI_SOURCE "api.alsa.midi.source" /**< an alsa Node interface for + * capturing midi */ /** keys for bluez5 factory names */ #define SPA_NAME_API_BLUEZ5_MONITOR "api.bluez5.monitor" /**< a Monitor interface */ diff --git a/spa/plugins/alsa/alsa-seq-source.c b/spa/plugins/alsa/alsa-seq-source.c new file mode 100644 index 000000000..77ae55bbd --- /dev/null +++ b/spa/plugins/alsa/alsa-seq-source.c @@ -0,0 +1,939 @@ +/* Spa ALSA Source + * + * Copyright © 2018 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 +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#define NAME "alsa-source" + +#include "alsa-seq.h" + +static const char default_device[] = "default"; +static const uint32_t default_min_latency = 64; +static const uint32_t default_max_latency = 1024; + +static void reset_props(struct props *props) +{ + strncpy(props->device, default_device, 64); + props->min_latency = default_min_latency; + props->max_latency = default_max_latency; +} + +static int impl_node_enum_params(void *object, int seq, + uint32_t id, uint32_t start, uint32_t num, + const struct spa_pod *filter) +{ + struct seq_state *this = object; + struct spa_pod *param; + uint8_t buffer[1024]; + struct spa_pod_builder b = { 0 }; + struct props *p; + struct spa_result_node_params result; + uint32_t count = 0; + + spa_return_val_if_fail(this != NULL, -EINVAL); + spa_return_val_if_fail(num != 0, -EINVAL); + + p = &this->props; + + result.id = id; + result.next = start; + next: + result.index = result.next++; + + spa_pod_builder_init(&b, buffer, sizeof(buffer)); + + switch (id) { + case SPA_PARAM_PropInfo: + switch (result.index) { + case 0: + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_PropInfo, id, + SPA_PROP_INFO_id, SPA_POD_Id(SPA_PROP_device), + SPA_PROP_INFO_name, SPA_POD_String("The ALSA device"), + SPA_PROP_INFO_type, SPA_POD_Stringn(p->device, sizeof(p->device))); + break; + case 1: + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_PropInfo, id, + SPA_PROP_INFO_id, SPA_POD_Id(SPA_PROP_minLatency), + SPA_PROP_INFO_name, SPA_POD_String("The minimum latency"), + SPA_PROP_INFO_type, SPA_POD_CHOICE_RANGE_Int(p->min_latency, 1, INT32_MAX)); + break; + case 2: + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_PropInfo, id, + SPA_PROP_INFO_id, SPA_POD_Id(SPA_PROP_maxLatency), + SPA_PROP_INFO_name, SPA_POD_String("The maximum latency"), + SPA_PROP_INFO_type, SPA_POD_CHOICE_RANGE_Int(p->max_latency, 1, INT32_MAX)); + break; + default: + return 0; + } + break; + + case SPA_PARAM_Props: + switch (result.index) { + case 0: + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_Props, id, + SPA_PROP_device, SPA_POD_Stringn(p->device, sizeof(p->device)), + SPA_PROP_minLatency, SPA_POD_Int(p->min_latency), + SPA_PROP_maxLatency, SPA_POD_Int(p->max_latency)); + break; + default: + return 0; + } + break; + + case SPA_PARAM_IO: + switch (result.index) { + case 0: + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_ParamIO, id, + SPA_PARAM_IO_id, SPA_POD_Id(SPA_IO_Clock), + SPA_PARAM_IO_size, SPA_POD_Int(sizeof(struct spa_io_clock))); + break; + case 1: + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_ParamIO, id, + SPA_PARAM_IO_id, SPA_POD_Id(SPA_IO_Position), + SPA_PARAM_IO_size, SPA_POD_Int(sizeof(struct spa_io_position))); + break; + default: + return 0; + } + break; + + default: + return -ENOENT; + } + + if (spa_pod_filter(&b, &result.param, param, filter) < 0) + goto next; + + spa_node_emit_result(&this->hooks, seq, 0, SPA_RESULT_TYPE_NODE_PARAMS, &result); + + if (++count != num) + goto next; + + return 0; +} + +static int impl_node_set_io(void *object, uint32_t id, void *data, size_t size) +{ + struct seq_state *this = object; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + switch (id) { + case SPA_IO_Clock: + this->clock = data; + break; + case SPA_IO_Position: + this->position = data; + break; + default: + return -ENOENT; + } + spa_alsa_seq_reslave(this); + return 0; +} + +static int impl_node_set_param(void *object, uint32_t id, uint32_t flags, + const struct spa_pod *param) +{ + struct seq_state *this = object; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + switch (id) { + case SPA_PARAM_Props: + { + struct props *p = &this->props; + + if (param == NULL) { + reset_props(p); + return 0; + } + spa_pod_parse_object(param, + SPA_TYPE_OBJECT_Props, NULL, + SPA_PROP_device, SPA_POD_OPT_Stringn(p->device, sizeof(p->device)), + SPA_PROP_minLatency, SPA_POD_OPT_Int(&p->min_latency), + SPA_PROP_maxLatency, SPA_POD_OPT_Int(&p->max_latency)); + break; + } + default: + return -ENOENT; + } + + return 0; +} + +static int impl_node_send_command(void *object, const struct spa_command *command) +{ + struct seq_state *this = object; + int res; + + spa_return_val_if_fail(this != NULL, -EINVAL); + spa_return_val_if_fail(command != NULL, -EINVAL); + + switch (SPA_NODE_COMMAND_ID(command)) { + case SPA_NODE_COMMAND_Start: + if ((res = spa_alsa_seq_start(this)) < 0) + return res; + break; + case SPA_NODE_COMMAND_Pause: + if ((res = spa_alsa_seq_pause(this)) < 0) + return res; + break; + default: + return -ENOTSUP; + } + return 0; +} + +static const struct spa_dict_item node_info_items[] = { + { SPA_KEY_DEVICE_API, "alsa" }, + { SPA_KEY_MEDIA_CLASS, "Audio/Source" }, + { SPA_KEY_NODE_DRIVER, "true" }, +}; + +static void emit_node_info(struct seq_state *this, bool full) +{ + if (full) + this->info.change_mask = this->info_all; + if (this->info.change_mask) { + this->info.props = &SPA_DICT_INIT_ARRAY(node_info_items); + spa_node_emit_info(&this->hooks, &this->info); + this->info.change_mask = 0; + } +} + +static inline void clean_name(char *name) +{ + char *c; + for (c = name; *c; ++c) { + if (!isalnum(*c) && *c != '/' && *c != '_' && *c != ':' && *c != '(' && *c != ')') + *c = '-'; + } +} + +static void emit_port_info(struct seq_state *this, struct seq_port *port, bool full) +{ + if (full) + port->info.change_mask = port->info_all; + if (port->info.change_mask) { + struct spa_dict_item items[2]; + snd_seq_port_info_t *info; + char name[128]; + + snd_seq_port_info_alloca(&info); + snd_seq_get_any_port_info(this->sys.hndl + , port->addr.client, port->addr.port, info); + + snprintf(name, sizeof(name), "%s:%s_%d", + snd_seq_port_info_get_name(info), + port->direction == SPA_DIRECTION_OUTPUT ? "capture" : "playback", + port->addr.port); + clean_name(name); + + items[0] = SPA_DICT_ITEM_INIT(SPA_KEY_FORMAT_DSP, "8 bit raw midi"); + items[1] = SPA_DICT_ITEM_INIT(SPA_KEY_PORT_NAME, name); + port->info.props = &SPA_DICT_INIT(items, 2); + + spa_node_emit_port_info(&this->hooks, + port->direction, port->id, &port->info); + port->info.change_mask = 0; + } +} + +static void emit_stream_info(struct seq_state *this, struct seq_stream *stream, bool full) +{ + uint32_t i; + + for (i = 0; i < MAX_PORTS; i++) { + struct seq_port *port = &stream->ports[i]; + if (port->valid) + emit_port_info(this, port, full); + } +} + +static int +impl_node_add_listener(void *object, + struct spa_hook *listener, + const struct spa_node_events *events, + void *data) +{ + struct seq_state *this = object; + struct spa_hook_list save; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + spa_hook_list_isolate(&this->hooks, &save, listener, events, data); + + emit_node_info(this, true); + emit_stream_info(this, &this->streams[SPA_DIRECTION_INPUT], true); + emit_stream_info(this, &this->streams[SPA_DIRECTION_OUTPUT], true); + + spa_hook_list_join(&this->hooks, &save); + + return 0; +} + +static int +impl_node_set_callbacks(void *object, + const struct spa_node_callbacks *callbacks, + void *data) +{ + struct seq_state *this = object; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + this->callbacks = SPA_CALLBACKS_INIT(callbacks, data); + + return 0; +} + +static int impl_node_sync(void *object, int seq) +{ + struct seq_state *this = object; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + spa_node_emit_result(&this->hooks, seq, 0, 0, NULL); + + return 0; +} + +static struct seq_port *find_port(struct seq_state *state, + struct seq_stream *stream, const snd_seq_addr_t *addr) +{ + uint32_t i; + for (i = 0; i < MAX_PORTS; i++) { + struct seq_port *port = &stream->ports[i]; + if (port->valid && + port->addr.client == addr->client && + port->addr.port == addr->port) + return port; + } + return NULL; +} + +static struct seq_port *alloc_port(struct seq_state *state, struct seq_stream *stream) +{ + uint32_t i; + for (i = 0; i < MAX_PORTS; i++) { + struct seq_port *port = &stream->ports[i]; + if (!port->valid) { + port->id = i; + port->direction = stream->direction; + port->valid = true; + return port; + } + } + return NULL; +} +static void free_port(struct seq_state *state, struct seq_port *port) +{ + spa_node_emit_port_info(&state->hooks, + port->direction, port->id, NULL); + port->valid = false; +} + +static int alsa_connect_from(struct seq_state *state, const snd_seq_addr_t *addr) +{ + snd_seq_port_subscribe_t* sub; + snd_seq_addr_t seq_addr; + int res; + + snd_seq_port_subscribe_alloca(&sub); + seq_addr.client = addr->client; + seq_addr.port = addr->port; + snd_seq_port_subscribe_set_sender(sub, &seq_addr); + seq_addr.client = state->event.client_id; + seq_addr.port = state->event.port_id; + snd_seq_port_subscribe_set_dest(sub, &seq_addr); + + snd_seq_port_subscribe_set_time_update(sub, 1); + snd_seq_port_subscribe_set_time_real(sub, 1); + snd_seq_port_subscribe_set_queue(sub, state->event.queue_id); + + if ((res = snd_seq_subscribe_port(state->event.hndl, sub)) < 0) { + spa_log_error(state->log, "can't subscribe to %d:%d - %s", + addr->client, addr->port, snd_strerror(res)); + } + return res; +} + +static void init_port(struct seq_state *state, struct seq_port *port, const snd_seq_addr_t *addr) +{ + int res; + + port->addr = *addr; + port->info_all = SPA_PORT_CHANGE_MASK_FLAGS | + SPA_PORT_CHANGE_MASK_PROPS | + SPA_PORT_CHANGE_MASK_PARAMS; + port->info = SPA_PORT_INFO_INIT(); + port->info.flags = SPA_PORT_FLAG_LIVE | + SPA_PORT_FLAG_PHYSICAL | + SPA_PORT_FLAG_TERMINAL; + port->params[0] = SPA_PARAM_INFO(SPA_PARAM_EnumFormat, SPA_PARAM_INFO_READ); + port->params[1] = SPA_PARAM_INFO(SPA_PARAM_Meta, SPA_PARAM_INFO_READ); + port->params[2] = SPA_PARAM_INFO(SPA_PARAM_IO, SPA_PARAM_INFO_READ); + port->params[3] = SPA_PARAM_INFO(SPA_PARAM_Format, SPA_PARAM_INFO_WRITE); + port->params[4] = SPA_PARAM_INFO(SPA_PARAM_Buffers, 0); + + port->info.params = port->params; + port->info.n_params = 5; + + spa_list_init(&port->free); + spa_list_init(&port->ready); + + if (port->direction == SPA_DIRECTION_OUTPUT) { + res = alsa_connect_from(state, addr); + } else { + res = snd_seq_connect_to(state->event.hndl, state->event.port_id, + addr->client, addr->port); + } + spa_log_debug(state->log, "connect: %d.%d: %d", addr->client, addr->port, res); + emit_port_info(state, port, true); +} + +static void update_stream_port(struct seq_state *state, struct seq_stream *stream, + const snd_seq_addr_t *addr, unsigned int caps, const snd_seq_port_info_t *info) +{ + struct seq_port *port = find_port(state, stream, addr); + + if (info == NULL) { + spa_log_debug(state->log, "free port %d.%d", addr->client, addr->port); + if (port) + free_port(state, port); + } else { + if (port != NULL && (caps & stream->caps) != stream->caps) { + spa_log_debug(state->log, "free port %d.%d", addr->client, addr->port); + free_port(state, port); + } + else if (port == NULL && (caps & stream->caps) == stream->caps) { + spa_log_debug(state->log, "new port %d.%d", addr->client, addr->port); + port = alloc_port(state, stream); + if (port == NULL) + return; + init_port(state, port, addr); + } + } + +} + +static int on_port_info(void *data, const snd_seq_addr_t *addr, const snd_seq_port_info_t *info) +{ + struct seq_state *state = data; + + if (info == NULL) { + update_stream_port(state, &state->streams[SPA_DIRECTION_INPUT], addr, 0, info); + update_stream_port(state, &state->streams[SPA_DIRECTION_OUTPUT], addr, 0, info); + } else { + unsigned int caps = snd_seq_port_info_get_capability(info); + + if (caps & SND_SEQ_PORT_CAP_NO_EXPORT) + return 0; + + update_stream_port(state, &state->streams[SPA_DIRECTION_INPUT], addr, caps, info); + update_stream_port(state, &state->streams[SPA_DIRECTION_OUTPUT], addr, caps, info); + } + return 0; +} + +static int impl_node_add_port(void *object, enum spa_direction direction, uint32_t port_id, + const struct spa_dict *props) +{ + return -ENOTSUP; +} + +static int impl_node_remove_port(void *object, enum spa_direction direction, uint32_t port_id) +{ + return -ENOTSUP; +} + +static int +impl_node_port_enum_params(void *object, int seq, + enum spa_direction direction, uint32_t port_id, + uint32_t id, uint32_t start, uint32_t num, + const struct spa_pod *filter) +{ + struct seq_state *this = object; + struct seq_port *port; + struct spa_pod *param; + struct spa_pod_builder b = { 0 }; + uint8_t buffer[1024]; + struct spa_result_node_params result; + uint32_t count = 0; + + spa_return_val_if_fail(this != NULL, -EINVAL); + spa_return_val_if_fail(num != 0, -EINVAL); + + spa_return_val_if_fail(CHECK_PORT(this, direction, port_id), -EINVAL); + + port = GET_PORT(this, direction, port_id); + + result.id = id; + result.next = start; + next: + result.index = result.next++; + + spa_pod_builder_init(&b, buffer, sizeof(buffer)); + + switch (id) { + case SPA_PARAM_EnumFormat: + if (result.index > 0) + return 0; + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat, + SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_application), + SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_control)); + break; + + case SPA_PARAM_Format: + if (!port->have_format) + return -EIO; + if (result.index > 0) + return 0; + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat, + SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_application), + SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_control)); + break; + + case SPA_PARAM_Buffers: + if (!port->have_format) + return -EIO; + if (result.index > 0) + return 0; + + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_ParamBuffers, id, + SPA_PARAM_BUFFERS_buffers, SPA_POD_CHOICE_RANGE_Int(2, 1, MAX_BUFFERS), + SPA_PARAM_BUFFERS_blocks, SPA_POD_Int(1), + SPA_PARAM_BUFFERS_size, SPA_POD_CHOICE_RANGE_Int( + 4096, 4096, INT32_MAX), + SPA_PARAM_BUFFERS_stride, SPA_POD_Int(1), + SPA_PARAM_BUFFERS_align, SPA_POD_Int(16)); + break; + + case SPA_PARAM_Meta: + switch (result.index) { + case 0: + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_ParamMeta, id, + SPA_PARAM_META_type, SPA_POD_Id(SPA_META_Header), + SPA_PARAM_META_size, SPA_POD_Int(sizeof(struct spa_meta_header))); + break; + default: + return 0; + } + break; + + case SPA_PARAM_IO: + switch (result.index) { + case 0: + param = spa_pod_builder_add_object(&b, + SPA_TYPE_OBJECT_ParamIO, id, + SPA_PARAM_IO_id, SPA_POD_Id(SPA_IO_Buffers), + SPA_PARAM_IO_size, SPA_POD_Int(sizeof(struct spa_io_buffers))); + break; + default: + return 0; + } + break; + + default: + return -ENOENT; + } + + if (spa_pod_filter(&b, &result.param, param, filter) < 0) + goto next; + + spa_node_emit_result(&this->hooks, seq, 0, SPA_RESULT_TYPE_NODE_PARAMS, &result); + + if (++count != num) + goto next; + + return 0; +} + +static int clear_buffers(struct seq_state *this, struct seq_port *port) +{ + if (port->n_buffers > 0) { + spa_list_init(&port->free); + spa_list_init(&port->ready); + port->n_buffers = 0; + } + return 0; +} + +static int port_set_format(void *object, struct seq_port *port, + uint32_t flags, const struct spa_pod *format) +{ + struct seq_state *this = object; + int err; + + if (format == NULL) { + if (!port->have_format) + return 0; + + clear_buffers(this, port); + port->have_format = false; + } else { + struct spa_audio_info info = { 0 }; + + if ((err = spa_format_parse(format, &info.media_type, &info.media_subtype)) < 0) + return err; + + if (info.media_type != SPA_MEDIA_TYPE_application || + info.media_subtype != SPA_MEDIA_SUBTYPE_control) + return -EINVAL; + + port->current_format = info; + port->have_format = true; + } + + port->info.change_mask |= SPA_PORT_CHANGE_MASK_RATE; + port->info.rate = SPA_FRACTION(1, 1); + port->info.change_mask |= SPA_PORT_CHANGE_MASK_PARAMS; + if (port->have_format) { + port->params[3] = SPA_PARAM_INFO(SPA_PARAM_Format, SPA_PARAM_INFO_READWRITE); + port->params[4] = SPA_PARAM_INFO(SPA_PARAM_Buffers, SPA_PARAM_INFO_READ); + } else { + port->params[3] = SPA_PARAM_INFO(SPA_PARAM_Format, SPA_PARAM_INFO_WRITE); + port->params[4] = SPA_PARAM_INFO(SPA_PARAM_Buffers, 0); + } + emit_port_info(this, port, false); + + return 0; +} + +static int +impl_node_port_set_param(void *object, + enum spa_direction direction, uint32_t port_id, + uint32_t id, uint32_t flags, + const struct spa_pod *param) +{ + struct seq_state *this = object; + struct seq_port *port; + int res; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + spa_return_val_if_fail(CHECK_PORT(this, direction, port_id), -EINVAL); + + port = GET_PORT(this, direction, port_id); + + switch (id) { + case SPA_PARAM_Format: + res = port_set_format(this, port, flags, param); + break; + + default: + res = -ENOENT; + break; + } + return res; +} + +static int +impl_node_port_use_buffers(void *object, + enum spa_direction direction, uint32_t port_id, + uint32_t flags, + struct spa_buffer **buffers, uint32_t n_buffers) +{ + struct seq_state *this = object; + struct seq_port *port; + uint32_t i; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + spa_return_val_if_fail(CHECK_PORT(this, direction, port_id), -EINVAL); + + port = GET_PORT(this, direction, port_id); + + if (!port->have_format) + return -EIO; + + clear_buffers(this, port); + + for (i = 0; i < n_buffers; i++) { + struct buffer *b = &port->buffers[i]; + struct spa_data *d = buffers[i]->datas; + + b->buf = buffers[i]; + b->id = i; + b->flags = BUFFER_FLAG_OUT; + + b->h = spa_buffer_find_meta_data(b->buf, SPA_META_Header, sizeof(*b->h)); + + if (!((d[0].type == SPA_DATA_MemFd || + d[0].type == SPA_DATA_DmaBuf || + d[0].type == SPA_DATA_MemPtr) && d[0].data != NULL)) { + spa_log_error(this->log, NAME " %p: need mapped memory", this); + return -EINVAL; + } + if (direction == SPA_DIRECTION_OUTPUT) + spa_alsa_seq_recycle_buffer(this, port, i); + } + port->n_buffers = n_buffers; + + return 0; +} + +static int +impl_node_port_set_io(void *object, + enum spa_direction direction, + uint32_t port_id, + uint32_t id, + void *data, size_t size) +{ + struct seq_state *this = object; + struct seq_port *port; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + spa_return_val_if_fail(CHECK_PORT(this, direction, port_id), -EINVAL); + + port = GET_PORT(this, direction, port_id); + + spa_log_debug(this->log, NAME " %p: io %d.%d %d %p %zd", this, + direction, port_id, id, data, size); + + switch (id) { + case SPA_IO_Buffers: + port->io = data; + break; + default: + return -ENOENT; + } + return 0; +} + +static int impl_node_port_reuse_buffer(void *object, uint32_t port_id, uint32_t buffer_id) +{ + struct seq_state *this = object; + struct seq_port *port; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + spa_return_val_if_fail(!CHECK_PORT(this, SPA_DIRECTION_OUTPUT, port_id), -EINVAL); + + port = GET_PORT(this, SPA_DIRECTION_OUTPUT, port_id); + + if (port->n_buffers == 0) + return -EIO; + + if (buffer_id >= port->n_buffers) + return -EINVAL; + + spa_alsa_seq_recycle_buffer(this, port, buffer_id); + + return 0; +} + +static int impl_node_process(void *object) +{ + struct seq_state *this = object; + + spa_return_val_if_fail(this != NULL, -EINVAL); + + return spa_alsa_seq_process(this); +} + +static const struct spa_node_methods impl_node = { + SPA_VERSION_NODE_METHODS, + .add_listener = impl_node_add_listener, + .set_callbacks = impl_node_set_callbacks, + .sync = impl_node_sync, + .enum_params = impl_node_enum_params, + .set_param = impl_node_set_param, + .set_io = impl_node_set_io, + .send_command = impl_node_send_command, + .add_port = impl_node_add_port, + .remove_port = impl_node_remove_port, + .port_enum_params = impl_node_port_enum_params, + .port_set_param = impl_node_port_set_param, + .port_use_buffers = impl_node_port_use_buffers, + .port_set_io = impl_node_port_set_io, + .port_reuse_buffer = impl_node_port_reuse_buffer, + .process = impl_node_process, +}; + +static int impl_get_interface(struct spa_handle *handle, uint32_t type, void **interface) +{ + struct seq_state *this; + + spa_return_val_if_fail(handle != NULL, -EINVAL); + spa_return_val_if_fail(interface != NULL, -EINVAL); + + this = (struct seq_state *) handle; + + if (type == SPA_TYPE_INTERFACE_Node) + *interface = &this->node; + else + return -ENOENT; + + return 0; +} + +static int impl_clear(struct spa_handle *handle) +{ + return 0; +} + +static size_t +impl_get_size(const struct spa_handle_factory *factory, + const struct spa_dict *params) +{ + return sizeof(struct seq_state); +} + +static int +impl_init(const struct spa_handle_factory *factory, + struct spa_handle *handle, + const struct spa_dict *info, + const struct spa_support *support, + uint32_t n_support) +{ + struct seq_state *this; + uint32_t i; + int res; + + spa_return_val_if_fail(factory != NULL, -EINVAL); + spa_return_val_if_fail(handle != NULL, -EINVAL); + + handle->get_interface = impl_get_interface; + handle->clear = impl_clear; + + this = (struct seq_state *) handle; + + for (i = 0; i < n_support; i++) { + switch (support[i].type) { + case SPA_TYPE_INTERFACE_Log: + this->log = support[i].data; + break; + case SPA_TYPE_INTERFACE_DataSystem: + this->data_system = support[i].data; + break; + case SPA_TYPE_INTERFACE_DataLoop: + this->data_loop = support[i].data; + break; + case SPA_TYPE_INTERFACE_Loop: + this->main_loop = support[i].data; + break; + } + } + if (this->data_loop == NULL) { + spa_log_error(this->log, "a data loop is needed"); + return -EINVAL; + } + if (this->data_system == NULL) { + spa_log_error(this->log, "a data system is needed"); + return -EINVAL; + } + + this->node.iface = SPA_INTERFACE_INIT(SPA_TYPE_INTERFACE_Node, SPA_VERSION_NODE, &impl_node, this); + + spa_hook_list_init(&this->hooks); + + this->info_all = SPA_NODE_CHANGE_MASK_FLAGS | + SPA_NODE_CHANGE_MASK_PROPS | + SPA_NODE_CHANGE_MASK_PARAMS; + this->info.max_output_ports = 1; + this->info.flags = SPA_NODE_FLAG_RT; + this->params[0] = SPA_PARAM_INFO(SPA_PARAM_PropInfo, SPA_PARAM_INFO_READ); + this->params[1] = SPA_PARAM_INFO(SPA_PARAM_Props, SPA_PARAM_INFO_READWRITE); + this->params[2] = SPA_PARAM_INFO(SPA_PARAM_IO, SPA_PARAM_INFO_READ); + this->info.params = this->params; + this->info.n_params = 3; + reset_props(&this->props); + + for (i = 0; info && i < info->n_items; i++) { + if (!strcmp(info->items[i].key, SPA_KEY_API_ALSA_PATH)) { + snprintf(this->props.device, 63, "%s", info->items[i].value); + } + } + + this->port_info = on_port_info; + this->port_info_data = this; + + if ((res = spa_alsa_seq_open(this)) < 0) + return res; + + return 0; +} + +static const struct spa_interface_info impl_interfaces[] = { + {SPA_TYPE_INTERFACE_Node,}, +}; + +static int +impl_enum_interface_info(const struct spa_handle_factory *factory, + const struct spa_interface_info **info, + uint32_t *index) +{ + spa_return_val_if_fail(factory != NULL, -EINVAL); + spa_return_val_if_fail(info != NULL, -EINVAL); + spa_return_val_if_fail(index != NULL, -EINVAL); + + if (*index >= SPA_N_ELEMENTS(impl_interfaces)) + return 0; + + *info = &impl_interfaces[(*index)++]; + + return 1; +} + +static const struct spa_dict_item info_items[] = { + { SPA_KEY_FACTORY_AUTHOR, "Wim Taymans " }, + { SPA_KEY_FACTORY_DESCRIPTION, "Record midi with the alsa API" }, + { SPA_KEY_FACTORY_USAGE, "["SPA_KEY_API_ALSA_PATH"=]" }, +}; + +static const struct spa_dict info = SPA_DICT_INIT_ARRAY(info_items); + +const struct spa_handle_factory spa_alsa_midi_source_factory = { + SPA_VERSION_HANDLE_FACTORY, + SPA_NAME_API_ALSA_MIDI_SOURCE, + &info, + impl_get_size, + impl_init, + impl_enum_interface_info, +}; diff --git a/spa/plugins/alsa/alsa-seq.c b/spa/plugins/alsa/alsa-seq.c new file mode 100644 index 000000000..e32acabc2 --- /dev/null +++ b/spa/plugins/alsa/alsa-seq.c @@ -0,0 +1,773 @@ +/* Spa ALSA Sequencer + * + * Copyright © 2019 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define NAME "alsa-seq" + +#include "alsa-seq.h" + +#define CHECK(s,msg) if ((res = (s)) < 0) { spa_log_error(state->log, msg ": %s", snd_strerror(res)); return res; } + +static int seq_open(struct seq_state *state, struct seq_conn *conn) +{ + struct props *props = &state->props; + struct pollfd pfd; + snd_seq_port_info_t *pinfo; + int res; + + spa_log_info(state->log, "%p: ALSA seq open '%s' duplex", state, props->device); + + if ((res = snd_seq_open(&conn->hndl, + props->device, + SND_SEQ_OPEN_DUPLEX, + 0)) < 0) { + spa_log_error(state->log, "open failed: %s", snd_strerror(res)); + goto error_exit_close; + } + + /* client id */ + if ((res = snd_seq_client_id(conn->hndl)) < 0) { + spa_log_error(state->log, "failed to get client id: %d", res); + goto error_exit_close; + } + conn->client_id = res; + + /* queue */ + if ((res = snd_seq_alloc_queue(conn->hndl)) < 0) { + spa_log_error(state->log, "failed to create queue: %d", res); + goto error_exit_close; + } + conn->queue_id = res; + + if ((res = snd_seq_nonblock(conn->hndl, 1)) < 0) + spa_log_warn(state->log, "can't set nonblock mode: %s", snd_strerror(res)); + + /* port for receiving */ + snd_seq_port_info_alloca(&pinfo); + snd_seq_port_info_set_name(pinfo, "input"); + snd_seq_port_info_set_type(pinfo, SND_SEQ_PORT_TYPE_MIDI_GENERIC); + snd_seq_port_info_set_capability(pinfo, + SND_SEQ_PORT_CAP_WRITE | + SND_SEQ_PORT_CAP_READ | + SND_SEQ_PORT_CAP_NO_EXPORT); + /* Enable timestamping for events sent by external subscribers. */ + snd_seq_port_info_set_timestamping(pinfo, 1); + snd_seq_port_info_set_timestamp_real(pinfo, 1); + snd_seq_port_info_set_timestamp_queue(pinfo, conn->queue_id); + + if ((res = snd_seq_create_port(conn->hndl, pinfo)) < 0) { + spa_log_error(state->log, "failed to create port: %s", snd_strerror(res)); + goto error_exit_close; + } + conn->port_id = snd_seq_port_info_get_port(pinfo); + + spa_log_debug(state->log, "queue:%d client:%d port:%d", + conn->queue_id, conn->client_id, conn->port_id); + + snd_seq_poll_descriptors(conn->hndl, &pfd, 1, POLLIN); + conn->source.fd = pfd.fd; + conn->source.mask = SPA_IO_IN; + + return 0; + +error_exit_close: + snd_seq_close(conn->hndl); + return res; +} + +static int seq_close(struct seq_state *state, struct seq_conn *conn) +{ + int res; + spa_log_info(state->log, "%p: Device '%s' closing", state, state->props.device); + if ((res = snd_seq_close(conn->hndl)) < 0) { + spa_log_warn(state->log, "close failed: %s", snd_strerror(res)); + } + return res; +} + +static int seq_start(struct seq_state *state, struct seq_conn *conn) +{ + int res; + if ((res = snd_seq_start_queue(conn->hndl, conn->queue_id, NULL)) < 0) { + spa_log_warn(state->log, "failed to start queue: %s", snd_strerror(res)); + } + while (snd_seq_drain_output(conn->hndl) > 0) + sleep(1); + return res; +} + +static int init_stream(struct seq_state *state, enum spa_direction direction) +{ + struct seq_stream *stream = &state->streams[direction]; + stream->direction = direction; + if (direction == SPA_DIRECTION_INPUT) { + stream->caps = SND_SEQ_PORT_CAP_SUBS_WRITE; + } else { + stream->caps = SND_SEQ_PORT_CAP_SUBS_READ; + } + snd_midi_event_new(MAX_EVENT_SIZE, &stream->codec); + memset(stream->ports, 0, sizeof(stream->ports)); + return 0; +} + +static void init_ports(struct seq_state *state) +{ + snd_seq_addr_t addr; + snd_seq_client_info_t *client_info; + snd_seq_port_info_t *port_info; + + snd_seq_client_info_alloca(&client_info); + snd_seq_port_info_alloca(&port_info); + snd_seq_client_info_set_client(client_info, -1); + + while (snd_seq_query_next_client(state->sys.hndl, client_info) >= 0) { + + addr.client = snd_seq_client_info_get_client(client_info); + if (addr.client == SND_SEQ_CLIENT_SYSTEM || + addr.client == state->sys.client_id || + addr.client == state->event.client_id) + continue; + + snd_seq_port_info_set_client(port_info, addr.client); + snd_seq_port_info_set_port(port_info, -1); + while (snd_seq_query_next_port(state->sys.hndl, port_info) >= 0) { + addr.port = snd_seq_port_info_get_port(port_info); + state->port_info(state->port_info_data, &addr, port_info); + } + } +} + +static void debug_event(struct seq_state *state, snd_seq_event_t *ev) +{ + spa_log_trace(state->log, "event type:%d flags:0x%x", ev->type, ev->flags); + switch (ev->flags & SND_SEQ_TIME_STAMP_MASK) { + case SND_SEQ_TIME_STAMP_TICK: + spa_log_trace(state->log, " time: %d ticks", ev->time.tick); + break; + case SND_SEQ_TIME_STAMP_REAL: + spa_log_trace(state->log, " time = %d.%09d", + (int)ev->time.time.tv_sec, + (int)ev->time.time.tv_nsec); + break; + } + spa_log_trace(state->log, " source:%d.%d dest:%d.%d queue:%d", + ev->source.client, + ev->source.port, + ev->dest.client, + ev->dest.port, + ev->queue); +} + +static void alsa_seq_on_sys(struct spa_source *source) +{ + struct seq_state *state = source->data; + snd_seq_event_t *ev; + int res; + + while (snd_seq_event_input (state->sys.hndl, &ev) > 0) { + const snd_seq_addr_t *addr = &ev->data.addr; + + if (addr->client == state->event.client_id) + continue; + + debug_event(state, ev); + + switch (ev->type) { + case SND_SEQ_EVENT_PORT_START: + case SND_SEQ_EVENT_PORT_CHANGE: + { + snd_seq_port_info_t *info; + + snd_seq_port_info_alloca(&info); + + if ((res = snd_seq_get_any_port_info(state->sys.hndl, + addr->client, addr->port, info)) < 0) { + spa_log_warn(state->log, "can't get port info %d.%d: %s", + addr->client, addr->port, snd_strerror(res)); + } else { + spa_log_debug(state->log, "port add/change %d:%d", + addr->client, addr->port); + state->port_info(state->port_info_data, addr, info); + } + break; + } + case SND_SEQ_EVENT_PORT_EXIT: + spa_log_debug(state->log, "port_event: del %d:%d", + addr->client, addr->port); + state->port_info(state->port_info_data, addr, NULL); + break; + } + snd_seq_free_event(ev); + } +} + +int spa_alsa_seq_open(struct seq_state *state) +{ + int res; + snd_seq_port_subscribe_t *sub; + snd_seq_addr_t addr; + + if (state->opened) + return 0; + + init_stream(state, SPA_DIRECTION_INPUT); + init_stream(state, SPA_DIRECTION_OUTPUT); + + if ((res = seq_open(state, &state->sys)) < 0) + return res; + + if ((res = seq_open(state, &state->event)) < 0) + return res; + + /* connect to system announce */ + snd_seq_port_subscribe_alloca(&sub); + addr.client = SND_SEQ_CLIENT_SYSTEM; + addr.port = SND_SEQ_PORT_SYSTEM_ANNOUNCE; + snd_seq_port_subscribe_set_sender(sub, &addr); + addr.client = state->sys.client_id; + addr.port = state->sys.port_id; + snd_seq_port_subscribe_set_dest(sub, &addr); + snd_seq_port_subscribe_set_queue(sub, state->sys.queue_id); + snd_seq_port_subscribe_set_time_update(sub, 1); + snd_seq_port_subscribe_set_time_real(sub, 1); + if ((res = snd_seq_subscribe_port(state->sys.hndl, sub)) < 0) { + spa_log_warn(state->log, "failed to connect announce port: %s", snd_strerror(res)); + } + + addr.client = SND_SEQ_CLIENT_SYSTEM; + addr.port = SND_SEQ_PORT_SYSTEM_TIMER; + snd_seq_port_subscribe_set_sender(sub, &addr); + if ((res = snd_seq_subscribe_port(state->sys.hndl, sub)) < 0) { + spa_log_warn(state->log, "failed to connect timer port: %s", snd_strerror(res)); + } + + seq_start(state, &state->sys); + + state->sys.source.func = alsa_seq_on_sys; + state->sys.source.data = state; + spa_loop_add_source(state->main_loop, &state->sys.source); + + init_ports(state); + + if ((res = spa_system_timerfd_create(state->data_system, + CLOCK_MONOTONIC, SPA_FD_CLOEXEC | SPA_FD_NONBLOCK)) < 0) + return res; + + state->timerfd = res; + + state->opened = true; + + return 0; +} + +int spa_alsa_seq_close(struct seq_state *state) +{ + int res = 0; + + if (!state->opened) + return 0; + + spa_loop_remove_source(state->main_loop, &state->sys.source); + + seq_close(state, &state->sys); + seq_close(state, &state->event); + + spa_system_close(state->data_system, state->timerfd); + state->opened = false; + + return res; +} + +static int set_timeout(struct seq_state *state, uint64_t time) +{ + struct itimerspec ts; + + ts.it_value.tv_sec = time / SPA_NSEC_PER_SEC; + ts.it_value.tv_nsec = time % SPA_NSEC_PER_SEC; + ts.it_interval.tv_sec = 0; + ts.it_interval.tv_nsec = 0; + spa_system_timerfd_settime(state->data_system, + state->timerfd, SPA_FD_TIMER_ABSTIME, &ts, NULL); + return 0; +} + +static struct seq_port *find_port(struct seq_state *state, + struct seq_stream *stream, const snd_seq_addr_t *addr) +{ + uint32_t i; + for (i = 0; i < MAX_PORTS; i++) { + struct seq_port *port = &stream->ports[i]; + if (port->valid && + port->addr.client == addr->client && + port->addr.port == addr->port) + return port; + } + return NULL; +} + +static struct buffer *peek_buffer(struct seq_state *state, + struct seq_port *port) +{ + if (spa_list_is_empty(&port->free)) + return NULL; + return spa_list_first(&port->free, struct buffer, link); +} + +int spa_alsa_seq_recycle_buffer(struct seq_state *state, struct seq_port *port, uint32_t buffer_id) +{ + struct buffer *b = &port->buffers[buffer_id]; + + if (SPA_FLAG_CHECK(b->flags, BUFFER_FLAG_OUT)) { + spa_log_trace_fp(state->log, NAME " %p: recycle buffer port:%p buffer-id:%u", + state, port, buffer_id); + spa_list_append(&port->free, &b->link); + SPA_FLAG_UNSET(b->flags, BUFFER_FLAG_OUT); + } + return 0; +} + +static int prepare_buffer(struct seq_state *state, struct seq_port *port) +{ + if (port->buffer != NULL) + return 0; + + if ((port->buffer = peek_buffer(state, port)) == NULL) + return -EPIPE; + + spa_pod_builder_init(&port->builder, + port->buffer->buf->datas[0].data, + port->buffer->buf->datas[0].maxsize); + spa_pod_builder_push_sequence(&port->builder, &port->frame, 0); + + return 0; +} + +static int process_recycle(struct seq_state *state) +{ + struct seq_stream *stream = &state->streams[SPA_DIRECTION_OUTPUT]; + uint32_t i; + + for (i = 0; i < MAX_PORTS; i++) { + struct seq_port *port = &stream->ports[i]; + struct spa_io_buffers *io = port->io; + + if (!port->valid || io == NULL) + continue; + + if (io->status == SPA_STATUS_NEED_DATA && + io->buffer_id < port->n_buffers) { + spa_alsa_seq_recycle_buffer(state, port, io->buffer_id); + io->buffer_id = SPA_ID_INVALID; + } + } + return 0; +} + +static int process_read(struct seq_state *state) +{ + snd_seq_event_t *ev; + struct seq_stream *stream = &state->streams[SPA_DIRECTION_OUTPUT]; + uint32_t i; + long size; + uint8_t data[MAX_EVENT_SIZE]; + int res; + + /* copy all new midi events into their port buffers */ + while (snd_seq_event_input(state->event.hndl, &ev) > 0) { + const snd_seq_addr_t *addr = &ev->source; + struct seq_port *port; + uint64_t ev_time, diff; + uint32_t offset; + + debug_event(state, ev); + + if ((port = find_port(state, stream, addr)) == NULL) { + spa_log_debug(state->log, "unknown port %d.%d", + addr->client, addr->port); + continue; + } + if ((res = prepare_buffer(state, port)) < 0) { + spa_log_debug(state->log, "can't prepare buffer port:%p %d.%d: %s", + port, addr->client, addr->port, spa_strerror(res)); + continue; + } + + snd_midi_event_reset_decode(stream->codec); + if ((size = snd_midi_event_decode(stream->codec, data, MAX_EVENT_SIZE, ev)) < 0) { + spa_log_warn(state->log, "decode failed: %s", snd_strerror(size)); + continue; + } + + /* fixup NoteOn with vel 0 */ + if ((data[0] & 0xF0) == 0x90 && data[2] == 0x00) { + data[0] = 0x80 + (data[0] & 0x0F); + data[2] = 0x40; + } + + ev_time = SPA_TIMESPEC_TO_NSEC(&ev->time.time); + if (state->queue_time > ev_time) + diff = state->queue_time - ev_time; + else + diff = 0; + + offset = (diff * state->rate.denom) / (state->rate.num * SPA_NSEC_PER_SEC); + if (state->duration > offset) + offset = state->duration - offset; + else + offset = 0; + + spa_log_trace_fp(state->log, "event time:%"PRIu64" offset:%d size:%ld port:%d.%d", + ev_time, offset, size, addr->client, addr->port); + + spa_pod_builder_control(&port->builder, offset, SPA_CONTROL_Midi); + spa_pod_builder_bytes(&port->builder, data, size); + + snd_seq_free_event(ev); + } + + /* prepare a buffer on each port, some ports might have their + * buffer filled above */ + res = 0; + for (i = 0; i < MAX_PORTS; i++) { + struct seq_port *port = &stream->ports[i]; + struct spa_io_buffers *io = port->io; + + if (!port->valid || io == NULL) + continue; + + if (prepare_buffer(state, port) >= 0) { + port->buffer->buf->datas[0].chunk->offset = 0; + port->buffer->buf->datas[0].chunk->size = port->builder.state.offset, + + spa_pod_builder_pop(&port->builder, &port->frame); + + /* move buffer to ready queue */ + spa_list_remove(&port->buffer->link); + SPA_FLAG_SET(port->buffer->flags, BUFFER_FLAG_OUT); + spa_list_append(&port->ready, &port->buffer->link); + port->buffer = NULL; + } + + /* if there is already data, continue */ + if (io->status == SPA_STATUS_HAVE_DATA) { + res |= SPA_STATUS_HAVE_DATA; + continue; + } + + if (io->buffer_id < port->n_buffers) + spa_alsa_seq_recycle_buffer(state, port, io->buffer_id); + + if (spa_list_is_empty(&port->ready)) { + /* we have no ready buffers */ + io->buffer_id = SPA_ID_INVALID; + io->status = -EPIPE; + } else { + struct buffer *b = spa_list_first(&port->ready, struct buffer, link); + spa_list_remove(&b->link); + + /* dequeue ready buffer */ + io->buffer_id = b->id; + io->status = SPA_STATUS_HAVE_DATA; + res |= SPA_STATUS_HAVE_DATA; + } + } + return res; +} + +static int process_write(struct seq_state *state) +{ + struct seq_stream *stream = &state->streams[SPA_DIRECTION_INPUT]; + uint32_t i; + int res; + + for (i = 0; i < MAX_PORTS; i++) { + struct seq_port *port = &stream->ports[i]; + struct spa_io_buffers *io = port->io; + struct buffer *buffer; + struct spa_pod_sequence *pod; + struct spa_data *d; + struct spa_pod_control *c; + snd_seq_event_t ev; + uint64_t out_time; + snd_seq_real_time_t out_rt; + + if (!port->valid || io == NULL) + continue; + + if (io->status != SPA_STATUS_HAVE_DATA || + io->buffer_id >= port->n_buffers) + continue; + + buffer = &port->buffers[io->buffer_id]; + d = &buffer->buf->datas[0]; + + spa_node_call_reuse_buffer(&state->callbacks, i, io->buffer_id); + + pod = spa_pod_from_data(d->data, d->maxsize, d->chunk->offset, d->chunk->size); + if (pod == NULL) { + spa_log_warn(state->log, "invalid sequence in buffer max:%u offset:%u size:%u", + d->maxsize, d->chunk->offset, d->chunk->size); + continue; + } + + SPA_POD_SEQUENCE_FOREACH(pod, c) { + long size; + + if (c->type != SPA_CONTROL_Midi) + continue; + + snd_seq_ev_clear(&ev); + + snd_midi_event_reset_encode(stream->codec); + if ((size = snd_midi_event_encode(stream->codec, + SPA_POD_BODY(&c->value), + SPA_POD_BODY_SIZE(&c->value), &ev)) <= 0) { + spa_log_warn(state->log, "failed to encode event: %s", + snd_strerror(size)); + continue; + } + + snd_seq_ev_set_source(&ev, state->event.port_id); + snd_seq_ev_set_dest(&ev, port->addr.client, port->addr.port); + + out_time = state->queue_time + + (c->offset * state->rate.num * SPA_NSEC_PER_SEC) / state->rate.denom; + + out_rt.tv_nsec = out_time % SPA_NSEC_PER_SEC; + out_rt.tv_sec = out_time / SPA_NSEC_PER_SEC; + snd_seq_ev_schedule_real(&ev, state->event.queue_id, 0, &out_rt); + + spa_log_trace_fp(state->log, "event time:%"PRIu64" offset:%d size:%ld port:%d.%d", + out_time, c->offset, size, port->addr.client, port->addr.port); + + if ((res = snd_seq_event_output(state->event.hndl, &ev)) < 0) { + spa_log_warn(state->log, "failed to output event: %s", + snd_strerror(res)); + } + } + } + snd_seq_drain_output(state->event.hndl); + + return SPA_STATUS_NEED_DATA; +} + +static int update_time(struct seq_state *state) +{ + snd_seq_queue_status_t *status; + const snd_seq_real_time_t* queue_time; + + /* take queue time */ + snd_seq_queue_status_alloca(&status); + snd_seq_get_queue_status(state->event.hndl, state->event.queue_id, status); + queue_time = snd_seq_queue_status_get_real_time(status); + state->queue_time = SPA_TIMESPEC_TO_NSEC(queue_time); + + spa_log_trace_fp(state->log, "now:%"PRIu64" queue:%"PRIu64" diff:%"PRIu64, + state->current_time, state->queue_time, + state->current_time - state->queue_time); + + return 0; +} + +int spa_alsa_seq_process(struct seq_state *state) +{ + int res; + + res = process_recycle(state); + + if (state->slaved) { + update_time(state); + res |= process_read(state); + } + res = process_write(state); + return res; +} + +static void alsa_on_timeout_event(struct spa_source *source) +{ + struct seq_state *state = source->data; + uint64_t expire; + int res; + + if (state->started && spa_system_timerfd_read(state->data_system, state->timerfd, &expire) < 0) + spa_log_warn(state->log, "error reading timerfd: %m"); + + state->current_time = state->next_time; + + spa_log_trace(state->log, "timeout %"PRIu64, state->current_time); + + if (state->position) { + struct spa_io_clock *clock = &state->position->clock; + state->rate = clock->rate; + state->duration = clock->duration; + state->threshold = (state->duration * clock->rate.num * SPA_NSEC_PER_SEC) / + clock->rate.denom; + } + + update_time(state); + + res = process_read(state); + if (res > 0) + spa_node_call_ready(&state->callbacks, res); + + state->next_time += state->threshold; + + set_timeout(state, state->next_time); +} + +static void reset_buffers(struct seq_state *this, struct seq_port *port) +{ + uint32_t i; + + spa_list_init(&port->free); + spa_list_init(&port->ready); + + for (i = 0; i < port->n_buffers; i++) { + struct buffer *b = &port->buffers[i]; + if (port->direction == SPA_DIRECTION_INPUT) { + SPA_FLAG_SET(b->flags, BUFFER_FLAG_OUT); + } else { + spa_list_append(&port->free, &b->link); + SPA_FLAG_UNSET(b->flags, BUFFER_FLAG_OUT); + } + } +} + +static int set_timers(struct seq_state *state) +{ + struct timespec now; + + spa_system_clock_gettime(state->data_system, CLOCK_MONOTONIC, &now); + + state->next_time = SPA_TIMESPEC_TO_NSEC(&now); + if (state->slaved) { + set_timeout(state, 0); + } else { + set_timeout(state, state->next_time); + } + return 0; +} + +static inline bool is_slaved(struct seq_state *state) +{ + return state->position && state->clock && state->position->clock.id != state->clock->id; +} + +int spa_alsa_seq_start(struct seq_state *state) +{ + int res; + + if (state->started) + return 0; + + state->slaved = is_slaved(state); + + spa_log_debug(state->log, "alsa %p: start slave:%d", state, state->slaved); + + if ((res = seq_start(state, &state->event)) < 0) + return res; + + state->source.func = alsa_on_timeout_event; + state->source.data = state; + state->source.fd = state->timerfd; + state->source.mask = SPA_IO_IN; + state->source.rmask = 0; + spa_loop_add_source(state->data_loop, &state->source); + + set_timers(state); + + state->started = true; + + return 0; +} + +static int do_reslave(struct spa_loop *loop, + bool async, + uint32_t seq, + const void *data, + size_t size, + void *user_data) +{ + struct seq_state *state = user_data; + set_timers(state); + return 0; +} + +int spa_alsa_seq_reslave(struct seq_state *state) +{ + bool slaved; + + if (!state->started) + return 0; + + slaved = is_slaved(state); + if (slaved != state->slaved) { + spa_log_debug(state->log, "alsa %p: reslave %d->%d", state, state->slaved, slaved); + state->slaved = slaved; + spa_loop_invoke(state->data_loop, do_reslave, 0, NULL, 0, true, state); + } + return 0; +} + +static int do_remove_source(struct spa_loop *loop, + bool async, + uint32_t seq, + const void *data, + size_t size, + void *user_data) +{ + struct seq_state *state = user_data; + + spa_loop_remove_source(state->data_loop, &state->source); + set_timeout(state, 0); + + return 0; +} + +int spa_alsa_seq_pause(struct seq_state *state) +{ + if (!state->started) + return 0; + + spa_log_debug(state->log, "alsa %p: pause", state); + + spa_loop_invoke(state->data_loop, do_remove_source, 0, NULL, 0, true, state); + + state->started = false; + + return 0; +} diff --git a/spa/plugins/alsa/alsa-seq.h b/spa/plugins/alsa/alsa-seq.h new file mode 100644 index 000000000..baf6d823f --- /dev/null +++ b/spa/plugins/alsa/alsa-seq.h @@ -0,0 +1,174 @@ +/* Spa ALSA Sequencer + * + * Copyright © 2019 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. + */ + +#ifndef SPA_ALSA_SEQ_H +#define SPA_ALSA_SEQ_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +struct props { + char device[64]; + uint32_t min_latency; + uint32_t max_latency; +}; + +#define MAX_EVENT_SIZE 1024 +#define MAX_PORTS 256 +#define MAX_BUFFERS 32 + +struct buffer { + uint32_t id; +#define BUFFER_FLAG_OUT (1<<0) + uint32_t flags; + struct spa_buffer *buf; + struct spa_meta_header *h; + struct spa_list link; +}; + +struct seq_port { + uint32_t id; + enum spa_direction direction; + snd_seq_addr_t addr; + + uint64_t info_all; + struct spa_port_info info; + struct spa_param_info params[8]; + + struct spa_io_buffers *io; + + struct buffer buffers[MAX_BUFFERS]; + unsigned int n_buffers; + + struct spa_list free; + struct spa_list ready; + + struct buffer *buffer; + struct spa_pod_builder builder; + struct spa_pod_frame frame; + + struct spa_audio_info current_format; + unsigned int have_format:1; + unsigned int valid:1; +}; + +struct seq_stream { + enum spa_direction direction; + unsigned int caps; + snd_midi_event_t *codec; + struct seq_port ports[MAX_PORTS]; +}; + +struct seq_conn { + snd_seq_t *hndl; + int client_id; + int port_id; + int queue_id; + int fd; + struct spa_source source; +}; + +struct seq_state { + struct spa_handle handle; + struct spa_node node; + + struct spa_log *log; + struct spa_system *data_system; + struct spa_loop *data_loop; + struct spa_loop *main_loop; + + struct seq_conn sys; + struct seq_conn event; + int (*port_info) (void *data, const snd_seq_addr_t *addr, const snd_seq_port_info_t *info); + void *port_info_data; + + struct spa_hook_list hooks; + struct spa_callbacks callbacks; + + uint64_t info_all; + struct spa_node_info info; + struct spa_param_info params[8]; + struct props props; + + struct spa_io_clock *clock; + struct spa_io_position *position; + + int rate_denom; + uint32_t duration; + uint32_t threshold; + struct spa_fraction rate; + + struct spa_source source; + int timerfd; + uint64_t current_time; + uint64_t next_time; + uint64_t queue_time; + + unsigned int opened:1; + unsigned int started:1; + unsigned int slaved:1; + + struct seq_stream streams[2]; +}; + +#define VALID_DIRECTION(this,d) ((d) == SPA_DIRECTION_INPUT || (d) == SPA_DIRECTION_OUTPUT) +#define VALID_PORT(this,d,p) ((p) < MAX_PORTS && this->streams[d].ports[p].id == (p)) +#define CHECK_IN_PORT(this,d,p) ((d) == SPA_DIRECTION_INPUT && VALID_PORT(this,d,p)) +#define CHECK_OUT_PORT(this,d,p) ((d) == SPA_DIRECTION_OUTPUT && VALID_PORT(this,d,p)) +#define CHECK_PORT(this,d,p) (VALID_DIRECTION(this,d) && VALID_PORT(this,d,p)) + +#define GET_PORT(this,d,p) (&this->streams[d].ports[p]) + +int spa_alsa_seq_open(struct seq_state *state); +int spa_alsa_seq_close(struct seq_state *state); + +int spa_alsa_seq_start(struct seq_state *state); +int spa_alsa_seq_pause(struct seq_state *state); +int spa_alsa_seq_reslave(struct seq_state *state); + +int spa_alsa_seq_recycle_buffer(struct seq_state *state, struct seq_port *port, uint32_t buffer_id); + +int spa_alsa_seq_process(struct seq_state *state); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* SPA_ALSA_SEQ_H */ diff --git a/spa/plugins/alsa/alsa.c b/spa/plugins/alsa/alsa.c index 6cfd597b8..5b27cb9c6 100644 --- a/spa/plugins/alsa/alsa.c +++ b/spa/plugins/alsa/alsa.c @@ -30,6 +30,7 @@ extern const struct spa_handle_factory spa_alsa_source_factory; extern const struct spa_handle_factory spa_alsa_sink_factory; extern const struct spa_handle_factory spa_alsa_monitor_factory; extern const struct spa_handle_factory spa_alsa_device_factory; +extern const struct spa_handle_factory spa_alsa_midi_source_factory; SPA_EXPORT int spa_handle_factory_enum(const struct spa_handle_factory **factory, uint32_t *index) @@ -50,6 +51,9 @@ int spa_handle_factory_enum(const struct spa_handle_factory **factory, uint32_t case 3: *factory = &spa_alsa_device_factory; break; + case 4: + *factory = &spa_alsa_midi_source_factory; + break; default: return 0; } diff --git a/spa/plugins/alsa/meson.build b/spa/plugins/alsa/meson.build index 79a462121..673840717 100644 --- a/spa/plugins/alsa/meson.build +++ b/spa/plugins/alsa/meson.build @@ -1,6 +1,8 @@ spa_alsa_sources = ['alsa.c', 'alsa-monitor.c', 'alsa-device.c', + 'alsa-seq-source.c', + 'alsa-seq.c', 'alsa-sink.c', 'alsa-source.c', 'alsa-utils.c'] diff --git a/src/daemon/pipewire.conf.in b/src/daemon/pipewire.conf.in index 079ec7309..0442717f6 100644 --- a/src/daemon/pipewire.conf.in +++ b/src/daemon/pipewire.conf.in @@ -11,6 +11,7 @@ add-spa-lib api.vulkan.* vulkan/libspa-vulkan add-spa-lib api.jack.* jack/libspa-jack #load-module libpipewire-module-spa-device api.jack.device +load-module libpipewire-module-spa-node api.alsa.midi.source node.name=MIDI-Bridge load-module libpipewire-module-rtkit load-module libpipewire-module-protocol-native load-module libpipewire-module-spa-node-factory