]> mj.ucw.cz Git - misc.git/blobdiff - ursaryd/ut.c
Ursary: First light...
[misc.git] / ursaryd / ut.c
index afb70890f4ce2a7bf071e5560856fc15779db51e..0468955ed61ba778ed923c44659be3225c406ada 100644 (file)
 #define LOCAL_DEBUG
 
 #include <ucw/lib.h>
-#include <ucw/bitops.h>
 #include <ucw/clists.h>
-#include <ucw/gary.h>
 #include <ucw/mainloop.h>
-#include <ucw/string.h>
+#include <ucw/stkstring.h>
 
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
-#include <sys/poll.h>
-#include <sys/time.h>
 
-#include <libusb.h>
 #include <pulse/pulseaudio.h>
 
-/*
- *  Interface to Novation Nocturn
- *
- *  Protocol reverse-engineered by De Wet van Niekerk <dewert@gmail.com>,
- *  see https://github.com/dewert/nocturn-linux-midi for inspiration.
- */
+#include "ursaryd.h"
 
-static libusb_context *usb_ctx;
-static libusb_device_handle *usb_dev;
+/*** Interface to PulseAudio ***/
 
-static struct main_file **usb_fds;
+static pa_context *pulse_ctx;
+
+static void pulse_dump(void);
+
+enum pulse_state {
+  PS_OFFLINE,
+  PS_SUBSCRIBE,
+  PS_GET_CLIENTS,
+  PS_GET_SINKS,
+  PS_GET_SINK_INPUTS,
+  PS_ONLINE,
+};
 
-static int usb_fd_ready(struct main_file *f UNUSED)
+static enum pulse_state pulse_state;
+#define PULSE_STATE(s) do { pulse_state = s; DBG("Pulse: " #s); } while (0)
+
+// Tracking of currently running asynchronous operations
+struct pulse_op {
+  cnode n;
+  pa_operation *o;
+  bool is_init;
+};
+
+static clist pulse_op_list;
+
+static struct pulse_op *pulse_op_new(void)
 {
-  DBG("USB: Handling events (ready on fd %d)", f->fd);
-  struct timeval tv = { 0, 0 };
-  int comp = 0;
-  int err = libusb_handle_events_timeout_completed(usb_ctx, &tv, &comp);
-  if (err < 0)
-    msg(L_ERROR, "libusb_handle_events: error %d", err);
-  return HOOK_IDLE;
+  struct pulse_op *op = xmalloc_zero(sizeof(*op));
+  clist_add_tail(&pulse_op_list, &op->n);
+  return op;
 }
 
-static void usb_added_fd(int fd, short events, void *user_data UNUSED)
+static void pulse_op_done(struct pulse_op *op)
 {
-  if (fd >= (int) GARY_SIZE(usb_fds))
-    GARY_RESIZE(usb_fds, fd + 1);
+  if (op->o)
+    pa_operation_unref(op->o);
+  clist_remove(&op->n);
+  xfree(op);
+}
 
-  struct main_file *f = usb_fds[fd];
-  if (!f)
-    {
-      f = xmalloc_zero(sizeof(*f));
-      usb_fds[fd] = f;
-    }
-  else if (file_is_active(f))
+static void pulse_op_cancel_all(void)
+{
+  struct pulse_op *op;
+  while (op = (struct pulse_op *) clist_head(&pulse_op_list))
     {
-      DBG("USB: Releasing fd %d", fd);
-      file_del(f);
+      DBG("Pulse: Cancelling pending operation");
+      pa_operation_cancel(op->o);
+      pulse_op_done(op);
     }
-
-  DBG("USB: Adding fd %d with event mask %u", fd, events);
-  f->fd = fd;
-  f->read_handler = (events & POLLIN) ? usb_fd_ready : NULL;
-  f->write_handler = (events & POLLOUT) ? usb_fd_ready : NULL;
-  file_add(f);
 }
 
-static void usb_removed_fd(int fd, void *user_data UNUSED)
+#define PULSE_ASYNC_RUN(name, ...) do { struct pulse_op *_op = pulse_op_new(); _op->o = name(__VA_ARGS__, _op); } while (0)
+#define PULSE_ASYNC_INIT_RUN(name, ...) do { struct pulse_op *_op = pulse_op_new(); _op->is_init = 1; _op->o = name(__VA_ARGS__, _op); } while (0)
+
+static void pulse_success_cb(pa_context *ctx UNUSED, int success, void *userdata)
 {
-  DBG("USB: Releasing fd %d", fd);
-  ASSERT(fd < (int) GARY_SIZE(usb_fds));
-  struct main_file *f = usb_fds[fd];
-  ASSERT(f);
-  ASSERT(file_is_active(f));
-  file_del(f);
+  if (!success)
+    msg(L_ERROR, "Pulse: Failure reported");
+  pulse_op_done(userdata);
 }
 
-static const char noct_init[4][9] = {
-  { 3, 0xb0, 0x00, 0x00 },
-  { 8, 0x28, 0x00, 0x2b, 0x4a, 0x2c, 0x00, 0x2e, 0x35 },
-  { 6, 0x2a, 0x02, 0x2c, 0x72, 0x2e, 0x30 },
-  { 2, 0x7f, 0x00 },
-};
-
-static void noct_read_done(struct libusb_transfer *xfer)
+static void pulse_dump_proplist(pa_proplist *pl UNUSED)
 {
-  byte *pkt = xfer->buffer;
-  int len = xfer->actual_length;
-  DBG("USB: Read done: status %d, length %d", xfer->status, len);
+#if 0
+  void *iterator = NULL;
+  const char *key;
 
-  if (xfer->status != LIBUSB_TRANSFER_COMPLETED)
+  while (key = pa_proplist_iterate(pl, &iterator))
     {
-      msg(L_ERROR, "USB read failed with status %d, not submitting again", xfer->status);
-      return;
+      const char *val = pa_proplist_gets(pl, key);
+      DBG("   %s = %s", key, val);
     }
-
-#ifdef LOCAL_DEBUG
-  char buf[256];
-  mem_to_hex(buf, pkt, len, ' ');
-  DBG("USB: Read <%s>", buf);
 #endif
+}
+
+struct pulse_sink_input {
+  int idx;
+  char *name;
+  int client_idx;
+  int sink_idx;
+  uns volume;
+  uns mute;
+};
+
+#define HASH_NODE struct pulse_sink_input
+#define HASH_PREFIX(x) pulse_sink_input_##x
+#define HASH_KEY_ATOMIC idx
+// #define HASH_WANT_CLEANUP
+#define HASH_WANT_LOOKUP
+#define HASH_WANT_REMOVE
+#define HASH_ZERO_FILL
+#include <ucw/hashtable.h>
+
+#define SET_STRING(_field, _val) do { if (!_field || strcmp(_field, _val)) { xfree(_field); _field = xstrdup(_val); } } while (0)
 
-  int i = 0;
-  while (i < len)
+static void pulse_sink_input_cb(pa_context *ctx UNUSED, const pa_sink_input_info *i, int eol, void *userdata)
+{
+  struct pulse_op *op = userdata;
+
+  if (eol)
     {
-      if (i + 3 > len)
-       {
-         msg(L_ERROR, "Unknown USB packet: length %d not divisible by 3", len);
-         break;
-       }
-      if (pkt[i] != 0xb0)
-       {
-         msg(L_ERROR, "Unknown USB packet: expected 0xb0 at position %d", i);
-         break;
-       }
-      int cmd = pkt[i+1];
-      int arg = pkt[i+2];
-      i += 3;
-      switch (cmd)
+      if (op->is_init)
        {
-       case 0x30:
-         // Unknown packet sent during init
-         continue;
-       case 0x40 ... 0x47:
-         if (arg < 0x80)
-           {
-             int r = cmd - 0x40;
-             int delta = (arg < 0x40 ? arg : arg - 0x80);
-             DBG("Noct: Rotary %d = %d", r, delta);
-             continue;
-           }
-         break;
-       case 0x48:
-         if (arg < 0x80)
-           {
-             DBG("Noct: Slider value = %d", arg);
-             continue;
-           }
-         break;
-       case 0x49:
-         // Unknown packet, maybe least significant bit of slider
-         continue;
-       case 0x4a:
-         if (arg < 0x80)
-           {
-             int delta = (arg < 0x40 ? arg : arg - 0x80);
-             DBG("Noct: Center = %d", delta);
-             continue;
-           }
-         break;
-       case 0x52:
-         if (arg == 0x00 || arg == 0x7f)
-           {
-             int state = !!arg;
-             DBG("Noct: Center touch = %d", state);
-             continue;
-           }
-         break;
-       case 0x53:
-         if (arg == 0x00 || arg == 0x7f)
-           {
-             int state = !!arg;
-             DBG("Noct: Slider touch = %d", state);
-             continue;
-           }
-         break;
-       case 0x60 ... 0x67:
-         if (arg == 0x00 || arg == 0x7f)
-           {
-             int r = cmd - 0x60;
-             int state = !!arg;
-             DBG("Noct: Rotary %d touch = %d", r, state);
-             continue;
-           }
-         break;
-       case 0x70 ... 0x7f:
-         if (arg == 0x00 || arg == 0x7f)
-           {
-             int b = cmd - 0x70;
-             int state = !!arg;
-             DBG("Noct: Button %d = %d", b, state);
-             continue;
-           }
-         break;
+         PULSE_STATE(PS_ONLINE);
+         schedule_update();
        }
-      msg(L_ERROR, "Unknown USB packet: unrecognized cmd=%02x arg=%02x", cmd, arg);
+      pulse_op_done(op);
+      return;
     }
 
-  int err;
-  if ((err = libusb_submit_transfer(xfer)) < 0)
-    die("Cannot submit transfer: error %d", err);
+  DBG("Pulse: SINK INPUT #%u: %s client=%d sink=%d has_vol=%d vol_rw=%d volume=%u mute=%d",
+    i->index, i->name, i->client, i->sink, i->has_volume, i->volume_writable, i->volume.values[0], i->mute);
+  pulse_dump_proplist(i->proplist);
+
+  struct pulse_sink_input *s = pulse_sink_input_lookup(i->index);
+  SET_STRING(s->name, i->name);
+  s->client_idx = i->client;
+  s->sink_idx = i->sink;
+  s->volume = pa_cvolume_avg(&i->volume);
+  s->mute = i->mute;
+  schedule_update();
 }
 
-static void noct_read_init(void)
+static void pulse_sink_input_gone(int idx)
 {
-  DBG("Noct: Read init");
-
-  struct libusb_transfer *xfer = libusb_alloc_transfer(0);
-  libusb_fill_interrupt_transfer(xfer, usb_dev, 0x81, xmalloc(8), 8, noct_read_done, NULL, 0);
-
-  int err;
-  if ((err = libusb_submit_transfer(xfer)) < 0)
-    die("Cannot submit transfer: error %d", err);
+  DBG("Pulse: REMOVE SINK INPUT #%d", idx);
+  struct pulse_sink_input *s = pulse_sink_input_lookup(idx);
+  pulse_sink_input_remove(s);
+  schedule_update();
 }
 
-static byte noct_button_state[16];
-static byte noct_ring_mode[8];         // 0=from-min, 1=from-max, 2=from-mid-right, 3=from-mid-both, 4=single-on, 5=single-off
-static byte noct_ring_val[9];
-
-static uns noct_dirty_button;
-static uns noct_dirty_ring_mode;
-static uns noct_dirty_ring_val;
+struct pulse_sink {
+  int idx;
+  char *name;
+  uns volume;
+  uns base_volume;
+  int mute;
+};
 
-static struct libusb_transfer *noct_write_xfer;
-static uns noct_write_pending;
-static void noct_sched_write(void);
+#define HASH_NODE struct pulse_sink
+#define HASH_PREFIX(x) pulse_sink_##x
+#define HASH_KEY_ATOMIC idx
+// #define HASH_WANT_CLEANUP
+#define HASH_WANT_LOOKUP
+#define HASH_WANT_REMOVE
+#define HASH_ZERO_FILL
+#include <ucw/hashtable.h>
 
-static void noct_write_done(struct libusb_transfer *xfer)
+static void pulse_sink_cb(pa_context *ctx, const pa_sink_info *i, int eol, void *userdata)
 {
-  int len = xfer->actual_length;
-  DBG("USB: Write done: status %d, length %d", xfer->status, len);
+  struct pulse_op *op = userdata;
 
-  if (xfer->status != LIBUSB_TRANSFER_COMPLETED)
+  if (eol)
     {
-      msg(L_ERROR, "USB write failed with status %d", xfer->status);
+      if (op->is_init)
+       {
+         PULSE_STATE(PS_GET_SINK_INPUTS);
+         PULSE_ASYNC_INIT_RUN(pa_context_get_sink_input_info_list, ctx, pulse_sink_input_cb);
+       }
+      pulse_op_done(op);
       return;
     }
 
-  noct_write_pending = 0;
-  noct_sched_write();
+  DBG("Pulse: SINK #%u: %s (%s) flags=%08x volume=%u mute=%d base_vol=%u state=%u",
+    i->index, i->name, i->description, i->flags, i->volume.values[0], i->mute, i->base_volume, i->state);
+  pulse_dump_proplist(i->proplist);
+
+  struct pulse_sink *s = pulse_sink_lookup(i->index);
+  SET_STRING(s->name, i->name);
+  s->volume = pa_cvolume_avg(&i->volume);
+  s->base_volume = i->base_volume;
+  s->mute = i->mute;
+  schedule_update();
 }
 
-static void noct_do_write(uns cmd, uns arg)
+static void pulse_sink_gone(int idx)
 {
-  DBG("USB: Submitting write %02x %02x", cmd, arg);
-  ASSERT(!noct_write_pending);
-  noct_write_pending = 1;
-
-  struct libusb_transfer *xfer = noct_write_xfer;
-  byte *pkt = xfer->buffer;
-  pkt[0] = cmd;
-  pkt[1] = arg;
-  xfer->length = 2;
-
-  int err;
-  if ((err = libusb_submit_transfer(xfer)) < 0)
-    die("Cannot submit transfer: error %d", err);
+  DBG("Pulse: REMOVE SINK #%d", idx);
+  struct pulse_sink *s = pulse_sink_lookup(idx);
+  pulse_sink_remove(s);
+  schedule_update();
 }
 
-static void noct_sched_write(void)
+static struct pulse_sink *pulse_sink_by_name(const char *name)
 {
-  if (noct_write_pending)
-    return;
-
-  if (noct_dirty_button)
-    {
-      int i = bit_ffs(noct_dirty_button);
-      noct_dirty_button ^= 1U << i;
-      noct_do_write(0x70 + i, noct_button_state[i]);
-    }
-  else if (noct_dirty_ring_mode)
+  HASH_FOR_ALL(pulse_sink, s)
     {
-      int i = bit_ffs(noct_dirty_ring_mode);
-      noct_dirty_ring_mode ^= 1U << i;
-      noct_do_write(0x48 + i, noct_ring_mode[i] << 4);
-    }
-  else if (noct_dirty_ring_val)
-    {
-      int i = bit_ffs(noct_dirty_ring_val);
-      noct_dirty_ring_val ^= 1U << i;
-      if (i == 8)
-       noct_do_write(0x50 + i, noct_ring_val[i]);
-      else
-       noct_do_write(0x40 + i, noct_ring_val[i]);
+      if (!strcmp(s->name, name))
+       return s;
     }
+  HASH_END_FOR;
+  return NULL;
 }
 
-static void noct_write_init(void)
-{
-  DBG("Noct: Write init");
-
-  noct_write_xfer = libusb_alloc_transfer(0);
-  libusb_fill_interrupt_transfer(noct_write_xfer, usb_dev, 0x02, xmalloc(8), 0, noct_write_done, NULL, 1000);
+struct pulse_client {
+  int idx;
+  char *name;
+  char *host;
+};
 
-#if 0 // FIXME
-  noct_button_state[2] = 1;
-  noct_ring_mode[0] = 4;
-  noct_ring_val[0] = 0x40;
-#endif
+#define HASH_NODE struct pulse_client
+#define HASH_PREFIX(x) pulse_client_##x
+#define HASH_KEY_ATOMIC idx
+// #define HASH_WANT_CLEANUP
+#define HASH_WANT_LOOKUP
+#define HASH_WANT_REMOVE
+#define HASH_ZERO_FILL
+#include <ucw/hashtable.h>
 
-  noct_dirty_button = 0xffff;
-  noct_dirty_ring_mode = 0xff;
-  noct_dirty_ring_val = 0x1ff;
-  noct_sched_write();
-}
-
-static void usb_init(void)
+static void pulse_client_cb(pa_context *ctx, const pa_client_info *i, int eol, void *userdata)
 {
-  int err;
-
-  if ((err = libusb_init(&usb_ctx)) < 0)
-    die("libusb_init failed: error %d", err);
-  libusb_set_debug(usb_ctx, 3);
+  struct pulse_op *op = userdata;
 
-  libusb_device **dev_list;
-  libusb_device *found_dev = NULL;
-  ssize_t len = libusb_get_device_list(usb_ctx, &dev_list);
-  for (ssize_t i=0; i < len; i++)
+  if (eol)
     {
-      libusb_device *dev = dev_list[i];
-      struct libusb_device_descriptor desc;
-      if (libusb_get_device_descriptor(dev, &desc) >= 0 &&
-         desc.idVendor == 0x1235 &&
-         desc.idProduct == 0x000a)
+      if (op->is_init)
        {
-         msg(L_DEBUG, "Found device: bus %d, addr %d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
-         if (found_dev)
-           die("Multiple Nocturn devices found. Please fix me to handle it.");
-         found_dev = libusb_ref_device(dev);
+         PULSE_STATE(PS_GET_SINKS);
+         PULSE_ASYNC_INIT_RUN(pa_context_get_sink_info_list, ctx, pulse_sink_cb);
        }
+      pulse_op_done(op);
+      return;
     }
-  libusb_free_device_list(dev_list, 1);
-
-  if (!found_dev)
-    die("No Nocturn device found");
-
-  msg(L_DEBUG, "Initializing device");
-
-  if ((err = libusb_open(found_dev, &usb_dev)) < 0)
-    die("libusb_open failed: error %d", err);
-
-  // There exist configurations 1 (high brightness) and 2 (power-save)
-  if ((err = libusb_set_configuration(usb_dev, 1)) < 0)
-    die("libusb_set_configuration: error %d", err);
-
-  if ((err = libusb_claim_interface(usb_dev, 0)) < 0)
-    die("libusb_claim_interface: error %d", err);
-
-  for (int i=0; i<4; i++)
-    {
-      int done;
-      if ((err = libusb_interrupt_transfer(usb_dev, 0x02, (byte *) noct_init[i] + 1, noct_init[i][0], &done, 5000)) < 0)
-       die("Cannot send init packets: error %d", err);
-      if (done != noct_init[i][0])
-       die("Partial send of init packet: %d < %d", done, noct_init[i][0]);
-    }
-
-#if 0
-  byte xxx[] = { 0x7f, 0x01 };
-  int done;
-  libusb_interrupt_transfer(usb_dev, 0x02, xxx, 2, &done, 5000);
-#endif
 
-  DBG("USB: Connecting libusb to mainloop");
+  char *host = stk_strdup(pa_proplist_gets(i->proplist, "application.process.host") ? : "?");
+  DBG("Pulse: CLIENT #%u: %s mod=%u drv=%s host=%s",
+    i->index, i->name, i->owner_module, i->driver, host);
+  pulse_dump_proplist(i->proplist);
 
-  if (!libusb_pollfds_handle_timeouts(usb_ctx))
-    die("Unsupported version of libusb, please fix me");
-
-  GARY_INIT_ZERO(usb_fds, 0);
-  libusb_set_pollfd_notifiers(usb_ctx, usb_added_fd, usb_removed_fd, NULL);
-
-  const struct libusb_pollfd **fds = libusb_get_pollfds(usb_ctx);
-  ASSERT(fds);
-  for (int i=0; fds[i]; i++)
-    usb_added_fd(fds[i]->fd, fds[i]->events, NULL);
-  free(fds);
-
-  noct_read_init();
-  noct_write_init();
+  struct pulse_client *c = pulse_client_lookup(i->index);
+  SET_STRING(c->name, i->name);
+  SET_STRING(c->host, host);
+  schedule_update();
 }
 
-/*
- *  Interface to PulseAudio
- *
- *  FIXME
- */
-
-struct pmain_io {
-  cnode n;
-  struct main_file f;
-  clist io_events;
-};
-
-static clist pmain_io_list;
-
-struct pa_io_event {
-  cnode n;
-  cnode gc_n;
-  struct pmain_io *io;
-  pa_io_event_flags_t events;
-  pa_io_event_cb_t callback;
-  pa_io_event_destroy_cb_t destroy_callback;
-  void *userdata;
-};
-
-static clist pmain_io_gc_list;
-
-static pa_io_event *pmain_io_new(pa_mainloop_api *api, int fd, pa_io_event_flags_t events, pa_io_event_cb_t cb, void *userdata);
-static void pmain_io_enable(pa_io_event *e, pa_io_event_flags_t events);
-static void pmain_io_free(pa_io_event *e);
-static void pmain_io_set_destroy(pa_io_event *e, pa_io_event_destroy_cb_t cb);
-
-struct pa_time_event {
-  cnode n;
-  struct main_timer t;
-  pa_time_event_cb_t callback;
-  pa_time_event_destroy_cb_t destroy_callback;
-  void *userdata;
-  struct timeval tv;
-};
-
-static clist pmain_time_gc_list;
-
-static pa_time_event *pmain_time_new(pa_mainloop_api *api, const struct timeval *tv, pa_time_event_cb_t cb, void *userdata);
-static void pmain_time_restart(pa_time_event *e, const struct timeval *tv);
-static void pmain_time_free(pa_time_event *e);
-static void pmain_time_set_destroy(pa_time_event *e, pa_time_event_destroy_cb_t cb);
-
-struct pa_defer_event {
-  cnode n;
-  struct main_hook h;
-  pa_defer_event_cb_t callback;
-  pa_defer_event_destroy_cb_t destroy_callback;
-  void *userdata;
-};
-
-static clist pmain_defer_gc_list;
-
-static pa_defer_event *pmain_defer_new(pa_mainloop_api *api, pa_defer_event_cb_t cb, void *userdata);
-static void pmain_defer_enable(pa_defer_event *e, int b);
-static void pmain_defer_free(pa_defer_event *e);
-static void pmain_defer_set_destroy(pa_defer_event *e, pa_defer_event_destroy_cb_t cb);
-
-static void pmain_quit(pa_mainloop_api *a, int retval);
-
-static struct main_hook pmain_gc_hook;
-
-static void pmain_trigger_gc(void);
-
-static struct pa_mainloop_api pmainloop_api = {
-  .io_new = pmain_io_new,
-  .io_enable = pmain_io_enable,
-  .io_free = pmain_io_free,
-  .io_set_destroy = pmain_io_set_destroy,
-
-  .time_new = pmain_time_new,
-  .time_restart = pmain_time_restart,
-  .time_free = pmain_time_free,
-  .time_set_destroy = pmain_time_set_destroy,
-
-  .defer_new = pmain_defer_new,
-  .defer_enable = pmain_defer_enable,
-  .defer_free = pmain_defer_free,
-  .defer_set_destroy = pmain_defer_set_destroy,
-
-  .quit = pmain_quit,
-};
-
-static struct pmain_io *pmain_get_io(int fd)
+static void pulse_client_gone(int idx)
 {
-  CLIST_FOR_EACH(struct pmain_io *, io, pmain_io_list)
-    if (io->f.fd == fd)
-      {
-       DBG("Pulse: Recycling IO master");
-       return io;
-      }
-
-  struct pmain_io *io = xmalloc(sizeof(*io));
-  io->f.fd = fd;
-  io->f.data = io;
-  clist_add_tail(&pmain_io_list, &io->n);
-  clist_init(&io->io_events);
-  return io;
+  DBG("Pulse: REMOVE CLIENT #%d", idx);
+  struct pulse_client *c = pulse_client_lookup(idx);
+  pulse_client_remove(c);
+  schedule_update();
 }
 
-static pa_io_event *pmain_io_new(pa_mainloop_api *api UNUSED, int fd, pa_io_event_flags_t events, pa_io_event_cb_t cb, void *userdata)
+static void pulse_subscribe_done_cb(pa_context *ctx, int success, void *userdata)
 {
-  struct pa_io_event *e = xmalloc_zero(sizeof(*e));
-  DBG("Pulse: Creating new IO %p for fd %u", e, fd);
-
-  e->io = pmain_get_io(fd);
-  e->callback = cb;
-  e->userdata = userdata;
-  clist_add_head(&e->io->io_events, &e->n);    // Do not call the new IO if created from another IO on the same fd
-  pmain_io_enable(e, events);
-  return e;
+  pulse_op_done(userdata);
+
+  if (!success)
+    msg(L_ERROR, "pa_context_subscribe failed: success=%d", success);
+
+  PULSE_STATE(PS_GET_CLIENTS);
+  PULSE_ASYNC_INIT_RUN(pa_context_get_client_info_list, ctx, pulse_client_cb);
 }
 
-static int pmain_io_read(struct main_file *f)
+static void pulse_event_cb(pa_context *ctx, pa_subscription_event_type_t type, uint32_t idx, void *userdata UNUSED)
 {
-  struct pmain_io *io = f->data;
-  DBG("Pulse: fd %d ready for read", io->f.fd);
-
-  CLIST_FOR_EACH(struct pa_io_event *, e, io->io_events)
-    if (e->events & PA_IO_EVENT_INPUT)
-      {
-       DBG("Pulse: Callback on IO %p", e);
-       e->callback(&pmainloop_api, e, io->f.fd, PA_IO_EVENT_INPUT, e->userdata);
-      }
-
-  DBG("Pulse: fd %d read done", io->f.fd);
-  return HOOK_IDLE;
+  DBG("Pulse: SUBSCRIBE EVENT type=%08x idx=%u", type, idx);
+
+  uns object = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK;
+  uns action = type & PA_SUBSCRIPTION_EVENT_TYPE_MASK;
+  switch (object)
+    {
+    case PA_SUBSCRIPTION_EVENT_CLIENT:
+      if (action == PA_SUBSCRIPTION_EVENT_NEW || action == PA_SUBSCRIPTION_EVENT_CHANGE)
+       PULSE_ASYNC_RUN(pa_context_get_client_info, ctx, idx, pulse_client_cb);
+      else if (action == PA_SUBSCRIPTION_EVENT_REMOVE)
+       pulse_client_gone(idx);
+      break;
+    case PA_SUBSCRIPTION_EVENT_SINK:
+      if (action == PA_SUBSCRIPTION_EVENT_NEW || action == PA_SUBSCRIPTION_EVENT_CHANGE)
+       PULSE_ASYNC_RUN(pa_context_get_sink_info_by_index, ctx, idx, pulse_sink_cb);
+      else if (action == PA_SUBSCRIPTION_EVENT_REMOVE)
+       pulse_sink_gone(idx);
+      break;
+    case PA_SUBSCRIPTION_EVENT_SINK_INPUT:
+      if (action == PA_SUBSCRIPTION_EVENT_NEW || action == PA_SUBSCRIPTION_EVENT_CHANGE)
+       PULSE_ASYNC_RUN(pa_context_get_sink_input_info, ctx, idx, pulse_sink_input_cb);
+      else if (action == PA_SUBSCRIPTION_EVENT_REMOVE)
+       pulse_sink_input_gone(idx);
+      break;
+    }
 }
 
-static int pmain_io_write(struct main_file *f)
+static void pulse_state_cb(pa_context *ctx, void *userdata UNUSED)
 {
-  struct pmain_io *io = f->data;
-  DBG("Pulse: fd %d ready for write", io->f.fd);
-
-  CLIST_FOR_EACH(struct pa_io_event *, e, io->io_events)
-    if (e->events & PA_IO_EVENT_OUTPUT)
-      {
-       DBG("Pulse: Callback on IO %p", e);
-       e->callback(&pmainloop_api, e, io->f.fd, PA_IO_EVENT_OUTPUT, e->userdata);
-      }
-
-  DBG("Pulse: fd %d write done", io->f.fd);
-  return HOOK_IDLE;
+  int state = pa_context_get_state(ctx);
+  DBG("Pulse: State callback, new state = %d", state);
+  if (state == PA_CONTEXT_READY)
+    {
+      if (pulse_state == PS_OFFLINE)
+       {
+         PULSE_STATE(PS_SUBSCRIBE);
+         pa_context_set_subscribe_callback(ctx, pulse_event_cb, NULL);
+         PULSE_ASYNC_INIT_RUN(pa_context_subscribe, ctx, PA_SUBSCRIPTION_MASK_ALL, pulse_subscribe_done_cb);
+       }
+    }
+  else
+    {
+      if (pulse_state != PS_OFFLINE)
+       {
+         PULSE_STATE(PS_OFFLINE);
+         pulse_op_cancel_all();
+         // FIXME: Reset all data structures
+       }
+    }
 }
 
-static void pmain_io_enable(pa_io_event *e, pa_io_event_flags_t events)
+static void pulse_dump(void)
 {
-  struct pmain_io *io = e->io;
-  DBG("Pulse: Changing IO event mask for IO %p on fd %d to %02x", e, io->f.fd, events);
-  e->events = events;
+  HASH_FOR_ALL(pulse_client, c)
+    {
+      DBG("## Client #%d: %s host=%s", c->idx, c->name, c->host);
+    }
+  HASH_END_FOR;
 
-  pa_io_event_flags_t mask = 0;
-  CLIST_FOR_EACH(struct pa_io_event *, f, io->io_events)
-    mask |= f->events;
-  DBG("Pulse: Recalculated IO mask for fd %d to %02x", io->f.fd, mask);
+  HASH_FOR_ALL(pulse_sink, s)
+    {
+      DBG("## Sink #%d: %s volume=%u base_vol=%u mute=%u",
+       s->idx, s->name, s->volume, s->base_volume, s->mute);
+    }
+  HASH_END_FOR;
 
-  if (mask)
+  HASH_FOR_ALL(pulse_sink_input, s)
     {
-      io->f.read_handler = (mask & PA_IO_EVENT_INPUT) ? pmain_io_read : NULL;
-      io->f.write_handler = (mask & PA_IO_EVENT_OUTPUT) ? pmain_io_write : NULL;
-      if (file_is_active(&io->f))
-       file_chg(&io->f);
-      else
-       file_add(&io->f);
+      DBG("## Sink input #%d: %s client=%d sink=%d volume=%u mute=%u",
+       s->idx, s->name, s->client_idx, s->sink_idx, s->volume, s->mute);
     }
-  else
-    file_del(&io->f);
+  HASH_END_FOR;
 }
 
-static void pmain_io_free(pa_io_event *e)
+static void pulse_init(void)
 {
-  DBG("Pulse: Deleting IO %p for fd %d", e, e->io->f.fd);
-  pmain_io_enable(e, 0);
-  clist_add_tail(&pmain_io_gc_list, &e->gc_n);
-  pmain_trigger_gc();
-}
+  pmain_init();
+  clist_init(&pulse_op_list);
+  pulse_client_init();
+  pulse_sink_init();
+  pulse_sink_input_init();
 
-static void pmain_io_set_destroy(pa_io_event *e, pa_io_event_destroy_cb_t cb)
-{
-  e->destroy_callback = cb;
+  pulse_ctx = pa_context_new(&pmain_api, "ursaryd");
+  pa_context_set_state_callback(pulse_ctx, pulse_state_cb, NULL);
+  pa_context_connect(pulse_ctx, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL);
 }
 
-static void pmain_time_handler(struct main_timer *t)
-{
-  struct pa_time_event *e = t->data;
-  DBG("Pulse: Timer %p triggered", e);
-  timer_del(t);
-  e->callback(&pmainloop_api, e, &e->tv, e->userdata);
-  DBG("Pulse: Timer %p done", e);
-}
+/*** High-level logic ***/
 
-static pa_time_event *pmain_time_new(pa_mainloop_api *api UNUSED, const struct timeval *tv, pa_time_event_cb_t cb, void *userdata)
-{
-  struct pa_time_event *e = xmalloc_zero(sizeof(*e));
-  DBG("Pulse: Creating timer %p", e);
-  e->callback = cb;
-  e->userdata = userdata;
-  e->t.handler = pmain_time_handler;
-  e->t.data = e;
-  pmain_time_restart(e, tv);
-  return e;
-}
+static struct main_timer update_timer;
 
-static timestamp_t timeval_to_timestamp(const struct timeval *tv)
+static void update_ring_from_sink(int ring, const char *sink_name)
 {
-  return 1000 * (timestamp_t) tv->tv_sec + tv->tv_usec / 1000;
-}
+  struct pulse_sink *s = pulse_sink_by_name(sink_name);
+  if (!s)
+    {
+      noct_set_ring(ring, RING_MODE_SINGLE_ON, 0x7f);
+      noct_set_button(ring, 0);
+      return;
+    }
 
-static void pmain_time_restart(pa_time_event *e, const struct timeval *tv)
-{
-  struct timeval now;
-  gettimeofday(&now, NULL);
-  timestamp_t ts_now = timeval_to_timestamp(&now);
-  timestamp_t ts_fire = timeval_to_timestamp(tv);
-  timestamp_t ts_delta = ts_fire - ts_now;
-  DBG("Pulse: Setting timer %p to %+d", e, (int) ts_delta);
-  timer_del(&e->t);
-  e->tv = *tv;
-  timer_add_rel(&e->t, ts_delta);
-}
+  if (s->mute)
+    {
+      noct_set_ring(ring, RING_MODE_SINGLE_ON, 0x7f);
+      noct_set_button(ring, 1);
+      return;
+    }
 
-static void pmain_time_free(pa_time_event *e)
-{
-  DBG("Pulse: Timer %p deleted", e);
-  timer_del(&e->t);
-  clist_add_tail(&pmain_time_gc_list, &e->n);
-  pmain_trigger_gc();
+  double vol = pa_sw_volume_to_linear(s->volume);
+  vol = CLAMP(vol, 0, 1);
+  int val = 0x7f * vol;
+  val = CLAMP(val, 0, 0x7f);
+  noct_set_ring(ring, RING_MODE_LEFT, val);
+  noct_set_button(ring, 0);
 }
 
-static void pmain_time_set_destroy(pa_time_event *e, pa_time_event_destroy_cb_t cb)
+static void do_update(struct main_timer *t)
 {
-  e->destroy_callback = cb;
-}
+  timer_del(t);
+  if (pulse_state != PS_ONLINE)
+    {
+      DBG("## UPDATE: Pulse is not online");
+      return;
+    }
+  if (!noct_is_ready())
+    {
+      DBG("## UPDATE: Nocturn is not ready");
+      return;
+    }
 
-static int pmain_defer_handler(struct main_hook *h)
-{
-  struct pa_defer_event *e = h->data;
-  DBG("Pulse: Deferred event %p triggered", e);
-  e->callback(&pmainloop_api, e, e->userdata);
-  DBG("Pulse: Deferred event done");
-  return hook_is_active(&e->h) ? HOOK_RETRY : HOOK_IDLE;
-}
+  DBG("## UPDATE");
+  pulse_dump();
 
-static pa_defer_event *pmain_defer_new(pa_mainloop_api *api UNUSED, pa_defer_event_cb_t cb, void *userdata)
-{
-  struct pa_defer_event *e = xmalloc_zero(sizeof(*e));
-  DBG("Pulse: Creating defer %p", e);
-  e->callback = cb;
-  e->userdata = userdata;
-  e->h.handler = pmain_defer_handler;
-  e->h.data = e;
-  pmain_defer_enable(e, 1);
-  return e;
+  update_ring_from_sink(0, "ursarium");
+  update_ring_from_sink(1, "catarium");
 }
 
-static void pmain_defer_enable(pa_defer_event *e, int b)
+void schedule_update(void)
 {
-  DBG("Pulse: %sabling defer %p", (b ? "En" : "Dis"), e);
-  if (b)
-    hook_add(&e->h);
-  else
-    hook_del(&e->h);
+  timer_add_rel(&update_timer, 10);    // FIXME
 }
 
-static void pmain_defer_free(pa_defer_event *e)
+static void update_sink_from_rotary(int delta, const char *sink_name)
 {
-  DBG("Pulse: Deferred event %p deleted", e);
-  hook_del(&e->h);
-  clist_add_tail(&pmain_defer_gc_list, &e->n);
-  pmain_trigger_gc();
-}
+  struct pulse_sink *s = pulse_sink_by_name(sink_name);
+  if (!s)
+    return;
 
-static void pmain_defer_set_destroy(pa_defer_event *e, pa_defer_event_destroy_cb_t cb)
-{
-  e->destroy_callback = cb;
-}
+  double vol = pa_sw_volume_to_linear(s->volume);
+  vol += delta * 0.02;
+  vol = CLAMP(vol, 0, 1);
+  pa_cvolume cvol;
+  pa_cvolume_set(&cvol, 2, pa_sw_volume_from_linear(vol));
 
-static void pmain_quit(pa_mainloop_api *a UNUSED, int retval UNUSED)
-{
-  DBG("Pulse: Main loop quit not implemented");
+  DBG("## Setting volume of sink %s to %d", s->name, cvol.values[0]);
+  PULSE_ASYNC_RUN(pa_context_set_sink_volume_by_index, pulse_ctx, s->idx, &cvol, pulse_success_cb);
 }
 
-static int pmain_gc_handler(struct main_hook *h)
+void notify_rotary(int rotary, int delta)
 {
-  DBG("Pulse: Garbage collector");
-  hook_del(h);
-
-  cnode *n;
-  while (n = clist_remove_head(&pmain_io_gc_list))
-    {
-      struct pa_io_event *ei = SKIP_BACK(struct pa_io_event, gc_n, n);
-      struct pmain_io *io = ei->io;
-      DBG("Pulse: GC of IO event %p on fd %d", ei, io->f.fd);
-      if (ei->destroy_callback)
-       ei->destroy_callback(&pmainloop_api, ei, ei->userdata);
-      clist_remove(&ei->n);
-      if (clist_empty(&io->io_events))
-       {
-         ASSERT(!file_is_active(&io->f));
-         DBG("Pulse: GC of IO master for fd %d", io->f.fd);
-         clist_remove(&io->n);
-         xfree(io);
-       }
-      xfree(ei);
-    }
-
-  struct pa_time_event *et;
-  while (et = (struct pa_time_event *) clist_remove_head(&pmain_time_gc_list))
+  if (pulse_state != PS_ONLINE)
     {
-      DBG("Pulse: GC for timer %p", et);
-      if (et->destroy_callback)
-       et->destroy_callback(&pmainloop_api, et, et->userdata);
-      xfree(et);
+      DBG("## NOTIFY: Pulse is not inline");
+      return;
     }
 
-  struct pa_defer_event *ed;
-  while (ed = (struct pa_defer_event *) clist_remove_head(&pmain_defer_gc_list))
+  switch (rotary)
     {
-      DBG("Pulse: GC for defer %p", ed);
-      if (ed->destroy_callback)
-       ed->destroy_callback(&pmainloop_api, ed, ed->userdata);
-      xfree(ed);
+    case 0:
+      update_sink_from_rotary(delta, "ursarium");
+      break;
+    case 1:
+      update_sink_from_rotary(delta, "catarium");
+      break;
+    case 8:
+      update_sink_from_rotary(delta, "ursarium");
+      update_sink_from_rotary(delta, "catarium");
+      break;
     }
-
-  DBG("Pulse: Garbage collector done");
-  return HOOK_RETRY;
 }
 
-static void pmain_trigger_gc(void)
+static void update_sink_mute_from_button(int on, const char *sink_name)
 {
-  hook_add(&pmain_gc_hook);
-}
-
-static pa_context *pulse_ctx;
-static bool pulse_ready;
+  if (!on)
+    return;
 
-static void pulse_client_info_cb(pa_context *ctx, const pa_client_info *i, int eol, void *userdata)
-{
-  if (eol)
-    {
-      DBG("Pulse: CLIENT DONE");
-      return;
-    }
+  struct pulse_sink *s = pulse_sink_by_name(sink_name);
+  if (!s)
+    return;
 
-  DBG("Pulse: CLIENT #%u: %s mod=%u drv=%s", i->index, i->name, i->owner_module, i->driver);
+  DBG("## Setting mute of sink %s to %d", s->name, !s->mute);
+  PULSE_ASYNC_RUN(pa_context_set_sink_mute_by_index, pulse_ctx, s->idx, !s->mute, pulse_success_cb);
 }
 
-static void pulse_state_cb(pa_context *ctx, void *userdata UNUSED)
+void notify_button(int button, int on)
 {
-  int state = pa_context_get_state(ctx);
-  DBG("Pulse: State callback, new state = %d", state);
-  if (state == PA_CONTEXT_READY)
+  if (pulse_state != PS_ONLINE)
     {
-      if (!pulse_ready)
-       {
-         pulse_ready = 1;
-         DBG("Pulse: ONLINE");
-         pa_context_get_client_info_list(ctx, pulse_client_info_cb, NULL);
-         // FIXME: Discard the operation when server goes offline
-       }
+      DBG("## NOTIFY: Pulse is not inline");
+      return;
     }
-  else
+
+  switch (button)
     {
-      if (pulse_ready)
-       {
-         pulse_ready = 0;
-         DBG("Pulse: OFFLINE");
-       }
+    case 0:
+      update_sink_mute_from_button(on, "ursarium");
+      break;
+    case 1:
+      update_sink_mute_from_button(on, "catarium");
+      break;
     }
 }
 
-static void pulse_init(void)
-{
-  clist_init(&pmain_io_list);
-  clist_init(&pmain_io_gc_list);
-  clist_init(&pmain_time_gc_list);
-  clist_init(&pmain_defer_gc_list);
-  pmain_gc_hook.handler = pmain_gc_handler;
-
-  pulse_ctx = pa_context_new(&pmainloop_api, "ursaryd");
-  pa_context_set_state_callback(pulse_ctx, pulse_state_cb, NULL);
-  pa_context_connect(pulse_ctx, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL);
-}
-
 int main(int argc UNUSED, char **argv)
 {
   log_init(argv[0]);
   main_init();
+  update_timer.handler = do_update;
 
-  // msg(L_INFO, "Initializing USB");
-  // usb_init();
+  noct_init();
 
   msg(L_INFO, "Initializing PulseAudio");
   pulse_init();