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