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