fixed nubb error on my part, transcoder now unlocks and locks correctly, as well...
[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 = 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_unlock(&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_unlock(&channelcount);
269         return zap_translate(pvt, pvt->t->dstfmt, pvt->t->srcfmt);
270 }
271
272 static struct ast_frame *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 = 240,
278                 .src = __PRETTY_FUNCTION__
279         };
280
281         return &f;
282 }
283
284 static int register_translator(int dst, int src)
285 {
286         struct translator *zt;
287         int res;
288
289         if (!(zt = ast_calloc(1, sizeof(*zt))))
290                 return -1;
291
292         snprintf((char *) (zt->t.name), sizeof(zt->t.name), "zap%sto%s", 
293                  ast_getformatname((1 << src)), ast_getformatname((1 << dst)));
294         zt->t.srcfmt = (1 << src);
295         zt->t.dstfmt = (1 << dst);
296         zt->t.newpvt = zap_new;
297         zt->t.framein = zap_framein;
298         zt->t.frameout = zap_frameout;
299         zt->t.destroy = zap_destroy;
300         zt->t.sample = fakesrc_sample;
301         zt->t.useplc = global_useplc;
302         zt->t.buf_size = BUFFER_SAMPLES * 2;
303         zt->t.desc_size = sizeof(struct pvt);
304         if ((res = ast_register_translator(&zt->t))) {
305                 free(zt);
306                 return -1;
307         }
308
309         AST_LIST_LOCK(&translators);
310         AST_LIST_INSERT_HEAD(&translators, zt, entry);
311         AST_LIST_UNLOCK(&translators);
312
313         global_format_map.map[dst][src] = 1;
314
315         return res;
316 }
317
318 static void drop_translator(int dst, int src)
319 {
320         struct translator *cur;
321
322         AST_LIST_LOCK(&translators);
323         AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, cur, entry) {
324                 if (cur->t.srcfmt != src)
325                         continue;
326
327                 if (cur->t.dstfmt != dst)
328                         continue;
329
330                 AST_LIST_REMOVE_CURRENT(&translators, entry);
331                 ast_unregister_translator(&cur->t);
332                 free(cur);
333                 global_format_map.map[dst][src] = 0;
334                 break;
335         }
336         AST_LIST_TRAVERSE_SAFE_END;
337         AST_LIST_UNLOCK(&translators);
338 }
339
340 static void unregister_translators(void)
341 {
342         struct translator *cur;
343
344         AST_LIST_LOCK(&translators);
345         while ((cur = AST_LIST_REMOVE_HEAD(&translators, entry))) {
346                 ast_unregister_translator(&cur->t);
347                 free(cur);
348         }
349         AST_LIST_UNLOCK(&translators);
350 }
351
352 static void parse_config(void)
353 {
354         struct ast_variable *var;
355         struct ast_config *cfg = ast_config_load("codecs.conf");
356         cardsmode = 0;
357
358         if (!cfg)
359                 return;
360
361         for (var = ast_variable_browse(cfg, "plc"); var; var = var->next) {
362                if (!strcasecmp(var->name, "genericplc")) {
363                        global_useplc = ast_true(var->value);
364                        if (option_verbose > 2)
365                                ast_verbose(VERBOSE_PREFIX_3 "codec_zap: %susing generic PLC\n",
366                                            global_useplc ? "" : "not ");
367                }
368         }
369         for (var = ast_variable_browse(cfg, "transcoder_card"); var; var = var->next) {
370                 if (!strcasecmp(var->name, "mode")) {
371                         if(strstr(var->value, "g729"))
372                                 cardsmode = 1;
373                         else if(strstr(var->value, "g723"))
374                                 cardsmode = 2;
375                         else if(strstr(var->value, "mixed"))
376                                 cardsmode = 0;
377                 }
378         }
379
380         ast_config_destroy(cfg);
381 }
382
383 static void build_translators(struct format_map *map, unsigned int dstfmts, unsigned int srcfmts)
384 {
385         unsigned int src, dst;
386
387         for (src = 0; src < 32; src++) {
388                 for (dst = 0; dst < 32; dst++) {
389                         if (!(srcfmts & (1 << src)))
390                                 continue;
391
392                         if (!(dstfmts & (1 << dst)))
393                                 continue;
394
395                         if (global_format_map.map[dst][src])
396                                 continue;
397
398                         if (!register_translator(dst, src))
399                                 map->map[dst][src] = 1;
400                 }
401         }
402 }
403
404 static int find_transcoders(void)
405 {
406         struct zt_transcode_info info = { 0, };
407         struct format_map map = { { { 0 } } };
408         int fd, res;
409         unsigned int x, y;
410
411         info.op = ZT_TCOP_GETINFO;
412         if ((fd = open("/dev/zap/transcode", O_RDWR)) < 0) {
413                 ast_log(LOG_NOTICE, "No Zaptel transcoder support!\n");
414                 return 0;
415         }
416         for (info.tcnum = 0; !(res = ioctl(fd, ZT_TRANSCODE_OP, &info)); info.tcnum++) {
417                 if (option_verbose > 1)
418                         ast_verbose(VERBOSE_PREFIX_2 "Found transcoder '%s'.\n", info.name);
419                 ast_mutex_lock(&channelcount);
420                 totalchannels += info.numchannels;
421                 ast_mutex_unlock(&channelcount);
422                 build_translators(&map, info.dstfmts, info.srcfmts);
423         }
424         close(fd);
425
426         if (!info.tcnum && (option_verbose > 1))
427                 ast_verbose(VERBOSE_PREFIX_2 "No hardware transcoders found.\n");
428
429         for (x = 0; x < 32; x++) {
430                 for (y = 0; y < 32; y++) {
431                         if (!map.map[x][y] && global_format_map.map[x][y])
432                                 drop_translator(x, y);
433                 }
434         }
435
436         return 0;
437 }
438
439 static int reload(void)
440 {
441         struct translator *cur;
442
443         parse_config();
444         find_transcoders();
445
446         AST_LIST_LOCK(&translators);
447         AST_LIST_TRAVERSE(&translators, cur, entry)
448                 cur->t.useplc = global_useplc;
449         AST_LIST_UNLOCK(&translators);
450
451         return 0;
452 }
453
454 static int unload_module(void)
455 {
456         unregister_translators();
457         ast_cli_unregister_multiple(transcoder_cli, sizeof(transcoder_cli) / sizeof(struct ast_cli_entry));
458         return 0;
459 }
460
461 static int load_module(void)
462 {
463         ast_mutex_init(&channelcount);
464         parse_config();
465
466         find_transcoders();
467         ast_cli_register_multiple(transcoder_cli, sizeof(transcoder_cli) / sizeof(struct ast_cli_entry));
468         return 0;
469 }
470
471 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Generic Zaptel Transcoder Codec Translator",
472                 .load = load_module,
473                 .unload = unload_module,
474                 .reload = reload,
475                );