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