Debian Codegraph @

src/alsa.c

raw symbols SCIP
1 // SPDX-FileCopyrightText: 2022-2025 Geoffrey D. Bennett <[email protected]>
2 // SPDX-License-Identifier: GPL-3.0-or-later
3
4 #include <sys/inotify.h>
5 #include <alsa/sound/uapi/tlv.h>
6
7 #include "alsa.h"
8 #include "scarlett2.h"
9 #include "scarlett2-firmware.h"
10 #include "scarlett4-firmware.h"
11 #include "scarlett2-ioctls.h"
12 #include "stringhelper.h"
13 #include "window-iface.h"
14 #include "optional-controls.h"
15 #include "custom-names.h"
16 #include "port-enable.h"
17 #include "stereo-link.h"
18 #include "dsp-state.h"
19 #include "hw-io-availability.h"
20 #include "presets.h"
21
22 #define MAJOR_HWDEP_VERSION_SCARLETT2 1
23 #define MAJOR_HWDEP_VERSION_FCP 2
24
25 #define MAX_TLV_RANGE_SIZE 1024
26
27 // TLV type for channel labels
28 #ifndef SNDRV_CTL_TLVT_FCP_CHANNEL_LABELS
29 #define SNDRV_CTL_TLVT_FCP_CHANNEL_LABELS 0x110
30 #endif
31
32 // names for the port categories
33 const char *port_category_names[PC_COUNT] = {
34 NULL,
35 "Hardware Outputs",
36 "Mixer Inputs",
37 "DSP Inputs",
38 "PCM Inputs"
39 };
40
41 // short names for the port categories (for debug output)
42 const char *port_category_short_names[PC_COUNT] = {
43 "OFF",
44 "HW",
45 "MIX",
46 "DSP",
47 "PCM"
48 };
49
50 // names for the hardware types
51 const char *hw_type_names[HW_TYPE_COUNT] = {
52 "Analogue",
53 "S/PDIF",
54 "ADAT"
55 };
56
57 // global array of cards
58 static GArray *alsa_cards;
59
60 // static fd and wd for ALSA inotify
61 static int inotify_fd, inotify_wd;
62
63 struct reopen_callback {
64 ReOpenCallback *callback;
65 void *data;
66 };
67
68 // hash table for cards being rebooted
69 GHashTable *reopen_callbacks;
70
71 // forward declaration
72 void alsa_elem_change(struct alsa_elem *elem);
73
74 void fatal_alsa_error(const char *msg, int err) {
75 fprintf(stderr, "%s: %s\n", msg, snd_strerror(err));
76 exit(1);
77 }
78
79 //
80 // functions to locate elements or get information about them
81 //
82
83 // return the element with the exact matching name
84 struct alsa_elem *get_elem_by_name(GPtrArray *elems, const char *name) {
85 for (int i = 0; i < elems->len; i++) {
86 struct alsa_elem *elem = g_ptr_array_index(elems, i);
87
88 if (!elem->card)
89 continue;
90
91 if (strcmp(elem->name, name) == 0)
92 return elem;
93 }
94
95 return NULL;
96 }
97
98 // return the first element with a name starting with the given prefix
99 struct alsa_elem *get_elem_by_prefix(GPtrArray *elems, const char *prefix) {
100 int prefix_len = strlen(prefix);
101
102 for (int i = 0; i < elems->len; i++) {
103 struct alsa_elem *elem = g_ptr_array_index(elems, i);
104
105 if (!elem->card)
106 continue;
107
108 if (strncmp(elem->name, prefix, prefix_len) == 0)
109 return elem;
110 }
111
112 return NULL;
113 }
114
115 // return the first element with a name containing the given substring
116 struct alsa_elem *get_elem_by_substr(GPtrArray *elems, const char *substr) {
117 for (int i = 0; i < elems->len; i++) {
118 struct alsa_elem *elem = g_ptr_array_index(elems, i);
119
120 if (!elem->card)
121 continue;
122
123 if (strstr(elem->name, substr))
124 return elem;
125 }
126
127 return NULL;
128 }
129
130 // find the maximum number in the matching elements
131 // search by element name prefix and substring
132 // e.g. get_max_elem_by_name(elems, "Line", "Pad Capture Switch")
133 // will return 8 when the last pad capture switch is
134 // "Line In 8 Pad Capture Switch"
135 int get_max_elem_by_name(
136 GPtrArray *elems,
137 const char *prefix,
138 const char *needle
139 ) {
140 int max = 0;
141 int l = strlen(prefix);
142
143 for (int i = 0; i < elems->len; i++) {
144 struct alsa_elem *elem = g_ptr_array_index(elems, i);
145 int num;
146
147 if (!elem->card)
148 continue;
149
150 if (strncmp(elem->name, prefix, l) != 0)
151 continue;
152
153 if (!strstr(elem->name, needle))
154 continue;
155
156 num = get_num_from_string(elem->name);
157 if (num > max)
158 max = num;
159 }
160
161 return max;
162 }
163
164 // add a callback to the list of callbacks for this element
165 void alsa_elem_add_callback(
166 struct alsa_elem *elem,
167 AlsaElemCallback *callback,
168 void *data,
169 GDestroyNotify destroy
170 ) {
171 struct alsa_elem_callback *cb = calloc(1, sizeof(struct alsa_elem_callback));
172
173 cb->callback = callback;
174 cb->data = data;
175 cb->destroy = destroy;
176
177 elem->callbacks = g_list_append(elem->callbacks, cb);
178 }
179
180 void alsa_elem_remove_callbacks_by_data(struct alsa_elem *elem, void *data) {
181 if (!elem || !elem->callbacks)
182 return;
183
184 GList *l = elem->callbacks;
185 while (l) {
186 GList *next = l->next;
187 struct alsa_elem_callback *cb = l->data;
188
189 if (cb && cb->data == data) {
190 if (cb->destroy)
191 cb->destroy(cb->data);
192 free(cb);
193 elem->callbacks = g_list_delete_link(elem->callbacks, l);
194 }
195
196 l = next;
197 }
198 }
199
200 //
201 // alsa snd_ctl_elem_*() mediation functions
202 // for simulated elements, fake the ALSA element
203 // for real elements, pass through to snd_ctl_elem*()
204 //
205
206 // get the element type
207 int alsa_get_elem_type(struct alsa_elem *elem) {
208 snd_ctl_elem_info_t *elem_info;
209
210 snd_ctl_elem_info_alloca(&elem_info);
211 snd_ctl_elem_info_set_numid(elem_info, elem->numid);
212 snd_ctl_elem_info(elem->card->handle, elem_info);
213
214 return snd_ctl_elem_info_get_type(elem_info);
215 }
216
217 // get the element name
218 char *alsa_get_elem_name(struct alsa_elem *elem) {
219 snd_ctl_elem_info_t *elem_info;
220
221 snd_ctl_elem_info_alloca(&elem_info);
222 snd_ctl_elem_info_set_numid(elem_info, elem->numid);
223 snd_ctl_elem_info(elem->card->handle, elem_info);
224
225 const char *name = snd_ctl_elem_info_get_name(elem_info);
226 return strdup(name);
227 }
228
229 // get the element value
230 // boolean, enum, or int all returned as long ints
231 long alsa_get_elem_value(struct alsa_elem *elem) {
232 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated)
233 return elem->value;
234
235 snd_ctl_elem_value_t *elem_value;
236
237 snd_ctl_elem_value_alloca(&elem_value);
238 snd_ctl_elem_value_set_numid(elem_value, elem->numid);
239 snd_ctl_elem_read(elem->card->handle, elem_value);
240
241 int type = elem->type;
242 if (type == SND_CTL_ELEM_TYPE_BOOLEAN) {
243 return snd_ctl_elem_value_get_boolean(elem_value, elem->index);
244 } else if (type == SND_CTL_ELEM_TYPE_ENUMERATED) {
245 return snd_ctl_elem_value_get_enumerated(elem_value, elem->index);
246 } else if (type == SND_CTL_ELEM_TYPE_INTEGER) {
247 return snd_ctl_elem_value_get_integer(elem_value, elem->index);
248 } else {
249 fprintf(
250 stderr,
251 "internal error: elem %s (%d) type %d not bool/enum/int\n",
252 elem->name,
253 elem->numid,
254 elem->type
255 );
256 return 0;
257 }
258 }
259
260 // idle callback to trigger element change
261 static gboolean alsa_elem_change_idle(gpointer user_data) {
262 struct alsa_elem *elem = user_data;
263 elem->pending_idle = 0;
264 alsa_elem_change(elem);
265 return G_SOURCE_REMOVE;
266 }
267
268 // for elements with multiple int values, return all the values
269 // the int array returned needs to be freed by the caller
270 long *alsa_get_elem_int_values(struct alsa_elem *elem) {
271 long *values = calloc(elem->count, sizeof(long));
272
273 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated) {
274 if (elem->values)
275 memcpy(values, elem->values, elem->count * sizeof(long));
276 return values;
277 }
278
279 snd_ctl_elem_value_t *elem_value;
280
281 snd_ctl_elem_value_alloca(&elem_value);
282 snd_ctl_elem_value_set_numid(elem_value, elem->numid);
283 snd_ctl_elem_read(elem->card->handle, elem_value);
284
285 for (int i = 0; i < elem->count; i++)
286 values[i] = snd_ctl_elem_value_get_integer(elem_value, i);
287
288 return values;
289 }
290
291 // set multiple int values for an element (e.g., biquad coefficients)
292 void alsa_set_elem_int_values(
293 struct alsa_elem *elem, const long *values, int count
294 ) {
295 int n = count < elem->count ? count : elem->count;
296 size_t size = n * sizeof(long);
297
298 // Allocate cache on first use
299 if (!elem->values)
300 elem->values = calloc(elem->count, sizeof(long));
301
302 // Skip if unchanged
303 if (memcmp(elem->values, values, size) == 0)
304 return;
305
306 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated) {
307 memcpy(elem->values, values, size);
308 if (!elem->pending_idle)
309 elem->pending_idle =
310 g_idle_add(alsa_elem_change_idle, elem);
311 return;
312 }
313
314 // Don't update cache here - let ALSA callback do it so callbacks fire
315
316 snd_ctl_elem_value_t *elem_value;
317
318 snd_ctl_elem_value_alloca(&elem_value);
319 snd_ctl_elem_value_set_numid(elem_value, elem->numid);
320
321 for (int i = 0; i < n; i++)
322 snd_ctl_elem_value_set_integer(elem_value, i, values[i]);
323
324 snd_ctl_elem_write(elem->card->handle, elem_value);
325 }
326
327 // set the element value
328 // boolean, enum, or int all set from long ints
329 void alsa_set_elem_value(struct alsa_elem *elem, long value) {
330 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated) {
331 if (elem->value != value) {
332 elem->value = value;
333 alsa_elem_change(elem);
334 }
335 return;
336 }
337
338 snd_ctl_elem_value_t *elem_value;
339
340 snd_ctl_elem_value_alloca(&elem_value);
341 snd_ctl_elem_value_set_numid(elem_value, elem->numid);
342 snd_ctl_elem_read(elem->card->handle, elem_value);
343
344 int type = elem->type;
345 if (type == SND_CTL_ELEM_TYPE_BOOLEAN) {
346 snd_ctl_elem_value_set_boolean(elem_value, elem->index, value);
347 } else if (type == SND_CTL_ELEM_TYPE_ENUMERATED) {
348 snd_ctl_elem_value_set_enumerated(elem_value, elem->index, value);
349 } else if (type == SND_CTL_ELEM_TYPE_INTEGER) {
350 snd_ctl_elem_value_set_integer(elem_value, elem->index, value);
351 } else {
352 fprintf(
353 stderr,
354 "internal error: elem %s (%d) type %d not bool/enum/int\n",
355 elem->name,
356 elem->numid,
357 elem->type
358 );
359 return;
360 }
361
362 snd_ctl_elem_write(elem->card->handle, elem_value);
363 }
364
365 // return whether the element can be modified (is writable)
366 int alsa_get_elem_writable(struct alsa_elem *elem) {
367 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated)
368 return elem->is_writable;
369
370 snd_ctl_elem_info_t *elem_info;
371
372 snd_ctl_elem_info_alloca(&elem_info);
373 snd_ctl_elem_info_set_numid(elem_info, elem->numid);
374 snd_ctl_elem_info(elem->card->handle, elem_info);
375
376 return snd_ctl_elem_info_is_writable(elem_info) &&
377 !snd_ctl_elem_info_is_locked(elem_info);
378 }
379
380 // return whether the element is volatile (can change without
381 // notification)
382 int alsa_get_elem_volatile(struct alsa_elem *elem) {
383 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated)
384 return elem->is_volatile;
385
386 snd_ctl_elem_info_t *elem_info;
387
388 snd_ctl_elem_info_alloca(&elem_info);
389 snd_ctl_elem_info_set_numid(elem_info, elem->numid);
390 snd_ctl_elem_info(elem->card->handle, elem_info);
391
392 return snd_ctl_elem_info_is_volatile(elem_info);
393 }
394
395 // get the number of values this element has
396 // (most are just 1; the levels element is the exception)
397 int alsa_get_elem_count(struct alsa_elem *elem) {
398 snd_ctl_elem_info_t *elem_info;
399
400 snd_ctl_elem_info_alloca(&elem_info);
401 snd_ctl_elem_info_set_numid(elem_info, elem->numid);
402 snd_ctl_elem_info(elem->card->handle, elem_info);
403
404 return snd_ctl_elem_info_get_count(elem_info);
405 }
406
407 // get the integer element's min and max values
408 static void alsa_get_elem_int_range(struct alsa_elem *elem) {
409 snd_ctl_elem_info_t *elem_info;
410
411 snd_ctl_elem_info_alloca(&elem_info);
412 snd_ctl_elem_info_set_numid(elem_info, elem->numid);
413 snd_ctl_elem_info(elem->card->handle, elem_info);
414
415 elem->min_val = snd_ctl_elem_info_get_min(elem_info);
416 elem->max_val = snd_ctl_elem_info_get_max(elem_info);
417 }
418
419 // get the number of items this enum element has
420 int alsa_get_item_count(struct alsa_elem *elem) {
421 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated)
422 return elem->item_count;
423
424 snd_ctl_elem_info_t *elem_info;
425
426 snd_ctl_elem_info_alloca(&elem_info);
427 snd_ctl_elem_info_set_numid(elem_info, elem->numid);
428 snd_ctl_elem_info(elem->card->handle, elem_info);
429
430 return snd_ctl_elem_info_get_items(elem_info);
431 }
432
433 // get the name of an item of the given enum element
434 char *alsa_get_item_name(struct alsa_elem *elem, int i) {
435 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated)
436 return strdup(elem->item_names[i]);
437
438 snd_ctl_elem_info_t *elem_info;
439
440 snd_ctl_elem_info_alloca(&elem_info);
441 snd_ctl_elem_info_set_numid(elem_info, elem->numid);
442 snd_ctl_elem_info_set_item(elem_info, i);
443 snd_ctl_elem_info(elem->card->handle, elem_info);
444
445 const char *name = snd_ctl_elem_info_get_item_name(elem_info);
446 return strdup(name);
447 }
448
449 // get the bytes data from a BYTES element
450 // returns pointer to data and sets *size to the data size
451 // for simulated elements, returns the stored bytes_value
452 // for real elements, reads from ALSA and caches in elem->bytes_value
453 const void *alsa_get_elem_bytes(struct alsa_elem *elem, size_t *size) {
454 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated) {
455 if (size)
456 *size = elem->count;
457 return elem->bytes_value;
458 }
459
460 // for real elements, read from ALSA and cache in elem->bytes_value
461 snd_ctl_elem_value_t *elem_value;
462
463 snd_ctl_elem_value_alloca(&elem_value);
464 snd_ctl_elem_value_set_numid(elem_value, elem->numid);
465 snd_ctl_elem_read(elem->card->handle, elem_value);
466
467 const void *data = snd_ctl_elem_value_get_bytes(elem_value);
468
469 // cache the data in elem->bytes_value (free old value first)
470 if (elem->bytes_value)
471 free(elem->bytes_value);
472 elem->bytes_value = malloc(elem->count);
473 memcpy(elem->bytes_value, data, elem->count);
474
475 if (size)
476 *size = elem->count;
477
478 return elem->bytes_value;
479 }
480
481 // set the bytes data for a BYTES element
482 // for simulated elements, stores in elem->bytes_value and triggers callbacks
483 // for real elements, writes to ALSA
484 void alsa_set_elem_bytes(struct alsa_elem *elem, const void *data, size_t size) {
485 if (elem->card->num == SIMULATED_CARD_NUM || elem->is_simulated) {
486 // truncate to max capacity
487 if (size > elem->bytes_size)
488 size = elem->bytes_size;
489
490 // skip if not changed
491 if (elem->count == size &&
492 memcmp(elem->bytes_value, data, size) == 0)
493 return;
494
495 memcpy(elem->bytes_value, data, size);
496 elem->count = size; // update actual length
497
498 // schedule callback from idle to avoid GTK warnings
499 if (!elem->pending_idle)
500 elem->pending_idle = g_idle_add(alsa_elem_change_idle, elem);
501 return;
502 }
503
504 snd_ctl_elem_value_t *elem_value;
505
506 snd_ctl_elem_value_alloca(&elem_value);
507 snd_ctl_elem_value_set_numid(elem_value, elem->numid);
508 snd_ctl_elem_set_bytes(elem_value, (void *)data, size);
509 snd_ctl_elem_write(elem->card->handle, elem_value);
510 }
511
512 // create a simulated optional element and add it to the card's element array
513 // used for optional controls that may not exist on all devices
514 struct alsa_elem *alsa_create_optional_elem(
515 struct alsa_card *card,
516 const char *name,
517 int type,
518 size_t max_size
519 ) {
520 // allocate new element
521 struct alsa_elem *elem = calloc(1, sizeof(struct alsa_elem));
522
523 elem->card = card;
524 elem->numid = 0; // simulated elements have no numid
525 elem->name = strdup(name);
526 elem->type = type;
527 elem->count = 1;
528 elem->index = 0;
529
530 // mark as simulated
531 elem->is_simulated = 1;
532 elem->is_writable = 1;
533 elem->is_volatile = 0;
534
535 // for BYTES elements, allocate buffer at max size
536 if (type == SND_CTL_ELEM_TYPE_BYTES) {
537 elem->bytes_value = malloc(max_size);
538 elem->count = 0; // actual length, starts at 0
539 elem->bytes_size = max_size; // max capacity
540 }
541
542 // add to card->elems array
543 g_ptr_array_add(card->elems, elem);
544
545 return elem;
546 }
547
548 // create a simulated optional enumerated element with item names
549 struct alsa_elem *alsa_create_optional_enum_elem(
550 struct alsa_card *card,
551 const char *name,
552 const char **item_names,
553 int item_count
554 ) {
555 // check if element already exists
556 struct alsa_elem *elem = get_elem_by_name(card->elems, name);
557 if (elem)
558 return elem;
559
560 // allocate new element
561 elem = calloc(1, sizeof(struct alsa_elem));
562
563 elem->card = card;
564 elem->numid = 0; // simulated elements have no numid
565 elem->name = strdup(name);
566 elem->type = SND_CTL_ELEM_TYPE_ENUMERATED;
567 elem->count = 1;
568 elem->index = 0;
569
570 // mark as simulated
571 elem->is_simulated = 1;
572 elem->is_writable = 1;
573 elem->is_volatile = 0;
574
575 // set up enum items
576 elem->item_count = item_count;
577 elem->item_names = calloc(item_count, sizeof(char *));
578 for (int i = 0; i < item_count; i++)
579 elem->item_names[i] = strdup(item_names[i]);
580
581 elem->min_val = 0;
582 elem->max_val = item_count - 1;
583 elem->value = 0;
584
585 // add to card->elems array
586 g_ptr_array_add(card->elems, elem);
587
588 return elem;
589 }
590
591 //
592 // create/destroy alsa cards
593 //
594
595 static void alsa_get_elem_tlv(struct alsa_elem *elem) {
596 struct alsa_card *card = elem->card;
597
598 if (elem->type != SND_CTL_ELEM_TYPE_INTEGER)
599 return;
600
601 snd_ctl_elem_info_t *elem_info;
602
603 snd_ctl_elem_info_alloca(&elem_info);
604 snd_ctl_elem_info_set_numid(elem_info, elem->numid);
605 snd_ctl_elem_info(card->handle, elem_info);
606
607 if (!snd_ctl_elem_info_is_tlv_readable(elem_info))
608 return;
609
610 snd_ctl_elem_id_t *elem_id;
611 unsigned int tlv[MAX_TLV_RANGE_SIZE];
612 unsigned int *dbrec;
613 int ret;
614 long min_cdB, max_cdB;
615
616 snd_ctl_elem_id_alloca(&elem_id);
617 snd_ctl_elem_id_set_numid(elem_id, elem->numid);
618
619 ret = snd_ctl_elem_tlv_read(
620 card->handle, elem_id, tlv, sizeof(tlv)
621 );
622 if (ret < 0) {
623 fprintf(stderr, "TLV read error: %s\n", snd_strerror(ret));
624 return;
625 }
626
627 // meter map
628 if (tlv[SNDRV_CTL_TLVO_TYPE] == SNDRV_CTL_TLVT_FCP_CHANNEL_LABELS) {
629 int label_data_size = tlv[SNDRV_CTL_TLVO_LEN];
630 char *label_data = (char *)&tlv[SNDRV_CTL_TLVO_LEN + 1];
631
632 // check that there are at least elem->count labels in the data
633 int label_count = 0;
634 for (int i = 0; i < label_data_size; i++) {
635 if (!label_data[i])
636 label_count++;
637 }
638
639 if (label_count < elem->count) {
640 fprintf(
641 stderr,
642 "TLV label count %d < %d\n",
643 label_count,
644 elem->count
645 );
646 return;
647 }
648
649 if (elem->count < 0 || elem->count > 255) {
650 fprintf(stderr, "TLV label count %d out of range\n", elem->count);
651 exit(1);
652 }
653
654 elem->meter_labels = calloc(elem->count, sizeof(char *));
655
656 char *cur_label = label_data;
657 for (int i = 0; i < elem->count; i++) {
658 elem->meter_labels[i] = strdup(cur_label);
659 if (!elem->meter_labels[i]) {
660 fprintf(stderr, "strdup failed\n");
661 exit(1);
662 }
663
664 cur_label += strlen(cur_label) + 1;
665 }
666
667 /* firmware version TLV contains socket location */
668 } else if (tlv[SNDRV_CTL_TLVO_TYPE] == 0x53434B54) {
669 card->fcp_socket = strdup((char *)&tlv[SNDRV_CTL_TLVO_LEN + 1]);
670
671 /* dB range */
672 } else {
673 ret = snd_tlv_parse_dB_info(tlv, sizeof(tlv), &dbrec);
674 if (ret <= 0) {
675 fprintf(stderr, "TLV parse error: %s\n", snd_strerror(ret));
676 return;
677 }
678
679 int min_val = snd_ctl_elem_info_get_min(elem_info);
680 int max_val = snd_ctl_elem_info_get_max(elem_info);
681
682 ret = snd_tlv_get_dB_range(
683 dbrec, min_val, max_val, &min_cdB, &max_cdB
684 );
685 if (ret != 0) {
686 fprintf(stderr, "TLV range error: %s\n", snd_strerror(ret));
687 return;
688 }
689
690 elem->min_val = min_val;
691 elem->max_val = max_val;
692 elem->dB_type = dbrec[SNDRV_CTL_TLVO_TYPE];
693 elem->min_cdB = min_cdB;
694 elem->max_cdB = max_cdB;
695 }
696 }
697
698 static void alsa_get_elem(struct alsa_card *card, int numid) {
699 // allocate a temporary struct alsa_elem (will be copied later if
700 // we want to keep it)
701 struct alsa_elem alsa_elem = {};
702
703 // keep a reference to the card in the element
704 alsa_elem.card = card;
705
706 // get the control's numeric identifier (different to the index
707 // into this array)
708 alsa_elem.numid = numid;
709
710 // get the control's info
711 alsa_elem.type = alsa_get_elem_type(&alsa_elem);
712 alsa_elem.name = alsa_get_elem_name(&alsa_elem);
713 alsa_elem.count = alsa_get_elem_count(&alsa_elem);
714
715 switch (alsa_elem.type) {
716 case SND_CTL_ELEM_TYPE_BOOLEAN:
717 case SND_CTL_ELEM_TYPE_ENUMERATED:
718 case SND_CTL_ELEM_TYPE_INTEGER:
719 case SND_CTL_ELEM_TYPE_BYTES:
720 break;
721 default:
722 return;
723 }
724
725 if (strstr(alsa_elem.name, "Validity"))
726 return;
727 if (strstr(alsa_elem.name, "Channel Map"))
728 return;
729
730 alsa_get_elem_tlv(&alsa_elem);
731
732 // get integer range if not set by TLV
733 if (alsa_elem.type == SND_CTL_ELEM_TYPE_INTEGER &&
734 alsa_elem.min_val >= alsa_elem.max_val)
735 alsa_get_elem_int_range(&alsa_elem);
736
737 // Scarlett 1st Gen driver puts two volume controls/mutes in the
738 // same element, so split them out to match the other series
739 int count = alsa_elem.count;
740
741 if (strcmp(alsa_elem.name, "Level Meter") == 0)
742 count = 1;
743
744 if (count > 2)
745 count = 1;
746
747 for (int i = 0; i < count; i++, alsa_elem.lr_num++) {
748 alsa_elem.index = i;
749
750 // allocate new element and copy data
751 struct alsa_elem *elem = malloc(sizeof(struct alsa_elem));
752 *elem = alsa_elem;
753
754 // Initialise value cache for change detection
755 if (elem->count == 1)
756 elem->value = alsa_get_elem_value(elem);
757 else if (elem->count > 1)
758 elem->values = alsa_get_elem_int_values(elem);
759
760 g_ptr_array_add(card->elems, elem);
761 }
762 }
763
764 // scan the ALSA ctl element list container and put the useful
765 // elements into the cards->elems array of struct alsa_elem
766 static void alsa_get_elem_list(struct alsa_card *card) {
767 snd_ctl_elem_list_t *list;
768 int count;
769
770 // get the list from ALSA
771 snd_ctl_elem_list_malloc(&list);
772 snd_ctl_elem_list(card->handle, list);
773 count = snd_ctl_elem_list_get_count(list);
774 snd_ctl_elem_list_alloc_space(list, count);
775 snd_ctl_elem_list(card->handle, list);
776
777 // for each element in the list
778 for (int i = 0; i < count; i++) {
779 int numid = snd_ctl_elem_list_get_numid(list, i);
780 alsa_get_elem(card, numid);
781 }
782
783 // free the ALSA list
784 snd_ctl_elem_list_free_space(list);
785 snd_ctl_elem_list_free(list);
786 }
787
788 static void alsa_set_elem_lr_num(struct alsa_elem *elem) {
789 const char *name = elem->name;
790 char side;
791
792 if (strncmp(name, "Master Playback", 15) == 0 ||
793 strncmp(name, "Master HW Playback", 18) == 0)
794 elem->lr_num = 0;
795
796 else if (strncmp(name, "Master", 6) == 0)
797 if (sscanf(name, "Master %d%c", &elem->lr_num, &side) != 2)
798 printf("can't parse Master '%s'\n", name);
799 else
800 elem->lr_num = elem->lr_num * 2
801 - (side == 'L' || side == ' ')
802 + elem->index;
803
804 else
805 elem->lr_num = get_num_from_string(name);
806 }
807
808 void alsa_set_lr_nums(struct alsa_card *card) {
809 for (int i = 0; i < card->elems->len; i++) {
810 struct alsa_elem *elem = g_ptr_array_index(card->elems, i);
811
812 alsa_set_elem_lr_num(elem);
813 }
814 }
815
816 static void get_routing_srcs(struct alsa_card *card) {
817 struct alsa_elem *elem = card->sample_capture_elem;
818
819 int count = alsa_get_item_count(elem);
820 card->routing_srcs = g_array_new(
821 FALSE, TRUE, sizeof(struct routing_src)
822 );
823 g_array_set_size(card->routing_srcs, count);
824
825 for (int i = 0; i < count; i++) {
826 char *name = alsa_get_item_name(elem, i);
827
828 struct routing_src *r = &g_array_index(
829 card->routing_srcs, struct routing_src, i
830 );
831 r->card = card;
832 r->id = i;
833 r->level_index = -1;
834
835 if (strcmp(name, "Off") == 0)
836 r->port_category = PC_OFF;
837 else if (strncmp(name, "Mix", 3) == 0)
838 r->port_category = PC_MIX;
839 else if (strncmp(name, "DSP", 3) == 0)
840 r->port_category = PC_DSP;
841 else if (strncmp(name, "PCM", 3) == 0)
842 r->port_category = PC_PCM;
843 else {
844 r->port_category = PC_HW;
845
846 if (strncmp(name, "Analog", 6) == 0)
847 r->hw_type = HW_TYPE_ANALOGUE;
848 else if (strncmp(name, "S/PDIF", 6) == 0)
849 r->hw_type = HW_TYPE_SPDIF;
850 else if (strncmp(name, "SPDIF", 5) == 0)
851 r->hw_type = HW_TYPE_SPDIF;
852 else if (strncmp(name, "ADAT", 4) == 0)
853 r->hw_type = HW_TYPE_ADAT;
854 }
855
856 r->name = name;
857 r->lr_num =
858 r->port_category == PC_MIX
859 ? name[4] - 'A' + 1
860 : get_num_from_string(name);
861
862 r->port_num = card->routing_in_count[r->port_category]++;
863 }
864
865 assert(card->routing_in_count[PC_MIX] <= MAX_MIX_OUT);
866 }
867
868 // return true if the element is an routing sink enum, e.g.:
869 // PCM xx Capture Enum
870 // Mixer Input xx Capture Enum
871 // Analogue Output xx Playback Enum
872 // S/PDIF Output xx Playback Enum
873 // ADAT Output xx Playback Enum
874 //
875 // or new style:
876 // PCM xx Capture Enum
877 // Mixer xx Capture Enum
878 // Analogue xx Playback Enum
879 // S/PDIF xx Playback Enum
880 // ADAT xx Playback Enum
881
882 static int is_elem_routing_snk(struct alsa_elem *elem) {
883 if (strstr(elem->name, "Capture Route") ||
884 strstr(elem->name, "Input Playback Route") ||
885 (strncmp(elem->name, "Master ", 7) == 0 &&
886 strstr(elem->name, "Source Playback Enu")))
887 return 1;
888
889 if (strstr(elem->name, "Capture Enum") && (
890 strncmp(elem->name, "PCM ", 4) == 0 ||
891 strncmp(elem->name, "Mixer ", 6) == 0 ||
892 strncmp(elem->name, "DSP ", 4) == 0
893 ))
894 return 1;
895
896 if (strstr(elem->name, "Playback Enum") && (
897 strncmp(elem->name, "Analogue ", 9) == 0 ||
898 strncmp(elem->name, "S/PDIF ", 7) == 0 ||
899 strncmp(elem->name, "ADAT ", 5) == 0
900 ))
901 return 1;
902
903 return 0;
904 }
905
906 static void get_routing_snks(struct alsa_card *card) {
907 GPtrArray *elems = card->elems;
908
909 int count = 0;
910 struct alsa_elem *first_mix_snk = NULL;
911
912 // count and label routing snks
913 for (int i = 0; i < elems->len; i++) {
914 struct alsa_elem *elem = g_ptr_array_index(elems, i);
915
916 if (!elem->card)
917 continue;
918
919 if (!is_elem_routing_snk(elem))
920 continue;
921
922 elem->is_routing_snk = 1;
923
924 if (strncmp(elem->name, "Mixer", 5) == 0 ||
925 strncmp(elem->name, "Matrix", 6) == 0) {
926 elem->port_category = PC_MIX;
927
928 if (!first_mix_snk)
929 first_mix_snk = elem;
930
931 } else if (strncmp(elem->name, "DSP", 3) == 0) {
932 elem->port_category = PC_DSP;
933 } else if (strncmp(elem->name, "PCM", 3) == 0 ||
934 strncmp(elem->name, "Input Source", 12) == 0) {
935 elem->port_category = PC_PCM;
936 } else if (strstr(elem->name, "Playback Enu")) {
937 elem->port_category = PC_HW;
938
939 if (strncmp(elem->name, "Analog", 6) == 0)
940 elem->hw_type = HW_TYPE_ANALOGUE;
941 else if (strncmp(elem->name, "S/PDIF", 6) == 0 ||
942 strstr(elem->name, "SPDIF"))
943 elem->hw_type = HW_TYPE_SPDIF;
944 else if (strstr(elem->name, "ADAT"))
945 elem->hw_type = HW_TYPE_ADAT;
946 } else {
947 printf("unknown mixer routing elem %s\n", elem->name);
948 continue;
949 }
950
951 if (elem->lr_num <= 0) {
952 fprintf(stderr, "routing sink %s had no number\n", elem->name);
953 continue;
954 }
955
956 count++;
957 }
958
959 // Check mixer input capabilities from first PC_MIX sink
960 if (first_mix_snk) {
961 if (!alsa_get_elem_writable(first_mix_snk))
962 card->has_fixed_mixer_inputs = 1;
963
964 int item_count = alsa_get_item_count(first_mix_snk);
965 for (int i = 0; i < item_count; i++) {
966 char *item_name = alsa_get_item_name(first_mix_snk, i);
967 if (strncmp(item_name, "Mix", 3) == 0) {
968 card->mixer_has_mix_srcs = 1;
969 break;
970 }
971 }
972 }
973
974 // create an array of routing snks pointing to those elements
975 card->routing_snks = g_array_new(
976 FALSE, TRUE, sizeof(struct routing_snk)
977 );
978 g_array_set_size(card->routing_snks, count);
979
980 // count through card->routing_snks
981 int j = 0;
982
983 for (int i = 0; i < elems->len; i++) {
984 struct alsa_elem *elem = g_ptr_array_index(elems, i);
985
986 if (!elem->is_routing_snk)
987 continue;
988
989 struct routing_snk *r = &g_array_index(
990 card->routing_snks, struct routing_snk, j
991 );
992 r->idx = j;
993 r->level_index = -1;
994 j++;
995 r->elem = elem;
996 elem->port_num = card->routing_out_count[elem->port_category]++;
997
998 // Cache monitor group element pointers for HW analogue outputs
999 if (elem->port_category == PC_HW && elem->hw_type == HW_TYPE_ANALOGUE) {
1000 char ctrl_name[64];
1001
1002 snprintf(ctrl_name, sizeof(ctrl_name),
1003 "Main Group Output %d Playback Switch", elem->lr_num);
1004 r->main_group_switch = get_elem_by_name(card->elems, ctrl_name);
1005
1006 snprintf(ctrl_name, sizeof(ctrl_name),
1007 "Alt Group Output %d Playback Switch", elem->lr_num);
1008 r->alt_group_switch = get_elem_by_name(card->elems, ctrl_name);
1009
1010 snprintf(ctrl_name, sizeof(ctrl_name),
1011 "Main Group Output %d Source Playback Enum", elem->lr_num);
1012 r->main_group_source = get_elem_by_name(card->elems, ctrl_name);
1013
1014 snprintf(ctrl_name, sizeof(ctrl_name),
1015 "Alt Group Output %d Source Playback Enum", elem->lr_num);
1016 r->alt_group_source = get_elem_by_name(card->elems, ctrl_name);
1017
1018 snprintf(ctrl_name, sizeof(ctrl_name),
1019 "Main Group Output %d Trim Playback Volume", elem->lr_num);
1020 r->main_group_trim = get_elem_by_name(card->elems, ctrl_name);
1021
1022 snprintf(ctrl_name, sizeof(ctrl_name),
1023 "Alt Group Output %d Trim Playback Volume", elem->lr_num);
1024 r->alt_group_trim = get_elem_by_name(card->elems, ctrl_name);
1025
1026 // Initialize effective_source_idx to normal routing value
1027 r->effective_source_idx = alsa_get_elem_value(elem);
1028 } else {
1029 // Non-HW-analogue sinks just use normal routing
1030 r->effective_source_idx = alsa_get_elem_value(elem);
1031 }
1032
1033 // Cache is_left status
1034 // For fixed mixer inputs, use source's left/right (lr_num can be
1035 // misaligned on devices with odd analogue input count)
1036 if (elem->port_category == PC_MIX && !alsa_get_elem_writable(elem)) {
1037 int src_id = r->effective_source_idx;
1038 if (src_id > 0 && src_id < card->routing_srcs->len) {
1039 struct routing_src *src = &g_array_index(
1040 card->routing_srcs, struct routing_src, src_id
1041 );
1042 r->is_left = (src->lr_num % 2) == 1;
1043 } else {
1044 r->is_left = (elem->lr_num % 2) == 1;
1045 }
1046 } else {
1047 r->is_left = (elem->lr_num % 2) == 1;
1048 }
1049 }
1050
1051 assert(j == count);
1052 assert(card->routing_out_count[PC_MIX] <= MAX_MUX_IN);
1053 }
1054
1055 // Build lookup table mapping monitor group source enum values to routing
1056 // source indices. The monitor group source enums (Main/Alt Group Output X
1057 // Source Playback Enum) have different indices than the main routing
1058 // sources, so we need this mapping.
1059 static void get_monitor_group_src_map(struct alsa_card *card) {
1060 // Find any monitor group source enum to get the item names
1061 struct alsa_elem *vg_elem = get_elem_by_name(
1062 card->elems, "Main Group Output 1 Source Playback Enum"
1063 );
1064 if (!vg_elem) {
1065 card->monitor_group_src_map = NULL;
1066 card->monitor_group_src_map_count = 0;
1067 return;
1068 }
1069
1070 int count = alsa_get_item_count(vg_elem);
1071 card->monitor_group_src_map = g_malloc(count * sizeof(int));
1072 card->monitor_group_src_map_count = count;
1073
1074 // For each monitor group enum item, find matching routing source by name
1075 for (int i = 0; i < count; i++) {
1076 char *vg_name = alsa_get_item_name(vg_elem, i);
1077 card->monitor_group_src_map[i] = 0; // Default to "Off"
1078
1079 for (int j = 0; j < card->routing_srcs->len; j++) {
1080 struct routing_src *r_src = &g_array_index(
1081 card->routing_srcs, struct routing_src, j
1082 );
1083 if (strcmp(vg_name, r_src->name) == 0) {
1084 card->monitor_group_src_map[i] = j;
1085 break;
1086 }
1087 }
1088 }
1089 }
1090
1091 void alsa_get_routing_controls(struct alsa_card *card) {
1092
1093 // check that we can find a routing control
1094 card->sample_capture_elem =
1095 get_elem_by_name(card->elems, "PCM 01 Capture Enum");
1096 if (!card->sample_capture_elem)
1097 card->sample_capture_elem =
1098 get_elem_by_name(card->elems, "PCM 1 Capture Enum");
1099 if (!card->sample_capture_elem)
1100 card->sample_capture_elem =
1101 get_elem_by_name(card->elems, "Input Source 01 Capture Route");
1102
1103 if (!card->sample_capture_elem) {
1104 fprintf(
1105 stderr,
1106 "can't find routing control PCM 01 Capture Enum or "
1107 "Input Source 01 Capture Route\n"
1108 );
1109
1110 return;
1111 }
1112
1113 get_routing_srcs(card);
1114 get_routing_snks(card);
1115 get_monitor_group_src_map(card);
1116
1117 // look up Digital I/O Mode element for HW I/O availability
1118 card->digital_io_mode_elem =
1119 get_elem_by_prefix(card->elems, "Digital I/O Mode");
1120 if (!card->digital_io_mode_elem)
1121 card->digital_io_mode_elem =
1122 get_elem_by_prefix(card->elems, "S/PDIF Mode");
1123 if (!card->digital_io_mode_elem) {
1124 card->digital_io_mode_elem =
1125 get_elem_by_prefix(card->elems, "S/PDIF Source");
1126 card->digital_io_mode_live = 1;
1127 }
1128
1129 // cache the mode value at init time
1130 if (card->digital_io_mode_elem)
1131 card->digital_io_mode = alsa_get_elem_value(card->digital_io_mode_elem);
1132
1133 // initialize HW I/O limits (sample rate unknown at this point, so
1134 // limits will be set to -1 meaning all available)
1135 update_hw_io_limits(card);
1136 }
1137
1138 void alsa_elem_change(struct alsa_elem *elem) {
1139 if (!elem || !elem->callbacks)
1140 return;
1141
1142 for (GList *l = elem->callbacks; l; l = l->next) {
1143 struct alsa_elem_callback *cb = (struct alsa_elem_callback *)l->data;
1144
1145 if (!cb || !cb->callback)
1146 continue;
1147
1148 cb->callback(elem, cb->data);
1149 }
1150 }
1151
1152 static void card_destroy_callback(void *data) {
1153 struct alsa_card *card = data;
1154
1155 // cancel the levels timer first to prevent it firing with freed data
1156 if (card->levels_timer) {
1157 g_source_remove(card->levels_timer);
1158 card->levels_timer = 0;
1159 }
1160
1161 // close the windows associated with this card
1162 destroy_card_window(card);
1163
1164 // free all elements and their callbacks
1165 if (card->elems) {
1166 for (int i = 0; i < card->elems->len; i++) {
1167 struct alsa_elem *elem = g_ptr_array_index(card->elems, i);
1168
1169 // free callback list
1170 for (GList *l = elem->callbacks; l; l = l->next) {
1171 struct alsa_elem_callback *cb = l->data;
1172
1173 // call cleanup function if provided
1174 if (cb->destroy && cb->data)
1175 cb->destroy(cb->data);
1176
1177 free(cb);
1178 }
1179 g_list_free(elem->callbacks);
1180
1181 // cancel pending idle callback
1182 if (elem->pending_idle)
1183 g_source_remove(elem->pending_idle);
1184
1185 // free element data
1186 if (elem->name)
1187 free(elem->name);
1188 if (elem->values)
1189 free(elem->values);
1190 if (elem->bytes_value)
1191 free(elem->bytes_value);
1192 if (elem->meter_labels) {
1193 for (int j = 0; j < elem->count; j++)
1194 free(elem->meter_labels[j]);
1195 free(elem->meter_labels);
1196 }
1197 if (elem->item_names) {
1198 for (int j = 0; j < elem->item_count; j++)
1199 free(elem->item_names[j]);
1200 free(elem->item_names);
1201 }
1202
1203 // free the element struct itself
1204 free(elem);
1205 }
1206 g_ptr_array_free(card->elems, TRUE);
1207 }
1208
1209 // free routing arrays
1210 if (card->routing_srcs) {
1211 for (int i = 0; i < card->routing_srcs->len; i++) {
1212 struct routing_src *src = &g_array_index(
1213 card->routing_srcs, struct routing_src, i
1214 );
1215 g_free(src->display_name);
1216 }
1217 g_array_free(card->routing_srcs, TRUE);
1218 }
1219 if (card->routing_snks) {
1220 for (int i = 0; i < card->routing_snks->len; i++) {
1221 struct routing_snk *snk = &g_array_index(
1222 card->routing_snks, struct routing_snk, i
1223 );
1224 g_free(snk->display_name);
1225 }
1226 g_array_free(card->routing_snks, TRUE);
1227 }
1228 g_free(card->monitor_group_src_map);
1229
1230 // close ALSA handle
1231 if (card->handle)
1232 snd_ctl_close(card->handle);
1233
1234 // unref IO channel
1235 if (card->io_channel)
1236 g_io_channel_unref(card->io_channel);
1237
1238 free(card->device);
1239 free(card->serial);
1240 free(card->name);
1241 free(card->fcp_socket);
1242 free(card);
1243
1244 // go through the alsa_cards array and clear the entry for this card
1245 for (int i = 0; i < alsa_cards->len; i++) {
1246 struct alsa_card **card_ptr =
1247 &g_array_index(alsa_cards, struct alsa_card *, i);
1248 if (*card_ptr == card)
1249 *card_ptr = NULL;
1250 }
1251 }
1252
1253 void alsa_init_mixer_gains_cache(struct alsa_card *card) {
1254 GPtrArray *elems = card->elems;
1255
1256 for (int i = 0; i < elems->len; i++) {
1257 struct alsa_elem *elem = g_ptr_array_index(elems, i);
1258
1259 if (!elem->card)
1260 continue;
1261
1262 if (!strstr(elem->name, "Playback Volume"))
1263 continue;
1264
1265 // Gen 2+: "Mix X Input Y", Gen 1: "Matrix Y Mix X"
1266 if (strncmp(elem->name, "Mix ", 4) &&
1267 strncmp(elem->name, "Matrix ", 7))
1268 continue;
1269
1270 char *mix_str = strstr(elem->name, "Mix ");
1271 if (!mix_str || !mix_str[4])
1272 continue;
1273
1274 int mix_num = mix_str[4] - 'A';
1275 int input_num = get_num_from_string(elem->name) - 1;
1276
1277 if (mix_num < 0 || mix_num >= MAX_MIX_OUT)
1278 continue;
1279 if (input_num < 0 || input_num >= MAX_MUX_IN)
1280 continue;
1281
1282 card->mixer_gains[mix_num][input_num] = elem;
1283 }
1284 }
1285
1286 // Complete card initialisation after the driver is ready
1287 static void complete_card_init(struct alsa_card *card) {
1288
1289 // Get full element list and create main window
1290 alsa_get_elem_list(card);
1291 alsa_set_lr_nums(card);
1292 alsa_get_routing_controls(card);
1293 alsa_init_mixer_gains_cache(card);
1294 optional_controls_init(card);
1295 custom_names_init(card);
1296 port_enable_init(card);
1297 stereo_link_init(card);
1298 dsp_state_init(card);
1299 card->best_firmware_version = scarlett2_get_best_firmware_version(card->pid);
1300
1301 // For FCP/scarlett4 devices, get the 4-valued best firmware version
1302 // and read the current device firmware versions
1303 if (card->driver_type == DRIVER_TYPE_SOCKET) {
1304 card->best_firmware_version_4 = scarlett4_get_best_firmware_version(card->pid);
1305
1306 // Read current device firmware version
1307 struct alsa_elem *fw_elem = get_elem_by_name(card->elems, "Firmware Version");
1308 if (fw_elem && fw_elem->count == 4) {
1309 long *values = alsa_get_elem_int_values(fw_elem);
1310 if (values) {
1311 for (int i = 0; i < 4; i++)
1312 card->firmware_version_4[i] = values[i];
1313 g_free(values);
1314 }
1315 }
1316
1317 // Read current device ESP firmware version
1318 struct alsa_elem *esp_elem = get_elem_by_name(card->elems, "ESP Firmware Version");
1319 if (esp_elem && esp_elem->count == 4) {
1320 long *values = alsa_get_elem_int_values(esp_elem);
1321 if (values) {
1322 for (int i = 0; i < 4; i++)
1323 card->esp_firmware_version[i] = values[i];
1324 g_free(values);
1325 }
1326 }
1327 }
1328
1329 if (card->serial) {
1330 // Call the reopen callbacks for this card
1331 struct reopen_callback *rc = g_hash_table_lookup(
1332 reopen_callbacks, card->serial
1333 );
1334 if (rc)
1335 rc->callback(rc->data);
1336
1337 g_hash_table_remove(reopen_callbacks, card->serial);
1338 }
1339
1340 // Save initial configuration on first-ever load
1341 save_initial_config(card);
1342
1343 create_card_window(card);
1344 }
1345
1346 // Check if the Firmware Version control has a TLV and is locked,
1347 // indicating the driver is ready
1348 static int check_driver_ready(snd_ctl_elem_info_t *info) {
1349 return snd_ctl_elem_info_is_tlv_readable(info) &&
1350 snd_ctl_elem_info_is_locked(info);
1351 }
1352
1353 // Check if the FCP driver is initialised
1354 static void check_driver_init(
1355 struct alsa_card *card, int numid, unsigned int mask
1356 ) {
1357
1358 // Ignore controls going away
1359 if (mask == SND_CTL_EVENT_MASK_REMOVE)
1360 return;
1361
1362 // Get the control's info
1363 snd_ctl_elem_id_t *id;
1364 snd_ctl_elem_info_t *info;
1365
1366 snd_ctl_elem_id_alloca(&id);
1367 snd_ctl_elem_info_alloca(&info);
1368
1369 snd_ctl_elem_id_set_numid(id, numid);
1370 snd_ctl_elem_info_set_id(info, id);
1371
1372 if (snd_ctl_elem_info(card->handle, info) < 0) {
1373 fprintf(stderr, "error getting elem info %d\n", numid);
1374 return;
1375 }
1376
1377 const char *name = snd_ctl_elem_info_get_name(info);
1378
1379 // Check if it's the Firmware Version control being updated
1380 if (strcmp(name, "Firmware Version"))
1381 return;
1382
1383 // Check if the driver is ready
1384 if (!check_driver_ready(info))
1385 return;
1386
1387 // The driver is initialised; update the card's driver type
1388 card->driver_type = DRIVER_TYPE_SOCKET;
1389
1390 // Complete the card initialisation
1391 complete_card_init(card);
1392 }
1393
1394 static gboolean alsa_card_callback(
1395 GIOChannel *source,
1396 GIOCondition condition,
1397 void *data
1398 ) {
1399 struct alsa_card *card = data;
1400 snd_ctl_event_t *event;
1401
1402 snd_ctl_event_alloca(&event);
1403 if (!card->handle) {
1404 printf("oops, no card handle??\n");
1405 return 0;
1406 }
1407 int err = snd_ctl_read(card->handle, event);
1408 if (err == 0) {
1409 printf("alsa_card_callback nothing to read??\n");
1410 return 0;
1411 }
1412 if (err < 0) {
1413 if (err == -ENODEV)
1414 return 0;
1415 printf("card_callback_error %d\n", err);
1416 exit(1);
1417 }
1418
1419 if (snd_ctl_event_get_type(event) != SND_CTL_EVENT_ELEM)
1420 return 1;
1421
1422 int numid = snd_ctl_event_elem_get_numid(event);
1423 unsigned int mask = snd_ctl_event_elem_get_mask(event);
1424
1425 // Check if we're waiting for FCP driver to initialise and check if
1426 // it's now ready
1427 if (card->driver_type == DRIVER_TYPE_SOCKET_UNINIT) {
1428 check_driver_init(card, numid, mask);
1429 return 1;
1430 }
1431
1432 if (mask == SND_CTL_EVENT_MASK_REMOVE) {
1433 card_destroy_callback(card);
1434 return 0;
1435 }
1436
1437 if (!(mask & (SND_CTL_EVENT_MASK_VALUE | SND_CTL_EVENT_MASK_INFO)))
1438 return 1;
1439
1440 for (int i = 0; i < card->elems->len; i++) {
1441 struct alsa_elem *elem = g_ptr_array_index(card->elems, i);
1442
1443 if (elem->numid == numid) {
1444 // Update cached value
1445 int value_changed = 0;
1446
1447 if (elem->count == 1) {
1448 long new_value = alsa_get_elem_value(elem);
1449 value_changed = new_value != elem->value;
1450 elem->value = new_value;
1451 } else if (elem->count > 1) {
1452 long *new_values = alsa_get_elem_int_values(elem);
1453 value_changed = !elem->values ||
1454 memcmp(new_values, elem->values, elem->count * sizeof(long)) != 0;
1455 free(elem->values);
1456 elem->values = new_values;
1457 }
1458
1459 // Info events (writable/range changes) always need a
1460 // callback; value-only events only when the value changed.
1461 if (value_changed || (mask & SND_CTL_EVENT_MASK_INFO))
1462 alsa_elem_change(elem);
1463 }
1464 }
1465
1466 return 1;
1467 }
1468
1469 // go through the alsa_cards array and look for an entry with the
1470 // matching card_num
1471 static struct alsa_card *find_card_by_card_num(int card_num) {
1472 for (int i = 0; i < alsa_cards->len; i++) {
1473 struct alsa_card **card_ptr =
1474 &g_array_index(alsa_cards, struct alsa_card *, i);
1475 if (!*card_ptr)
1476 continue;
1477 if ((*card_ptr)->num == card_num)
1478 return *card_ptr;
1479 }
1480
1481 return NULL;
1482 }
1483
1484 // create a new entry in the alsa_cards array (either an unused entry
1485 // or add a new entry to the end)
1486 struct alsa_card *card_create(int card_num) {
1487 int i, found = 0;
1488 struct alsa_card **card_ptr;
1489
1490 // look for an unused entry
1491 for (i = 0; i < alsa_cards->len; i++) {
1492 card_ptr = &g_array_index(alsa_cards, struct alsa_card *, i);
1493 if (!*card_ptr) {
1494 found = 1;
1495 break;
1496 }
1497 }
1498
1499 // no unused entry? extend the array
1500 if (!found) {
1501 g_array_set_size(alsa_cards, i + 1);
1502 card_ptr = &g_array_index(alsa_cards, struct alsa_card *, i);
1503 }
1504
1505 *card_ptr = calloc(1, sizeof(struct alsa_card));
1506 struct alsa_card *card = *card_ptr;
1507 card->num = card_num;
1508 card->elems = g_ptr_array_new();
1509
1510 return card;
1511 }
1512
1513 static void alsa_add_card_callback(struct alsa_card *card) {
1514 card->io_channel = g_io_channel_unix_new(card->pfd.fd);
1515 card->event_source_id = g_io_add_watch_full(
1516 card->io_channel, 0,
1517 G_IO_IN | G_IO_ERR | G_IO_HUP,
1518 alsa_card_callback, card, card_destroy_callback
1519 );
1520 }
1521
1522 static void alsa_subscribe(struct alsa_card *card) {
1523 int count = snd_ctl_poll_descriptors_count(card->handle);
1524
1525 if (count != 1) {
1526 printf("poll descriptors %d != 1", count);
1527 exit(1);
1528 }
1529 snd_ctl_subscribe_events(card->handle, 1);
1530 snd_ctl_poll_descriptors(card->handle, &card->pfd, 1);
1531 }
1532
1533 static void alsa_get_usbid(struct alsa_card *card) {
1534 char path[256];
1535 snprintf(path, 256, "/proc/asound/card%d/usbid", card->num);
1536
1537 FILE *f = fopen(path, "r");
1538 if (!f) {
1539 fprintf(stderr, "can't open %s: %s\n", path, strerror(errno));
1540 return;
1541 }
1542
1543 int vid, pid;
1544 int result = fscanf(f, "%04x:%04x", &vid, &pid);
1545 fclose(f);
1546
1547 if (result != 2) {
1548 fprintf(stderr, "can't read %s\n", path);
1549 return;
1550 }
1551
1552 if (vid != 0x1235) {
1553 fprintf(stderr, "VID %04x != expected 0x1235 for Focusrite\n", vid);
1554 return;
1555 }
1556
1557 card->pid = pid;
1558 }
1559
1560 // Read the USB serial number via sysfs.
1561 // controlC<N>/device points to the ALSA sound card, whose own
1562 // device symlink points to the USB interface; the parent of
1563 // that is the USB device which has the serial file.
1564 static void alsa_get_serial_number(struct alsa_card *card) {
1565 char path[128];
1566 snprintf(
1567 path, sizeof(path),
1568 "/sys/class/sound/controlC%d/device/device/../serial",
1569 card->num
1570 );
1571
1572 FILE *f = fopen(path, "r");
1573 if (!f) {
1574 fprintf(
1575 stderr, "can't open %s: %s\n", path, strerror(errno)
1576 );
1577 return;
1578 }
1579
1580 char serial[40];
1581 int result = fscanf(f, "%39s", serial);
1582 fclose(f);
1583
1584 if (result != 1) {
1585 fprintf(stderr, "can't read %s\n", path);
1586 return;
1587 }
1588
1589 card->serial = strdup(serial);
1590 }
1591
1592 // return true if the Firmware Version control exists and is writable
1593 // and locked (i.e. the FCP server is running)
1594 static int check_firmware_version_locked(struct alsa_card *card) {
1595 snd_ctl_elem_id_t *id;
1596 snd_ctl_elem_info_t *info;
1597
1598 snd_ctl_elem_id_alloca(&id);
1599 snd_ctl_elem_info_alloca(&info);
1600
1601 // look for the Firmware Version control
1602 snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_CARD);
1603 snd_ctl_elem_id_set_name(id, "Firmware Version");
1604 snd_ctl_elem_info_set_id(info, id);
1605
1606 // no Firmware Version control found
1607 int err = snd_ctl_elem_info(card->handle, info);
1608 if (err < 0)
1609 return 0;
1610
1611 return check_driver_ready(info);
1612 }
1613
1614 // return the driver type for this card
1615 // DRIVER_TYPE_NONE: no driver
1616 // DRIVER_TYPE_HWDEP: Scarlett2 driver
1617 // DRIVER_TYPE_SOCKET: FCP driver
1618 // DRIVER_TYPE_SOCKET_UNINIT: FCP driver, but not initialised
1619 static int get_driver_type(struct alsa_card *card) {
1620 snd_hwdep_t *hwdep;
1621
1622 int err = scarlett2_open_card(card->device, &hwdep);
1623
1624 // no hwdep for this card - driver type none
1625 if (err == -ENOENT)
1626 return DRIVER_TYPE_NONE;
1627
1628 // if we get EPERM, it's FCP but no server running
1629 if (err == -EPERM)
1630 return DRIVER_TYPE_SOCKET_UNINIT;
1631
1632 // if we get EBUSY, it's FCP
1633 if (err == -EBUSY)
1634 // fcp-server locks the Firmware Version control when it has
1635 // finished starting up
1636 return check_firmware_version_locked(card) ?
1637 DRIVER_TYPE_SOCKET : DRIVER_TYPE_SOCKET_UNINIT;
1638
1639 // failed to open hwdep
1640 if (err < 0)
1641 return DRIVER_TYPE_NONE;
1642
1643 // we can open hwdep, so now check the protocol version
1644 int ver = scarlett2_get_protocol_version(hwdep);
1645 scarlett2_close(hwdep);
1646
1647 // failed to get protocol version
1648 if (ver < 0)
1649 return DRIVER_TYPE_NONE;
1650
1651 // hwdep protocol version 1.x.x is Scarlett2 driver
1652 if (SCARLETT2_HWDEP_VERSION_MAJOR(ver) == MAJOR_HWDEP_VERSION_SCARLETT2)
1653 return DRIVER_TYPE_HWDEP;
1654
1655 // hwdep protocol version 2.x.x is FCP driver (but not initialised,
1656 // because we were able to open the hwdep)
1657 if (SCARLETT2_HWDEP_VERSION_MAJOR(ver) == MAJOR_HWDEP_VERSION_FCP)
1658 return DRIVER_TYPE_SOCKET_UNINIT;
1659
1660 return DRIVER_TYPE_NONE;
1661 }
1662
1663 static void card_init(struct alsa_card *card) {
1664 alsa_get_usbid(card);
1665 alsa_get_serial_number(card);
1666 alsa_subscribe(card);
1667 alsa_add_card_callback(card);
1668
1669 card->driver_type = get_driver_type(card);
1670
1671 // Driver not ready? Create the iface-waiting window
1672 if (card->driver_type == DRIVER_TYPE_SOCKET_UNINIT) {
1673 create_card_window(card);
1674 return;
1675 }
1676
1677 complete_card_init(card);
1678 }
1679
1680 static void alsa_scan_cards(void) {
1681 snd_ctl_card_info_t *info;
1682 snd_ctl_t *ctl;
1683 int card_num = -1;
1684 char device[32];
1685 struct alsa_card *card;
1686
1687 snd_ctl_card_info_alloca(&info);
1688 while (1) {
1689 int err = snd_card_next(&card_num);
1690 if (err < 0)
1691 fatal_alsa_error("snd_card_next", err);
1692 if (card_num < 0)
1693 break;
1694
1695 snprintf(device, 32, "hw:%d", card_num);
1696
1697 err = snd_ctl_open(&ctl, device, 0);
1698 if (err < 0)
1699 goto next;
1700 err = snd_ctl_card_info(ctl, info);
1701 if (err < 0)
1702 goto next;
1703
1704 if (strncmp(snd_ctl_card_info_get_name(info), "Scarlett", 8) != 0 &&
1705 strncmp(snd_ctl_card_info_get_name(info), "Clarett", 7) != 0 &&
1706 strncmp(snd_ctl_card_info_get_name(info), "Vocaster", 8) != 0)
1707 goto next;
1708
1709 // is there already an entry for this card in alsa_cards?
1710 card = find_card_by_card_num(card_num);
1711
1712 // yes: skip
1713 if (card)
1714 goto next;
1715
1716 // no: create
1717 card = card_create(card_num);
1718
1719 card->device = strdup(device);
1720 card->name = strdup(snd_ctl_card_info_get_name(info));
1721 card->handle = ctl;
1722
1723 card_init(card);
1724
1725 continue;
1726
1727 next:
1728 snd_ctl_close(ctl);
1729 }
1730 }
1731
1732 // inotify
1733
1734 static gboolean inotify_callback(
1735 GIOChannel *source,
1736 GIOCondition condition,
1737 void *data
1738 ) {
1739 char buf[4096] __attribute__ ((aligned(__alignof__(struct inotify_event))));
1740 const struct inotify_event *event;
1741 int len;
1742
1743 len = read(inotify_fd, &buf, sizeof(buf));
1744 if (len < 0) {
1745 perror("inotify read");
1746 exit(1);
1747 }
1748
1749 for (
1750 event = (struct inotify_event *)buf;
1751 (char *)event < buf + len;
1752 event = (struct inotify_event *)
1753 ((char *)event + sizeof(*event) + event->len)
1754 ) {
1755 if (event->mask & IN_CREATE &&
1756 len &&
1757 strncmp(event->name, "control", 7) == 0) {
1758
1759 // can't rescan for new cards too fast
1760 sleep(1);
1761 alsa_scan_cards();
1762 }
1763 }
1764
1765 return TRUE;
1766 }
1767
1768 static void alsa_inotify_init(void) {
1769 GIOChannel *io_channel;
1770
1771 inotify_fd = inotify_init();
1772 inotify_wd = inotify_add_watch(inotify_fd, "/dev/snd", IN_CREATE);
1773 io_channel = g_io_channel_unix_new(inotify_fd);
1774 g_io_add_watch_full(
1775 io_channel, 0,
1776 G_IO_IN | G_IO_ERR | G_IO_HUP,
1777 inotify_callback, NULL, NULL
1778 );
1779 }
1780
1781 void alsa_init(void) {
1782 alsa_cards = g_array_new(FALSE, TRUE, sizeof(struct alsa_card *));
1783 reopen_callbacks = g_hash_table_new_full(
1784 g_str_hash, g_str_equal, g_free, g_free
1785 );
1786 alsa_inotify_init();
1787 alsa_scan_cards();
1788 }
1789
1790 void alsa_register_reopen_callback(
1791 const char *serial,
1792 ReOpenCallback *callback,
1793 void *data
1794 ) {
1795 struct reopen_callback *rc = g_new0(struct reopen_callback, 1);
1796 rc->callback = callback;
1797 rc->data = data;
1798
1799 g_hash_table_insert(reopen_callbacks, g_strdup(serial), rc);
1800 }
1801
1802 void alsa_unregister_reopen_callback(const char *serial) {
1803 g_hash_table_remove(reopen_callbacks, serial);
1804 }
1805
1806 int alsa_has_reopen_callbacks(void) {
1807 return g_hash_table_size(reopen_callbacks);
1808 }