translate.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  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. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  29. #include <sys/time.h>
  30. #include <sys/resource.h>
  31. #include <math.h>
  32. #include "asterisk/lock.h"
  33. #include "asterisk/channel.h"
  34. #include "asterisk/translate.h"
  35. #include "asterisk/module.h"
  36. #include "asterisk/frame.h"
  37. #include "asterisk/sched.h"
  38. #include "asterisk/cli.h"
  39. #include "asterisk/term.h"
  40. #include "asterisk/format.h"
  41. #include "asterisk/linkedlists.h"
  42. /*! \todo
  43. * TODO: sample frames for each supported input format.
  44. * We build this on the fly, by taking an SLIN frame and using
  45. * the existing converter to play with it.
  46. */
  47. /*! max sample recalc */
  48. #define MAX_RECALC 1000
  49. /*! \brief the list of translators */
  50. static AST_RWLIST_HEAD_STATIC(translators, ast_translator);
  51. struct translator_path {
  52. struct ast_translator *step; /*!< Next step translator */
  53. uint32_t table_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 reconstricted 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. ast_log(LOG_WARNING, "no samples for %s\n", pvt->t->name);
  352. }
  353. if (pvt->t->buffer_samples) { /* do not pass empty frames to callback */
  354. if (f->datalen == 0) { /* perform native PLC if available */
  355. /* If the codec has native PLC, then do that */
  356. if (!pvt->t->native_plc)
  357. return 0;
  358. }
  359. if (pvt->samples + f->samples > pvt->t->buffer_samples) {
  360. ast_log(LOG_WARNING, "Out of buffer space\n");
  361. return -1;
  362. }
  363. }
  364. /* we require a framein routine, wouldn't know how to do
  365. * it otherwise.
  366. */
  367. return pvt->t->framein(pvt, f);
  368. }
  369. /*! \brief generic frameout routine.
  370. * If samples and datalen are 0, take whatever is in pvt
  371. * and reset them, otherwise take the values in the caller and
  372. * leave alone the pvt values.
  373. */
  374. struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
  375. int datalen, int samples)
  376. {
  377. struct ast_frame *f = &pvt->f;
  378. if (samples) {
  379. f->samples = samples;
  380. } else {
  381. if (pvt->samples == 0) {
  382. return NULL;
  383. }
  384. f->samples = pvt->samples;
  385. pvt->samples = 0;
  386. }
  387. if (datalen) {
  388. f->datalen = datalen;
  389. f->data.ptr = pvt->outbuf.c;
  390. } else {
  391. f->datalen = pvt->datalen;
  392. if (!f->datalen) {
  393. f->data.ptr = NULL;
  394. } else {
  395. f->data.ptr = pvt->outbuf.c;
  396. }
  397. pvt->datalen = 0;
  398. }
  399. return ast_frisolate(f);
  400. }
  401. static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
  402. {
  403. return ast_trans_frameout(pvt, 0, 0);
  404. }
  405. /* end of callback wrappers and helpers */
  406. void ast_translator_free_path(struct ast_trans_pvt *p)
  407. {
  408. struct ast_trans_pvt *pn = p;
  409. while ( (p = pn) ) {
  410. pn = p->next;
  411. destroy(p);
  412. }
  413. }
  414. /*! \brief Build a chain of translators based upon the given source and dest formats */
  415. struct ast_trans_pvt *ast_translator_build_path(struct ast_format *dst, struct ast_format *src)
  416. {
  417. struct ast_trans_pvt *head = NULL, *tail = NULL;
  418. int src_index, dst_index;
  419. src_index = format2index(src);
  420. dst_index = format2index(dst);
  421. if (src_index < 0 || dst_index < 0) {
  422. ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", src_index < 0 ? "starting" : "ending");
  423. return NULL;
  424. }
  425. AST_RWLIST_RDLOCK(&translators);
  426. while (src_index != dst_index) {
  427. struct ast_trans_pvt *cur;
  428. struct ast_format *explicit_dst = NULL;
  429. struct ast_translator *t = matrix_get(src_index, dst_index)->step;
  430. if (!t) {
  431. ast_log(LOG_WARNING, "No translator path from %s to %s\n",
  432. ast_format_get_name(src), ast_format_get_name(dst));
  433. AST_RWLIST_UNLOCK(&translators);
  434. ast_translator_free_path(head);
  435. return NULL;
  436. }
  437. if ((t->dst_codec.sample_rate == ast_format_get_sample_rate(dst)) && (t->dst_codec.type == ast_format_get_type(dst))) {
  438. explicit_dst = dst;
  439. }
  440. if (!(cur = newpvt(t, explicit_dst))) {
  441. ast_log(LOG_WARNING, "Failed to build translator step from %s to %s\n",
  442. ast_format_get_name(src), ast_format_get_name(dst));
  443. ast_translator_free_path(head);
  444. AST_RWLIST_UNLOCK(&translators);
  445. return NULL;
  446. }
  447. if (!head) {
  448. head = cur;
  449. } else {
  450. tail->next = cur;
  451. }
  452. tail = cur;
  453. cur->nextin = cur->nextout = ast_tv(0, 0);
  454. /* Keep going if this isn't the final destination */
  455. src_index = cur->t->dst_fmt_index;
  456. }
  457. AST_RWLIST_UNLOCK(&translators);
  458. return head;
  459. }
  460. static struct ast_frame *generate_interpolated_slin(struct ast_trans_pvt *p, struct ast_frame *f)
  461. {
  462. struct ast_frame res = { AST_FRAME_VOICE };
  463. /*
  464. * If we've gotten here then we should have an interpolated frame that was not handled
  465. * by the translation codec. So create an interpolated frame in the appropriate format
  466. * that was going to be written. This frame might be handled later by other resources.
  467. * For instance, generic plc.
  468. *
  469. * Note, generic plc is currently only available for the format type 'slin' (8KHz only -
  470. * The generic plc code appears to have been based around that). Generic plc is filled
  471. * in later on frame write.
  472. */
  473. if (!ast_opt_generic_plc || f->datalen != 0 ||
  474. ast_format_cmp(p->explicit_dst, ast_format_slin) == AST_FORMAT_CMP_NOT_EQUAL) {
  475. return NULL;
  476. }
  477. res.subclass.format = ast_format_cache_get_slin_by_rate(8000); /* ref bumped on dup */
  478. res.samples = f->samples;
  479. res.datalen = 0;
  480. res.data.ptr = NULL;
  481. res.offset = AST_FRIENDLY_OFFSET;
  482. return ast_frdup(&res);
  483. }
  484. /*! \brief do the actual translation */
  485. struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
  486. {
  487. struct ast_trans_pvt *p = path;
  488. struct ast_frame *out;
  489. struct timeval delivery;
  490. int has_timing_info;
  491. long ts;
  492. long len;
  493. int seqno;
  494. has_timing_info = ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO);
  495. ts = f->ts;
  496. len = f->len;
  497. seqno = f->seqno;
  498. if (!ast_tvzero(f->delivery)) {
  499. if (!ast_tvzero(path->nextin)) {
  500. /* Make sure this is in line with what we were expecting */
  501. if (!ast_tveq(path->nextin, f->delivery)) {
  502. /* The time has changed between what we expected and this
  503. most recent time on the new packet. If we have a
  504. valid prediction adjust our output time appropriately */
  505. if (!ast_tvzero(path->nextout)) {
  506. path->nextout = ast_tvadd(path->nextout,
  507. ast_tvsub(f->delivery, path->nextin));
  508. }
  509. path->nextin = f->delivery;
  510. }
  511. } else {
  512. /* This is our first pass. Make sure the timing looks good */
  513. path->nextin = f->delivery;
  514. path->nextout = f->delivery;
  515. }
  516. /* Predict next incoming sample */
  517. path->nextin = ast_tvadd(path->nextin, ast_samp2tv(
  518. f->samples, ast_format_get_sample_rate(f->subclass.format)));
  519. }
  520. delivery = f->delivery;
  521. for (out = f; out && p ; p = p->next) {
  522. struct ast_frame *current = out;
  523. do {
  524. framein(p, current);
  525. current = AST_LIST_NEXT(current, frame_list);
  526. } while (current);
  527. if (out != f) {
  528. ast_frfree(out);
  529. }
  530. out = p->t->frameout(p);
  531. }
  532. if (!out) {
  533. out = generate_interpolated_slin(path, f);
  534. }
  535. if (out) {
  536. /* we have a frame, play with times */
  537. if (!ast_tvzero(delivery)) {
  538. struct ast_frame *current = out;
  539. do {
  540. /* Regenerate prediction after a discontinuity */
  541. if (ast_tvzero(path->nextout)) {
  542. path->nextout = ast_tvnow();
  543. }
  544. /* Use next predicted outgoing timestamp */
  545. current->delivery = path->nextout;
  546. /* Invalidate prediction if we're entering a silence period */
  547. if (current->frametype == AST_FRAME_CNG) {
  548. path->nextout = ast_tv(0, 0);
  549. /* Predict next outgoing timestamp from samples in this
  550. frame. */
  551. } else {
  552. path->nextout = ast_tvadd(path->nextout, ast_samp2tv(
  553. current->samples, ast_format_get_sample_rate(current->subclass.format)));
  554. }
  555. if (f->samples != current->samples && ast_test_flag(current, AST_FRFLAG_HAS_TIMING_INFO)) {
  556. ast_debug(4, "Sample size different %d vs %d\n", f->samples, current->samples);
  557. ast_clear_flag(current, AST_FRFLAG_HAS_TIMING_INFO);
  558. }
  559. current = AST_LIST_NEXT(current, frame_list);
  560. } while (current);
  561. } else {
  562. out->delivery = ast_tv(0, 0);
  563. ast_set2_flag(out, has_timing_info, AST_FRFLAG_HAS_TIMING_INFO);
  564. if (has_timing_info) {
  565. out->ts = ts;
  566. out->len = len;
  567. out->seqno = seqno;
  568. }
  569. /* Invalidate prediction if we're entering a silence period */
  570. if (out->frametype == AST_FRAME_CNG) {
  571. path->nextout = ast_tv(0, 0);
  572. }
  573. }
  574. }
  575. if (consume) {
  576. ast_frfree(f);
  577. }
  578. return out;
  579. }
  580. /*!
  581. * \internal
  582. * \brief Compute the computational cost of a single translation step.
  583. *
  584. * \note This function is only used to decide which translation path to
  585. * use between two translators with identical src and dst formats. Computational
  586. * cost acts only as a tie breaker. This is done so hardware translators
  587. * can naturally have precedence over software translators.
  588. */
  589. static void generate_computational_cost(struct ast_translator *t, int seconds)
  590. {
  591. int num_samples = 0;
  592. struct ast_trans_pvt *pvt;
  593. struct rusage start;
  594. struct rusage end;
  595. int cost;
  596. int out_rate = t->dst_codec.sample_rate;
  597. if (!seconds) {
  598. seconds = 1;
  599. }
  600. /* If they don't make samples, give them a terrible score */
  601. if (!t->sample) {
  602. ast_debug(3, "Translator '%s' does not produce sample frames.\n", t->name);
  603. t->comp_cost = 999999;
  604. return;
  605. }
  606. pvt = newpvt(t, NULL);
  607. if (!pvt) {
  608. ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
  609. t->comp_cost = 999999;
  610. return;
  611. }
  612. getrusage(RUSAGE_SELF, &start);
  613. /* Call the encoder until we've processed the required number of samples */
  614. while (num_samples < seconds * out_rate) {
  615. struct ast_frame *f = t->sample();
  616. if (!f) {
  617. ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
  618. destroy(pvt);
  619. t->comp_cost = 999999;
  620. return;
  621. }
  622. framein(pvt, f);
  623. ast_frfree(f);
  624. while ((f = t->frameout(pvt))) {
  625. num_samples += f->samples;
  626. ast_frfree(f);
  627. }
  628. }
  629. getrusage(RUSAGE_SELF, &end);
  630. cost = ((end.ru_utime.tv_sec - start.ru_utime.tv_sec) * 1000000) + end.ru_utime.tv_usec - start.ru_utime.tv_usec;
  631. cost += ((end.ru_stime.tv_sec - start.ru_stime.tv_sec) * 1000000) + end.ru_stime.tv_usec - start.ru_stime.tv_usec;
  632. destroy(pvt);
  633. t->comp_cost = cost / seconds;
  634. if (!t->comp_cost) {
  635. t->comp_cost = 1;
  636. }
  637. }
  638. /*!
  639. * \internal
  640. *
  641. * \brief If no table cost value was pre set by the translator. An attempt is made to
  642. * automatically generate that cost value from the cost table based on our src and
  643. * dst formats.
  644. *
  645. * \note This function allows older translators built before the translation cost
  646. * changed away from using onely computational time to continue to be registered
  647. * correctly. It is expected that translators built after the introduction of this
  648. * function will manually assign their own table cost value.
  649. *
  650. * \note This function is safe to use on any audio formats that used to be defined in the
  651. * first 64 bits of the old bit field codec representation.
  652. *
  653. * \retval Table Cost value greater than 0.
  654. * \retval 0 on error.
  655. */
  656. static int generate_table_cost(struct ast_codec *src, struct ast_codec *dst)
  657. {
  658. int src_rate = src->sample_rate;
  659. int src_ll = 0;
  660. int dst_rate = dst->sample_rate;
  661. int dst_ll = 0;
  662. if ((src->type != AST_MEDIA_TYPE_AUDIO) ||
  663. (dst->type != AST_MEDIA_TYPE_AUDIO)) {
  664. /* This method of generating table cost is limited to audio.
  665. * Translators for media other than audio must manually set their
  666. * table cost. */
  667. return 0;
  668. }
  669. src_ll = !strcmp(src->name, "slin");
  670. dst_ll = !strcmp(dst->name, "slin");
  671. if (src_ll) {
  672. if (dst_ll && (src_rate == dst_rate)) {
  673. return AST_TRANS_COST_LL_LL_ORIGSAMP;
  674. } else if (!dst_ll && (src_rate == dst_rate)) {
  675. return AST_TRANS_COST_LL_LY_ORIGSAMP;
  676. } else if (dst_ll && (src_rate < dst_rate)) {
  677. return AST_TRANS_COST_LL_LL_UPSAMP;
  678. } else if (!dst_ll && (src_rate < dst_rate)) {
  679. return AST_TRANS_COST_LL_LY_UPSAMP;
  680. } else if (dst_ll && (src_rate > dst_rate)) {
  681. return AST_TRANS_COST_LL_LL_DOWNSAMP;
  682. } else if (!dst_ll && (src_rate > dst_rate)) {
  683. return AST_TRANS_COST_LL_LY_DOWNSAMP;
  684. } else {
  685. return AST_TRANS_COST_LL_UNKNOWN;
  686. }
  687. } else {
  688. if (dst_ll && (src_rate == dst_rate)) {
  689. return AST_TRANS_COST_LY_LL_ORIGSAMP;
  690. } else if (!dst_ll && (src_rate == dst_rate)) {
  691. return AST_TRANS_COST_LY_LY_ORIGSAMP;
  692. } else if (dst_ll && (src_rate < dst_rate)) {
  693. return AST_TRANS_COST_LY_LL_UPSAMP;
  694. } else if (!dst_ll && (src_rate < dst_rate)) {
  695. return AST_TRANS_COST_LY_LY_UPSAMP;
  696. } else if (dst_ll && (src_rate > dst_rate)) {
  697. return AST_TRANS_COST_LY_LL_DOWNSAMP;
  698. } else if (!dst_ll && (src_rate > dst_rate)) {
  699. return AST_TRANS_COST_LY_LY_DOWNSAMP;
  700. } else {
  701. return AST_TRANS_COST_LY_UNKNOWN;
  702. }
  703. }
  704. }
  705. /*!
  706. * \brief rebuild a translation matrix.
  707. * \note This function expects the list of translators to be locked
  708. */
  709. static void matrix_rebuild(int samples)
  710. {
  711. struct ast_translator *t;
  712. int newtablecost;
  713. int x; /* source format index */
  714. int y; /* intermediate format index */
  715. int z; /* destination format index */
  716. ast_debug(1, "Resetting translation matrix\n");
  717. matrix_clear();
  718. /* first, compute all direct costs */
  719. AST_RWLIST_TRAVERSE(&translators, t, list) {
  720. if (!t->active) {
  721. continue;
  722. }
  723. x = t->src_fmt_index;
  724. z = t->dst_fmt_index;
  725. if (samples) {
  726. generate_computational_cost(t, samples);
  727. }
  728. /* This new translator is the best choice if any of the below are true.
  729. * 1. no translation path is set between x and z yet.
  730. * 2. the new table cost is less.
  731. * 3. the new computational cost is less. Computational cost is only used
  732. * to break a tie between two identical translation paths.
  733. */
  734. if (!matrix_get(x, z)->step ||
  735. (t->table_cost < matrix_get(x, z)->step->table_cost) ||
  736. (t->comp_cost < matrix_get(x, z)->step->comp_cost)) {
  737. matrix_get(x, z)->step = t;
  738. matrix_get(x, z)->table_cost = t->table_cost;
  739. }
  740. }
  741. /*
  742. * For each triple x, y, z of distinct formats, check if there is
  743. * a path from x to z through y which is cheaper than what is
  744. * currently known, and in case, update the matrix.
  745. * Repeat until the matrix is stable.
  746. */
  747. for (;;) {
  748. int changed = 0;
  749. for (x = 0; x < cur_max_index; x++) { /* source format */
  750. for (y = 0; y < cur_max_index; y++) { /* intermediate format */
  751. if (x == y) { /* skip ourselves */
  752. continue;
  753. }
  754. for (z = 0; z < cur_max_index; z++) { /* dst format */
  755. if ((z == x || z == y) || /* skip null conversions */
  756. !matrix_get(x, y)->step || /* no path from x to y */
  757. !matrix_get(y, z)->step) { /* no path from y to z */
  758. continue;
  759. }
  760. /* calculate table cost from x->y->z */
  761. newtablecost = matrix_get(x, y)->table_cost + matrix_get(y, z)->table_cost;
  762. /* if no step already exists between x and z OR the new cost of using the intermediate
  763. * step is cheaper, use this step. */
  764. if (!matrix_get(x, z)->step || (newtablecost < matrix_get(x, z)->table_cost)) {
  765. matrix_get(x, z)->step = matrix_get(x, y)->step;
  766. matrix_get(x, z)->table_cost = newtablecost;
  767. matrix_get(x, z)->multistep = 1;
  768. changed++;
  769. if (DEBUG_ATLEAST(10)) {
  770. struct ast_codec *x_codec = index2codec(x);
  771. struct ast_codec *y_codec = index2codec(y);
  772. struct ast_codec *z_codec = index2codec(z);
  773. ast_log(LOG_DEBUG,
  774. "Discovered %u cost path from %s to %s, via %s\n",
  775. matrix_get(x, z)->table_cost, x_codec->name,
  776. y_codec->name, z_codec->name);
  777. ao2_ref(x_codec, -1);
  778. ao2_ref(y_codec, -1);
  779. ao2_ref(z_codec, -1);
  780. }
  781. }
  782. }
  783. }
  784. }
  785. if (!changed) {
  786. break;
  787. }
  788. }
  789. }
  790. static void codec_append_name(const struct ast_codec *codec, struct ast_str **buf)
  791. {
  792. if (codec) {
  793. ast_str_append(buf, 0, "(%s@%u)", codec->name, codec->sample_rate);
  794. } else {
  795. ast_str_append(buf, 0, "(nothing)");
  796. }
  797. }
  798. const char *ast_translate_path_to_str(struct ast_trans_pvt *p, struct ast_str **str)
  799. {
  800. if (!p || !p->t) {
  801. return "";
  802. }
  803. ast_str_reset(*str);
  804. codec_append_name(&p->t->src_codec, str);
  805. while (p) {
  806. ast_str_append(str, 0, "->");
  807. codec_append_name(&p->t->dst_codec, str);
  808. p = p->next;
  809. }
  810. return ast_str_buffer(*str);
  811. }
  812. static char *complete_trans_path_choice(const char *word)
  813. {
  814. int i = 1;
  815. int wordlen = strlen(word);
  816. struct ast_codec *codec;
  817. while ((codec = ast_codec_get_by_id(i))) {
  818. ++i;
  819. if (codec->type != AST_MEDIA_TYPE_AUDIO) {
  820. ao2_ref(codec, -1);
  821. continue;
  822. }
  823. if (!strncasecmp(word, codec->name, wordlen)) {
  824. if (ast_cli_completion_add(ast_strdup(codec->name))) {
  825. ao2_ref(codec, -1);
  826. break;
  827. }
  828. }
  829. ao2_ref(codec, -1);
  830. }
  831. return NULL;
  832. }
  833. static void handle_cli_recalc(struct ast_cli_args *a)
  834. {
  835. int time = a->argv[4] ? atoi(a->argv[4]) : 1;
  836. if (time <= 0) {
  837. ast_cli(a->fd, " Recalc must be greater than 0. Defaulting to 1.\n");
  838. time = 1;
  839. }
  840. if (time > MAX_RECALC) {
  841. ast_cli(a->fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", time - MAX_RECALC, MAX_RECALC);
  842. time = MAX_RECALC;
  843. }
  844. ast_cli(a->fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", time);
  845. AST_RWLIST_WRLOCK(&translators);
  846. matrix_rebuild(time);
  847. AST_RWLIST_UNLOCK(&translators);
  848. }
  849. static char *handle_show_translation_table(struct ast_cli_args *a)
  850. {
  851. int x, y, i, k;
  852. int longest = 7; /* slin192 */
  853. int num_codecs = 0, curlen = 0;
  854. struct ast_str *out = ast_str_create(1024);
  855. struct ast_codec *codec;
  856. /* Get the length of the longest (usable?) codec name,
  857. so we know how wide the left side should be */
  858. for (i = 1; (codec = ast_codec_get_by_id(i)); ao2_ref(codec, -1), ++i) {
  859. ++num_codecs;
  860. if (codec->type != AST_MEDIA_TYPE_AUDIO) {
  861. continue;
  862. }
  863. curlen = strlen(codec->name);
  864. if (curlen > longest) {
  865. longest = curlen;
  866. }
  867. }
  868. AST_RWLIST_RDLOCK(&translators);
  869. ast_cli(a->fd, " Translation times between formats (in microseconds) for one second of data\n");
  870. ast_cli(a->fd, " Source Format (Rows) Destination Format (Columns)\n\n");
  871. for (i = 0; i < num_codecs; i++) {
  872. struct ast_codec *row = i ? ast_codec_get_by_id(i) : NULL;
  873. x = -1;
  874. if ((i > 0) && (row->type != AST_MEDIA_TYPE_AUDIO)) {
  875. ao2_ref(row, -1);
  876. continue;
  877. }
  878. if ((i > 0) && (x = codec2index(row)) == -1) {
  879. ao2_ref(row, -1);
  880. continue;
  881. }
  882. ast_str_set(&out, 0, " ");
  883. for (k = 0; k < num_codecs; k++) {
  884. int adjust = 0;
  885. struct ast_codec *col = k ? ast_codec_get_by_id(k) : NULL;
  886. y = -1;
  887. if ((k > 0) && (col->type != AST_MEDIA_TYPE_AUDIO)) {
  888. ao2_ref(col, -1);
  889. continue;
  890. }
  891. if ((k > 0) && (y = codec2index(col)) == -1) {
  892. ao2_ref(col, -1);
  893. continue;
  894. }
  895. if (k > 0) {
  896. curlen = strlen(col->name);
  897. if (!strcmp(col->name, "slin") ||
  898. !strcmp(col->name, "speex") ||
  899. !strcmp(col->name, "silk")) {
  900. adjust = log10(col->sample_rate / 1000) + 1;
  901. curlen = curlen + adjust;
  902. }
  903. }
  904. if (curlen < 5) {
  905. curlen = 5;
  906. }
  907. if (x >= 0 && y >= 0 && matrix_get(x, y)->step) {
  908. /* Actual codec output */
  909. ast_str_append(&out, 0, "%*u", curlen + 1, (matrix_get(x, y)->table_cost/100));
  910. } else if (i == 0 && k > 0) {
  911. /* Top row - use a dynamic size */
  912. if (!strcmp(col->name, "slin") ||
  913. !strcmp(col->name, "speex") ||
  914. !strcmp(col->name, "silk")) {
  915. ast_str_append(&out, 0, "%*s%u", curlen - adjust + 1,
  916. col->name, col->sample_rate / 1000);
  917. } else {
  918. ast_str_append(&out, 0, "%*s", curlen + 1, col->name);
  919. }
  920. } else if (k == 0 && i > 0) {
  921. /* Left column - use a static size. */
  922. if (!strcmp(row->name, "slin") ||
  923. !strcmp(row->name, "speex") ||
  924. !strcmp(row->name, "silk")) {
  925. int adjust_row = log10(row->sample_rate / 1000) + 1;
  926. ast_str_append(&out, 0, "%*s%u", longest - adjust_row,
  927. row->name, row->sample_rate / 1000);
  928. } else {
  929. ast_str_append(&out, 0, "%*s", longest, row->name);
  930. }
  931. } else if (x >= 0 && y >= 0) {
  932. /* Codec not supported */
  933. ast_str_append(&out, 0, "%*s", curlen + 1, "-");
  934. } else {
  935. /* Upper left hand corner */
  936. ast_str_append(&out, 0, "%*s", longest, "");
  937. }
  938. ao2_cleanup(col);
  939. }
  940. ast_str_append(&out, 0, "\n");
  941. ast_cli(a->fd, "%s", ast_str_buffer(out));
  942. ao2_cleanup(row);
  943. }
  944. ast_free(out);
  945. AST_RWLIST_UNLOCK(&translators);
  946. return CLI_SUCCESS;
  947. }
  948. static char *handle_show_translation_path(struct ast_cli_args *a, const char *codec_name, unsigned int sample_rate)
  949. {
  950. int i = 1;
  951. struct ast_str *str = ast_str_alloca(1024);
  952. struct ast_translator *step;
  953. struct ast_codec *dst_codec;
  954. struct ast_codec *src_codec = ast_codec_get(codec_name, AST_MEDIA_TYPE_AUDIO, sample_rate);
  955. if (!src_codec) {
  956. ast_cli(a->fd, "Source codec \"%s\" is not found.\n", codec_name);
  957. return CLI_FAILURE;
  958. }
  959. AST_RWLIST_RDLOCK(&translators);
  960. ast_cli(a->fd, "--- Translation paths SRC Codec \"%s\" sample rate %u ---\n",
  961. codec_name, src_codec->sample_rate);
  962. while ((dst_codec = ast_codec_get_by_id(i))) {
  963. int src, dst;
  964. char src_buffer[64];
  965. char dst_buffer[64];
  966. ++i;
  967. if (src_codec == dst_codec ||
  968. dst_codec->type != AST_MEDIA_TYPE_AUDIO) {
  969. ao2_ref(dst_codec, -1);
  970. continue;
  971. }
  972. dst = codec2index(dst_codec);
  973. src = codec2index(src_codec);
  974. if (src < 0 || dst < 0) {
  975. ast_str_set(&str, 0, "No Translation Path");
  976. } else {
  977. step = matrix_get(src, dst)->step;
  978. if (step) {
  979. codec_append_name(&step->src_codec, &str);
  980. while (src != dst) {
  981. src = step->dst_fmt_index;
  982. step = matrix_get(src, dst)->step;
  983. if (!step) {
  984. ast_str_append(&str, 0, "->");
  985. codec_append_name(dst_codec, &str);
  986. break;
  987. }
  988. ast_str_append(&str, 0, "->");
  989. codec_append_name(&step->src_codec, &str);
  990. }
  991. }
  992. }
  993. snprintf(src_buffer, sizeof(src_buffer), "%s:%u", src_codec->name, src_codec->sample_rate);
  994. snprintf(dst_buffer, sizeof(dst_buffer), "%s:%u", dst_codec->name, dst_codec->sample_rate);
  995. ast_cli(a->fd, "\t%-16.16s To %-16.16s: %-60.60s\n",
  996. src_buffer, dst_buffer, ast_str_buffer(str));
  997. ast_str_reset(str);
  998. ao2_ref(dst_codec, -1);
  999. }
  1000. AST_RWLIST_UNLOCK(&translators);
  1001. ao2_ref(src_codec, -1);
  1002. return CLI_SUCCESS;
  1003. }
  1004. static char *handle_cli_core_show_translation(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1005. {
  1006. static const char * const option[] = { "recalc", "paths", NULL };
  1007. switch (cmd) {
  1008. case CLI_INIT:
  1009. e->command = "core show translation";
  1010. e->usage =
  1011. "Usage: 'core show translation' can be used in two ways.\n"
  1012. " 1. 'core show translation [recalc [<recalc seconds>]]\n"
  1013. " Displays known codec translators and the cost associated\n"
  1014. " with each conversion. If the argument 'recalc' is supplied along\n"
  1015. " with optional number of seconds to test a new test will be performed\n"
  1016. " as the chart is being displayed.\n"
  1017. " 2. 'core show translation paths [codec [sample_rate]]'\n"
  1018. " This will display all the translation paths associated with a codec.\n"
  1019. " If a codec has multiple sample rates, the sample rate must be\n"
  1020. " provided as well.\n";
  1021. return NULL;
  1022. case CLI_GENERATE:
  1023. if (a->pos == 3) {
  1024. return ast_cli_complete(a->word, option, -1);
  1025. }
  1026. if (a->pos == 4 && !strcasecmp(a->argv[3], option[1])) {
  1027. return complete_trans_path_choice(a->word);
  1028. }
  1029. /* BUGBUG - add tab completion for sample rates */
  1030. return NULL;
  1031. }
  1032. if (a->argc > 6)
  1033. return CLI_SHOWUSAGE;
  1034. if (a->argv[3] && !strcasecmp(a->argv[3], option[1]) && a->argc == 5) { /* show paths */
  1035. return handle_show_translation_path(a, a->argv[4], 0);
  1036. } else if (a->argv[3] && !strcasecmp(a->argv[3], option[1]) && a->argc == 6) {
  1037. unsigned int sample_rate;
  1038. if (sscanf(a->argv[5], "%30u", &sample_rate) != 1) {
  1039. ast_cli(a->fd, "Invalid sample rate: %s.\n", a->argv[5]);
  1040. return CLI_FAILURE;
  1041. }
  1042. return handle_show_translation_path(a, a->argv[4], sample_rate);
  1043. } else if (a->argv[3] && !strcasecmp(a->argv[3], option[0])) { /* recalc and then fall through to show table */
  1044. handle_cli_recalc(a);
  1045. } else if (a->argc > 3) { /* wrong input */
  1046. return CLI_SHOWUSAGE;
  1047. }
  1048. return handle_show_translation_table(a);
  1049. }
  1050. static struct ast_cli_entry cli_translate[] = {
  1051. AST_CLI_DEFINE(handle_cli_core_show_translation, "Display translation matrix")
  1052. };
  1053. /*! \brief register codec translator */
  1054. int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
  1055. {
  1056. struct ast_translator *u;
  1057. char tmp[80];
  1058. RAII_VAR(struct ast_codec *, src_codec, NULL, ao2_cleanup);
  1059. RAII_VAR(struct ast_codec *, dst_codec, NULL, ao2_cleanup);
  1060. src_codec = ast_codec_get(t->src_codec.name, t->src_codec.type, t->src_codec.sample_rate);
  1061. if (!src_codec) {
  1062. ast_assert(0);
  1063. ast_log(LOG_WARNING, "Failed to register translator: unknown source codec %s\n", t->src_codec.name);
  1064. return -1;
  1065. }
  1066. dst_codec = ast_codec_get(t->dst_codec.name, t->dst_codec.type, t->dst_codec.sample_rate);
  1067. if (!dst_codec) {
  1068. ast_log(LOG_WARNING, "Failed to register translator: unknown destination codec %s\n", t->dst_codec.name);
  1069. return -1;
  1070. }
  1071. if (add_codec2index(src_codec) || add_codec2index(dst_codec)) {
  1072. if (matrix_resize(0)) {
  1073. ast_log(LOG_WARNING, "Translator matrix can not represent any more translators. Out of resources.\n");
  1074. return -1;
  1075. }
  1076. add_codec2index(src_codec);
  1077. add_codec2index(dst_codec);
  1078. }
  1079. if (!mod) {
  1080. ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
  1081. return -1;
  1082. }
  1083. if (!t->buf_size) {
  1084. ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
  1085. return -1;
  1086. }
  1087. if (!t->table_cost && !(t->table_cost = generate_table_cost(src_codec, dst_codec))) {
  1088. ast_log(LOG_WARNING, "Table cost could not be generated for %s, "
  1089. "Please set table_cost variable on translator.\n", t->name);
  1090. return -1;
  1091. }
  1092. t->module = mod;
  1093. t->src_fmt_index = codec2index(src_codec);
  1094. t->dst_fmt_index = codec2index(dst_codec);
  1095. t->active = 1;
  1096. if (t->src_fmt_index < 0 || t->dst_fmt_index < 0) {
  1097. ast_log(LOG_WARNING, "Invalid translator path: (%s codec is not valid)\n", t->src_fmt_index < 0 ? "starting" : "ending");
  1098. return -1;
  1099. }
  1100. if (t->src_fmt_index >= cur_max_index) {
  1101. ast_log(LOG_WARNING, "Source codec %s is larger than cur_max_index\n", t->src_codec.name);
  1102. return -1;
  1103. }
  1104. if (t->dst_fmt_index >= cur_max_index) {
  1105. ast_log(LOG_WARNING, "Destination codec %s is larger than cur_max_index\n", t->dst_codec.name);
  1106. return -1;
  1107. }
  1108. if (t->buf_size) {
  1109. /*
  1110. * Align buf_size properly, rounding up to the machine-specific
  1111. * alignment for pointers.
  1112. */
  1113. struct _test_align { void *a, *b; } p;
  1114. int align = (char *)&p.b - (char *)&p.a;
  1115. t->buf_size = ((t->buf_size + align - 1) / align) * align;
  1116. }
  1117. if (t->frameout == NULL) {
  1118. t->frameout = default_frameout;
  1119. }
  1120. generate_computational_cost(t, 1);
  1121. ast_verb(2, "Registered translator '%s' from codec %s to %s, table cost, %d, computational cost %d\n",
  1122. term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
  1123. t->src_codec.name, t->dst_codec.name, t->table_cost, t->comp_cost);
  1124. AST_RWLIST_WRLOCK(&translators);
  1125. /* find any existing translators that provide this same srcfmt/dstfmt,
  1126. and put this one in order based on computational cost */
  1127. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
  1128. if ((u->src_fmt_index == t->src_fmt_index) &&
  1129. (u->dst_fmt_index == t->dst_fmt_index) &&
  1130. (u->comp_cost > t->comp_cost)) {
  1131. AST_RWLIST_INSERT_BEFORE_CURRENT(t, list);
  1132. t = NULL;
  1133. break;
  1134. }
  1135. }
  1136. AST_RWLIST_TRAVERSE_SAFE_END;
  1137. /* if no existing translator was found for this codec combination,
  1138. add it to the beginning of the list */
  1139. if (t) {
  1140. AST_RWLIST_INSERT_HEAD(&translators, t, list);
  1141. }
  1142. matrix_rebuild(0);
  1143. AST_RWLIST_UNLOCK(&translators);
  1144. return 0;
  1145. }
  1146. /*! \brief unregister codec translator */
  1147. int ast_unregister_translator(struct ast_translator *t)
  1148. {
  1149. char tmp[80];
  1150. struct ast_translator *u;
  1151. int found = 0;
  1152. AST_RWLIST_WRLOCK(&translators);
  1153. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
  1154. if (u == t) {
  1155. AST_RWLIST_REMOVE_CURRENT(list);
  1156. ast_verb(2, "Unregistered translator '%s' from codec %s to %s\n",
  1157. term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
  1158. t->src_codec.name, t->dst_codec.name);
  1159. found = 1;
  1160. break;
  1161. }
  1162. }
  1163. AST_RWLIST_TRAVERSE_SAFE_END;
  1164. if (found && !ast_shutting_down()) {
  1165. matrix_rebuild(0);
  1166. }
  1167. AST_RWLIST_UNLOCK(&translators);
  1168. return (u ? 0 : -1);
  1169. }
  1170. void ast_translator_activate(struct ast_translator *t)
  1171. {
  1172. AST_RWLIST_WRLOCK(&translators);
  1173. t->active = 1;
  1174. matrix_rebuild(0);
  1175. AST_RWLIST_UNLOCK(&translators);
  1176. }
  1177. void ast_translator_deactivate(struct ast_translator *t)
  1178. {
  1179. AST_RWLIST_WRLOCK(&translators);
  1180. t->active = 0;
  1181. matrix_rebuild(0);
  1182. AST_RWLIST_UNLOCK(&translators);
  1183. }
  1184. /*! Calculate the absolute difference between sample rate of two formats. */
  1185. #define format_sample_rate_absdiff(fmt1, fmt2) ({ \
  1186. unsigned int rate1 = ast_format_get_sample_rate(fmt1); \
  1187. unsigned int rate2 = ast_format_get_sample_rate(fmt2); \
  1188. (rate1 > rate2 ? rate1 - rate2 : rate2 - rate1); \
  1189. })
  1190. /*! \brief Calculate our best translator source format, given costs, and a desired destination */
  1191. int ast_translator_best_choice(struct ast_format_cap *dst_cap,
  1192. struct ast_format_cap *src_cap,
  1193. struct ast_format **dst_fmt_out,
  1194. struct ast_format **src_fmt_out)
  1195. {
  1196. unsigned int besttablecost = INT_MAX;
  1197. unsigned int beststeps = INT_MAX;
  1198. struct ast_format *fmt;
  1199. struct ast_format *dst;
  1200. struct ast_format *src;
  1201. RAII_VAR(struct ast_format *, best, NULL, ao2_cleanup);
  1202. RAII_VAR(struct ast_format *, bestdst, NULL, ao2_cleanup);
  1203. struct ast_format_cap *joint_cap;
  1204. int i;
  1205. int j;
  1206. if (ast_format_cap_empty(dst_cap) || ast_format_cap_empty(src_cap)) {
  1207. ast_log(LOG_ERROR, "Cannot determine best translation path since one capability supports no formats\n");
  1208. return -1;
  1209. }
  1210. joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  1211. if (!joint_cap) {
  1212. return -1;
  1213. }
  1214. ast_format_cap_get_compatible(dst_cap, src_cap, joint_cap);
  1215. for (i = 0; i < ast_format_cap_count(joint_cap); ++i, ao2_cleanup(fmt)) {
  1216. fmt = ast_format_cap_get_format(joint_cap, i);
  1217. if (!fmt
  1218. || ast_format_get_type(fmt) != AST_MEDIA_TYPE_AUDIO) {
  1219. continue;
  1220. }
  1221. if (!best
  1222. || ast_format_get_sample_rate(best) < ast_format_get_sample_rate(fmt)) {
  1223. ao2_replace(best, fmt);
  1224. }
  1225. }
  1226. ao2_ref(joint_cap, -1);
  1227. if (best) {
  1228. ao2_replace(*dst_fmt_out, best);
  1229. ao2_replace(*src_fmt_out, best);
  1230. return 0;
  1231. }
  1232. /* need to translate */
  1233. AST_RWLIST_RDLOCK(&translators);
  1234. for (i = 0; i < ast_format_cap_count(dst_cap); ++i, ao2_cleanup(dst)) {
  1235. dst = ast_format_cap_get_format(dst_cap, i);
  1236. if (!dst
  1237. || ast_format_get_type(dst) != AST_MEDIA_TYPE_AUDIO) {
  1238. continue;
  1239. }
  1240. for (j = 0; j < ast_format_cap_count(src_cap); ++j, ao2_cleanup(src)) {
  1241. int x;
  1242. int y;
  1243. src = ast_format_cap_get_format(src_cap, j);
  1244. if (!src
  1245. || ast_format_get_type(src) != AST_MEDIA_TYPE_AUDIO) {
  1246. continue;
  1247. }
  1248. x = format2index(src);
  1249. y = format2index(dst);
  1250. if (x < 0 || y < 0) {
  1251. continue;
  1252. }
  1253. if (!matrix_get(x, y) || !(matrix_get(x, y)->step)) {
  1254. continue;
  1255. }
  1256. if (matrix_get(x, y)->table_cost < besttablecost
  1257. || matrix_get(x, y)->multistep < beststeps) {
  1258. /* better than what we have so far */
  1259. ao2_replace(best, src);
  1260. ao2_replace(bestdst, dst);
  1261. besttablecost = matrix_get(x, y)->table_cost;
  1262. beststeps = matrix_get(x, y)->multistep;
  1263. } else if (matrix_get(x, y)->table_cost == besttablecost
  1264. && matrix_get(x, y)->multistep == beststeps) {
  1265. unsigned int gap_selected = format_sample_rate_absdiff(best, bestdst);
  1266. unsigned int gap_current = format_sample_rate_absdiff(src, dst);
  1267. if (gap_current < gap_selected) {
  1268. /* better than what we have so far */
  1269. ao2_replace(best, src);
  1270. ao2_replace(bestdst, dst);
  1271. besttablecost = matrix_get(x, y)->table_cost;
  1272. beststeps = matrix_get(x, y)->multistep;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. AST_RWLIST_UNLOCK(&translators);
  1278. if (!best) {
  1279. return -1;
  1280. }
  1281. ao2_replace(*dst_fmt_out, bestdst);
  1282. ao2_replace(*src_fmt_out, best);
  1283. return 0;
  1284. }
  1285. unsigned int ast_translate_path_steps(struct ast_format *dst_format, struct ast_format *src_format)
  1286. {
  1287. unsigned int res = -1;
  1288. /* convert bitwise format numbers into array indices */
  1289. int src = format2index(src_format);
  1290. int dest = format2index(dst_format);
  1291. if (src < 0 || dest < 0) {
  1292. ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", src < 0 ? "starting" : "ending");
  1293. return -1;
  1294. }
  1295. AST_RWLIST_RDLOCK(&translators);
  1296. if (matrix_get(src, dest)->step) {
  1297. res = matrix_get(src, dest)->multistep + 1;
  1298. }
  1299. AST_RWLIST_UNLOCK(&translators);
  1300. return res;
  1301. }
  1302. static void check_translation_path(
  1303. struct ast_format_cap *dest, struct ast_format_cap *src,
  1304. struct ast_format_cap *result, struct ast_format *src_fmt,
  1305. enum ast_media_type type)
  1306. {
  1307. int index, src_index = format2index(src_fmt);
  1308. /* For a given source format, traverse the list of
  1309. known formats to determine whether there exists
  1310. a translation path from the source format to the
  1311. destination format. */
  1312. for (index = 0; (src_index >= 0) && index < cur_max_index; index++) {
  1313. struct ast_codec *codec = index2codec(index);
  1314. RAII_VAR(struct ast_format *, fmt, ast_format_create(codec), ao2_cleanup);
  1315. ao2_ref(codec, -1);
  1316. if (ast_format_get_type(fmt) != type) {
  1317. continue;
  1318. }
  1319. /* if this is not a desired format, nothing to do */
  1320. if (ast_format_cap_iscompatible_format(dest, fmt) == AST_FORMAT_CMP_NOT_EQUAL) {
  1321. continue;
  1322. }
  1323. /* if the source is supplying this format, then
  1324. we can leave it in the result */
  1325. if (ast_format_cap_iscompatible_format(src, fmt) == AST_FORMAT_CMP_EQUAL) {
  1326. continue;
  1327. }
  1328. /* if we don't have a translation path from the src
  1329. to this format, remove it from the result */
  1330. if (!matrix_get(src_index, index)->step) {
  1331. ast_format_cap_remove(result, fmt);
  1332. continue;
  1333. }
  1334. /* now check the opposite direction */
  1335. if (!matrix_get(index, src_index)->step) {
  1336. ast_format_cap_remove(result, fmt);
  1337. }
  1338. }
  1339. }
  1340. void ast_translate_available_formats(struct ast_format_cap *dest, struct ast_format_cap *src, struct ast_format_cap *result)
  1341. {
  1342. struct ast_format *cur_dest, *cur_src;
  1343. int index;
  1344. for (index = 0; index < ast_format_cap_count(dest); ++index) {
  1345. if (!(cur_dest = ast_format_cap_get_format(dest, index))) {
  1346. continue;
  1347. }
  1348. /* We give preference to a joint format structure if possible */
  1349. if ((cur_src = ast_format_cap_get_compatible_format(src, cur_dest))) {
  1350. ast_format_cap_append(result, cur_src, 0);
  1351. ao2_ref(cur_src, -1);
  1352. } else {
  1353. /* Otherwise we just use the destination format */
  1354. ast_format_cap_append(result, cur_dest, 0);
  1355. }
  1356. ao2_ref(cur_dest, -1);
  1357. }
  1358. /* if we don't have a source format, we just have to try all
  1359. possible destination formats */
  1360. if (!src) {
  1361. return;
  1362. }
  1363. for (index = 0; index < ast_format_cap_count(src); ++index) {
  1364. if (!(cur_src = ast_format_cap_get_format(src, index))) {
  1365. continue;
  1366. }
  1367. AST_RWLIST_RDLOCK(&translators);
  1368. check_translation_path(dest, src, result,
  1369. cur_src, AST_MEDIA_TYPE_AUDIO);
  1370. check_translation_path(dest, src, result,
  1371. cur_src, AST_MEDIA_TYPE_VIDEO);
  1372. AST_RWLIST_UNLOCK(&translators);
  1373. ao2_ref(cur_src, -1);
  1374. }
  1375. }
  1376. static void translate_shutdown(void)
  1377. {
  1378. int x;
  1379. ast_cli_unregister_multiple(cli_translate, ARRAY_LEN(cli_translate));
  1380. ast_rwlock_wrlock(&tablelock);
  1381. for (x = 0; x < index_size; x++) {
  1382. ast_free(__matrix[x]);
  1383. }
  1384. ast_free(__matrix);
  1385. __matrix = NULL;
  1386. ast_free(__indextable);
  1387. __indextable = NULL;
  1388. ast_rwlock_unlock(&tablelock);
  1389. ast_rwlock_destroy(&tablelock);
  1390. }
  1391. int ast_translate_init(void)
  1392. {
  1393. int res = 0;
  1394. ast_rwlock_init(&tablelock);
  1395. res = matrix_resize(1);
  1396. res |= ast_cli_register_multiple(cli_translate, ARRAY_LEN(cli_translate));
  1397. ast_register_cleanup(translate_shutdown);
  1398. return res;
  1399. }