translate.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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. #define MAX_RECALC 1000 /* max sample recalc */
  41. /*! \brief the list of translators */
  42. static AST_RWLIST_HEAD_STATIC(translators, ast_translator);
  43. /*! \brief these values indicate how a translation path will affect the sample rate
  44. *
  45. * \note These must stay in this order. They are ordered by most optimal selection first.
  46. */
  47. enum path_samp_change {
  48. /* Lossless Source Translation Costs */
  49. /*! [lossless -> lossless] original sampling */
  50. AST_TRANS_COST_LL_LL_ORIGSAMP = 400000,
  51. /*! [lossless -> lossy] original sampling */
  52. AST_TRANS_COST_LL_LY_ORIGSAMP = 600000,
  53. /*! [lossless -> lossless] up sample */
  54. AST_TRANS_COST_LL_LL_UPSAMP = 800000,
  55. /*! [lossless -> lossy] up sample */
  56. AST_TRANS_COST_LL_LY_UPSAMP = 825000,
  57. /*! [lossless -> lossless] down sample */
  58. AST_TRANS_COST_LL_LL_DOWNSAMP = 850000,
  59. /*! [lossless -> lossy] down sample */
  60. AST_TRANS_COST_LL_LY_DOWNSAMP = 875000,
  61. /*! [lossless -> unknown] unknown.
  62. * This value is for a lossless source translation
  63. * with an unknown destination and or sample rate conversion. */
  64. AST_TRANS_COST_LL_UNKNOWN = 885000,
  65. /* Lossy Source Translation Costs */
  66. /*! [lossy -> lossless] original sampling */
  67. AST_TRANS_COST_LY_LL_ORIGSAMP = 900000,
  68. /*! [lossy -> lossy] original sampling */
  69. AST_TRANS_COST_LY_LY_ORIGSAMP = 915000,
  70. /*! [lossy -> lossless] up sample */
  71. AST_TRANS_COST_LY_LL_UPSAMP = 930000,
  72. /*! [lossy -> lossy] up sample */
  73. AST_TRANS_COST_LY_LY_UPSAMP = 945000,
  74. /*! [lossy -> lossless] down sample */
  75. AST_TRANS_COST_LY_LL_DOWNSAMP = 960000,
  76. /*! [lossy -> lossy] down sample */
  77. AST_TRANS_COST_LY_LY_DOWNSAMP = 975000,
  78. /*! [lossy -> unknown] unknown.
  79. * This value is for a lossy source translation
  80. * with an unknown destination and or sample rate conversion. */
  81. AST_TRANS_COST_LY_UNKNOWN = 985000,
  82. };
  83. struct translator_path {
  84. struct ast_translator *step; /*!< Next step translator */
  85. unsigned int cost; /*!< Complete cost to destination */
  86. unsigned int multistep; /*!< Multiple conversions required for this translation */
  87. enum path_samp_change rate_change; /*!< does this path require a sample rate change, if so what kind. */
  88. };
  89. /*! \brief a matrix that, for any pair of supported formats,
  90. * indicates the total cost of translation and the first step.
  91. * The full path can be reconstricted iterating on the matrix
  92. * until step->dstfmt == desired_format.
  93. *
  94. * Array indexes are 'src' and 'dest', in that order.
  95. *
  96. * Note: the lock in the 'translators' list is also used to protect
  97. * this structure.
  98. */
  99. static struct translator_path tr_matrix[MAX_FORMAT][MAX_FORMAT];
  100. /*! \todo
  101. * TODO: sample frames for each supported input format.
  102. * We build this on the fly, by taking an SLIN frame and using
  103. * the existing converter to play with it.
  104. */
  105. /*! \brief returns the index of the lowest bit set */
  106. static force_inline int powerof(format_t d)
  107. {
  108. int x = ffsll(d);
  109. if (x)
  110. return x - 1;
  111. ast_log(LOG_WARNING, "No bits set? %llu\n", (unsigned long long) d);
  112. return -1;
  113. }
  114. /*
  115. * wrappers around the translator routines.
  116. */
  117. /*!
  118. * \brief Allocate the descriptor, required outbuf space,
  119. * and possibly desc.
  120. */
  121. static void *newpvt(struct ast_translator *t)
  122. {
  123. struct ast_trans_pvt *pvt;
  124. int len;
  125. char *ofs;
  126. /*
  127. * compute the required size adding private descriptor,
  128. * buffer, AST_FRIENDLY_OFFSET.
  129. */
  130. len = sizeof(*pvt) + t->desc_size;
  131. if (t->buf_size)
  132. len += AST_FRIENDLY_OFFSET + t->buf_size;
  133. pvt = ast_calloc(1, len);
  134. if (!pvt)
  135. return NULL;
  136. pvt->t = t;
  137. ofs = (char *)(pvt + 1); /* pointer to data space */
  138. if (t->desc_size) { /* first comes the descriptor */
  139. pvt->pvt = ofs;
  140. ofs += t->desc_size;
  141. }
  142. if (t->buf_size) /* finally buffer and header */
  143. pvt->outbuf.c = ofs + AST_FRIENDLY_OFFSET;
  144. /* call local init routine, if present */
  145. if (t->newpvt && t->newpvt(pvt)) {
  146. ast_free(pvt);
  147. return NULL;
  148. }
  149. ast_module_ref(t->module);
  150. return pvt;
  151. }
  152. static void destroy(struct ast_trans_pvt *pvt)
  153. {
  154. struct ast_translator *t = pvt->t;
  155. if (t->destroy)
  156. t->destroy(pvt);
  157. ast_free(pvt);
  158. ast_module_unref(t->module);
  159. }
  160. /*! \brief framein wrapper, deals with bound checks. */
  161. static int framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
  162. {
  163. int ret;
  164. int samples = pvt->samples; /* initial value */
  165. /* Copy the last in jb timing info to the pvt */
  166. ast_copy_flags(&pvt->f, f, AST_FRFLAG_HAS_TIMING_INFO);
  167. pvt->f.ts = f->ts;
  168. pvt->f.len = f->len;
  169. pvt->f.seqno = f->seqno;
  170. if (f->samples == 0) {
  171. ast_log(LOG_WARNING, "no samples for %s\n", pvt->t->name);
  172. }
  173. if (pvt->t->buffer_samples) { /* do not pass empty frames to callback */
  174. if (f->datalen == 0) { /* perform native PLC if available */
  175. /* If the codec has native PLC, then do that */
  176. if (!pvt->t->native_plc)
  177. return 0;
  178. }
  179. if (pvt->samples + f->samples > pvt->t->buffer_samples) {
  180. ast_log(LOG_WARNING, "Out of buffer space\n");
  181. return -1;
  182. }
  183. }
  184. /* we require a framein routine, wouldn't know how to do
  185. * it otherwise.
  186. */
  187. ret = pvt->t->framein(pvt, f);
  188. /* diagnostic ... */
  189. if (pvt->samples == samples)
  190. ast_log(LOG_WARNING, "%s did not update samples %d\n",
  191. pvt->t->name, pvt->samples);
  192. return ret;
  193. }
  194. /*! \brief generic frameout routine.
  195. * If samples and datalen are 0, take whatever is in pvt
  196. * and reset them, otherwise take the values in the caller and
  197. * leave alone the pvt values.
  198. */
  199. struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
  200. int datalen, int samples)
  201. {
  202. struct ast_frame *f = &pvt->f;
  203. if (samples)
  204. f->samples = samples;
  205. else {
  206. if (pvt->samples == 0)
  207. return NULL;
  208. f->samples = pvt->samples;
  209. pvt->samples = 0;
  210. }
  211. if (datalen)
  212. f->datalen = datalen;
  213. else {
  214. f->datalen = pvt->datalen;
  215. pvt->datalen = 0;
  216. }
  217. f->frametype = AST_FRAME_VOICE;
  218. f->subclass.codec = 1LL << (pvt->t->dstfmt);
  219. f->mallocd = 0;
  220. f->offset = AST_FRIENDLY_OFFSET;
  221. f->src = pvt->t->name;
  222. f->data.ptr = pvt->outbuf.c;
  223. return ast_frisolate(f);
  224. }
  225. static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
  226. {
  227. return ast_trans_frameout(pvt, 0, 0);
  228. }
  229. /* end of callback wrappers and helpers */
  230. void ast_translator_free_path(struct ast_trans_pvt *p)
  231. {
  232. struct ast_trans_pvt *pn = p;
  233. while ( (p = pn) ) {
  234. pn = p->next;
  235. destroy(p);
  236. }
  237. }
  238. /*! \brief Build a chain of translators based upon the given source and dest formats */
  239. struct ast_trans_pvt *ast_translator_build_path(format_t dest, format_t source)
  240. {
  241. struct ast_trans_pvt *head = NULL, *tail = NULL;
  242. source = powerof(source);
  243. dest = powerof(dest);
  244. if (source == -1 || dest == -1) {
  245. ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", source == -1 ? "starting" : "ending");
  246. return NULL;
  247. }
  248. AST_RWLIST_RDLOCK(&translators);
  249. while (source != dest) {
  250. struct ast_trans_pvt *cur;
  251. struct ast_translator *t = tr_matrix[source][dest].step;
  252. if (!t) {
  253. ast_log(LOG_WARNING, "No translator path from %s to %s\n",
  254. ast_getformatname(source), ast_getformatname(dest));
  255. AST_RWLIST_UNLOCK(&translators);
  256. return NULL;
  257. }
  258. if (!(cur = newpvt(t))) {
  259. ast_log(LOG_WARNING, "Failed to build translator step from %s to %s\n",
  260. ast_getformatname(source), ast_getformatname(dest));
  261. if (head)
  262. ast_translator_free_path(head);
  263. AST_RWLIST_UNLOCK(&translators);
  264. return NULL;
  265. }
  266. if (!head)
  267. head = cur;
  268. else
  269. tail->next = cur;
  270. tail = cur;
  271. cur->nextin = cur->nextout = ast_tv(0, 0);
  272. /* Keep going if this isn't the final destination */
  273. source = cur->t->dstfmt;
  274. }
  275. AST_RWLIST_UNLOCK(&translators);
  276. return head;
  277. }
  278. /*! \brief do the actual translation */
  279. struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
  280. {
  281. struct ast_trans_pvt *p = path;
  282. struct ast_frame *out = f;
  283. struct timeval delivery;
  284. int has_timing_info;
  285. long ts;
  286. long len;
  287. int seqno;
  288. has_timing_info = ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO);
  289. ts = f->ts;
  290. len = f->len;
  291. seqno = f->seqno;
  292. /* XXX hmmm... check this below */
  293. if (!ast_tvzero(f->delivery)) {
  294. if (!ast_tvzero(path->nextin)) {
  295. /* Make sure this is in line with what we were expecting */
  296. if (!ast_tveq(path->nextin, f->delivery)) {
  297. /* The time has changed between what we expected and this
  298. most recent time on the new packet. If we have a
  299. valid prediction adjust our output time appropriately */
  300. if (!ast_tvzero(path->nextout)) {
  301. path->nextout = ast_tvadd(path->nextout,
  302. ast_tvsub(f->delivery, path->nextin));
  303. }
  304. path->nextin = f->delivery;
  305. }
  306. } else {
  307. /* This is our first pass. Make sure the timing looks good */
  308. path->nextin = f->delivery;
  309. path->nextout = f->delivery;
  310. }
  311. /* Predict next incoming sample */
  312. path->nextin = ast_tvadd(path->nextin, ast_samp2tv(f->samples, ast_format_rate(f->subclass.codec)));
  313. }
  314. delivery = f->delivery;
  315. for ( ; out && p ; p = p->next) {
  316. framein(p, out);
  317. if (out != f)
  318. ast_frfree(out);
  319. out = p->t->frameout(p);
  320. }
  321. if (out) {
  322. /* we have a frame, play with times */
  323. if (!ast_tvzero(delivery)) {
  324. /* Regenerate prediction after a discontinuity */
  325. if (ast_tvzero(path->nextout)) {
  326. path->nextout = ast_tvnow();
  327. }
  328. /* Use next predicted outgoing timestamp */
  329. out->delivery = path->nextout;
  330. /* Predict next outgoing timestamp from samples in this
  331. frame. */
  332. path->nextout = ast_tvadd(path->nextout, ast_samp2tv(out->samples, ast_format_rate(out->subclass.codec)));
  333. if (f->samples != out->samples && ast_test_flag(out, AST_FRFLAG_HAS_TIMING_INFO)) {
  334. ast_debug(4, "Sample size different %d vs %d\n", f->samples, out->samples);
  335. ast_clear_flag(out, AST_FRFLAG_HAS_TIMING_INFO);
  336. }
  337. } else {
  338. out->delivery = ast_tv(0, 0);
  339. ast_set2_flag(out, has_timing_info, AST_FRFLAG_HAS_TIMING_INFO);
  340. if (has_timing_info) {
  341. out->ts = ts;
  342. out->len = len;
  343. out->seqno = seqno;
  344. }
  345. }
  346. /* Invalidate prediction if we're entering a silence period */
  347. if (out->frametype == AST_FRAME_CNG) {
  348. path->nextout = ast_tv(0, 0);
  349. }
  350. }
  351. if (consume) {
  352. ast_frfree(f);
  353. }
  354. return out;
  355. }
  356. /*! \brief compute the cost of a single translation step */
  357. static void calc_cost(struct ast_translator *t, int seconds)
  358. {
  359. int num_samples = 0;
  360. struct ast_trans_pvt *pvt;
  361. struct rusage start;
  362. struct rusage end;
  363. int cost;
  364. int out_rate = ast_format_rate(t->dstfmt);
  365. if (!seconds)
  366. seconds = 1;
  367. /* If they don't make samples, give them a terrible score */
  368. if (!t->sample) {
  369. ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
  370. t->cost = 999999;
  371. return;
  372. }
  373. pvt = newpvt(t);
  374. if (!pvt) {
  375. ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
  376. t->cost = 999999;
  377. return;
  378. }
  379. getrusage(RUSAGE_SELF, &start);
  380. /* Call the encoder until we've processed the required number of samples */
  381. while (num_samples < seconds * out_rate) {
  382. struct ast_frame *f = t->sample();
  383. if (!f) {
  384. ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
  385. destroy(pvt);
  386. t->cost = 999999;
  387. return;
  388. }
  389. framein(pvt, f);
  390. ast_frfree(f);
  391. while ((f = t->frameout(pvt))) {
  392. num_samples += f->samples;
  393. ast_frfree(f);
  394. }
  395. }
  396. getrusage(RUSAGE_SELF, &end);
  397. cost = ((end.ru_utime.tv_sec - start.ru_utime.tv_sec) * 1000000) + end.ru_utime.tv_usec - start.ru_utime.tv_usec;
  398. cost += ((end.ru_stime.tv_sec - start.ru_stime.tv_sec) * 1000000) + end.ru_stime.tv_usec - start.ru_stime.tv_usec;
  399. destroy(pvt);
  400. t->cost = cost / seconds;
  401. if (!t->cost)
  402. t->cost = 1;
  403. }
  404. static enum path_samp_change get_rate_change_result(format_t src, format_t dst)
  405. {
  406. int src_ll = src == AST_FORMAT_SLINEAR || src == AST_FORMAT_SLINEAR16;
  407. int dst_ll = dst == AST_FORMAT_SLINEAR || src == AST_FORMAT_SLINEAR16;
  408. int src_rate = ast_format_rate(src);
  409. int dst_rate = ast_format_rate(dst);
  410. if (src_ll) {
  411. if (dst_ll && (src_rate == dst_rate)) {
  412. return AST_TRANS_COST_LL_LL_ORIGSAMP;
  413. } else if (!dst_ll && (src_rate == dst_rate)) {
  414. return AST_TRANS_COST_LL_LY_ORIGSAMP;
  415. } else if (dst_ll && (src_rate < dst_rate)) {
  416. return AST_TRANS_COST_LL_LL_UPSAMP;
  417. } else if (!dst_ll && (src_rate < dst_rate)) {
  418. return AST_TRANS_COST_LL_LY_UPSAMP;
  419. } else if (dst_ll && (src_rate > dst_rate)) {
  420. return AST_TRANS_COST_LL_LL_DOWNSAMP;
  421. } else if (!dst_ll && (src_rate > dst_rate)) {
  422. return AST_TRANS_COST_LL_LY_DOWNSAMP;
  423. } else {
  424. return AST_TRANS_COST_LL_UNKNOWN;
  425. }
  426. } else {
  427. if (dst_ll && (src_rate == dst_rate)) {
  428. return AST_TRANS_COST_LY_LL_ORIGSAMP;
  429. } else if (!dst_ll && (src_rate == dst_rate)) {
  430. return AST_TRANS_COST_LY_LY_ORIGSAMP;
  431. } else if (dst_ll && (src_rate < dst_rate)) {
  432. return AST_TRANS_COST_LY_LL_UPSAMP;
  433. } else if (!dst_ll && (src_rate < dst_rate)) {
  434. return AST_TRANS_COST_LY_LY_UPSAMP;
  435. } else if (dst_ll && (src_rate > dst_rate)) {
  436. return AST_TRANS_COST_LY_LL_DOWNSAMP;
  437. } else if (!dst_ll && (src_rate > dst_rate)) {
  438. return AST_TRANS_COST_LY_LY_DOWNSAMP;
  439. } else {
  440. return AST_TRANS_COST_LY_UNKNOWN;
  441. }
  442. }
  443. }
  444. /*!
  445. * \brief rebuild a translation matrix.
  446. * \note This function expects the list of translators to be locked
  447. */
  448. static void rebuild_matrix(int samples)
  449. {
  450. struct ast_translator *t;
  451. int new_rate_change;
  452. int newcost;
  453. int x; /* source format index */
  454. int y; /* intermediate format index */
  455. int z; /* destination format index */
  456. ast_debug(1, "Resetting translation matrix\n");
  457. memset(tr_matrix, '\0', sizeof(tr_matrix));
  458. /* first, compute all direct costs */
  459. AST_RWLIST_TRAVERSE(&translators, t, list) {
  460. if (!t->active)
  461. continue;
  462. x = t->srcfmt;
  463. z = t->dstfmt;
  464. if (samples)
  465. calc_cost(t, samples);
  466. new_rate_change = get_rate_change_result(1LL << t->srcfmt, 1LL << t->dstfmt);
  467. /* this translator is the best choice if any of the below are true.
  468. * 1. no translation path is set between x and z yet.
  469. * 2. the new translation costs less and sample rate is no worse than old one.
  470. * 3. the new translation has a better sample rate conversion than the old one.
  471. */
  472. if (!tr_matrix[x][z].step ||
  473. ((t->cost < tr_matrix[x][z].cost) && (new_rate_change <= tr_matrix[x][z].rate_change)) ||
  474. (new_rate_change < tr_matrix[x][z].rate_change)) {
  475. tr_matrix[x][z].step = t;
  476. tr_matrix[x][z].cost = t->cost;
  477. tr_matrix[x][z].rate_change = new_rate_change;
  478. }
  479. }
  480. /*
  481. * For each triple x, y, z of distinct formats, check if there is
  482. * a path from x to z through y which is cheaper than what is
  483. * currently known, and in case, update the matrix.
  484. * Repeat until the matrix is stable.
  485. */
  486. for (;;) {
  487. int changed = 0;
  488. int better_choice = 0;
  489. for (x = 0; x < MAX_FORMAT; x++) { /* source format */
  490. for (y = 0; y < MAX_FORMAT; y++) { /* intermediate format */
  491. if (x == y) /* skip ourselves */
  492. continue;
  493. for (z = 0; z < MAX_FORMAT; z++) { /* dst format */
  494. if (z == x || z == y) /* skip null conversions */
  495. continue;
  496. if (!tr_matrix[x][y].step) /* no path from x to y */
  497. continue;
  498. if (!tr_matrix[y][z].step) /* no path from y to z */
  499. continue;
  500. /* Does x->y->z result in a less optimal sample rate change?
  501. * Never downgrade the sample rate conversion quality regardless
  502. * of any cost improvements */
  503. if (tr_matrix[x][z].step &&
  504. ((tr_matrix[x][z].rate_change < tr_matrix[x][y].rate_change) ||
  505. (tr_matrix[x][z].rate_change < tr_matrix[y][z].rate_change))) {
  506. continue;
  507. }
  508. /* is x->y->z a better sample rate confersion that the current x->z? */
  509. new_rate_change = tr_matrix[x][y].rate_change + tr_matrix[y][z].rate_change;
  510. /* calculate cost from x->y->z */
  511. newcost = tr_matrix[x][y].cost + tr_matrix[y][z].cost;
  512. /* Is x->y->z a better choice than x->z?
  513. * There are three conditions for x->y->z to be a better choice than x->z
  514. * 1. if there is no step directly between x->z then x->y->z is the best and only current option.
  515. * 2. if x->y->z results in a more optimal sample rate conversion. */
  516. if (!tr_matrix[x][z].step) {
  517. better_choice = 1;
  518. } else if (new_rate_change < tr_matrix[x][z].rate_change) {
  519. better_choice = 1;
  520. } else {
  521. better_choice = 0;
  522. }
  523. if (!better_choice) {
  524. continue;
  525. }
  526. /* ok, we can get from x to z via y with a cost that
  527. is the sum of the transition from x to y and from y to z */
  528. tr_matrix[x][z].step = tr_matrix[x][y].step;
  529. tr_matrix[x][z].cost = newcost;
  530. tr_matrix[x][z].multistep = 1;
  531. /* now calculate what kind of sample rate change is required for this multi-step path
  532. *
  533. * if both paths require a change in rate, and they are not in the same direction
  534. * then this is a up sample down sample conversion scenario. */
  535. tr_matrix[x][z].rate_change = tr_matrix[x][y].rate_change + tr_matrix[y][z].rate_change;
  536. ast_debug(10, "Discovered %u cost path from %s to %s, via %s\n", tr_matrix[x][z].cost,
  537. ast_getformatname(1LL << x), ast_getformatname(1LL << z), ast_getformatname(1LL << y));
  538. changed++;
  539. }
  540. }
  541. }
  542. if (!changed)
  543. break;
  544. }
  545. }
  546. const char *ast_translate_path_to_str(struct ast_trans_pvt *p, struct ast_str **str)
  547. {
  548. struct ast_trans_pvt *pn = p;
  549. if (!p || !p->t) {
  550. return "";
  551. }
  552. ast_str_set(str, 0, "%s", ast_getformatname(1LL << p->t->srcfmt));
  553. while ( (p = pn) ) {
  554. pn = p->next;
  555. ast_str_append(str, 0, "->%s", ast_getformatname(1LL << p->t->dstfmt));
  556. }
  557. return ast_str_buffer(*str);
  558. }
  559. static char *complete_trans_path_choice(const char *line, const char *word, int pos, int state)
  560. {
  561. int which = 0;
  562. int wordlen = strlen(word);
  563. int i;
  564. char *ret = NULL;
  565. size_t len = 0;
  566. const struct ast_format_list *format_list = ast_get_format_list(&len);
  567. for (i = 0; i < len; i++) {
  568. if (!(format_list[i].bits & AST_FORMAT_AUDIO_MASK)) {
  569. continue;
  570. }
  571. if (!strncasecmp(word, format_list[i].name, wordlen) && ++which > state) {
  572. ret = ast_strdup(format_list[i].name);
  573. break;
  574. }
  575. }
  576. return ret;
  577. }
  578. static char *handle_cli_core_show_translation(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  579. {
  580. #define SHOW_TRANS 64
  581. static const char * const option1[] = { "recalc", "paths", NULL };
  582. int x, y, z;
  583. int curlen = 0, longest = 0, magnitude[SHOW_TRANS] = { 0, };
  584. switch (cmd) {
  585. case CLI_INIT:
  586. e->command = "core show translation";
  587. e->usage =
  588. "Usage: 'core show translation' can be used in two ways.\n"
  589. " 1. 'core show translation [recalc [<recalc seconds>]]\n"
  590. " Displays known codec translators and the cost associated\n"
  591. " with each conversion. If the argument 'recalc' is supplied along\n"
  592. " with optional number of seconds to test a new test will be performed\n"
  593. " as the chart is being displayed.\n"
  594. " 2. 'core show translation paths [codec]'\n"
  595. " This will display all the translation paths associated with a codec\n";
  596. return NULL;
  597. case CLI_GENERATE:
  598. if (a->pos == 3) {
  599. return ast_cli_complete(a->word, option1, a->n);
  600. }
  601. if (a->pos == 4 && !strcasecmp(a->argv[3], option1[1])) {
  602. return complete_trans_path_choice(a->line, a->word, a->pos, a->n);
  603. }
  604. return NULL;
  605. }
  606. if (a->argc > 5)
  607. return CLI_SHOWUSAGE;
  608. if (a->argv[3] && !strcasecmp(a->argv[3], option1[1]) && a->argc == 5) {
  609. format_t input_src = 0;
  610. format_t src = 0;
  611. size_t len = 0;
  612. int dst;
  613. int i;
  614. const struct ast_format_list *format_list = ast_get_format_list(&len);
  615. struct ast_str *str = ast_str_alloca(256);
  616. struct ast_translator *step;
  617. for (i = 0; i < len; i++) {
  618. if (!(format_list[i].bits & AST_FORMAT_AUDIO_MASK)) {
  619. continue;
  620. }
  621. if (!strncasecmp(format_list[i].name, a->argv[4], strlen(format_list[i].name))) {
  622. input_src = format_list[i].bits;
  623. }
  624. }
  625. if (!input_src) {
  626. ast_cli(a->fd, "Source codec \"%s\" is not found.\n", a->argv[4]);
  627. return CLI_FAILURE;
  628. }
  629. AST_RWLIST_RDLOCK(&translators);
  630. ast_cli(a->fd, "--- Translation paths SRC Codec \"%s\" sample rate %d ---\n", a->argv[4], ast_format_rate(input_src));
  631. for (i = 0; i < len; i++) {
  632. if (!(format_list[i].bits & AST_FORMAT_AUDIO_MASK) || (format_list[i].bits == input_src)) {
  633. continue;
  634. }
  635. /* Note that dst can never be -1, as an element of format_list will have
  636. * at least one bit set. src cannot be -1 as well, as it is previously
  637. * sanitized - hence it is safe to directly index tr_matrix with the results
  638. * of powerof.
  639. */
  640. dst = powerof(format_list[i].bits);
  641. src = powerof(input_src);
  642. ast_str_reset(str);
  643. if (tr_matrix[src][dst].step) {
  644. ast_str_append(&str, 0, "%s", ast_getformatname(1LL << tr_matrix[src][dst].step->srcfmt));
  645. while (src != dst) {
  646. step = tr_matrix[src][dst].step;
  647. if (!step) {
  648. ast_str_reset(str);
  649. break;
  650. }
  651. ast_str_append(&str, 0, "->%s", ast_getformatname(1LL << step->dstfmt));
  652. src = step->dstfmt;
  653. }
  654. }
  655. if (ast_strlen_zero(ast_str_buffer(str))) {
  656. ast_str_set(&str, 0, "No Translation Path");
  657. }
  658. ast_cli(a->fd, "\t%-10.10s To %-10.10s: %-60.60s\n", a->argv[4], format_list[i].name, ast_str_buffer(str));
  659. }
  660. AST_RWLIST_UNLOCK(&translators);
  661. return CLI_SUCCESS;
  662. } else if (a->argv[3] && !strcasecmp(a->argv[3], "recalc")) {
  663. z = a->argv[4] ? atoi(a->argv[4]) : 1;
  664. if (z <= 0) {
  665. ast_cli(a->fd, " Recalc must be greater than 0. Defaulting to 1.\n");
  666. z = 1;
  667. }
  668. if (z > MAX_RECALC) {
  669. ast_cli(a->fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
  670. z = MAX_RECALC;
  671. }
  672. ast_cli(a->fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
  673. AST_RWLIST_WRLOCK(&translators);
  674. rebuild_matrix(z);
  675. AST_RWLIST_UNLOCK(&translators);
  676. } else if (a->argc > 3)
  677. return CLI_SHOWUSAGE;
  678. AST_RWLIST_RDLOCK(&translators);
  679. ast_cli(a->fd, " Translation times between formats (in microseconds) for one second of data\n");
  680. ast_cli(a->fd, " Source Format (Rows) Destination Format (Columns)\n\n");
  681. /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
  682. for (x = 0; x < SHOW_TRANS; x++) {
  683. /* translation only applies to audio right now. */
  684. if (!(AST_FORMAT_AUDIO_MASK & (1LL << (x))))
  685. continue;
  686. curlen = strlen(ast_getformatname(1LL << (x)));
  687. if (curlen > longest)
  688. longest = curlen;
  689. for (y = 0; y < SHOW_TRANS; y++) {
  690. if (!(AST_FORMAT_AUDIO_MASK & (1LL << (y))))
  691. continue;
  692. if (tr_matrix[x][y].cost > pow(10, magnitude[x])) {
  693. magnitude[y] = floor(log10(tr_matrix[x][y].cost));
  694. }
  695. }
  696. }
  697. for (x = -1; x < SHOW_TRANS; x++) {
  698. struct ast_str *out = ast_str_alloca(256);
  699. /* translation only applies to audio right now. */
  700. if (x >= 0 && !(AST_FORMAT_AUDIO_MASK & (1LL << (x))))
  701. continue;
  702. /*Go ahead and move to next iteration if dealing with an unknown codec*/
  703. if(x >= 0 && !strcmp(ast_getformatname(1LL << (x)), "unknown"))
  704. continue;
  705. ast_str_set(&out, -1, " ");
  706. for (y = -1; y < SHOW_TRANS; y++) {
  707. /* translation only applies to audio right now. */
  708. if (y >= 0 && !(AST_FORMAT_AUDIO_MASK & (1LL << (y))))
  709. continue;
  710. /*Go ahead and move to next iteration if dealing with an unknown codec*/
  711. if (y >= 0 && !strcmp(ast_getformatname(1LL << (y)), "unknown"))
  712. continue;
  713. if (y >= 0)
  714. curlen = strlen(ast_getformatname(1LL << (y)));
  715. if (y >= 0 && magnitude[y] + 1 > curlen) {
  716. curlen = magnitude[y] + 1;
  717. }
  718. if (curlen < 5)
  719. curlen = 5;
  720. if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
  721. /* Actual codec output */
  722. ast_str_append(&out, -1, "%*u", curlen + 1, tr_matrix[x][y].cost);
  723. } else if (x == -1 && y >= 0) {
  724. /* Top row - use a dynamic size */
  725. ast_str_append(&out, -1, "%*s", curlen + 1, ast_getformatname(1LL << (y)) );
  726. } else if (y == -1 && x >= 0) {
  727. /* Left column - use a static size. */
  728. ast_str_append(&out, -1, "%*s", longest, ast_getformatname(1LL << (x)) );
  729. } else if (x >= 0 && y >= 0) {
  730. /* Codec not supported */
  731. ast_str_append(&out, -1, "%*s", curlen + 1, "-");
  732. } else {
  733. /* Upper left hand corner */
  734. ast_str_append(&out, -1, "%*s", longest, "");
  735. }
  736. }
  737. ast_str_append(&out, -1, "\n");
  738. ast_cli(a->fd, "%s", ast_str_buffer(out));
  739. }
  740. AST_RWLIST_UNLOCK(&translators);
  741. return CLI_SUCCESS;
  742. }
  743. static struct ast_cli_entry cli_translate[] = {
  744. AST_CLI_DEFINE(handle_cli_core_show_translation, "Display translation matrix")
  745. };
  746. /*! \brief register codec translator */
  747. int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
  748. {
  749. static int added_cli = 0;
  750. struct ast_translator *u;
  751. char tmp[80];
  752. if (!mod) {
  753. ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
  754. return -1;
  755. }
  756. if (!t->buf_size) {
  757. ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
  758. return -1;
  759. }
  760. t->module = mod;
  761. t->srcfmt = powerof(t->srcfmt);
  762. t->dstfmt = powerof(t->dstfmt);
  763. t->active = 1;
  764. if (t->srcfmt == -1 || t->dstfmt == -1) {
  765. ast_log(LOG_WARNING, "Invalid translator path: (%s codec is not valid)\n", t->srcfmt == -1 ? "starting" : "ending");
  766. return -1;
  767. }
  768. if (t->srcfmt >= MAX_FORMAT) {
  769. ast_log(LOG_WARNING, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
  770. return -1;
  771. }
  772. if (t->dstfmt >= MAX_FORMAT) {
  773. ast_log(LOG_WARNING, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t->dstfmt));
  774. return -1;
  775. }
  776. if (t->buf_size) {
  777. /*
  778. * Align buf_size properly, rounding up to the machine-specific
  779. * alignment for pointers.
  780. */
  781. struct _test_align { void *a, *b; } p;
  782. int align = (char *)&p.b - (char *)&p.a;
  783. t->buf_size = ((t->buf_size + align - 1) / align) * align;
  784. }
  785. if (t->frameout == NULL)
  786. t->frameout = default_frameout;
  787. calc_cost(t, 1);
  788. ast_verb(2, "Registered translator '%s' from format %s to %s, cost %d\n",
  789. term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
  790. ast_getformatname(1LL << t->srcfmt), ast_getformatname(1LL << t->dstfmt), t->cost);
  791. if (!added_cli) {
  792. ast_cli_register_multiple(cli_translate, ARRAY_LEN(cli_translate));
  793. added_cli++;
  794. }
  795. AST_RWLIST_WRLOCK(&translators);
  796. /* find any existing translators that provide this same srcfmt/dstfmt,
  797. and put this one in order based on cost */
  798. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
  799. if ((u->srcfmt == t->srcfmt) &&
  800. (u->dstfmt == t->dstfmt) &&
  801. (u->cost > t->cost)) {
  802. AST_RWLIST_INSERT_BEFORE_CURRENT(t, list);
  803. t = NULL;
  804. break;
  805. }
  806. }
  807. AST_RWLIST_TRAVERSE_SAFE_END;
  808. /* if no existing translator was found for this format combination,
  809. add it to the beginning of the list */
  810. if (t)
  811. AST_RWLIST_INSERT_HEAD(&translators, t, list);
  812. rebuild_matrix(0);
  813. AST_RWLIST_UNLOCK(&translators);
  814. return 0;
  815. }
  816. /*! \brief unregister codec translator */
  817. int ast_unregister_translator(struct ast_translator *t)
  818. {
  819. char tmp[80];
  820. struct ast_translator *u;
  821. int found = 0;
  822. AST_RWLIST_WRLOCK(&translators);
  823. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
  824. if (u == t) {
  825. AST_RWLIST_REMOVE_CURRENT(list);
  826. ast_verb(2, "Unregistered translator '%s' from format %s to %s\n", term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)), ast_getformatname(1LL << t->srcfmt), ast_getformatname(1LL << t->dstfmt));
  827. found = 1;
  828. break;
  829. }
  830. }
  831. AST_RWLIST_TRAVERSE_SAFE_END;
  832. if (found)
  833. rebuild_matrix(0);
  834. AST_RWLIST_UNLOCK(&translators);
  835. return (u ? 0 : -1);
  836. }
  837. void ast_translator_activate(struct ast_translator *t)
  838. {
  839. AST_RWLIST_WRLOCK(&translators);
  840. t->active = 1;
  841. rebuild_matrix(0);
  842. AST_RWLIST_UNLOCK(&translators);
  843. }
  844. void ast_translator_deactivate(struct ast_translator *t)
  845. {
  846. AST_RWLIST_WRLOCK(&translators);
  847. t->active = 0;
  848. rebuild_matrix(0);
  849. AST_RWLIST_UNLOCK(&translators);
  850. }
  851. /*! \brief Calculate our best translator source format, given costs, and a desired destination */
  852. format_t ast_translator_best_choice(format_t *dst, format_t *srcs)
  853. {
  854. int x,y;
  855. int better = 0;
  856. int besttime = INT_MAX;
  857. int beststeps = INT_MAX;
  858. unsigned int best_rate_change = INT_MAX;
  859. format_t best = -1;
  860. format_t bestdst = 0;
  861. format_t cur, cursrc;
  862. format_t common = ((*dst) & (*srcs)) & AST_FORMAT_AUDIO_MASK; /* are there common formats ? */
  863. if (common) { /* yes, pick one and return */
  864. for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
  865. if (!(cur & common)) {
  866. continue;
  867. }
  868. /* We are guaranteed to find one common format. */
  869. if (best == -1) {
  870. best = cur;
  871. continue;
  872. }
  873. /* If there are multiple common formats, pick the one with the highest sample rate */
  874. if (ast_format_rate(best) < ast_format_rate(cur)) {
  875. best = cur;
  876. continue;
  877. }
  878. }
  879. /* We are done, this is a common format to both. */
  880. *srcs = *dst = best;
  881. return 0;
  882. } else { /* No, we will need to translate */
  883. AST_RWLIST_RDLOCK(&translators);
  884. for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
  885. if (! (cur & *dst)) {
  886. continue;
  887. }
  888. for (cursrc = 1, x = 0; x <= MAX_AUDIO_FORMAT; cursrc <<= 1, x++) {
  889. if (!(*srcs & cursrc) || !tr_matrix[x][y].step) {
  890. continue;
  891. }
  892. /* This is a better choice if any of the following are true.
  893. * 1. The sample rate conversion is better than the current pick.
  894. * 2. the sample rate conversion is no worse than the current pick and the cost or multistep is better
  895. */
  896. better = 0;
  897. if (tr_matrix[x][y].rate_change < best_rate_change) {
  898. better = 1; /* this match has a better rate conversion */
  899. }
  900. if ((tr_matrix[x][y].rate_change <= best_rate_change) &&
  901. (tr_matrix[x][y].cost < besttime || tr_matrix[x][y].multistep < beststeps)) {
  902. better = 1; /* this match has no worse rate conversion and the conversion cost is less */
  903. }
  904. if (better) {
  905. /* better than what we have so far */
  906. best = cursrc;
  907. bestdst = cur;
  908. besttime = tr_matrix[x][y].cost;
  909. beststeps = tr_matrix[x][y].multistep;
  910. best_rate_change = tr_matrix[x][y].rate_change;
  911. }
  912. }
  913. }
  914. AST_RWLIST_UNLOCK(&translators);
  915. if (best > -1) {
  916. *srcs = best;
  917. *dst = bestdst;
  918. best = 0;
  919. }
  920. return best;
  921. }
  922. }
  923. unsigned int ast_translate_path_steps(format_t dest, format_t src)
  924. {
  925. unsigned int res = -1;
  926. /* convert bitwise format numbers into array indices */
  927. src = powerof(src);
  928. dest = powerof(dest);
  929. if (src == -1 || dest == -1) {
  930. ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", src == -1 ? "starting" : "ending");
  931. return -1;
  932. }
  933. AST_RWLIST_RDLOCK(&translators);
  934. if (tr_matrix[src][dest].step)
  935. res = tr_matrix[src][dest].multistep + 1;
  936. AST_RWLIST_UNLOCK(&translators);
  937. return res;
  938. }
  939. format_t ast_translate_available_formats(format_t dest, format_t src)
  940. {
  941. format_t res = dest;
  942. format_t x;
  943. format_t src_audio = src & AST_FORMAT_AUDIO_MASK;
  944. format_t src_video = src & AST_FORMAT_VIDEO_MASK;
  945. format_t x_bits;
  946. /* if we don't have a source format, we just have to try all
  947. possible destination formats */
  948. if (!src)
  949. return dest;
  950. /* If we have a source audio format, get its format index */
  951. if (src_audio) {
  952. src_audio = powerof(src_audio);
  953. }
  954. /* If we have a source video format, get its format index */
  955. if (src_video) {
  956. src_video = powerof(src_video);
  957. }
  958. /* Note that src_audio and src_video are guaranteed to not be
  959. * negative at this point, as we ensured they were non-zero. It is
  960. * safe to use the return value of powerof as an index into tr_matrix.
  961. */
  962. AST_RWLIST_RDLOCK(&translators);
  963. /* For a given source audio format, traverse the list of
  964. known audio formats to determine whether there exists
  965. a translation path from the source format to the
  966. destination format. */
  967. for (x = 1LL; src_audio && x > 0; x <<= 1) {
  968. if (!(x & AST_FORMAT_AUDIO_MASK)) {
  969. continue;
  970. }
  971. /* if this is not a desired format, nothing to do */
  972. if (!(dest & x))
  973. continue;
  974. /* if the source is supplying this format, then
  975. we can leave it in the result */
  976. if (src & x)
  977. continue;
  978. /* if we don't have a translation path from the src
  979. to this format, remove it from the result. Note that x_bits
  980. cannot be less than 0 as x will always have one bit set to 1 */
  981. x_bits = powerof(x);
  982. if (!tr_matrix[src_audio][x_bits].step) {
  983. res &= ~x;
  984. continue;
  985. }
  986. /* now check the opposite direction */
  987. if (!tr_matrix[x_bits][src_audio].step)
  988. res &= ~x;
  989. }
  990. /* For a given source video format, traverse the list of
  991. known video formats to determine whether there exists
  992. a translation path from the source format to the
  993. destination format. */
  994. for (x = 1LL; src_video && x > 0; x <<= 1) {
  995. if (!(x & AST_FORMAT_VIDEO_MASK)) {
  996. continue;
  997. }
  998. /* if this is not a desired format, nothing to do */
  999. if (!(dest & x))
  1000. continue;
  1001. /* if the source is supplying this format, then
  1002. we can leave it in the result */
  1003. if (src & x)
  1004. continue;
  1005. /* if we don't have a translation path from the src
  1006. to this format, remove it from the result. Note that x_bits
  1007. cannot be less than 0 as x will always have one bit set to 1 */
  1008. x_bits = powerof(x);
  1009. if (!tr_matrix[src_video][x_bits].step) {
  1010. res &= ~x;
  1011. continue;
  1012. }
  1013. /* now check the opposite direction */
  1014. if (!tr_matrix[x_bits][src_video].step)
  1015. res &= ~x;
  1016. }
  1017. AST_RWLIST_UNLOCK(&translators);
  1018. return res;
  1019. }