1 /* tinymix.c
2 **
3 ** Copyright 2011, The Android Open Source Project
4 **
5 ** Redistribution and use in source and binary forms, with or without
6 ** modification, are permitted provided that the following conditions are met:
7 **     * Redistributions of source code must retain the above copyright
8 **       notice, this list of conditions and the following disclaimer.
9 **     * Redistributions in binary form must reproduce the above copyright
10 **       notice, this list of conditions and the following disclaimer in the
11 **       documentation and/or other materials provided with the distribution.
12 **     * Neither the name of The Android Open Source Project nor the names of
13 **       its contributors may be used to endorse or promote products derived
14 **       from this software without specific prior written permission.
15 **
16 ** THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND
17 ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 ** ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE
20 ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 ** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 ** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 ** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
26 ** DAMAGE.
27 */
28 
29 #include <tinyalsa/asoundlib.h>
30 #include <errno.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <ctype.h>
34 #include <string.h>
35 #include <limits.h>
36 
37 #define OPTPARSE_IMPLEMENTATION
38 #include "optparse.h"
39 
40 static void list_controls(struct mixer *mixer, int print_all);
41 
42 static void print_control_values(struct mixer_ctl *control);
43 static void print_control_values_by_name_or_id(struct mixer *mixer, const char *name_or_id);
44 
45 static int set_values(struct mixer *mixer, const char *control,
46                              char **values, unsigned int num_values);
47 
48 static void print_enum(struct mixer_ctl *ctl);
49 
usage(void)50 void usage(void)
51 {
52     printf("usage: tinymix [options] <command>\n");
53     printf("options:\n");
54     printf("\t-h, --help               : prints this help message and exits\n");
55     printf("\t-v, --version            : prints this version of tinymix and exits\n");
56     printf("\t-D, --card NUMBER        : specifies the card number of the mixer\n");
57     printf("\n");
58     printf("commands:\n");
59     printf("\tget NAME|ID              : prints the values of a control\n");
60     printf("\tset NAME|ID VALUE(S) ... : sets the value of a control\n");
61     printf("\t\tVALUE(S): integers, percents, and relative values\n");
62     printf("\t\t\tIntegers: 0, 100, -100 ...\n");
63     printf("\t\t\tPercents: 0%%, 100%% ...\n");
64     printf("\t\t\tRelative values: 1+, 1-, 1%%+, 2%%+ ...\n");
65     printf("\tcontrols                 : lists controls of the mixer\n");
66     printf("\tcontents                 : lists controls of the mixer and their contents\n");
67 }
68 
version(void)69 void version(void)
70 {
71     printf("tinymix version 2.0 (tinyalsa version %s)\n", TINYALSA_VERSION_STRING);
72 }
73 
is_command(char * arg)74 static int is_command(char *arg) {
75     return strcmp(arg, "get") == 0 || strcmp(arg, "set") == 0 ||
76             strcmp(arg, "controls") == 0 || strcmp(arg, "contents") == 0;
77 }
78 
find_command_position(int argc,char ** argv)79 static int find_command_position(int argc, char **argv)
80 {
81     for (int i = 0; i < argc; ++i) {
82         if (is_command(argv[i])) {
83             return i;
84         }
85     }
86     return -1;
87 }
88 
main(int argc,char ** argv)89 int main(int argc, char **argv)
90 {
91     int card = 0;
92     struct optparse opts;
93     static struct optparse_long long_options[] = {
94         { "card",    'D', OPTPARSE_REQUIRED },
95         { "version", 'v', OPTPARSE_NONE     },
96         { "help",    'h', OPTPARSE_NONE     },
97         { 0, 0, 0 }
98     };
99 
100     // optparse_long may change the order of the argv list. Duplicate one for parsing the options.
101     char **argv_options_list = (char **) calloc(argc + 1, sizeof(char *));
102     if (!argv_options_list) {
103         fprintf(stderr, "Failed to allocate options list\n");
104         return EXIT_FAILURE;
105     }
106 
107     for (int i = 0; i < argc; ++i) {
108         argv_options_list[i] = argv[i];
109     }
110 
111     optparse_init(&opts, argv_options_list);
112     /* Detect the end of the options. */
113     int c;
114     while ((c = optparse_long(&opts, long_options, NULL)) != -1) {
115         switch (c) {
116         case 'D':
117             card = atoi(opts.optarg);
118             break;
119         case 'h':
120             usage();
121             free(argv_options_list);
122             return EXIT_SUCCESS;
123         case 'v':
124             version();
125             free(argv_options_list);
126             return EXIT_SUCCESS;
127         case '?':
128         default:
129             break;
130         }
131     }
132     free(argv_options_list);
133 
134     struct mixer *mixer = mixer_open(card);
135     if (!mixer) {
136         fprintf(stderr, "Failed to open mixer\n");
137         return EXIT_FAILURE;
138     }
139 
140     int command_position = find_command_position(argc, argv);
141     if (command_position < 0) {
142         usage();
143         mixer_close(mixer);
144         return EXIT_FAILURE;
145     }
146 
147     char *cmd = argv[command_position];
148     if (strcmp(cmd, "get") == 0) {
149         if (command_position + 1 >= argc) {
150             fprintf(stderr, "no control specified\n");
151             mixer_close(mixer);
152             return EXIT_FAILURE;
153         }
154         print_control_values_by_name_or_id(mixer, argv[command_position + 1]);
155         printf("\n");
156     } else if (strcmp(cmd, "set") == 0) {
157         if (command_position + 1 >= argc) {
158             fprintf(stderr, "no control specified\n");
159             mixer_close(mixer);
160             return EXIT_FAILURE;
161         }
162         if (command_position + 2 >= argc) {
163             fprintf(stderr, "no value(s) specified\n");
164             mixer_close(mixer);
165             return EXIT_FAILURE;
166         }
167         int res = set_values(mixer,
168                              argv[command_position + 1],
169                              &argv[command_position + 2],
170                              argc - command_position - 2);
171         if (res != 0) {
172             mixer_close(mixer);
173             return EXIT_FAILURE;
174         }
175     } else if (strcmp(cmd, "controls") == 0) {
176         list_controls(mixer, 0);
177     } else if (strcmp(cmd, "contents") == 0) {
178         list_controls(mixer, 1);
179     } else {
180         fprintf(stderr, "unknown command '%s'\n", cmd);
181         usage();
182         mixer_close(mixer);
183         return EXIT_FAILURE;
184     }
185 
186     mixer_close(mixer);
187     return EXIT_SUCCESS;
188 }
189 
isnumber(const char * str)190 static int isnumber(const char *str) {
191     char *end;
192 
193     if (str == NULL || strlen(str) == 0)
194         return 0;
195 
196     strtol(str, &end, 0);
197     return strlen(end) == 0;
198 }
199 
list_controls(struct mixer * mixer,int print_all)200 static void list_controls(struct mixer *mixer, int print_all)
201 {
202     struct mixer_ctl *ctl;
203     const char *name, *type;
204     unsigned int num_ctls, num_values;
205     unsigned int i;
206 
207     num_ctls = mixer_get_num_ctls(mixer);
208 
209     printf("Number of controls: %u\n", num_ctls);
210 
211     if (print_all)
212         printf("ctl\ttype\tnum\t%-40svalue\n", "name");
213     else
214         printf("ctl\ttype\tnum\t%-40s\n", "name");
215 
216     for (i = 0; i < num_ctls; i++) {
217         ctl = mixer_get_ctl(mixer, i);
218 
219         name = mixer_ctl_get_name(ctl);
220         type = mixer_ctl_get_type_string(ctl);
221         num_values = mixer_ctl_get_num_values(ctl);
222         printf("%u\t%s\t%u\t%-40s", i, type, num_values, name);
223         if (print_all)
224             print_control_values(ctl);
225         printf("\n");
226     }
227 }
228 
print_enum(struct mixer_ctl * ctl)229 static void print_enum(struct mixer_ctl *ctl)
230 {
231     unsigned int num_enums;
232     unsigned int i;
233     unsigned int value;
234     const char *string;
235 
236     num_enums = mixer_ctl_get_num_enums(ctl);
237     value = mixer_ctl_get_value(ctl, 0);
238 
239     for (i = 0; i < num_enums; i++) {
240         string = mixer_ctl_get_enum_string(ctl, i);
241         printf("%s%s, ", value == i ? "> " : "", string);
242     }
243 }
244 
print_control_values_by_name_or_id(struct mixer * mixer,const char * name_or_id)245 static void print_control_values_by_name_or_id(struct mixer *mixer, const char *name_or_id)
246 {
247     struct mixer_ctl *ctl;
248 
249     if (isnumber(name_or_id))
250         ctl = mixer_get_ctl(mixer, atoi(name_or_id));
251     else
252         ctl = mixer_get_ctl_by_name(mixer, name_or_id);
253 
254     if (!ctl) {
255         fprintf(stderr, "Invalid mixer control\n");
256         return;
257     }
258 
259     print_control_values(ctl);
260 }
261 
print_control_values(struct mixer_ctl * control)262 static void print_control_values(struct mixer_ctl *control)
263 {
264     enum mixer_ctl_type type;
265     unsigned int num_values;
266     unsigned int i;
267     int min, max;
268     int ret;
269     char *buf = NULL;
270 
271     type = mixer_ctl_get_type(control);
272     num_values = mixer_ctl_get_num_values(control);
273 
274     if ((type == MIXER_CTL_TYPE_BYTE) && (num_values > 0)) {
275         buf = calloc(1, num_values);
276         if (buf == NULL) {
277             fprintf(stderr, "Failed to alloc mem for bytes %u\n", num_values);
278             return;
279         }
280 
281         ret = mixer_ctl_get_array(control, buf, num_values);
282         if (ret < 0) {
283             fprintf(stderr, "Failed to mixer_ctl_get_array\n");
284             free(buf);
285             return;
286         }
287     }
288 
289     for (i = 0; i < num_values; i++) {
290         switch (type)
291         {
292         case MIXER_CTL_TYPE_INT:
293             printf("%d", mixer_ctl_get_value(control, i));
294             break;
295         case MIXER_CTL_TYPE_BOOL:
296             printf("%s", mixer_ctl_get_value(control, i) ? "On" : "Off");
297             break;
298         case MIXER_CTL_TYPE_ENUM:
299             print_enum(control);
300             break;
301         case MIXER_CTL_TYPE_BYTE:
302             printf("%02hhx", buf[i]);
303             break;
304         default:
305             printf("unknown");
306             break;
307         };
308         if ((i + 1) < num_values) {
309            printf(", ");
310         }
311     }
312 
313     if (type == MIXER_CTL_TYPE_INT) {
314         min = mixer_ctl_get_range_min(control);
315         max = mixer_ctl_get_range_max(control);
316         printf(" (range %d->%d)", min, max);
317     }
318 
319     free(buf);
320 }
321 
tinymix_set_byte_ctl(struct mixer_ctl * ctl,char ** values,unsigned int num_values)322 static void tinymix_set_byte_ctl(struct mixer_ctl *ctl,
323                                  char **values, unsigned int num_values)
324 {
325     int ret;
326     char *buf;
327     char *end;
328     unsigned int i;
329     long n;
330 
331     buf = calloc(1, num_values);
332     if (buf == NULL) {
333         fprintf(stderr, "set_byte_ctl: Failed to alloc mem for bytes %u\n", num_values);
334         exit(EXIT_FAILURE);
335     }
336 
337     for (i = 0; i < num_values; i++) {
338         errno = 0;
339         n = strtol(values[i], &end, 0);
340         if (*end) {
341             fprintf(stderr, "%s not an integer\n", values[i]);
342             goto fail;
343         }
344         if (errno) {
345             fprintf(stderr, "strtol: %s: %s\n", values[i],
346                 strerror(errno));
347             goto fail;
348         }
349         if (n < 0 || n > 0xff) {
350             fprintf(stderr, "%s should be between [0, 0xff]\n",
351                 values[i]);
352             goto fail;
353         }
354         buf[i] = n;
355     }
356 
357     ret = mixer_ctl_set_array(ctl, buf, num_values);
358     if (ret < 0) {
359         fprintf(stderr, "Failed to set binary control\n");
360         goto fail;
361     }
362 
363     free(buf);
364     return;
365 
366 fail:
367     free(buf);
368     exit(EXIT_FAILURE);
369 }
370 
is_int(const char * value)371 static int is_int(const char *value)
372 {
373     return value[0] >= '0' && value[0] <= '9';
374 }
375 
376 struct parsed_int
377 {
378     /** Wether or not the integer was valid. */
379     int valid;
380     /** The value of the parsed integer. */
381     int value;
382     /** The number of characters that were parsed. */
383     unsigned int length;
384     /** The number of characters remaining in the string. */
385     unsigned int remaining_length;
386     /** The remaining characters (or suffix) of the integer. */
387     const char* remaining;
388 };
389 
parse_int(const char * str)390 static struct parsed_int parse_int(const char* str)
391 {
392     struct parsed_int out = {
393         0 /* valid */,
394         0 /* value */,
395         0 /* length */,
396         0 /* remaining length */,
397         NULL /* remaining characters */
398     };
399 
400     size_t length = strlen(str);
401     size_t i = 0;
402     int negative = 0;
403 
404     if (i < length && str[i] == '-') {
405         negative = 1;
406         i++;
407     }
408 
409     while (i < length) {
410         char c = str[i++];
411 
412         if (c < '0' || c > '9') {
413             --i;
414             break;
415         }
416 
417         out.value *= 10;
418         out.value += c - '0';
419 
420         out.length++;
421     }
422 
423     if (negative) {
424         out.value *= -1;
425     }
426 
427     out.valid = out.length > 0;
428     out.remaining_length = length - out.length;
429     out.remaining = str + out.length;
430 
431     return out;
432 }
433 
434 struct control_value
435 {
436     int value;
437     int is_percent;
438     int is_relative;
439 };
440 
to_control_value(const char * value_string)441 static struct control_value to_control_value(const char* value_string)
442 {
443     struct parsed_int parsed_int = parse_int(value_string);
444 
445     struct control_value out = {
446         0 /* value */,
447         0 /* is percent */,
448         0 /* is relative */
449     };
450 
451     out.value = parsed_int.value;
452 
453     unsigned int i = 0;
454 
455     if (parsed_int.remaining[i] == '%') {
456         out.is_percent = 1;
457         i++;
458     }
459 
460     if (parsed_int.remaining[i] == '+') {
461         out.is_relative = 1;
462     } else if (parsed_int.remaining[i] == '-') {
463         out.is_relative = 1;
464         out.value *= -1;
465     }
466 
467     return out;
468 }
469 
set_control_value(struct mixer_ctl * ctl,unsigned int i,const struct control_value * value)470 static int set_control_value(struct mixer_ctl* ctl, unsigned int i,
471                              const struct control_value* value)
472 {
473     int next_value = value->value;
474 
475     if (value->is_relative) {
476 
477         int prev_value = value->is_percent ? mixer_ctl_get_percent(ctl, i)
478                                            : mixer_ctl_get_value(ctl, i);
479 
480         if (prev_value < 0) {
481           return prev_value;
482         }
483 
484         next_value += prev_value;
485     }
486 
487     return value->is_percent ? mixer_ctl_set_percent(ctl, i, next_value)
488                              : mixer_ctl_set_value(ctl, i, next_value);
489 }
490 
set_control_values(struct mixer_ctl * ctl,char ** values,unsigned int num_values)491 static int set_control_values(struct mixer_ctl* ctl,
492                               char** values,
493                               unsigned int num_values)
494 {
495     unsigned int num_ctl_values = mixer_ctl_get_num_values(ctl);
496 
497     if (num_values == 1) {
498 
499         /* Set all values the same */
500         struct control_value value = to_control_value(values[0]);
501 
502         for (unsigned int i = 0; i < num_values; i++) {
503             int res = set_control_value(ctl, i, &value);
504             if (res != 0) {
505                 fprintf(stderr, "Error: invalid value (%d%s%s)\n", value.value,
506                         value.is_relative ? "r" : "", value.is_percent ? "%" : "");
507                 return -1;
508             }
509         }
510 
511     } else {
512 
513         /* Set multiple values */
514         if (num_values > num_ctl_values) {
515             fprintf(stderr,
516                     "Error: %u values given, but control only takes %u\n",
517                     num_values, num_ctl_values);
518             return -1;
519         }
520 
521         for (unsigned int i = 0; i < num_values; i++) {
522 
523             struct control_value v = to_control_value(values[i]);
524 
525             int res = set_control_value(ctl, i, &v);
526             if (res != 0) {
527                 fprintf(stderr, "Error: invalid value (%d%s%s) for index %u\n", v.value,
528                         v.is_relative ? "r" : "", v.is_percent ? "%" : "", i);
529                 return -1;
530             }
531         }
532     }
533 
534     return 0;
535 }
536 
set_values(struct mixer * mixer,const char * control,char ** values,unsigned int num_values)537 static int set_values(struct mixer *mixer, const char *control,
538                              char **values, unsigned int num_values)
539 {
540     struct mixer_ctl *ctl;
541     enum mixer_ctl_type type;
542 
543     if (isnumber(control))
544         ctl = mixer_get_ctl(mixer, atoi(control));
545     else
546         ctl = mixer_get_ctl_by_name(mixer, control);
547 
548     if (!ctl) {
549         fprintf(stderr, "Invalid mixer control\n");
550         return -1;
551     }
552 
553     type = mixer_ctl_get_type(ctl);
554 
555     if (type == MIXER_CTL_TYPE_BYTE) {
556         tinymix_set_byte_ctl(ctl, values, num_values);
557         return 0;
558     }
559 
560     if (is_int(values[0])) {
561         set_control_values(ctl, values, num_values);
562     } else {
563         if (type == MIXER_CTL_TYPE_ENUM) {
564             if (num_values != 1) {
565                 fprintf(stderr, "Enclose strings in quotes and try again\n");
566                 return -1;
567             }
568             if (mixer_ctl_set_enum_by_string(ctl, values[0])) {
569                 fprintf(stderr, "Error: invalid enum value\n");
570                 return -1;
571             }
572         } else {
573             fprintf(stderr, "Error: only enum types can be set with strings\n");
574             return -1;
575         }
576     }
577 
578     return 0;
579 }
580 
581