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