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