forked from TheOnlyJoey/MixiD
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
2663 lines (2562 loc) · 105 KB
/
Copy pathmain.cpp
File metadata and controls
2663 lines (2562 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Dear ImGui: standalone example application for GLFW + OpenGL 3, using programmable pipeline
// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui-custom.h"
#include "imgui-knobs.h"
//#include "imgui.h"
#include "backends/imgui_impl_glfw.h"
#include "backends/imgui_impl_opengl3.h"
#include <stdio.h>
#define GL_SILENCE_DEPRECATION
#if defined(IMGUI_IMPL_OPENGL_ES2)
#include <GLES2/gl2.h>
#endif
#include <GLFW/glfw3.h> // Will drag system OpenGL headers
#include <vector>
#include <string>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <csignal>
#include <cmath>
#include <algorithm>
#include <sys/stat.h>
#include <unistd.h>
#include <climits>
#include <dirent.h>
#include <cctype>
#include <thread>
#include <atomic>
#include <ctime>
#include "driver.h"
#include "tray.h"
#include "Raw_Assets.h"
// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details.
#ifdef __EMSCRIPTEN__
#include "../libs/emscripten/emscripten_mainloop_stub.h"
#endif
static int driver_indicator = 0;
static bool connected = false;
static bool tray_active = false;
static bool force_quit = false;
// [0] monitor, [1] headphones. The monitor starts down and is either read
// from the hardware or raised by hand; the headphones start wide open,
// because this scale is dB and half of it is -64 - near enough to silence
// to leave someone deaf in their own headphones wondering what broke.
std::vector<float> levels = {0.0f,1.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f};
// Which output the one big knob is moving: 0 the monitors, 1 the phones.
// Only boxes that share an encoder between the two are given the choice.
static int knob_target = 0;
static std::vector<bool> knob_focus = {true, false};
// One set of faders serves all three matrix buses; the tabs above the strips
// pick which mix is being edited, and every mix keeps its own levels and pans.
static std::vector <float> bar_value[MIXER_BUSES];
static std::vector <float> pan_value[MIXER_BUSES];
static int current_mix = 0;
// The pinned output pair moves as one while Link is lit. A vector only
// because toggleButton takes a vector<bool> reference.
static std::vector<bool> out_link = {true};
// The input strips link in twos as well - MIC 1+2, and the digital inputs
// pair by pair - keyed by the pair's left channel. They start unlinked:
// two mics are usually two sources, not one stereo one.
static std::vector<bool> chan_link;
// And any pair - inputs or the pinned outputs - can be summed to mono:
// while lit, both sides hear both channels. Keyed like chan_link.
static std::vector<bool> chan_mono;
// A channel can be named for what it carries; empty keeps the stock
// label. rename_idx is the strip being edited right now, if any.
static std::vector<std::string> chan_name;
static int rename_idx = -1;
static char rename_buf[24];
static bool rename_focus = false;
// One-shot: the mix tab the state file wants selected on the first frame.
static int want_mix_tab = -1;
// Per mix: a master trim over everything it sends, and mute/solo per
// channel. None of this exists in hardware - it is baked into the levels
// that reach the matrix. Solo mutes everyone who is not soloed.
static float mix_master[MIXER_BUSES] = {1.0f, 1.0f, 1.0f};
static std::vector<bool> mute_value[MIXER_BUSES];
static std::vector<bool> solo_value[MIXER_BUSES];
static std::vector <bool> phase_value;
static std::vector <bool> master_bools = {false,false,false,false,false,false};
static void glfw_error_callback(int error, const char* description)
{
fprintf(stderr, "GLFW Error %d: %s\n", error, description);
}
static GLFWwindow* window = nullptr;
static const char* glsl_version = nullptr;
static float main_scale = 1.0f;
static bool want_hide = false;
static double last_poll = 0.0;
static void window_close_callback(GLFWwindow* win)
{
// only flag it here, the window is torn down from the main loop:
// destroying a window inside its own callback is not safe
if (tray_active && !force_quit) {
glfwSetWindowShouldClose(win, GLFW_FALSE);
want_hide = true;
}
}
// Hiding is a full window teardown rather than glfwHideWindow(): on Wayland a
// re-shown window does not reliably get a configured surface back, and the
// first buffer swap then blocks forever waiting for a frame callback.
static void window_open()
{
if (window)
return;
#ifdef GLFW_WAYLAND_APP_ID
glfwWindowHintString(GLFW_WAYLAND_APP_ID, "bid");
#endif
#ifdef GLFW_X11_CLASS_NAME
glfwWindowHintString(GLFW_X11_CLASS_NAME, "bid");
glfwWindowHintString(GLFW_X11_INSTANCE_NAME, "bid");
#endif
window = glfwCreateWindow((int)(1280 * main_scale), (int)(800 * main_scale), "BiD - Open Source Audient mixer for Linux", nullptr, nullptr);
if (!window)
return;
glfwMakeContextCurrent(window);
glfwSwapInterval(1); // Enable vsync
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
glfwSetWindowCloseCallback(window, window_close_callback);
}
static void window_close()
{
if (!window)
return;
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
glfwDestroyWindow(window);
window = nullptr;
}
// A fader position as the number an engineer thinks in. The hardware takes
// an int16 of 1/256 dB with 0x8000 meaning silence, and BiD's 0..1 maps
// straight onto that - so the top of the travel is unity and the bottom is
// nothing, exactly as the official app's scale reads.
static void db_label(char *out, size_t n, float v)
{
if (v <= 0.0005f) {
snprintf(out, n, "-inf");
return;
}
float db = (-32768.0f + 32767.0f * v) / 256.0f;
if (db <= -100.0f)
snprintf(out, n, "%.0f", db);
else if (db <= -10.0f)
snprintf(out, n, "%.1f", db);
else
snprintf(out, n, "%+.1f", db);
}
// A delayed tooltip on whatever was drawn last: for buttons whose label
// is an abbreviation rather than a name.
static void hover_tip(const char* text)
{
if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal))
ImGui::SetTooltip("%s", text);
}
void TextCentered(const char* text) {
float avail = ImGui::GetContentRegionAvail().x;
float width = ImGui::CalcTextSize(text).x;
if (width < avail)
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (avail - width) * 0.5f);
ImGui::TextUnformatted(text);
}
// What each output pair listens to, in route_source order: outputs 1+2,
// outputs 3+4, phones. The hardware keeps its routing across power cycles
// and never answers reads, so whatever was last written anywhere stays in
// force until connect pushes this. The first pair carries the main mix, the
// second the alternate speakers, and the phones cue A: the main feed is the
// monitor section's, so dim and cut would land in the headphones too, while
// on a cue the phones answer only to their own dial.
// The fourth entry is the loopback pair: not a jack, but routing outputs
// 10 and 11, whose signal the hardware hands back to the computer as
// capture channels 11+12 (decoded by Monix from the official app). Its
// default is DAW Thru: silent unless something plays into 11+12, and
// never coupled to the monitor knob by surprise.
static const int route_default[4] = { ROUTE_MAIN, ROUTE_ALT, ROUTE_CUE_A, ROUTE_DAW };
static int route_state[4] = { ROUTE_MAIN, ROUTE_ALT, ROUTE_CUE_A, ROUTE_DAW };
// the alternate speakers' level offset, in dB; lives with the desk state
// and rides the volume while ALT is engaged - see alt_shifted below
static int alt_trim_db = -6;
// How many fader pages this model has: the main mix plus its cues, within
// what the state file can hold.
static int active_buses()
{
return ImClamp(1 + devices[driver_indicator].cue_mixes, 1, MIXER_BUSES);
}
// Teach the driver this model's matrix spacing before anything is written.
static void apply_device_profile()
{
mixer_stride = devices[driver_indicator].mixer_stride;
routing_outputs = devices[driver_indicator].routing_outputs;
route_scheme = devices[driver_indicator].route_scheme;
if (current_mix >= active_buses())
current_mix = 0;
}
// A model without alternate speakers has no Alt column, so Alt must never
// come up as a value there - not from the defaults, not from a state file
// written before the column was hidden. The main pair falls back to Main,
// anything else to DAW Thru, both always on offer.
static int sane_route(int p, int s)
{
if (s == ROUTE_ALT && !devices[driver_indicator].has_alt)
return p == 0 ? ROUTE_MAIN : ROUTE_DAW;
return s;
}
static void reset_routing()
{
for (int p = 0; p < 4; p++)
route_state[p] = sane_route(p, route_default[p]);
}
static void reset_mixes()
{
for (int m = 0; m < MIXER_BUSES; m++) {
bar_value[m].clear();
pan_value[m].clear();
mute_value[m].clear();
solo_value[m].clear();
mix_master[m] = 1.0f;
}
chan_link.clear();
chan_mono.clear();
chan_name.clear();
}
// Which pair does a channel belong to? Returns the pair's left channel,
// or -1 for a channel with no partner. The digital inputs pair on even
// boundaries, the same way the strips are drawn; the monitor pair is a
// pair like any other.
static int pair_left_of(int idx)
{
const device_properties &dev = devices[driver_indicator];
if (idx < dev.mic_inputs)
return ((idx & ~1) + 1 < dev.mic_inputs) ? (idx & ~1) : -1;
int d = idx - dev.mic_inputs;
int base = d & ~1;
if (base + 1 >= dev.digital_inputs)
return -1;
return dev.mic_inputs + base;
}
// What actually reaches the matrix: the fader times the mix master, and
// nothing at all when the channel is muted or someone else is soloed.
static void send_channel(int idx, int m)
{
bool any_solo = false;
for (size_t i = 0; i < solo_value[m].size(); i++)
if (solo_value[m][i]) { any_solo = true; break; }
float v = bar_value[m][idx] * mix_master[m];
if (idx < (int)mute_value[m].size()
&& (mute_value[m][idx] || (any_solo && !solo_value[m][idx])))
v = 0.0f;
float p = pan_value[m][idx];
int pl = pair_left_of(idx);
if (pl >= 0 && pl < (int)chan_mono.size() && chan_mono[pl])
p = 0.5f; // mono pair: centre both, so both sides hear both
set_channel_send(idx, m, v, p);
}
static void send_mix(int m)
{
for (size_t i = 0; i < bar_value[m].size(); i++)
send_channel(i, m);
}
// A restart should come back with the mixes, routing and levels it left
// with. Nothing of that can be read out of the hardware, so a plain text
// file per device, keyed by USB id, is the only memory there is. It lives
// in $XDG_CONFIG_HOME/bid, or ~/.config/bid.
static std::string config_base()
{
const char *xdg = getenv("XDG_CONFIG_HOME");
if (xdg && *xdg)
return xdg;
const char *home = getenv("HOME");
if (!home || !*home)
return "";
return std::string(home) + "/.config";
}
static std::string state_path()
{
std::string base = config_base();
if (devices.empty() || base.empty())
return "";
char name[40];
snprintf(name, sizeof(name), "/bid/state-%04x.conf", devices[driver_indicator].usb_id);
return base + name;
}
static void save_state_to(const std::string& path)
{
if (path.empty() || bar_value[0].empty())
return;
std::string dir = path.substr(0, path.rfind('/'));
mkdir(dir.substr(0, dir.rfind('/')).c_str(), 0755);
mkdir(dir.c_str(), 0755);
std::string tmp = path + ".tmp";
FILE *f = fopen(tmp.c_str(), "w");
if (!f)
return;
size_t n = bar_value[0].size();
fprintf(f, "bid-state 1\nchannels %zu\n", n);
for (int m = 0; m < MIXER_BUSES; m++) {
fprintf(f, "levels %d", m);
for (size_t i = 0; i < n; i++)
fprintf(f, " %.6f", bar_value[m][i]);
fprintf(f, "\npans %d", m);
for (size_t i = 0; i < n; i++)
fprintf(f, " %.6f", pan_value[m][i]);
fprintf(f, "\n");
}
fprintf(f, "phase");
for (size_t i = 0; i < n && i < phase_value.size(); i++)
fprintf(f, " %d", phase_value[i] ? 1 : 0);
fprintf(f, "\nroute %d %d %d\n", route_state[0], route_state[1], route_state[2]);
fprintf(f, "link %d\n", out_link[0] ? 1 : 0);
fprintf(f, "phones %.6f\n", levels[1]); // no dial reads it now; the line stays so older files still parse
fprintf(f, "monitor %.6f\n", levels[0]);
fprintf(f, "tab %d\n", current_mix);
fprintf(f, "masters %.6f %.6f %.6f\n", mix_master[0], mix_master[1], mix_master[2]);
for (int m = 0; m < MIXER_BUSES; m++) {
fprintf(f, "mutes %d", m);
for (size_t i = 0; i < n && i < mute_value[m].size(); i++)
fprintf(f, " %d", mute_value[m][i] ? 1 : 0);
fprintf(f, "\nsolos %d", m);
for (size_t i = 0; i < n && i < solo_value[m].size(); i++)
fprintf(f, " %d", solo_value[m][i] ? 1 : 0);
fprintf(f, "\n");
}
fprintf(f, "pairlinks");
for (size_t i = 0; i < n && i < chan_link.size(); i++)
fprintf(f, " %d", chan_link[i] ? 1 : 0);
fprintf(f, "\npairmono");
for (size_t i = 0; i < n && i < chan_mono.size(); i++)
fprintf(f, " %d", chan_mono[i] ? 1 : 0);
fprintf(f, "\nloopback %d\n", route_state[3]);
for (size_t i = 0; i < n && i < chan_name.size(); i++)
if (!chan_name[i].empty())
fprintf(f, "name %zu %s\n", i, chan_name[i].c_str());
// after the names, whose reader stops at the first key that is not
// one - which is exactly how this line is found again
fprintf(f, "alttrim %d\n", alt_trim_db);
fclose(f);
// written to the side and renamed over, so a crash mid-write cannot
// leave a half file where the good one was
rename(tmp.c_str(), path.c_str());
}
static void save_state() { save_state_to(state_path()); }
// All or nothing: a file that does not parse, or that was written for a
// different channel count, is ignored and the defaults stand.
static bool load_state_from(const std::string& path)
{
if (path.empty())
return false;
FILE *f = fopen(path.c_str(), "r");
if (!f)
return false;
const device_properties &dev = devices[driver_indicator];
const long want = dev.mic_inputs + dev.digital_inputs;
char key[16] = {0};
int ver = 0;
long n = 0;
std::vector<float> lv[MIXER_BUSES], pv[MIXER_BUSES];
std::vector<char> ph;
int route[3] = {0}, link = 1, tab = 0;
float phones = 0.0f, monitor = 0.0f;
float mm[MIXER_BUSES] = {1.0f, 1.0f, 1.0f};
std::vector<char> mu[MIXER_BUSES], so[MIXER_BUSES];
auto clamp01 = [](float v) { return v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v); };
bool ok = fscanf(f, "%15s %d", key, &ver) == 2 && !strcmp(key, "bid-state") && ver == 1
&& fscanf(f, "%15s %ld", key, &n) == 2 && !strcmp(key, "channels") && n == want;
auto row = [&](const char *name, std::vector<float> &out) {
int m = 0;
if (!ok || fscanf(f, "%15s %d", key, &m) != 2 || strcmp(key, name) != 0) {
ok = false;
return;
}
for (long i = 0; i < n; i++) {
float v = 0.0f;
if (fscanf(f, "%f", &v) != 1) {
ok = false;
return;
}
out.push_back(clamp01(v));
}
};
for (int m = 0; m < MIXER_BUSES; m++) {
row("levels", lv[m]);
row("pans", pv[m]);
}
if (ok && (fscanf(f, "%15s", key) != 1 || strcmp(key, "phase") != 0))
ok = false;
for (long i = 0; ok && i < n; i++) {
int v = 0;
if (fscanf(f, "%d", &v) != 1)
ok = false;
else
ph.push_back(v != 0);
}
if (ok && (fscanf(f, "%15s %d %d %d", key, &route[0], &route[1], &route[2]) != 4 || strcmp(key, "route") != 0))
ok = false;
if (ok && (fscanf(f, "%15s %d", key, &link) != 2 || strcmp(key, "link") != 0))
ok = false;
if (ok && (fscanf(f, "%15s %f", key, &phones) != 2 || strcmp(key, "phones") != 0))
ok = false;
if (ok && (fscanf(f, "%15s %f", key, &monitor) != 2 || strcmp(key, "monitor") != 0))
ok = false;
if (ok && (fscanf(f, "%15s %d", key, &tab) != 2 || strcmp(key, "tab") != 0))
ok = false;
// newer fields: absent from older files, which stay valid without them
bool extra = ok && fscanf(f, "%15s %f %f %f", key, &mm[0], &mm[1], &mm[2]) == 4 && strcmp(key, "masters") == 0;
for (int m = 0; extra && m < MIXER_BUSES; m++) {
int mi = 0;
extra = fscanf(f, "%15s %d", key, &mi) == 2 && strcmp(key, "mutes") == 0;
for (long i = 0; extra && i < n; i++) {
int v = 0;
if (fscanf(f, "%d", &v) != 1) extra = false; else mu[m].push_back(v != 0);
}
if (extra)
extra = fscanf(f, "%15s %d", key, &mi) == 2 && strcmp(key, "solos") == 0;
for (long i = 0; extra && i < n; i++) {
int v = 0;
if (fscanf(f, "%d", &v) != 1) extra = false; else so[m].push_back(v != 0);
}
}
// the input pair links arrived later still; a file without them is valid
bool extra2 = extra && fscanf(f, "%15s", key) == 1 && strcmp(key, "pairlinks") == 0;
std::vector<char> pl;
for (long i = 0; extra2 && i < n; i++) {
int v = 0;
if (fscanf(f, "%d", &v) != 1) extra2 = false; else pl.push_back(v != 0);
}
bool extra3 = extra2 && fscanf(f, "%15s", key) == 1 && strcmp(key, "pairmono") == 0;
std::vector<char> pm;
for (long i = 0; extra3 && i < n; i++) {
int v = 0;
if (fscanf(f, "%d", &v) != 1) extra3 = false; else pm.push_back(v != 0);
}
int lbsrc = -1;
bool extra4 = extra3 && fscanf(f, "%15s %d", key, &lbsrc) == 2 && strcmp(key, "loopback") == 0;
// channel names, one line each, written only for the renamed
std::vector<std::string> nm((size_t)n);
int atrim = -6;
if (extra4) {
long ni = 0;
while (fscanf(f, "%15s %ld", key, &ni) == 2 && strcmp(key, "name") == 0) {
char rest[64] = {0};
if (!fgets(rest, sizeof(rest), f))
break;
char *t = rest;
while (*t == ' ')
t++;
t[strcspn(t, "\n")] = 0;
if (ni >= 0 && ni < n && *t)
nm[ni] = t;
}
// the loop stops on the first key that is not a name - which is
// where the alt trim line lives, already parsed into key and ni
if (!strcmp(key, "alttrim"))
atrim = (int)(ni < -24 ? -24 : (ni > 0 ? 0 : ni));
}
fclose(f);
if (!ok)
return false;
for (int m = 0; m < MIXER_BUSES; m++) {
bar_value[m] = lv[m];
pan_value[m] = pv[m];
}
phase_value.assign(ph.begin(), ph.end());
for (int p = 0; p < 3; p++)
route_state[p] = sane_route(p, (route[p] >= 0 && route[p] < ROUTE_SOURCES) ? route[p] : route_default[p]);
out_link[0] = link != 0;
levels[1] = clamp01(phones);
levels[0] = clamp01(monitor);
current_mix = (tab >= 0 && tab < MIXER_BUSES) ? tab : 0;
want_mix_tab = current_mix;
for (int m = 0; m < MIXER_BUSES; m++) {
mix_master[m] = extra ? clamp01(mm[m]) : 1.0f;
if (extra && (long)mu[m].size() == n)
mute_value[m].assign(mu[m].begin(), mu[m].end());
else
mute_value[m].assign(n, false);
if (extra && (long)so[m].size() == n)
solo_value[m].assign(so[m].begin(), so[m].end());
else
solo_value[m].assign(n, false);
}
if (extra2 && (long)pl.size() == n)
chan_link.assign(pl.begin(), pl.end());
else
chan_link.assign(n, false);
if (extra3 && (long)pm.size() == n)
chan_mono.assign(pm.begin(), pm.end());
else
chan_mono.assign(n, false);
route_state[3] = sane_route(3, (extra4 && lbsrc >= 0 && lbsrc < ROUTE_SOURCES) ? lbsrc : route_default[3]);
chan_name.assign(nm.begin(), nm.end());
alt_trim_db = atrim;
return true;
}
static void load_state() { load_state_from(state_path()); }
// Presets are the same file format under a chosen name, per device, in
// the presets folder next to the state file. Recalling one is a load
// plus the same push a connect does.
static std::string presets_dir()
{
std::string p = state_path();
if (p.empty())
return "";
return p.substr(0, p.rfind('/')) + "/presets";
}
static std::string preset_path(const std::string& name)
{
char pfx[24];
snprintf(pfx, sizeof(pfx), "/preset-%04x-", devices[driver_indicator].usb_id);
return presets_dir() + pfx + name + ".conf";
}
// keep names filesystem-tame: letters, digits, space, dash, underscore
static std::string sanitize_preset(const char* raw)
{
std::string out;
for (const char* c = raw; *c; c++)
if (isalnum((unsigned char)*c) || *c == ' ' || *c == '-' || *c == '_')
out += *c;
while (!out.empty() && out.back() == ' ')
out.pop_back();
while (!out.empty() && out.front() == ' ')
out.erase(out.begin());
return out;
}
// One saved desk per device is the one to come back to: the default. It
// lives beside the presets under a name of its own, so renaming or deleting
// presets cannot touch it, and it holds everything a preset does - levels,
// pans, names, routing. Restoring it is a recall like any other.
static std::string default_path()
{
std::string d = presets_dir();
if (d.empty())
return d;
char pfx[24];
snprintf(pfx, sizeof(pfx), "/default-%04x.conf", devices[driver_indicator].usb_id);
return d + pfx;
}
static bool have_default()
{
std::string p = default_path();
if (p.empty())
return false;
FILE *f = fopen(p.c_str(), "r");
if (!f)
return false;
fclose(f);
return true;
}
// A preset becomes the default by being copied over it, byte for byte:
// nothing is loaded onto the desk on the way there.
static bool copy_conf(const std::string& src, const std::string& dst)
{
if (src.empty() || dst.empty())
return false;
FILE *in = fopen(src.c_str(), "rb");
if (!in)
return false;
std::string tmp = dst + ".tmp";
FILE *out = fopen(tmp.c_str(), "wb");
if (!out) {
fclose(in);
return false;
}
char buf[4096];
size_t n;
bool ok = true;
while ((n = fread(buf, 1, sizeof(buf), in)) > 0)
if (fwrite(buf, 1, n, out) != n) {
ok = false;
break;
}
fclose(in);
fclose(out);
if (ok)
rename(tmp.c_str(), dst.c_str());
else
remove(tmp.c_str());
return ok;
}
static void list_presets(std::vector<std::string>& out)
{
out.clear();
std::string dir = presets_dir();
char pfx[24];
snprintf(pfx, sizeof(pfx), "preset-%04x-", devices[driver_indicator].usb_id);
DIR *d = opendir(dir.c_str());
if (!d)
return;
struct dirent *e;
size_t pl = strlen(pfx);
while ((e = readdir(d)) != NULL) {
std::string fn = e->d_name;
if (fn.size() > pl + 5 && fn.rfind(pfx, 0) == 0 && fn.substr(fn.size() - 5) == ".conf")
out.push_back(fn.substr(pl, fn.size() - pl - 5));
}
closedir(d);
std::sort(out.begin(), out.end());
}
// App settings, global rather than per device: whether launch connects
// by itself, whether BiD claims the system output (settings.conf), and
// whether login starts BiD at all - that one is the XDG autostart file's
// existence, so it can never desync.
static bool opt_autoconnect = false;
static bool opt_autostart = false;
static bool opt_sysout = false;
static std::string settings_path()
{
std::string base = config_base();
return base.empty() ? "" : base + "/bid/settings.conf";
}
static void save_settings()
{
std::string path = settings_path();
if (path.empty())
return;
mkdir(path.substr(0, path.rfind('/')).c_str(), 0755);
FILE *f = fopen(path.c_str(), "w");
if (!f)
return;
fprintf(f, "bid-settings 1\nautoconnect %d\nsysout %d\n",
opt_autoconnect ? 1 : 0, opt_sysout ? 1 : 0);
fclose(f);
}
static void load_settings()
{
std::string path = settings_path();
if (path.empty())
return;
FILE *f = fopen(path.c_str(), "r");
if (!f)
return;
char key[16] = {0};
int ver = 0, ac = 0, so = 0;
if (fscanf(f, "%15s %d", key, &ver) == 2 && !strcmp(key, "bid-settings")
&& fscanf(f, "%15s %d", key, &ac) == 2 && !strcmp(key, "autoconnect")) {
opt_autoconnect = ac != 0;
// later arrival: a file without the line keeps the default
if (fscanf(f, "%15s %d", key, &so) == 2 && !strcmp(key, "sysout"))
opt_sysout = so != 0;
}
fclose(f);
}
// Claiming the system output: switch the Audient card to the sound
// server's Pro Audio profile and make it the default sink. One honest
// multichannel output instead of the invented stereo splits - and since
// the desktop's output menu offers every profile as a clickable entry, a
// misclick there flips the card right back, which is why the claim is
// reasserted on every launch and every connect rather than made once.
// All through pactl in a worker thread: PipeWire remembers the choice,
// and a system without pactl or the profile quietly declines.
static std::atomic<int> sysout_state{0}; // indexes sysout_note below
static std::string run_read(const char* cmd)
{
std::string out;
FILE *p = popen(cmd, "r");
if (!p)
return out;
char buf[256];
size_t got;
while ((got = fread(buf, 1, sizeof(buf), p)) > 0)
out.append(buf, got);
pclose(p);
return out;
}
// How many listing lines hold the needle.
static int pactl_count(const std::string& listing, const char* what)
{
int n = 0;
size_t at = 0;
while (at < listing.size()) {
size_t end = listing.find('\n', at);
if (end == std::string::npos)
end = listing.size();
if (listing.substr(at, end - at).find(what) != std::string::npos)
n++;
at = end + 1;
}
return n;
}
// Second tab-separated field of the first listing line holding both
// needles (the second may be null), or empty.
static std::string pactl_find(const std::string& listing, const char* what, const char* also)
{
size_t at = 0;
while (at < listing.size()) {
size_t end = listing.find('\n', at);
if (end == std::string::npos)
end = listing.size();
std::string line = listing.substr(at, end - at);
if (line.find(what) != std::string::npos
&& (!also || line.find(also) != std::string::npos)) {
size_t a = line.find('\t');
if (a == std::string::npos)
return "";
size_t b = line.find('\t', a + 1);
return line.substr(a + 1, b == std::string::npos ? std::string::npos : b - a - 1);
}
at = end + 1;
}
return "";
}
static void sysout_claim()
{
if (sysout_state == 1)
return;
sysout_state = 1;
std::thread([]{
if (run_read("command -v pactl 2>/dev/null").empty()) {
sysout_state = 3;
return;
}
std::string card = pactl_find(run_read("pactl list short cards 2>/dev/null"), "usb-Audient", NULL);
if (card.empty()) {
sysout_state = 4;
return;
}
// Everything from here on speaks about this one card, by its own
// name token - a second Audient box on the bus must not sway the
// sink count, and the flipped card's own input is the one to
// follow. The token is the card name shorn of its alsa_card.
// prefix, which is exactly how its sinks and sources begin.
std::string token = card.compare(0, 10, "alsa_card.") == 0 ? card.substr(10) : card;
// What the claim does depends on what the card already shows. One
// sink is already the honest shape: flipping its profile would
// only rename the nodes out from under every app that remembered
// them - the mic hunt that followed doing it to an iD24 - so it
// just becomes the default. Only a card split into several sinks
// is moved to Pro Audio, and there the default input moves too,
// because the flip kills the input name apps were holding.
std::string sinks = run_read("pactl list short sinks 2>/dev/null");
std::string sink = pactl_find(sinks, token.c_str(), NULL);
if (pactl_count(sinks, token.c_str()) != 1) {
run_read(("pactl set-card-profile '" + card + "' pro-audio 2>/dev/null").c_str());
// the new sinks arrive a beat after the profile flips
sink.clear();
for (int i = 0; i < 25 && sink.empty(); i++) {
sink = pactl_find(run_read("pactl list short sinks 2>/dev/null"), token.c_str(), "pro-output");
if (sink.empty())
usleep(100000);
}
if (sink.empty()) {
sysout_state = 5;
return;
}
std::string src = pactl_find(run_read("pactl list short sources 2>/dev/null"), token.c_str(), "pro-input");
if (!src.empty())
run_read(("pactl set-default-source '" + src + "' 2>/dev/null").c_str());
}
run_read(("pactl set-default-sink '" + sink + "' 2>/dev/null").c_str());
sysout_state = 2;
}).detach();
}
static std::string autostart_path()
{
std::string base = config_base();
return base.empty() ? "" : base + "/autostart/bid.desktop";
}
// The autostart entry points at this very binary, so whichever build the
// user runs is the build that greets the next login - hidden in the tray.
static void set_autostart(bool on)
{
std::string path = autostart_path();
if (path.empty())
return;
if (!on) {
remove(path.c_str());
return;
}
char self[PATH_MAX];
ssize_t n = readlink("/proc/self/exe", self, sizeof(self) - 1);
if (n <= 0)
return;
self[n] = 0;
mkdir(path.substr(0, path.rfind('/')).c_str(), 0755);
FILE *f = fopen(path.c_str(), "w");
if (!f)
return;
fprintf(f, "[Desktop Entry]\nType=Application\nName=BiD\n"
"Comment=Open source Audient mixer\nExec=%s --tray\n"
"Icon=bid\nTerminal=false\n", self);
fclose(f);
}
// Which ALSA card is this device? procfs, matched by USB id.
static int asound_card_of(uint16_t usb_id)
{
char path[64];
for (int card = 0; card < 32; card++) {
snprintf(path, sizeof(path), "/proc/asound/card%d/usbid", card);
FILE *f = fopen(path, "r");
if (!f)
continue;
unsigned vid = 0, pid = 0;
int m = fscanf(f, "%x:%x", &vid, &pid);
fclose(f);
if (m == 2 && vid == 0x2708 && pid == usb_id)
return card;
}
return -1;
}
// The sample rate is negotiated by the kernel driver and the applications,
// not by anything BiD says over USB, so the honest source is ALSA's procfs:
// take the momentary rate of whichever stream is running. Zero means no
// stream is up, or no card was found at all.
static int read_sample_rate(uint16_t usb_id)
{
char path[64], line[256];
int card = asound_card_of(usb_id);
if (card >= 0) {
for (int stream = 0; stream < 4; stream++) {
snprintf(path, sizeof(path), "/proc/asound/card%d/stream%d", card, stream);
FILE *f = fopen(path, "r");
if (!f)
break;
int rate = 0;
while (fgets(line, sizeof(line), f)) {
const char *hit = strstr(line, "Momentary freq = ");
if (hit && sscanf(hit, "Momentary freq = %d", &rate) == 1 && rate > 0)
break;
}
fclose(f);
if (rate > 0)
return rate;
}
}
return 0;
}
// The rates the card offers, parsed from the same stream file: the union
// of every "Rates:" line, sorted. Feeds the pin-the-rate menu.
static void read_supported_rates(uint16_t usb_id, std::vector<int>& out)
{
out.clear();
char path[64], line[256];
int card = asound_card_of(usb_id);
{
if (card < 0)
return;
snprintf(path, sizeof(path), "/proc/asound/card%d/stream0", card);
FILE *f = fopen(path, "r");
if (!f)
return;
while (fgets(line, sizeof(line), f)) {
const char *hit = strstr(line, "Rates: ");
if (!hit)
continue;
for (const char *c = hit + 7; *c; ) {
int r = 0;
if (sscanf(c, "%d", &r) == 1 && r >= 8000
&& std::find(out.begin(), out.end(), r) == out.end())
out.push_back(r);
while (*c && *c != ',')
c++;
if (*c == ',')
c++;
}
}
fclose(f);
std::sort(out.begin(), out.end());
return;
}
}
// Pinning the rate is PipeWire's decision, not the device's: the graph
// owns the clock and the hardware follows it. pw-metadata is the same
// knob the PipeWire tools use; zero unpins, and the graph goes back to
// following whatever the applications ask for.
static void force_graph_rate(int hz)
{
char cmd[128];
snprintf(cmd, sizeof(cmd), "pw-metadata -n settings 0 clock.force-rate %d >/dev/null 2>&1", hz);
if (system(cmd)) {}
}
// The clock selector and its validity flags are plain ALSA controls - the
// kernel owns them, no USB protocol involved. amixer keeps BiD free of a
// libasound link, the same bargain pw-metadata strikes with PipeWire.
// Source 0 is the internal clock, 1 the optical input's.
static void read_clock_state(int card, int *src, bool *int_ok, bool *opt_ok)
{
char cmd[160], line[256];
*src = -1;
*int_ok = *opt_ok = false;
snprintf(cmd, sizeof(cmd), "amixer -c %d cget iface=MIXER,name='Audient Clock Selector Clock Source' 2>/dev/null", card);
FILE *p = popen(cmd, "r");
if (p) {
while (fgets(line, sizeof(line), p)) {
const char *v = strstr(line, ": values=");
if (v)
*src = atoi(v + 9);
}
pclose(p);
}
const char *names[2] = { "Internal", "Optical1" };
bool *flags[2] = { int_ok, opt_ok };
for (int i = 0; i < 2; i++) {
snprintf(cmd, sizeof(cmd), "amixer -c %d cget iface=CARD,name='Audient %s Clock Validity' 2>/dev/null", card, names[i]);
p = popen(cmd, "r");
if (!p)
continue;
while (fgets(line, sizeof(line), p))
if (strstr(line, ": values=on"))
*flags[i] = true;
pclose(p);
}
}
static void set_clock_source(int card, int src)
{
char cmd[160];
snprintf(cmd, sizeof(cmd), "amixer -c %d cset iface=MIXER,name='Audient Clock Selector Clock Source' %d >/dev/null 2>&1", card, src);
if (system(cmd)) {}
}
// When no stream runs the kernel has no momentary rate to report, so ask
// PipeWire what the graph is set to: the pin when one is set, the default
// otherwise. Whatever plays next will run at this rate.
static int read_graph_rate()
{
FILE *p = popen("pw-metadata -n settings 0 2>/dev/null", "r");
if (!p)
return 0;
char line[256];
int rate = 0, forced = 0;
while (fgets(line, sizeof(line), p)) {
const char *vv = strstr(line, "value:'");
int v = 0;
if (!vv || sscanf(vv + 7, "%d", &v) != 1)
continue;
if (strstr(line, "'clock.force-rate'"))
forced = v;
else if (strstr(line, "'clock.rate'"))
rate = v;
}
pclose(p);
return forced > 0 ? forced : rate;
}
// A short kHz label: 48000 reads "48 kHz", 44100 reads "44.1 kHz".
static void khz_label(char *out, size_t n, int hz)
{
if (hz <= 0)
snprintf(out, n, "-- kHz");
else if (hz % 1000 == 0)
snprintf(out, n, "%d kHz", hz / 1000);
else
snprintf(out, n, "%.1f kHz", hz / 1000.0);
}