summaryrefslogtreecommitdiff
path: root/modules/speex/speex.c
blob: 66a7ff453eae97d88f8dda4097c709ae6dd9c58a (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
/**
 * @file speex.c  Speex audio codec
 *
 * Copyright (C) 2010 Creytiv.com
 */
#include <stdlib.h>
#include <speex/speex.h>
#include <speex/speex_stereo.h>
#include <speex/speex_callbacks.h>
#include <re.h>
#include <baresip.h>


/**
 * @defgroup speex speex
 *
 * The Speex audio codec
 *
 * NOTE: The Speex codec has been obsoleted by Opus.
 */


enum {
	MIN_FRAME_SIZE = 43,
	SPEEX_PTIME    = 20,
};


struct auenc_state {
	void *enc;
	SpeexBits bits;

	uint32_t frame_size;  /* Number of sample-frames */
	uint8_t channels;
};


struct audec_state {
	void *dec;
	SpeexBits bits;
	SpeexStereoState stereo;
	SpeexCallback callback;

	uint32_t frame_size;  /* Number of sample-frames */
	uint8_t channels;
};


static char speex_fmtp_nb[128];
static char speex_fmtp_wb[128];


/** Speex configuration */
static struct {
	int quality;
	int complexity;
	int enhancement;
	int mode_nb;
	int mode_wb;
	int vbr;
	int vad;
} sconf = {
	3,  /* 0-10   */
	2,  /* 0-10   */
	0,  /* 0 or 1 */
	3,  /* 1-6    */
	6,  /* 1-6    */
	0,  /* 0 or 1 */
	0   /* 0 or 1 */
};


static void encode_destructor(void *arg)
{
	struct auenc_state *st = arg;

	speex_bits_destroy(&st->bits);
	speex_encoder_destroy(st->enc);
}


static void decode_destructor(void *arg)
{
	struct audec_state *st = arg;

	speex_bits_destroy(&st->bits);
	speex_decoder_destroy(st->dec);
}


static void encoder_config(void *st)
{
	int ret;

	ret = speex_encoder_ctl(st, SPEEX_SET_QUALITY, &sconf.quality);
	if (ret) {
		warning("speex: SPEEX_SET_QUALITY: %d\n", ret);
	}

	ret = speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &sconf.complexity);
	if (ret) {
		warning("speex: SPEEX_SET_COMPLEXITY: %d\n", ret);
	}

	ret = speex_encoder_ctl(st, SPEEX_SET_VBR, &sconf.vbr);
	if (ret) {
		warning("speex: SPEEX_SET_VBR: %d\n", ret);
	}

	ret = speex_encoder_ctl(st, SPEEX_SET_VAD, &sconf.vad);
	if (ret) {
		warning("speex: SPEEX_SET_VAD: %d\n", ret);
	}
}


static void decoder_config(void *st)
{
	int ret;

	ret = speex_decoder_ctl(st, SPEEX_SET_ENH, &sconf.enhancement);
	if (ret) {
		warning("speex: SPEEX_SET_ENH: %d\n", ret);
	}
}


static int decode_param(struct auenc_state *st, const struct pl *name,
			const struct pl *val)
{
	int ret;

	/* mode: List supported Speex decoding modes.  The valid modes are
	   different for narrowband and wideband, and are defined as follows:

	   {1,2,3,4,5,6,any}
	 */
	if (0 == pl_strcasecmp(name, "mode")) {
		struct pl v;
		int mode;

		/* parameter is quoted */
		if (re_regex(val->p, val->l, "\"[^\"]+\"", &v))
			v = *val;

		if (0 == pl_strcasecmp(&v, "any"))
			return 0;

		mode = pl_u32(&v);

		ret = speex_encoder_ctl(st->enc, SPEEX_SET_MODE, &mode);
		if (ret) {
			warning("speex: SPEEX_SET_MODE: ret=%d\n", ret);
		}
	}
	/* vbr: variable bit rate - either 'on' 'off' or 'vad' */
	else if (0 == pl_strcasecmp(name, "vbr")) {
		int vbr = 0, vad = 0;

		if (0 == pl_strcasecmp(val, "on"))
			vbr = 1;
		else if (0 == pl_strcasecmp(val, "off"))
			vbr = 0;
		else if (0 == pl_strcasecmp(val, "vad"))
			vad = 1;
		else {
			warning("speex: invalid vbr value %r\n", val);
		}

		debug("speex: setting VBR=%d VAD=%d\n", vbr, vad);
		ret = speex_encoder_ctl(st->enc, SPEEX_SET_VBR, &vbr);
		if (ret) {
			warning("speex: SPEEX_SET_VBR: ret=%d\n", ret);
		}
		ret = speex_encoder_ctl(st->enc, SPEEX_SET_VAD, &vad);
		if (ret) {
			warning("speex: SPEEX_SET_VAD: ret=%d\n", ret);
		}
	}
	else if (0 == pl_strcasecmp(name, "cng")) {
		int dtx = 0;

		if (0 == pl_strcasecmp(val, "on"))
			dtx = 0;
		else if (0 == pl_strcasecmp(val, "off"))
			dtx = 1;

		ret = speex_encoder_ctl(st->enc, SPEEX_SET_DTX, &dtx);
		if (ret) {
			warning("speex: SPEEX_SET_DTX: ret=%d\n", ret);
		}
	}
	else {
		debug("speex: unknown Speex param: %r=%r\n", name, val);
	}

	return 0;
}


static void param_handler(const struct pl *name, const struct pl *val,
			  void *arg)
{
	struct auenc_state *st = arg;

	decode_param(st, name, val);
}


static const SpeexMode *resolve_mode(uint32_t srate)
{
	switch (srate) {

	default:
	case 8000:  return &speex_nb_mode;
	case 16000: return &speex_wb_mode;
	case 32000: return &speex_uwb_mode;
	}
}


static int encode_update(struct auenc_state **aesp, const struct aucodec *ac,
			 struct auenc_param *prm, const char *fmtp)
{
	struct auenc_state *st;
	int ret, err = 0;

	if (!aesp || !ac || !prm)
		return EINVAL;
	if (prm->ptime != SPEEX_PTIME)
		return EPROTO;
	if (*aesp)
		return 0;

	st = mem_zalloc(sizeof(*st), encode_destructor);
	if (!st)
		return ENOMEM;

	st->frame_size = ac->srate * SPEEX_PTIME / 1000;
	st->channels = ac->ch;

	/* Encoder */
	st->enc = speex_encoder_init(resolve_mode(ac->srate));
	if (!st->enc) {
		err = ENOMEM;
		goto out;
	}

	speex_bits_init(&st->bits);

	encoder_config(st->enc);

	ret = speex_encoder_ctl(st->enc, SPEEX_GET_FRAME_SIZE,
				&st->frame_size);
	if (ret) {
		warning("speex: SPEEX_GET_FRAME_SIZE: %d\n", ret);
	}

	if (str_isset(fmtp)) {
		struct pl params;

		pl_set_str(&params, fmtp);

		fmt_param_apply(&params, param_handler, st);
	}

 out:
	if (err)
		mem_deref(st);
	else
		*aesp = st;

	return err;
}


static int decode_update(struct audec_state **adsp,
			 const struct aucodec *ac, const char *fmtp)
{
	struct audec_state *st;
	int err = 0;
	(void)fmtp;

	if (!adsp || !ac)
		return EINVAL;
	if (*adsp)
		return 0;

	st = mem_zalloc(sizeof(*st), decode_destructor);
	if (!st)
		return ENOMEM;

	st->frame_size = ac->srate * SPEEX_PTIME / 1000;
	st->channels = ac->ch;

	/* Decoder */
	st->dec = speex_decoder_init(resolve_mode(ac->srate));
	if (!st->dec) {
		err = ENOMEM;
		goto out;
	}

	speex_bits_init(&st->bits);

	if (2 == st->channels) {

		/* Stereo. */
		st->stereo.balance = 1;
		st->stereo.e_ratio = .5f;
		st->stereo.smooth_left = 1;
		st->stereo.smooth_right = 1;

		st->callback.callback_id = SPEEX_INBAND_STEREO;
		st->callback.func = speex_std_stereo_request_handler;
		st->callback.data = &st->stereo;
		speex_decoder_ctl(st->dec, SPEEX_SET_HANDLER,
				  &st->callback);
	}

	decoder_config(st->dec);

 out:
	if (err)
		mem_deref(st);
	else
		*adsp = st;

	return err;
}


static int encode(struct auenc_state *st, uint8_t *buf,
		  size_t *len, const int16_t *sampv, size_t sampc)
{
	const size_t n = st->channels * st->frame_size;
	int ret, r;

	if (*len < 128)
		return ENOMEM;

	/* VAD */
	if (!sampv || !sampc) {
		/* 5 zeros interpreted by Speex as silence (submode 0) */
		speex_bits_pack(&st->bits, 0, 5);
		goto out;
	}

	/* Handle multiple Speex frames in one RTP packet */
	while (sampc > 0) {

		/* Assume stereo */
		if (2 == st->channels) {
			speex_encode_stereo_int((int16_t *)sampv,
						st->frame_size, &st->bits);
		}

		ret = speex_encode_int(st->enc, (int16_t *)sampv, &st->bits);
		if (1 != ret) {
			warning("speex: speex_encode_int: ret=%d\n", ret);
		}

		sampc -= n;
		sampv += n;
	}

 out:
	/* Terminate bit stream */
	speex_bits_pack(&st->bits, 15, 5);

	r = speex_bits_write(&st->bits, (char *)buf, (int)*len);
	*len = r;

	speex_bits_reset(&st->bits);

	return 0;
}


static int decode(struct audec_state *st, int16_t *sampv,
		  size_t *sampc, const uint8_t *buf, size_t len)
{
	const size_t n = st->channels * st->frame_size;
	size_t i = 0;

	/* Read into bit-stream */
	speex_bits_read_from(&st->bits, (char *)buf, (int)len);

	/* Handle multiple Speex frames in one RTP packet */
	while (speex_bits_remaining(&st->bits) >= MIN_FRAME_SIZE) {
		int ret;

		if (*sampc < n)
			return ENOMEM;

		ret = speex_decode_int(st->dec, &st->bits,
				       (int16_t *)&sampv[i]);
		if (ret < 0) {
			if (-1 == ret) {
			}
			else if (-2 == ret) {
				warning("speex: decode: corrupt stream\n");
			}
			else {
				warning("speex: decode: speex_decode_int:"
					" ret=%d\n", ret);
			}
			break;
		}

		/* Transforms a mono frame into a stereo frame
		   using intensity stereo info */
		if (2 == st->channels) {
			speex_decode_stereo_int((int16_t *)&sampv[i],
						st->frame_size,
						&st->stereo);
		}

		i      += n;
		*sampc -= n;
	}

	*sampc = i;

	return 0;
}


static int pkloss(struct audec_state *st, int16_t *sampv, size_t *sampc)
{
	const size_t n = st->channels * st->frame_size;

	if (*sampc < n)
		return ENOMEM;

	/* Silence */
	speex_decode_int(st->dec, NULL, sampv);
	*sampc = n;

	return 0;
}


static void config_parse(struct conf *conf)
{
	uint32_t v;

	if (0 == conf_get_u32(conf, "speex_quality", &v))
		sconf.quality = v;
	if (0 == conf_get_u32(conf, "speex_complexity", &v))
		sconf.complexity = v;
	if (0 == conf_get_u32(conf, "speex_enhancement", &v))
		sconf.enhancement = v;
	if (0 == conf_get_u32(conf, "speex_mode_nb", &v))
		sconf.mode_nb = v;
	if (0 == conf_get_u32(conf, "speex_mode_wb", &v))
		sconf.mode_wb = v;
	if (0 == conf_get_u32(conf, "speex_vbr", &v))
		sconf.vbr = v;
	if (0 == conf_get_u32(conf, "speex_vad", &v))
		sconf.vad = v;
}


static struct aucodec speexv[] = {

	/* Stereo Speex */
	{LE_INIT, 0, "speex", 32000, 32000, 2, speex_fmtp_wb,
	 encode_update, encode, decode_update, decode, pkloss, 0, 0, 0, 0},
	{LE_INIT, 0, "speex", 16000, 16000, 2, speex_fmtp_wb,
	 encode_update, encode, decode_update, decode, pkloss, 0, 0, 0, 0},
	{LE_INIT, 0, "speex",  8000,  8000, 2, speex_fmtp_nb,
	 encode_update, encode, decode_update, decode, pkloss, 0, 0, 0, 0},

	/* Standard Speex */
	{LE_INIT, 0, "speex", 32000, 32000, 1, speex_fmtp_wb,
	 encode_update, encode, decode_update, decode, pkloss, 0, 0, 0, 0},
	{LE_INIT, 0, "speex", 16000, 16000, 1, speex_fmtp_wb,
	 encode_update, encode, decode_update, decode, pkloss, 0, 0, 0, 0},
	{LE_INIT, 0, "speex",  8000,  8000, 1, speex_fmtp_nb,
	 encode_update, encode, decode_update, decode, pkloss, 0, 0, 0, 0},
};


static int speex_init(void)
{
	size_t i;

	config_parse(conf_cur());

	(void)re_snprintf(speex_fmtp_nb, sizeof(speex_fmtp_nb),
			  "mode=\"%d\";vbr=%s;cng=on", sconf.mode_nb,
			  sconf.vad ? "vad" : (sconf.vbr ? "on" : "off"));

	(void)re_snprintf(speex_fmtp_wb, sizeof(speex_fmtp_wb),
			  "mode=\"%d\";vbr=%s;cng=on", sconf.mode_wb,
			  sconf.vad ? "vad" : (sconf.vbr ? "on" : "off"));

	for (i=0; i<ARRAY_SIZE(speexv); i++)
		aucodec_register(baresip_aucodecl(), &speexv[i]);

	return 0;
}


static int speex_close(void)
{
	size_t i;
	for (i=0; i<ARRAY_SIZE(speexv); i++)
		aucodec_unregister(&speexv[i]);
	return 0;
}


EXPORT_SYM const struct mod_export DECL_EXPORTS(speex) = {
	"speex",
	"codec",
	speex_init,
	speex_close
};