]> mj.ucw.cz Git - ursary.git/blob - ursaryd.c
Reformed volume handling
[ursary.git] / ursaryd.c
1 #define LOCAL_DEBUG
2
3 #include <ucw/lib.h>
4 #include <ucw/clists.h>
5 #include <ucw/mainloop.h>
6 #include <ucw/stkstring.h>
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <stdlib.h>
11
12 #include <pulse/pulseaudio.h>
13
14 #include "ursaryd.h"
15
16 /*** Interface to PulseAudio ***/
17
18 static pa_context *pulse_ctx;
19 static struct main_timer pulse_connect_timer;
20
21 static void pulse_dump(void);
22
23 enum pulse_state {
24   PS_OFFLINE,
25   PS_SUBSCRIBE,
26   PS_GET_CLIENTS,
27   PS_GET_SINKS,
28   PS_GET_SINK_INPUTS,
29   PS_ONLINE,
30 };
31
32 static enum pulse_state pulse_state;
33 #define PULSE_STATE(s) do { pulse_state = s; DBG("Pulse: " #s); } while (0)
34
35 // Tracking of currently running asynchronous operations
36 struct pulse_op {
37   cnode n;
38   pa_operation *o;
39   bool is_init;
40 };
41
42 static clist pulse_op_list;
43
44 static struct pulse_op *pulse_op_new(void)
45 {
46   struct pulse_op *op = xmalloc_zero(sizeof(*op));
47   clist_add_tail(&pulse_op_list, &op->n);
48   return op;
49 }
50
51 static void pulse_op_done(struct pulse_op *op)
52 {
53   if (op->o)
54     pa_operation_unref(op->o);
55   clist_remove(&op->n);
56   xfree(op);
57 }
58
59 static void pulse_op_cancel_all(void)
60 {
61   struct pulse_op *op;
62   while (op = (struct pulse_op *) clist_head(&pulse_op_list))
63     {
64       DBG("Pulse: Cancelling pending operation");
65       pa_operation_cancel(op->o);
66       pulse_op_done(op);
67     }
68 }
69
70 #define PULSE_ASYNC_RUN(name, ...) do { struct pulse_op *_op = pulse_op_new(); _op->o = name(__VA_ARGS__, _op); } while (0)
71 #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)
72
73 static void pulse_success_cb(pa_context *ctx UNUSED, int success, void *userdata)
74 {
75   if (!success)
76     msg(L_ERROR, "Pulse: Failure reported");
77   pulse_op_done(userdata);
78 }
79
80 static void pulse_dump_proplist(pa_proplist *pl UNUSED)
81 {
82 #if 0
83   void *iterator = NULL;
84   const char *key;
85
86   while (key = pa_proplist_iterate(pl, &iterator))
87     {
88       const char *val = pa_proplist_gets(pl, key);
89       DBG("   %s = %s", key, val);
90     }
91 #endif
92 }
93
94 struct pulse_sink_input {
95   int idx;
96   char *name;
97   int client_idx;
98   int sink_idx;
99   uns channels;
100   uns volume;
101   uns mute;
102   int noct_client_idx;          // Used by the high-level logic below
103 };
104
105 #define HASH_NODE struct pulse_sink_input
106 #define HASH_PREFIX(x) pulse_sink_input_##x
107 #define HASH_KEY_ATOMIC idx
108 #define HASH_WANT_CLEANUP
109 #define HASH_WANT_LOOKUP
110 #define HASH_WANT_REMOVE
111 #define HASH_ZERO_FILL
112 #include <ucw/hashtable.h>
113
114 #define SET_STRING(_field, _val) do { if (!_field || strcmp(_field, _val)) { xfree(_field); _field = xstrdup(_val); } } while (0)
115
116 static void pulse_sink_input_cb(pa_context *ctx UNUSED, const pa_sink_input_info *i, int eol, void *userdata)
117 {
118   struct pulse_op *op = userdata;
119
120   if (eol)
121     {
122       if (op->is_init)
123         {
124           PULSE_STATE(PS_ONLINE);
125           schedule_update();
126         }
127       pulse_op_done(op);
128       return;
129     }
130
131   DBG("Pulse: SINK INPUT #%u: %s client=%d sink=%d chans=%d has_vol=%d vol_rw=%d volume=%u mute=%d",
132     i->index, i->name, i->client, i->sink, i->channel_map.channels, i->has_volume, i->volume_writable, i->volume.values[0], i->mute);
133   pulse_dump_proplist(i->proplist);
134
135   struct pulse_sink_input *s = pulse_sink_input_lookup(i->index);
136   SET_STRING(s->name, i->name);
137   s->client_idx = i->client;
138   s->sink_idx = i->sink;
139   s->channels = i->channel_map.channels;
140   s->volume = pa_cvolume_avg(&i->volume);
141   s->mute = i->mute;
142   schedule_update();
143 }
144
145 static void pulse_sink_input_gone(int idx)
146 {
147   DBG("Pulse: REMOVE SINK INPUT #%d", idx);
148   struct pulse_sink_input *s = pulse_sink_input_lookup(idx);
149   pulse_sink_input_remove(s);
150   schedule_update();
151 }
152
153 struct pulse_sink {
154   int idx;
155   char *name;
156   uns channels;
157   uns volume;
158   uns base_volume;
159   int mute;
160 };
161
162 #define HASH_NODE struct pulse_sink
163 #define HASH_PREFIX(x) pulse_sink_##x
164 #define HASH_KEY_ATOMIC idx
165 #define HASH_WANT_CLEANUP
166 #define HASH_WANT_LOOKUP
167 #define HASH_WANT_REMOVE
168 #define HASH_ZERO_FILL
169 #include <ucw/hashtable.h>
170
171 static void pulse_sink_cb(pa_context *ctx, const pa_sink_info *i, int eol, void *userdata)
172 {
173   struct pulse_op *op = userdata;
174
175   if (eol)
176     {
177       if (op->is_init)
178         {
179           PULSE_STATE(PS_GET_SINK_INPUTS);
180           PULSE_ASYNC_INIT_RUN(pa_context_get_sink_input_info_list, ctx, pulse_sink_input_cb);
181         }
182       pulse_op_done(op);
183       return;
184     }
185
186   DBG("Pulse: SINK #%u: %s (%s) flags=%08x channels=%u volume=%u mute=%d base_vol=%u state=%u",
187     i->index, i->name, i->description, i->flags, i->channel_map.channels, i->volume.values[0], i->mute, i->base_volume, i->state);
188   pulse_dump_proplist(i->proplist);
189
190   struct pulse_sink *s = pulse_sink_lookup(i->index);
191   SET_STRING(s->name, i->name);
192   s->channels = i->channel_map.channels;
193   s->volume = pa_cvolume_avg(&i->volume);
194   s->base_volume = i->base_volume;
195   s->mute = i->mute;
196   schedule_update();
197 }
198
199 static void pulse_sink_gone(int idx)
200 {
201   DBG("Pulse: REMOVE SINK #%d", idx);
202   struct pulse_sink *s = pulse_sink_lookup(idx);
203   pulse_sink_remove(s);
204   schedule_update();
205 }
206
207 static struct pulse_sink *pulse_sink_by_name(const char *name)
208 {
209   HASH_FOR_ALL(pulse_sink, s)
210     {
211       if (!strcmp(s->name, name))
212         return s;
213     }
214   HASH_END_FOR;
215   return NULL;
216 }
217
218 struct pulse_client {
219   int idx;
220   char *name;
221   char *host;
222 };
223
224 #define HASH_NODE struct pulse_client
225 #define HASH_PREFIX(x) pulse_client_##x
226 #define HASH_KEY_ATOMIC idx
227 #define HASH_WANT_CLEANUP
228 #define HASH_WANT_LOOKUP
229 #define HASH_WANT_REMOVE
230 #define HASH_ZERO_FILL
231 #include <ucw/hashtable.h>
232
233 static void pulse_client_cb(pa_context *ctx, const pa_client_info *i, int eol, void *userdata)
234 {
235   struct pulse_op *op = userdata;
236
237   if (eol)
238     {
239       if (op->is_init)
240         {
241           PULSE_STATE(PS_GET_SINKS);
242           PULSE_ASYNC_INIT_RUN(pa_context_get_sink_info_list, ctx, pulse_sink_cb);
243         }
244       pulse_op_done(op);
245       return;
246     }
247
248   char *host = stk_strdup(pa_proplist_gets(i->proplist, "application.process.host") ? : "?");
249   DBG("Pulse: CLIENT #%u: %s mod=%u drv=%s host=%s",
250     i->index, i->name, i->owner_module, i->driver, host);
251   pulse_dump_proplist(i->proplist);
252
253   struct pulse_client *c = pulse_client_lookup(i->index);
254   SET_STRING(c->name, i->name);
255   SET_STRING(c->host, host);
256   schedule_update();
257 }
258
259 static void pulse_client_gone(int idx)
260 {
261   DBG("Pulse: REMOVE CLIENT #%d", idx);
262   struct pulse_client *c = pulse_client_lookup(idx);
263   pulse_client_remove(c);
264   schedule_update();
265 }
266
267 static void pulse_shutdown(void)
268 {
269   DBG("Pulse: Shutting down");
270   pulse_client_cleanup();
271   pulse_sink_cleanup();
272   pulse_sink_input_cleanup();
273 }
274
275 static void pulse_subscribe_done_cb(pa_context *ctx, int success, void *userdata)
276 {
277   pulse_op_done(userdata);
278
279   if (!success)
280     msg(L_ERROR, "pa_context_subscribe failed: success=%d", success);
281
282   PULSE_STATE(PS_GET_CLIENTS);
283   PULSE_ASYNC_INIT_RUN(pa_context_get_client_info_list, ctx, pulse_client_cb);
284 }
285
286 static void pulse_event_cb(pa_context *ctx, pa_subscription_event_type_t type, uint32_t idx, void *userdata UNUSED)
287 {
288   DBG("Pulse: SUBSCRIBE EVENT type=%08x idx=%u", type, idx);
289
290   uns object = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK;
291   uns action = type & PA_SUBSCRIPTION_EVENT_TYPE_MASK;
292   switch (object)
293     {
294     case PA_SUBSCRIPTION_EVENT_CLIENT:
295       if (action == PA_SUBSCRIPTION_EVENT_NEW || action == PA_SUBSCRIPTION_EVENT_CHANGE)
296         PULSE_ASYNC_RUN(pa_context_get_client_info, ctx, idx, pulse_client_cb);
297       else if (action == PA_SUBSCRIPTION_EVENT_REMOVE)
298         pulse_client_gone(idx);
299       break;
300     case PA_SUBSCRIPTION_EVENT_SINK:
301       if (action == PA_SUBSCRIPTION_EVENT_NEW || action == PA_SUBSCRIPTION_EVENT_CHANGE)
302         PULSE_ASYNC_RUN(pa_context_get_sink_info_by_index, ctx, idx, pulse_sink_cb);
303       else if (action == PA_SUBSCRIPTION_EVENT_REMOVE)
304         pulse_sink_gone(idx);
305       break;
306     case PA_SUBSCRIPTION_EVENT_SINK_INPUT:
307       if (action == PA_SUBSCRIPTION_EVENT_NEW || action == PA_SUBSCRIPTION_EVENT_CHANGE)
308         PULSE_ASYNC_RUN(pa_context_get_sink_input_info, ctx, idx, pulse_sink_input_cb);
309       else if (action == PA_SUBSCRIPTION_EVENT_REMOVE)
310         pulse_sink_input_gone(idx);
311       break;
312     }
313 }
314
315 static void pulse_state_cb(pa_context *ctx, void *userdata UNUSED)
316 {
317   int state = pa_context_get_state(ctx);
318   DBG("Pulse: State callback, new state = %d", state);
319   if (state == PA_CONTEXT_READY)
320     {
321       if (pulse_state == PS_OFFLINE)
322         {
323           PULSE_STATE(PS_SUBSCRIBE);
324           pa_context_set_subscribe_callback(ctx, pulse_event_cb, NULL);
325           PULSE_ASYNC_INIT_RUN(pa_context_subscribe, ctx, PA_SUBSCRIPTION_MASK_ALL, pulse_subscribe_done_cb);
326         }
327     }
328   else
329     {
330       if (pulse_state != PS_OFFLINE)
331         {
332           PULSE_STATE(PS_OFFLINE);
333           pulse_op_cancel_all();
334           pulse_shutdown();
335           schedule_update();
336         }
337       if (state == PA_CONTEXT_FAILED && !timer_is_active(&pulse_connect_timer))
338         timer_add_rel(&pulse_connect_timer, 2000);
339     }
340 }
341
342 static void pulse_dump(void)
343 {
344   HASH_FOR_ALL(pulse_client, c)
345     {
346       DBG("## Client #%d: %s host=%s", c->idx, c->name, c->host);
347     }
348   HASH_END_FOR;
349
350   HASH_FOR_ALL(pulse_sink, s)
351     {
352       DBG("## Sink #%d: %s channels=%u volume=%u base_vol=%u mute=%u",
353         s->idx, s->name, s->channels, s->volume, s->base_volume, s->mute);
354     }
355   HASH_END_FOR;
356
357   HASH_FOR_ALL(pulse_sink_input, s)
358     {
359       DBG("## Sink input #%d: %s client=%d sink=%d channels=%u volume=%u mute=%u",
360         s->idx, s->name, s->client_idx, s->sink_idx, s->channels, s->volume, s->mute);
361     }
362   HASH_END_FOR;
363 }
364
365 static void pulse_connect(struct main_timer *t)
366 {
367   DBG("Pulse: Connecting");
368   timer_del(t);
369
370   clist_init(&pulse_op_list);
371   pulse_client_init();
372   pulse_sink_init();
373   pulse_sink_input_init();
374
375   if (pulse_ctx)
376     pa_context_unref(pulse_ctx);
377   pulse_ctx = pa_context_new(&pmain_api, "ursaryd");
378
379   pa_context_set_state_callback(pulse_ctx, pulse_state_cb, NULL);
380   pa_context_connect(pulse_ctx, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL);
381 }
382
383 static void pulse_init(void)
384 {
385   pmain_init();
386
387   pulse_connect_timer.handler = pulse_connect;
388   timer_add_rel(&pulse_connect_timer, 0);
389 }
390
391 /*** High-level logic ***/
392
393 static struct main_timer update_timer;
394
395 static double volume_from_pa(pa_volume_t vol)
396 {
397   return (double) vol / PA_VOLUME_NORM;
398 }
399
400 static pa_volume_t volume_to_pa(double vol)
401 {
402   return vol * PA_VOLUME_NORM + 0.0001;
403 }
404
405 static void update_ring_from_sink(int ring, const char *sink_name)
406 {
407   struct pulse_sink *s = pulse_sink_by_name(sink_name);
408   if (!s)
409     {
410       noct_set_ring(ring, RING_MODE_SINGLE_ON, 0x7f);
411       noct_set_button(ring, 0);
412       return;
413     }
414
415   if (s->mute)
416     {
417       noct_set_ring(ring, RING_MODE_SINGLE_ON, 0x7f);
418       noct_set_button(ring, 1);
419       return;
420     }
421
422   double vol = CLAMP(volume_from_pa(s->volume), 0, 1);
423   noct_set_ring(ring, RING_MODE_LEFT, CLAMP((int)(0x7f * vol), 12, 0x7f));
424   noct_set_button(ring, 0);
425 }
426
427 static void update_sink_from_rotary(int delta, const char *sink_name)
428 {
429   struct pulse_sink *s = pulse_sink_by_name(sink_name);
430   if (!s)
431     return;
432
433   double vol = volume_from_pa(s->volume) + delta * 0.02;
434   pa_volume_t pavol = volume_to_pa(CLAMP(vol, 0, 1));
435   if (pavol == s->volume)
436     return;
437   pa_cvolume cvol;
438   pa_cvolume_set(&cvol, s->channels, pavol);
439
440   DBG("## Setting volume of sink %s to %d", s->name, cvol.values[0]);
441   PULSE_ASYNC_RUN(pa_context_set_sink_volume_by_index, pulse_ctx, s->idx, &cvol, pulse_success_cb);
442 }
443
444 struct client_map {
445   int rotary;
446   const char *client;
447   const char *host;
448   double range;
449 };
450
451 static struct client_map client_map[] = {
452   { 4, "Music Player Daemon",   "albireo",      1 },
453   { 5, "MPlayer",               NULL,           1 },
454   { 6, NULL,                    "ogion",        1 },
455   { 7, NULL,                    "ursula",       1 },
456 };
457
458 #define NUM_CLIENTS ARRAY_SIZE(client_map)
459
460 struct client_state {
461   double volume;
462   bool have_muted[2];
463 };
464
465 static struct client_state client_state[NUM_CLIENTS];
466
467 static int find_client_by_rotary(int rotary)
468 {
469   uns i;
470   for (i=0; i < NUM_CLIENTS; i++)
471     if (client_map[i].rotary == rotary)
472       return i;
473   return -1;
474 }
475
476 static void calc_clients(void)
477 {
478   bzero(client_state, sizeof(client_state));
479
480   HASH_FOR_ALL(pulse_sink_input, s)
481     {
482       s->noct_client_idx = -1;
483
484       if (s->client_idx < 0 || s->sink_idx < 0)
485         continue;
486
487       struct pulse_client *c = pulse_client_lookup(s->client_idx);
488       if (!c)
489         continue;
490
491       for (uns i=0; i < NUM_CLIENTS; i++)
492         {
493           struct client_map *cm = &client_map[i];
494           struct client_state *cs = &client_state[i];
495           if ((!cm->client || !strcmp(cm->client, c->name)) &&
496               (!cm->host || !strcmp(cm->host, c->host)))
497             {
498               // DBG("@@ Client #%d, sink input #%d -> rotary %d", s->client_idx, s->idx, cm->rotary);
499               s->noct_client_idx = i;
500               cs->volume = MAX(cs->volume, s->volume);
501               cs->have_muted[!!s->mute] = 1;
502               break;
503             }
504         }
505     }
506   HASH_END_FOR;
507 }
508
509 static void update_clients(void)
510 {
511   calc_clients();
512
513   for (uns i=0; i < NUM_CLIENTS; i++)
514     {
515       struct client_map *cm = &client_map[i];
516       struct client_state *cs = &client_state[i];
517       if (!cs->have_muted[0] && !cs->have_muted[1])
518         {
519           noct_set_ring(cm->rotary, RING_MODE_LEFT, 0);
520           noct_set_button(cm->rotary, 0);
521         }
522       else if (!cs->have_muted[0])
523         {
524           noct_set_ring(cm->rotary, RING_MODE_SINGLE_ON, 0x7f);
525           noct_set_button(cm->rotary, 1);
526         }
527       else
528         {
529           double vol = CLAMP(volume_from_pa(cs->volume), 0, cm->range);
530           int val = 0x7f * vol / cm->range;
531           val = CLAMP(val, 12, 0x7f);
532           noct_set_ring(cm->rotary, RING_MODE_LEFT, val);
533           noct_set_button(cm->rotary, 0);
534         }
535     }
536 }
537
538 static void update_client_from_rotary(int rotary, int delta)
539 {
540   int i = find_client_by_rotary(rotary);
541   if (i < 0)
542     return;
543   struct client_map *cm = &client_map[i];
544   struct client_state *cs = &client_state[i];
545
546   calc_clients();
547   double vol = volume_from_pa(cs->volume) + delta*0.02;
548   pa_volume_t pavol = volume_to_pa(CLAMP(vol, 0, cm->range));
549
550   HASH_FOR_ALL(pulse_sink_input, s)
551     {
552       if (s->noct_client_idx == i && s->volume != pavol)
553         {
554           DBG("@@ Client #%d, sink input #%d: setting volume=%u", s->client_idx, s->idx, pavol);
555           pa_cvolume cvol;
556           pa_cvolume_set(&cvol, s->channels, pavol);
557           PULSE_ASYNC_RUN(pa_context_set_sink_input_volume, pulse_ctx, s->idx, &cvol, pulse_success_cb);
558         }
559     }
560   HASH_END_FOR;
561 }
562
563 static void do_update(struct main_timer *t)
564 {
565   timer_del(t);
566   if (!noct_is_ready())
567     {
568       DBG("## UPDATE: Nocturn is not ready");
569       return;
570     }
571
572   static bool dead;
573   if (pulse_state != PS_ONLINE)
574     {
575       DBG("## UPDATE: Pulse is not online");
576       for (int i=0; i<=8; i++)
577         noct_set_ring(i, RING_MODE_LEFT, 0);
578       for (int i=0; i<8; i++)
579         {
580           noct_set_button(i, 1);
581           noct_set_button(i+8, 0);
582         }
583       dead = 1;
584       return;
585     }
586   if (dead)
587     {
588       DBG("## UPDATE: Waking up from the dead");
589       for (int i=0; i<=8; i++)
590         noct_set_ring(i, RING_MODE_LEFT, 0);
591       for (int i=0; i<16; i++)
592         noct_set_button(i, 0);
593       dead = 0;
594     }
595
596   DBG("## UPDATE");
597   pulse_dump();
598
599   update_ring_from_sink(0, "ursarium");
600   update_ring_from_sink(1, "catarium");
601   update_clients();
602 }
603
604 void schedule_update(void)
605 {
606   timer_add_rel(&update_timer, 10);
607 }
608
609 void notify_rotary(int rotary, int delta)
610 {
611   if (pulse_state != PS_ONLINE)
612     {
613       DBG("## NOTIFY: Pulse is not online");
614       return;
615     }
616
617   switch (rotary)
618     {
619     case 0:
620       update_sink_from_rotary(delta, "ursarium");
621       break;
622     case 1:
623       update_sink_from_rotary(delta, "catarium");
624       break;
625     case 8:
626       update_sink_from_rotary(delta, "ursarium");
627       update_sink_from_rotary(delta, "catarium");
628       break;
629     default:
630       update_client_from_rotary(rotary, delta);
631     }
632 }
633
634 static void update_sink_mute_from_button(int on, const char *sink_name)
635 {
636   if (!on)
637     return;
638
639   struct pulse_sink *s = pulse_sink_by_name(sink_name);
640   if (!s)
641     return;
642
643   DBG("## Setting mute of sink %s to %d", s->name, !s->mute);
644   PULSE_ASYNC_RUN(pa_context_set_sink_mute_by_index, pulse_ctx, s->idx, !s->mute, pulse_success_cb);
645 }
646
647 static void update_client_from_button(int button, int on)
648 {
649   if (button >= 8 || !on)
650     return;
651
652   int i = find_client_by_rotary(button);
653   if (i < 0)
654     return;
655   struct client_state *cs = &client_state[i];
656
657   calc_clients();
658   if (!cs->have_muted[0] && !cs->have_muted[1])
659     return;
660   uns mute = !cs->have_muted[1];
661
662   HASH_FOR_ALL(pulse_sink_input, s)
663     {
664       if (s->noct_client_idx == i)
665         {
666           DBG("@@ Client #%d, sink input #%d: setting mute=%u", s->client_idx, s->idx, mute);
667           PULSE_ASYNC_RUN(pa_context_set_sink_input_mute, pulse_ctx, s->idx, mute, pulse_success_cb);
668         }
669     }
670   HASH_END_FOR;
671 }
672
673 void notify_button(int button, int on)
674 {
675   if (pulse_state != PS_ONLINE)
676     {
677       DBG("## NOTIFY: Pulse is not online");
678       return;
679     }
680
681   switch (button)
682     {
683     case 0:
684       update_sink_mute_from_button(on, "ursarium");
685       break;
686     case 1:
687       update_sink_mute_from_button(on, "catarium");
688       break;
689     default:
690       update_client_from_button(button, on);
691     }
692 }
693
694 int main(int argc UNUSED, char **argv)
695 {
696   log_init(argv[0]);
697   main_init();
698   update_timer.handler = do_update;
699
700   noct_init();
701
702   msg(L_INFO, "Initializing PulseAudio");
703   pulse_init();
704
705   msg(L_INFO, "Entering main loop");
706   main_loop();
707
708   return 0;
709 }