Merged revisions 305131 via svnmerge from
[asterisk/asterisk.git] / codecs / codec_dahdi.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * DAHDI native transcoding support
5  *
6  * Copyright (C) 1999 - 2008, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  * Kevin P. Fleming <kpfleming@digium.com>
10  *
11  * See http://www.asterisk.org for more information about
12  * the Asterisk project. Please do not directly contact
13  * any of the maintainers of this project for assistance;
14  * the project provides a web site, mailing lists and IRC
15  * channels for your use.
16  *
17  * This program is free software, distributed under the terms of
18  * the GNU General Public License Version 2. See the LICENSE file
19  * at the top of the source tree.
20  */
21
22 /*! \file
23  *
24  * \brief Translate between various formats natively through DAHDI transcoding
25  *
26  * \ingroup codecs
27  */
28
29 /*** MODULEINFO
30         <depend>dahdi</depend>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <fcntl.h>
38 #include <netinet/in.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/poll.h>
42 #include <dahdi/user.h>
43
44 #include "asterisk/lock.h"
45 #include "asterisk/translate.h"
46 #include "asterisk/config.h"
47 #include "asterisk/module.h"
48 #include "asterisk/cli.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/utils.h"
51 #include "asterisk/linkedlists.h"
52 #include "asterisk/ulaw.h"
53
54 #define BUFFER_SIZE 8000
55
56 #define G723_SAMPLES 240
57 #define G729_SAMPLES 160
58
59 static struct channel_usage {
60         int total;
61         int encoders;
62         int decoders;
63 } channels;
64
65 static char *handle_cli_transcoder_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
66
67 static struct ast_cli_entry cli[] = {
68         AST_CLI_DEFINE(handle_cli_transcoder_show, "Display DAHDI transcoder utilization.")
69 };
70
71 struct format_map {
72         unsigned int map[32][32];
73 };
74
75 static struct format_map global_format_map = { { { 0 } } };
76
77 struct translator {
78         struct ast_translator t;
79         AST_LIST_ENTRY(translator) entry;
80 };
81
82 static AST_LIST_HEAD_STATIC(translators, translator);
83
84 struct codec_dahdi_pvt {
85         int fd;
86         struct dahdi_transcoder_formats fmts;
87         unsigned int softslin:1;
88         unsigned int fake:2;
89         uint16_t required_samples;
90         uint16_t samples_in_buffer;
91         uint8_t ulaw_buffer[1024];
92 };
93
94 /* Only used by a decoder */
95 static int ulawtolin(struct ast_trans_pvt *pvt, int samples)
96 {
97         struct codec_dahdi_pvt *dahdip = pvt->pvt;
98         int i = samples;
99         uint8_t *src = &dahdip->ulaw_buffer[0];
100         int16_t *dst = pvt->outbuf.i16 + pvt->datalen;
101
102         /* convert and copy in outbuf */
103         while (i--) {
104                 *dst++ = AST_MULAW(*src++);
105         }
106
107         return 0;
108 }
109
110 /* Only used by an encoder. */
111 static int lintoulaw(struct ast_trans_pvt *pvt, struct ast_frame *f)
112 {
113         struct codec_dahdi_pvt *dahdip = pvt->pvt;
114         int i = f->samples;
115         uint8_t *dst = &dahdip->ulaw_buffer[dahdip->samples_in_buffer];
116         int16_t *src = f->data.ptr;
117
118         if (dahdip->samples_in_buffer + i > sizeof(dahdip->ulaw_buffer)) {
119                 ast_log(LOG_ERROR, "Out of buffer space!\n");
120                 return -i;
121         }
122
123         while (i--) {
124                 *dst++ = AST_LIN2MU(*src++);
125         }
126
127         dahdip->samples_in_buffer += f->samples;
128         return 0;
129 }
130
131 static char *handle_cli_transcoder_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
132 {
133         struct channel_usage copy;
134
135         switch (cmd) {
136         case CLI_INIT:
137                 e->command = "transcoder show";
138                 e->usage =
139                         "Usage: transcoder show\n"
140                         "       Displays channel utilization of DAHDI transcoder(s).\n";
141                 return NULL;
142         case CLI_GENERATE:
143                 return NULL;
144         }
145
146         if (a->argc != 2)
147                 return CLI_SHOWUSAGE;
148
149         copy = channels;
150
151         if (copy.total == 0)
152                 ast_cli(a->fd, "No DAHDI transcoders found.\n");
153         else
154                 ast_cli(a->fd, "%d/%d encoders/decoders of %d channels are in use.\n", copy.encoders, copy.decoders, copy.total);
155
156         return CLI_SUCCESS;
157 }
158
159 static void dahdi_write_frame(struct codec_dahdi_pvt *dahdip, const uint8_t *buffer, const ssize_t count)
160 {
161         int res;
162         struct pollfd p = {0};
163         if (!count) return;
164         res = write(dahdip->fd, buffer, count);
165         if (option_verbose > 10) {
166                 if (-1 == res) {
167                         ast_log(LOG_ERROR, "Failed to write to transcoder: %s\n", strerror(errno));
168                 }
169                 if (count != res) {
170                         ast_log(LOG_ERROR, "Requested write of %zd bytes, but only wrote %d bytes.\n", count, res);
171                 }
172         }
173         p.fd = dahdip->fd;
174         p.events = POLLOUT;
175         res = poll(&p, 1, 50);
176 }
177
178 static int dahdi_encoder_framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
179 {
180         struct codec_dahdi_pvt *dahdip = pvt->pvt;
181
182         if (!f->subclass.codec) {
183                 /* We're just faking a return for calculation purposes. */
184                 dahdip->fake = 2;
185                 pvt->samples = f->samples;
186                 return 0;
187         }
188
189         /* Buffer up the packets and send them to the hardware if we
190          * have enough samples set up. */
191         if (dahdip->softslin) {
192                 if (lintoulaw(pvt, f)) {
193                          return -1;
194                 }
195         } else {
196                 /* NOTE:  If softslin support is not needed, and the sample
197                  * size is equal to the required sample size, we wouldn't
198                  * need this copy operation.  But at the time this was
199                  * written, only softslin is supported. */
200                 if (dahdip->samples_in_buffer + f->samples > sizeof(dahdip->ulaw_buffer)) {
201                         ast_log(LOG_ERROR, "Out of buffer space.\n");
202                         return -1;
203                 }
204                 memcpy(&dahdip->ulaw_buffer[dahdip->samples_in_buffer], f->data.ptr, f->samples);
205                 dahdip->samples_in_buffer += f->samples;
206         }
207
208         while (dahdip->samples_in_buffer > dahdip->required_samples) {
209                 dahdi_write_frame(dahdip, dahdip->ulaw_buffer, dahdip->required_samples);
210                 dahdip->samples_in_buffer -= dahdip->required_samples;
211                 if (dahdip->samples_in_buffer) {
212                         /* Shift any remaining bytes down. */
213                         memmove(dahdip->ulaw_buffer, &dahdip->ulaw_buffer[dahdip->required_samples],
214                                 dahdip->samples_in_buffer);
215                 }
216         }
217         pvt->samples += f->samples;
218         pvt->datalen = 0;
219         return -1;
220 }
221
222 static struct ast_frame *dahdi_encoder_frameout(struct ast_trans_pvt *pvt)
223 {
224         struct codec_dahdi_pvt *dahdip = pvt->pvt;
225         int res;
226
227         if (2 == dahdip->fake) {
228                 dahdip->fake = 1;
229                 pvt->f.frametype = AST_FRAME_VOICE;
230                 pvt->f.subclass.codec = 0;
231                 pvt->f.samples = dahdip->required_samples;
232                 pvt->f.data.ptr = NULL;
233                 pvt->f.offset = 0;
234                 pvt->f.datalen = 0;
235                 pvt->f.mallocd = 0;
236                 pvt->samples = 0;
237
238                 return ast_frisolate(&pvt->f);
239
240         } else if (1 == dahdip->fake) {
241                 dahdip->fake = 0;
242                 return NULL;
243         }
244
245         res = read(dahdip->fd, pvt->outbuf.c + pvt->datalen, pvt->t->buf_size - pvt->datalen);
246         if (-1 == res) {
247                 if (EWOULDBLOCK == errno) {
248                         /* Nothing waiting... */
249                         return NULL;
250                 } else {
251                         ast_log(LOG_ERROR, "Failed to read from transcoder: %s\n", strerror(errno));
252                         return NULL;
253                 }
254         } else {
255                 pvt->f.datalen = res;
256                 pvt->f.samples = dahdip->required_samples;
257                 pvt->f.frametype = AST_FRAME_VOICE;
258                 pvt->f.subclass.codec = 1 <<  (pvt->t->dstfmt);
259                 pvt->f.mallocd = 0;
260                 pvt->f.offset = AST_FRIENDLY_OFFSET;
261                 pvt->f.src = pvt->t->name;
262                 pvt->f.data.ptr = pvt->outbuf.c;
263
264                 pvt->samples = 0;
265                 pvt->datalen = 0;
266                 return ast_frisolate(&pvt->f);
267         }
268
269         /* Shouldn't get here... */
270         return NULL;
271 }
272
273 static int dahdi_decoder_framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
274 {
275         struct codec_dahdi_pvt *dahdip = pvt->pvt;
276
277         if (!f->subclass.codec) {
278                 /* We're just faking a return for calculation purposes. */
279                 dahdip->fake = 2;
280                 pvt->samples = f->samples;
281                 return 0;
282         }
283
284         if (!f->datalen) {
285                 if (f->samples != dahdip->required_samples) {
286                         ast_log(LOG_ERROR, "%d != %d %d\n", f->samples, dahdip->required_samples, f->datalen);
287                 }
288         }
289         dahdi_write_frame(dahdip, f->data.ptr, f->datalen);
290         pvt->samples += f->samples;
291         pvt->datalen = 0;
292         return -1;
293 }
294
295 static struct ast_frame *dahdi_decoder_frameout(struct ast_trans_pvt *pvt)
296 {
297         int res;
298         struct codec_dahdi_pvt *dahdip = pvt->pvt;
299
300         if (2 == dahdip->fake) {
301                 dahdip->fake = 1;
302                 pvt->f.frametype = AST_FRAME_VOICE;
303                 pvt->f.subclass.codec = 0;
304                 pvt->f.samples = dahdip->required_samples;
305                 pvt->f.data.ptr = NULL;
306                 pvt->f.offset = 0;
307                 pvt->f.datalen = 0;
308                 pvt->f.mallocd = 0;
309                 pvt->samples = 0;
310                 return ast_frisolate(&pvt->f);
311         } else if (1 == dahdip->fake) {
312                 pvt->samples = 0;
313                 dahdip->fake = 0;
314                 return NULL;
315         }
316
317         /* Let's check to see if there is a new frame for us.... */
318         if (dahdip->softslin) {
319                 res = read(dahdip->fd, dahdip->ulaw_buffer, sizeof(dahdip->ulaw_buffer));
320         } else {
321                 res = read(dahdip->fd, pvt->outbuf.c + pvt->datalen, pvt->t->buf_size - pvt->datalen);
322         }
323
324         if (-1 == res) {
325                 if (EWOULDBLOCK == errno) {
326                         /* Nothing waiting... */
327                         return NULL;
328                 } else {
329                         ast_log(LOG_ERROR, "Failed to read from transcoder: %s\n", strerror(errno));
330                         return NULL;
331                 }
332         } else {
333                 if (dahdip->softslin) {
334                         ulawtolin(pvt, res);
335                         pvt->f.datalen = res * 2;
336                 } else {
337                         pvt->f.datalen = res;
338                 }
339                 pvt->datalen = 0;
340                 pvt->f.frametype = AST_FRAME_VOICE;
341                 pvt->f.subclass.codec = 1 <<  (pvt->t->dstfmt);
342                 pvt->f.mallocd = 0;
343                 pvt->f.offset = AST_FRIENDLY_OFFSET;
344                 pvt->f.src = pvt->t->name;
345                 pvt->f.data.ptr = pvt->outbuf.c;
346                 pvt->f.samples = res;
347                 pvt->samples = 0;
348
349                 return ast_frisolate(&pvt->f);
350         }
351
352         /* Shouldn't get here... */
353         return NULL;
354 }
355
356
357 static void dahdi_destroy(struct ast_trans_pvt *pvt)
358 {
359         struct codec_dahdi_pvt *dahdip = pvt->pvt;
360
361         switch (dahdip->fmts.dstfmt) {
362         case AST_FORMAT_G729A:
363         case AST_FORMAT_G723_1:
364                 ast_atomic_fetchadd_int(&channels.encoders, -1);
365                 break;
366         default:
367                 ast_atomic_fetchadd_int(&channels.decoders, -1);
368                 break;
369         }
370
371         close(dahdip->fd);
372 }
373
374 static int dahdi_translate(struct ast_trans_pvt *pvt, int dest, int source)
375 {
376         /* Request translation through zap if possible */
377         int fd;
378         struct codec_dahdi_pvt *dahdip = pvt->pvt;
379         int flags;
380         int tried_once = 0;
381         const char *dev_filename = "/dev/dahdi/transcode";
382
383         if ((fd = open(dev_filename, O_RDWR)) < 0) {
384                 ast_log(LOG_ERROR, "Failed to open %s: %s\n", dev_filename, strerror(errno));
385                 return -1;
386         }
387
388         dahdip->fmts.srcfmt = (1 << source);
389         dahdip->fmts.dstfmt = (1 << dest);
390
391         ast_debug(1, "Opening transcoder channel from %d to %d.\n", source, dest);
392
393 retry:
394         if (ioctl(fd, DAHDI_TC_ALLOCATE, &dahdip->fmts)) {
395                 if ((ENODEV == errno) && !tried_once) {
396                         /* We requested to translate to/from an unsupported
397                          * format.  Most likely this is because signed linear
398                          * was not supported by any hardware devices even
399                          * though this module always registers signed linear
400                          * support. In this case we'll retry, requesting
401                          * support for ULAW instead of signed linear and then
402                          * we'll just convert from ulaw to signed linear in
403                          * software. */
404                         if (AST_FORMAT_SLINEAR == dahdip->fmts.srcfmt) {
405                                 ast_debug(1, "Using soft_slin support on source\n");
406                                 dahdip->softslin = 1;
407                                 dahdip->fmts.srcfmt = AST_FORMAT_ULAW;
408                         } else if (AST_FORMAT_SLINEAR == dahdip->fmts.dstfmt) {
409                                 ast_debug(1, "Using soft_slin support on destination\n");
410                                 dahdip->softslin = 1;
411                                 dahdip->fmts.dstfmt = AST_FORMAT_ULAW;
412                         }
413                         tried_once = 1;
414                         goto retry;
415                 }
416                 ast_log(LOG_ERROR, "Unable to attach to transcoder: %s\n", strerror(errno));
417                 close(fd);
418
419                 return -1;
420         }
421
422         flags = fcntl(fd, F_GETFL);
423         if (flags > - 1) {
424                 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
425                         ast_log(LOG_WARNING, "Could not set non-block mode!\n");
426         }
427
428         dahdip->fd = fd;
429
430         dahdip->required_samples = ((dahdip->fmts.dstfmt|dahdip->fmts.srcfmt)&AST_FORMAT_G723_1) ? G723_SAMPLES : G729_SAMPLES;
431
432         switch (dahdip->fmts.dstfmt) {
433         case AST_FORMAT_G729A:
434                 ast_atomic_fetchadd_int(&channels.encoders, +1);
435                 break;
436         case AST_FORMAT_G723_1:
437                 ast_atomic_fetchadd_int(&channels.encoders, +1);
438                 break;
439         default:
440                 ast_atomic_fetchadd_int(&channels.decoders, +1);
441                 break;
442         }
443
444         return 0;
445 }
446
447 static int dahdi_new(struct ast_trans_pvt *pvt)
448 {
449         return dahdi_translate(pvt, pvt->t->dstfmt, pvt->t->srcfmt);
450 }
451
452 static struct ast_frame *fakesrc_sample(void)
453 {
454         /* Don't bother really trying to test hardware ones. */
455         static struct ast_frame f = {
456                 .frametype = AST_FRAME_VOICE,
457                 .samples = 160,
458                 .src = __PRETTY_FUNCTION__
459         };
460
461         return &f;
462 }
463
464 static int is_encoder(struct translator *zt)
465 {
466         if (zt->t.srcfmt&(AST_FORMAT_ULAW|AST_FORMAT_ALAW|AST_FORMAT_SLINEAR)) {
467                 return 1;
468         } else {
469                 return 0;
470         }
471 }
472
473 static int register_translator(int dst, int src)
474 {
475         struct translator *zt;
476         int res;
477
478         if (!(zt = ast_calloc(1, sizeof(*zt)))) {
479                 return -1;
480         }
481
482         snprintf((char *) (zt->t.name), sizeof(zt->t.name), "zap%sto%s",
483                  ast_getformatname((1 << src)), ast_getformatname((1 << dst)));
484         zt->t.srcfmt = (1 << src);
485         zt->t.dstfmt = (1 << dst);
486         zt->t.buf_size = BUFFER_SIZE;
487         if (is_encoder(zt)) {
488                 zt->t.framein = dahdi_encoder_framein;
489                 zt->t.frameout = dahdi_encoder_frameout;
490         } else {
491                 zt->t.framein = dahdi_decoder_framein;
492                 zt->t.frameout = dahdi_decoder_frameout;
493         }
494         zt->t.destroy = dahdi_destroy;
495         zt->t.buffer_samples = 0;
496         zt->t.newpvt = dahdi_new;
497         zt->t.sample = fakesrc_sample;
498         zt->t.native_plc = 0;
499
500         zt->t.desc_size = sizeof(struct codec_dahdi_pvt);
501         if ((res = ast_register_translator(&zt->t))) {
502                 ast_free(zt);
503                 return -1;
504         }
505
506         AST_LIST_LOCK(&translators);
507         AST_LIST_INSERT_HEAD(&translators, zt, entry);
508         AST_LIST_UNLOCK(&translators);
509
510         global_format_map.map[dst][src] = 1;
511
512         return res;
513 }
514
515 static void drop_translator(int dst, int src)
516 {
517         struct translator *cur;
518
519         AST_LIST_LOCK(&translators);
520         AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, cur, entry) {
521                 if (cur->t.srcfmt != src)
522                         continue;
523
524                 if (cur->t.dstfmt != dst)
525                         continue;
526
527                 AST_LIST_REMOVE_CURRENT(entry);
528                 ast_unregister_translator(&cur->t);
529                 ast_free(cur);
530                 global_format_map.map[dst][src] = 0;
531                 break;
532         }
533         AST_LIST_TRAVERSE_SAFE_END;
534         AST_LIST_UNLOCK(&translators);
535 }
536
537 static void unregister_translators(void)
538 {
539         struct translator *cur;
540
541         AST_LIST_LOCK(&translators);
542         while ((cur = AST_LIST_REMOVE_HEAD(&translators, entry))) {
543                 ast_unregister_translator(&cur->t);
544                 ast_free(cur);
545         }
546         AST_LIST_UNLOCK(&translators);
547 }
548
549 static void build_translators(struct format_map *map, unsigned int dstfmts, unsigned int srcfmts)
550 {
551         unsigned int src, dst;
552
553         for (src = 0; src < 32; src++) {
554                 for (dst = 0; dst < 32; dst++) {
555                         if (!(srcfmts & (1 << src)))
556                                 continue;
557
558                         if (!(dstfmts & (1 << dst)))
559                                 continue;
560
561                         if (global_format_map.map[dst][src])
562                                 continue;
563
564                         if (!register_translator(dst, src))
565                                 map->map[dst][src] = 1;
566                 }
567         }
568 }
569
570 static int find_transcoders(void)
571 {
572         struct dahdi_transcoder_info info = { 0, };
573         struct format_map map = { { { 0 } } };
574         int fd, res;
575         unsigned int x, y;
576
577         if ((fd = open("/dev/dahdi/transcode", O_RDWR)) < 0) {
578                 ast_log(LOG_ERROR, "Failed to open /dev/dahdi/transcode: %s\n", strerror(errno));
579                 return 0;
580         }
581
582         for (info.tcnum = 0; !(res = ioctl(fd, DAHDI_TC_GETINFO, &info)); info.tcnum++) {
583                 if (option_verbose > 1)
584                         ast_verbose(VERBOSE_PREFIX_2 "Found transcoder '%s'.\n", info.name);
585
586                 /* Complex codecs need to support signed linear.  If the
587                  * hardware transcoder does not natively support signed linear
588                  * format, we will emulate it in software directly in this
589                  * module. Also, do not allow direct ulaw/alaw to complex
590                  * codec translation, since that will prevent the generic PLC
591                  * functions from working. */
592                 if (info.dstfmts & (AST_FORMAT_ULAW | AST_FORMAT_ALAW)) {
593                         info.dstfmts |= AST_FORMAT_SLINEAR;
594                         info.dstfmts &= ~(AST_FORMAT_ULAW | AST_FORMAT_ALAW);
595                 }
596                 if (info.srcfmts & (AST_FORMAT_ULAW | AST_FORMAT_ALAW)) {
597                         info.srcfmts |= AST_FORMAT_SLINEAR;
598                         info.srcfmts &= ~(AST_FORMAT_ULAW | AST_FORMAT_ALAW);
599                 }
600
601                 build_translators(&map, info.dstfmts, info.srcfmts);
602                 ast_atomic_fetchadd_int(&channels.total, info.numchannels / 2);
603
604         }
605
606         close(fd);
607
608         if (!info.tcnum && (option_verbose > 1))
609                 ast_verbose(VERBOSE_PREFIX_2 "No hardware transcoders found.\n");
610
611         for (x = 0; x < 32; x++) {
612                 for (y = 0; y < 32; y++) {
613                         if (!map.map[x][y] && global_format_map.map[x][y])
614                                 drop_translator(x, y);
615                 }
616         }
617
618         return 0;
619 }
620
621 static int reload(void)
622 {
623         return AST_MODULE_LOAD_SUCCESS;
624 }
625
626 static int unload_module(void)
627 {
628         ast_cli_unregister_multiple(cli, ARRAY_LEN(cli));
629         unregister_translators();
630
631         return 0;
632 }
633
634 static int load_module(void)
635 {
636         ast_ulaw_init();
637         find_transcoders();
638         ast_cli_register_multiple(cli, ARRAY_LEN(cli));
639         return AST_MODULE_LOAD_SUCCESS;
640 }
641
642 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Generic DAHDI Transcoder Codec Translator",
643                 .load = load_module,
644                 .unload = unload_module,
645                 .reload = reload,
646                );