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