opus.c 43 KB

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