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