]> mj.ucw.cz Git - ursary.git/blob - ursaryd.c
Muting of sources
[ursary.git] / ursaryd.c
1 /*
2  *      The Ursary Audio Controls
3  *
4  *      (c) 2014--2020 Martin Mares <mj@ucw.cz>
5  */
6
7 #undef LOCAL_DEBUG
8
9 #include <ucw/lib.h>
10 #include <ucw/clists.h>
11 #include <ucw/daemon.h>
12 #include <ucw/log.h>
13 #include <ucw/mainloop.h>
14 #include <ucw/opt.h>
15 #include <ucw/stkstring.h>
16
17 #include <math.h>
18 #include <signal.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <syslog.h>
23
24 #include "ursaryd.h"
25 #include "usb.h"
26
27 /*
28  *      Map of all controls
29  *
30  *              rotary          red button      green button
31  *              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
32  *      0       sink PCH        mute            switch to PCH
33  *      1       sink BT         mute            switch to BT
34  *      2       -               mic non-mute    -
35  *      3       desk brightness -               desk lights on
36  *      4       MPD             mute            MPD play/pause
37  *      5       Albireo MPV     mute            MPD stop
38  *      6       Albireo other   mute            MPD prev
39  *      7       other machines  mute            MPD next
40  *
41  *      center  -
42  *      slider  light color temperature
43  */
44
45 #define PCH_SINK "alsa_output.pci-0000_00_1f.3.analog-stereo"
46 #define BT_SINK "bluez_sink.CC_98_8B_D0_8C_06.a2dp_sink"
47 #define LOGI_SOURCE "alsa_input.usb-046d_Logitech_Webcam_C925e_EF163C5F-02.analog-stereo"
48
49 /*** Sink controls ***/
50
51 static double volume_from_pa(pa_volume_t vol)
52 {
53   return (double) vol / PA_VOLUME_NORM;
54 }
55
56 static pa_volume_t volume_to_pa(double vol)
57 {
58   return vol * PA_VOLUME_NORM + 0.0001;
59 }
60
61 static void update_ring_from_sink(int ring, const char *sink_name)
62 {
63   struct pulse_sink *s = pulse_sink_by_name(sink_name);
64   if (!s)
65     {
66       noct_set_ring(ring, RING_MODE_SINGLE_ON, 0x7f);
67       noct_set_button(ring, 0);
68       return;
69     }
70
71   if (s->mute)
72     {
73       noct_set_ring(ring, RING_MODE_SINGLE_ON, 0x7f);
74       noct_set_button(ring, 1);
75       return;
76     }
77
78   double vol = CLAMP(volume_from_pa(s->volume), 0, 1);
79   noct_set_ring(ring, RING_MODE_LEFT, CLAMP((int)(0x7f * vol), 12, 0x7f));
80   noct_set_button(ring, 0);
81 }
82
83 static void update_sink_from_rotary(int delta, const char *sink_name)
84 {
85   struct pulse_sink *s = pulse_sink_by_name(sink_name);
86   if (!s)
87     return;
88
89   double vol = volume_from_pa(s->volume) + delta * 0.02;
90   pa_volume_t pavol = volume_to_pa(CLAMP(vol, 0, 1));
91   if (pavol == s->volume)
92     return;
93   pa_cvolume cvol;
94   pa_cvolume_set(&cvol, s->channels, pavol);
95
96   DBG("## Setting volume of sink %s to %d", s->name, cvol.values[0]);
97   pulse_sink_set_volume(s->idx, &cvol);
98 }
99
100 static void update_sink_mute_from_button(int on, const char *sink_name)
101 {
102   if (!on)
103     return;
104
105   struct pulse_sink *s = pulse_sink_by_name(sink_name);
106   if (!s)
107     return;
108
109   DBG("## Setting mute of sink %s to %d", s->name, !s->mute);
110   pulse_sink_set_mute(s->idx, !s->mute);
111 }
112
113 /*** Client controls ***/
114
115 struct client_map {
116   int group;
117   const char *client;
118   const char *host;
119 };
120
121 static struct client_map client_map[] = {
122   { 4, "Music Player Daemon",   "albireo",      },
123   { 5, "mpv",                   "albireo",      },
124   { 6, NULL,                    "albireo",      },
125   { 7, NULL,                    NULL,           },
126 };
127
128 #define CLIENT_MAP_SIZE ARRAY_SIZE(client_map)
129
130 struct group_config {
131   bool enabled;
132   double range;
133 };
134
135 struct group_state {
136   double volume;
137   bool have_muted[2];
138 };
139
140 #define NUM_GROUPS 9
141
142 static struct group_config group_config[NUM_GROUPS] = {
143   [4] = { .enabled = 1, .range = 1.5 },
144   [5] = { .enabled = 1, .range = 1.5 },
145   [6] = { .enabled = 1, .range = 1.5 },
146   [7] = { .enabled = 1, .range = 1.5 },
147 };
148
149 static struct group_state group_state[NUM_GROUPS];
150
151 static void calc_groups(void)
152 {
153   bzero(group_state, sizeof(group_state));
154
155   CLIST_FOR_EACH(struct pulse_sink_input *, s, pulse_sink_input_list)
156     {
157       s->noct_group_idx = -1;
158
159       if (s->client_idx < 0 || s->sink_idx < 0)
160         continue;
161
162       struct pulse_client *c = pulse_client_by_idx(s->client_idx);
163       if (!c)
164         continue;
165
166       for (uns i=0; i < CLIENT_MAP_SIZE; i++)
167         {
168           struct client_map *cm = &client_map[i];
169           if ((!cm->client || !strcmp(cm->client, c->name)) &&
170               (!cm->host || !strcmp(cm->host, c->host)))
171             {
172               int g = cm->group;
173               struct group_state *gs = &group_state[g];
174               DBG("@@ Client #%d, sink input #%d -> group %d", s->client_idx, s->idx, g);
175               s->noct_group_idx = g;
176               gs->volume = MAX(gs->volume, s->volume);
177               gs->have_muted[!!s->mute] = 1;
178               break;
179             }
180         }
181     }
182 }
183
184 static void update_groups(void)
185 {
186   calc_groups();
187
188   for (uns i=0; i < NUM_GROUPS; i++)
189     {
190       struct group_config *gc = &group_config[i];
191       struct group_state *gs = &group_state[i];
192       if (!gc->enabled)
193         continue;
194
195       DBG("@@ Group #%d: mute=%d/%d volume=%.3f/%.3f", i, gs->have_muted[0], gs->have_muted[1], volume_from_pa(gs->volume), gc->range);
196
197       if (!gs->have_muted[0] && !gs->have_muted[1])
198         {
199           noct_set_ring(i, RING_MODE_LEFT, 0);
200           noct_set_button(i, 0);
201         }
202       else if (!gs->have_muted[0])
203         {
204           noct_set_ring(i, RING_MODE_SINGLE_ON, 0x7f);
205           noct_set_button(i, 1);
206         }
207       else
208         {
209           double vol = CLAMP(volume_from_pa(gs->volume), 0, gc->range);
210           int val = 0x7f * vol / gc->range;
211           val = CLAMP(val, 12, 0x7f);
212           noct_set_ring(i, RING_MODE_LEFT, val);
213           noct_set_button(i, 0);
214         }
215     }
216 }
217
218 static void update_group_from_rotary(int i, int delta)
219 {
220   if (i >= NUM_GROUPS)
221     return;
222   struct group_config *gc = &group_config[i];
223   struct group_state *gs = &group_state[i];
224   if (!gc->enabled)
225     return;
226
227   calc_groups();
228   double vol = volume_from_pa(gs->volume) + delta*0.02;
229   pa_volume_t pavol = volume_to_pa(CLAMP(vol, 0, gc->range));
230
231   CLIST_FOR_EACH(struct pulse_sink_input *, s, pulse_sink_input_list)
232     {
233       if (s->noct_group_idx == i && s->volume != pavol)
234         {
235           DBG("@@ Client #%d, sink input #%d: setting volume=%u", s->client_idx, s->idx, pavol);
236           pa_cvolume cvol;
237           pa_cvolume_set(&cvol, s->channels, pavol);
238           pulse_sink_input_set_volume(s->idx, &cvol);
239         }
240     }
241 }
242
243 static void update_group_from_button(int i, int on)
244 {
245   if (!on)
246     return;
247   if (i >= NUM_GROUPS)
248     return;
249   struct group_config *gc = &group_config[i];
250   struct group_state *gs = &group_state[i];
251   if (!gc->enabled)
252     return;
253
254   calc_groups();
255   if (!gs->have_muted[0] && !gs->have_muted[1])
256     return;
257   uns mute = !gs->have_muted[1];
258
259   CLIST_FOR_EACH(struct pulse_sink_input *, s, pulse_sink_input_list)
260     {
261       if (s->noct_group_idx == i)
262         {
263           DBG("@@ Client #%d, sink input #%d: setting mute=%u", s->client_idx, s->idx, mute);
264           pulse_sink_input_set_mute(s->idx, mute);
265         }
266     }
267 }
268
269 static int find_touched_client(void)
270 {
271   int touched = -1;
272
273   for (uns i=0; i < NUM_GROUPS; i++)
274     if (group_config[i].enabled && noct_rotary_touched[i])
275       {
276         if (touched >= 0)
277           return -1;
278         touched = i;
279       }
280   return touched;
281 }
282
283 /*** Default sink controls ***/
284
285 static const char *get_client_sink(int i)
286 {
287   const char *sink = NULL;
288
289   CLIST_FOR_EACH(struct pulse_sink_input *, s, pulse_sink_input_list)
290     if (s->noct_group_idx == i)
291       {
292         struct pulse_sink *sk = (s->sink_idx >= 0) ? pulse_sink_by_idx(s->sink_idx) : NULL;
293         const char *ss = sk ? sk->name : NULL;
294         if (!sink)
295           sink = ss;
296         else if (strcmp(sink, ss))
297           sink = "?";
298       }
299   return sink ? : "?";
300 }
301
302 static void update_default_sink(void)
303 {
304   int i = find_touched_client();
305   const char *sink;
306   if (i >= 0)
307     sink = get_client_sink(i);
308   else
309     sink = pulse_default_sink_name ? : "?";
310
311   if (!strcmp(sink, PCH_SINK))
312     {
313       noct_set_button(8, 1);
314       noct_set_button(9, 0);
315     }
316   else if (!strcmp(sink, BT_SINK))
317     {
318       noct_set_button(8, 0);
319       noct_set_button(9, 1);
320     }
321   else
322     {
323       noct_set_button(8, 0);
324       noct_set_button(9, 0);
325     }
326 }
327
328 static void update_default_sink_from_button(int button, int on)
329 {
330   if (!on)
331     return;
332
333   int i = find_touched_client();
334 #if 0
335   const char *sink;
336   if (i >= 0)
337     sink = get_client_sink(i);
338   else
339     sink = pulse_default_sink_name ? : "?";
340 #endif
341
342   const char *switch_to = NULL;
343   if (button == 8)
344     switch_to = PCH_SINK;
345   else if (button == 9)
346     switch_to = BT_SINK;
347
348   if (!switch_to)
349     return;
350
351   if (i >= 0)
352     {
353       struct pulse_sink *sk = pulse_sink_by_name(switch_to);
354       if (!sk)
355         return;
356
357       CLIST_FOR_EACH(struct pulse_sink_input *, s, pulse_sink_input_list)
358         if (s->noct_group_idx == i)
359           {
360             DBG("Moving input #%d to sink #%d", s->idx, sk->idx);
361             pulse_sink_input_move(s->idx, sk->idx);
362           }
363     }
364   else
365     {
366       DBG("Switching default sink to %s", switch_to);
367       pulse_server_set_default_sink(switch_to);
368     }
369 }
370
371 /*** Source mute controls ***/
372
373 static void update_source_buttons(void)
374 {
375   struct pulse_source *source = pulse_source_by_name(LOGI_SOURCE);
376   if (!source)
377     return;
378
379   // if (source->suspended || source->mute)
380   if (source->mute)
381     noct_set_button(2, 0);
382   else
383     noct_set_button(2, 1);
384 }
385
386 static void update_source_mute_from_button(int on, const char *source_name)
387 {
388   if (!on)
389     return;
390
391   struct pulse_source *s = pulse_source_by_name(source_name);
392   if (!s)
393     return;
394
395   DBG("## Setting mute of source %s to %d", s->name, !s->mute);
396   pulse_source_set_mute(s->idx, !s->mute);
397 }
398
399 /*** MPD controls ***/
400
401 static bool mpd_flash_state;
402
403 static void mpd_flash_timeout(struct main_timer *t)
404 {
405   mpd_flash_state ^= 1;
406   noct_set_button(12, mpd_flash_state);
407   timer_add_rel(t, 500);
408 }
409
410 static struct main_timer mpd_flash_timer = {
411   .handler = mpd_flash_timeout,
412 };
413
414 static void update_mpd(void)
415 {
416   const char *state = mpd_get_player_state();
417   if (!strcmp(state, "play"))
418     {
419       noct_set_button(12, 1);
420       timer_del(&mpd_flash_timer);
421     }
422   else if (!strcmp(state, "pause"))
423     {
424       if (!timer_is_active(&mpd_flash_timer))
425         {
426           mpd_flash_state = 1;
427           mpd_flash_timeout(&mpd_flash_timer);
428         }
429     }
430   else
431     {
432       noct_set_button(12, 0);
433       timer_del(&mpd_flash_timer);
434     }
435 }
436
437 static void mpd_button_timeout(struct main_timer *t)
438 {
439   DBG("MPD stop");
440   timer_del(t);
441   mpd_stop();
442 }
443
444 static void update_mpd_from_button(int button UNUSED, int on)
445 {
446   static struct main_timer mpd_button_timer = {
447     .handler = mpd_button_timeout,
448   };
449
450   const char *state = mpd_get_player_state();
451
452   if (!on)
453     {
454       if (timer_is_active(&mpd_button_timer))
455         {
456           timer_del(&mpd_button_timer);
457           if (!strcmp(state, "play"))
458             {
459               DBG("MPD pause");
460               mpd_pause(1);
461             }
462           else if (!strcmp(state, "pause"))
463             {
464               DBG("MPD resume");
465               mpd_pause(0);
466             }
467         }
468       return;
469     }
470
471   if (!strcmp(state, "stop"))
472     {
473       DBG("MPD play");
474       mpd_play();
475     }
476   else
477     {
478       DBG("MPD starting button timer");
479       timer_add_rel(&mpd_button_timer, 1000);
480     }
481 }
482
483 /*** Lights ***/
484
485 static bool lights_on[2];
486 static double lights_brightness[2];
487 static double lights_temperature[2];
488
489 static void update_lights(void)
490 {
491   if (!dmx_is_ready())
492     {
493       noct_set_ring(3, RING_MODE_SINGLE_ON, 0x7f);
494       noct_set_button(11, 0);
495       return;
496     }
497
498   for (uint i=0; i<1; i++)
499     {
500       uint warm, cold;
501       if (lights_on[i])
502         {
503           noct_set_ring(3, RING_MODE_LEFT, lights_brightness[i] * 127);
504           noct_set_button(11, 1);
505           double r = 2;
506           double x = (exp(r*lights_brightness[i]) - 1) / (exp(r) - 1);
507           double t = lights_temperature[i];
508           double w = 2*x*(1-t);
509           double c = 2*x*t;
510           warm = CLAMP((int)(255*w), 0, 255);
511           cold = CLAMP((int)(255*c), 0, 255);
512         }
513       else
514         {
515           noct_set_ring(3, RING_MODE_LEFT, 0);
516           noct_set_button(11, 0);
517           warm = cold = 0;
518         }
519       DBG("Lights[%d]: on=%d bri=%.3f temp=%.3f -> warm=%d cold=%d", i, lights_on[i], lights_brightness[i], lights_temperature[i], warm, cold);
520       dmx_set_pwm(2*i, warm);
521       dmx_set_pwm(2*i+1, cold);
522     }
523 }
524
525 static void update_lights_from_rotary(int ch, int delta)
526 {
527   if (lights_on[ch])
528     lights_brightness[ch] = CLAMP(lights_brightness[ch] + 0.015*delta*abs(delta), 0., 1.);
529   update_lights();
530 }
531
532 static void update_lights_from_slider(int value)
533 {
534   lights_temperature[0] = value / 127.;
535   update_lights();
536 }
537
538 static void lights_button_timeout(struct main_timer *t)
539 {
540   int ch = (uintptr_t) t->data;
541   DBG("Lights[%d]: Full throttle!", ch);
542   timer_del(t);
543   lights_on[ch] = 1;
544   lights_brightness[ch] = 1;
545   update_lights();
546 }
547
548 static void update_lights_from_button(int ch, int on)
549 {
550   static struct main_timer lights_button_timer[2] = {{
551     .handler = lights_button_timeout,
552     .data = (void *)(uintptr_t) 0,
553   },{
554     .handler = lights_button_timeout,
555     .data = (void *)(uintptr_t) 1,
556   }};
557
558   if (on)
559     {
560       lights_on[ch] = !lights_on[ch];
561       update_lights();
562       timer_add_rel(&lights_button_timer[ch], 1000);
563     }
564   else
565     timer_del(&lights_button_timer[ch]);
566 }
567
568 /*** Main update routines ***/
569
570 static struct main_timer update_timer;
571 static timestamp_t last_touch_time;
572
573 enum update_state {
574   US_OFFLINE,
575   US_ONLINE,
576   US_SLEEPING,
577   US_PULSE_DEAD,
578 };
579
580 static enum update_state update_state;
581
582 static bool want_sleep_p(void)
583 {
584   CLIST_FOR_EACH(struct pulse_sink *, s, pulse_sink_list)
585     if (!s->suspended)
586       return 0;
587   return 1;
588 }
589
590 static void do_update(struct main_timer *t)
591 {
592   DBG("## UPDATE in state %u", update_state);
593   timer_del(t);
594
595   // Nocturn dead?
596   if (!noct_is_ready())
597     {
598       DBG("## UPDATE: Nocturn is not ready");
599       update_state = US_OFFLINE;
600       return;
601     }
602   else if (update_state == US_OFFLINE)
603     {
604       DBG("## UPDATE: Going online");
605       update_state = US_ONLINE;
606     }
607
608   // Pulse dead?
609   if (!pulse_is_ready())
610     {
611       DBG("## UPDATE: Pulse is not online");
612       if (update_state != US_PULSE_DEAD)
613         {
614           update_state = US_PULSE_DEAD;
615           noct_clear();
616           for (int i=0; i<8; i++)
617             noct_set_button(i, 1);
618         }
619       return;
620     }
621   else if (update_state == US_PULSE_DEAD)
622     {
623       DBG("## UPDATE: Waking up from the dead");
624       update_state = US_ONLINE;
625       noct_clear();
626     }
627
628 #ifdef LOCAL_DEBUG
629   pulse_dump();
630 #endif
631
632   // Sleeping?
633   bool want_sleep = want_sleep_p();
634   if (!want_sleep)
635     last_touch_time = main_get_now();
636   timestamp_t since_touch = last_touch_time ? main_get_now() - last_touch_time : 0;
637   timestamp_t sleep_in = 30000;
638   if (since_touch >= sleep_in)
639     {
640       DBG("UPDATE: Sleeping");
641       if (update_state == US_ONLINE)
642         {
643           update_state = US_SLEEPING;
644           noct_clear();
645           noct_set_ring(8, RING_MODE_LEFT, 127);
646         }
647       return;
648     }
649   else
650     {
651       if (update_state == US_SLEEPING)
652         {
653           DBG("UPDATE: Waking up");
654           update_state = US_ONLINE;
655           noct_clear();
656         }
657       if (want_sleep)
658         {
659           timestamp_t t = sleep_in - since_touch + 10;
660           DBG("UPDATE: Scheduling sleep in %d ms", (int) t);
661           timer_add_rel(&update_timer, t);
662         }
663     }
664
665   // Everything normal
666   update_ring_from_sink(0, PCH_SINK);
667   update_ring_from_sink(1, BT_SINK);
668   update_groups();
669   update_default_sink();
670   update_source_buttons();
671   update_mpd();
672   update_lights();
673 }
674
675 void schedule_update(void)
676 {
677   timer_add_rel(&update_timer, 10);
678 }
679
680 static bool prepare_notify(void)
681 {
682   if (!pulse_is_ready())
683     {
684       DBG("## NOTIFY: Pulse is not online");
685       return 0;
686     }
687
688   last_touch_time = main_get_now();
689   if (update_state == US_SLEEPING)
690     {
691       DBG("## NOTIFY: Scheduling wakeup");
692       schedule_update();
693     }
694
695   return 1;
696 }
697
698 void notify_rotary(int rotary, int delta)
699 {
700   if (!prepare_notify())
701     return;
702
703   switch (rotary)
704     {
705     case 0:
706       update_sink_from_rotary(delta, PCH_SINK);
707       break;
708     case 1:
709       update_sink_from_rotary(delta, BT_SINK);
710       break;
711     case 3:
712       update_lights_from_rotary(0, delta);
713       break;
714     case 9:
715       update_lights_from_slider(delta);
716       break;
717     default:
718       update_group_from_rotary(rotary, delta);
719     }
720 }
721
722 void notify_button(int button, int on)
723 {
724   if (!prepare_notify())
725     return;
726
727   switch (button)
728     {
729     case 0:
730       update_sink_mute_from_button(on, PCH_SINK);
731       break;
732     case 1:
733       update_sink_mute_from_button(on, BT_SINK);
734       break;
735     case 2:
736       update_source_mute_from_button(on, LOGI_SOURCE);
737       break;
738     case 8:
739     case 9:
740       update_default_sink_from_button(button, on);
741       break;
742     case 11:
743       update_lights_from_button(0, on);
744       break;
745     case 12:
746       update_mpd_from_button(button, on);
747       break;
748     case 13:
749       if (on)
750         mpd_stop();
751       break;
752     case 14:
753       if (on)
754         mpd_prev();
755       break;
756     case 15:
757       if (on)
758         mpd_next();
759       break;
760     default:
761       update_group_from_button(button, on);
762     }
763 }
764
765 void notify_touch(int rotary UNUSED, int on UNUSED)
766 {
767   if (!prepare_notify())
768     return;
769
770   // Rotary touches switch meaning of LEDs, this is handled inside display updates
771   if (rotary >= 4 && rotary < 8)
772     schedule_update();
773 }
774
775 /*** Main entry point ***/
776
777 static int debug;
778 static int no_fork;
779
780 static struct opt_section options = {
781   OPT_ITEMS {
782     OPT_HELP("Control console for the Ursary"),
783     OPT_HELP(""),
784     OPT_HELP("Options:"),
785     OPT_HELP_OPTION,
786     OPT_BOOL('d', "debug", debug, 0, "\tEnable debugging mode (no fork etc.)"),
787     OPT_BOOL(0, "no-fork", no_fork, 0, "\tDo not fork\n"),
788     OPT_END
789   }
790 };
791
792 static void sigterm_handler(struct main_signal *ms UNUSED)
793 {
794   main_shut_down();
795 }
796
797 static void daemon_body(struct daemon_params *dp)
798 {
799   main_init();
800   update_timer.handler = do_update;
801
802   usb_init();
803   noct_init();
804   dmx_init();
805   pulse_init();
806   mpd_init();
807
808   static struct main_signal term_sig = {
809     .signum = SIGTERM,
810     .handler = sigterm_handler,
811   };
812   signal_add(&term_sig);
813
814   msg(L_INFO, "Ursary daemon starting");
815   main_loop();
816   msg(L_INFO, "Ursary daemon shut down");
817   daemon_exit(dp);
818 }
819
820 int main(int argc UNUSED, char **argv)
821 {
822   opt_parse(&options, argv+1);
823   unsetenv("DISPLAY");
824   unsetenv("HOME");
825
826   struct daemon_params dp = {
827     .flags = ((debug || no_fork) ? DAEMON_FLAG_SIMULATE : 0),
828     .pid_file = "/run/ursaryd.pid",
829     .run_as_user = "ursary",
830   };
831   daemon_init(&dp);
832
833   log_init(argv[0]);
834   if (!debug)
835     {
836       struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
837       ls->levels = ~(1U << L_DEBUG);
838       log_set_default_stream(ls);
839     }
840
841   daemon_run(&dp, daemon_body);
842   return 0;
843 }