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