summaryrefslogtreecommitdiff
path: root/tools/mako/csd-daemon.c
blob: 3f04fd19a5a5972933f66e0cbeadc3cbcfebd6cb (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
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
/* csd-daemon.c
**
** Copyright 2013, Mozilla Corporation
**
** 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 Mozilla Corporation ``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 <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <dlfcn.h>
#include <errno.h>
#include <unistd.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <asoundlib.h>

#define DEBUG 1
#include "common.h"

/* FIXME: we're always setting dmic + tty-off, is that always correct? */
#define ACDB_SETTINGS 0x12

struct state {
    int sockfd;
    int rx_dev, tx_dev;

    int start_voice, started_voice;
    int enabled_device;

    snd_pcm_t *play, *rec;
    snd_ctl_t *ctl;

    snd_ctl_elem_id_t *play_id, *rec_id;

    int volume;
    int mic_mute;

    struct pollfd *pollfds;
    int nfds;
};

static struct state state;

/* Based on prototypes in hardware/qcom/audio/hal/audio_hw.h */

int  (*acdb_loader_init_ACDB)();
void (*acdb_loader_deallocate_ACDB)();
void (*acdb_loader_send_audio_cal)(int, int);
void (*acdb_loader_send_voice_cal)(int, int);

int (*csd_client_init)(void);
int (*csd_client_deinit)(void);
int (*csd_client_disable_device)(void);
int (*csd_client_enable_device)(int, int, uint32_t);
int (*csd_client_volume)(int);
int (*csd_client_mic_mute)(int);
int (*csd_client_start_voice)(void);
int (*csd_client_stop_voice)(void);

static int init_lib(void)
{
    void *handle;

    handle = dlopen("/system/lib/libacdbloader.so", RTLD_NOW);

    acdb_loader_init_ACDB = dlsym(handle, "acdb_loader_init_ACDB");
    acdb_loader_deallocate_ACDB = dlsym(handle, "acdb_loader_deallocate_ACDB");
    acdb_loader_send_audio_cal = dlsym(handle, "acdb_loader_send_audio_cal");
    acdb_loader_send_voice_cal = dlsym(handle, "acdb_loader_send_voice_cal");

    if (!acdb_loader_init_ACDB || !acdb_loader_deallocate_ACDB ||
        !acdb_loader_send_audio_cal || !acdb_loader_send_voice_cal) {
        ERR("Could not find all acdb_loader_* functions\n");
        return -1;
    }

    handle = dlopen("/system/lib/libcsd-client.so", RTLD_NOW);

    csd_client_init = dlsym(handle, "csd_client_init");
    csd_client_deinit = dlsym(handle, "csd_client_deinit");
    csd_client_disable_device = dlsym(handle, "csd_client_disable_device");
    csd_client_enable_device = dlsym(handle, "csd_client_enable_device");
    csd_client_volume = dlsym(handle, "csd_client_volume");
    csd_client_mic_mute = dlsym(handle, "csd_client_mic_mute");
    csd_client_start_voice = dlsym(handle, "csd_client_start_voice");
    csd_client_stop_voice = dlsym(handle, "csd_client_stop_voice");

    if (!csd_client_init || !csd_client_deinit || !csd_client_disable_device ||
        !csd_client_enable_device || !csd_client_volume ||
        !csd_client_mic_mute || !csd_client_start_voice ||
        !csd_client_stop_voice) {
        ERR("Could not find all csd_client_* functions\n");
        return -1;
    }

    return 0;
}

static int init_daemon(void)
{
    struct stat st;
    struct sockaddr_un sa;

    state.rx_dev = state.tx_dev = -1;

    if (stat(DEFAULT_RUNTIME_DIR, &st) < 0) {
        if (errno != -ENOENT) {
            /* First run, try to create the directory */
            if (mkdir(DEFAULT_RUNTIME_DIR, 0700) < 0) {
                ERR("Could not create runtime directory\n");
                return -1;
            }
        } else {
            ERR("Could not access runtime directory\n");
            return -1;
        }
    }

    if ((state.sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        ERR("Could not create socket\n");
        return -1;
    }

    sa.sun_family = AF_UNIX;
    snprintf(sa.sun_path, sizeof(sa.sun_path), DEFAULT_SOCKET_PATH);

    if (stat(DEFAULT_SOCKET_PATH, &st) == 0) {
        /* Either a daemon is already running or this is a stale socket */
        if (connect(state.sockfd, (struct sockaddr *) &sa, sizeof(sa)) < 0 &&
            errno == ECONNREFUSED) {
            DBG("Removing stale socket\n");
            unlink(DEFAULT_SOCKET_PATH);
        } else {
            ERR("Found existing socket, daemon already running?\n");
            close(state.sockfd);
            return -1;
        }
    }

    if (bind(state.sockfd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
        ERR("Could not bind address\n");
        return -1;
    }

    if (listen(state.sockfd, 1) < 0) {
        ERR("Could not start listening for connections\n");
        return -1;
    }

    return 0;
}

#define MODEM_PCM "hw:apq8064tablasnd,12"

static int open_pcms(void)
{
    if (snd_pcm_open(&state.play, MODEM_PCM, SND_PCM_STREAM_PLAYBACK, 0) < 0) {
        ERR("Could not open playback device\n");
        return -1;
    }

    if (snd_pcm_open(&state.rec, MODEM_PCM, SND_PCM_STREAM_CAPTURE, 0) < 0) {
        ERR("Could not open capture device\n");
        return -1;
    }

    if (snd_pcm_set_params(state.play,
                           SND_PCM_FORMAT_S16_LE,
                           SND_PCM_ACCESS_RW_INTERLEAVED,
                           1,
                           8000,
                           0,
                           0) < 0) {
        ERR("Could not set playback params\n");
        return -1;
    }

    if (snd_pcm_set_params(state.rec,
                           SND_PCM_FORMAT_S16_LE,
                           SND_PCM_ACCESS_RW_INTERLEAVED,
                           1,
                           8000,
                           0,
                           0) < 0) {
        ERR("Could not set capture params\n");
        return -1;
    }

    if (snd_pcm_start(state.play) < 0) {
        ERR("Could not start playback PCM\n");
        return -1;
    }

    if (snd_pcm_start(state.rec) < 0) {
        ERR("Could not start capture PCM\n");
        return -1;
    }

    return 0;
}

static void close_pcms(void)
{
    if (state.play) {
        snd_pcm_close(state.play);
        state.play = NULL;
    }

    if (state.rec) {
        snd_pcm_close(state.rec);
        state.rec = NULL;
    }
}

static void remove_user_ctls(void)
{
    snd_ctl_subscribe_events(state.ctl, 0);

    if (state.play_id) {
        snd_ctl_elem_remove(state.ctl, state.play_id);
        state.play_id = NULL;
    }

    if (state.rec_id) {
        snd_ctl_elem_remove(state.ctl, state.rec_id);
        state.rec_id = NULL;
    }

    if (state.ctl) {
        snd_ctl_close(state.ctl);
        state.ctl = NULL;
    }
}

static void set_volume(int volume)
{
    if (state.volume == volume)
        return;

    if (csd_client_volume(100 - volume) < 0)
        ERR("Could not set volume");
    else
        state.volume = volume;
}

static void set_mic_mute(int mic_mute)
{
    if (state.mic_mute == mic_mute)
        return;

    if (csd_client_mic_mute(mic_mute) < 0)
        ERR("Could not set mic_mute");
    else
        state.mic_mute = mic_mute;
}

static void handle_play_volume()
{
    snd_ctl_elem_value_t *elem;

    snd_ctl_elem_value_alloca(&elem);
    snd_ctl_elem_value_set_id(elem, state.play_id);

    if (snd_ctl_elem_read(state.ctl, elem) < 0) {
        ERR("Error reading volume value\n");
        return;
    }

    set_volume(snd_ctl_elem_value_get_integer(elem, 0));
    DBG("Volume set to: %d\n", state.volume);
}

static void handle_mic_switch()
{
    snd_ctl_elem_value_t *elem;

    snd_ctl_elem_value_alloca(&elem);
    snd_ctl_elem_value_set_id(elem, state.rec_id);

    if (snd_ctl_elem_read(state.ctl, elem) < 0) {
        ERR("Error reading mic mute value\n");
        return;
    }

    set_mic_mute(1 - snd_ctl_elem_value_get_boolean(elem, 0));
    DBG("Mic mute set to: %d\n", state.mic_mute);
}

#define CTL_DEVICE "hw:0"

static int create_user_ctls(void)
{
    snd_ctl_elem_value_t *elem;
    int err;

    if (snd_ctl_open(&state.ctl, CTL_DEVICE, SND_CTL_NONBLOCK) < 0) {
        ERR("Could not open playback ctl device\n");
        goto error;
    }

    snd_ctl_elem_id_malloc(&state.play_id);
    snd_ctl_elem_id_set_interface(state.play_id, SND_CTL_ELEM_IFACE_MIXER);
    snd_ctl_elem_id_set_name(state.play_id, "Voice Call Playback Volume");
    snd_ctl_elem_id_set_device(state.play_id, 0);
    snd_ctl_elem_id_set_subdevice(state.play_id, 0);

    /* We ignore -EEXIST to make things more robust if a previous instance of
     * csd-daemon didn't clean up properly */
    err = snd_ctl_elem_add_integer(state.ctl, state.play_id, 1, 0, 100, 1);
    if (err < 0 && err != -EEXIST) {
        ERR("Could not add voice call playback volume control (%d)\n", err);
        goto error;
    }

    snd_ctl_elem_id_malloc(&state.rec_id);
    snd_ctl_elem_id_set_interface(state.rec_id, SND_CTL_ELEM_IFACE_MIXER);
    snd_ctl_elem_id_set_name(state.rec_id, "Voice Call Capture Switch");
    snd_ctl_elem_id_set_device(state.rec_id, 0);
    snd_ctl_elem_id_set_subdevice(state.rec_id, 0);

    err = snd_ctl_elem_add_boolean(state.ctl, state.rec_id, 1);
    if (err < 0 && err != -EEXIST) {
        ERR("Could not add voice call capture switch (%d)\n", err);
        goto error;
    }

    snd_ctl_elem_unlock(state.ctl, state.play_id);
    snd_ctl_elem_unlock(state.ctl, state.rec_id);

    if (snd_ctl_subscribe_events(state.ctl, 1) < 0) {
        ERR("Could not subscribe to mixer events");
        goto error;
    }

    snd_ctl_elem_value_alloca(&elem);

    snd_ctl_elem_value_set_id(elem, state.play_id);
    snd_ctl_elem_value_set_integer(elem, 0, 100);
    if ((err = snd_ctl_elem_write(state.ctl, elem)) < 0)
        ERR("Could not set volume: %d", err);

    snd_ctl_elem_value_set_id(elem, state.rec_id);
    snd_ctl_elem_value_set_boolean(elem, 0, 1);
    if ((err = snd_ctl_elem_write(state.ctl, elem)) < 0)
        ERR("Could not set mic mute: %d", err);

    return 0;

error:
    remove_user_ctls();
    return -1;
}

static int prepare_poll(void)
{
    int i;

    state.nfds = 1 /* socket */ + snd_ctl_poll_descriptors_count(state.ctl);
    state.pollfds = (struct pollfd *) calloc(state.nfds, sizeof(struct pollfd));

    state.pollfds[0].fd = state.sockfd;
    state.pollfds[0].events = POLLIN;

    i = snd_ctl_poll_descriptors(state.ctl, &state.pollfds[1], state.nfds - 1);
    if (i != state.nfds - 1) {
        ERR("Got a wrong number of pollfds\n");
        return -1;
    }

    for (i = 1; i < state.nfds; i++)
        state.pollfds[i].events = POLLIN;

    return 0;
}

static int start_voice(void)
{
    int ret;

    state.start_voice = 0;
    ret = csd_client_start_voice();

    if (ret == 0) {
        state.started_voice = 1;

        DBG("Opening PCMs\n");
        ret = open_pcms();
    }

    return ret;
}

static int enable_device(void)
{
    int ret = 0;

    if (ret == 0) {
        ret = csd_client_enable_device(state.rx_dev, state.tx_dev,
                                       ACDB_SETTINGS);

        if (ret == 0) {
            state.enabled_device = 1;

            if (state.start_voice)
                ret = start_voice();
        }
    }

    return ret;
}

/* Return negative value to signal death (currently only returns 0 */
static int process(const char *command)
{
    int32_t ret = 0;

    if (strncmp(command, "enable-rx-device", 16) == 0) {
        if (sscanf(command, "%*s %d", &state.rx_dev) != 1) {
            ERR("Bad argument to enable-rx-device\n");
            goto out;
        }

        DBG("enable rx device: %d\n", state.rx_dev);

        /* Only enable device after we get both rx and tx device */
        if (state.rx_dev != -1 && state.tx_dev != -1)
            ret = enable_device();

    } else if (strncmp(command, "enable-tx-device", 16) == 0) {
        if (sscanf(command, "%*s %d", &state.tx_dev) != 1) {
            ERR("Bad argument to enable-tx-device\n");
            goto out;
        }

        DBG("enable tx device: %d\n", state.tx_dev);

        /* Only enable device after we get both rx and tx device */
        if (state.rx_dev != -1 && state.tx_dev != -1)
            ret = enable_device();

    } else if (strcmp(command, "disable-device") == 0) {
        /* We need to disable the device before an enable-device and ignore for
         * stop-voice. Since we don't know what's coming next, we wait for
         * these to happen before actually executing the command. */
        ret = csd_client_disable_device();
        state.enabled_device = 0;

    } else if (strncmp(command, "volume", 6) == 0) {
        int volume;

        if (sscanf(command, "%*s %d", &volume) != 1) {
            ERR("Bad volume\n");
            goto out;
        }

        ret = csd_client_volume(volume);

    } else if (strncmp(command, "mic-mute", 8) == 0) {
        int state;

        if (sscanf(command, "%*s %d", &state) != 1 || (state != 0 && state != 1)) {
            ERR("Bad volume\n");
            goto out;
        }

        ret = csd_client_mic_mute(state);

    } else if (strcmp(command, "start-voice") == 0) {
        if (state.rx_dev != -1 && state.tx_dev != -1)
            ret = start_voice();
        else {
            DBG("Deferring start voice till devices are enabled\n");
            state.start_voice = 1;
            ret = 0;
        }

    } else if (strcmp(command, "stop-voice") == 0) {
        if (state.started_voice) {
            if (!state.enabled_device) {
                /* Run a fake enable device because the firmware can't deal
                 * with a stop-voice after disable-device */
                if (csd_client_enable_device(7, 6, ACDB_SETTINGS) < 0)
                    ERR("Error enabling device before shutdown\n");
            }

            ret = csd_client_stop_voice();

            DBG("Closing PCMs\n");
            close_pcms();

        } else
            DBG("Ignoring stop-voice before start-voice was executed\n");

        /* Reset all the things */
        state.start_voice = state.started_voice = 0;
        state.enabled_device = 0;
        state.rx_dev = state.tx_dev = -1;

    } else {
        ERR("Bad command: %s\n", command);
    }

    if (ret < 0)
        ERR("Error running command\n");

    /* For now, there are no fatal errors */

out:
    return 0;
}

int main(int argc, char **argv)
{
    char command[COMMAND_MAX];
    int child, fd, done = 0, ret = 0;
    unsigned int i;
    unsigned short revents;

    if (argc > 1) {
        ERR("Bad arguments\n");
        return -1;
    }

    /* Make our socket readable by only us and the parent */
    umask(0077);

    if (init_lib() < 0)
        return -1;

    if (init_daemon() < 0)
        return -1;

    if (create_user_ctls() < 0)
        return -1;

    /* Basic setup was successful, so clients try to connect. Daemonize before
     * making any actual library init, else nothing will work. */
    if ((child = fork()) < 0) {
        ERR("Could not daemonize");
        return -1;
    }

    if (child > 0) {
        /* This is the parent, exit */
        return 0;
    }

    /* Child process, don't need to double-fork since in most cases we're not
     * actually being run from a terminal. */

    if ((ret = acdb_loader_init_ACDB()) < 0) {
        ERR("Could not initialise acdb loader\n");
        return ret;
    }

    if ((ret = csd_client_init()) < 0) {
        ERR("Could not initialise csd client\n");
        return ret;
    }

    if ((ret = prepare_poll()) < 0) {
        ERR("Could not set up poll()\n");
        return ret;
    }

    while (!done) {
        ret = poll(state.pollfds, state.nfds, -1);
        if (ret < 0) {
            ERR("Error in poll()\n");
            break;
        }

        if ((ret = snd_ctl_poll_descriptors_revents(state.ctl,
                                                    &state.pollfds[1],
                                                    state.nfds - 1,
                                                    &revents)) < 0) {
            ERR("Could not get ALSA revents\n");
        } else {
            if (revents) {
                snd_ctl_event_t *event;

                /* Just force update */
                handle_play_volume();
                handle_mic_switch();

                /* Now consume all pending events */
                snd_ctl_event_alloca(&event);
                do {
                    ret = snd_ctl_read(state.ctl, event);
                } while (ret != 0 && ret != -EAGAIN);
            }
        }

        if (state.pollfds[0].revents == 0)
            continue;

        /* Got a connection */

        fd = accept(state.sockfd, NULL, NULL);

        if (fd < 0) {
            ERR("Could not accept incoming connection\n");
            continue;
        }

        /* We now read one "command" which is a string terminated with a NULL */
        for (i = 0; i < sizeof(command); i++) {
            if (read(fd, &command[i], 1) != 1) {
                ERR("Error reading command. Ignoring.\n");
                goto next;
            }

            if (command[i] == '\0') {
                DBG("Got command: %s\n", command);
                break;
            }
        }

        if (strcmp(command, "quit") == 0) {
            DBG("Got quit message. Exiting.\n");
            done = 1;
        } else if (process(command) < 0) {
            ERR("Fatal error while processing commands. Exiting.\n");
            ret = -1;
            done = 1;
        }

        /* Send back return code */
        if (write(fd, &ret, 4) < 4)
            ERR("Error sending return code");

next:
        close(fd);
    }

out:
    close(state.sockfd);

    if (state.pollfds)
        free(state.pollfds);

    remove_user_ctls();

    /* Clearly deinitialisation is for the weak - this breaks the radio
     * firmware until reboot! */
#if 0
    csd_client_deinit();
    acdb_loader_deallocate_ACDB();
#endif

    return ret;
}