Debian Codegraph @

main/translate.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2006, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
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
19 /*! \file
20 *
21 * \brief Translate via the use of pseudo channels
22 *
23 * \author Mark Spencer <[email protected]>
24 */
25
26 /*** MODULEINFO
27 <support_level>core</support_level>
28 ***/
29
30 #include "asterisk.h"
31
32 #include <sys/time.h>
33 #include <sys/resource.h>
34 #include <math.h>
35
36 #include "asterisk/lock.h"
37 #include "asterisk/channel.h"
38 #include "asterisk/translate.h"
39 #include "asterisk/module.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/sched.h"
42 #include "asterisk/cli.h"
43 #include "asterisk/term.h"
44 #include "asterisk/format.h"
45 #include "asterisk/linkedlists.h"
46
47 /*
48 * Sample type selection for codec matrix cost computation.
49 */
50 enum sample_type {
51 SAMPLE_TYPE_CODEC = 0, /*!< Default: take samples defined by codec */
52 SAMPLE_TYPE_SINE, /*!< Default: 1kHz sine wave */
53 SAMPLE_TYPE_SILENCE, /*!< All-zero frames */
54 SAMPLE_TYPE_NOISE, /*!< White noise via LCG PRNG */
55 SAMPLE_TYPE_SPEECH, /*!< Synthetic speech-like signal */
56 };
57
58 static enum sample_type current_sample_type = SAMPLE_TYPE_CODEC;
59
60 /*! Simple LCG state for reproducible pseudo-random noise */
61 static uint32_t lcg_state = 0xdeadbeef;
62 static uint32_t lcg_rand(void)
63 {
64 lcg_state = lcg_state * 1664525u + 1013904223u;
65 return lcg_state;
66 }
67
68 /*!
69 * \brief Fill a buffer with samples of the selected type.
70 * \param buf Output sample buffer (int16_t)
71 * \param samples Number of samples to generate
72 * \param offset Running sample offset (for continuous sample types)
73 */
74 static void generate_samples(int16_t *buf, int samples, int offset)
75 {
76 int i;
77 switch (current_sample_type) {
78 case SAMPLE_TYPE_SILENCE:
79 memset(buf, 0, samples * sizeof(int16_t));
80 break;
81 case SAMPLE_TYPE_NOISE:
82 for (i = 0; i < samples; i++) {
83 buf[i] = (int16_t)(lcg_rand() & 0xFFFF);
84 }
85 break;
86 case SAMPLE_TYPE_SPEECH:
87 /* Synthetic speech approximation: mix of two sine waves
88 * (fundamental ~200Hz + harmonic ~800Hz) with slow AM envelope,
89 * loosely inspired by ITU-T P.50 artificial voice. */
90 for (i = 0; i < samples; i++) {
91 double t = (double)(offset + i) / 8000.0;
92 double sig = 0.6 * sin(2.0 * M_PI * 200.0 * t)
93 + 0.4 * sin(2.0 * M_PI * 800.0 * t);
94 /* Slow AM at 4Hz to simulate syllable rhythm */
95 sig *= 0.5 * (1.0 + sin(2.0 * M_PI * 4.0 * t));
96 buf[i] = (int16_t)(sig * 16000.0);
97 }
98 break;
99 case SAMPLE_TYPE_SINE:
100 default:
101 /* pure 1kHz sine wave */
102 for (i = 0; i < samples; i++) {
103 buf[i] = (int16_t)(sin(2.0 * M_PI * 1000.0 *
104 (double)(offset + i) / 8000.0) * 16000.0);
105 }
106 break;
107 }
108 }
109
110 /*! max sample recalc */
111 #define MAX_RECALC 1000
112
113 /*! \brief the list of translators */
114 static AST_RWLIST_HEAD_STATIC(translators, ast_translator);
115
116 struct translator_path {
117 struct ast_translator *step; /*!< Next step translator */
118 uint32_t table_cost; /*!< Complete table cost to destination */
119 uint32_t comp_cost; /*!< Complete table cost to destination */
120 uint8_t multistep; /*!< Multiple conversions required for this translation */
121 };
122
123 /*!
124 * \brief a matrix that, for any pair of supported formats,
125 * indicates the total cost of translation and the first step.
126 * The full path can be reconstructed iterating on the matrix
127 * until step->dstfmt == desired_format.
128 *
129 * Array indexes are 'src' and 'dest', in that order.
130 *
131 * Note: the lock in the 'translators' list is also used to protect
132 * this structure.
133 */
134 static struct translator_path **__matrix;
135
136 /*!
137 * \brief table for converting index to format values.
138 *
139 * \note this table is protected by the table_lock.
140 */
141 static unsigned int *__indextable;
142
143 /*! protects the __indextable for resizing */
144 static ast_rwlock_t tablelock;
145
146 /* index size starts at this*/
147 #define INIT_INDEX 32
148 /* index size grows by this as necessary */
149 #define GROW_INDEX 16
150
151 /*! the current largest index used by the __matrix and __indextable arrays*/
152 static int cur_max_index;
153 /*! the largest index that can be used in either the __indextable or __matrix before resize must occur */
154 static int index_size;
155
156 static void matrix_rebuild(int samples);
157
158 /*!
159 * \internal
160 * \brief converts codec id to index value.
161 */
162 static int codec_to_index(unsigned int id)
163 {
164 int x;
165
166 ast_rwlock_rdlock(&tablelock);
167 for (x = 0; x < cur_max_index; x++) {
168 if (__indextable[x] == id) {
169 /* format already exists in index2format table */
170 ast_rwlock_unlock(&tablelock);
171 return x;
172 }
173 }
174 ast_rwlock_unlock(&tablelock);
175 return -1; /* not found */
176 }
177
178 /*!
179 * \internal
180 * \brief converts codec to index value.
181 */
182 static int codec2index(struct ast_codec *codec)
183 {
184 return codec_to_index(codec->id);
185 }
186
187 /*!
188 * \internal
189 * \brief converts format to codec index value.
190 */
191 static int format2index(struct ast_format *format)
192 {
193 return codec_to_index(ast_format_get_codec_id(format));
194 }
195
196 /*!
197 * \internal
198 * \brief add a new codec to the matrix and index table structures.
199 *
200 * \note it is perfectly safe to call this on codecs already indexed.
201 *
202 * \retval 0 success
203 * \retval -1 matrix and index table need to be resized
204 */
205 static int add_codec2index(struct ast_codec *codec)
206 {
207 if (codec2index(codec) != -1) {
208 /* format is already already indexed */
209 return 0;
210 }
211
212 ast_rwlock_wrlock(&tablelock);
213 if (cur_max_index == (index_size)) {
214 ast_rwlock_unlock(&tablelock);
215 return -1; /* hit max length */
216 }
217 __indextable[cur_max_index] = codec->id;
218 cur_max_index++;
219 ast_rwlock_unlock(&tablelock);
220
221 return 0;
222 }
223
224 /*!
225 * \internal
226 * \brief converts index value back to codec
227 */
228 static struct ast_codec *index2codec(int index)
229 {
230 struct ast_codec *codec;
231
232 if (index >= cur_max_index) {
233 return 0;
234 }
235 ast_rwlock_rdlock(&tablelock);
236 codec = ast_codec_get_by_id(__indextable[index]);
237 ast_rwlock_unlock(&tablelock);
238
239 return codec;
240 }
241
242 /*!
243 * \internal
244 * \brief resize both the matrix and index table so they can represent
245 * more translators
246 *
247 * \note _NO_ locks can be held prior to calling this function
248 *
249 * \retval 0 success
250 * \retval -1 failure. Old matrix and index table can still be used though
251 */
252 static int matrix_resize(int init)
253 {
254 struct translator_path **tmp_matrix = NULL;
255 unsigned int *tmp_table = NULL;
256 int old_index;
257 int x;
258
259 AST_RWLIST_WRLOCK(&translators);
260 ast_rwlock_wrlock(&tablelock);
261
262 old_index = index_size;
263 if (init) {
264 index_size += INIT_INDEX;
265 } else {
266 index_size += GROW_INDEX;
267 }
268
269 /* make new 2d array of translator_path structures */
270 if (!(tmp_matrix = ast_calloc(1, sizeof(struct translator_path *) * (index_size)))) {
271 goto resize_cleanup;
272 }
273
274 for (x = 0; x < index_size; x++) {
275 if (!(tmp_matrix[x] = ast_calloc(1, sizeof(struct translator_path) * (index_size)))) {
276 goto resize_cleanup;
277 }
278 }
279
280 /* make new index table */
281 if (!(tmp_table = ast_calloc(1, sizeof(unsigned int) * index_size))) {
282 goto resize_cleanup;
283 }
284
285 /* if everything went well this far, free the old and use the new */
286 if (!init) {
287 for (x = 0; x < old_index; x++) {
288 ast_free(__matrix[x]);
289 }
290 ast_free(__matrix);
291
292 memcpy(tmp_table, __indextable, sizeof(unsigned int) * old_index);
293 ast_free(__indextable);
294 }
295
296 /* now copy them over */
297 __matrix = tmp_matrix;
298 __indextable = tmp_table;
299
300 matrix_rebuild(0);
301 ast_rwlock_unlock(&tablelock);
302 AST_RWLIST_UNLOCK(&translators);
303
304 return 0;
305
306 resize_cleanup:
307 ast_rwlock_unlock(&tablelock);
308 AST_RWLIST_UNLOCK(&translators);
309 if (tmp_matrix) {
310 for (x = 0; x < index_size; x++) {
311 ast_free(tmp_matrix[x]);
312 }
313 ast_free(tmp_matrix);
314 }
315 ast_free(tmp_table);
316
317 return -1;
318 }
319
320 /*!
321 * \internal
322 * \brief reinitialize the __matrix during matrix rebuild
323 *
324 * \note must be protected by the translators list lock
325 */
326 static void matrix_clear(void)
327 {
328 int x;
329 for (x = 0; x < index_size; x++) {
330 memset(__matrix[x], '\0', sizeof(struct translator_path) * (index_size));
331 }
332 }
333
334 /*!
335 * \internal
336 * \brief get a matrix entry
337 *
338 * \note This function must be protected by the translators list lock
339 */
340 static struct translator_path *matrix_get(unsigned int x, unsigned int y)
341 {
342 return __matrix[x] + y;
343 }
344
345 /*
346 * wrappers around the translator routines.
347 */
348
349 static void destroy(struct ast_trans_pvt *pvt)
350 {
351 struct ast_translator *t = pvt->t;
352
353 if (t->destroy) {
354 t->destroy(pvt);
355 }
356 ao2_cleanup(pvt->f.subclass.format);
357 if (pvt->explicit_dst) {
358 ao2_ref(pvt->explicit_dst, -1);
359 pvt->explicit_dst = NULL;
360 }
361 ast_free(pvt);
362 ast_module_unref(t->module);
363 }
364
365 /*!
366 * \brief Allocate the descriptor, required outbuf space,
367 * and possibly desc.
368 */
369 static struct ast_trans_pvt *newpvt(struct ast_translator *t, struct ast_format *explicit_dst)
370 {
371 struct ast_trans_pvt *pvt;
372 int len;
373 char *ofs;
374
375 /*
376 * compute the required size adding private descriptor,
377 * buffer, AST_FRIENDLY_OFFSET.
378 */
379 len = sizeof(*pvt) + t->desc_size;
380 if (t->buf_size)
381 len += AST_FRIENDLY_OFFSET + t->buf_size;
382 pvt = ast_calloc(1, len);
383 if (!pvt) {
384 return NULL;
385 }
386 pvt->t = t;
387 ofs = (char *)(pvt + 1); /* pointer to data space */
388 if (t->desc_size) { /* first comes the descriptor */
389 pvt->pvt = ofs;
390 ofs += t->desc_size;
391 }
392 if (t->buf_size) {/* finally buffer and header */
393 pvt->outbuf.c = ofs + AST_FRIENDLY_OFFSET;
394 }
395 /*
396 * If the format has an attribute module, explicit_dst includes the (joined)
397 * result of the SDP negotiation. For example with the Opus Codec, the format
398 * knows whether both parties want to do forward-error correction (FEC).
399 */
400 pvt->explicit_dst = ao2_bump(explicit_dst);
401
402 ast_module_ref(t->module);
403
404 /* call local init routine, if present */
405 if (t->newpvt && t->newpvt(pvt)) {
406 ast_free(pvt);
407 ast_module_unref(t->module);
408 return NULL;
409 }
410
411 /* Setup normal static translation frame. */
412 pvt->f.frametype = AST_FRAME_VOICE;
413 pvt->f.mallocd = 0;
414 pvt->f.offset = AST_FRIENDLY_OFFSET;
415 pvt->f.src = pvt->t->name;
416 pvt->f.data.ptr = pvt->outbuf.c;
•417 pvt->f.seqno = 0x10000;
418
419 /*
420 * If the translator has not provided a format
421 * A) use the joined one,
422 * B) use the cached one, or
423 * C) create one.
424 */
425 if (!pvt->f.subclass.format) {
426 pvt->f.subclass.format = ao2_bump(pvt->explicit_dst);
427
428 if (!pvt->f.subclass.format && !ast_strlen_zero(pvt->t->format)) {
429 pvt->f.subclass.format = ast_format_cache_get(pvt->t->format);
430 }
431
432 if (!pvt->f.subclass.format) {
433 struct ast_codec *codec = ast_codec_get(t->dst_codec.name,
434 t->dst_codec.type, t->dst_codec.sample_rate);
435 if (!codec) {
436 ast_log(LOG_ERROR, "Unable to get destination codec\n");
437 destroy(pvt);
438 return NULL;
439 }
440 pvt->f.subclass.format = ast_format_create(codec);
441 ao2_ref(codec, -1);
442 }
443
444 if (!pvt->f.subclass.format) {
445 ast_log(LOG_ERROR, "Unable to create format\n");
446 destroy(pvt);
447 return NULL;
448 }
449 }
450
451 return pvt;
452 }
453
454 /*! \brief framein wrapper, deals with bound checks. */
455 static int framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
456 {
457 /* Copy the last in jb timing info to the pvt */
458 ast_copy_flags(&pvt->f, f, AST_FRFLAG_HAS_TIMING_INFO);
459 pvt->f.ts = f->ts;
460 pvt->f.len = f->len;
461 pvt->f.seqno = f->seqno;
462
463 if (f->samples == 0) {
464 /* Do not log empty audio frame */
465 if (!f->src || strcasecmp(f->src, "ast_prod")) {
466 ast_log(LOG_WARNING, "no samples for %s\n", pvt->t->name);
467 }
468 }
469 if (pvt->t->buffer_samples) { /* do not pass empty frames to callback */
470 int src_srate = pvt->t->src_codec.sample_rate;
471 int dst_srate = pvt->t->dst_codec.sample_rate;
472
473 ast_assert(src_srate > 0);
474
475 if (f->datalen == 0) { /* perform native PLC if available */
476 /* If the codec has native PLC, then do that */
477 if (!pvt->t->native_plc)
478 return 0;
479 }
480
481 if (pvt->samples + (f->samples * dst_srate / src_srate) > pvt->t->buffer_samples) {
482 ast_log(LOG_WARNING, "Out of buffer space\n");
483 return -1;
484 }
485 }
486 /* we require a framein routine, wouldn't know how to do
487 * it otherwise.
488 */
489 return pvt->t->framein(pvt, f);
490 }
491
492 /*! \brief generic frameout routine.
493 * If samples and datalen are 0, take whatever is in pvt
494 * and reset them, otherwise take the values in the caller and
495 * leave alone the pvt values.
496 */
497 struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
498 int datalen, int samples)
499 {
500 struct ast_frame *f = &pvt->f;
501
502 if (samples) {
503 f->samples = samples;
504 } else {
505 if (pvt->samples == 0) {
506 return NULL;
507 }
508 f->samples = pvt->samples;
509 pvt->samples = 0;
510 }
511 if (datalen) {
512 f->datalen = datalen;
513 f->data.ptr = pvt->outbuf.c;
514 } else {
515 f->datalen = pvt->datalen;
516 if (!f->datalen) {
517 f->data.ptr = NULL;
518 } else {
519 f->data.ptr = pvt->outbuf.c;
520 }
521 pvt->datalen = 0;
522 }
523
524 return ast_frisolate(f);
525 }
526
527 static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
528 {
529 return ast_trans_frameout(pvt, 0, 0);
530 }
531
532 /* end of callback wrappers and helpers */
533
534 void ast_translator_free_path(struct ast_trans_pvt *p)
535 {
536 struct ast_trans_pvt *pn = p;
537 while ( (p = pn) ) {
538 pn = p->next;
539 destroy(p);
540 }
541 }
542
543 /*! \brief Build a chain of translators based upon the given source and dest formats */
544 struct ast_trans_pvt *ast_translator_build_path(struct ast_format *dst, struct ast_format *src)
545 {
546 struct ast_trans_pvt *head = NULL, *tail = NULL;
547 int src_index, dst_index;
548
549 src_index = format2index(src);
550 dst_index = format2index(dst);
551
552 if (src_index < 0 || dst_index < 0) {
553 ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", src_index < 0 ? "starting" : "ending");
554 return NULL;
555 }
556
557 AST_RWLIST_RDLOCK(&translators);
558
559 while (src_index != dst_index) {
560 struct ast_trans_pvt *cur;
561 struct ast_format *explicit_dst = NULL;
562 struct ast_translator *t = matrix_get(src_index, dst_index)->step;
563 if (!t) {
564 ast_log(LOG_WARNING, "No translator path from %s to %s\n",
565 ast_format_get_name(src), ast_format_get_name(dst));
566 AST_RWLIST_UNLOCK(&translators);
567 ast_translator_free_path(head);
568 return NULL;
569 }
570 if ((t->dst_codec.sample_rate == ast_format_get_sample_rate(dst)) && (t->dst_codec.type == ast_format_get_type(dst))) {
571 explicit_dst = dst;
572 }
573 if (!(cur = newpvt(t, explicit_dst))) {
574 ast_log(LOG_WARNING, "Failed to build translator step from %s to %s\n",
575 ast_format_get_name(src), ast_format_get_name(dst));
576 ast_translator_free_path(head);
577 AST_RWLIST_UNLOCK(&translators);
578 return NULL;
579 }
580 if (!head) {
581 head = cur;
582 } else {
583 tail->next = cur;
584 }
585 tail = cur;
586 cur->nextin = cur->nextout = ast_tv(0, 0);
587 /* Keep going if this isn't the final destination */
588 src_index = cur->t->dst_fmt_index;
589 }
590
591 AST_RWLIST_UNLOCK(&translators);
592 return head;
593 }
594
595 static struct ast_frame *generate_interpolated_slin(struct ast_trans_pvt *p, struct ast_frame *f)
596 {
597 struct ast_frame res = { AST_FRAME_VOICE };
598
599 /*
600 * If we've gotten here then we should have an interpolated frame that was not handled
601 * by the translation codec. So create an interpolated frame in the appropriate format
602 * that was going to be written. This frame might be handled later by other resources.
603 * For instance, generic plc.
604 *
605 * Note, generic plc is currently only available for the format type 'slin' (8KHz only -
606 * The generic plc code appears to have been based around that). Generic plc is filled
607 * in later on frame write.
608 */
609 if (!ast_opt_generic_plc || f->datalen != 0 ||
610 ast_format_cmp(p->explicit_dst, ast_format_slin) == AST_FORMAT_CMP_NOT_EQUAL) {
611 return NULL;
612 }
613
614 res.subclass.format = ast_format_cache_get_slin_by_rate(8000); /* ref bumped on dup */
615 res.samples = f->samples;
616 res.datalen = 0;
617 res.data.ptr = NULL;
618 res.offset = AST_FRIENDLY_OFFSET;
619
620 return ast_frdup(&res);
621 }
622
623 /*! \brief do the actual translation */
624 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
625 {
•626 const unsigned int rtp_seqno_max_value = 0xffff;
627 struct ast_trans_pvt *p = path;
•628 struct ast_frame *out_last, *out = NULL;
629 struct timeval delivery;
630 int has_timing_info;
631 long ts;
632 long len;
•633 int seqno, frames_missing;
634
635 /* Determine the amount of lost packets for PLC */
636 /* But not at start with first frame = path->f.seqno is still 0x10000 */
637 /* But not when there is no sequence number = frame created internally */
638 if ((path->f.seqno <= rtp_seqno_max_value) && (path->f.seqno != f->seqno)) {
639 if (f->seqno < path->f.seqno) { /* seqno overrun situation */
640 frames_missing = rtp_seqno_max_value + f->seqno - path->f.seqno - 1;
641 } else {
642 frames_missing = f->seqno - path->f.seqno - 1;
643 }
644 /* Out-of-order packet - more precise: late packet */
645 if ((rtp_seqno_max_value + 1) / 2 < frames_missing) {
646 if (consume) {
647 ast_frfree(f);
648 }
649 /*
650 * Do not pass late packets to any transcoding module, because that
651 * confuses the state of any library (packets inter-depend). With
652 * the next packet, this one is going to be treated as lost packet.
653 */
654 return NULL;
655 }
656
657 if (frames_missing > 96) {
658 struct ast_str *str = ast_str_alloca(256);
659
660 /* disabled by default to not flood log in production even in non-Opus use
661 /* not DEBUG but NOTICE because of WARNING in main/channel.c:__ast_queue_frame */
662 //ast_log(LOG_NOTICE, "%d lost frame(s) %d/%d %s\n", frames_missing, f->seqno, path->f.seqno, ast_translate_path_to_str(path, &str));
663 }
664 } else {
665 frames_missing = 0;
666 }
667
668 if (f->frametype == AST_FRAME_RTCP) {
669 /* Just pass the feedback to the right callback, if it exists.
670 * This "translation" does nothing so return a null frame. */
671 struct ast_trans_pvt *tp;
672 for (tp = p; tp; tp = tp->next) {
673 if (tp->t->feedback)
674 tp->t->feedback(tp, f);
675 }
676 return &ast_null_frame;
677 }
678
679 has_timing_info = ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO);
680 ts = f->ts;
681 len = f->len;
682 seqno = f->seqno;
683
684 if (!ast_tvzero(f->delivery)) {
685 if (!ast_tvzero(path->nextin)) {
686 /* Make sure this is in line with what we were expecting */
687 if (!ast_tveq(path->nextin, f->delivery)) {
688 /* The time has changed between what we expected and this
689 most recent time on the new packet. If we have a
690 valid prediction adjust our output time appropriately */
691 if (!ast_tvzero(path->nextout)) {
692 path->nextout = ast_tvadd(path->nextout,
693 ast_tvsub(f->delivery, path->nextin));
694 }
695 path->nextin = f->delivery;
696 }
697 } else {
698 /* This is our first pass. Make sure the timing looks good */
699 path->nextin = f->delivery;
700 path->nextout = f->delivery;
701 }
702 /* Predict next incoming sample */
703 path->nextin = ast_tvadd(path->nextin, ast_samp2tv(
704 f->samples, ast_format_get_sample_rate(f->subclass.format)));
705 }
706 delivery = f->delivery;
707
•708 for (out_last = NULL; frames_missing + 1; frames_missing--) {
709 struct ast_frame *frame_to_translate, *inner_head;
710 struct ast_frame missed = {
711 .frametype = AST_FRAME_VOICE,
712 .subclass.format = f->subclass.format,
713 .datalen = 0,
714 /* In RTP, the amount of samples might change anytime */
715 /* If that happened while frames got lost, what to do? */
716 .samples = f->samples, /* FIXME */
717 .src = __FUNCTION__,
718 .data.uint32 = 0,
719 .delivery.tv_sec = 0,
720 .delivery.tv_usec = 0,
721 .flags = 0,
722 /* RTP sequence number is between 0x0001 and 0xffff */
723 .seqno = (rtp_seqno_max_value + 1 + f->seqno - frames_missing) & rtp_seqno_max_value,
724 };
725
726 if (frames_missing) {
727 frame_to_translate = &missed;
728 } else {
729 frame_to_translate = f;
730 }
731
732 /* The translation path from one format to another might contain several steps */
733 /* out* collects the result for missed frame(s) and input frame(s) */
734 /* out is the result of the conversion of all frames, translated into the destination format */
735 /* out_last is the last frame in that list, to add frames faster */
736 for (p = path, inner_head = frame_to_translate; inner_head && p; p = p->next) {
737 struct ast_frame *current, *inner_last, *inner_prev = frame_to_translate;
738
739 /* inner* collects the result of each conversion step, the input for the next step */
740 /* inner_head is a list of frames created by each conversion step */
741 /* inner_last is the last frame in that list, to add frames faster */
742 for (inner_last = NULL, current = inner_head; current; current = AST_LIST_NEXT(current, frame_list)) {
743 struct ast_frame *tmp;
744
745 framein(p, current);
746 tmp = p->t->frameout(p);
747
748 if (!tmp) {
749 continue;
750 } else if (inner_last) {
751 struct ast_frame *t;
752
753 /* Determine the last frame of the list before appending to it */
754 while ((t = AST_LIST_NEXT(inner_last, frame_list))) {
755 inner_last = t;
756 }
757 AST_LIST_NEXT(inner_last, frame_list) = tmp;
758 } else {
759 inner_prev = inner_head;
760 inner_head = tmp;
761 inner_last = tmp;
762 }
763 }
764
765 /* The current step did not create any frames = no frames for the next step */
766 /* The steps are not lost because framein buffered those for the next input frame */
767 if (!inner_last) {
768 inner_prev = inner_head;
769 inner_head = NULL;
770 }
771 if (inner_prev != frame_to_translate) {
772 ast_frfree(inner_prev); /* Frees just the intermediate lists */
773 }
774 }
775
776 /* This frame created no frames after translation = continue with next frame */
777 /* The frame is not lost because framein buffered it to be combined with the next frame */
778 if (!inner_head) {
779 continue;
780 } else if (out_last) {
781 struct ast_frame *t;
782
783 /* Determine the last frame of the list before appending to it */
784 while ((t = AST_LIST_NEXT(out_last, frame_list))) {
785 out_last = t;
786 }
787 AST_LIST_NEXT(out_last, frame_list) = inner_head;
788 } else {
789 out = inner_head;
790 out_last = inner_head;
791 }
792 }
793
•794
795 if (!out) {
796 out = generate_interpolated_slin(path, f);
797 }
798
799 if (out) {
800 /* we have a frame, play with times */
801 if (!ast_tvzero(delivery)) {
802 struct ast_frame *current = out;
803
804 do {
805 /* Regenerate prediction after a discontinuity */
806 if (ast_tvzero(path->nextout)) {
807 path->nextout = ast_tvnow();
808 }
809
810 /* Use next predicted outgoing timestamp */
811 current->delivery = path->nextout;
812
813 /* Invalidate prediction if we're entering a silence period */
814 if (current->frametype == AST_FRAME_CNG) {
815 path->nextout = ast_tv(0, 0);
816 /* Predict next outgoing timestamp from samples in this
817 frame. */
818 } else {
819 path->nextout = ast_tvadd(path->nextout, ast_samp2tv(
820 current->samples, ast_format_get_sample_rate(current->subclass.format)));
821 }
822
823 if (f->samples != current->samples && ast_test_flag(current, AST_FRFLAG_HAS_TIMING_INFO)) {
824 ast_debug(4, "Sample size different %d vs %d\n", f->samples, current->samples);
825 ast_clear_flag(current, AST_FRFLAG_HAS_TIMING_INFO);
826 }
827 current = AST_LIST_NEXT(current, frame_list);
828 } while (current);
829 } else {
830 out->delivery = ast_tv(0, 0);
831 ast_set2_flag(out, has_timing_info, AST_FRFLAG_HAS_TIMING_INFO);
832 if (has_timing_info) {
833 out->ts = ts;
834 out->len = len;
835 out->seqno = seqno;
836 }
837 /* Invalidate prediction if we're entering a silence period */
838 if (out->frametype == AST_FRAME_CNG) {
839 path->nextout = ast_tv(0, 0);
840 }
841 }
842 }
843 if (consume) {
844 ast_frfree(f);
845 }
846 return out;
847 }
848
849 /*! Maximum number of pre-encoded frames cached for non-slin benchmark sources */
850 #define PRE_ENCODE_POOL_MAX 200
851
852 /*!
853 * \internal
854 * \brief Build a translation path from slin (8 kHz) to the source codec of
855 * translator \p t, using the already-populated translation matrix.
856 *
857 * \note Must be called with the translators list locked.
858 *
859 * \retval NULL Source codec is already slin, or no path through the matrix exists.
860 */
861 static struct ast_trans_pvt *build_slin_to_src_path(const struct ast_translator *t)
862 {
863 struct ast_trans_pvt *head = NULL, *tail = NULL;
864 struct ast_codec *slin_codec;
865 int slin_index, dst_index;
866
867 if (!strcmp(t->src_codec.name, "slin")) {
868 return NULL; /* source is already slin, no pre-encoding needed */
869 }
870
871 slin_codec = ast_codec_get("slin", AST_MEDIA_TYPE_AUDIO, 8000);
872 if (!slin_codec) {
873 return NULL;
874 }
875
876 slin_index = codec2index(slin_codec);
877 ao2_ref(slin_codec, -1);
878
879 if (slin_index < 0) {
880 return NULL;
881 }
882
883 dst_index = t->src_fmt_index;
884 if (dst_index < 0 || slin_index == dst_index) {
885 return NULL;
886 }
887
888 while (slin_index != dst_index) {
889 struct ast_trans_pvt *cur;
890 struct ast_translator *step = matrix_get(slin_index, dst_index)->step;
891 if (!step) {
892 ast_translator_free_path(head);
893 return NULL;
894 }
895 cur = newpvt(step, NULL);
896 if (!cur) {
897 ast_translator_free_path(head);
898 return NULL;
899 }
900 if (!head) {
901 head = cur;
902 } else {
903 tail->next = cur;
904 }
905 tail = cur;
906 cur->nextin = cur->nextout = ast_tv(0, 0);
907 slin_index = cur->t->dst_fmt_index;
908 }
909
910 return head;
911 }
912
913 /*!
914 * \internal
915 * \brief Compute the computational cost of a single translation step.
916 *
917 * \note This function is only used to decide which translation path to
918 * use between two translators with identical src and dst formats. Computational
919 * cost acts only as a tie breaker. This is done so hardware translators
920 * can naturally have precedence over software translators.
921 */
922 static void generate_computational_cost(struct ast_translator *t, int seconds)
923 {
924 int num_samples = 0;
925 struct ast_trans_pvt *pvt;
926 struct rusage start;
927 struct rusage end;
928 int cost;
929 int out_rate = t->dst_codec.sample_rate;
930 struct ast_frame **pre_pool = NULL;
931 int pre_pool_count = 0;
932 int pre_pool_idx = 0;
933 int use_pre_pool = 0;
934
935 if (!seconds) {
936 seconds = 1;
937 }
938
939 /* If they don't make samples, give them a terrible score */
940 if (!t->sample) {
941 ast_debug(3, "Translator '%s' does not produce sample frames.\n", t->name);
942 t->comp_cost = 999999;
943 return;
944 }
945
946 pvt = newpvt(t, NULL);
947 if (!pvt) {
948 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
949 t->comp_cost = 999999;
950 return;
951 }
952
953 /*
954 * For non-CODEC sample types, pre-generate frames before starting the
955 * timer so sample-generation overhead is excluded from the measurement.
956 *
957 * For slin sources: isolate a fresh copy of each generated frame directly.
958 * For non-slin sources: route the generated slin frames through a
959 * slin->src_codec encoding path first. If no such path exists in the
960 * current matrix, use_pre_pool stays 0 and we fall back to t->sample().
961 */
962 if (current_sample_type != SAMPLE_TYPE_CODEC) {
963 int16_t slin_buf[80];
964 struct ast_frame slin_f;
965 struct ast_trans_pvt *pre_path = NULL;
966 int attempt;
967
968 if (strcmp(t->src_codec.name, "slin")) {
969 pre_path = build_slin_to_src_path(t);
970 }
971
972 if (!strcmp(t->src_codec.name, "slin") || pre_path) {
973 pre_pool = ast_malloc(PRE_ENCODE_POOL_MAX * sizeof(*pre_pool));
974 if (pre_pool) {
975 memset(&slin_f, 0, sizeof(slin_f));
976 slin_f.frametype = AST_FRAME_VOICE;
977 slin_f.datalen = sizeof(slin_buf);
978 slin_f.samples = ARRAY_LEN(slin_buf);
979 slin_f.data.ptr = slin_buf;
980 slin_f.src = __PRETTY_FUNCTION__;
981 slin_f.subclass.format = ast_format_slin;
982
983 for (attempt = 0; pre_pool_count < PRE_ENCODE_POOL_MAX; attempt++) {
984 struct ast_frame *out;
985
986 if (attempt >= PRE_ENCODE_POOL_MAX * 10) {
987 break; /* encoder not producing output; give up */
988 }
989
990 generate_samples(slin_buf, ARRAY_LEN(slin_buf),
991 attempt * (int)ARRAY_LEN(slin_buf));
992
993 if (pre_path) {
994 /* non-slin: encode through the pre_path chain */
995 struct ast_trans_pvt *pp;
996 out = &slin_f;
997 for (pp = pre_path; pp; pp = pp->next) {
998 struct ast_frame *next_out;
999 framein(pp, out);
1000 if (out != &slin_f) {
1001 ast_frfree(out);
1002 }
1003 next_out = pp->t->frameout(pp);
1004 out = next_out;
1005 if (!out) {
1006 break;
1007 }
1008 }
1009 } else {
1010 /* slin: isolate a standalone copy of the frame */
1011 out = ast_frisolate(&slin_f);
1012 }
1013
1014 if (out) {
1015 pre_pool[pre_pool_count++] = out;
1016 }
1017 }
1018 use_pre_pool = (pre_pool_count > 0);
1019 }
1020 ast_translator_free_path(pre_path);
1021 }
1022 }
1023
1024 getrusage(RUSAGE_SELF, &start);
1025
1026 /* Call the encoder until we've processed the required number of samples */
1027 while (num_samples < seconds * out_rate) {
1028 struct ast_frame *f;
1029
1030 if (use_pre_pool) {
1031 /* cycle through the pre-generated frame pool */
1032 framein(pvt, pre_pool[pre_pool_idx % pre_pool_count]);
1033 pre_pool_idx++;
1034 } else {
1035 /* default: use the codec's own sample generator */
1036 f = t->sample();
1037 if (!f) {
1038 ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
1039 destroy(pvt);
1040 t->comp_cost = 999999;
1041 goto cleanup;
1042 }
1043 framein(pvt, f);
1044 ast_frfree(f);
1045 }
1046
1047 while ((f = t->frameout(pvt))) {
1048 num_samples += f->samples;
1049 ast_frfree(f);
1050 }
1051 }
1052
1053 getrusage(RUSAGE_SELF, &end);
1054
1055 cost = ((end.ru_utime.tv_sec - start.ru_utime.tv_sec) * 1000000) + end.ru_utime.tv_usec - start.ru_utime.tv_usec;
1056 cost += ((end.ru_stime.tv_sec - start.ru_stime.tv_sec) * 1000000) + end.ru_stime.tv_usec - start.ru_stime.tv_usec;
1057
1058 destroy(pvt);
1059
1060 t->comp_cost = cost / seconds;
1061
1062 if (!t->comp_cost) {
1063 t->comp_cost = 1;
1064 }
1065
1066 cleanup:
1067 if (pre_pool) {
1068 int i;
1069 for (i = 0; i < pre_pool_count; i++) {
1070 ast_frfree(pre_pool[i]);
1071 }
1072 ast_free(pre_pool);
1073 }
1074 }
1075
1076 /*!
1077 * \internal
1078 *
1079 * \brief If no table cost value was pre set by the translator. An attempt is made to
1080 * automatically generate that cost value from the cost table based on our src and
1081 * dst formats.
1082 *
1083 * \note This function allows older translators built before the translation cost
1084 * changed away from using onely computational time to continue to be registered
1085 * correctly. It is expected that translators built after the introduction of this
1086 * function will manually assign their own table cost value.
1087 *
1088 * \note This function is safe to use on any audio formats that used to be defined in the
1089 * first 64 bits of the old bit field codec representation.
1090 *
1091 * \return Table Cost value greater than 0.
1092 * \retval 0 on error.
1093 */
1094 static int generate_table_cost(struct ast_codec *src, struct ast_codec *dst)
1095 {
1096 int src_rate = src->sample_rate;
1097 int src_ll = 0;
1098 int dst_rate = dst->sample_rate;
1099 int dst_ll = 0;
1100
1101 if ((src->type != AST_MEDIA_TYPE_AUDIO) ||
1102 (dst->type != AST_MEDIA_TYPE_AUDIO)) {
1103 /* This method of generating table cost is limited to audio.
1104 * Translators for media other than audio must manually set their
1105 * table cost. */
1106 return 0;
1107 }
1108
1109 src_ll = !strcmp(src->name, "slin");
1110 dst_ll = !strcmp(dst->name, "slin");
1111 if (src_ll) {
1112 if (dst_ll && (src_rate == dst_rate)) {
1113 return AST_TRANS_COST_LL_LL_ORIGSAMP;
1114 } else if (!dst_ll && (src_rate == dst_rate)) {
1115 return AST_TRANS_COST_LL_LY_ORIGSAMP;
1116 } else if (dst_ll && (src_rate < dst_rate)) {
1117 return AST_TRANS_COST_LL_LL_UPSAMP;
1118 } else if (!dst_ll && (src_rate < dst_rate)) {
1119 return AST_TRANS_COST_LL_LY_UPSAMP;
1120 } else if (dst_ll && (src_rate > dst_rate)) {
1121 return AST_TRANS_COST_LL_LL_DOWNSAMP;
1122 } else if (!dst_ll && (src_rate > dst_rate)) {
1123 return AST_TRANS_COST_LL_LY_DOWNSAMP;
1124 } else {
1125 return AST_TRANS_COST_LL_UNKNOWN;
1126 }
1127 } else {
1128 if (dst_ll && (src_rate == dst_rate)) {
1129 return AST_TRANS_COST_LY_LL_ORIGSAMP;
1130 } else if (!dst_ll && (src_rate == dst_rate)) {
1131 return AST_TRANS_COST_LY_LY_ORIGSAMP;
1132 } else if (dst_ll && (src_rate < dst_rate)) {
1133 return AST_TRANS_COST_LY_LL_UPSAMP;
1134 } else if (!dst_ll && (src_rate < dst_rate)) {
1135 return AST_TRANS_COST_LY_LY_UPSAMP;
1136 } else if (dst_ll && (src_rate > dst_rate)) {
1137 return AST_TRANS_COST_LY_LL_DOWNSAMP;
1138 } else if (!dst_ll && (src_rate > dst_rate)) {
1139 return AST_TRANS_COST_LY_LY_DOWNSAMP;
1140 } else {
1141 return AST_TRANS_COST_LY_UNKNOWN;
1142 }
1143 }
1144 }
1145
1146 /*!
1147 * \brief rebuild a translation matrix.
1148 * \note This function expects the list of translators to be locked
1149 */
1150 static void matrix_rebuild(int samples)
1151 {
1152 struct ast_translator *t;
1153 int newtablecost;
1154 int x; /* source format index */
1155 int y; /* intermediate format index */
1156 int z; /* destination format index */
1157
1158 ast_debug(1, "Resetting translation matrix\n");
1159
1160 matrix_clear();
1161
1162 /* first, compute all direct costs */
1163 AST_RWLIST_TRAVERSE(&translators, t, list) {
1164 if (!t->active) {
1165 continue;
1166 }
1167
1168 x = t->src_fmt_index;
1169 z = t->dst_fmt_index;
1170
1171 if (samples) {
1172 generate_computational_cost(t, samples);
1173 }
1174
1175 /* This new translator is the best choice if any of the below are true.
1176 * 1. no translation path is set between x and z yet.
1177 * 2. the new table cost is less.
1178 * 3. the new computational cost is less. Computational cost is only used
1179 * to break a tie between two identical translation paths.
1180 */
1181 if (!matrix_get(x, z)->step ||
1182 (t->table_cost < matrix_get(x, z)->step->table_cost) ||
1183 (t->comp_cost < matrix_get(x, z)->step->comp_cost)) {
1184
1185 matrix_get(x, z)->step = t;
1186 matrix_get(x, z)->table_cost = t->table_cost;
1187 matrix_get(x, z)->comp_cost = t->comp_cost;
1188 }
1189 }
1190
1191 /*
1192 * For each triple x, y, z of distinct formats, check if there is
1193 * a path from x to z through y which is cheaper than what is
1194 * currently known, and in case, update the matrix.
1195 * Repeat until the matrix is stable.
1196 */
1197 for (;;) {
1198 int changed = 0;
1199 for (x = 0; x < cur_max_index; x++) { /* source format */
1200 for (y = 0; y < cur_max_index; y++) { /* intermediate format */
1201 if (x == y) { /* skip ourselves */
1202 continue;
1203 }
1204 for (z = 0; z < cur_max_index; z++) { /* dst format */
1205 if ((z == x || z == y) || /* skip null conversions */
1206 !matrix_get(x, y)->step || /* no path from x to y */
1207 !matrix_get(y, z)->step) { /* no path from y to z */
1208 continue;
1209 }
1210
1211 /* calculate table cost from x->y->z */
1212 newtablecost = matrix_get(x, y)->table_cost + matrix_get(y, z)->table_cost;
1213
1214 /* if no step already exists between x and z OR the new cost of using the intermediate
1215 * step is cheaper, use this step. */
1216 if (!matrix_get(x, z)->step || (newtablecost < matrix_get(x, z)->table_cost)) {
1217 matrix_get(x, z)->step = matrix_get(x, y)->step;
1218 matrix_get(x, z)->table_cost = newtablecost;
1219 matrix_get(x, z)->multistep = 1;
1220 changed++;
1221
1222 if (DEBUG_ATLEAST(10)) {
1223 struct ast_codec *x_codec = index2codec(x);
1224 struct ast_codec *y_codec = index2codec(y);
1225 struct ast_codec *z_codec = index2codec(z);
1226
1227 ast_log(LOG_DEBUG,
1228 "Discovered %u cost path from %s to %s, via %s\n",
1229 matrix_get(x, z)->table_cost, x_codec->name,
1230 y_codec->name, z_codec->name);
1231
1232 ao2_ref(x_codec, -1);
1233 ao2_ref(y_codec, -1);
1234 ao2_ref(z_codec, -1);
1235 }
1236 }
1237 }
1238 }
1239 }
1240 if (!changed) {
1241 break;
1242 }
1243 }
1244 }
1245
1246 static void codec_append_name(const struct ast_codec *codec, struct ast_str **buf)
1247 {
1248 if (codec) {
1249 ast_str_append(buf, 0, "(%s@%u)", codec->name, codec->sample_rate);
1250 } else {
1251 ast_str_append(buf, 0, "(nothing)");
1252 }
1253 }
1254
1255 const char *ast_translate_path_to_str(struct ast_trans_pvt *p, struct ast_str **str)
1256 {
1257 if (!p || !p->t) {
1258 return "";
1259 }
1260
1261 ast_str_reset(*str);
1262 codec_append_name(&p->t->src_codec, str);
1263 while (p) {
1264 ast_str_append(str, 0, "->");
1265 codec_append_name(&p->t->dst_codec, str);
1266 p = p->next;
1267 }
1268
1269 return ast_str_buffer(*str);
1270 }
1271
1272 static char *complete_trans_path_choice(const char *word)
1273 {
1274 int i = 1;
1275 int wordlen = strlen(word);
1276 struct ast_codec *codec;
1277
1278 while ((codec = ast_codec_get_by_id(i))) {
1279 ++i;
1280 if (codec->type != AST_MEDIA_TYPE_AUDIO) {
1281 ao2_ref(codec, -1);
1282 continue;
1283 }
1284 if (!strncasecmp(word, codec->name, wordlen)) {
1285 if (ast_cli_completion_add(ast_strdup(codec->name))) {
1286 ao2_ref(codec, -1);
1287 break;
1288 }
1289 }
1290 ao2_ref(codec, -1);
1291 }
1292
1293 return NULL;
1294 }
1295
1296 static void handle_cli_recalc(struct ast_cli_args *a)
1297 {
1298 int time = a->argv[4] ? atoi(a->argv[4]) : 1;
1299
1300 if (time <= 0) {
1301 ast_cli(a->fd, " Recalc must be greater than 0. Defaulting to 1.\n");
1302 time = 1;
1303 }
1304
1305 if (time > MAX_RECALC) {
1306 ast_cli(a->fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", time - MAX_RECALC, MAX_RECALC);
1307 time = MAX_RECALC;
1308 }
1309 ast_cli(a->fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", time);
1310 AST_RWLIST_WRLOCK(&translators);
1311 matrix_rebuild(time);
1312 AST_RWLIST_UNLOCK(&translators);
1313 }
1314
1315 static char *handle_show_translation_table(struct ast_cli_args *a)
1316 {
1317 int x, y, i, k, compCost;
1318 int longest = 7; /* slin192 */
1319 int max_codec_index = 0, curlen = 0;
1320 struct ast_str *out = ast_str_create(1024);
1321 struct ast_codec *codec;
1322
1323 /* Get the length of the longest (usable?) codec name,
1324 so we know how wide the left side should be */
1325 for (i = 1; (codec = ast_codec_get_by_id(i)); ao2_ref(codec, -1), ++i) {
1326 ++max_codec_index;
1327 if (codec->type != AST_MEDIA_TYPE_AUDIO) {
1328 continue;
1329 }
1330 curlen = strlen(codec->name);
1331 if (curlen > longest) {
1332 longest = curlen;
1333 }
1334 }
1335
1336 AST_RWLIST_RDLOCK(&translators);
1337 ast_cli(a->fd, " Translation times between formats (in microseconds) for one second of data\n");
1338 ast_cli(a->fd, " Source Format (Rows) Destination Format (Columns)\n\n");
1339
1340 for (i = 0; i <= max_codec_index; i++) {
1341 struct ast_codec *row = i ? ast_codec_get_by_id(i) : NULL;
1342
1343 x = -1;
1344 if ((i > 0) && (row->type != AST_MEDIA_TYPE_AUDIO)) {
1345 ao2_ref(row, -1);
1346 continue;
1347 }
1348
1349 if ((i > 0) && (x = codec2index(row)) == -1) {
1350 ao2_ref(row, -1);
1351 continue;
1352 }
1353
1354 ast_str_set(&out, 0, " ");
1355 for (k = 0; k <= max_codec_index; k++) {
1356 int adjust = 0;
1357 struct ast_codec *col = k ? ast_codec_get_by_id(k) : NULL;
1358
1359 y = -1;
1360 if ((k > 0) && (col->type != AST_MEDIA_TYPE_AUDIO)) {
1361 ao2_ref(col, -1);
1362 continue;
1363 }
1364
1365 if ((k > 0) && (y = codec2index(col)) == -1) {
1366 ao2_ref(col, -1);
1367 continue;
1368 }
1369
1370 if (k > 0) {
1371 curlen = strlen(col->name);
1372 if (!strcmp(col->name, "slin") ||
1373 !strcmp(col->name, "speex") ||
1374 !strcmp(col->name, "silk")) {
1375 adjust = log10(col->sample_rate / 1000) + 1;
1376 curlen = curlen + adjust;
1377 }
1378 }
1379
1380 if (curlen < 5) {
1381 curlen = 5;
1382 }
1383
1384 if (x >= 0 && y >= 0 && matrix_get(x, y)->step) {
1385 /* Actual codec output */
1386 if (a->argv[3] && !strcasecmp(a->argv[3], "comp")) {
1387 compCost = matrix_get(x, y)->comp_cost;
1388 if (compCost == 0 || compCost == 999999) {
1389 ast_str_append(&out, 0, "%*s", curlen + 1, "-");
1390 } else {
1391 ast_str_append(&out, 0, "%*u", curlen + 1, compCost);
1392 }
1393 } else {
1394 ast_str_append(&out, 0, "%*u", curlen + 1, (matrix_get(x, y)->table_cost / 100));
1395 }
1396 } else if (i == 0 && k > 0) {
1397 /* Top row - use a dynamic size */
1398 if (!strcmp(col->name, "slin") ||
1399 !strcmp(col->name, "speex") ||
1400 !strcmp(col->name, "silk")) {
1401 ast_str_append(&out, 0, "%*s%u", curlen - adjust + 1,
1402 col->name, col->sample_rate / 1000);
1403 } else {
1404 ast_str_append(&out, 0, "%*s", curlen + 1, col->name);
1405 }
1406 } else if (k == 0 && i > 0) {
1407 /* Left column - use a static size. */
1408 if (!strcmp(row->name, "slin") ||
1409 !strcmp(row->name, "speex") ||
1410 !strcmp(row->name, "silk")) {
1411 int adjust_row = log10(row->sample_rate / 1000) + 1;
1412 ast_str_append(&out, 0, "%*s%u", longest - adjust_row,
1413 row->name, row->sample_rate / 1000);
1414 } else {
1415 ast_str_append(&out, 0, "%*s", longest, row->name);
1416 }
1417 } else if (x >= 0 && y >= 0) {
1418 /* Codec not supported */
1419 ast_str_append(&out, 0, "%*s", curlen + 1, "-");
1420 } else {
1421 /* Upper left hand corner */
1422 ast_str_append(&out, 0, "%*s", longest, "");
1423 }
1424 ao2_cleanup(col);
1425 }
1426 ast_str_append(&out, 0, "\n");
1427 ast_cli(a->fd, "%s", ast_str_buffer(out));
1428 ao2_cleanup(row);
1429 }
1430 ast_free(out);
1431 AST_RWLIST_UNLOCK(&translators);
1432 return CLI_SUCCESS;
1433 }
1434
1435 static char *handle_show_translation_path(struct ast_cli_args *a, const char *codec_name, unsigned int sample_rate)
1436 {
1437 int i = 1;
1438 struct ast_str *str = ast_str_alloca(1024);
1439 struct ast_translator *step;
1440 struct ast_codec *dst_codec;
1441 struct ast_codec *src_codec = ast_codec_get(codec_name, AST_MEDIA_TYPE_AUDIO, sample_rate);
1442
1443 if (!src_codec) {
1444 ast_cli(a->fd, "Source codec \"%s\" is not found.\n", codec_name);
1445 return CLI_FAILURE;
1446 }
1447
1448 AST_RWLIST_RDLOCK(&translators);
1449 ast_cli(a->fd, "--- Translation paths SRC Codec \"%s\" sample rate %u ---\n",
1450 codec_name, src_codec->sample_rate);
1451
1452 while ((dst_codec = ast_codec_get_by_id(i))) {
1453 int src, dst;
1454 char src_buffer[64];
1455 char dst_buffer[64];
1456
1457 ++i;
1458 if (src_codec == dst_codec ||
1459 dst_codec->type != AST_MEDIA_TYPE_AUDIO) {
1460 ao2_ref(dst_codec, -1);
1461 continue;
1462 }
1463
1464 dst = codec2index(dst_codec);
1465 src = codec2index(src_codec);
1466
1467 if (src < 0 || dst < 0) {
1468 ast_str_set(&str, 0, "No Translation Path");
1469 } else {
1470 step = matrix_get(src, dst)->step;
1471
1472 if (step) {
1473 codec_append_name(&step->src_codec, &str);
1474 while (src != dst) {
1475 src = step->dst_fmt_index;
1476 step = matrix_get(src, dst)->step;
1477 if (!step) {
1478 ast_str_append(&str, 0, "->");
1479 codec_append_name(dst_codec, &str);
1480 break;
1481 }
1482 ast_str_append(&str, 0, "->");
1483 codec_append_name(&step->src_codec, &str);
1484 }
1485 }
1486 }
1487
1488 snprintf(src_buffer, sizeof(src_buffer), "%s:%u", src_codec->name, src_codec->sample_rate);
1489 snprintf(dst_buffer, sizeof(dst_buffer), "%s:%u", dst_codec->name, dst_codec->sample_rate);
1490 ast_cli(a->fd, "\t%-16.16s To %-16.16s: %-60.60s\n",
1491 src_buffer, dst_buffer, ast_str_buffer(str));
1492 ast_str_reset(str);
1493 ao2_ref(dst_codec, -1);
1494 }
1495 AST_RWLIST_UNLOCK(&translators);
1496 ao2_ref(src_codec, -1);
1497 return CLI_SUCCESS;
1498 }
1499
1500 static char *handle_cli_core_show_translation(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1501 {
1502 static const char * const option[] = { "recalc", "paths", "comp", NULL };
1503
1504 switch (cmd) {
1505 case CLI_INIT:
1506 e->command = "core show translation";
1507 e->usage =
1508 "Usage: 'core show translation' can be used in three ways.\n"
1509 " 1. 'core show translation [recalc [<recalc seconds>]\n"
1510 " Displays known codec translators and the cost associated\n"
1511 " with each conversion. If the argument 'recalc' is supplied along\n"
1512 " with optional number of seconds to test a new test will be performed\n"
1513 " as the chart is being displayed.\n"
1514 " 2. 'core show translation paths [codec [sample_rate]]'\n"
1515 " This will display all the translation paths associated with a codec.\n"
1516 " If a codec has multiple sample rates, the sample rate must be\n"
1517 " provided as well.\n"
1518 " 3. 'core show translation comp [<recalc seconds>]'\n"
1519 " Displays known codec translators and the cost associated\n"
1520 " with each conversion. If the argument 'recalc' is supplied along\n"
1521 " with optional number of seconds to test a new test will be performed\n"
1522 " as the chart is being displayed. The resulting numbers in the table\n"
1523 " give the actual computational costs in microseconds.\n";
1524 return NULL;
1525 case CLI_GENERATE:
1526 if (a->pos == 3) {
1527 return ast_cli_complete(a->word, option, -1);
1528 }
1529 if (a->pos == 4 && !strcasecmp(a->argv[3], option[1])) {
1530 return complete_trans_path_choice(a->word);
1531 }
1532 /* BUGBUG - add tab completion for sample rates */
1533 return NULL;
1534 }
1535
1536 if (a->argc > 6)
1537 return CLI_SHOWUSAGE;
1538
1539 if (a->argv[3] && !strcasecmp(a->argv[3], option[1]) && a->argc == 5) { /* show paths */
1540 return handle_show_translation_path(a, a->argv[4], 0);
1541 } else if (a->argv[3] && !strcasecmp(a->argv[3], option[1]) && a->argc == 6) {
1542 unsigned int sample_rate;
1543 if (sscanf(a->argv[5], "%30u", &sample_rate) != 1) {
1544 ast_cli(a->fd, "Invalid sample rate: %s.\n", a->argv[5]);
1545 return CLI_FAILURE;
1546 }
1547 return handle_show_translation_path(a, a->argv[4], sample_rate);
1548 } else if (a->argv[3] && (!strcasecmp(a->argv[3], option[0]) || !strcasecmp(a->argv[3], option[2]))) { /* recalc and then fall through to show table */
1549 handle_cli_recalc(a);
1550 } else if (a->argc > 3) { /* wrong input */
1551 return CLI_SHOWUSAGE;
1552 }
1553
1554 return handle_show_translation_table(a);
1555 }
1556
1557 static char *handle_cli_translate_sampletype(struct ast_cli_entry *e,
1558 int cmd, struct ast_cli_args *a)
1559 {
1560 static const char * const types[] = { "codec", "sine", "silence", "noise", "speech", NULL };
1561
1562 switch (cmd) {
1563 case CLI_INIT:
1564 e->command = "translate sampletype";
1565 e->usage =
1566 "Usage: translate sampletype [codec|sine|silence|noise|speech]\n"
1567 " Get or set the sample type used for codec matrix cost\n"
1568 " computation. Default is 'codec'.\n"
1569 " codec - samples defined inside codec\n"
1570 " sine - 1kHz sine wave\n"
1571 " silence - All-zero frames\n"
1572 " noise - White noise\n"
1573 " speech - Synthetic speech-like signal (P.50 inspired)\n";
1574 return NULL;
1575 case CLI_GENERATE:
1576 return ast_cli_complete(a->word, types, a->n);
1577 }
1578
1579 if (a->argc == 2) {
1580 /* Query current setting */
1581 const char *names[] = { "codec", "sine", "silence", "noise", "speech" };
1582 ast_cli(a->fd, "Current translate sample type: %s\n",
1583 names[current_sample_type]);
1584 return CLI_SUCCESS;
1585 }
1586
1587 if (a->argc != 3)
1588 return CLI_SHOWUSAGE;
1589
1590 if (!strcasecmp(a->argv[2], "silence")) {
1591 current_sample_type = SAMPLE_TYPE_SILENCE;
1592 } else if (!strcasecmp(a->argv[2], "noise")) {
1593 current_sample_type = SAMPLE_TYPE_NOISE;
1594 } else if (!strcasecmp(a->argv[2], "speech")) {
1595 current_sample_type = SAMPLE_TYPE_SPEECH;
1596 } else if (!strcasecmp(a->argv[2], "sine")) {
1597 current_sample_type = SAMPLE_TYPE_SINE;
1598 } else if (!strcasecmp(a->argv[2], "codec")) {
1599 current_sample_type = SAMPLE_TYPE_CODEC;
1600 } else {
1601 ast_cli(a->fd, "Unknown sample type '%s'. Use: codec, sine, silence, noise, speech\n",
1602 a->argv[2]);
1603 return CLI_SHOWUSAGE;
1604 }
1605
1606 /* Rebuild the matrix with the new sample type */
1607 ast_cli(a->fd, "Sample type set to '%s'. Rebuilding codec matrix...\n", a->argv[2]);
1608 AST_RWLIST_WRLOCK(&translators);
1609 matrix_rebuild(1);
1610 AST_RWLIST_UNLOCK(&translators);
1611
1612 return CLI_SUCCESS;
1613 }
1614
1615 static struct ast_cli_entry cli_translate[] = {
1616 AST_CLI_DEFINE(handle_cli_core_show_translation, "Display translation matrix"),
1617 AST_CLI_DEFINE(handle_cli_translate_sampletype, "Get/set codec matrix sample type"),
1618 };
1619
1620 /*! \brief register codec translator */
1621 int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
1622 {
1623 struct ast_translator *u;
1624 char tmp[80];
1625 RAII_VAR(struct ast_codec *, src_codec, NULL, ao2_cleanup);
1626 RAII_VAR(struct ast_codec *, dst_codec, NULL, ao2_cleanup);
1627
1628 src_codec = ast_codec_get(t->src_codec.name, t->src_codec.type, t->src_codec.sample_rate);
1629 if (!src_codec) {
1630 ast_assert(0);
1631 ast_log(LOG_WARNING, "Failed to register translator: unknown source codec %s\n", t->src_codec.name);
1632 return -1;
1633 }
1634
1635 dst_codec = ast_codec_get(t->dst_codec.name, t->dst_codec.type, t->dst_codec.sample_rate);
1636 if (!dst_codec) {
1637 ast_log(LOG_WARNING, "Failed to register translator: unknown destination codec %s\n", t->dst_codec.name);
1638 return -1;
1639 }
1640
1641 if (add_codec2index(src_codec) || add_codec2index(dst_codec)) {
1642 if (matrix_resize(0)) {
1643 ast_log(LOG_WARNING, "Translator matrix can not represent any more translators. Out of resources.\n");
1644 return -1;
1645 }
1646 add_codec2index(src_codec);
1647 add_codec2index(dst_codec);
1648 }
1649
1650 if (!mod) {
1651 ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
1652 return -1;
1653 }
1654
1655 if (!t->buf_size) {
1656 ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
1657 return -1;
1658 }
1659 if (!t->table_cost && !(t->table_cost = generate_table_cost(src_codec, dst_codec))) {
1660 ast_log(LOG_WARNING, "Table cost could not be generated for %s, "
1661 "Please set table_cost variable on translator.\n", t->name);
1662 return -1;
1663 }
1664
1665 t->module = mod;
1666 t->src_fmt_index = codec2index(src_codec);
1667 t->dst_fmt_index = codec2index(dst_codec);
1668 t->active = 1;
1669
1670 if (t->src_fmt_index < 0 || t->dst_fmt_index < 0) {
1671 ast_log(LOG_WARNING, "Invalid translator path: (%s codec is not valid)\n", t->src_fmt_index < 0 ? "starting" : "ending");
1672 return -1;
1673 }
1674 if (t->src_fmt_index >= cur_max_index) {
1675 ast_log(LOG_WARNING, "Source codec %s is larger than cur_max_index\n", t->src_codec.name);
1676 return -1;
1677 }
1678
1679 if (t->dst_fmt_index >= cur_max_index) {
1680 ast_log(LOG_WARNING, "Destination codec %s is larger than cur_max_index\n", t->dst_codec.name);
1681 return -1;
1682 }
1683
1684 if (t->buf_size) {
1685 /*
1686 * Align buf_size properly, rounding up to the machine-specific
1687 * alignment for pointers.
1688 */
1689 struct _test_align { void *a, *b; } p;
1690 int align = (char *)&p.b - (char *)&p.a;
1691
1692 t->buf_size = ((t->buf_size + align - 1) / align) * align;
1693 }
1694
1695 if (t->frameout == NULL) {
1696 t->frameout = default_frameout;
1697 }
1698
1699 generate_computational_cost(t, 1);
1700
1701 ast_verb(5, "Registered translator '%s' from codec %s to %s, table cost, %d, computational cost %d\n",
1702 term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
1703 t->src_codec.name, t->dst_codec.name, t->table_cost, t->comp_cost);
1704
1705 AST_RWLIST_WRLOCK(&translators);
1706
1707 /* find any existing translators that provide this same srcfmt/dstfmt,
1708 and put this one in order based on computational cost */
1709 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
1710 if ((u->src_fmt_index == t->src_fmt_index) &&
1711 (u->dst_fmt_index == t->dst_fmt_index) &&
1712 (u->comp_cost > t->comp_cost)) {
1713 AST_RWLIST_INSERT_BEFORE_CURRENT(t, list);
1714 t = NULL;
1715 break;
1716 }
1717 }
1718 AST_RWLIST_TRAVERSE_SAFE_END;
1719
1720 /* if no existing translator was found for this codec combination,
1721 add it to the beginning of the list */
1722 if (t) {
1723 AST_RWLIST_INSERT_HEAD(&translators, t, list);
1724 }
1725
1726 matrix_rebuild(0);
1727
1728 AST_RWLIST_UNLOCK(&translators);
1729
1730 return 0;
1731 }
1732
1733 /*! \brief unregister codec translator */
1734 int ast_unregister_translator(struct ast_translator *t)
1735 {
1736 char tmp[80];
1737 struct ast_translator *u;
1738 int found = 0;
1739
1740 AST_RWLIST_WRLOCK(&translators);
1741 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
1742 if (u == t) {
1743 AST_RWLIST_REMOVE_CURRENT(list);
1744 ast_verb(5, "Unregistered translator '%s' from codec %s to %s\n",
1745 term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
1746 t->src_codec.name, t->dst_codec.name);
1747 found = 1;
1748 break;
1749 }
1750 }
1751 AST_RWLIST_TRAVERSE_SAFE_END;
1752
1753 if (found && !ast_shutting_down()) {
1754 matrix_rebuild(0);
1755 }
1756
1757 AST_RWLIST_UNLOCK(&translators);
1758
1759 return (u ? 0 : -1);
1760 }
1761
1762 void ast_translator_activate(struct ast_translator *t)
1763 {
1764 AST_RWLIST_WRLOCK(&translators);
1765 t->active = 1;
1766 matrix_rebuild(0);
1767 AST_RWLIST_UNLOCK(&translators);
1768 }
1769
1770 void ast_translator_deactivate(struct ast_translator *t)
1771 {
1772 AST_RWLIST_WRLOCK(&translators);
1773 t->active = 0;
1774 matrix_rebuild(0);
1775 AST_RWLIST_UNLOCK(&translators);
1776 }
1777
1778 /*! Calculate the absolute difference between sample rate of two formats. */
1779 #define format_sample_rate_absdiff(fmt1, fmt2) ({ \
1780 unsigned int rate1 = ast_format_get_sample_rate(fmt1); \
1781 unsigned int rate2 = ast_format_get_sample_rate(fmt2); \
1782 (rate1 > rate2 ? rate1 - rate2 : rate2 - rate1); \
1783 })
1784
1785 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
1786 int ast_translator_best_choice(struct ast_format_cap *dst_cap,
1787 struct ast_format_cap *src_cap,
1788 struct ast_format **dst_fmt_out,
1789 struct ast_format **src_fmt_out)
1790 {
1791 unsigned int besttablecost = INT_MAX;
1792 unsigned int beststeps = INT_MAX;
1793 struct ast_format *fmt;
1794 struct ast_format *dst;
1795 struct ast_format *src;
1796 RAII_VAR(struct ast_format *, best, NULL, ao2_cleanup);
1797 RAII_VAR(struct ast_format *, bestdst, NULL, ao2_cleanup);
1798 struct ast_format_cap *joint_cap;
1799 int i;
1800 int j;
1801
1802 if (ast_format_cap_empty(dst_cap) || ast_format_cap_empty(src_cap)) {
1803 ast_log(LOG_ERROR, "Cannot determine best translation path since one capability supports no formats\n");
1804 return -1;
1805 }
1806
1807 joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1808 if (!joint_cap) {
1809 return -1;
1810 }
1811 ast_format_cap_get_compatible(dst_cap, src_cap, joint_cap);
1812
1813 for (i = 0; i < ast_format_cap_count(joint_cap); ++i, ao2_cleanup(fmt)) {
1814 fmt = ast_format_cap_get_format(joint_cap, i);
1815 if (!fmt
1816 || ast_format_get_type(fmt) != AST_MEDIA_TYPE_AUDIO) {
1817 continue;
1818 }
1819
1820 if (!best
1821 || ast_format_get_sample_rate(best) < ast_format_get_sample_rate(fmt)) {
1822 ao2_replace(best, fmt);
1823 }
1824 }
1825 ao2_ref(joint_cap, -1);
1826
1827 if (best) {
1828 ao2_replace(*dst_fmt_out, best);
1829 ao2_replace(*src_fmt_out, best);
1830 return 0;
1831 }
1832
1833 /* need to translate */
1834 AST_RWLIST_RDLOCK(&translators);
1835 for (i = 0; i < ast_format_cap_count(dst_cap); ++i, ao2_cleanup(dst)) {
1836 dst = ast_format_cap_get_format(dst_cap, i);
1837 if (!dst
1838 || ast_format_get_type(dst) != AST_MEDIA_TYPE_AUDIO) {
1839 continue;
1840 }
1841
1842 for (j = 0; j < ast_format_cap_count(src_cap); ++j, ao2_cleanup(src)) {
1843 int x;
1844 int y;
1845
1846 src = ast_format_cap_get_format(src_cap, j);
1847 if (!src
1848 || ast_format_get_type(src) != AST_MEDIA_TYPE_AUDIO) {
1849 continue;
1850 }
1851
1852 x = format2index(src);
1853 y = format2index(dst);
1854 if (x < 0 || y < 0) {
1855 continue;
1856 }
1857 if (!matrix_get(x, y) || !(matrix_get(x, y)->step)) {
1858 continue;
1859 }
1860 if (matrix_get(x, y)->table_cost < besttablecost
1861 || matrix_get(x, y)->multistep < beststeps) {
1862 /* better than what we have so far */
1863 ao2_replace(best, src);
1864 ao2_replace(bestdst, dst);
1865 besttablecost = matrix_get(x, y)->table_cost;
1866 beststeps = matrix_get(x, y)->multistep;
1867 } else if (matrix_get(x, y)->table_cost == besttablecost
1868 && matrix_get(x, y)->multistep == beststeps) {
1869 int replace = 0;
1870 unsigned int gap_selected = format_sample_rate_absdiff(best, bestdst);
1871 unsigned int gap_current = format_sample_rate_absdiff(src, dst);
1872
1873 if (gap_current < gap_selected) {
1874 /* better than what we have so far */
1875 replace = 1;
1876 } else if (gap_current == gap_selected) {
1877 int src_quality, best_quality;
1878 struct ast_codec *src_codec, *best_codec;
1879
1880 src_codec = ast_format_get_codec(src);
1881 best_codec = ast_format_get_codec(best);
1882 src_quality = src_codec->quality;
1883 best_quality = best_codec->quality;
1884
1885 ao2_cleanup(src_codec);
1886 ao2_cleanup(best_codec);
1887
1888 /* We have a tie, so choose the format with the higher quality, if they differ. */
1889 if (src_quality > best_quality) {
1890 /* Better than what we had before. */
1891 replace = 1;
1892 ast_debug(2, "Tiebreaker: preferring format %s (%d) to %s (%d)\n", ast_format_get_name(src), src_quality,
1893 ast_format_get_name(best), best_quality);
1894 } else {
1895 /* This isn't necessarily indicative of a problem, but in reality this shouldn't really happen, unless
1896 * there are 2 formats that are basically the same. */
1897 ast_debug(1, "Completely ambiguous tie between formats %s and %s (quality %d): sticking with %s, but this is arbitrary\n",
1898 ast_format_get_name(src), ast_format_get_name(best), best_quality, ast_format_get_name(best));
1899 }
1900 }
1901 if (replace) {
1902 ao2_replace(best, src);
1903 ao2_replace(bestdst, dst);
1904 besttablecost = matrix_get(x, y)->table_cost;
1905 beststeps = matrix_get(x, y)->multistep;
1906 }
1907 }
1908 }
1909 }
1910 AST_RWLIST_UNLOCK(&translators);
1911
1912 if (!best) {
1913 return -1;
1914 }
1915 ao2_replace(*dst_fmt_out, bestdst);
1916 ao2_replace(*src_fmt_out, best);
1917 return 0;
1918 }
1919
1920 unsigned int ast_translate_path_steps(struct ast_format *dst_format, struct ast_format *src_format)
1921 {
1922 unsigned int res = -1;
1923 /* convert bitwise format numbers into array indices */
1924 int src = format2index(src_format);
1925 int dest = format2index(dst_format);
1926
1927 if (src < 0 || dest < 0) {
1928 ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", src < 0 ? "starting" : "ending");
1929 return -1;
1930 }
1931 AST_RWLIST_RDLOCK(&translators);
1932
1933 if (matrix_get(src, dest)->step) {
1934 res = matrix_get(src, dest)->multistep + 1;
1935 }
1936
1937 AST_RWLIST_UNLOCK(&translators);
1938
1939 return res;
1940 }
1941
1942 static void check_translation_path(
1943 struct ast_format_cap *dest, struct ast_format_cap *src,
1944 struct ast_format_cap *result, struct ast_format *src_fmt,
1945 enum ast_media_type type)
1946 {
1947 int i;
1948
1949 if (ast_format_get_type(src_fmt) != type) {
1950 return;
1951 }
1952
1953 /* For a given source format, traverse the list of
1954 known formats to determine whether there exists
1955 a translation path from the source format to the
1956 destination format. */
1957 for (i = ast_format_cap_count(result) - 1; 0 <= i; i--) {
1958 int index, src_index;
1959 RAII_VAR(struct ast_format *, fmt, ast_format_cap_get_format(result, i), ao2_cleanup);
1960
1961 if (ast_format_get_type(fmt) != type) {
1962 continue;
1963 }
1964
1965 /* if this is not a desired format, nothing to do */
1966 if (ast_format_cap_iscompatible_format(dest, fmt) == AST_FORMAT_CMP_NOT_EQUAL) {
1967 continue;
1968 }
1969
1970 /* if the source is supplying this format, then
1971 we can leave it in the result */
1972 if (ast_format_cap_iscompatible_format(src, fmt) == AST_FORMAT_CMP_EQUAL) {
1973 continue;
1974 }
1975
1976 /* if this is a pass-through format, not in the source,
1977 we cannot transcode. Therefore, remove it from the result */
1978 src_index = format2index(src_fmt);
1979 index = format2index(fmt);
1980 if (src_index < 0 || index < 0) {
1981 ast_format_cap_remove(result, fmt);
1982 continue;
1983 }
1984
1985 /* if we don't have a translation path from the src
1986 to this format, remove it from the result */
1987 if (!matrix_get(src_index, index)->step) {
1988 ast_format_cap_remove(result, fmt);
1989 continue;
1990 }
1991
1992 /* now check the opposite direction */
1993 if (!matrix_get(index, src_index)->step) {
1994 ast_format_cap_remove(result, fmt);
1995 }
1996 }
1997
1998 }
1999
2000 void ast_translate_available_formats(struct ast_format_cap *dest, struct ast_format_cap *src, struct ast_format_cap *result)
2001 {
2002 struct ast_format *cur_dest, *cur_src;
2003 int index;
2004
2005 for (index = 0; index < ast_format_cap_count(dest); ++index) {
2006 if (!(cur_dest = ast_format_cap_get_format(dest, index))) {
2007 continue;
2008 }
2009
2010 /* We give preference to a joint format structure if possible */
2011 if ((cur_src = ast_format_cap_get_compatible_format(src, cur_dest))) {
2012 ast_format_cap_append(result, cur_src, 0);
2013 ao2_ref(cur_src, -1);
2014 } else {
2015 /* Otherwise we just use the destination format */
2016 ast_format_cap_append(result, cur_dest, 0);
2017 }
2018 ao2_ref(cur_dest, -1);
2019 }
2020
2021 /* if we don't have a source format, we just have to try all
2022 possible destination formats */
2023 if (!src) {
2024 return;
2025 }
2026
2027 for (index = 0; index < ast_format_cap_count(src); ++index) {
2028 if (!(cur_src = ast_format_cap_get_format(src, index))) {
2029 continue;
2030 }
2031
2032 AST_RWLIST_RDLOCK(&translators);
2033 check_translation_path(dest, src, result,
2034 cur_src, AST_MEDIA_TYPE_AUDIO);
2035 check_translation_path(dest, src, result,
2036 cur_src, AST_MEDIA_TYPE_VIDEO);
2037 AST_RWLIST_UNLOCK(&translators);
2038 ao2_ref(cur_src, -1);
2039 }
2040 }
2041
2042 static void translate_shutdown(void)
2043 {
2044 int x;
2045 ast_cli_unregister_multiple(cli_translate, ARRAY_LEN(cli_translate));
2046
2047 ast_rwlock_wrlock(&tablelock);
2048 for (x = 0; x < index_size; x++) {
2049 ast_free(__matrix[x]);
2050 }
2051 ast_free(__matrix);
2052 __matrix = NULL;
2053 ast_free(__indextable);
2054 __indextable = NULL;
2055 ast_rwlock_unlock(&tablelock);
2056 ast_rwlock_destroy(&tablelock);
2057 }
2058
2059 int ast_translate_init(void)
2060 {
2061 int res = 0;
2062 ast_rwlock_init(&tablelock);
2063 res = matrix_resize(1);
2064 res |= ast_cli_register_multiple(cli_translate, ARRAY_LEN(cli_translate));
2065 ast_register_cleanup(translate_shutdown);
2066 return res;
2067 }