1 /*
2 * Copyright © 2019-2020 Nia Alarie <nia@NetBSD.org>
3 * Copyright © 2020 Ka Ho Ng <khng300@gmail.com>
4 * Copyright © 2020 The FreeBSD Foundation
5 *
6 * Portions of this software were developed by Ka Ho Ng
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * This program is made available under an ISC-style license. See the
10 * accompanying file LICENSE for details.
11 */
12
13 #include <assert.h>
14 #include <ctype.h>
15 #include <limits.h>
16 #include <errno.h>
17 #include <sys/types.h>
18 #include <sys/soundcard.h>
19 #include <sys/ioctl.h>
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <pthread.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <poll.h>
28 #include "cubeb/cubeb.h"
29 #include "cubeb_mixer.h"
30 #include "cubeb_strings.h"
31 #include "cubeb-internal.h"
32
33 /* Supported well by most hardware. */
34 #ifndef OSS_PREFER_RATE
35 #define OSS_PREFER_RATE (48000)
36 #endif
37
38 /* Standard acceptable minimum. */
39 #ifndef OSS_LATENCY_MS
40 #define OSS_LATENCY_MS (8)
41 #endif
42
43 #ifndef OSS_NFRAGS
44 #define OSS_NFRAGS (4)
45 #endif
46
47 #ifndef OSS_DEFAULT_DEVICE
48 #define OSS_DEFAULT_DEVICE "/dev/dsp"
49 #endif
50
51 #ifndef OSS_DEFAULT_MIXER
52 #define OSS_DEFAULT_MIXER "/dev/mixer"
53 #endif
54
55 #define ENV_AUDIO_DEVICE "AUDIO_DEVICE"
56
57 #ifndef OSS_MAX_CHANNELS
58 # if defined(__FreeBSD__) || defined(__DragonFly__)
59 /*
60 * The current maximum number of channels supported
61 * on FreeBSD is 8.
62 *
63 * Reference: FreeBSD 12.1-RELEASE
64 */
65 # define OSS_MAX_CHANNELS (8)
66 # elif defined(__sun__)
67 /*
68 * The current maximum number of channels supported
69 * on Illumos is 16.
70 *
71 * Reference: PSARC 2008/318
72 */
73 # define OSS_MAX_CHANNELS (16)
74 # else
75 # define OSS_MAX_CHANNELS (2)
76 # endif
77 #endif
78
79 #if defined(__FreeBSD__) || defined(__DragonFly__)
80 #define SNDSTAT_BEGIN_STR "Installed devices:"
81 #define SNDSTAT_USER_BEGIN_STR "Installed devices from userspace:"
82 #define SNDSTAT_FV_BEGIN_STR "File Versions:"
83 #endif
84
85 static struct cubeb_ops const oss_ops;
86
87 struct cubeb {
88 struct cubeb_ops const * ops;
89
90 /* Our intern string store */
91 pthread_mutex_t mutex; /* protects devid_strs */
92 cubeb_strings *devid_strs;
93 };
94
95 struct oss_stream {
96 oss_devnode_t name;
97 int fd;
98 void * buf;
99
100 struct stream_info {
101 int channels;
102 int sample_rate;
103 int fmt;
104 int precision;
105 } info;
106
107 unsigned int frame_size; /* precision in bytes * channels */
108 bool floating;
109 };
110
111 struct cubeb_stream {
112 struct cubeb * context;
113 void * user_ptr;
114 pthread_t thread;
115 bool doorbell; /* (m) */
116 pthread_cond_t doorbell_cv; /* (m) */
117 pthread_cond_t stopped_cv; /* (m) */
118 pthread_mutex_t mtx; /* Members protected by this should be marked (m) */
119 bool thread_created; /* (m) */
120 bool running; /* (m) */
121 bool destroying; /* (m) */
122 cubeb_state state; /* (m) */
123 float volume /* (m) */;
124 struct oss_stream play;
125 struct oss_stream record;
126 cubeb_data_callback data_cb;
127 cubeb_state_callback state_cb;
128 uint64_t frames_written /* (m) */;
129 unsigned int nfr; /* Number of frames allocated */
130 unsigned int nfrags;
131 unsigned int bufframes;
132 };
133
134 static char const *
oss_cubeb_devid_intern(cubeb * context,char const * devid)135 oss_cubeb_devid_intern(cubeb *context, char const * devid)
136 {
137 char const *is;
138 pthread_mutex_lock(&context->mutex);
139 is = cubeb_strings_intern(context->devid_strs, devid);
140 pthread_mutex_unlock(&context->mutex);
141 return is;
142 }
143
144 int
oss_init(cubeb ** context,char const * context_name)145 oss_init(cubeb **context, char const *context_name) {
146 cubeb * c;
147
148 (void)context_name;
149 if ((c = calloc(1, sizeof(cubeb))) == NULL) {
150 return CUBEB_ERROR;
151 }
152
153 if (cubeb_strings_init(&c->devid_strs) == CUBEB_ERROR) {
154 goto fail;
155 }
156
157 if (pthread_mutex_init(&c->mutex, NULL) != 0) {
158 goto fail;
159 }
160
161 c->ops = &oss_ops;
162 *context = c;
163 return CUBEB_OK;
164
165 fail:
166 cubeb_strings_destroy(c->devid_strs);
167 free(c);
168 return CUBEB_ERROR;
169 }
170
171 static void
oss_destroy(cubeb * context)172 oss_destroy(cubeb * context)
173 {
174 pthread_mutex_destroy(&context->mutex);
175 cubeb_strings_destroy(context->devid_strs);
176 free(context);
177 }
178
179 static char const *
oss_get_backend_id(cubeb * context)180 oss_get_backend_id(cubeb * context)
181 {
182 return "oss";
183 }
184
185 static int
oss_get_preferred_sample_rate(cubeb * context,uint32_t * rate)186 oss_get_preferred_sample_rate(cubeb * context, uint32_t * rate)
187 {
188 (void)context;
189
190 *rate = OSS_PREFER_RATE;
191 return CUBEB_OK;
192 }
193
194 static int
oss_get_max_channel_count(cubeb * context,uint32_t * max_channels)195 oss_get_max_channel_count(cubeb * context, uint32_t * max_channels)
196 {
197 (void)context;
198
199 *max_channels = OSS_MAX_CHANNELS;
200 return CUBEB_OK;
201 }
202
203 static int
oss_get_min_latency(cubeb * context,cubeb_stream_params params,uint32_t * latency_frames)204 oss_get_min_latency(cubeb * context, cubeb_stream_params params,
205 uint32_t * latency_frames)
206 {
207 (void)context;
208
209 *latency_frames = (OSS_LATENCY_MS * params.rate) / 1000;
210 return CUBEB_OK;
211 }
212
213 static void
oss_free_cubeb_device_info_strings(cubeb_device_info * cdi)214 oss_free_cubeb_device_info_strings(cubeb_device_info *cdi)
215 {
216 free((char *)cdi->device_id);
217 free((char *)cdi->friendly_name);
218 free((char *)cdi->group_id);
219 cdi->device_id = NULL;
220 cdi->friendly_name = NULL;
221 cdi->group_id = NULL;
222 }
223
224 #if defined(__FreeBSD__) || defined(__DragonFly__)
225 /*
226 * Check if the specified DSP is okay for the purpose specified
227 * in type. Here type can only specify one operation each time
228 * this helper is called.
229 *
230 * Return 0 if OK, otherwise 1.
231 */
232 static int
oss_probe_open(const char * dsppath,cubeb_device_type type,int * fdp,oss_audioinfo * resai)233 oss_probe_open(const char *dsppath, cubeb_device_type type,
234 int *fdp, oss_audioinfo *resai)
235 {
236 oss_audioinfo ai;
237 int error;
238 int oflags = (type == CUBEB_DEVICE_TYPE_INPUT) ? O_RDONLY : O_WRONLY;
239 int dspfd = open(dsppath, oflags);
240 if (dspfd == -1)
241 return 1;
242
243 ai.dev = -1;
244 error = ioctl(dspfd, SNDCTL_AUDIOINFO, &ai);
245 if (error < 0) {
246 close(dspfd);
247 return 1;
248 }
249
250 if (resai)
251 *resai = ai;
252 if (fdp)
253 *fdp = dspfd;
254 else
255 close(dspfd);
256 return 0;
257 }
258
259 struct sndstat_info {
260 oss_devnode_t devname;
261 const char *desc;
262 cubeb_device_type type;
263 int preferred;
264 };
265
266 static int
oss_sndstat_line_parse(char * line,int is_ud,struct sndstat_info * sinfo)267 oss_sndstat_line_parse(char *line, int is_ud, struct sndstat_info *sinfo)
268 {
269 char *matchptr = line, *n = NULL;
270 struct sndstat_info res;
271
272 memset(&res, 0, sizeof(res));
273
274 n = strchr(matchptr, ':');
275 if (n == NULL)
276 goto fail;
277 if (is_ud == 0) {
278 unsigned int devunit;
279
280 if (sscanf(matchptr, "pcm%u: ", &devunit) < 1)
281 goto fail;
282
283 if (snprintf(res.devname, sizeof(res.devname), "/dev/dsp%u", devunit) < 1)
284 goto fail;
285 } else {
286 if (n - matchptr >= (ssize_t)(sizeof(res.devname) - strlen("/dev/")))
287 goto fail;
288
289 strlcpy(res.devname, "/dev/", sizeof(res.devname));
290 strncat(res.devname, matchptr, n - matchptr);
291 }
292 matchptr = n + 1;
293
294 n = strchr(matchptr, '<');
295 if (n == NULL)
296 goto fail;
297 matchptr = n + 1;
298 n = strrchr(matchptr, '>');
299 if (n == NULL)
300 goto fail;
301 *n = 0;
302 res.desc = matchptr;
303 matchptr = n + 1;
304
305 n = strchr(matchptr, '(');
306 if (n == NULL)
307 goto fail;
308 matchptr = n + 1;
309 n = strrchr(matchptr, ')');
310 if (n == NULL)
311 goto fail;
312 *n = 0;
313 if (!isdigit(matchptr[0])) {
314 if (strstr(matchptr, "play") != NULL)
315 res.type |= CUBEB_DEVICE_TYPE_OUTPUT;
316 if (strstr(matchptr, "rec") != NULL)
317 res.type |= CUBEB_DEVICE_TYPE_INPUT;
318 } else {
319 int p, r;
320 if (sscanf(matchptr, "%dp:%*dv/%dr:%*dv", &p, &r) != 2)
321 goto fail;
322 if (p > 0)
323 res.type |= CUBEB_DEVICE_TYPE_OUTPUT;
324 if (r > 0)
325 res.type |= CUBEB_DEVICE_TYPE_INPUT;
326 }
327 matchptr = n + 1;
328 if (strstr(matchptr, "default") != NULL)
329 res.preferred = 1;
330
331 *sinfo = res;
332 return 0;
333
334 fail:
335 return 1;
336 }
337
338 /*
339 * XXX: On FreeBSD we have to rely on SNDCTL_CARDINFO to get all
340 * the usable audio devices currently, as SNDCTL_AUDIOINFO will
341 * never return directly usable audio device nodes.
342 */
343 static int
oss_enumerate_devices(cubeb * context,cubeb_device_type type,cubeb_device_collection * collection)344 oss_enumerate_devices(cubeb * context, cubeb_device_type type,
345 cubeb_device_collection * collection)
346 {
347 cubeb_device_info *devinfop = NULL;
348 char *line = NULL;
349 size_t linecap = 0;
350 FILE *sndstatfp = NULL;
351 int collection_cnt = 0;
352 int is_ud = 0;
353 int skipall = 0;
354
355 devinfop = calloc(1, sizeof(cubeb_device_info));
356 if (devinfop == NULL)
357 goto fail;
358
359 sndstatfp = fopen("/dev/sndstat", "r");
360 if (sndstatfp == NULL)
361 goto fail;
362 while (getline(&line, &linecap, sndstatfp) > 0) {
363 const char *devid = NULL;
364 struct sndstat_info sinfo;
365 oss_audioinfo ai;
366
367 if (!strncmp(line, SNDSTAT_FV_BEGIN_STR, strlen(SNDSTAT_FV_BEGIN_STR))) {
368 skipall = 1;
369 continue;
370 }
371 if (!strncmp(line, SNDSTAT_BEGIN_STR, strlen(SNDSTAT_BEGIN_STR))) {
372 is_ud = 0;
373 skipall = 0;
374 continue;
375 }
376 if (!strncmp(line, SNDSTAT_USER_BEGIN_STR, strlen(SNDSTAT_USER_BEGIN_STR))) {
377 is_ud = 1;
378 skipall = 0;
379 continue;
380 }
381 if (skipall || isblank(line[0]))
382 continue;
383
384 if (oss_sndstat_line_parse(line, is_ud, &sinfo))
385 continue;
386
387 devinfop[collection_cnt].type = 0;
388 switch (sinfo.type) {
389 case CUBEB_DEVICE_TYPE_INPUT:
390 if (type & CUBEB_DEVICE_TYPE_OUTPUT)
391 continue;
392 break;
393 case CUBEB_DEVICE_TYPE_OUTPUT:
394 if (type & CUBEB_DEVICE_TYPE_INPUT)
395 continue;
396 break;
397 case 0:
398 continue;
399 }
400
401 if (oss_probe_open(sinfo.devname, type, NULL, &ai))
402 continue;
403
404 devid = oss_cubeb_devid_intern(context, sinfo.devname);
405 if (devid == NULL)
406 continue;
407
408 devinfop[collection_cnt].device_id = strdup(sinfo.devname);
409 asprintf((char **)&devinfop[collection_cnt].friendly_name, "%s: %s",
410 sinfo.devname, sinfo.desc);
411 devinfop[collection_cnt].group_id = strdup(sinfo.devname);
412 devinfop[collection_cnt].vendor_name = NULL;
413 if (devinfop[collection_cnt].device_id == NULL ||
414 devinfop[collection_cnt].friendly_name == NULL ||
415 devinfop[collection_cnt].group_id == NULL) {
416 oss_free_cubeb_device_info_strings(&devinfop[collection_cnt]);
417 continue;
418 }
419
420 devinfop[collection_cnt].type = type;
421 devinfop[collection_cnt].devid = devid;
422 devinfop[collection_cnt].state = CUBEB_DEVICE_STATE_ENABLED;
423 devinfop[collection_cnt].preferred =
424 (sinfo.preferred) ? CUBEB_DEVICE_PREF_ALL : CUBEB_DEVICE_PREF_NONE;
425 devinfop[collection_cnt].format = CUBEB_DEVICE_FMT_S16NE;
426 devinfop[collection_cnt].default_format = CUBEB_DEVICE_FMT_S16NE;
427 devinfop[collection_cnt].max_channels = ai.max_channels;
428 devinfop[collection_cnt].default_rate = OSS_PREFER_RATE;
429 devinfop[collection_cnt].max_rate = ai.max_rate;
430 devinfop[collection_cnt].min_rate = ai.min_rate;
431 devinfop[collection_cnt].latency_lo = 0;
432 devinfop[collection_cnt].latency_hi = 0;
433
434 collection_cnt++;
435
436 void *newp = reallocarray(devinfop, collection_cnt + 1,
437 sizeof(cubeb_device_info));
438 if (newp == NULL)
439 goto fail;
440 devinfop = newp;
441 }
442
443 free(line);
444 fclose(sndstatfp);
445
446 collection->count = collection_cnt;
447 collection->device = devinfop;
448
449 return CUBEB_OK;
450
451 fail:
452 free(line);
453 if (sndstatfp)
454 fclose(sndstatfp);
455 free(devinfop);
456 return CUBEB_ERROR;
457 }
458
459 #else
460
461 static int
oss_enumerate_devices(cubeb * context,cubeb_device_type type,cubeb_device_collection * collection)462 oss_enumerate_devices(cubeb * context, cubeb_device_type type,
463 cubeb_device_collection * collection)
464 {
465 oss_sysinfo si;
466 int error, i;
467 cubeb_device_info *devinfop = NULL;
468 int collection_cnt = 0;
469 int mixer_fd = -1;
470
471 mixer_fd = open(OSS_DEFAULT_MIXER, O_RDWR);
472 if (mixer_fd == -1) {
473 LOG("Failed to open mixer %s. errno: %d", OSS_DEFAULT_MIXER, errno);
474 return CUBEB_ERROR;
475 }
476
477 error = ioctl(mixer_fd, SNDCTL_SYSINFO, &si);
478 if (error) {
479 LOG("Failed to run SNDCTL_SYSINFO on mixer %s. errno: %d", OSS_DEFAULT_MIXER, errno);
480 goto fail;
481 }
482
483 devinfop = calloc(si.numaudios, sizeof(cubeb_device_info));
484 if (devinfop == NULL)
485 goto fail;
486
487 collection->count = 0;
488 for (i = 0; i < si.numaudios; i++) {
489 oss_audioinfo ai;
490 cubeb_device_info cdi = { 0 };
491 const char *devid = NULL;
492
493 ai.dev = i;
494 error = ioctl(mixer_fd, SNDCTL_AUDIOINFO, &ai);
495 if (error)
496 goto fail;
497
498 assert(ai.dev < si.numaudios);
499 if (!ai.enabled)
500 continue;
501
502 cdi.type = 0;
503 switch (ai.caps & DSP_CAP_DUPLEX) {
504 case DSP_CAP_INPUT:
505 if (type & CUBEB_DEVICE_TYPE_OUTPUT)
506 continue;
507 break;
508 case DSP_CAP_OUTPUT:
509 if (type & CUBEB_DEVICE_TYPE_INPUT)
510 continue;
511 break;
512 case 0:
513 continue;
514 }
515 cdi.type = type;
516
517 devid = oss_cubeb_devid_intern(context, ai.devnode);
518 cdi.device_id = strdup(ai.name);
519 cdi.friendly_name = strdup(ai.name);
520 cdi.group_id = strdup(ai.name);
521 if (devid == NULL || cdi.device_id == NULL || cdi.friendly_name == NULL ||
522 cdi.group_id == NULL) {
523 oss_free_cubeb_device_info_strings(&cdi);
524 continue;
525 }
526
527 cdi.devid = devid;
528 cdi.vendor_name = NULL;
529 cdi.state = CUBEB_DEVICE_STATE_ENABLED;
530 cdi.preferred = CUBEB_DEVICE_PREF_NONE;
531 cdi.format = CUBEB_DEVICE_FMT_S16NE;
532 cdi.default_format = CUBEB_DEVICE_FMT_S16NE;
533 cdi.max_channels = ai.max_channels;
534 cdi.default_rate = OSS_PREFER_RATE;
535 cdi.max_rate = ai.max_rate;
536 cdi.min_rate = ai.min_rate;
537 cdi.latency_lo = 0;
538 cdi.latency_hi = 0;
539
540 devinfop[collection_cnt++] = cdi;
541 }
542
543 collection->count = collection_cnt;
544 collection->device = devinfop;
545
546 if (mixer_fd != -1)
547 close(mixer_fd);
548 return CUBEB_OK;
549
550 fail:
551 if (mixer_fd != -1)
552 close(mixer_fd);
553 free(devinfop);
554 return CUBEB_ERROR;
555 }
556
557 #endif
558
559 static int
oss_device_collection_destroy(cubeb * context,cubeb_device_collection * collection)560 oss_device_collection_destroy(cubeb * context,
561 cubeb_device_collection * collection)
562 {
563 size_t i;
564 for (i = 0; i < collection->count; i++) {
565 oss_free_cubeb_device_info_strings(&collection->device[i]);
566 }
567 free(collection->device);
568 collection->device = NULL;
569 collection->count = 0;
570 return 0;
571 }
572
573 static unsigned int
oss_chn_from_cubeb(cubeb_channel chn)574 oss_chn_from_cubeb(cubeb_channel chn)
575 {
576 switch (chn) {
577 case CHANNEL_FRONT_LEFT:
578 return CHID_L;
579 case CHANNEL_FRONT_RIGHT:
580 return CHID_R;
581 case CHANNEL_FRONT_CENTER:
582 return CHID_C;
583 case CHANNEL_LOW_FREQUENCY:
584 return CHID_LFE;
585 case CHANNEL_BACK_LEFT:
586 return CHID_LR;
587 case CHANNEL_BACK_RIGHT:
588 return CHID_RR;
589 case CHANNEL_SIDE_LEFT:
590 return CHID_LS;
591 case CHANNEL_SIDE_RIGHT:
592 return CHID_RS;
593 default:
594 return CHID_UNDEF;
595 }
596 }
597
598 static unsigned long long
oss_cubeb_layout_to_chnorder(cubeb_channel_layout layout)599 oss_cubeb_layout_to_chnorder(cubeb_channel_layout layout)
600 {
601 unsigned int i, nchns = 0;
602 unsigned long long chnorder = 0;
603
604 for (i = 0; layout; i++, layout >>= 1) {
605 unsigned long long chid = oss_chn_from_cubeb((layout & 1) << i);
606 if (chid == CHID_UNDEF)
607 continue;
608
609 chnorder |= (chid & 0xf) << nchns * 4;
610 nchns++;
611 }
612
613 return chnorder;
614 }
615
616 static int
oss_copy_params(int fd,cubeb_stream * stream,cubeb_stream_params * params,struct stream_info * sinfo)617 oss_copy_params(int fd, cubeb_stream * stream, cubeb_stream_params * params,
618 struct stream_info * sinfo)
619 {
620 unsigned long long chnorder;
621
622 sinfo->channels = params->channels;
623 sinfo->sample_rate = params->rate;
624 switch (params->format) {
625 case CUBEB_SAMPLE_S16LE:
626 sinfo->fmt = AFMT_S16_LE;
627 sinfo->precision = 16;
628 break;
629 case CUBEB_SAMPLE_S16BE:
630 sinfo->fmt = AFMT_S16_BE;
631 sinfo->precision = 16;
632 break;
633 case CUBEB_SAMPLE_FLOAT32NE:
634 sinfo->fmt = AFMT_S32_NE;
635 sinfo->precision = 32;
636 break;
637 default:
638 LOG("Unsupported format");
639 return CUBEB_ERROR_INVALID_FORMAT;
640 }
641 if (ioctl(fd, SNDCTL_DSP_CHANNELS, &sinfo->channels) == -1) {
642 return CUBEB_ERROR;
643 }
644 if (ioctl(fd, SNDCTL_DSP_SETFMT, &sinfo->fmt) == -1) {
645 return CUBEB_ERROR;
646 }
647 if (ioctl(fd, SNDCTL_DSP_SPEED, &sinfo->sample_rate) == -1) {
648 return CUBEB_ERROR;
649 }
650 /* Mono layout is an exception */
651 if (params->layout != CUBEB_LAYOUT_UNDEFINED && params->layout != CUBEB_LAYOUT_MONO) {
652 chnorder = oss_cubeb_layout_to_chnorder(params->layout);
653 if (ioctl(fd, SNDCTL_DSP_SET_CHNORDER, &chnorder) == -1)
654 LOG("Non-fatal error %d occured when setting channel order.", errno);
655 }
656 return CUBEB_OK;
657 }
658
659 static int
oss_stream_stop(cubeb_stream * s)660 oss_stream_stop(cubeb_stream * s)
661 {
662 pthread_mutex_lock(&s->mtx);
663 if (s->thread_created && s->running) {
664 s->running = false;
665 s->doorbell = false;
666 pthread_cond_wait(&s->stopped_cv, &s->mtx);
667 }
668 if (s->state != CUBEB_STATE_STOPPED) {
669 s->state = CUBEB_STATE_STOPPED;
670 pthread_mutex_unlock(&s->mtx);
671 s->state_cb(s, s->user_ptr, CUBEB_STATE_STOPPED);
672 } else {
673 pthread_mutex_unlock(&s->mtx);
674 }
675 return CUBEB_OK;
676 }
677
678 static void
oss_stream_destroy(cubeb_stream * s)679 oss_stream_destroy(cubeb_stream * s)
680 {
681 pthread_mutex_lock(&s->mtx);
682 if (s->thread_created) {
683 s->destroying = true;
684 s->doorbell = true;
685 pthread_cond_signal(&s->doorbell_cv);
686 }
687 pthread_mutex_unlock(&s->mtx);
688 pthread_join(s->thread, NULL);
689
690 pthread_cond_destroy(&s->doorbell_cv);
691 pthread_cond_destroy(&s->stopped_cv);
692 pthread_mutex_destroy(&s->mtx);
693 if (s->play.fd != -1) {
694 close(s->play.fd);
695 }
696 if (s->record.fd != -1) {
697 close(s->record.fd);
698 }
699 free(s->play.buf);
700 free(s->record.buf);
701 free(s);
702 }
703
704 static void
oss_float_to_linear32(void * buf,unsigned sample_count,float vol)705 oss_float_to_linear32(void * buf, unsigned sample_count, float vol)
706 {
707 float * in = buf;
708 int32_t * out = buf;
709 int32_t * tail = out + sample_count;
710
711 while (out < tail) {
712 int64_t f = *(in++) * vol * 0x80000000LL;
713 if (f < -INT32_MAX)
714 f = -INT32_MAX;
715 else if (f > INT32_MAX)
716 f = INT32_MAX;
717 *(out++) = f;
718 }
719 }
720
721 static void
oss_linear32_to_float(void * buf,unsigned sample_count)722 oss_linear32_to_float(void * buf, unsigned sample_count)
723 {
724 int32_t * in = buf;
725 float * out = buf;
726 float * tail = out + sample_count;
727
728 while (out < tail) {
729 *(out++) = (1.0 / 0x80000000LL) * *(in++);
730 }
731 }
732
733 static void
oss_linear16_set_vol(int16_t * buf,unsigned sample_count,float vol)734 oss_linear16_set_vol(int16_t * buf, unsigned sample_count, float vol)
735 {
736 unsigned i;
737 int32_t multiplier = vol * 0x8000;
738
739 for (i = 0; i < sample_count; ++i) {
740 buf[i] = (buf[i] * multiplier) >> 15;
741 }
742 }
743
744 static int
oss_get_rec_frames(cubeb_stream * s,unsigned int nframes)745 oss_get_rec_frames(cubeb_stream * s, unsigned int nframes)
746 {
747 size_t rem = nframes * s->record.frame_size;
748 size_t read_ofs = 0;
749 while (rem > 0) {
750 ssize_t n;
751 if ((n = read(s->record.fd, (uint8_t *)s->record.buf + read_ofs, rem)) < 0) {
752 if (errno == EINTR)
753 continue;
754 return CUBEB_ERROR;
755 }
756 read_ofs += n;
757 rem -= n;
758 }
759 return 0;
760 }
761
762
763 static int
oss_put_play_frames(cubeb_stream * s,unsigned int nframes)764 oss_put_play_frames(cubeb_stream * s, unsigned int nframes)
765 {
766 size_t rem = nframes * s->play.frame_size;
767 size_t write_ofs = 0;
768 while (rem > 0) {
769 ssize_t n;
770 if ((n = write(s->play.fd, (uint8_t *)s->play.buf + write_ofs, rem)) < 0) {
771 if (errno == EINTR)
772 continue;
773 return CUBEB_ERROR;
774 }
775 pthread_mutex_lock(&s->mtx);
776 s->frames_written += n / s->play.frame_size;
777 pthread_mutex_unlock(&s->mtx);
778 write_ofs += n;
779 rem -= n;
780 }
781 return 0;
782 }
783
784 static int
oss_wait_playfd_for_space(cubeb_stream * s)785 oss_wait_playfd_for_space(cubeb_stream * s)
786 {
787 /* For non-duplex stream we have to wait until we have space in the
788 * buffer */
789 int rate = s->play.info.sample_rate;
790 struct pollfd pfd;
791
792 pfd.events = POLLOUT|POLLHUP;
793 pfd.revents = 0;
794 pfd.fd = s->play.fd;
795
796 if (poll(&pfd, 1, s->nfr * 1000 + rate - 1 / rate) == -1) {
797 return CUBEB_ERROR;
798 }
799
800 if (pfd.revents & POLLHUP) {
801 return CUBEB_ERROR;
802 }
803 return 0;
804 }
805
806 /* 1 - Stopped by cubeb_stream_stop, otherwise 0 */
807 static int
oss_audio_loop(cubeb_stream * s,cubeb_state * new_state)808 oss_audio_loop(cubeb_stream * s, cubeb_state *new_state)
809 {
810 cubeb_state state = CUBEB_STATE_STOPPED;
811 int trig = 0;
812 int drain = 0;
813 const bool play_on = s->play.fd != -1, record_on = s->record.fd != -1;
814 long nfr = s->bufframes;
815
816 if (record_on) {
817 if (ioctl(s->record.fd, SNDCTL_DSP_SETTRIGGER, &trig)) {
818 LOG("Error %d occured when setting trigger on record fd", errno);
819 state = CUBEB_STATE_ERROR;
820 goto breakdown;
821 }
822 trig |= PCM_ENABLE_INPUT;
823 if (ioctl(s->record.fd, SNDCTL_DSP_SETTRIGGER, &trig)) {
824 LOG("Error %d occured when setting trigger on record fd", errno);
825 state = CUBEB_STATE_ERROR;
826 goto breakdown;
827 }
828
829 memset(s->record.buf, 0, s->bufframes * s->record.frame_size);
830 }
831
832 if (!play_on && !record_on) {
833 /*
834 * Stop here if the stream is not play & record stream,
835 * play-only stream or record-only stream
836 */
837
838 goto breakdown;
839 }
840
841 while (1) {
842 pthread_mutex_lock(&s->mtx);
843 if (!s->running || s->destroying) {
844 pthread_mutex_unlock(&s->mtx);
845 break;
846 }
847 pthread_mutex_unlock(&s->mtx);
848
849 long got = 0;
850 if (nfr > 0) {
851 got = s->data_cb(s, s->user_ptr, s->record.buf, s->play.buf, nfr);
852 if (got == CUBEB_ERROR) {
853 state = CUBEB_STATE_ERROR;
854 goto breakdown;
855 }
856 if (play_on) {
857 float vol;
858
859 pthread_mutex_lock(&s->mtx);
860 vol = s->volume;
861 pthread_mutex_unlock(&s->mtx);
862
863 if (s->play.floating) {
864 oss_float_to_linear32(s->play.buf, s->play.info.channels * got, vol);
865 } else {
866 oss_linear16_set_vol((int16_t *)s->play.buf,
867 s->play.info.channels * got, vol);
868 }
869 }
870 if (got < nfr) {
871 if (s->play.fd != -1) {
872 drain = 1;
873 } else {
874 /*
875 * This is a record-only stream and number of frames
876 * returned from data_cb() is smaller than number
877 * of frames required to read. Stop here.
878 */
879
880 state = CUBEB_STATE_STOPPED;
881 goto breakdown;
882 }
883 }
884 nfr = 0;
885 }
886
887 if (got > 0) {
888 if (play_on && oss_put_play_frames(s, got) < 0) {
889 state = CUBEB_STATE_ERROR;
890 goto breakdown;
891 }
892 }
893 if (drain) {
894 state = CUBEB_STATE_DRAINED;
895 goto breakdown;
896 }
897
898 if (play_on) {
899 /*
900 * In duplex mode, playback direction drives recording direction to
901 * prevent building up latencies.
902 */
903
904 if (oss_wait_playfd_for_space(s) != 0) {
905 state = CUBEB_STATE_ERROR;
906 goto breakdown;
907 }
908
909 audio_buf_info bi;
910 if (ioctl(s->play.fd, SNDCTL_DSP_GETOSPACE, &bi)) {
911 state = CUBEB_STATE_ERROR;
912 goto breakdown;
913 }
914 nfr = bi.fragsize * bi.fragments / s->play.frame_size;
915 if (nfr > s->bufframes) {
916 nfr = s->bufframes;
917 }
918 } else {
919 nfr = s->nfr;
920 }
921
922 if (record_on) {
923 if (oss_get_rec_frames(s, nfr) == CUBEB_ERROR) {
924 state = CUBEB_STATE_ERROR;
925 goto breakdown;
926 }
927 if (s->record.floating) {
928 oss_linear32_to_float(s->record.buf, s->record.info.channels * nfr);
929 }
930 }
931 }
932
933 return 1;
934
935 breakdown:
936 pthread_mutex_lock(&s->mtx);
937 *new_state = s->state = state;
938 s->running = false;
939 pthread_mutex_unlock(&s->mtx);
940 return 0;
941 }
942
943 static void *
oss_io_routine(void * arg)944 oss_io_routine(void *arg)
945 {
946 cubeb_stream *s = arg;
947 cubeb_state new_state;
948 int stopped;
949
950 do {
951 pthread_mutex_lock(&s->mtx);
952 if (s->destroying) {
953 pthread_mutex_unlock(&s->mtx);
954 break;
955 }
956 pthread_mutex_unlock(&s->mtx);
957
958 stopped = oss_audio_loop(s, &new_state);
959 if (s->record.fd != -1)
960 ioctl(s->record.fd, SNDCTL_DSP_HALT_INPUT, NULL);
961 if (!stopped)
962 s->state_cb(s, s->user_ptr, new_state);
963
964 pthread_mutex_lock(&s->mtx);
965 pthread_cond_signal(&s->stopped_cv);
966 if (s->destroying) {
967 pthread_mutex_unlock(&s->mtx);
968 break;
969 }
970 while (!s->doorbell) {
971 pthread_cond_wait(&s->doorbell_cv, &s->mtx);
972 }
973 s->doorbell = false;
974 pthread_mutex_unlock(&s->mtx);
975 } while (1);
976
977 pthread_mutex_lock(&s->mtx);
978 s->thread_created = false;
979 pthread_mutex_unlock(&s->mtx);
980 return NULL;
981 }
982
983 static inline int
oss_calc_frag_shift(unsigned int frames,unsigned int frame_size)984 oss_calc_frag_shift(unsigned int frames, unsigned int frame_size)
985 {
986 int n = 4;
987 int blksize = (frames * frame_size + OSS_NFRAGS - 1) / OSS_NFRAGS;
988 while ((1 << n) < blksize)
989 n++;
990 return n;
991 }
992
993 static inline int
oss_get_frag_params(unsigned int shift)994 oss_get_frag_params(unsigned int shift)
995 {
996 return (OSS_NFRAGS << 16) | shift;
997 }
998
999 static int
oss_stream_init(cubeb * context,cubeb_stream ** stream,char const * stream_name,cubeb_devid input_device,cubeb_stream_params * input_stream_params,cubeb_devid output_device,cubeb_stream_params * output_stream_params,unsigned int latency_frames,cubeb_data_callback data_callback,cubeb_state_callback state_callback,void * user_ptr)1000 oss_stream_init(cubeb * context,
1001 cubeb_stream ** stream,
1002 char const * stream_name,
1003 cubeb_devid input_device,
1004 cubeb_stream_params * input_stream_params,
1005 cubeb_devid output_device,
1006 cubeb_stream_params * output_stream_params,
1007 unsigned int latency_frames,
1008 cubeb_data_callback data_callback,
1009 cubeb_state_callback state_callback,
1010 void * user_ptr)
1011 {
1012 int ret = CUBEB_OK;
1013 unsigned int playnfr = 0, recnfr = 0;
1014 cubeb_stream *s = NULL;
1015 const char *defdsp;
1016
1017 if (!(defdsp = getenv(ENV_AUDIO_DEVICE)) || *defdsp == '\0')
1018 defdsp = OSS_DEFAULT_DEVICE;
1019
1020 (void)stream_name;
1021 if ((s = calloc(1, sizeof(cubeb_stream))) == NULL) {
1022 ret = CUBEB_ERROR;
1023 goto error;
1024 }
1025 s->state = CUBEB_STATE_STOPPED;
1026 s->record.fd = s->play.fd = -1;
1027 s->nfr = latency_frames;
1028 if (input_device != NULL) {
1029 strlcpy(s->record.name, input_device, sizeof(s->record.name));
1030 } else {
1031 strlcpy(s->record.name, defdsp, sizeof(s->record.name));
1032 }
1033 if (output_device != NULL) {
1034 strlcpy(s->play.name, output_device, sizeof(s->play.name));
1035 } else {
1036 strlcpy(s->play.name, defdsp, sizeof(s->play.name));
1037 }
1038 if (input_stream_params != NULL) {
1039 unsigned int nb_channels;
1040 if (input_stream_params->prefs & CUBEB_STREAM_PREF_LOOPBACK) {
1041 LOG("Loopback not supported");
1042 ret = CUBEB_ERROR_NOT_SUPPORTED;
1043 goto error;
1044 }
1045 nb_channels = cubeb_channel_layout_nb_channels(input_stream_params->layout);
1046 if (input_stream_params->layout != CUBEB_LAYOUT_UNDEFINED &&
1047 nb_channels != input_stream_params->channels) {
1048 LOG("input_stream_params->layout does not match input_stream_params->channels");
1049 ret = CUBEB_ERROR_INVALID_PARAMETER;
1050 goto error;
1051 }
1052 if (s->record.fd == -1) {
1053 if ((s->record.fd = open(s->record.name, O_RDONLY)) == -1) {
1054 LOG("Audio device \"%s\" could not be opened as read-only",
1055 s->record.name);
1056 ret = CUBEB_ERROR_DEVICE_UNAVAILABLE;
1057 goto error;
1058 }
1059 }
1060 if ((ret = oss_copy_params(s->record.fd, s, input_stream_params,
1061 &s->record.info)) != CUBEB_OK) {
1062 LOG("Setting record params failed");
1063 goto error;
1064 }
1065 s->record.floating = (input_stream_params->format == CUBEB_SAMPLE_FLOAT32NE);
1066 s->record.frame_size = s->record.info.channels * (s->record.info.precision / 8);
1067 recnfr = (1 << oss_calc_frag_shift(s->nfr, s->record.frame_size)) / s->record.frame_size;
1068 }
1069 if (output_stream_params != NULL) {
1070 unsigned int nb_channels;
1071 if (output_stream_params->prefs & CUBEB_STREAM_PREF_LOOPBACK) {
1072 LOG("Loopback not supported");
1073 ret = CUBEB_ERROR_NOT_SUPPORTED;
1074 goto error;
1075 }
1076 nb_channels = cubeb_channel_layout_nb_channels(output_stream_params->layout);
1077 if (output_stream_params->layout != CUBEB_LAYOUT_UNDEFINED &&
1078 nb_channels != output_stream_params->channels) {
1079 LOG("output_stream_params->layout does not match output_stream_params->channels");
1080 ret = CUBEB_ERROR_INVALID_PARAMETER;
1081 goto error;
1082 }
1083 if (s->play.fd == -1) {
1084 if ((s->play.fd = open(s->play.name, O_WRONLY)) == -1) {
1085 LOG("Audio device \"%s\" could not be opened as write-only",
1086 s->play.name);
1087 ret = CUBEB_ERROR_DEVICE_UNAVAILABLE;
1088 goto error;
1089 }
1090 }
1091 if ((ret = oss_copy_params(s->play.fd, s, output_stream_params,
1092 &s->play.info)) != CUBEB_OK) {
1093 LOG("Setting play params failed");
1094 goto error;
1095 }
1096 s->play.floating = (output_stream_params->format == CUBEB_SAMPLE_FLOAT32NE);
1097 s->play.frame_size = s->play.info.channels * (s->play.info.precision / 8);
1098 playnfr = (1 << oss_calc_frag_shift(s->nfr, s->play.frame_size)) / s->play.frame_size;
1099 }
1100 /*
1101 * Use the largest nframes among playing and recording streams to set OSS buffer size.
1102 * After that, use the smallest allocated nframes among both direction to allocate our
1103 * temporary buffers.
1104 */
1105 s->nfr = (playnfr > recnfr) ? playnfr : recnfr;
1106 s->nfrags = OSS_NFRAGS;
1107 if (s->play.fd != -1) {
1108 int frag = oss_get_frag_params(oss_calc_frag_shift(s->nfr, s->play.frame_size));
1109 if (ioctl(s->play.fd, SNDCTL_DSP_SETFRAGMENT, &frag))
1110 LOG("Failed to set play fd with SNDCTL_DSP_SETFRAGMENT. frag: 0x%x",
1111 frag);
1112 audio_buf_info bi;
1113 if (ioctl(s->play.fd, SNDCTL_DSP_GETOSPACE, &bi))
1114 LOG("Failed to get play fd's buffer info.");
1115 else {
1116 if (bi.fragsize / s->play.frame_size < s->nfr)
1117 s->nfr = bi.fragsize / s->play.frame_size;
1118 }
1119 }
1120 if (s->record.fd != -1) {
1121 int frag = oss_get_frag_params(oss_calc_frag_shift(s->nfr, s->record.frame_size));
1122 if (ioctl(s->record.fd, SNDCTL_DSP_SETFRAGMENT, &frag))
1123 LOG("Failed to set record fd with SNDCTL_DSP_SETFRAGMENT. frag: 0x%x",
1124 frag);
1125 audio_buf_info bi;
1126 if (ioctl(s->record.fd, SNDCTL_DSP_GETISPACE, &bi))
1127 LOG("Failed to get record fd's buffer info.");
1128 else {
1129 if (bi.fragsize / s->record.frame_size < s->nfr)
1130 s->nfr = bi.fragsize / s->record.frame_size;
1131 }
1132 }
1133 s->bufframes = s->nfr * s->nfrags;
1134 s->context = context;
1135 s->volume = 1.0;
1136 s->state_cb = state_callback;
1137 s->data_cb = data_callback;
1138 s->user_ptr = user_ptr;
1139
1140 if (pthread_mutex_init(&s->mtx, NULL) != 0) {
1141 LOG("Failed to create mutex");
1142 goto error;
1143 }
1144 if (pthread_cond_init(&s->doorbell_cv, NULL) != 0) {
1145 LOG("Failed to create cv");
1146 goto error;
1147 }
1148 if (pthread_cond_init(&s->stopped_cv, NULL) != 0) {
1149 LOG("Failed to create cv");
1150 goto error;
1151 }
1152 s->doorbell = false;
1153
1154 if (s->play.fd != -1) {
1155 if ((s->play.buf = calloc(s->bufframes, s->play.frame_size)) == NULL) {
1156 ret = CUBEB_ERROR;
1157 goto error;
1158 }
1159 }
1160 if (s->record.fd != -1) {
1161 if ((s->record.buf = calloc(s->bufframes, s->record.frame_size)) == NULL) {
1162 ret = CUBEB_ERROR;
1163 goto error;
1164 }
1165 }
1166
1167 *stream = s;
1168 return CUBEB_OK;
1169 error:
1170 if (s != NULL) {
1171 oss_stream_destroy(s);
1172 }
1173 return ret;
1174 }
1175
1176 static int
oss_stream_thr_create(cubeb_stream * s)1177 oss_stream_thr_create(cubeb_stream * s)
1178 {
1179 if (s->thread_created) {
1180 s->doorbell = true;
1181 pthread_cond_signal(&s->doorbell_cv);
1182 return CUBEB_OK;
1183 }
1184
1185 if (pthread_create(&s->thread, NULL, oss_io_routine, s) != 0) {
1186 LOG("Couldn't create thread");
1187 return CUBEB_ERROR;
1188 }
1189
1190 return CUBEB_OK;
1191 }
1192
1193 static int
oss_stream_start(cubeb_stream * s)1194 oss_stream_start(cubeb_stream * s)
1195 {
1196 s->state_cb(s, s->user_ptr, CUBEB_STATE_STARTED);
1197 pthread_mutex_lock(&s->mtx);
1198 /* Disallow starting an already started stream */
1199 assert(!s->running && s->state != CUBEB_STATE_STARTED);
1200 if (oss_stream_thr_create(s) != CUBEB_OK) {
1201 pthread_mutex_unlock(&s->mtx);
1202 s->state_cb(s, s->user_ptr, CUBEB_STATE_ERROR);
1203 return CUBEB_ERROR;
1204 }
1205 s->state = CUBEB_STATE_STARTED;
1206 s->thread_created = true;
1207 s->running = true;
1208 pthread_mutex_unlock(&s->mtx);
1209 return CUBEB_OK;
1210 }
1211
1212 static int
oss_stream_get_position(cubeb_stream * s,uint64_t * position)1213 oss_stream_get_position(cubeb_stream * s, uint64_t * position)
1214 {
1215 pthread_mutex_lock(&s->mtx);
1216 *position = s->frames_written;
1217 pthread_mutex_unlock(&s->mtx);
1218 return CUBEB_OK;
1219 }
1220
1221 static int
oss_stream_get_latency(cubeb_stream * s,uint32_t * latency)1222 oss_stream_get_latency(cubeb_stream * s, uint32_t * latency)
1223 {
1224 int delay;
1225
1226 if (ioctl(s->play.fd, SNDCTL_DSP_GETODELAY, &delay) == -1) {
1227 return CUBEB_ERROR;
1228 }
1229
1230 /* Return number of frames there */
1231 *latency = delay / s->play.frame_size;
1232 return CUBEB_OK;
1233 }
1234
1235 static int
oss_stream_set_volume(cubeb_stream * stream,float volume)1236 oss_stream_set_volume(cubeb_stream * stream, float volume)
1237 {
1238 if (volume < 0.0)
1239 volume = 0.0;
1240 else if (volume > 1.0)
1241 volume = 1.0;
1242 pthread_mutex_lock(&stream->mtx);
1243 stream->volume = volume;
1244 pthread_mutex_unlock(&stream->mtx);
1245 return CUBEB_OK;
1246 }
1247
1248 static int
oss_get_current_device(cubeb_stream * stream,cubeb_device ** const device)1249 oss_get_current_device(cubeb_stream * stream, cubeb_device ** const device)
1250 {
1251 *device = calloc(1, sizeof(cubeb_device));
1252 if (*device == NULL) {
1253 return CUBEB_ERROR;
1254 }
1255 (*device)->input_name = stream->record.fd != -1 ?
1256 strdup(stream->record.name) : NULL;
1257 (*device)->output_name = stream->play.fd != -1 ?
1258 strdup(stream->play.name) : NULL;
1259 return CUBEB_OK;
1260 }
1261
1262 static int
oss_stream_device_destroy(cubeb_stream * stream,cubeb_device * device)1263 oss_stream_device_destroy(cubeb_stream * stream, cubeb_device * device)
1264 {
1265 (void)stream;
1266 free(device->input_name);
1267 free(device->output_name);
1268 free(device);
1269 return CUBEB_OK;
1270 }
1271
1272 static struct cubeb_ops const oss_ops = {
1273 .init = oss_init,
1274 .get_backend_id = oss_get_backend_id,
1275 .get_max_channel_count = oss_get_max_channel_count,
1276 .get_min_latency = oss_get_min_latency,
1277 .get_preferred_sample_rate = oss_get_preferred_sample_rate,
1278 .enumerate_devices = oss_enumerate_devices,
1279 .device_collection_destroy = oss_device_collection_destroy,
1280 .destroy = oss_destroy,
1281 .stream_init = oss_stream_init,
1282 .stream_destroy = oss_stream_destroy,
1283 .stream_start = oss_stream_start,
1284 .stream_stop = oss_stream_stop,
1285 .stream_get_position = oss_stream_get_position,
1286 .stream_get_latency = oss_stream_get_latency,
1287 .stream_get_input_latency = NULL,
1288 .stream_set_volume = oss_stream_set_volume,
1289 .stream_set_name = NULL,
1290 .stream_get_current_device = oss_get_current_device,
1291 .stream_device_destroy = oss_stream_device_destroy,
1292 .stream_register_device_changed_callback = NULL,
1293 .register_device_collection_changed = NULL};
1294