1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (c) 2005-2009 Ariff Abdullah <ariff@FreeBSD.org>
5 * Copyright (c) 1999 Cameron Grant <cg@FreeBSD.org>
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#ifdef HAVE_KERNEL_OPTION_HEADERS
31#include "opt_snd.h"
32#endif
33
34#include <dev/sound/pcm/sound.h>
35
36#include "feeder_if.h"
37
38SND_DECLARE_FILE("$FreeBSD$");
39
40static MALLOC_DEFINE(M_FEEDER, "feeder", "pcm feeder");
41
42#define MAXFEEDERS 	256
43#undef FEEDER_DEBUG
44
45struct feedertab_entry {
46	SLIST_ENTRY(feedertab_entry) link;
47	struct feeder_class *feederclass;
48	struct pcm_feederdesc *desc;
49
50	int idx;
51};
52static SLIST_HEAD(, feedertab_entry) feedertab;
53
54/*****************************************************************************/
55
56void
57feeder_register(void *p)
58{
59	static int feedercnt = 0;
60
61	struct feeder_class *fc = p;
62	struct feedertab_entry *fte;
63	int i;
64
65	if (feedercnt == 0) {
66		KASSERT(fc->desc == NULL, ("first feeder not root: %s", fc->name));
67
68		SLIST_INIT(&feedertab);
69		fte = malloc(sizeof(*fte), M_FEEDER, M_NOWAIT | M_ZERO);
70		if (fte == NULL) {
71			printf("can't allocate memory for root feeder: %s\n",
72			    fc->name);
73
74			return;
75		}
76		fte->feederclass = fc;
77		fte->desc = NULL;
78		fte->idx = feedercnt;
79		SLIST_INSERT_HEAD(&feedertab, fte, link);
80		feedercnt++;
81
82		/* initialize global variables */
83
84		if (snd_verbose < 0 || snd_verbose > 4)
85			snd_verbose = 1;
86
87		/* initialize unit numbering */
88		snd_unit_init();
89		if (snd_unit < 0 || snd_unit > PCMMAXUNIT)
90			snd_unit = -1;
91
92		if (snd_maxautovchans < 0 ||
93		    snd_maxautovchans > SND_MAXVCHANS)
94			snd_maxautovchans = 0;
95
96		if (chn_latency < CHN_LATENCY_MIN ||
97		    chn_latency > CHN_LATENCY_MAX)
98			chn_latency = CHN_LATENCY_DEFAULT;
99
100		if (chn_latency_profile < CHN_LATENCY_PROFILE_MIN ||
101		    chn_latency_profile > CHN_LATENCY_PROFILE_MAX)
102			chn_latency_profile = CHN_LATENCY_PROFILE_DEFAULT;
103
104		if (feeder_rate_min < FEEDRATE_MIN ||
105			    feeder_rate_max < FEEDRATE_MIN ||
106			    feeder_rate_min > FEEDRATE_MAX ||
107			    feeder_rate_max > FEEDRATE_MAX ||
108			    !(feeder_rate_min < feeder_rate_max)) {
109			feeder_rate_min = FEEDRATE_RATEMIN;
110			feeder_rate_max = FEEDRATE_RATEMAX;
111		}
112
113		if (feeder_rate_round < FEEDRATE_ROUNDHZ_MIN ||
114		    	    feeder_rate_round > FEEDRATE_ROUNDHZ_MAX)
115			feeder_rate_round = FEEDRATE_ROUNDHZ;
116
117		if (bootverbose)
118			printf("%s: snd_unit=%d snd_maxautovchans=%d "
119			    "latency=%d "
120			    "feeder_rate_min=%d feeder_rate_max=%d "
121			    "feeder_rate_round=%d\n",
122			    __func__, snd_unit, snd_maxautovchans,
123			    chn_latency,
124			    feeder_rate_min, feeder_rate_max,
125			    feeder_rate_round);
126
127		/* we've got our root feeder so don't veto pcm loading anymore */
128		pcm_veto_load = 0;
129
130		return;
131	}
132
133	KASSERT(fc->desc != NULL, ("feeder '%s' has no descriptor", fc->name));
134
135	/* beyond this point failure is non-fatal but may result in some translations being unavailable */
136	i = 0;
137	while ((feedercnt < MAXFEEDERS) && (fc->desc[i].type > 0)) {
138		/* printf("adding feeder %s, %x -> %x\n", fc->name, fc->desc[i].in, fc->desc[i].out); */
139		fte = malloc(sizeof(*fte), M_FEEDER, M_NOWAIT | M_ZERO);
140		if (fte == NULL) {
141			printf("can't allocate memory for feeder '%s', %x -> %x\n", fc->name, fc->desc[i].in, fc->desc[i].out);
142
143			return;
144		}
145		fte->feederclass = fc;
146		fte->desc = &fc->desc[i];
147		fte->idx = feedercnt;
148		fte->desc->idx = feedercnt;
149		SLIST_INSERT_HEAD(&feedertab, fte, link);
150		i++;
151	}
152	feedercnt++;
153	if (feedercnt >= MAXFEEDERS)
154		printf("MAXFEEDERS (%d >= %d) exceeded\n", feedercnt, MAXFEEDERS);
155}
156
157static void
158feeder_unregisterall(void *p)
159{
160	struct feedertab_entry *fte, *next;
161
162	next = SLIST_FIRST(&feedertab);
163	while (next != NULL) {
164		fte = next;
165		next = SLIST_NEXT(fte, link);
166		free(fte, M_FEEDER);
167	}
168}
169
170static int
171cmpdesc(struct pcm_feederdesc *n, struct pcm_feederdesc *m)
172{
173	return ((n->type == m->type) &&
174		((n->in == 0) || (n->in == m->in)) &&
175		((n->out == 0) || (n->out == m->out)) &&
176		(n->flags == m->flags));
177}
178
179static void
180feeder_destroy(struct pcm_feeder *f)
181{
182	FEEDER_FREE(f);
183	kobj_delete((kobj_t)f, M_FEEDER);
184}
185
186static struct pcm_feeder *
187feeder_create(struct feeder_class *fc, struct pcm_feederdesc *desc)
188{
189	struct pcm_feeder *f;
190	int err;
191
192	f = (struct pcm_feeder *)kobj_create((kobj_class_t)fc, M_FEEDER, M_NOWAIT | M_ZERO);
193	if (f == NULL)
194		return NULL;
195
196	f->data = fc->data;
197	f->source = NULL;
198	f->parent = NULL;
199	f->class = fc;
200	f->desc = &(f->desc_static);
201
202	if (desc) {
203		*(f->desc) = *desc;
204	} else {
205		f->desc->type = FEEDER_ROOT;
206		f->desc->in = 0;
207		f->desc->out = 0;
208		f->desc->flags = 0;
209		f->desc->idx = 0;
210	}
211
212	err = FEEDER_INIT(f);
213	if (err) {
214		printf("feeder_init(%p) on %s returned %d\n", f, fc->name, err);
215		feeder_destroy(f);
216
217		return NULL;
218	}
219
220	return f;
221}
222
223struct feeder_class *
224feeder_getclass(struct pcm_feederdesc *desc)
225{
226	struct feedertab_entry *fte;
227
228	SLIST_FOREACH(fte, &feedertab, link) {
229		if ((desc == NULL) && (fte->desc == NULL))
230			return fte->feederclass;
231		if ((fte->desc != NULL) && (desc != NULL) && cmpdesc(desc, fte->desc))
232			return fte->feederclass;
233	}
234	return NULL;
235}
236
237int
238chn_addfeeder(struct pcm_channel *c, struct feeder_class *fc, struct pcm_feederdesc *desc)
239{
240	struct pcm_feeder *nf;
241
242	nf = feeder_create(fc, desc);
243	if (nf == NULL)
244		return ENOSPC;
245
246	nf->source = c->feeder;
247
248	if (c->feeder != NULL)
249		c->feeder->parent = nf;
250	c->feeder = nf;
251
252	return 0;
253}
254
255int
256chn_removefeeder(struct pcm_channel *c)
257{
258	struct pcm_feeder *f;
259
260	if (c->feeder == NULL)
261		return -1;
262	f = c->feeder;
263	c->feeder = c->feeder->source;
264	feeder_destroy(f);
265
266	return 0;
267}
268
269struct pcm_feeder *
270chn_findfeeder(struct pcm_channel *c, u_int32_t type)
271{
272	struct pcm_feeder *f;
273
274	f = c->feeder;
275	while (f != NULL) {
276		if (f->desc->type == type)
277			return f;
278		f = f->source;
279	}
280
281	return NULL;
282}
283
284/*
285 * 14bit format scoring
286 * --------------------
287 *
288 *  13  12  11  10   9   8        2        1   0    offset
289 * +---+---+---+---+---+---+-------------+---+---+
290 * | X | X | X | X | X | X | X X X X X X | X | X |
291 * +---+---+---+---+---+---+-------------+---+---+
292 *   |   |   |   |   |   |        |        |   |
293 *   |   |   |   |   |   |        |        |   +--> signed?
294 *   |   |   |   |   |   |        |        |
295 *   |   |   |   |   |   |        |        +------> bigendian?
296 *   |   |   |   |   |   |        |
297 *   |   |   |   |   |   |        +---------------> total channels
298 *   |   |   |   |   |   |
299 *   |   |   |   |   |   +------------------------> AFMT_A_LAW
300 *   |   |   |   |   |
301 *   |   |   |   |   +----------------------------> AFMT_MU_LAW
302 *   |   |   |   |
303 *   |   |   |   +--------------------------------> AFMT_8BIT
304 *   |   |   |
305 *   |   |   +------------------------------------> AFMT_16BIT
306 *   |   |
307 *   |   +----------------------------------------> AFMT_24BIT
308 *   |
309 *   +--------------------------------------------> AFMT_32BIT
310 */
311#define score_signeq(s1, s2)	(((s1) & 0x1) == ((s2) & 0x1))
312#define score_endianeq(s1, s2)	(((s1) & 0x2) == ((s2) & 0x2))
313#define score_cheq(s1, s2)	(((s1) & 0xfc) == ((s2) & 0xfc))
314#define score_chgt(s1, s2)	(((s1) & 0xfc) > ((s2) & 0xfc))
315#define score_chlt(s1, s2)	(((s1) & 0xfc) < ((s2) & 0xfc))
316#define score_val(s1)		((s1) & 0x3f00)
317#define score_cse(s1)		((s1) & 0x7f)
318
319u_int32_t
320snd_fmtscore(u_int32_t fmt)
321{
322	u_int32_t ret;
323
324	ret = 0;
325	if (fmt & AFMT_SIGNED)
326		ret |= 1 << 0;
327	if (fmt & AFMT_BIGENDIAN)
328		ret |= 1 << 1;
329	/*if (fmt & AFMT_STEREO)
330		ret |= (2 & 0x3f) << 2;
331	else
332		ret |= (1 & 0x3f) << 2;*/
333	ret |= (AFMT_CHANNEL(fmt) & 0x3f) << 2;
334	if (fmt & AFMT_A_LAW)
335		ret |= 1 << 8;
336	else if (fmt & AFMT_MU_LAW)
337		ret |= 1 << 9;
338	else if (fmt & AFMT_8BIT)
339		ret |= 1 << 10;
340	else if (fmt & AFMT_16BIT)
341		ret |= 1 << 11;
342	else if (fmt & AFMT_24BIT)
343		ret |= 1 << 12;
344	else if (fmt & AFMT_32BIT)
345		ret |= 1 << 13;
346
347	return ret;
348}
349
350static u_int32_t
351snd_fmtbestfunc(u_int32_t fmt, u_int32_t *fmts, int cheq)
352{
353	u_int32_t best, score, score2, oldscore;
354	int i;
355
356	if (fmt == 0 || fmts == NULL || fmts[0] == 0)
357		return 0;
358
359	if (snd_fmtvalid(fmt, fmts))
360		return fmt;
361
362	best = 0;
363	score = snd_fmtscore(fmt);
364	oldscore = 0;
365	for (i = 0; fmts[i] != 0; i++) {
366		score2 = snd_fmtscore(fmts[i]);
367		if (cheq && !score_cheq(score, score2) &&
368		    (score_chlt(score2, score) ||
369		    (oldscore != 0 && score_chgt(score2, oldscore))))
370				continue;
371		if (oldscore == 0 ||
372			    (score_val(score2) == score_val(score)) ||
373			    (score_val(score2) == score_val(oldscore)) ||
374			    (score_val(score2) > score_val(oldscore) &&
375			    score_val(score2) < score_val(score)) ||
376			    (score_val(score2) < score_val(oldscore) &&
377			    score_val(score2) > score_val(score)) ||
378			    (score_val(oldscore) < score_val(score) &&
379			    score_val(score2) > score_val(oldscore))) {
380			if (score_val(oldscore) != score_val(score2) ||
381				    score_cse(score) == score_cse(score2) ||
382				    ((score_cse(oldscore) != score_cse(score) &&
383				    !score_endianeq(score, oldscore) &&
384				    (score_endianeq(score, score2) ||
385				    (!score_signeq(score, oldscore) &&
386				    score_signeq(score, score2)))))) {
387				best = fmts[i];
388				oldscore = score2;
389			}
390		}
391	}
392	return best;
393}
394
395u_int32_t
396snd_fmtbestbit(u_int32_t fmt, u_int32_t *fmts)
397{
398	return snd_fmtbestfunc(fmt, fmts, 0);
399}
400
401u_int32_t
402snd_fmtbestchannel(u_int32_t fmt, u_int32_t *fmts)
403{
404	return snd_fmtbestfunc(fmt, fmts, 1);
405}
406
407u_int32_t
408snd_fmtbest(u_int32_t fmt, u_int32_t *fmts)
409{
410	u_int32_t best1, best2;
411	u_int32_t score, score1, score2;
412
413	if (snd_fmtvalid(fmt, fmts))
414		return fmt;
415
416	best1 = snd_fmtbestchannel(fmt, fmts);
417	best2 = snd_fmtbestbit(fmt, fmts);
418
419	if (best1 != 0 && best2 != 0 && best1 != best2) {
420		/*if (fmt & AFMT_STEREO)*/
421		if (AFMT_CHANNEL(fmt) > 1)
422			return best1;
423		else {
424			score = score_val(snd_fmtscore(fmt));
425			score1 = score_val(snd_fmtscore(best1));
426			score2 = score_val(snd_fmtscore(best2));
427			if (score1 == score2 || score1 == score)
428				return best1;
429			else if (score2 == score)
430				return best2;
431			else if (score1 > score2)
432				return best1;
433			return best2;
434		}
435	} else if (best2 == 0)
436		return best1;
437	else
438		return best2;
439}
440
441void
442feeder_printchain(struct pcm_feeder *head)
443{
444	struct pcm_feeder *f;
445
446	printf("feeder chain (head @%p)\n", head);
447	f = head;
448	while (f != NULL) {
449		printf("%s/%d @ %p\n", f->class->name, f->desc->idx, f);
450		f = f->source;
451	}
452	printf("[end]\n\n");
453}
454
455/*****************************************************************************/
456
457static int
458feed_root(struct pcm_feeder *feeder, struct pcm_channel *ch, u_int8_t *buffer, u_int32_t count, void *source)
459{
460	struct snd_dbuf *src = source;
461	int l, offset;
462
463	KASSERT(count > 0, ("feed_root: count == 0"));
464
465	if (++ch->feedcount == 0)
466		ch->feedcount = 2;
467
468	l = min(count, sndbuf_getready(src));
469
470	/* When recording only return as much data as available */
471	if (ch->direction == PCMDIR_REC) {
472		sndbuf_dispose(src, buffer, l);
473		return l;
474	}
475
476
477	offset = count - l;
478
479	if (offset > 0) {
480		if (snd_verbose > 3)
481			printf("%s: (%s) %spending %d bytes "
482			    "(count=%d l=%d feed=%d)\n",
483			    __func__,
484			    (ch->flags & CHN_F_VIRTUAL) ? "virtual" : "hardware",
485			    (ch->feedcount == 1) ? "pre" : "ap",
486			    offset, count, l, ch->feedcount);
487
488		if (ch->feedcount == 1) {
489			memset(buffer,
490			    sndbuf_zerodata(sndbuf_getfmt(src)),
491			    offset);
492			if (l > 0)
493				sndbuf_dispose(src, buffer + offset, l);
494			else
495				ch->feedcount--;
496		} else {
497			if (l > 0)
498				sndbuf_dispose(src, buffer, l);
499			memset(buffer + l,
500			    sndbuf_zerodata(sndbuf_getfmt(src)),
501			    offset);
502			if (!(ch->flags & CHN_F_CLOSING))
503				ch->xruns++;
504		}
505	} else if (l > 0)
506		sndbuf_dispose(src, buffer, l);
507
508	return count;
509}
510
511static kobj_method_t feeder_root_methods[] = {
512    	KOBJMETHOD(feeder_feed,		feed_root),
513	KOBJMETHOD_END
514};
515static struct feeder_class feeder_root_class = {
516	.name =		"feeder_root",
517	.methods =	feeder_root_methods,
518	.size =		sizeof(struct pcm_feeder),
519	.desc =		NULL,
520	.data =		NULL,
521};
522SYSINIT(feeder_root, SI_SUB_DRIVERS, SI_ORDER_FIRST, feeder_register, &feeder_root_class);
523SYSUNINIT(feeder_root, SI_SUB_DRIVERS, SI_ORDER_FIRST, feeder_unregisterall, NULL);
524