Goodbye Zaptel, hello DAHDI. Removes Zaptel driver support with DAHDI. Configuration...
[asterisk/asterisk.git] / codecs / codec_dahdi.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * DAHDI 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 DAHDI transcoding
25  *
26  * \ingroup codecs
27  */
28
29 /*** MODULEINFO
30         <depend>dahdi</depend>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <fcntl.h>
38 #include <netinet/in.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41
42 #include "asterisk/dahdi.h"
43 #include "asterisk/lock.h"
44 #include "asterisk/translate.h"
45 #include "asterisk/config.h"
46 #include "asterisk/module.h"
47 #include "asterisk/cli.h"
48 #include "asterisk/channel.h"
49 #include "asterisk/utils.h"
50 #include "asterisk/linkedlists.h"
51
52 #define BUFFER_SAMPLES  8000
53
54 static unsigned int global_useplc = 0;
55
56 static struct channel_usage {
57         int total;
58         int encoders;
59         int decoders;
60 } channels;
61
62 static char *handle_cli_transcoder_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
63
64 static struct ast_cli_entry cli[] = {
65         AST_CLI_DEFINE(handle_cli_transcoder_show, "Display DAHDI transcoder utilization.")
66 };
67
68 struct format_map {
69         unsigned int map[32][32];
70 };
71
72 static struct format_map global_format_map = { { { 0 } } };
73
74 struct translator {
75         struct ast_translator t;
76         AST_LIST_ENTRY(translator) entry;
77 };
78
79 static AST_LIST_HEAD_STATIC(translators, translator);
80
81 struct pvt {
82         int fd;
83         int fake;
84 #ifdef DEBUG_TRANSCODE
85         int totalms;
86         int lasttotalms;
87 #endif
88         struct dahdi_transcode_header *hdr;
89 };
90
91 static char *handle_cli_transcoder_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
92 {
93         struct channel_usage copy;
94
95         switch (cmd) {
96         case CLI_INIT:
97                 e->command = "transcoder show";
98                 e->usage =
99                         "Usage: transcoder show\n"
100                         "       Displays channel utilization of DAHDI transcoder(s).\n";
101                 return NULL;
102         case CLI_GENERATE:
103                 return NULL;
104         }
105
106         if (a->argc != 2)
107                 return CLI_SHOWUSAGE;
108
109         copy = channels;
110
111         if (copy.total == 0)
112                 ast_cli(a->fd, "No DAHDI transcoders found.\n");
113         else
114                 ast_cli(a->fd, "%d/%d encoders/decoders of %d channels are in use.\n", copy.encoders, copy.decoders, copy.total);
115
116         return CLI_SUCCESS;
117 }
118
119 static int dahdi_framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
120 {
121         struct pvt *dahdip = pvt->pvt;
122         struct dahdi_transcode_header *hdr = dahdip->hdr;
123
124         if (!f->subclass) {
125                 /* Fake a return frame for calculation purposes */
126                 dahdip->fake = 2;
127                 pvt->samples = f->samples;
128                 return 0;
129         }
130
131         if (!hdr->srclen)
132                 /* Copy at front of buffer */
133                 hdr->srcoffset = 0;
134
135         if (hdr->srclen + f->datalen > sizeof(hdr->srcdata)) {
136                 ast_log(LOG_WARNING, "Out of space for codec translation!\n");
137                 return -1;
138         }
139
140         if (hdr->srclen + f->datalen + hdr->srcoffset > sizeof(hdr->srcdata)) {
141                 /* Very unlikely */
142                 memmove(hdr->srcdata, hdr->srcdata + hdr->srcoffset, hdr->srclen);
143                 hdr->srcoffset = 0;
144         }
145
146         memcpy(hdr->srcdata + hdr->srcoffset + hdr->srclen, f->data.ptr, f->datalen);
147         hdr->srclen += f->datalen;
148         pvt->samples += f->samples;
149
150         return -1;
151 }
152
153 static struct ast_frame *dahdi_frameout(struct ast_trans_pvt *pvt)
154 {
155         struct pvt *dahdip = pvt->pvt;
156         struct dahdi_transcode_header *hdr = dahdip->hdr;
157         unsigned int x;
158
159         if (dahdip->fake == 2) {
160                 dahdip->fake = 1;
161                 pvt->f.frametype = AST_FRAME_VOICE;
162                 pvt->f.subclass = 0;
163                 pvt->f.samples = 160;
164                 pvt->f.data.ptr = NULL;
165                 pvt->f.offset = 0;
166                 pvt->f.datalen = 0;
167                 pvt->f.mallocd = 0;
168                 ast_set_flag(&pvt->f, AST_FRFLAG_FROM_TRANSLATOR);
169                 pvt->samples = 0;
170         } else if (dahdip->fake == 1) {
171                 return NULL;
172         } else {
173                 if (hdr->dstlen) {
174 #ifdef DEBUG_TRANSCODE
175                         dahdip->totalms += hdr->dstsamples;
176                         if ((dahdip->totalms - dahdip->lasttotalms) > 8000) {
177                                 printf("Whee %p, %d (%d to %d)\n", dahdip, hdr->dstlen, dahdip->lasttotalms, dahdip->totalms);
178                                 dahdip->lasttotalms = dahdip->totalms;
179                         }
180 #endif
181                         pvt->f.frametype = AST_FRAME_VOICE;
182                         pvt->f.subclass = hdr->dstfmt;
183                         pvt->f.samples = hdr->dstsamples;
184                         pvt->f.data.ptr = hdr->dstdata + hdr->dstoffset;
185                         pvt->f.offset = hdr->dstoffset;
186                         pvt->f.datalen = hdr->dstlen;
187                         pvt->f.mallocd = 0;
188                         ast_set_flag(&pvt->f, AST_FRFLAG_FROM_TRANSLATOR);
189                         pvt->samples -= pvt->f.samples;
190                         hdr->dstlen = 0;
191                         
192                 } else {
193                         if (hdr->srclen) {
194                                 hdr->dstoffset = AST_FRIENDLY_OFFSET;
195                                 x = DAHDI_TCOP_TRANSCODE;
196                                 if (ioctl(dahdip->fd, DAHDI_TRANSCODE_OP, &x))
197                                         ast_log(LOG_WARNING, "Failed to transcode: %s\n", strerror(errno));
198                         }
199                         return NULL;
200                 }
201         }
202
203         return &pvt->f;
204 }
205
206 static void dahdi_destroy(struct ast_trans_pvt *pvt)
207 {
208         struct pvt *dahdip = pvt->pvt;
209         unsigned int x;
210
211         x = DAHDI_TCOP_RELEASE;
212         if (ioctl(dahdip->fd, DAHDI_TRANSCODE_OP, &x))
213                 ast_log(LOG_WARNING, "Failed to release transcoder channel: %s\n", strerror(errno));
214
215         switch (dahdip->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(dahdip->hdr, sizeof(*dahdip->hdr));
226         close(dahdip->fd);
227 }
228
229 static int dahdi_translate(struct ast_trans_pvt *pvt, int dest, int source)
230 {
231         /* Request translation through dahdi if possible */
232         int fd;
233         unsigned int x = DAHDI_TCOP_ALLOCATE;
234         struct pvt *dahdip = pvt->pvt;
235         struct dahdi_transcode_header *hdr;
236         int flags;
237         
238         if ((fd = open("/dev/dahdi/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 != DAHDI_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, DAHDI_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         dahdip = pvt->pvt;
273         dahdip->fd = fd;
274         dahdip->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 dahdi_new(struct ast_trans_pvt *pvt)
290 {
291         return dahdi_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 *dahdi;
309         int res;
310
311         if (!(dahdi = ast_calloc(1, sizeof(*dahdi))))
312                 return -1;
313
314         snprintf((char *) (dahdi->t.name), sizeof(dahdi->t.name), "DAHDI%sto%s", 
315                  ast_getformatname((1 << src)), ast_getformatname((1 << dst)));
316         dahdi->t.srcfmt = (1 << src);
317         dahdi->t.dstfmt = (1 << dst);
318         dahdi->t.newpvt = dahdi_new;
319         dahdi->t.framein = dahdi_framein;
320         dahdi->t.frameout = dahdi_frameout;
321         dahdi->t.destroy = dahdi_destroy;
322         dahdi->t.sample = fakesrc_sample;
323         dahdi->t.useplc = global_useplc;
324         dahdi->t.buf_size = BUFFER_SAMPLES * 2;
325         dahdi->t.desc_size = sizeof(struct pvt);
326         if ((res = ast_register_translator(&dahdi->t))) {
327                 ast_free(dahdi);
328                 return -1;
329         }
330
331         AST_LIST_LOCK(&translators);
332         AST_LIST_INSERT_HEAD(&translators, dahdi, 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_dahdi: %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 dahdi_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/dahdi/transcode", O_RDWR)) < 0) {
425                 ast_verbose(VERBOSE_PREFIX_2 "No hardware transcoders found.\n");
426                 return 0;
427         }
428
429         info.op = DAHDI_TCOP_GETINFO;
430         for (info.tcnum = 0; !(res = ioctl(fd, DAHDI_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 DAHDI Transcoder Codec Translator",
484                 .load = load_module,
485                 .unload = unload_module,
486                 .reload = reload,
487                 );