aboutsummaryrefslogtreecommitdiff
path: root/utils/tinymix.c
blob: a47005c2310164dfd0e237ae998dc88e366a8e81 (plain)
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
/* tinymix.c
**
** Copyright 2011, The Android Open Source Project
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
**     * Redistributions of source code must retain the above copyright
**       notice, this list of conditions and the following disclaimer.
**     * Redistributions in binary form must reproduce the above copyright
**       notice, this list of conditions and the following disclaimer in the
**       documentation and/or other materials provided with the distribution.
**     * Neither the name of The Android Open Source Project nor the names of
**       its contributors may be used to endorse or promote products derived
**       from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
** ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
** DAMAGE.
*/

#include <tinyalsa/asoundlib.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <limits.h>

#define OPTPARSE_IMPLEMENTATION
#include "optparse.h"

static void tinymix_list_controls(struct mixer *mixer, int print_all);

static void tinymix_detail_control(struct mixer *mixer, const char *control);

static int tinymix_set_value(struct mixer *mixer, const char *control,
                             char **values, unsigned int num_values);

static void tinymix_print_enum(struct mixer_ctl *ctl);

void usage(void)
{
    printf("usage: tinymix [options] <command>\n");
    printf("options:\n");
    printf("\t-h, --help        : prints this help message and exits\n");
    printf("\t-v, --version     : prints this version of tinymix and exits\n");
    printf("\t-D, --card NUMBER : specifies the card number of the mixer\n");
    printf("commands:\n");
    printf("\tget NAME|ID       : prints the values of a control\n");
    printf("\tset NAME|ID VALUE : sets the value of a control\n");
    printf("\tcontrols          : lists controls of the mixer\n");
    printf("\tcontents          : lists controls of the mixer and their contents\n");
}

void version(void)
{
    printf("tinymix version 2.0 (tinyalsa version %s)\n", TINYALSA_VERSION_STRING);
}

int main(int argc, char **argv)
{
    struct mixer *mixer;
    int card = 0, c;
    char *cmd;
    struct optparse opts;
    static struct optparse_long long_options[] = {
        { "card",    'D', OPTPARSE_REQUIRED },
        { "version", 'v', OPTPARSE_NONE     },
        { "help",    'h', OPTPARSE_NONE     },
        { 0, 0, 0 }
    };

    optparse_init(&opts, argv);
    /* Detect the end of the options. */
    while ((c = optparse_long(&opts, long_options, NULL)) != -1) {
        switch (c) {
        case 'D':
            card = atoi(opts.optarg);
            break;
        case 'h':
            usage();
            return EXIT_SUCCESS;
        case 'v':
            version();
            return EXIT_SUCCESS;
        case '?':
            fprintf(stderr, "%s\n", opts.errmsg);
            return EXIT_FAILURE;
        }
    }

    mixer = mixer_open(card);
    if (!mixer) {
        fprintf(stderr, "Failed to open mixer\n");
        return EXIT_FAILURE;
    }

    cmd = argv[opts.optind];
    if (cmd == NULL) {
        fprintf(stderr, "no command specified (see --help)\n");
        mixer_close(mixer);
        return EXIT_FAILURE;
    } else if (strcmp(cmd, "get") == 0) {
        if ((opts.optind + 1) >= argc) {
            fprintf(stderr, "no control specified\n");
            mixer_close(mixer);
            return EXIT_FAILURE;
        }
        tinymix_detail_control(mixer, argv[opts.optind + 1]);
        printf("\n");
    } else if (strcmp(cmd, "set") == 0) {
        if ((opts.optind + 1) >= argc) {
            fprintf(stderr, "no control specified\n");
            mixer_close(mixer);
            return EXIT_FAILURE;
        }
        if ((opts.optind + 2) >= argc) {
            fprintf(stderr, "no value(s) specified\n");
            mixer_close(mixer);
            return EXIT_FAILURE;
        }
        int res = tinymix_set_value(mixer, argv[opts.optind + 1], &argv[opts.optind + 2], argc - opts.optind - 2);
        if (res != 0) {
            mixer_close(mixer);
            return EXIT_FAILURE;
        }
    } else if (strcmp(cmd, "controls") == 0) {
        tinymix_list_controls(mixer, 0);
    } else if (strcmp(cmd, "contents") == 0) {
        tinymix_list_controls(mixer, 1);
    } else {
        fprintf(stderr, "unknown command '%s' (see --help)\n", cmd);
        mixer_close(mixer);
        return EXIT_FAILURE;
    }

    mixer_close(mixer);
    return EXIT_SUCCESS;
}

static void tinymix_list_controls(struct mixer *mixer, int print_all)
{
    struct mixer_ctl *ctl;
    const char *name, *type;
    unsigned int num_ctls, num_values;
    unsigned int i;

    num_ctls = mixer_get_num_ctls(mixer);

    printf("Number of controls: %u\n", num_ctls);

    if (print_all)
        printf("ctl\ttype\tnum\t%-40svalue\n", "name");
    else
        printf("ctl\ttype\tnum\t%-40s\n", "name");

    for (i = 0; i < num_ctls; i++) {
        ctl = mixer_get_ctl(mixer, i);

        name = mixer_ctl_get_name(ctl);
        type = mixer_ctl_get_type_string(ctl);
        num_values = mixer_ctl_get_num_values(ctl);
        printf("%u\t%s\t%u\t%-40s", i, type, num_values, name);
        if (print_all)
            tinymix_detail_control(mixer, name);
        printf("\n");
    }
}

static void tinymix_print_enum(struct mixer_ctl *ctl)
{
    unsigned int num_enums;
    unsigned int i;
    unsigned int value;
    const char *string;

    num_enums = mixer_ctl_get_num_enums(ctl);
    value = mixer_ctl_get_value(ctl, 0);

    for (i = 0; i < num_enums; i++) {
        string = mixer_ctl_get_enum_string(ctl, i);
        printf("%s%s, ", value == i ? "> " : "", string);
    }
}

static void tinymix_detail_control(struct mixer *mixer, const char *control)
{
    struct mixer_ctl *ctl;
    enum mixer_ctl_type type;
    unsigned int num_values;
    unsigned int i;
    int min, max;
    int ret;
    char *buf = NULL;
    unsigned int tlv_header_size = 0;

    if (isdigit(control[0]))
        ctl = mixer_get_ctl(mixer, atoi(control));
    else
        ctl = mixer_get_ctl_by_name(mixer, control);

    if (!ctl) {
        fprintf(stderr, "Invalid mixer control\n");
        return;
    }

    type = mixer_ctl_get_type(ctl);
    num_values = mixer_ctl_get_num_values(ctl);

    if ((type == MIXER_CTL_TYPE_BYTE) && (num_values > 0)) {
        if (mixer_ctl_is_access_tlv_rw(ctl) != 0) {
            tlv_header_size = TLV_HEADER_SIZE;
        }
        buf = calloc(1, num_values + tlv_header_size);
        if (buf == NULL) {
            fprintf(stderr, "Failed to alloc mem for bytes %u\n", num_values);
            return;
        }

        ret = mixer_ctl_get_array(ctl, buf, num_values + tlv_header_size);
        if (ret < 0) {
            fprintf(stderr, "Failed to mixer_ctl_get_array\n");
            free(buf);
            return;
        }
    }

    for (i = 0; i < num_values; i++) {
        switch (type)
        {
        case MIXER_CTL_TYPE_INT:
            printf("%d", mixer_ctl_get_value(ctl, i));
            break;
        case MIXER_CTL_TYPE_BOOL:
            printf("%s", mixer_ctl_get_value(ctl, i) ? "On" : "Off");
            break;
        case MIXER_CTL_TYPE_ENUM:
            tinymix_print_enum(ctl);
            break;
        case MIXER_CTL_TYPE_BYTE:
            /* skip printing TLV header if exists */
            printf(" %02x", buf[i + tlv_header_size]);
            break;
        default:
            printf("unknown");
            break;
        };
        if ((i + 1) < num_values) {
           printf(", ");
        }
    }

    if (type == MIXER_CTL_TYPE_INT) {
        min = mixer_ctl_get_range_min(ctl);
        max = mixer_ctl_get_range_max(ctl);
        printf(" (range %d->%d)", min, max);
    }

    free(buf);
}

static void tinymix_set_byte_ctl(struct mixer_ctl *ctl,
                                 char **values, unsigned int num_values)
{
    int ret;
    char *buf;
    char *end;
    unsigned int i;
    long n;
    unsigned int *tlv, tlv_size;
    unsigned int tlv_header_size = 0;

    if (mixer_ctl_is_access_tlv_rw(ctl) != 0) {
        tlv_header_size = TLV_HEADER_SIZE;
    }

    tlv_size = num_values + tlv_header_size;

    buf = calloc(1, tlv_size);
    if (buf == NULL) {
        fprintf(stderr, "set_byte_ctl: Failed to alloc mem for bytes %u\n", num_values);
        exit(EXIT_FAILURE);
    }

    tlv = (unsigned int *)buf;
    tlv[0] = 0;
    tlv[1] = num_values;

    for (i = 0; i < num_values; i++) {
        errno = 0;
        n = strtol(values[i], &end, 0);
        if (*end) {
            fprintf(stderr, "%s not an integer\n", values[i]);
            goto fail;
        }
        if (errno) {
            fprintf(stderr, "strtol: %s: %s\n", values[i],
                strerror(errno));
            goto fail;
        }
        if (n < 0 || n > 0xff) {
            fprintf(stderr, "%s should be between [0, 0xff]\n",
                values[i]);
            goto fail;
        }
        /* start filling after tlv header */
        buf[i + tlv_header_size] = n;
    }

    ret = mixer_ctl_set_array(ctl, buf, tlv_size);
    if (ret < 0) {
        fprintf(stderr, "Failed to set binary control\n");
        goto fail;
    }

    free(buf);
    return;

fail:
    free(buf);
    exit(EXIT_FAILURE);
}

static int is_int(const char *value)
{
    return (value[0] >= '0') || (value[0] <= '9');
}

struct parsed_int
{
  /** Wether or not the integer was valid. */
  int valid;
  /** The value of the parsed integer. */
  int value;
  /** The number of characters that were parsed. */
  unsigned int length;
  /** The number of characters remaining in the string. */
  unsigned int remaining_length;
  /** The remaining characters (or suffix) of the integer. */
  const char* remaining;
};

static struct parsed_int parse_int(const char* str)
{
  struct parsed_int out = {
    0 /* valid */,
    0 /* value */,
    0 /* length */,
    0 /* remaining length */,
    "" /* remaining characters */
  };

  unsigned int max = strlen(str);

  for (unsigned int i = 0; i < max; i++) {

    char c = str[i];

    if ((c < '0') || (c > '9')) {
      break;
    }

    out.value *= 10;
    out.value += c - '0';

    out.length++;
  }

  out.valid = out.length > 0;
  out.remaining_length = max - out.length;
  out.remaining = str + out.length;

  return out;
}

struct control_value
{
    int value;
    int is_percent;
    int is_relative;
};

static struct control_value to_control_value(const char* value_string)
{
    struct parsed_int parsed_int = parse_int(value_string);

    struct control_value out = {
        0 /* value */,
        0 /* is percent */,
        0 /* is relative */
    };

    out.value = parsed_int.value;

    unsigned int i = 0;

    if (parsed_int.remaining[i] == '%') {
      out.is_percent = 1;
      i++;
    }

    if (parsed_int.remaining[i] == '+') {
      out.is_relative = 1;
    } else if (parsed_int.remaining[i] == '-') {
      out.is_relative = 1;
      out.value *= -1;
    }

    return out;
}

static int set_control_value(struct mixer_ctl* ctl, unsigned int i, const struct control_value* value)
{
    int next_value = value->value;

    if (value->is_relative) {

        int prev_value = value->is_percent ? mixer_ctl_get_percent(ctl, i)
                                           : mixer_ctl_get_value(ctl, i);

        if (prev_value < 0) {
          return prev_value;
        }

        next_value += prev_value;
    }

    return value->is_percent ? mixer_ctl_set_percent(ctl, i, next_value)
                             : mixer_ctl_set_value(ctl, i, next_value);
}

static int set_control_values(struct mixer_ctl* ctl,
                              char** values,
                              unsigned int num_values)
{
    unsigned int num_ctl_values = mixer_ctl_get_num_values(ctl);

    if (num_values == 1) {

        /* Set all values the same */
        struct control_value value = to_control_value(values[0]);

        for (unsigned int i = 0; i < num_values; i++) {
            int res = set_control_value(ctl, i, &value);
            if (res != 0) {
                fprintf(stderr, "Error: invalid value\n");
                return -1;
            }
        }

    } else {

        /* Set multiple values */
        if (num_values > num_ctl_values) {
            fprintf(stderr,
                    "Error: %u values given, but control only takes %u\n",
                    num_values, num_ctl_values);
            return -1;
        }

        for (unsigned int i = 0; i < num_values; i++) {

            struct control_value v = to_control_value(values[i]);

            int res = set_control_value(ctl, i, &v);
            if (res != 0) {
                fprintf(stderr, "Error: invalid value for index %u\n", i);
                return -1;
            }
        }
    }

    return 0;
}

static int tinymix_set_value(struct mixer *mixer, const char *control,
                             char **values, unsigned int num_values)
{
    struct mixer_ctl *ctl;
    enum mixer_ctl_type type;

    if (isdigit(control[0]))
        ctl = mixer_get_ctl(mixer, atoi(control));
    else
        ctl = mixer_get_ctl_by_name(mixer, control);

    if (!ctl) {
        fprintf(stderr, "Invalid mixer control\n");
        return -1;
    }

    type = mixer_ctl_get_type(ctl);

    if (type == MIXER_CTL_TYPE_BYTE) {
        tinymix_set_byte_ctl(ctl, values, num_values);
        return 0;
    }

    if (is_int(values[0])) {
        set_control_values(ctl, values, num_values);
    } else {
        if (type == MIXER_CTL_TYPE_ENUM) {
            if (num_values != 1) {
                fprintf(stderr, "Enclose strings in quotes and try again\n");
                return -1;
            }
            if (mixer_ctl_set_enum_by_string(ctl, values[0])) {
                fprintf(stderr, "Error: invalid enum value\n");
                return -1;
            }
        } else {
            fprintf(stderr, "Error: only enum types can be set with strings\n");
            return -1;
        }
    }

    return 0;
}