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