Merged revisions 49705 via svnmerge from
[asterisk/asterisk.git] / codecs / codec_zap.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Zaptel native transcoding support
5  *
6  * Copyright (C) 1999 - 2006, 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 Zaptel transcoding
25  *
26  * \ingroup codecs
27  */
28
29 /*** MODULEINFO
30         <depend>zaptel_transcode</depend>
31         <depend>zaptel</depend>
32  ***/
33
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include <fcntl.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <netinet/in.h>
42 #include <string.h>
43 #include <stdio.h>
44 #include <sys/ioctl.h>
45 #include <errno.h>
46 #include <sys/mman.h>
47 #include <zaptel/zaptel.h>
48
49 #include "asterisk/lock.h"
50 #include "asterisk/translate.h"
51 #include "asterisk/config.h"
52 #include "asterisk/options.h"
53 #include "asterisk/module.h"
54 #include "asterisk/cli.h"
55 #include "asterisk/logger.h"
56 #include "asterisk/channel.h"
57 #include "asterisk/utils.h"
58 #include "asterisk/linkedlists.h"
59
60 #define BUFFER_SAMPLES  8000
61
62 static unsigned int global_useplc = 0;
63 static int cardsmode = 0;
64
65 static int totalchannels = 0;
66 static int complexinuse = 0;
67 static int simpleinuse = 0;
68 AST_MUTEX_DEFINE_STATIC(channelcount);
69
70
71 static const char show_transcoder_usage[] =
72 "Usage: show transcoder\n"
73 "       Displays transcoder utilization.\n";
74
75 static int show_transcoder(int fd, int argc, char *argv[]);
76
77 static struct ast_cli_entry transcoder_cli[] = {
78         { { "show", "transcoder", NULL},
79         show_transcoder, "Displays transcoder utilization.",
80         show_transcoder_usage }
81 };
82
83 struct format_map {
84         unsigned int map[32][32];
85 };
86
87 static struct format_map global_format_map = { { { 0 } } };
88
89 struct translator {
90         struct ast_translator t;
91         AST_LIST_ENTRY(translator) entry;
92 };
93
94 static AST_LIST_HEAD_STATIC(zap_translators, translator);
95
96 struct pvt {
97         int fd;
98         int fake;
99         int inuse;
100 #ifdef DEBUG_TRANSCODE
101         int totalms;
102         int lasttotalms;
103 #endif
104         struct zt_transcode_header *hdr;
105         struct ast_frame f;
106 };
107
108 static void activate_translator(int simple);
109 static void deactivate_translator(int simple);
110
111
112 static int show_transcoder(int fd, int argc, char *argv[])
113 {
114         ast_mutex_lock(&channelcount);
115         if (!totalchannels) { 
116                 ast_verbose("No transcoder card registered\n");
117                 ast_mutex_unlock(&channelcount);
118                 return RESULT_SUCCESS;
119         }
120         if(!cardsmode)             
121                 ast_verbose("%d/%d encoders/decoders of %d channels (G.729a / G.723.1 5.3 kbps) are in use.\n",complexinuse, simpleinuse, totalchannels);
122         else if (cardsmode == 1)
123                 ast_verbose("%d/%d encoders/decoders of %d channels (G.729a) are in use.\n",complexinuse, simpleinuse, totalchannels);
124         else if (cardsmode == 2)
125                 ast_verbose("%d/%d encoders/decoders of %d channels (G.723.1 5.3 kbps) are in use.\n",complexinuse, simpleinuse, totalchannels);
126
127         ast_mutex_unlock(&channelcount);
128         return RESULT_SUCCESS;
129 }
130
131 static int zap_framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
132 {
133         struct pvt *ztp = pvt->pvt;
134         struct zt_transcode_header *hdr = ztp->hdr;
135
136         if (!f->subclass) {
137                 /* Fake a return frame for calculation purposes */
138                 ztp->fake = 2;
139                 pvt->samples = f->samples;
140                 return 0;
141         }
142         if(!ztp->inuse) {
143                 ast_mutex_lock(&channelcount);
144                 if(pvt->t->dstfmt == 8 || pvt->t->dstfmt == 0 ) {
145                         complexinuse++;
146                         if(complexinuse == totalchannels)
147                                 deactivate_translator(0);
148                 } else {
149                         simpleinuse++;
150                         if(simpleinuse == totalchannels)
151                                 deactivate_translator(1);
152                 }
153                 ast_mutex_unlock(&channelcount);
154                 ztp->inuse = 1;
155         }
156         if (!hdr->srclen)
157                 /* Copy at front of buffer */
158                 hdr->srcoffset = 0;
159
160         if (hdr->srclen + f->datalen > sizeof(hdr->srcdata)) {
161                 ast_log(LOG_WARNING, "Out of space for codec translation!\n");
162                 return -1;
163         }
164
165         if (hdr->srclen + f->datalen + hdr->srcoffset > sizeof(hdr->srcdata)) {
166                 /* Very unlikely */
167                 memmove(hdr->srcdata, hdr->srcdata + hdr->srcoffset, hdr->srclen);
168                 hdr->srcoffset = 0;
169         }
170
171         memcpy(hdr->srcdata + hdr->srcoffset + hdr->srclen, f->data, f->datalen);
172         hdr->srclen += f->datalen;
173         pvt->samples += f->samples;
174
175         return -1;
176 }
177
178 static struct ast_frame *zap_frameout(struct ast_trans_pvt *pvt)
179 {
180         struct pvt *ztp = pvt->pvt;
181         struct zt_transcode_header *hdr = ztp->hdr;
182         unsigned int x;
183
184         if (ztp->fake == 2) {
185                 ztp->fake = 1;
186                 ztp->f.frametype = AST_FRAME_VOICE;
187                 ztp->f.subclass = 0;
188                 ztp->f.samples = 240;
189                 ztp->f.data = NULL;
190                 ztp->f.offset = 0;
191                 ztp->f.datalen = 0;
192                 ztp->f.mallocd = 0;
193                 pvt->samples = 0;
194         } else if (ztp->fake == 1) {
195                 return NULL;
196         } else {
197                 if (hdr->dstlen) {
198 #ifdef DEBUG_TRANSCODE
199                         ztp->totalms += hdr->dstsamples;
200                         if ((ztp->totalms - ztp->lasttotalms) > 8000) {
201                                 ast_verbose("Whee %p, %d (%d to %d)\n", ztp, hdr->dstlen, ztp->lasttotalms, ztp->totalms);
202                                 ztp->lasttotalms = ztp->totalms;
203                         }
204 #endif
205                         ztp->f.frametype = AST_FRAME_VOICE;
206                         ztp->f.subclass = hdr->dstfmt;
207                         ztp->f.samples = hdr->dstsamples;
208                         ztp->f.data = hdr->dstdata + hdr->dstoffset;
209                         ztp->f.offset = hdr->dstoffset;
210                         ztp->f.datalen = hdr->dstlen;
211                         ztp->f.mallocd = 0;
212                         pvt->samples -= ztp->f.samples;
213                         hdr->dstlen = 0;
214                         
215                 } else {
216                         if (hdr->srclen) {
217                                 hdr->dstoffset = AST_FRIENDLY_OFFSET;
218                                 x = ZT_TCOP_TRANSCODE;
219                                 if (ioctl(ztp->fd, ZT_TRANSCODE_OP, &x))
220                                         ast_log(LOG_WARNING, "Failed to transcode: %s\n", strerror(errno));
221                         }
222                         return NULL;
223                 }
224         }
225
226         return &ztp->f;
227 }
228
229 static void zap_destroy(struct ast_trans_pvt *pvt)
230 {
231         struct pvt *ztp = pvt->pvt;
232         unsigned int x;
233
234         x = ZT_TCOP_RELEASE;
235         if (ioctl(ztp->fd, ZT_TRANSCODE_OP, &x))
236                 ast_log(LOG_WARNING, "Failed to release transcoder channel: %s\n", strerror(errno));
237                                 
238         munmap(ztp->hdr, sizeof(*ztp->hdr));
239         if(ztp->inuse) {
240                 ast_mutex_lock(&channelcount);
241                 if(pvt->t->dstfmt == 8 || pvt->t->dstfmt == 0) {
242                         if(complexinuse == totalchannels)
243                                 activate_translator(0);
244                         complexinuse--;
245                 } else {
246                         if(simpleinuse == totalchannels)
247                                 activate_translator(1);
248                         simpleinuse--;
249                 }
250                 ast_mutex_unlock(&channelcount);
251         }
252         close(ztp->fd);
253 }
254
255 static int zap_translate(struct ast_trans_pvt *pvt, int dest, int source)
256 {
257         /* Request translation through zap if possible */
258         int fd;
259         unsigned int x = ZT_TCOP_RESET;
260         struct pvt *ztp = pvt->pvt;
261         struct zt_transcode_header *hdr;
262         int flags;
263         
264         if ((fd = open("/dev/zap/transcode", O_RDWR)) < 0)
265                 return -1;
266         flags = fcntl(fd, F_GETFL);
267         if (flags > - 1) {
268                 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
269                         ast_log(LOG_WARNING, "Could not set non-block mode!\n");
270         }
271         
272
273         if ((hdr = mmap(NULL, sizeof(*hdr), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) {
274                 ast_log(LOG_ERROR, "Memory Map failed for transcoding (%s)\n", strerror(errno));
275                 close(fd);
276
277                 return -1;
278         }
279
280         if (hdr->magic != ZT_TRANSCODE_MAGIC) {
281                 ast_log(LOG_ERROR, "Transcoder header (%08x) wasn't magic.  Abandoning\n", hdr->magic);
282                 munmap(hdr, sizeof(*hdr));
283                 close(fd);
284
285                 return -1;
286         }
287         
288         hdr->srcfmt = (1 << source);
289         hdr->dstfmt = (1 << dest);
290         if (ioctl(fd, ZT_TRANSCODE_OP, &x)) {
291                 ast_log(LOG_ERROR, "Unable to attach transcoder: %s\n", strerror(errno));
292                 munmap(hdr, sizeof(*hdr));
293                 close(fd);
294
295                 return -1;
296         }
297
298         ztp = pvt->pvt;
299         ztp->fd = fd;
300         ztp->hdr = hdr;
301
302         return 0;
303 }
304
305 static int zap_new(struct ast_trans_pvt *pvt)
306 {
307         return zap_translate(pvt, pvt->t->dstfmt, pvt->t->srcfmt);
308 }
309
310 static struct ast_frame *fakesrc_sample(void)
311 {
312         /* Don't bother really trying to test hardware ones. */
313         static struct ast_frame f = {
314                 .frametype = AST_FRAME_VOICE,
315                 .samples = 240,
316                 .src = __PRETTY_FUNCTION__
317         };
318
319         return &f;
320 }
321
322 static int register_translator(int dst, int src)
323 {
324         struct translator *zt;
325         int res;
326
327         if (!(zt = ast_calloc(1, sizeof(*zt))))
328                 return -1;
329         if (!((cardsmode  == 1 && (dst == 8 || src == 8)) || (cardsmode == 2 && (dst == 0 || src == 0)) || (cardsmode == 0)))
330                 return -1;
331         snprintf((char *) (zt->t.name), sizeof(zt->t.name), "zap%sto%s", 
332                  ast_getformatname((1 << src)), ast_getformatname((1 << dst)));
333         zt->t.srcfmt = (1 << src);
334         zt->t.dstfmt = (1 << dst);
335         zt->t.newpvt = zap_new;
336         zt->t.framein = zap_framein;
337         zt->t.frameout = zap_frameout;
338         zt->t.destroy = zap_destroy;
339         zt->t.sample = fakesrc_sample;
340         zt->t.useplc = global_useplc;
341         zt->t.buf_size = BUFFER_SAMPLES * 2;
342         zt->t.desc_size = sizeof(struct pvt);
343         if ((res = ast_register_translator(&zt->t))) {
344                 free(zt);
345                 return -1;
346         }
347
348         AST_LIST_LOCK(&zap_translators);
349         AST_LIST_INSERT_HEAD(&zap_translators, zt, entry);
350         AST_LIST_UNLOCK(&zap_translators);
351
352         global_format_map.map[dst][src] = 1;
353
354         return res;
355 }
356
357 static void drop_translator(int dst, int src)
358 {
359         struct translator *cur;
360
361         AST_LIST_LOCK(&zap_translators);
362         AST_LIST_TRAVERSE_SAFE_BEGIN(&zap_translators, cur, entry) {
363                 if (cur->t.srcfmt != src)
364                         continue;
365
366                 if (cur->t.dstfmt != dst)
367                         continue;
368
369                 AST_LIST_REMOVE_CURRENT(&zap_translators, entry);
370                 ast_unregister_translator(&cur->t);
371                 free(cur);
372                 global_format_map.map[dst][src] = 0;
373                 break;
374         }
375         AST_LIST_TRAVERSE_SAFE_END;
376         AST_LIST_UNLOCK(&zap_translators);
377 }
378
379 static void unregister_translators(void)
380 {
381         struct translator *cur;
382
383         AST_LIST_LOCK(&zap_translators);
384         while ((cur = AST_LIST_REMOVE_HEAD(&zap_translators, entry))) {
385                 ast_unregister_translator(&cur->t);
386                 free(cur);
387         }
388         AST_LIST_UNLOCK(&zap_translators);
389 }
390
391
392 static void activate_translator(int simple)
393 {
394         struct translator *cur;
395
396         AST_LIST_LOCK(&zap_translators);
397         AST_LIST_TRAVERSE_SAFE_BEGIN(&zap_translators, cur, entry) {
398                 if(!simple) {
399                         if (cur->t.dstfmt == 0 || cur->t.dstfmt == 8) {
400                                 ast_translator_activate(&cur->t);
401                         }
402                 } else {
403                         if(cur->t.dstfmt == 2 || cur->t.dstfmt == 3) {
404                                 ast_translator_activate(&cur->t);
405                         }
406                 }
407         }
408         AST_LIST_TRAVERSE_SAFE_END;
409         AST_LIST_UNLOCK(&zap_translators);
410 }
411
412
413 static void deactivate_translator(int simple)
414 {
415         struct translator *cur;
416
417         AST_LIST_LOCK(&zap_translators);
418         AST_LIST_TRAVERSE_SAFE_BEGIN(&zap_translators, cur, entry) {
419                 if(!simple) {
420                         if (cur->t.dstfmt == 0 || cur->t.dstfmt == 8) {
421                                 ast_translator_deactivate(&cur->t);
422                         }
423                 } else {
424                         if(cur->t.dstfmt == 2 || cur->t.dstfmt == 3) {
425                                 ast_translator_deactivate(&cur->t);
426                         }
427                 }
428         }
429         AST_LIST_TRAVERSE_SAFE_END;
430         AST_LIST_UNLOCK(&zap_translators);
431 }
432
433 static void parse_config(void)
434 {
435         struct ast_variable *var;
436         struct ast_config *cfg = ast_config_load("codecs.conf");
437         cardsmode = 0;
438
439         if (!cfg)
440                 return;
441
442         for (var = ast_variable_browse(cfg, "plc"); var; var = var->next) {
443                if (!strcasecmp(var->name, "genericplc")) {
444                        global_useplc = ast_true(var->value);
445                        if (option_verbose > 2)
446                                ast_verbose(VERBOSE_PREFIX_3 "codec_zap: %susing generic PLC\n",
447                                            global_useplc ? "" : "not ");
448                }
449         }
450         for (var = ast_variable_browse(cfg, "transcoder_card"); var; var = var->next) {
451                 if (!strcasecmp(var->name, "mode")) {
452                         if(strstr(var->value, "g729"))
453                                 cardsmode = 1;
454                         else if(strstr(var->value, "g723"))
455                                 cardsmode = 2;
456                         else if(strstr(var->value, "mixed"))
457                                 cardsmode = 0;
458                 }
459         }
460
461         ast_config_destroy(cfg);
462 }
463
464 static int build_translators(struct format_map *map, unsigned int dstfmts, unsigned int srcfmts)
465 {
466         unsigned int src, dst;
467
468         for (src = 0; src < 32; src++) {
469                 for (dst = 0; dst < 32; dst++) {
470                         if (!(srcfmts & (1 << src)))
471                                 continue;
472
473                         if (!(dstfmts & (1 << dst)))
474                                 continue;
475
476                         if (global_format_map.map[dst][src])
477                                 continue;
478
479                         if (!register_translator(dst, src))
480                                 map->map[dst][src] = 1;
481                         else
482                                 return 0;
483                 }
484         }
485         return 1;
486 }
487
488 static int find_transcoders(void)
489 {
490         struct zt_transcode_info info = { 0, };
491         struct format_map map = { { { 0 } } };
492         int fd, res;
493         unsigned int x, y;
494
495         info.op = ZT_TCOP_GETINFO;
496         if ((fd = open("/dev/zap/transcode", O_RDWR)) < 0) {
497                 ast_log(LOG_NOTICE, "No Zaptel transcoder support!\n");
498                 return 0;
499         }
500         for (info.tcnum = 0; !(res = ioctl(fd, ZT_TRANSCODE_OP, &info)); info.tcnum++) {
501                 if (option_verbose > 1)
502                         ast_verbose(VERBOSE_PREFIX_2 "Found transcoder '%s'.\n", info.name);
503
504                 if(build_translators(&map, info.dstfmts, info.srcfmts)) {
505                         ast_mutex_lock(&channelcount);
506                         totalchannels += info.numchannels;
507                         ast_mutex_unlock(&channelcount);
508                 }
509         }
510         close(fd);
511
512         if (!info.tcnum && (option_verbose > 1))
513                 ast_verbose(VERBOSE_PREFIX_2 "No hardware transcoders found.\n");
514
515         for (x = 0; x < 32; x++) {
516                 for (y = 0; y < 32; y++) {
517                         if (!map.map[x][y] && global_format_map.map[x][y])
518                                 drop_translator(x, y);
519                 }
520         }
521         ast_mutex_lock(&channelcount);
522         totalchannels = totalchannels/2;
523         ast_mutex_unlock(&channelcount);
524         return 0;
525 }
526
527 static int reload(void)
528 {
529         struct translator *cur;
530
531         parse_config();
532         find_transcoders();
533
534         AST_LIST_LOCK(&zap_translators);
535         AST_LIST_TRAVERSE(&zap_translators, cur, entry)
536                 cur->t.useplc = global_useplc;
537         AST_LIST_UNLOCK(&zap_translators);
538
539         return 0;
540 }
541
542 static int unload_module(void)
543 {
544         unregister_translators();
545         ast_cli_unregister_multiple(transcoder_cli, sizeof(transcoder_cli) / sizeof(struct ast_cli_entry));
546         return 0;
547 }
548
549 static int load_module(void)
550 {
551         ast_mutex_init(&channelcount);
552         parse_config();
553
554         find_transcoders();
555         ast_cli_register_multiple(transcoder_cli, sizeof(transcoder_cli) / sizeof(struct ast_cli_entry));
556         return 0;
557 }
558
559 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Generic Zaptel Transcoder Codec Translator",
560                 .load = load_module,
561                 .unload = unload_module,
562                 .reload = reload,
563                );