Debian Codegraph @

Xpjproject/pjmedia/src/pjmedia-codec/opus.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2015-2016 Teluu Inc. (http://www.teluu.com)
3 * Copyright (C) 2012-2015 Zaark Technology AB
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 /* This file is the implementation of Opus codec wrapper and was contributed by
20 * Zaark Technology AB
21 */
22
23 #include <pjmedia-codec/opus.h>
24 #include <pjmedia/errno.h>
25 #include <pjmedia/endpoint.h>
26 #include <pj/log.h>
27 #include <pj/math.h>
28
29 #if defined(PJMEDIA_HAS_OPUS_CODEC) && (PJMEDIA_HAS_OPUS_CODEC!=0)
30
31 #include <opus/opus.h>
32
33 #define THIS_FILE "opus.c"
34
35 /* Default packet loss concealment setting. */
36 #define OPUS_DEFAULT_PLC 1
37 /* Default Voice Activity Detector setting. */
38 #define OPUS_DEFAULT_VAD 0
39
40 /* Maximum size of an encoded packet.
41 * If the the actual size is bigger, the encode/parse will fail.
42 */
43 #define MAX_ENCODED_PACKET_SIZE 1280
44
45 /* Default frame time (msec) */
46 #define PTIME 20
47 #define PTIME_DENUM 1
48
49 /* Tracing */
50 #if 0
51 # define TRACE_(expr) PJ_LOG(4,expr)
52 #else
53 # define TRACE_(expr)
54 #endif
55
56
57 /* Prototypes for Opus factory */
58 static pj_status_t factory_test_alloc( pjmedia_codec_factory *factory,
59 const pjmedia_codec_info *ci );
60 static pj_status_t factory_default_attr( pjmedia_codec_factory *factory,
61 const pjmedia_codec_info *ci,
62 pjmedia_codec_param *attr );
63 static pj_status_t factory_enum_codecs( pjmedia_codec_factory *factory,
64 unsigned *count,
65 pjmedia_codec_info codecs[]);
66 static pj_status_t factory_alloc_codec( pjmedia_codec_factory *factory,
67 const pjmedia_codec_info *ci,
68 pjmedia_codec **p_codec);
69 static pj_status_t factory_dealloc_codec( pjmedia_codec_factory *factory,
70 pjmedia_codec *codec );
71
72
73 /* Prototypes for Opus implementation. */
74 static pj_status_t codec_init( pjmedia_codec *codec,
75 pj_pool_t *pool );
76 static pj_status_t codec_open( pjmedia_codec *codec,
77 pjmedia_codec_param *attr );
78 static pj_status_t codec_close( pjmedia_codec *codec );
79 static pj_status_t codec_modify( pjmedia_codec *codec,
80 const pjmedia_codec_param *attr );
81 static pj_status_t codec_parse( pjmedia_codec *codec,
82 void *pkt,
83 pj_size_t pkt_size,
84 const pj_timestamp *ts,
85 unsigned *frame_cnt,
86 pjmedia_frame frames[]);
87 static pj_status_t codec_encode( pjmedia_codec *codec,
88 const struct pjmedia_frame *input,
89 unsigned output_buf_len,
90 struct pjmedia_frame *output);
91 static pj_status_t codec_decode( pjmedia_codec *codec,
92 const struct pjmedia_frame *input,
93 unsigned output_buf_len,
94 struct pjmedia_frame *output);
95 static pj_status_t codec_recover( pjmedia_codec *codec,
96 unsigned output_buf_len,
97 struct pjmedia_frame *output);
98
99 /* Definition for Opus operations. */
100 static pjmedia_codec_op opus_op =
101 {
102 &codec_init,
103 &codec_open,
104 &codec_close,
105 &codec_modify,
106 &codec_parse,
107 &codec_encode,
108 &codec_decode,
109 &codec_recover
110 };
111
112 /* Definition for Opus factory operations. */
113 static pjmedia_codec_factory_op opus_factory_op =
114 {
115 &factory_test_alloc,
116 &factory_default_attr,
117 &factory_enum_codecs,
118 &factory_alloc_codec,
119 &factory_dealloc_codec,
120 &pjmedia_codec_opus_deinit
121 };
122
123
124 /* Opus factory */
125 struct opus_codec_factory
126 {
127 pjmedia_codec_factory base;
128 pjmedia_endpt *endpt;
129 pj_pool_t *pool;
130 };
131
132 /* Opus codec private data. */
133 struct opus_data
134 {
135 pj_pool_t *pool;
136 pj_mutex_t *mutex;
137 OpusEncoder *enc;
138 OpusDecoder *dec;
139 OpusRepacketizer *enc_packer;
140 OpusRepacketizer *dec_packer;
141 pjmedia_codec_opus_config cfg;
142 unsigned enc_ptime;
143 unsigned enc_ptime_denum;
144 unsigned dec_ptime;
145 unsigned dec_ptime_denum;
146 pjmedia_frame dec_frame[2];
147 int dec_frame_index;
148 pj_size_t dec_frame_buf_size;
149 };
150
151 /* Codec factory instance */
152 static struct opus_codec_factory opus_codec_factory;
153
154 /* Opus default configuration */
155 static pjmedia_codec_opus_config opus_cfg =
156 {
157 PJMEDIA_CODEC_OPUS_DEFAULT_SAMPLE_RATE, /* Sample rate */
158 1, /* Channel count */
159 PTIME, /* Frame ptime */
160 PTIME_DENUM, /* Frame ptime denum */
161 PJMEDIA_CODEC_OPUS_DEFAULT_BIT_RATE, /* Bit rate */
162 5, /* Expected packet loss */
163 PJMEDIA_CODEC_OPUS_DEFAULT_COMPLEXITY, /* Complexity */
164 PJMEDIA_CODEC_OPUS_DEFAULT_CBR, /* Constant bit rate */
165 };
166
167
168 static int get_opus_bw_constant (unsigned sample_rate)
169 {
170 if (sample_rate <= 8000)
171 return OPUS_BANDWIDTH_NARROWBAND;
172 else if (sample_rate <= 12000)
173 return OPUS_BANDWIDTH_MEDIUMBAND;
174 else if (sample_rate <= 16000)
175 return OPUS_BANDWIDTH_WIDEBAND;
176 else if (sample_rate <= 24000)
177 return OPUS_BANDWIDTH_SUPERWIDEBAND;
178 else
179 return OPUS_BANDWIDTH_FULLBAND;
180 }
181
182
183 /*
184 * Initialize and register Opus codec factory to pjmedia endpoint.
185 */
186 PJ_DEF(pj_status_t) pjmedia_codec_opus_init( pjmedia_endpt *endpt )
187 {
188 pj_status_t status;
189 pjmedia_codec_mgr *codec_mgr;
190
191 PJ_ASSERT_RETURN(endpt, PJ_EINVAL);
192
193 if (opus_codec_factory.pool != NULL)
194 return PJ_SUCCESS;
195
196 /* Create the Opus codec factory */
197 opus_codec_factory.base.op = &opus_factory_op;
198 opus_codec_factory.base.factory_data = &opus_codec_factory;
199 opus_codec_factory.endpt = endpt;
200
201 opus_codec_factory.pool = pjmedia_endpt_create_pool(endpt, "opus-factory",
202 1024, 1024);
203 if (!opus_codec_factory.pool) {
204 PJ_LOG(2, (THIS_FILE, "Unable to create memory pool for Opus codec"));
205 return PJ_ENOMEM;
206 }
207
208 /* Get the codec manager */
209 codec_mgr = pjmedia_endpt_get_codec_mgr(endpt);
210 if (!codec_mgr) {
211 PJ_LOG(2, (THIS_FILE, "Unable to get the codec manager"));
212 status = PJ_EINVALIDOP;
213 goto on_codec_factory_error;
214 }
215
216 /* Register the codec factory */
217 status = pjmedia_codec_mgr_register_factory (codec_mgr,
218 &opus_codec_factory.base);
219 if (status != PJ_SUCCESS) {
220 PJ_LOG(2, (THIS_FILE, "Unable to register the codec factory"));
221 goto on_codec_factory_error;
222 }
223
224 return PJ_SUCCESS;
225
226 on_codec_factory_error:
227 pj_pool_release(opus_codec_factory.pool);
228 opus_codec_factory.pool = NULL;
229 return status;
230 }
231
232
233 /*
234 * Unregister Opus codec factory from pjmedia endpoint and
235 * deinitialize the codec.
236 */
237 PJ_DEF(pj_status_t) pjmedia_codec_opus_deinit( void )
238 {
239 pj_status_t status;
240 pjmedia_codec_mgr *codec_mgr;
241
242 if (opus_codec_factory.pool == NULL)
243 return PJ_SUCCESS;
244
245 /* Get the codec manager */
246 codec_mgr = pjmedia_endpt_get_codec_mgr(opus_codec_factory.endpt);
247 if (!codec_mgr) {
248 PJ_LOG(2, (THIS_FILE, "Unable to get the codec manager"));
249 pj_pool_release(opus_codec_factory.pool);
250 opus_codec_factory.pool = NULL;
251 return PJ_EINVALIDOP;
252 }
253
254 /* Unregister the codec factory */
255 status = pjmedia_codec_mgr_unregister_factory(codec_mgr,
256 &opus_codec_factory.base);
257 if (status != PJ_SUCCESS)
258 PJ_LOG(2, (THIS_FILE, "Unable to unregister the codec factory"));
259
260 /* Release the memory pool */
261 pj_pool_release(opus_codec_factory.pool);
262 opus_codec_factory.pool = NULL;
263
264 return status;
265 }
266
267
268 /**
269 * Get the opus configuration for a specific sample rate.
270 */
271 PJ_DEF(pj_status_t)
272 pjmedia_codec_opus_get_config( pjmedia_codec_opus_config *cfg )
273 {
274 PJ_ASSERT_RETURN(cfg, PJ_EINVAL);
275
276 pj_memcpy(cfg, &opus_cfg, sizeof(pjmedia_codec_opus_config));
277 return PJ_SUCCESS;
278 }
279
280
281 static pj_str_t STR_MAX_PLAYBACK = {"maxplaybackrate", 15};
282 static pj_str_t STR_MAX_CAPTURE = {"sprop-maxcapturerate", 20};
283 static pj_str_t STR_STEREO = {"stereo", 6};
284 static pj_str_t STR_SPROP_STEREO = {"sprop-stereo", 12};
285 static pj_str_t STR_MAX_BIT_RATE = {"maxaveragebitrate", 17};
286 static pj_str_t STR_INBAND_FEC = {"useinbandfec", 12};
287 static pj_str_t STR_DTX = {"usedtx", 6};
288 static pj_str_t STR_CBR = {"cbr", 3};
289
290 static int find_fmtp(pjmedia_codec_fmtp *fmtp, pj_str_t *name, pj_bool_t add)
291 {
292 int i;
293 for (i = 0; i < fmtp->cnt; i++) {
294 if (pj_stricmp(&fmtp->param[i].name, name) == 0)
295 return i;
296 }
297
298 if (add && (i < PJMEDIA_CODEC_MAX_FMTP_CNT)) {
299 fmtp->param[i].name = *name;
300 fmtp->cnt++;
301 return i;
302 } else
303 return -1;
304 }
305
306 static void remove_fmtp(pjmedia_codec_fmtp *fmtp, pj_str_t *name)
307 {
308 int i, j;
309 for (i = 0; i < fmtp->cnt; i++) {
310 if (pj_stricmp(&fmtp->param[i].name, name) == 0) {
311 fmtp->cnt--;
312 for (j = i; j < fmtp->cnt; j++) {
313 fmtp->param[i].name = fmtp->param[i+1].name;
314 fmtp->param[i].val = fmtp->param[i+1].val;
315 }
316 }
317 }
318 }
319
320 static pj_status_t generate_fmtp(pjmedia_codec_param *attr)
321 {
322 int idx;
323 static char bitrate_str[12];
324 static char clockrate_str[12];
325
326 if (attr->info.clock_rate != 48000) {
327 pj_ansi_snprintf(clockrate_str, sizeof(clockrate_str), "%u",
328 attr->info.clock_rate);
329
330 idx = find_fmtp(&attr->setting.dec_fmtp, &STR_MAX_PLAYBACK, PJ_TRUE);
331 if (idx >= 0)
332 attr->setting.dec_fmtp.param[idx].val = pj_str(clockrate_str);
333
334 idx = find_fmtp(&attr->setting.dec_fmtp, &STR_MAX_CAPTURE, PJ_TRUE);
335 if (idx >= 0)
336 attr->setting.dec_fmtp.param[idx].val = pj_str(clockrate_str);
337 } else {
338 remove_fmtp(&attr->setting.dec_fmtp, &STR_MAX_PLAYBACK);
339 remove_fmtp(&attr->setting.dec_fmtp, &STR_MAX_CAPTURE);
340 }
341
342 /* Check if we need to set parameter 'maxaveragebitrate' */
343 if (opus_cfg.bit_rate > 0) {
344 idx = find_fmtp(&attr->setting.dec_fmtp, &STR_MAX_BIT_RATE, PJ_TRUE);
345 if (idx >= 0) {
346 pj_ansi_snprintf(bitrate_str, sizeof(bitrate_str), "%u",
347 attr->info.avg_bps);
348 attr->setting.dec_fmtp.param[idx].val = pj_str(bitrate_str);
349 }
350 } else {
351 remove_fmtp(&attr->setting.dec_fmtp, &STR_MAX_BIT_RATE);
352 }
353
354 if (attr->info.channel_cnt > 1) {
355 idx = find_fmtp(&attr->setting.dec_fmtp, &STR_STEREO, PJ_TRUE);
356 if (idx >= 0)
357 attr->setting.dec_fmtp.param[idx].val = pj_str("1");
358
359 idx = find_fmtp(&attr->setting.dec_fmtp, &STR_SPROP_STEREO, PJ_TRUE);
360 if (idx >= 0)
361 attr->setting.dec_fmtp.param[idx].val = pj_str("1");
362 } else {
363 remove_fmtp(&attr->setting.dec_fmtp, &STR_STEREO);
364 remove_fmtp(&attr->setting.dec_fmtp, &STR_SPROP_STEREO);
365 }
366
367 if (opus_cfg.cbr) {
368 idx = find_fmtp(&attr->setting.dec_fmtp, &STR_CBR, PJ_TRUE);
369 if (idx >= 0)
370 attr->setting.dec_fmtp.param[idx].val = pj_str("1");
371 } else {
372 remove_fmtp(&attr->setting.dec_fmtp, &STR_CBR);
373 }
374
375 if (attr->setting.plc) {
376 idx = find_fmtp(&attr->setting.dec_fmtp, &STR_INBAND_FEC, PJ_TRUE);
377 if (idx >= 0)
378 attr->setting.dec_fmtp.param[idx].val = pj_str("1");
379 } else {
380 remove_fmtp(&attr->setting.dec_fmtp, &STR_INBAND_FEC);
381 }
382
383 if (attr->setting.vad) {
384 idx = find_fmtp(&attr->setting.dec_fmtp, &STR_DTX, PJ_TRUE);
385 if (idx >= 0)
386 attr->setting.dec_fmtp.param[idx].val = pj_str("1");
387 } else {
388 remove_fmtp(&attr->setting.dec_fmtp, &STR_DTX);
389 }
390
391 return PJ_SUCCESS;
392 }
393
394 /**
395 * Set the opus configuration and default param.
396 */
397 PJ_DEF(pj_status_t)
398 pjmedia_codec_opus_set_default_param(const pjmedia_codec_opus_config *cfg,
399 pjmedia_codec_param *param )
400 {
401 const pj_str_t opus_str = {"opus", 4};
402 const pjmedia_codec_info *info[1];
403 pjmedia_codec_mgr *codec_mgr;
404 unsigned count = 1;
405 pj_status_t status;
406
407 TRACE_((THIS_FILE, "%s:%d: - TRACE", __FUNCTION__, __LINE__));
408 PJ_ASSERT_RETURN(cfg && param, PJ_EINVAL);
409
410 codec_mgr = pjmedia_endpt_get_codec_mgr(opus_codec_factory.endpt);
411
412 status = pjmedia_codec_mgr_find_codecs_by_id(codec_mgr, &opus_str,
413 &count, info, NULL);
414 if (status != PJ_SUCCESS)
415 return status;
416
417 /* Set sample rate */
418 if (cfg->sample_rate != 8000 && cfg->sample_rate != 12000 &&
419 cfg->sample_rate != 16000 && cfg->sample_rate != 24000 &&
420 cfg->sample_rate != 48000)
421 {
422 return PJ_EINVAL;
423 }
424
425 param->info.clock_rate = opus_cfg.sample_rate = cfg->sample_rate;
426 param->info.max_bps = opus_cfg.sample_rate * 2;
427 opus_cfg.frm_ptime = cfg->frm_ptime;
428 opus_cfg.frm_ptime_denum = cfg->frm_ptime_denum;
429 param->info.frm_ptime = (pj_uint16_t)cfg->frm_ptime;
430 param->info.frm_ptime_denum = (pj_uint8_t)cfg->frm_ptime_denum;
431
432 /* Set channel count */
433 if (cfg->channel_cnt != 1 && cfg->channel_cnt != 2)
434 return PJ_EINVAL;
435 param->info.channel_cnt = opus_cfg.channel_cnt = cfg->channel_cnt;
436
437 /* Set bit_rate */
438 if ((cfg->bit_rate != PJMEDIA_CODEC_OPUS_DEFAULT_BIT_RATE) &&
439 (cfg->bit_rate < 6000 || cfg->bit_rate > 510000))
440 {
441 return PJ_EINVAL;
442 }
443 opus_cfg.bit_rate = cfg->bit_rate;
444 param->info.avg_bps = opus_cfg.bit_rate;
445
446 /* Set expected packet loss */
447 if (cfg->packet_loss >= 100)
448 return PJ_EINVAL;
449 opus_cfg.packet_loss = cfg->packet_loss;
450
451 /* Set complexity */
452 if (cfg->complexity > 10)
453 return PJ_EINVAL;
454 opus_cfg.complexity = cfg->complexity;
455
456 opus_cfg.cbr = cfg->cbr;
457
458 generate_fmtp(param);
459
460 status = pjmedia_codec_mgr_set_default_param(codec_mgr, info[0], param);
461 return status;
462 }
463
464
465 /*
466 * Check if factory can allocate the specified codec.
467 */
468 static pj_status_t factory_test_alloc( pjmedia_codec_factory *factory,
469 const pjmedia_codec_info *ci )
470 {
471 const pj_str_t opus_tag = {"OPUS", 4};
472
473 PJ_UNUSED_ARG(factory);
474 PJ_ASSERT_RETURN(factory==&opus_codec_factory.base, PJ_EINVAL);
475
476 /* Type MUST be audio. */
477 if (ci->type != PJMEDIA_TYPE_AUDIO)
478 return PJMEDIA_CODEC_EUNSUP;
479
480 /* Check encoding name. */
481 if (pj_stricmp(&ci->encoding_name, &opus_tag) != 0)
482 return PJMEDIA_CODEC_EUNSUP;
483
484 /* Check clock rate */
485 if (ci->clock_rate != 8000 && ci->clock_rate != 12000 &&
486 ci->clock_rate != 16000 && ci->clock_rate != 24000 &&
487 ci->clock_rate != 48000)
488 {
489 return PJMEDIA_CODEC_EUNSUP;
490 }
491
492 return PJ_SUCCESS;
493 }
494
495
496 /*
497 * Generate default attribute.
498 */
499 static pj_status_t factory_default_attr( pjmedia_codec_factory *factory,
500 const pjmedia_codec_info *ci,
501 pjmedia_codec_param *attr )
502 {
503 PJ_UNUSED_ARG(factory);
504 TRACE_((THIS_FILE, "%s:%d: - TRACE", __FUNCTION__, __LINE__));
505
506 pj_bzero(attr, sizeof(pjmedia_codec_param));
507 attr->info.pt = (pj_uint8_t)ci->pt;
508 attr->info.clock_rate = opus_cfg.sample_rate;
509 attr->info.channel_cnt = opus_cfg.channel_cnt;
510 attr->info.avg_bps = opus_cfg.bit_rate;
511 attr->info.max_bps = opus_cfg.sample_rate * 2;
512 attr->info.frm_ptime = (pj_uint16_t)opus_cfg.frm_ptime;
513 attr->info.frm_ptime_denum = (pj_uint8_t)opus_cfg.frm_ptime_denum;
514 attr->setting.frm_per_pkt = 1;
515 attr->info.pcm_bits_per_sample = 16;
516 attr->setting.vad = OPUS_DEFAULT_VAD;
517 attr->setting.plc = OPUS_DEFAULT_PLC;
518 attr->setting.packet_loss = opus_cfg.packet_loss;
519 attr->setting.complexity = opus_cfg.complexity;
520 attr->setting.cbr = opus_cfg.cbr;
521
522 /* Set max RX frame size. When codec_parse() splits a multi-frame
523 * packet via opus_repacketizer_out_range(), each single-frame output
524 * is a complete Opus packet (TOC + frame data + optional padding).
525 * Per the Opus API docs the worst-case size is 1277 bytes per frame.
526 * Use MAX_ENCODED_PACKET_SIZE (1280) for consistency with codec_parse()
527 * and a small safety margin.
528 */
529 attr->info.max_rx_frame_size = MAX_ENCODED_PACKET_SIZE;
530
531 generate_fmtp(attr);
532
533 return PJ_SUCCESS;
534 }
535
536
537 /*
538 * Enum codecs supported by this factory.
539 */
540 static pj_status_t factory_enum_codecs( pjmedia_codec_factory *factory,
541 unsigned *count,
542 pjmedia_codec_info codecs[] )
543 {
544 PJ_UNUSED_ARG(factory);
545 PJ_ASSERT_RETURN(codecs, PJ_EINVAL);
546
547 if (*count > 0) {
548 pj_bzero(&codecs[0], sizeof(pjmedia_codec_info));
549 codecs[0].type = PJMEDIA_TYPE_AUDIO;
550 codecs[0].pt = PJMEDIA_RTP_PT_OPUS;
551 /*
552 * RFC 7587, Section 7:
553 * The media subtype ("opus") goes in SDP "a=rtpmap" as the encoding
554 * name. The RTP clock rate in "a=rtpmap" MUST be 48000 and the
555 * number of channels MUST be 2.
556 */
557 codecs[0].encoding_name = pj_str("opus");
558 codecs[0].clock_rate = 48000;
559 codecs[0].channel_cnt = 2;
560 *count = 1;
561 }
562
563 return PJ_SUCCESS;
564 }
565
566
567 /*
568 * Allocate a new Opus codec instance.
569 */
570 static pj_status_t factory_alloc_codec( pjmedia_codec_factory *factory,
571 const pjmedia_codec_info *ci,
572 pjmedia_codec **p_codec )
573 {
574 pjmedia_codec *codec;
575 pj_pool_t *pool;
576 pj_status_t status;
577 struct opus_data *opus_data;
578 struct opus_codec_factory *f = (struct opus_codec_factory*) factory;
579
580 PJ_UNUSED_ARG(ci);
581 TRACE_((THIS_FILE, "%s:%d: - TRACE", __FUNCTION__, __LINE__));
582
583 pool = pjmedia_endpt_create_pool(f->endpt, "opus", 4000, 4000);
584 if (!pool) return PJ_ENOMEM;
585
586 opus_data = PJ_POOL_ZALLOC_T(pool, struct opus_data);
587 codec = PJ_POOL_ZALLOC_T(pool, pjmedia_codec);
588
589 status = pj_mutex_create_simple (pool, "opus_mutex", &opus_data->mutex);
590 if (status != PJ_SUCCESS) {
591 pj_pool_release(pool);
592 return status;
593 }
594
595 pj_memcpy(&opus_data->cfg, &opus_cfg, sizeof(pjmedia_codec_opus_config));
596 opus_data->pool = pool;
597 codec->op = &opus_op;
598 codec->factory = factory;
599 codec->codec_data = opus_data;
600
601 *p_codec = codec;
602 return PJ_SUCCESS;
603 }
604
605
606 /*
607 * Free codec.
608 */
609 static pj_status_t factory_dealloc_codec( pjmedia_codec_factory *factory,
610 pjmedia_codec *codec )
611 {
612 struct opus_data *opus_data;
613
614 PJ_ASSERT_RETURN(factory && codec, PJ_EINVAL);
615 PJ_ASSERT_RETURN(factory == &opus_codec_factory.base, PJ_EINVAL);
616
617 opus_data = (struct opus_data *)codec->codec_data;
618 if (opus_data) {
619 pj_mutex_destroy(opus_data->mutex);
620 opus_data->mutex = NULL;
621 pj_pool_release(opus_data->pool);
622 }
623
624 return PJ_SUCCESS;
625 }
626
627
628 /*
629 * Init codec.
630 */
631 static pj_status_t codec_init( pjmedia_codec *codec,
632 pj_pool_t *pool )
633 {
634 PJ_UNUSED_ARG(codec);
635 PJ_UNUSED_ARG(pool);
636 return PJ_SUCCESS;
637 }
638
639
640 /*
641 * Open codec.
642 */
643 static pj_status_t codec_open( pjmedia_codec *codec,
644 pjmedia_codec_param *attr )
645 {
646 struct opus_data *opus_data = (struct opus_data *)codec->codec_data;
647 int idx, err;
648 pj_bool_t auto_bit_rate = PJ_TRUE;
649 pj_bool_t enc_use_plc = PJ_FALSE;
650
651 PJ_ASSERT_RETURN(codec && attr && opus_data, PJ_EINVAL);
652
653 pj_mutex_lock (opus_data->mutex);
654
655 TRACE_((THIS_FILE, "%s:%d: - TRACE", __FUNCTION__, __LINE__));
656
657 opus_data->cfg.sample_rate = attr->info.clock_rate;
658 opus_data->cfg.channel_cnt = attr->info.channel_cnt;
659 opus_data->enc_ptime = opus_data->dec_ptime = attr->info.frm_ptime;
660 opus_data->enc_ptime_denum = attr->info.frm_ptime_denum?
661 attr->info.frm_ptime_denum: 1;
662 opus_data->dec_ptime_denum = opus_data->enc_ptime_denum;
663
664 /* Allocate memory used by the codec */
665 if (!opus_data->enc) {
666 /* Allocate memory for max 2 channels */
667 opus_data->enc = pj_pool_zalloc(opus_data->pool,
668 opus_encoder_get_size(2));
669 }
670 if (!opus_data->dec) {
671 /* Allocate memory for max 2 channels */
672 opus_data->dec = pj_pool_zalloc(opus_data->pool,
673 opus_decoder_get_size(2));
674 }
675 if (!opus_data->enc_packer) {
676 opus_data->enc_packer = pj_pool_zalloc(opus_data->pool,
677 opus_repacketizer_get_size());
678 }
679 if (!opus_data->dec_packer) {
680 opus_data->dec_packer = pj_pool_zalloc(opus_data->pool,
681 opus_repacketizer_get_size());
682 }
683 if (!opus_data->enc || !opus_data->dec ||
684 !opus_data->enc_packer || !opus_data->dec_packer)
685 {
686 PJ_LOG(2, (THIS_FILE, "Unable to allocate memory for the codec"));
687 pj_mutex_unlock (opus_data->mutex);
688 return PJ_ENOMEM;
689 }
690
691 /* Check max average bit rate */
692 idx = find_fmtp(&attr->setting.enc_fmtp, &STR_MAX_BIT_RATE, PJ_FALSE);
693 if (idx >= 0) {
694 unsigned rate;
695 rate = (unsigned)pj_strtoul(&attr->setting.enc_fmtp.param[idx].val);
696 /* Clamp to RFC 7587 range: 6000-510000 bps */
697 if (rate < 6000 || rate > 510000) {
698 PJ_LOG(3, (THIS_FILE, "Clamping maxaveragebitrate %u to "
699 "valid range [6000, 510000]", rate));
700 if (rate < 6000) rate = 6000;
701 if (rate > 510000) rate = 510000;
702 }
703 if (rate < attr->info.max_bps) {
704 PJ_LOG(5, (THIS_FILE, "Setting encoder bitrate to remote's "
705 "maxaveragebitrate %u", rate));
706 attr->info.avg_bps = rate;
707 auto_bit_rate = PJ_FALSE;
708 } else {
709 PJ_LOG(4, (THIS_FILE, "Ignoring remote's maxaveragebitrate "
710 "%u (>= max_bps %u)", rate, attr->info.max_bps));
711 }
712 }
713
714 /* Check plc */
715 idx = find_fmtp(&attr->setting.enc_fmtp, &STR_INBAND_FEC, PJ_FALSE);
716 if (idx >= 0) {
717 unsigned plc;
718 plc = (unsigned) pj_strtoul(&attr->setting.enc_fmtp.param[idx].val);
719 if (plc > 0)
720 enc_use_plc = PJ_TRUE;
721 /* Do not modify local PLC setting as it's used for decoding. */
722 // attr->setting.plc = plc > 0? PJ_TRUE: PJ_FALSE
723 }
724
725 /* Check vad */
726 idx = find_fmtp(&attr->setting.enc_fmtp, &STR_DTX, PJ_FALSE);
727 if (idx >= 0) {
728 unsigned vad;
729 vad = (unsigned) pj_strtoul(&attr->setting.enc_fmtp.param[idx].val);
730 attr->setting.vad = vad > 0? PJ_TRUE: PJ_FALSE;
731 }
732
733 /* Check cbr */
734 idx = find_fmtp(&attr->setting.enc_fmtp, &STR_CBR, PJ_FALSE);
735 if (idx >= 0) {
736 unsigned cbr;
737 cbr = (unsigned) pj_strtoul(&attr->setting.enc_fmtp.param[idx].val);
738 opus_data->cfg.cbr = cbr > 0? PJ_TRUE: PJ_FALSE;
739 }
740
741 TRACE_((THIS_FILE, "%s:%d: sample_rate: %u",
742 __FUNCTION__, __LINE__, opus_data->cfg.sample_rate));
743
744 /* Initialize encoder */
745 err = opus_encoder_init(opus_data->enc,
746 opus_data->cfg.sample_rate,
747 attr->info.channel_cnt,
748 OPUS_APPLICATION_VOIP);
749 if (err != OPUS_OK) {
750 PJ_LOG(2, (THIS_FILE, "Unable to create encoder: %s %d",
751 opus_strerror(err), err));
752 pj_mutex_unlock (opus_data->mutex);
753 return PJMEDIA_CODEC_EFAILED;
754 }
755
756 /* Set signal type */
757 opus_encoder_ctl(opus_data->enc, OPUS_SET_SIGNAL(OPUS_SIGNAL_VOICE));
758 /* Set bitrate */
759 opus_encoder_ctl(opus_data->enc, OPUS_SET_BITRATE(auto_bit_rate?
760 OPUS_AUTO:
761 (int)attr->info.avg_bps));
762 /* Set VAD */
763 opus_encoder_ctl(opus_data->enc, OPUS_SET_DTX(attr->setting.vad ? 1 : 0));
764 /* Set PLC */
765 opus_encoder_ctl(opus_data->enc,
766 OPUS_SET_INBAND_FEC(enc_use_plc));
767 /* Set bandwidth */
768 opus_encoder_ctl(opus_data->enc,
769 OPUS_SET_MAX_BANDWIDTH(get_opus_bw_constant(
770 opus_data->cfg.sample_rate)));
771 /* Set expected packet loss */
772 opus_encoder_ctl(opus_data->enc,
773 OPUS_SET_PACKET_LOSS_PERC(opus_data->cfg.packet_loss));
774 /* Set complexity */
775 opus_encoder_ctl(opus_data->enc,
776 OPUS_SET_COMPLEXITY(opus_data->cfg.complexity));
777 /* Set constant bit rate */
778 opus_encoder_ctl(opus_data->enc,
779 OPUS_SET_VBR(opus_data->cfg.cbr ? 0 : 1));
780
781 PJ_LOG(4, (THIS_FILE, "Initialize Opus encoder, sample rate: %d, ch: %d, "
782 "avg bitrate: %d%s, vad: %d, plc: %d, pkt loss: %d, "
783 "complexity: %d, constant bit rate: %d, "
784 "ptime: %d/%d",
785 opus_data->cfg.sample_rate,
786 opus_data->cfg.channel_cnt,
787 (auto_bit_rate? 0: attr->info.avg_bps),
788 (auto_bit_rate? "(auto)": ""),
789 attr->setting.vad?1:0,
790 attr->setting.plc?1:0,
791 opus_data->cfg.packet_loss,
792 opus_data->cfg.complexity,
793 opus_data->cfg.cbr?1:0,
794 opus_data->enc_ptime,
795 opus_data->enc_ptime_denum));
796
797 /* Initialize decoder */
798 err = opus_decoder_init (opus_data->dec,
799 opus_data->cfg.sample_rate,
800 attr->info.channel_cnt);
801 if (err != OPUS_OK) {
802 PJ_LOG(2, (THIS_FILE, "Unable to initialize decoder: %s %d",
803 opus_strerror(err), err));
804 pj_mutex_unlock (opus_data->mutex);
805 return PJMEDIA_CODEC_EFAILED;
806 }
807
808 /* Initialize temporary decode frames used for FEC.
809 * These buffers hold encoded input data, so they must be at least
810 * MAX_ENCODED_PACKET_SIZE to accept any frame from codec_parse().
811 */
812 opus_data->dec_frame_buf_size = (opus_data->cfg.sample_rate / 1000)
813 * 60 * attr->info.channel_cnt * 2 /* bytes per sample */;
814 if (opus_data->dec_frame_buf_size < MAX_ENCODED_PACKET_SIZE)
815 opus_data->dec_frame_buf_size = MAX_ENCODED_PACKET_SIZE;
816 opus_data->dec_frame[0].type = PJMEDIA_FRAME_TYPE_NONE;
817 opus_data->dec_frame[0].buf = pj_pool_zalloc(opus_data->pool,
818 opus_data->dec_frame_buf_size);
819 opus_data->dec_frame[1].type = PJMEDIA_FRAME_TYPE_NONE;
820 opus_data->dec_frame[1].buf = pj_pool_zalloc(opus_data->pool,
821 opus_data->dec_frame_buf_size);
822 opus_data->dec_frame_index = -1;
823
824 /* Initialize the repacketizers */
825 opus_repacketizer_init(opus_data->enc_packer);
826 opus_repacketizer_init(opus_data->dec_packer);
827
828 pj_mutex_unlock (opus_data->mutex);
829 return PJ_SUCCESS;
830 }
831
832
833 /*
834 * Close codec.
835 */
836 static pj_status_t codec_close( pjmedia_codec *codec )
837 {
838 PJ_UNUSED_ARG(codec);
839 return PJ_SUCCESS;
840 }
841
842
843 /*
844 * Modify codec settings.
845 */
846 static pj_status_t codec_modify( pjmedia_codec *codec,
847 const pjmedia_codec_param *attr )
848 {
849 struct opus_data *opus_data = (struct opus_data *)codec->codec_data;
850
851 pj_mutex_lock (opus_data->mutex);
852
853 TRACE_((THIS_FILE, "%s:%d: - TRACE", __FUNCTION__, __LINE__));
854
855 /* Set encoder ptime */
856 opus_data->enc_ptime = attr->info.frm_ptime;
857 opus_data->enc_ptime_denum = attr->info.frm_ptime_denum?
858 attr->info.frm_ptime_denum: 1;
859
860 /* Set bitrate */
861 opus_data->cfg.bit_rate = attr->info.avg_bps;
862 opus_encoder_ctl(opus_data->enc, OPUS_SET_BITRATE(attr->info.avg_bps?
863 (int)attr->info.avg_bps:
864 OPUS_AUTO));
865 /* Set VAD */
866 opus_encoder_ctl(opus_data->enc, OPUS_SET_DTX(attr->setting.vad ? 1 : 0));
867 /* Set PLC */
868 opus_encoder_ctl(opus_data->enc,
869 OPUS_SET_INBAND_FEC(attr->setting.plc ? 1 : 0));
870
871 /* Set bandwidth */
872 opus_encoder_ctl(opus_data->enc,
873 OPUS_SET_MAX_BANDWIDTH(get_opus_bw_constant(
874 attr->info.clock_rate)));
875 /* Set expected packet loss */
876 opus_encoder_ctl(opus_data->enc,
877 OPUS_SET_PACKET_LOSS_PERC(attr->setting.packet_loss));
878 /* Set complexity */
879 opus_encoder_ctl(opus_data->enc,
880 OPUS_SET_COMPLEXITY(attr->setting.complexity));
881 /* Set constant bit rate */
882 opus_encoder_ctl(opus_data->enc,
883 OPUS_SET_VBR(attr->setting.cbr ? 0 : 1));
884
885 PJ_LOG(4, (THIS_FILE, "Modifying Opus encoder, sample rate: %d, ch: %d, "
886 "avg bitrate: %d%s, vad: %d, plc: %d, pkt loss: %d, "
887 "complexity: %d, constant bit rate: %d, "
888 "ptime: %d/%d ms",
889 attr->info.clock_rate,
890 attr->info.channel_cnt,
891 (attr->info.avg_bps? attr->info.avg_bps: 0),
892 (attr->info.avg_bps? "": "(auto)"),
893 attr->setting.vad?1:0,
894 attr->setting.plc?1:0,
895 attr->setting.packet_loss,
896 attr->setting.complexity,
897 attr->setting.cbr?1:0,
898 opus_data->enc_ptime,
899 opus_data->enc_ptime_denum));
900
901 pj_mutex_unlock (opus_data->mutex);
902 return PJ_SUCCESS;
903 }
904
905
906 /*
907 * Get frames in the packet.
908 */
909 static pj_status_t codec_parse( pjmedia_codec *codec,
910 void *pkt,
911 pj_size_t pkt_size,
912 const pj_timestamp *ts,
913 unsigned *frame_cnt,
914 pjmedia_frame frames[] )
915 {
916 struct opus_data *opus_data = (struct opus_data *)codec->codec_data;
917 unsigned char tmp_buf[MAX_ENCODED_PACKET_SIZE];
918 int i, num_frames;
919 int size, out_pos;
920 unsigned samples_per_frame = 0;
921 #if (USE_INCOMING_WORSE_SETTINGS)
922 int bw;
923 #endif
924
925 PJ_ASSERT_RETURN(codec && ts && frames && frame_cnt, PJ_EINVAL);
926
927 pj_mutex_lock (opus_data->mutex);
928
929 if (pkt_size > sizeof(tmp_buf)) {
930 PJ_LOG(5, (THIS_FILE, "Encoded size bigger than buffer"));
931 pj_mutex_unlock (opus_data->mutex);
932 return PJMEDIA_CODEC_EFRMTOOSHORT;
933 }
934
935 pj_memcpy(tmp_buf, pkt, pkt_size);
936
937 opus_repacketizer_init(opus_data->dec_packer);
938 opus_repacketizer_cat(opus_data->dec_packer, tmp_buf,
939 (opus_int32)pkt_size);
940
941 num_frames = opus_repacketizer_get_nb_frames(opus_data->dec_packer);
942 if (num_frames == 0) {
943 PJ_LOG(2, (THIS_FILE, "No frames retrieved (num_frames = 0)"));
944 pj_mutex_unlock(opus_data->mutex);
945 return PJMEDIA_CODEC_EFAILED;
946 }
947
948 if (num_frames > (int)*frame_cnt) {
949 PJ_LOG(4, (THIS_FILE, "Opus parse: clamping num_frames from %d to %u",
950 num_frames, *frame_cnt));
951 num_frames = (int)*frame_cnt;
952 }
953
954 out_pos = 0;
955 for (i = 0; i < num_frames; ++i) {
956 size = opus_repacketizer_out_range(opus_data->dec_packer, i, i+1,
957 ((unsigned char*)pkt) + out_pos,
958 sizeof(tmp_buf));
959 if (size < 0) {
960 PJ_LOG(5, (THIS_FILE, "Parse failed! (pkt_size=%lu, err=%d)",
961 (unsigned long)pkt_size, size));
962 pj_mutex_unlock (opus_data->mutex);
963 return PJMEDIA_CODEC_EFAILED;
964 }
965 frames[i].type = PJMEDIA_FRAME_TYPE_AUDIO;
966 frames[i].buf = ((char*)pkt) + out_pos;
967 frames[i].size = size;
968 frames[i].bit_info = 0;
969
970 if (i == 0) {
971 int nsamples;
972 unsigned ptime;
973 unsigned ptime_denum = 1;
974
975 nsamples = opus_packet_get_nb_samples(frames[i].buf,
976 (opus_int32)frames[i].size,
977 (opus_int32)
978 opus_data->cfg.sample_rate);
979 if (nsamples <= 0) {
980 PJ_LOG(5, (THIS_FILE, "Parse failed to get samples number! "
981 "(err=%d)", nsamples));
982 pj_mutex_unlock (opus_data->mutex);
983 return PJMEDIA_CODEC_EFAILED;
984 }
985
986 if ((nsamples * 1000) % opus_data->cfg.sample_rate != 0) {
987 /* The only non-integer ptime that Opus supports is 2.5 ms */
988 ptime_denum = 2;
989 }
990 ptime = nsamples * ptime_denum * 1000 / opus_data->cfg.sample_rate;
991
992 if (ptime * opus_data->dec_ptime_denum !=
993 opus_data->dec_ptime * ptime_denum)
994 {
995 PJ_LOG(4, (THIS_FILE, "Opus ptime change detected: %d/%d ms "
996 "--> %d/%d ms",
997 opus_data->dec_ptime,
998 opus_data->dec_ptime_denum,
999 ptime, ptime_denum));
1000 opus_data->dec_ptime = ptime;
1001 opus_data->dec_ptime_denum = ptime_denum;
1002 opus_data->dec_frame_index = -1;
1003
1004 /* Signal to the stream about ptime change. */
1005 frames[i].bit_info = 0x10000 | nsamples;
1006 }
1007 samples_per_frame = nsamples;
1008 }
1009
1010 frames[i].timestamp.u64 = ts->u64 + i * samples_per_frame;
1011 out_pos += size;
1012 }
1013 *frame_cnt = num_frames;
1014
1015 pj_mutex_unlock (opus_data->mutex);
1016 return PJ_SUCCESS;
1017 }
1018
1019
1020 /*
1021 * Encode frame.
1022 */
1023 static pj_status_t codec_encode( pjmedia_codec *codec,
1024 const struct pjmedia_frame *input,
1025 unsigned output_buf_len,
1026 struct pjmedia_frame *output )
1027 {
1028 struct opus_data *opus_data = (struct opus_data *)codec->codec_data;
1029 opus_int32 size = 0;
1030 unsigned in_pos = 0;
1031 unsigned out_pos = 0;
1032 unsigned frame_size;
1033 unsigned samples_per_frame;
1034 unsigned char tmp_buf[MAX_ENCODED_PACKET_SIZE];
1035 unsigned tmp_bytes_left = sizeof(tmp_buf);
1036
1037 pj_mutex_lock (opus_data->mutex);
1038
1039 samples_per_frame = (opus_data->cfg.sample_rate *
1040 opus_data->enc_ptime /
1041 opus_data->enc_ptime_denum) / 1000;
1042 frame_size = samples_per_frame * opus_data->cfg.channel_cnt *
1043 sizeof(opus_int16);
1044
1045 opus_repacketizer_init(opus_data->enc_packer);
1046 while (input->size - in_pos >= frame_size) {
1047 size = opus_encode(opus_data->enc,
1048 (const opus_int16*)(((char*)input->buf) + in_pos),
1049 samples_per_frame,
1050 tmp_buf + out_pos,
1051 (tmp_bytes_left < frame_size ?
1052 tmp_bytes_left : frame_size));
1053 if (size < 0) {
1054 PJ_LOG(4, (THIS_FILE, "Encode failed! (%d)", size));
1055 pj_mutex_unlock (opus_data->mutex);
1056 return PJMEDIA_CODEC_EFAILED;
1057 } else if (size > 0) {
1058 /* Only add packets containing more than the TOC */
1059 opus_repacketizer_cat(opus_data->enc_packer,
1060 tmp_buf + out_pos,
1061 size);
1062 out_pos += size;
1063 tmp_bytes_left -= size;
1064 }
1065 in_pos += frame_size;
1066 }
1067
1068 if (!opus_repacketizer_get_nb_frames(opus_data->enc_packer)) {
1069 /* Empty packet */
1070 output->size = 0;
1071 output->type = PJMEDIA_FRAME_TYPE_NONE;
1072 output->timestamp = input->timestamp;
1073 }
1074
1075 if (size) {
1076 size = opus_repacketizer_out(opus_data->enc_packer,
1077 output->buf,
1078 output_buf_len);
1079 if (size < 0) {
1080 PJ_LOG(4, (THIS_FILE, "Encode failed! (%d), out_size: %u",
1081 size, output_buf_len));
1082 pj_mutex_unlock (opus_data->mutex);
1083 return PJMEDIA_CODEC_EFAILED;
1084 }
1085 }
1086
1087 output->size = (unsigned)size;
1088 output->type = PJMEDIA_FRAME_TYPE_AUDIO;
1089 output->timestamp = input->timestamp;
1090
1091 pj_mutex_unlock (opus_data->mutex);
1092 return PJ_SUCCESS;
1093 }
1094
1095
1096 /*
1097 * Decode frame.
1098 */
1099 static pj_status_t codec_decode( pjmedia_codec *codec,
1100 const struct pjmedia_frame *input,
1101 unsigned output_buf_len,
1102 struct pjmedia_frame *output )
1103 {
1104 struct opus_data *opus_data = (struct opus_data *)codec->codec_data;
1105 int decoded_samples;
1106 pjmedia_frame *inframe;
1107 int fec = 0;
1108 int frm_size;
1109
1110 PJ_UNUSED_ARG(output_buf_len);
1111
1112 pj_mutex_lock (opus_data->mutex);
1113
1114 /* Validate input size against decode buffer capacity before any copy.
1115 * This is a safety check to ensure the pj_memcpy() calls below
1116 * cannot overflow dec_frame[].buf.
1117 */
1118 if (input->size > opus_data->dec_frame_buf_size) {
1119 PJ_LOG(4, (THIS_FILE, "Opus decode: input size (%u) exceeds decode "
1120 "buffer (%u), dropping frame",
1121 (unsigned)input->size,
1122 (unsigned)opus_data->dec_frame_buf_size));
1123 pj_mutex_unlock (opus_data->mutex);
1124 return PJMEDIA_CODEC_EFRMTOOSHORT;
1125 }
1126
1127 if (opus_data->dec_frame_index == -1) {
1128 /* First packet, buffer it. */
1129 opus_data->dec_frame[0].type = input->type;
1130 opus_data->dec_frame[0].size = input->size;
1131 opus_data->dec_frame[0].timestamp = input->timestamp;
1132 pj_memcpy(opus_data->dec_frame[0].buf, input->buf, input->size);
1133 opus_data->dec_frame_index = 0;
1134
1135 /* Return zero decoded bytes */
1136 output->size = 0;
1137 output->type = PJMEDIA_FRAME_TYPE_NONE;
1138 output->timestamp = input->timestamp;
1139
1140 pj_mutex_unlock (opus_data->mutex);
1141 return PJ_SUCCESS;
1142 }
1143
1144 inframe = &opus_data->dec_frame[opus_data->dec_frame_index];
1145
1146 if (inframe->type != PJMEDIA_FRAME_TYPE_AUDIO) {
1147 /* Update current frame index */
1148 opus_data->dec_frame_index++;
1149 if (opus_data->dec_frame_index > 1)
1150 opus_data->dec_frame_index = 0;
1151 /* Copy original input buffer to current indexed frame */
1152 inframe = &opus_data->dec_frame[opus_data->dec_frame_index];
1153 inframe->type = input->type;
1154 inframe->size = input->size;
1155 inframe->timestamp = input->timestamp;
1156 pj_memcpy(inframe->buf, input->buf, input->size);
1157 fec = 1;
1158 }
1159
1160 /* From Opus doc: In the case of PLC (data==NULL) or FEC(decode_fec=1),
1161 * then frame_size needs to be exactly the duration of audio that
1162 * is missing.
1163 */
1164 frm_size = (int)output->size / (sizeof(opus_int16) *
1165 opus_data->cfg.channel_cnt);
1166 if (inframe->type != PJMEDIA_FRAME_TYPE_AUDIO || fec) {
1167 frm_size = PJ_MIN((unsigned)frm_size,
1168 opus_data->cfg.sample_rate *
1169 opus_data->dec_ptime /
1170 opus_data->dec_ptime_denum / 1000);
1171 }
1172 decoded_samples = opus_decode( opus_data->dec,
1173 inframe->type==PJMEDIA_FRAME_TYPE_AUDIO ?
1174 inframe->buf : NULL,
1175 inframe->type==PJMEDIA_FRAME_TYPE_AUDIO ?
1176 (opus_int32)inframe->size : 0,
1177 (opus_int16*)output->buf,
1178 frm_size,
1179 fec);
1180 output->timestamp = inframe->timestamp;
1181
1182 if (inframe->type == PJMEDIA_FRAME_TYPE_AUDIO) {
1183 /* Mark current indexed frame as invalid */
1184 inframe->type = PJMEDIA_FRAME_TYPE_NONE;
1185 /* Update current frame index */
1186 opus_data->dec_frame_index++;
1187 if (opus_data->dec_frame_index > 1)
1188 opus_data->dec_frame_index = 0;
1189 /* Copy original input buffer to current indexed frame */
1190 inframe = &opus_data->dec_frame[opus_data->dec_frame_index];
1191 inframe->type = input->type;
1192 inframe->size = input->size;
1193 inframe->timestamp = input->timestamp;
1194 pj_memcpy(inframe->buf, input->buf, input->size);
1195 }
1196
1197 if (decoded_samples < 0) {
1198 PJ_LOG(4, (THIS_FILE, "Decode failed!"));
1199 pj_mutex_unlock (opus_data->mutex);
1200 return PJMEDIA_CODEC_EFAILED;
1201 }
1202
1203 output->size = decoded_samples * sizeof(opus_int16) *
1204 opus_data->cfg.channel_cnt;
1205 output->type = PJMEDIA_FRAME_TYPE_AUDIO;
1206
1207 pj_mutex_unlock (opus_data->mutex);
1208 return PJ_SUCCESS;
1209 }
1210
1211
1212 /*
1213 * Recover lost frame.
1214 */
1215 static pj_status_t codec_recover( pjmedia_codec *codec,
1216 unsigned output_buf_len,
1217 struct pjmedia_frame *output )
1218 {
1219 struct opus_data *opus_data = (struct opus_data *)codec->codec_data;
1220 int decoded_samples;
1221 pjmedia_frame *inframe;
1222 int frm_size;
1223
1224 pj_mutex_lock (opus_data->mutex);
1225
1226 if (opus_data->dec_frame_index == -1) {
1227 /* Recover the first packet? Don't think so, fill it with zeroes. */
1228 unsigned samples_per_frame;
1229 samples_per_frame = opus_data->cfg.sample_rate * opus_data->dec_ptime/
1230 opus_data->dec_ptime_denum / 1000;
1231 output->type = PJMEDIA_FRAME_TYPE_AUDIO;
1232 output->size = samples_per_frame << 1;
1233 if (output->size > output_buf_len) {
1234 pj_assert(!"Buffer too small");
1235 output->size = output_buf_len;
1236 }
1237 pjmedia_zero_samples((pj_int16_t*)output->buf, samples_per_frame);
1238 pj_mutex_unlock (opus_data->mutex);
1239
1240 return PJ_SUCCESS;
1241 }
1242
1243 inframe = &opus_data->dec_frame[opus_data->dec_frame_index];
1244 frm_size = (int)output->size / (sizeof(opus_int16) *
1245 opus_data->cfg.channel_cnt);
1246 if (inframe->type != PJMEDIA_FRAME_TYPE_AUDIO) {
1247 frm_size = PJ_MIN((unsigned)frm_size, opus_data->cfg.sample_rate *
1248 opus_data->dec_ptime / opus_data->dec_ptime_denum /
1249 1000);
1250 }
1251 decoded_samples = opus_decode(opus_data->dec,
1252 inframe->type==PJMEDIA_FRAME_TYPE_AUDIO ?
1253 inframe->buf : NULL,
1254 inframe->type==PJMEDIA_FRAME_TYPE_AUDIO ?
1255 (opus_int32)inframe->size : 0,
1256 (opus_int16*)output->buf,
1257 frm_size,
1258 0);
1259
1260 /* Mark current indexed frame as invalid */
1261 inframe->type = PJMEDIA_FRAME_TYPE_NONE;
1262
1263 /* Update current frame index */
1264 opus_data->dec_frame_index++;
1265 if (opus_data->dec_frame_index > 1)
1266 opus_data->dec_frame_index = 0;
1267 /* Mark current indexed frame as invalid */
1268 inframe = &opus_data->dec_frame[opus_data->dec_frame_index];
1269 inframe->type = PJMEDIA_FRAME_TYPE_NONE;
1270
1271 if (decoded_samples < 0) {
1272 PJ_LOG(4, (THIS_FILE, "Recover failed!"));
1273 pj_mutex_unlock (opus_data->mutex);
1274 return PJMEDIA_CODEC_EFAILED;
1275 }
1276
1277 output->size = decoded_samples * sizeof(opus_int16) *
1278 opus_data->cfg.channel_cnt;
1279 output->type = PJMEDIA_FRAME_TYPE_AUDIO;
1280 output->timestamp = inframe->timestamp;
1281
1282 pj_mutex_unlock (opus_data->mutex);
1283 return PJ_SUCCESS;
1284 }
1285
1286 #if defined(_MSC_VER)
1287 # pragma comment(lib, PJMEDIA_CODEC_OPUS_LIB_NAME)
1288 #endif
1289
1290 #endif /* PJMEDIA_HAS_OPUS_CODEC */