translate.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Translate via the use of pseudo channels
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. */
  24. /*** MODULEINFO
  25. <support_level>core</support_level>
  26. ***/
  27. #include "asterisk.h"
  28. #include <sys/time.h>
  29. #include <sys/resource.h>
  30. #include <math.h>
  31. #include "asterisk/lock.h"
  32. #include "asterisk/channel.h"
  33. #include "asterisk/translate.h"
  34. #include "asterisk/module.h"
  35. #include "asterisk/frame.h"
  36. #include "asterisk/sched.h"
  37. #include "asterisk/cli.h"
  38. #include "asterisk/term.h"
  39. #include "asterisk/format.h"
  40. #include "asterisk/linkedlists.h"
  41. /*! \todo
  42. * TODO: sample frames for each supported input format.
  43. * We build this on the fly, by taking an SLIN frame and using
  44. * the existing converter to play with it.
  45. */
  46. /*! max sample recalc */
  47. #define MAX_RECALC 1000
  48. /*! \brief the list of translators */
  49. static AST_RWLIST_HEAD_STATIC(translators, ast_translator);
  50. struct translator_path {
  51. struct ast_translator *step; /*!< Next step translator */
  52. uint32_t table_cost; /*!< Complete table cost to destination */
  53. uint32_t comp_cost; /*!< Complete table cost to destination */
  54. uint8_t multistep; /*!< Multiple conversions required for this translation */
  55. };
  56. /*!
  57. * \brief a matrix that, for any pair of supported formats,
  58. * indicates the total cost of translation and the first step.
  59. * The full path can be reconstructed iterating on the matrix
  60. * until step->dstfmt == desired_format.
  61. *
  62. * Array indexes are 'src' and 'dest', in that order.
  63. *
  64. * Note: the lock in the 'translators' list is also used to protect
  65. * this structure.
  66. */
  67. static struct translator_path **__matrix;
  68. /*!
  69. * \brief table for converting index to format values.
  70. *
  71. * \note this table is protected by the table_lock.
  72. */
  73. static unsigned int *__indextable;
  74. /*! protects the __indextable for resizing */
  75. static ast_rwlock_t tablelock;
  76. /* index size starts at this*/
  77. #define INIT_INDEX 32
  78. /* index size grows by this as necessary */
  79. #define GROW_INDEX 16
  80. /*! the current largest index used by the __matrix and __indextable arrays*/
  81. static int cur_max_index;
  82. /*! the largest index that can be used in either the __indextable or __matrix before resize must occur */
  83. static int index_size;
  84. static void matrix_rebuild(int samples);
  85. /*!
  86. * \internal
  87. * \brief converts codec id to index value.
  88. */
  89. static int codec_to_index(unsigned int id)
  90. {
  91. int x;
  92. ast_rwlock_rdlock(&tablelock);
  93. for (x = 0; x < cur_max_index; x++) {
  94. if (__indextable[x] == id) {
  95. /* format already exists in index2format table */
  96. ast_rwlock_unlock(&tablelock);
  97. return x;
  98. }
  99. }
  100. ast_rwlock_unlock(&tablelock);
  101. return -1; /* not found */
  102. }
  103. /*!
  104. * \internal
  105. * \brief converts codec to index value.
  106. */
  107. static int codec2index(struct ast_codec *codec)
  108. {
  109. return codec_to_index(codec->id);
  110. }
  111. /*!
  112. * \internal
  113. * \brief converts format to codec index value.
  114. */
  115. static int format2index(struct ast_format *format)
  116. {
  117. return codec_to_index(ast_format_get_codec_id(format));
  118. }
  119. /*!
  120. * \internal
  121. * \brief add a new codec to the matrix and index table structures.
  122. *
  123. * \note it is perfectly safe to call this on codecs already indexed.
  124. *
  125. * \retval 0 success
  126. * \retval -1 matrix and index table need to be resized
  127. */
  128. static int add_codec2index(struct ast_codec *codec)
  129. {
  130. if (codec2index(codec) != -1) {
  131. /* format is already already indexed */
  132. return 0;
  133. }
  134. ast_rwlock_wrlock(&tablelock);
  135. if (cur_max_index == (index_size)) {
  136. ast_rwlock_unlock(&tablelock);
  137. return -1; /* hit max length */
  138. }
  139. __indextable[cur_max_index] = codec->id;
  140. cur_max_index++;
  141. ast_rwlock_unlock(&tablelock);
  142. return 0;
  143. }
  144. /*!
  145. * \internal
  146. * \brief converts index value back to codec
  147. */
  148. static struct ast_codec *index2codec(int index)
  149. {
  150. struct ast_codec *codec;
  151. if (index >= cur_max_index) {
  152. return 0;
  153. }
  154. ast_rwlock_rdlock(&tablelock);
  155. codec = ast_codec_get_by_id(__indextable[index]);
  156. ast_rwlock_unlock(&tablelock);
  157. return codec;
  158. }
  159. /*!
  160. * \internal
  161. * \brief resize both the matrix and index table so they can represent
  162. * more translators
  163. *
  164. * \note _NO_ locks can be held prior to calling this function
  165. *
  166. * \retval 0 success
  167. * \retval -1 failure. Old matrix and index table can still be used though
  168. */
  169. static int matrix_resize(int init)
  170. {
  171. struct translator_path **tmp_matrix = NULL;
  172. unsigned int *tmp_table = NULL;
  173. int old_index;
  174. int x;
  175. AST_RWLIST_WRLOCK(&translators);
  176. ast_rwlock_wrlock(&tablelock);
  177. old_index = index_size;
  178. if (init) {
  179. index_size += INIT_INDEX;
  180. } else {
  181. index_size += GROW_INDEX;
  182. }
  183. /* make new 2d array of translator_path structures */
  184. if (!(tmp_matrix = ast_calloc(1, sizeof(struct translator_path *) * (index_size)))) {
  185. goto resize_cleanup;
  186. }
  187. for (x = 0; x < index_size; x++) {
  188. if (!(tmp_matrix[x] = ast_calloc(1, sizeof(struct translator_path) * (index_size)))) {
  189. goto resize_cleanup;
  190. }
  191. }
  192. /* make new index table */
  193. if (!(tmp_table = ast_calloc(1, sizeof(unsigned int) * index_size))) {
  194. goto resize_cleanup;
  195. }
  196. /* if everything went well this far, free the old and use the new */
  197. if (!init) {
  198. for (x = 0; x < old_index; x++) {
  199. ast_free(__matrix[x]);
  200. }
  201. ast_free(__matrix);
  202. memcpy(tmp_table, __indextable, sizeof(unsigned int) * old_index);
  203. ast_free(__indextable);
  204. }
  205. /* now copy them over */
  206. __matrix = tmp_matrix;
  207. __indextable = tmp_table;
  208. matrix_rebuild(0);
  209. ast_rwlock_unlock(&tablelock);
  210. AST_RWLIST_UNLOCK(&translators);
  211. return 0;
  212. resize_cleanup:
  213. ast_rwlock_unlock(&tablelock);
  214. AST_RWLIST_UNLOCK(&translators);
  215. if (tmp_matrix) {
  216. for (x = 0; x < index_size; x++) {
  217. ast_free(tmp_matrix[x]);
  218. }
  219. ast_free(tmp_matrix);
  220. }
  221. ast_free(tmp_table);
  222. return -1;
  223. }
  224. /*!
  225. * \internal
  226. * \brief reinitialize the __matrix during matrix rebuild
  227. *
  228. * \note must be protected by the translators list lock
  229. */
  230. static void matrix_clear(void)
  231. {
  232. int x;
  233. for (x = 0; x < index_size; x++) {
  234. memset(__matrix[x], '\0', sizeof(struct translator_path) * (index_size));
  235. }
  236. }
  237. /*!
  238. * \internal
  239. * \brief get a matrix entry
  240. *
  241. * \note This function must be protected by the translators list lock
  242. */
  243. static struct translator_path *matrix_get(unsigned int x, unsigned int y)
  244. {
  245. return __matrix[x] + y;
  246. }
  247. /*
  248. * wrappers around the translator routines.
  249. */
  250. static void destroy(struct ast_trans_pvt *pvt)
  251. {
  252. struct ast_translator *t = pvt->t;
  253. if (t->destroy) {
  254. t->destroy(pvt);
  255. }
  256. ao2_cleanup(pvt->f.subclass.format);
  257. if (pvt->explicit_dst) {
  258. ao2_ref(pvt->explicit_dst, -1);
  259. pvt->explicit_dst = NULL;
  260. }
  261. ast_free(pvt);
  262. ast_module_unref(t->module);
  263. }
  264. /*!
  265. * \brief Allocate the descriptor, required outbuf space,
  266. * and possibly desc.
  267. */
  268. static struct ast_trans_pvt *newpvt(struct ast_translator *t, struct ast_format *explicit_dst)
  269. {
  270. struct ast_trans_pvt *pvt;
  271. int len;
  272. char *ofs;
  273. /*
  274. * compute the required size adding private descriptor,
  275. * buffer, AST_FRIENDLY_OFFSET.
  276. */
  277. len = sizeof(*pvt) + t->desc_size;
  278. if (t->buf_size)
  279. len += AST_FRIENDLY_OFFSET + t->buf_size;
  280. pvt = ast_calloc(1, len);
  281. if (!pvt) {
  282. return NULL;
  283. }
  284. pvt->t = t;
  285. ofs = (char *)(pvt + 1); /* pointer to data space */
  286. if (t->desc_size) { /* first comes the descriptor */
  287. pvt->pvt = ofs;
  288. ofs += t->desc_size;
  289. }
  290. if (t->buf_size) {/* finally buffer and header */
  291. pvt->outbuf.c = ofs + AST_FRIENDLY_OFFSET;
  292. }
  293. /*
  294. * If the format has an attribute module, explicit_dst includes the (joined)
  295. * result of the SDP negotiation. For example with the Opus Codec, the format
  296. * knows whether both parties want to do forward-error correction (FEC).
  297. */
  298. pvt->explicit_dst = ao2_bump(explicit_dst);
  299. ast_module_ref(t->module);
  300. /* call local init routine, if present */
  301. if (t->newpvt && t->newpvt(pvt)) {
  302. ast_free(pvt);
  303. ast_module_unref(t->module);
  304. return NULL;
  305. }
  306. /* Setup normal static translation frame. */
  307. pvt->f.frametype = AST_FRAME_VOICE;
  308. pvt->f.mallocd = 0;
  309. pvt->f.offset = AST_FRIENDLY_OFFSET;
  310. pvt->f.src = pvt->t->name;
  311. pvt->f.data.ptr = pvt->outbuf.c;
  312. /*
  313. * If the translator has not provided a format
  314. * A) use the joined one,
  315. * B) use the cached one, or
  316. * C) create one.
  317. */
  318. if (!pvt->f.subclass.format) {
  319. pvt->f.subclass.format = ao2_bump(pvt->explicit_dst);
  320. if (!pvt->f.subclass.format && !ast_strlen_zero(pvt->t->format)) {
  321. pvt->f.subclass.format = ast_format_cache_get(pvt->t->format);
  322. }
  323. if (!pvt->f.subclass.format) {
  324. struct ast_codec *codec = ast_codec_get(t->dst_codec.name,
  325. t->dst_codec.type, t->dst_codec.sample_rate);
  326. if (!codec) {
  327. ast_log(LOG_ERROR, "Unable to get destination codec\n");
  328. destroy(pvt);
  329. return NULL;
  330. }
  331. pvt->f.subclass.format = ast_format_create(codec);
  332. ao2_ref(codec, -1);
  333. }
  334. if (!pvt->f.subclass.format) {
  335. ast_log(LOG_ERROR, "Unable to create format\n");
  336. destroy(pvt);
  337. return NULL;
  338. }
  339. }
  340. return pvt;
  341. }
  342. /*! \brief framein wrapper, deals with bound checks. */
  343. static int framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
  344. {
  345. /* Copy the last in jb timing info to the pvt */
  346. ast_copy_flags(&pvt->f, f, AST_FRFLAG_HAS_TIMING_INFO);
  347. pvt->f.ts = f->ts;
  348. pvt->f.len = f->len;
  349. pvt->f.seqno = f->seqno;
  350. if (f->samples == 0) {
  351. /* Do not log empty audio frame */
  352. if (!f->src || strcasecmp(f->src, "ast_prod")) {
  353. ast_log(LOG_WARNING, "no samples for %s\n", pvt->t->name);
  354. }
  355. }
  356. if (pvt->t->buffer_samples) { /* do not pass empty frames to callback */
  357. int src_srate = pvt->t->src_codec.sample_rate;
  358. int dst_srate = pvt->t->dst_codec.sample_rate;
  359. ast_assert(src_srate > 0);
  360. if (f->datalen == 0) { /* perform native PLC if available */
  361. /* If the codec has native PLC, then do that */
  362. if (!pvt->t->native_plc)
  363. return 0;
  364. }
  365. if (pvt->samples + (f->samples * dst_srate / src_srate) > pvt->t->buffer_samples) {
  366. ast_log(LOG_WARNING, "Out of buffer space\n");
  367. return -1;
  368. }
  369. }
  370. /* we require a framein routine, wouldn't know how to do
  371. * it otherwise.
  372. */
  373. return pvt->t->framein(pvt, f);
  374. }
  375. /*! \brief generic frameout routine.
  376. * If samples and datalen are 0, take whatever is in pvt
  377. * and reset them, otherwise take the values in the caller and
  378. * leave alone the pvt values.
  379. */
  380. struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
  381. int datalen, int samples)
  382. {
  383. struct ast_frame *f = &pvt->f;
  384. if (samples) {
  385. f->samples = samples;
  386. } else {
  387. if (pvt->samples == 0) {
  388. return NULL;
  389. }
  390. f->samples = pvt->samples;
  391. pvt->samples = 0;
  392. }
  393. if (datalen) {
  394. f->datalen = datalen;
  395. f->data.ptr = pvt->outbuf.c;
  396. } else {
  397. f->datalen = pvt->datalen;
  398. if (!f->datalen) {
  399. f->data.ptr = NULL;
  400. } else {
  401. f->data.ptr = pvt->outbuf.c;
  402. }
  403. pvt->datalen = 0;
  404. }
  405. return ast_frisolate(f);
  406. }
  407. static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
  408. {
  409. return ast_trans_frameout(pvt, 0, 0);
  410. }
  411. /* end of callback wrappers and helpers */
  412. void ast_translator_free_path(struct ast_trans_pvt *p)
  413. {
  414. struct ast_trans_pvt *pn = p;
  415. while ( (p = pn) ) {
  416. pn = p->next;
  417. destroy(p);
  418. }
  419. }
  420. /*! \brief Build a chain of translators based upon the given source and dest formats */
  421. struct ast_trans_pvt *ast_translator_build_path(struct ast_format *dst, struct ast_format *src)
  422. {
  423. struct ast_trans_pvt *head = NULL, *tail = NULL;
  424. int src_index, dst_index;
  425. src_index = format2index(src);
  426. dst_index = format2index(dst);
  427. if (src_index < 0 || dst_index < 0) {
  428. ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", src_index < 0 ? "starting" : "ending");
  429. return NULL;
  430. }
  431. AST_RWLIST_RDLOCK(&translators);
  432. while (src_index != dst_index) {
  433. struct ast_trans_pvt *cur;
  434. struct ast_format *explicit_dst = NULL;
  435. struct ast_translator *t = matrix_get(src_index, dst_index)->step;
  436. if (!t) {
  437. ast_log(LOG_WARNING, "No translator path from %s to %s\n",
  438. ast_format_get_name(src), ast_format_get_name(dst));
  439. AST_RWLIST_UNLOCK(&translators);
  440. ast_translator_free_path(head);
  441. return NULL;
  442. }
  443. if ((t->dst_codec.sample_rate == ast_format_get_sample_rate(dst)) && (t->dst_codec.type == ast_format_get_type(dst))) {
  444. explicit_dst = dst;
  445. }
  446. if (!(cur = newpvt(t, explicit_dst))) {
  447. ast_log(LOG_WARNING, "Failed to build translator step from %s to %s\n",
  448. ast_format_get_name(src), ast_format_get_name(dst));
  449. ast_translator_free_path(head);
  450. AST_RWLIST_UNLOCK(&translators);
  451. return NULL;
  452. }
  453. if (!head) {
  454. head = cur;
  455. } else {
  456. tail->next = cur;
  457. }
  458. tail = cur;
  459. cur->nextin = cur->nextout = ast_tv(0, 0);
  460. /* Keep going if this isn't the final destination */
  461. src_index = cur->t->dst_fmt_index;
  462. }
  463. AST_RWLIST_UNLOCK(&translators);
  464. return head;
  465. }
  466. static struct ast_frame *generate_interpolated_slin(struct ast_trans_pvt *p, struct ast_frame *f)
  467. {
  468. struct ast_frame res = { AST_FRAME_VOICE };
  469. /*
  470. * If we've gotten here then we should have an interpolated frame that was not handled
  471. * by the translation codec. So create an interpolated frame in the appropriate format
  472. * that was going to be written. This frame might be handled later by other resources.
  473. * For instance, generic plc.
  474. *
  475. * Note, generic plc is currently only available for the format type 'slin' (8KHz only -
  476. * The generic plc code appears to have been based around that). Generic plc is filled
  477. * in later on frame write.
  478. */
  479. if (!ast_opt_generic_plc || f->datalen != 0 ||
  480. ast_format_cmp(p->explicit_dst, ast_format_slin) == AST_FORMAT_CMP_NOT_EQUAL) {
  481. return NULL;
  482. }
  483. res.subclass.format = ast_format_cache_get_slin_by_rate(8000); /* ref bumped on dup */
  484. res.samples = f->samples;
  485. res.datalen = 0;
  486. res.data.ptr = NULL;
  487. res.offset = AST_FRIENDLY_OFFSET;
  488. return ast_frdup(&res);
  489. }
  490. /*! \brief do the actual translation */
  491. struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
  492. {
  493. struct ast_trans_pvt *p = path;
  494. struct ast_frame *out;
  495. struct timeval delivery;
  496. int has_timing_info;
  497. long ts;
  498. long len;
  499. int seqno;
  500. if (f->frametype == AST_FRAME_RTCP) {
  501. /* Just pass the feedback to the right callback, if it exists.
  502. * This "translation" does nothing so return a null frame. */
  503. struct ast_trans_pvt *tp;
  504. for (tp = p; tp; tp = tp->next) {
  505. if (tp->t->feedback)
  506. tp->t->feedback(tp, f);
  507. }
  508. return &ast_null_frame;
  509. }
  510. has_timing_info = ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO);
  511. ts = f->ts;
  512. len = f->len;
  513. seqno = f->seqno;
  514. if (!ast_tvzero(f->delivery)) {
  515. if (!ast_tvzero(path->nextin)) {
  516. /* Make sure this is in line with what we were expecting */
  517. if (!ast_tveq(path->nextin, f->delivery)) {
  518. /* The time has changed between what we expected and this
  519. most recent time on the new packet. If we have a
  520. valid prediction adjust our output time appropriately */
  521. if (!ast_tvzero(path->nextout)) {
  522. path->nextout = ast_tvadd(path->nextout,
  523. ast_tvsub(f->delivery, path->nextin));
  524. }
  525. path->nextin = f->delivery;
  526. }
  527. } else {
  528. /* This is our first pass. Make sure the timing looks good */
  529. path->nextin = f->delivery;
  530. path->nextout = f->delivery;
  531. }
  532. /* Predict next incoming sample */
  533. path->nextin = ast_tvadd(path->nextin, ast_samp2tv(
  534. f->samples, ast_format_get_sample_rate(f->subclass.format)));
  535. }
  536. delivery = f->delivery;
  537. for (out = f; out && p ; p = p->next) {
  538. struct ast_frame *current = out;
  539. do {
  540. framein(p, current);
  541. current = AST_LIST_NEXT(current, frame_list);
  542. } while (current);
  543. if (out != f) {
  544. ast_frfree(out);
  545. }
  546. out = p->t->frameout(p);
  547. }
  548. if (!out) {
  549. out = generate_interpolated_slin(path, f);
  550. }
  551. if (out) {
  552. /* we have a frame, play with times */
  553. if (!ast_tvzero(delivery)) {
  554. struct ast_frame *current = out;
  555. do {
  556. /* Regenerate prediction after a discontinuity */
  557. if (ast_tvzero(path->nextout)) {
  558. path->nextout = ast_tvnow();
  559. }
  560. /* Use next predicted outgoing timestamp */
  561. current->delivery = path->nextout;
  562. /* Invalidate prediction if we're entering a silence period */
  563. if (current->frametype == AST_FRAME_CNG) {
  564. path->nextout = ast_tv(0, 0);
  565. /* Predict next outgoing timestamp from samples in this
  566. frame. */
  567. } else {
  568. path->nextout = ast_tvadd(path->nextout, ast_samp2tv(
  569. current->samples, ast_format_get_sample_rate(current->subclass.format)));
  570. }
  571. if (f->samples != current->samples && ast_test_flag(current, AST_FRFLAG_HAS_TIMING_INFO)) {
  572. ast_debug(4, "Sample size different %d vs %d\n", f->samples, current->samples);
  573. ast_clear_flag(current, AST_FRFLAG_HAS_TIMING_INFO);
  574. }
  575. current = AST_LIST_NEXT(current, frame_list);
  576. } while (current);
  577. } else {
  578. out->delivery = ast_tv(0, 0);
  579. ast_set2_flag(out, has_timing_info, AST_FRFLAG_HAS_TIMING_INFO);
  580. if (has_timing_info) {
  581. out->ts = ts;
  582. out->len = len;
  583. out->seqno = seqno;
  584. }
  585. /* Invalidate prediction if we're entering a silence period */
  586. if (out->frametype == AST_FRAME_CNG) {
  587. path->nextout = ast_tv(0, 0);
  588. }
  589. }
  590. }
  591. if (consume) {
  592. ast_frfree(f);
  593. }
  594. return out;
  595. }
  596. /*!
  597. * \internal
  598. * \brief Compute the computational cost of a single translation step.
  599. *
  600. * \note This function is only used to decide which translation path to
  601. * use between two translators with identical src and dst formats. Computational
  602. * cost acts only as a tie breaker. This is done so hardware translators
  603. * can naturally have precedence over software translators.
  604. */
  605. static void generate_computational_cost(struct ast_translator *t, int seconds)
  606. {
  607. int num_samples = 0;
  608. struct ast_trans_pvt *pvt;
  609. struct rusage start;
  610. struct rusage end;
  611. int cost;
  612. int out_rate = t->dst_codec.sample_rate;
  613. if (!seconds) {
  614. seconds = 1;
  615. }
  616. /* If they don't make samples, give them a terrible score */
  617. if (!t->sample) {
  618. ast_debug(3, "Translator '%s' does not produce sample frames.\n", t->name);
  619. t->comp_cost = 999999;
  620. return;
  621. }
  622. pvt = newpvt(t, NULL);
  623. if (!pvt) {
  624. ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
  625. t->comp_cost = 999999;
  626. return;
  627. }
  628. getrusage(RUSAGE_SELF, &start);
  629. /* Call the encoder until we've processed the required number of samples */
  630. while (num_samples < seconds * out_rate) {
  631. struct ast_frame *f = t->sample();
  632. if (!f) {
  633. ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
  634. destroy(pvt);
  635. t->comp_cost = 999999;
  636. return;
  637. }
  638. framein(pvt, f);
  639. ast_frfree(f);
  640. while ((f = t->frameout(pvt))) {
  641. num_samples += f->samples;
  642. ast_frfree(f);
  643. }
  644. }
  645. getrusage(RUSAGE_SELF, &end);
  646. cost = ((end.ru_utime.tv_sec - start.ru_utime.tv_sec) * 1000000) + end.ru_utime.tv_usec - start.ru_utime.tv_usec;
  647. cost += ((end.ru_stime.tv_sec - start.ru_stime.tv_sec) * 1000000) + end.ru_stime.tv_usec - start.ru_stime.tv_usec;
  648. destroy(pvt);
  649. t->comp_cost = cost / seconds;
  650. if (!t->comp_cost) {
  651. t->comp_cost = 1;
  652. }
  653. }
  654. /*!
  655. * \internal
  656. *
  657. * \brief If no table cost value was pre set by the translator. An attempt is made to
  658. * automatically generate that cost value from the cost table based on our src and
  659. * dst formats.
  660. *
  661. * \note This function allows older translators built before the translation cost
  662. * changed away from using onely computational time to continue to be registered
  663. * correctly. It is expected that translators built after the introduction of this
  664. * function will manually assign their own table cost value.
  665. *
  666. * \note This function is safe to use on any audio formats that used to be defined in the
  667. * first 64 bits of the old bit field codec representation.
  668. *
  669. * \return Table Cost value greater than 0.
  670. * \retval 0 on error.
  671. */
  672. static int generate_table_cost(struct ast_codec *src, struct ast_codec *dst)
  673. {
  674. int src_rate = src->sample_rate;
  675. int src_ll = 0;
  676. int dst_rate = dst->sample_rate;
  677. int dst_ll = 0;
  678. if ((src->type != AST_MEDIA_TYPE_AUDIO) ||
  679. (dst->type != AST_MEDIA_TYPE_AUDIO)) {
  680. /* This method of generating table cost is limited to audio.
  681. * Translators for media other than audio must manually set their
  682. * table cost. */
  683. return 0;
  684. }
  685. src_ll = !strcmp(src->name, "slin");
  686. dst_ll = !strcmp(dst->name, "slin");
  687. if (src_ll) {
  688. if (dst_ll && (src_rate == dst_rate)) {
  689. return AST_TRANS_COST_LL_LL_ORIGSAMP;
  690. } else if (!dst_ll && (src_rate == dst_rate)) {
  691. return AST_TRANS_COST_LL_LY_ORIGSAMP;
  692. } else if (dst_ll && (src_rate < dst_rate)) {
  693. return AST_TRANS_COST_LL_LL_UPSAMP;
  694. } else if (!dst_ll && (src_rate < dst_rate)) {
  695. return AST_TRANS_COST_LL_LY_UPSAMP;
  696. } else if (dst_ll && (src_rate > dst_rate)) {
  697. return AST_TRANS_COST_LL_LL_DOWNSAMP;
  698. } else if (!dst_ll && (src_rate > dst_rate)) {
  699. return AST_TRANS_COST_LL_LY_DOWNSAMP;
  700. } else {
  701. return AST_TRANS_COST_LL_UNKNOWN;
  702. }
  703. } else {
  704. if (dst_ll && (src_rate == dst_rate)) {
  705. return AST_TRANS_COST_LY_LL_ORIGSAMP;
  706. } else if (!dst_ll && (src_rate == dst_rate)) {
  707. return AST_TRANS_COST_LY_LY_ORIGSAMP;
  708. } else if (dst_ll && (src_rate < dst_rate)) {
  709. return AST_TRANS_COST_LY_LL_UPSAMP;
  710. } else if (!dst_ll && (src_rate < dst_rate)) {
  711. return AST_TRANS_COST_LY_LY_UPSAMP;
  712. } else if (dst_ll && (src_rate > dst_rate)) {
  713. return AST_TRANS_COST_LY_LL_DOWNSAMP;
  714. } else if (!dst_ll && (src_rate > dst_rate)) {
  715. return AST_TRANS_COST_LY_LY_DOWNSAMP;
  716. } else {
  717. return AST_TRANS_COST_LY_UNKNOWN;
  718. }
  719. }
  720. }
  721. /*!
  722. * \brief rebuild a translation matrix.
  723. * \note This function expects the list of translators to be locked
  724. */
  725. static void matrix_rebuild(int samples)
  726. {
  727. struct ast_translator *t;
  728. int newtablecost;
  729. int x; /* source format index */
  730. int y; /* intermediate format index */
  731. int z; /* destination format index */
  732. ast_debug(1, "Resetting translation matrix\n");
  733. matrix_clear();
  734. /* first, compute all direct costs */
  735. AST_RWLIST_TRAVERSE(&translators, t, list) {
  736. if (!t->active) {
  737. continue;
  738. }
  739. x = t->src_fmt_index;
  740. z = t->dst_fmt_index;
  741. if (samples) {
  742. generate_computational_cost(t, samples);
  743. }
  744. /* This new translator is the best choice if any of the below are true.
  745. * 1. no translation path is set between x and z yet.
  746. * 2. the new table cost is less.
  747. * 3. the new computational cost is less. Computational cost is only used
  748. * to break a tie between two identical translation paths.
  749. */
  750. if (!matrix_get(x, z)->step ||
  751. (t->table_cost < matrix_get(x, z)->step->table_cost) ||
  752. (t->comp_cost < matrix_get(x, z)->step->comp_cost)) {
  753. matrix_get(x, z)->step = t;
  754. matrix_get(x, z)->table_cost = t->table_cost;
  755. matrix_get(x, z)->comp_cost = t->comp_cost;
  756. }
  757. }
  758. /*
  759. * For each triple x, y, z of distinct formats, check if there is
  760. * a path from x to z through y which is cheaper than what is
  761. * currently known, and in case, update the matrix.
  762. * Repeat until the matrix is stable.
  763. */
  764. for (;;) {
  765. int changed = 0;
  766. for (x = 0; x < cur_max_index; x++) { /* source format */
  767. for (y = 0; y < cur_max_index; y++) { /* intermediate format */
  768. if (x == y) { /* skip ourselves */
  769. continue;
  770. }
  771. for (z = 0; z < cur_max_index; z++) { /* dst format */
  772. if ((z == x || z == y) || /* skip null conversions */
  773. !matrix_get(x, y)->step || /* no path from x to y */
  774. !matrix_get(y, z)->step) { /* no path from y to z */
  775. continue;
  776. }
  777. /* calculate table cost from x->y->z */
  778. newtablecost = matrix_get(x, y)->table_cost + matrix_get(y, z)->table_cost;
  779. /* if no step already exists between x and z OR the new cost of using the intermediate
  780. * step is cheaper, use this step. */
  781. if (!matrix_get(x, z)->step || (newtablecost < matrix_get(x, z)->table_cost)) {
  782. matrix_get(x, z)->step = matrix_get(x, y)->step;
  783. matrix_get(x, z)->table_cost = newtablecost;
  784. matrix_get(x, z)->multistep = 1;
  785. changed++;
  786. if (DEBUG_ATLEAST(10)) {
  787. struct ast_codec *x_codec = index2codec(x);
  788. struct ast_codec *y_codec = index2codec(y);
  789. struct ast_codec *z_codec = index2codec(z);
  790. ast_log(LOG_DEBUG,
  791. "Discovered %u cost path from %s to %s, via %s\n",
  792. matrix_get(x, z)->table_cost, x_codec->name,
  793. y_codec->name, z_codec->name);
  794. ao2_ref(x_codec, -1);
  795. ao2_ref(y_codec, -1);
  796. ao2_ref(z_codec, -1);
  797. }
  798. }
  799. }
  800. }
  801. }
  802. if (!changed) {
  803. break;
  804. }
  805. }
  806. }
  807. static void codec_append_name(const struct ast_codec *codec, struct ast_str **buf)
  808. {
  809. if (codec) {
  810. ast_str_append(buf, 0, "(%s@%u)", codec->name, codec->sample_rate);
  811. } else {
  812. ast_str_append(buf, 0, "(nothing)");
  813. }
  814. }
  815. const char *ast_translate_path_to_str(struct ast_trans_pvt *p, struct ast_str **str)
  816. {
  817. if (!p || !p->t) {
  818. return "";
  819. }
  820. ast_str_reset(*str);
  821. codec_append_name(&p->t->src_codec, str);
  822. while (p) {
  823. ast_str_append(str, 0, "->");
  824. codec_append_name(&p->t->dst_codec, str);
  825. p = p->next;
  826. }
  827. return ast_str_buffer(*str);
  828. }
  829. static char *complete_trans_path_choice(const char *word)
  830. {
  831. int i = 1;
  832. int wordlen = strlen(word);
  833. struct ast_codec *codec;
  834. while ((codec = ast_codec_get_by_id(i))) {
  835. ++i;
  836. if (codec->type != AST_MEDIA_TYPE_AUDIO) {
  837. ao2_ref(codec, -1);
  838. continue;
  839. }
  840. if (!strncasecmp(word, codec->name, wordlen)) {
  841. if (ast_cli_completion_add(ast_strdup(codec->name))) {
  842. ao2_ref(codec, -1);
  843. break;
  844. }
  845. }
  846. ao2_ref(codec, -1);
  847. }
  848. return NULL;
  849. }
  850. static void handle_cli_recalc(struct ast_cli_args *a)
  851. {
  852. int time = a->argv[4] ? atoi(a->argv[4]) : 1;
  853. if (time <= 0) {
  854. ast_cli(a->fd, " Recalc must be greater than 0. Defaulting to 1.\n");
  855. time = 1;
  856. }
  857. if (time > MAX_RECALC) {
  858. ast_cli(a->fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", time - MAX_RECALC, MAX_RECALC);
  859. time = MAX_RECALC;
  860. }
  861. ast_cli(a->fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", time);
  862. AST_RWLIST_WRLOCK(&translators);
  863. matrix_rebuild(time);
  864. AST_RWLIST_UNLOCK(&translators);
  865. }
  866. static char *handle_show_translation_table(struct ast_cli_args *a)
  867. {
  868. int x, y, i, k, compCost;
  869. int longest = 7; /* slin192 */
  870. int max_codec_index = 0, curlen = 0;
  871. struct ast_str *out = ast_str_create(1024);
  872. struct ast_codec *codec;
  873. /* Get the length of the longest (usable?) codec name,
  874. so we know how wide the left side should be */
  875. for (i = 1; (codec = ast_codec_get_by_id(i)); ao2_ref(codec, -1), ++i) {
  876. ++max_codec_index;
  877. if (codec->type != AST_MEDIA_TYPE_AUDIO) {
  878. continue;
  879. }
  880. curlen = strlen(codec->name);
  881. if (curlen > longest) {
  882. longest = curlen;
  883. }
  884. }
  885. AST_RWLIST_RDLOCK(&translators);
  886. ast_cli(a->fd, " Translation times between formats (in microseconds) for one second of data\n");
  887. ast_cli(a->fd, " Source Format (Rows) Destination Format (Columns)\n\n");
  888. for (i = 0; i <= max_codec_index; i++) {
  889. struct ast_codec *row = i ? ast_codec_get_by_id(i) : NULL;
  890. x = -1;
  891. if ((i > 0) && (row->type != AST_MEDIA_TYPE_AUDIO)) {
  892. ao2_ref(row, -1);
  893. continue;
  894. }
  895. if ((i > 0) && (x = codec2index(row)) == -1) {
  896. ao2_ref(row, -1);
  897. continue;
  898. }
  899. ast_str_set(&out, 0, " ");
  900. for (k = 0; k <= max_codec_index; k++) {
  901. int adjust = 0;
  902. struct ast_codec *col = k ? ast_codec_get_by_id(k) : NULL;
  903. y = -1;
  904. if ((k > 0) && (col->type != AST_MEDIA_TYPE_AUDIO)) {
  905. ao2_ref(col, -1);
  906. continue;
  907. }
  908. if ((k > 0) && (y = codec2index(col)) == -1) {
  909. ao2_ref(col, -1);
  910. continue;
  911. }
  912. if (k > 0) {
  913. curlen = strlen(col->name);
  914. if (!strcmp(col->name, "slin") ||
  915. !strcmp(col->name, "speex") ||
  916. !strcmp(col->name, "silk")) {
  917. adjust = log10(col->sample_rate / 1000) + 1;
  918. curlen = curlen + adjust;
  919. }
  920. }
  921. if (curlen < 5) {
  922. curlen = 5;
  923. }
  924. if (x >= 0 && y >= 0 && matrix_get(x, y)->step) {
  925. /* Actual codec output */
  926. if (a->argv[3] && !strcasecmp(a->argv[3], "comp")) {
  927. compCost = matrix_get(x, y)->comp_cost;
  928. if (compCost == 0 || compCost == 999999) {
  929. ast_str_append(&out, 0, "%*s", curlen + 1, "-");
  930. } else {
  931. ast_str_append(&out, 0, "%*u", curlen + 1, compCost);
  932. }
  933. } else {
  934. ast_str_append(&out, 0, "%*u", curlen + 1, (matrix_get(x, y)->table_cost / 100));
  935. }
  936. } else if (i == 0 && k > 0) {
  937. /* Top row - use a dynamic size */
  938. if (!strcmp(col->name, "slin") ||
  939. !strcmp(col->name, "speex") ||
  940. !strcmp(col->name, "silk")) {
  941. ast_str_append(&out, 0, "%*s%u", curlen - adjust + 1,
  942. col->name, col->sample_rate / 1000);
  943. } else {
  944. ast_str_append(&out, 0, "%*s", curlen + 1, col->name);
  945. }
  946. } else if (k == 0 && i > 0) {
  947. /* Left column - use a static size. */
  948. if (!strcmp(row->name, "slin") ||
  949. !strcmp(row->name, "speex") ||
  950. !strcmp(row->name, "silk")) {
  951. int adjust_row = log10(row->sample_rate / 1000) + 1;
  952. ast_str_append(&out, 0, "%*s%u", longest - adjust_row,
  953. row->name, row->sample_rate / 1000);
  954. } else {
  955. ast_str_append(&out, 0, "%*s", longest, row->name);
  956. }
  957. } else if (x >= 0 && y >= 0) {
  958. /* Codec not supported */
  959. ast_str_append(&out, 0, "%*s", curlen + 1, "-");
  960. } else {
  961. /* Upper left hand corner */
  962. ast_str_append(&out, 0, "%*s", longest, "");
  963. }
  964. ao2_cleanup(col);
  965. }
  966. ast_str_append(&out, 0, "\n");
  967. ast_cli(a->fd, "%s", ast_str_buffer(out));
  968. ao2_cleanup(row);
  969. }
  970. ast_free(out);
  971. AST_RWLIST_UNLOCK(&translators);
  972. return CLI_SUCCESS;
  973. }
  974. static char *handle_show_translation_path(struct ast_cli_args *a, const char *codec_name, unsigned int sample_rate)
  975. {
  976. int i = 1;
  977. struct ast_str *str = ast_str_alloca(1024);
  978. struct ast_translator *step;
  979. struct ast_codec *dst_codec;
  980. struct ast_codec *src_codec = ast_codec_get(codec_name, AST_MEDIA_TYPE_AUDIO, sample_rate);
  981. if (!src_codec) {
  982. ast_cli(a->fd, "Source codec \"%s\" is not found.\n", codec_name);
  983. return CLI_FAILURE;
  984. }
  985. AST_RWLIST_RDLOCK(&translators);
  986. ast_cli(a->fd, "--- Translation paths SRC Codec \"%s\" sample rate %u ---\n",
  987. codec_name, src_codec->sample_rate);
  988. while ((dst_codec = ast_codec_get_by_id(i))) {
  989. int src, dst;
  990. char src_buffer[64];
  991. char dst_buffer[64];
  992. ++i;
  993. if (src_codec == dst_codec ||
  994. dst_codec->type != AST_MEDIA_TYPE_AUDIO) {
  995. ao2_ref(dst_codec, -1);
  996. continue;
  997. }
  998. dst = codec2index(dst_codec);
  999. src = codec2index(src_codec);
  1000. if (src < 0 || dst < 0) {
  1001. ast_str_set(&str, 0, "No Translation Path");
  1002. } else {
  1003. step = matrix_get(src, dst)->step;
  1004. if (step) {
  1005. codec_append_name(&step->src_codec, &str);
  1006. while (src != dst) {
  1007. src = step->dst_fmt_index;
  1008. step = matrix_get(src, dst)->step;
  1009. if (!step) {
  1010. ast_str_append(&str, 0, "->");
  1011. codec_append_name(dst_codec, &str);
  1012. break;
  1013. }
  1014. ast_str_append(&str, 0, "->");
  1015. codec_append_name(&step->src_codec, &str);
  1016. }
  1017. }
  1018. }
  1019. snprintf(src_buffer, sizeof(src_buffer), "%s:%u", src_codec->name, src_codec->sample_rate);
  1020. snprintf(dst_buffer, sizeof(dst_buffer), "%s:%u", dst_codec->name, dst_codec->sample_rate);
  1021. ast_cli(a->fd, "\t%-16.16s To %-16.16s: %-60.60s\n",
  1022. src_buffer, dst_buffer, ast_str_buffer(str));
  1023. ast_str_reset(str);
  1024. ao2_ref(dst_codec, -1);
  1025. }
  1026. AST_RWLIST_UNLOCK(&translators);
  1027. ao2_ref(src_codec, -1);
  1028. return CLI_SUCCESS;
  1029. }
  1030. static char *handle_cli_core_show_translation(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1031. {
  1032. static const char * const option[] = { "recalc", "paths", "comp", NULL };
  1033. switch (cmd) {
  1034. case CLI_INIT:
  1035. e->command = "core show translation";
  1036. e->usage =
  1037. "Usage: 'core show translation' can be used in three ways.\n"
  1038. " 1. 'core show translation [recalc [<recalc seconds>]\n"
  1039. " Displays known codec translators and the cost associated\n"
  1040. " with each conversion. If the argument 'recalc' is supplied along\n"
  1041. " with optional number of seconds to test a new test will be performed\n"
  1042. " as the chart is being displayed.\n"
  1043. " 2. 'core show translation paths [codec [sample_rate]]'\n"
  1044. " This will display all the translation paths associated with a codec.\n"
  1045. " If a codec has multiple sample rates, the sample rate must be\n"
  1046. " provided as well.\n"
  1047. " 3. 'core show translation comp [<recalc seconds>]'\n"
  1048. " Displays known codec translators and the cost associated\n"
  1049. " with each conversion. If the argument 'recalc' is supplied along\n"
  1050. " with optional number of seconds to test a new test will be performed\n"
  1051. " as the chart is being displayed. The resulting numbers in the table\n"
  1052. " give the actual computational costs in microseconds.\n";
  1053. return NULL;
  1054. case CLI_GENERATE:
  1055. if (a->pos == 3) {
  1056. return ast_cli_complete(a->word, option, -1);
  1057. }
  1058. if (a->pos == 4 && !strcasecmp(a->argv[3], option[1])) {
  1059. return complete_trans_path_choice(a->word);
  1060. }
  1061. /* BUGBUG - add tab completion for sample rates */
  1062. return NULL;
  1063. }
  1064. if (a->argc > 6)
  1065. return CLI_SHOWUSAGE;
  1066. if (a->argv[3] && !strcasecmp(a->argv[3], option[1]) && a->argc == 5) { /* show paths */
  1067. return handle_show_translation_path(a, a->argv[4], 0);
  1068. } else if (a->argv[3] && !strcasecmp(a->argv[3], option[1]) && a->argc == 6) {
  1069. unsigned int sample_rate;
  1070. if (sscanf(a->argv[5], "%30u", &sample_rate) != 1) {
  1071. ast_cli(a->fd, "Invalid sample rate: %s.\n", a->argv[5]);
  1072. return CLI_FAILURE;
  1073. }
  1074. return handle_show_translation_path(a, a->argv[4], sample_rate);
  1075. } else if (a->argv[3] && (!strcasecmp(a->argv[3], option[0]) || !strcasecmp(a->argv[3], option[2]))) { /* recalc and then fall through to show table */
  1076. handle_cli_recalc(a);
  1077. } else if (a->argc > 3) { /* wrong input */
  1078. return CLI_SHOWUSAGE;
  1079. }
  1080. return handle_show_translation_table(a);
  1081. }
  1082. static struct ast_cli_entry cli_translate[] = {
  1083. AST_CLI_DEFINE(handle_cli_core_show_translation, "Display translation matrix")
  1084. };
  1085. /*! \brief register codec translator */
  1086. int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
  1087. {
  1088. struct ast_translator *u;
  1089. char tmp[80];
  1090. RAII_VAR(struct ast_codec *, src_codec, NULL, ao2_cleanup);
  1091. RAII_VAR(struct ast_codec *, dst_codec, NULL, ao2_cleanup);
  1092. src_codec = ast_codec_get(t->src_codec.name, t->src_codec.type, t->src_codec.sample_rate);
  1093. if (!src_codec) {
  1094. ast_assert(0);
  1095. ast_log(LOG_WARNING, "Failed to register translator: unknown source codec %s\n", t->src_codec.name);
  1096. return -1;
  1097. }
  1098. dst_codec = ast_codec_get(t->dst_codec.name, t->dst_codec.type, t->dst_codec.sample_rate);
  1099. if (!dst_codec) {
  1100. ast_log(LOG_WARNING, "Failed to register translator: unknown destination codec %s\n", t->dst_codec.name);
  1101. return -1;
  1102. }
  1103. if (add_codec2index(src_codec) || add_codec2index(dst_codec)) {
  1104. if (matrix_resize(0)) {
  1105. ast_log(LOG_WARNING, "Translator matrix can not represent any more translators. Out of resources.\n");
  1106. return -1;
  1107. }
  1108. add_codec2index(src_codec);
  1109. add_codec2index(dst_codec);
  1110. }
  1111. if (!mod) {
  1112. ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
  1113. return -1;
  1114. }
  1115. if (!t->buf_size) {
  1116. ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
  1117. return -1;
  1118. }
  1119. if (!t->table_cost && !(t->table_cost = generate_table_cost(src_codec, dst_codec))) {
  1120. ast_log(LOG_WARNING, "Table cost could not be generated for %s, "
  1121. "Please set table_cost variable on translator.\n", t->name);
  1122. return -1;
  1123. }
  1124. t->module = mod;
  1125. t->src_fmt_index = codec2index(src_codec);
  1126. t->dst_fmt_index = codec2index(dst_codec);
  1127. t->active = 1;
  1128. if (t->src_fmt_index < 0 || t->dst_fmt_index < 0) {
  1129. ast_log(LOG_WARNING, "Invalid translator path: (%s codec is not valid)\n", t->src_fmt_index < 0 ? "starting" : "ending");
  1130. return -1;
  1131. }
  1132. if (t->src_fmt_index >= cur_max_index) {
  1133. ast_log(LOG_WARNING, "Source codec %s is larger than cur_max_index\n", t->src_codec.name);
  1134. return -1;
  1135. }
  1136. if (t->dst_fmt_index >= cur_max_index) {
  1137. ast_log(LOG_WARNING, "Destination codec %s is larger than cur_max_index\n", t->dst_codec.name);
  1138. return -1;
  1139. }
  1140. if (t->buf_size) {
  1141. /*
  1142. * Align buf_size properly, rounding up to the machine-specific
  1143. * alignment for pointers.
  1144. */
  1145. struct _test_align { void *a, *b; } p;
  1146. int align = (char *)&p.b - (char *)&p.a;
  1147. t->buf_size = ((t->buf_size + align - 1) / align) * align;
  1148. }
  1149. if (t->frameout == NULL) {
  1150. t->frameout = default_frameout;
  1151. }
  1152. generate_computational_cost(t, 1);
  1153. ast_verb(5, "Registered translator '%s' from codec %s to %s, table cost, %d, computational cost %d\n",
  1154. term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
  1155. t->src_codec.name, t->dst_codec.name, t->table_cost, t->comp_cost);
  1156. AST_RWLIST_WRLOCK(&translators);
  1157. /* find any existing translators that provide this same srcfmt/dstfmt,
  1158. and put this one in order based on computational cost */
  1159. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
  1160. if ((u->src_fmt_index == t->src_fmt_index) &&
  1161. (u->dst_fmt_index == t->dst_fmt_index) &&
  1162. (u->comp_cost > t->comp_cost)) {
  1163. AST_RWLIST_INSERT_BEFORE_CURRENT(t, list);
  1164. t = NULL;
  1165. break;
  1166. }
  1167. }
  1168. AST_RWLIST_TRAVERSE_SAFE_END;
  1169. /* if no existing translator was found for this codec combination,
  1170. add it to the beginning of the list */
  1171. if (t) {
  1172. AST_RWLIST_INSERT_HEAD(&translators, t, list);
  1173. }
  1174. matrix_rebuild(0);
  1175. AST_RWLIST_UNLOCK(&translators);
  1176. return 0;
  1177. }
  1178. /*! \brief unregister codec translator */
  1179. int ast_unregister_translator(struct ast_translator *t)
  1180. {
  1181. char tmp[80];
  1182. struct ast_translator *u;
  1183. int found = 0;
  1184. AST_RWLIST_WRLOCK(&translators);
  1185. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
  1186. if (u == t) {
  1187. AST_RWLIST_REMOVE_CURRENT(list);
  1188. ast_verb(5, "Unregistered translator '%s' from codec %s to %s\n",
  1189. term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
  1190. t->src_codec.name, t->dst_codec.name);
  1191. found = 1;
  1192. break;
  1193. }
  1194. }
  1195. AST_RWLIST_TRAVERSE_SAFE_END;
  1196. if (found && !ast_shutting_down()) {
  1197. matrix_rebuild(0);
  1198. }
  1199. AST_RWLIST_UNLOCK(&translators);
  1200. return (u ? 0 : -1);
  1201. }
  1202. void ast_translator_activate(struct ast_translator *t)
  1203. {
  1204. AST_RWLIST_WRLOCK(&translators);
  1205. t->active = 1;
  1206. matrix_rebuild(0);
  1207. AST_RWLIST_UNLOCK(&translators);
  1208. }
  1209. void ast_translator_deactivate(struct ast_translator *t)
  1210. {
  1211. AST_RWLIST_WRLOCK(&translators);
  1212. t->active = 0;
  1213. matrix_rebuild(0);
  1214. AST_RWLIST_UNLOCK(&translators);
  1215. }
  1216. /*! Calculate the absolute difference between sample rate of two formats. */
  1217. #define format_sample_rate_absdiff(fmt1, fmt2) ({ \
  1218. unsigned int rate1 = ast_format_get_sample_rate(fmt1); \
  1219. unsigned int rate2 = ast_format_get_sample_rate(fmt2); \
  1220. (rate1 > rate2 ? rate1 - rate2 : rate2 - rate1); \
  1221. })
  1222. /*! \brief Calculate our best translator source format, given costs, and a desired destination */
  1223. int ast_translator_best_choice(struct ast_format_cap *dst_cap,
  1224. struct ast_format_cap *src_cap,
  1225. struct ast_format **dst_fmt_out,
  1226. struct ast_format **src_fmt_out)
  1227. {
  1228. unsigned int besttablecost = INT_MAX;
  1229. unsigned int beststeps = INT_MAX;
  1230. struct ast_format *fmt;
  1231. struct ast_format *dst;
  1232. struct ast_format *src;
  1233. RAII_VAR(struct ast_format *, best, NULL, ao2_cleanup);
  1234. RAII_VAR(struct ast_format *, bestdst, NULL, ao2_cleanup);
  1235. struct ast_format_cap *joint_cap;
  1236. int i;
  1237. int j;
  1238. if (ast_format_cap_empty(dst_cap) || ast_format_cap_empty(src_cap)) {
  1239. ast_log(LOG_ERROR, "Cannot determine best translation path since one capability supports no formats\n");
  1240. return -1;
  1241. }
  1242. joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  1243. if (!joint_cap) {
  1244. return -1;
  1245. }
  1246. ast_format_cap_get_compatible(dst_cap, src_cap, joint_cap);
  1247. for (i = 0; i < ast_format_cap_count(joint_cap); ++i, ao2_cleanup(fmt)) {
  1248. fmt = ast_format_cap_get_format(joint_cap, i);
  1249. if (!fmt
  1250. || ast_format_get_type(fmt) != AST_MEDIA_TYPE_AUDIO) {
  1251. continue;
  1252. }
  1253. if (!best
  1254. || ast_format_get_sample_rate(best) < ast_format_get_sample_rate(fmt)) {
  1255. ao2_replace(best, fmt);
  1256. }
  1257. }
  1258. ao2_ref(joint_cap, -1);
  1259. if (best) {
  1260. ao2_replace(*dst_fmt_out, best);
  1261. ao2_replace(*src_fmt_out, best);
  1262. return 0;
  1263. }
  1264. /* need to translate */
  1265. AST_RWLIST_RDLOCK(&translators);
  1266. for (i = 0; i < ast_format_cap_count(dst_cap); ++i, ao2_cleanup(dst)) {
  1267. dst = ast_format_cap_get_format(dst_cap, i);
  1268. if (!dst
  1269. || ast_format_get_type(dst) != AST_MEDIA_TYPE_AUDIO) {
  1270. continue;
  1271. }
  1272. for (j = 0; j < ast_format_cap_count(src_cap); ++j, ao2_cleanup(src)) {
  1273. int x;
  1274. int y;
  1275. src = ast_format_cap_get_format(src_cap, j);
  1276. if (!src
  1277. || ast_format_get_type(src) != AST_MEDIA_TYPE_AUDIO) {
  1278. continue;
  1279. }
  1280. x = format2index(src);
  1281. y = format2index(dst);
  1282. if (x < 0 || y < 0) {
  1283. continue;
  1284. }
  1285. if (!matrix_get(x, y) || !(matrix_get(x, y)->step)) {
  1286. continue;
  1287. }
  1288. if (matrix_get(x, y)->table_cost < besttablecost
  1289. || matrix_get(x, y)->multistep < beststeps) {
  1290. /* better than what we have so far */
  1291. ao2_replace(best, src);
  1292. ao2_replace(bestdst, dst);
  1293. besttablecost = matrix_get(x, y)->table_cost;
  1294. beststeps = matrix_get(x, y)->multistep;
  1295. } else if (matrix_get(x, y)->table_cost == besttablecost
  1296. && matrix_get(x, y)->multistep == beststeps) {
  1297. int replace = 0;
  1298. unsigned int gap_selected = format_sample_rate_absdiff(best, bestdst);
  1299. unsigned int gap_current = format_sample_rate_absdiff(src, dst);
  1300. if (gap_current < gap_selected) {
  1301. /* better than what we have so far */
  1302. replace = 1;
  1303. } else if (gap_current == gap_selected) {
  1304. int src_quality, best_quality;
  1305. struct ast_codec *src_codec, *best_codec;
  1306. src_codec = ast_format_get_codec(src);
  1307. best_codec = ast_format_get_codec(best);
  1308. src_quality = src_codec->quality;
  1309. best_quality = best_codec->quality;
  1310. ao2_cleanup(src_codec);
  1311. ao2_cleanup(best_codec);
  1312. /* We have a tie, so choose the format with the higher quality, if they differ. */
  1313. if (src_quality > best_quality) {
  1314. /* Better than what we had before. */
  1315. replace = 1;
  1316. ast_debug(2, "Tiebreaker: preferring format %s (%d) to %s (%d)\n", ast_format_get_name(src), src_quality,
  1317. ast_format_get_name(best), best_quality);
  1318. } else {
  1319. /* This isn't necessarily indicative of a problem, but in reality this shouldn't really happen, unless
  1320. * there are 2 formats that are basically the same. */
  1321. ast_debug(1, "Completely ambiguous tie between formats %s and %s (quality %d): sticking with %s, but this is arbitrary\n",
  1322. ast_format_get_name(src), ast_format_get_name(best), best_quality, ast_format_get_name(best));
  1323. }
  1324. }
  1325. if (replace) {
  1326. ao2_replace(best, src);
  1327. ao2_replace(bestdst, dst);
  1328. besttablecost = matrix_get(x, y)->table_cost;
  1329. beststeps = matrix_get(x, y)->multistep;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. AST_RWLIST_UNLOCK(&translators);
  1335. if (!best) {
  1336. return -1;
  1337. }
  1338. ao2_replace(*dst_fmt_out, bestdst);
  1339. ao2_replace(*src_fmt_out, best);
  1340. return 0;
  1341. }
  1342. unsigned int ast_translate_path_steps(struct ast_format *dst_format, struct ast_format *src_format)
  1343. {
  1344. unsigned int res = -1;
  1345. /* convert bitwise format numbers into array indices */
  1346. int src = format2index(src_format);
  1347. int dest = format2index(dst_format);
  1348. if (src < 0 || dest < 0) {
  1349. ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", src < 0 ? "starting" : "ending");
  1350. return -1;
  1351. }
  1352. AST_RWLIST_RDLOCK(&translators);
  1353. if (matrix_get(src, dest)->step) {
  1354. res = matrix_get(src, dest)->multistep + 1;
  1355. }
  1356. AST_RWLIST_UNLOCK(&translators);
  1357. return res;
  1358. }
  1359. static void check_translation_path(
  1360. struct ast_format_cap *dest, struct ast_format_cap *src,
  1361. struct ast_format_cap *result, struct ast_format *src_fmt,
  1362. enum ast_media_type type)
  1363. {
  1364. int i;
  1365. if (ast_format_get_type(src_fmt) != type) {
  1366. return;
  1367. }
  1368. /* For a given source format, traverse the list of
  1369. known formats to determine whether there exists
  1370. a translation path from the source format to the
  1371. destination format. */
  1372. for (i = ast_format_cap_count(result) - 1; 0 <= i; i--) {
  1373. int index, src_index;
  1374. RAII_VAR(struct ast_format *, fmt, ast_format_cap_get_format(result, i), ao2_cleanup);
  1375. if (ast_format_get_type(fmt) != type) {
  1376. continue;
  1377. }
  1378. /* if this is not a desired format, nothing to do */
  1379. if (ast_format_cap_iscompatible_format(dest, fmt) == AST_FORMAT_CMP_NOT_EQUAL) {
  1380. continue;
  1381. }
  1382. /* if the source is supplying this format, then
  1383. we can leave it in the result */
  1384. if (ast_format_cap_iscompatible_format(src, fmt) == AST_FORMAT_CMP_EQUAL) {
  1385. continue;
  1386. }
  1387. /* if this is a pass-through format, not in the source,
  1388. we cannot transcode. Therefore, remove it from the result */
  1389. src_index = format2index(src_fmt);
  1390. index = format2index(fmt);
  1391. if (src_index < 0 || index < 0) {
  1392. ast_format_cap_remove(result, fmt);
  1393. continue;
  1394. }
  1395. /* if we don't have a translation path from the src
  1396. to this format, remove it from the result */
  1397. if (!matrix_get(src_index, index)->step) {
  1398. ast_format_cap_remove(result, fmt);
  1399. continue;
  1400. }
  1401. /* now check the opposite direction */
  1402. if (!matrix_get(index, src_index)->step) {
  1403. ast_format_cap_remove(result, fmt);
  1404. }
  1405. }
  1406. }
  1407. void ast_translate_available_formats(struct ast_format_cap *dest, struct ast_format_cap *src, struct ast_format_cap *result)
  1408. {
  1409. struct ast_format *cur_dest, *cur_src;
  1410. int index;
  1411. for (index = 0; index < ast_format_cap_count(dest); ++index) {
  1412. if (!(cur_dest = ast_format_cap_get_format(dest, index))) {
  1413. continue;
  1414. }
  1415. /* We give preference to a joint format structure if possible */
  1416. if ((cur_src = ast_format_cap_get_compatible_format(src, cur_dest))) {
  1417. ast_format_cap_append(result, cur_src, 0);
  1418. ao2_ref(cur_src, -1);
  1419. } else {
  1420. /* Otherwise we just use the destination format */
  1421. ast_format_cap_append(result, cur_dest, 0);
  1422. }
  1423. ao2_ref(cur_dest, -1);
  1424. }
  1425. /* if we don't have a source format, we just have to try all
  1426. possible destination formats */
  1427. if (!src) {
  1428. return;
  1429. }
  1430. for (index = 0; index < ast_format_cap_count(src); ++index) {
  1431. if (!(cur_src = ast_format_cap_get_format(src, index))) {
  1432. continue;
  1433. }
  1434. AST_RWLIST_RDLOCK(&translators);
  1435. check_translation_path(dest, src, result,
  1436. cur_src, AST_MEDIA_TYPE_AUDIO);
  1437. check_translation_path(dest, src, result,
  1438. cur_src, AST_MEDIA_TYPE_VIDEO);
  1439. AST_RWLIST_UNLOCK(&translators);
  1440. ao2_ref(cur_src, -1);
  1441. }
  1442. }
  1443. static void translate_shutdown(void)
  1444. {
  1445. int x;
  1446. ast_cli_unregister_multiple(cli_translate, ARRAY_LEN(cli_translate));
  1447. ast_rwlock_wrlock(&tablelock);
  1448. for (x = 0; x < index_size; x++) {
  1449. ast_free(__matrix[x]);
  1450. }
  1451. ast_free(__matrix);
  1452. __matrix = NULL;
  1453. ast_free(__indextable);
  1454. __indextable = NULL;
  1455. ast_rwlock_unlock(&tablelock);
  1456. ast_rwlock_destroy(&tablelock);
  1457. }
  1458. int ast_translate_init(void)
  1459. {
  1460. int res = 0;
  1461. ast_rwlock_init(&tablelock);
  1462. res = matrix_resize(1);
  1463. res |= ast_cli_register_multiple(cli_translate, ARRAY_LEN(cli_translate));
  1464. ast_register_cleanup(translate_shutdown);
  1465. return res;
  1466. }