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