Convert between MS and non-MS formats
[asterisk/asterisk.git] / formats / format_gsm.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Save to raw, headerless GSM data.
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13  
14 #include <asterisk/lock.h>
15 #include <asterisk/channel.h>
16 #include <asterisk/file.h>
17 #include <asterisk/logger.h>
18 #include <asterisk/sched.h>
19 #include <asterisk/module.h>
20 #include <arpa/inet.h>
21 #include <stdlib.h>
22 #include <sys/time.h>
23 #include <stdio.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <string.h>
27 #include <pthread.h>
28 #ifdef __linux__
29 #include <endian.h>
30 #else
31 #include <machine/endian.h>
32 #endif
33 #include "msgsm.h"
34
35
36 /* Some Ideas for this code came from makegsme.c by Jeffery Chilton */
37
38 /* Portions of the conversion code are by guido@sienanet.it */
39
40 struct ast_filestream {
41         void *reserved[AST_RESERVED_POINTERS];
42         /* Believe it or not, we must decode/recode to account for the
43            weird MS format */
44         /* This is what a filestream means to us */
45         int fd; /* Descriptor */
46         struct ast_channel *owner;
47         struct ast_frame fr;                            /* Frame information */
48         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
49         char empty;                                                     /* Empty character */
50         unsigned char gsm[66];                          /* Two Real GSM Frames */
51         int lasttimeout;
52         struct timeval last;
53         int adj;
54         struct ast_filestream *next;
55 };
56
57
58 static struct ast_filestream *glist = NULL;
59 static pthread_mutex_t gsm_lock = AST_MUTEX_INITIALIZER;
60 static int glistcnt = 0;
61
62 static char *name = "gsm";
63 static char *desc = "Raw GSM data";
64 static char *exts = "gsm";
65
66 static struct ast_filestream *gsm_open(int fd)
67 {
68         /* We don't have any header to read or anything really, but
69            if we did, it would go here.  We also might want to check
70            and be sure it's a valid file.  */
71         struct ast_filestream *tmp;
72         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
73                 memset(tmp, 0, sizeof(struct ast_filestream));
74                 if (ast_pthread_mutex_lock(&gsm_lock)) {
75                         ast_log(LOG_WARNING, "Unable to lock gsm list\n");
76                         free(tmp);
77                         return NULL;
78                 }
79                 tmp->next = glist;
80                 glist = tmp;
81                 tmp->fd = fd;
82                 tmp->owner = NULL;
83                 tmp->fr.data = tmp->gsm;
84                 tmp->fr.frametype = AST_FRAME_VOICE;
85                 tmp->fr.subclass = AST_FORMAT_GSM;
86                 /* datalen will vary for each frame */
87                 tmp->fr.src = name;
88                 tmp->fr.mallocd = 0;
89                 tmp->lasttimeout = -1;
90                 glistcnt++;
91                 ast_pthread_mutex_unlock(&gsm_lock);
92                 ast_update_use_count();
93         }
94         return tmp;
95 }
96
97 static struct ast_filestream *gsm_rewrite(int fd, char *comment)
98 {
99         /* We don't have any header to read or anything really, but
100            if we did, it would go here.  We also might want to check
101            and be sure it's a valid file.  */
102         struct ast_filestream *tmp;
103         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
104                 memset(tmp, 0, sizeof(struct ast_filestream));
105                 if (ast_pthread_mutex_lock(&gsm_lock)) {
106                         ast_log(LOG_WARNING, "Unable to lock gsm list\n");
107                         free(tmp);
108                         return NULL;
109                 }
110                 tmp->next = glist;
111                 glist = tmp;
112                 tmp->fd = fd;
113                 tmp->owner = NULL;
114                 tmp->lasttimeout = -1;
115                 glistcnt++;
116                 ast_pthread_mutex_unlock(&gsm_lock);
117                 ast_update_use_count();
118         } else
119                 ast_log(LOG_WARNING, "Out of memory\n");
120         return tmp;
121 }
122
123 static struct ast_frame *gsm_read(struct ast_filestream *s)
124 {
125         return NULL;
126 }
127
128 static void gsm_close(struct ast_filestream *s)
129 {
130         struct ast_filestream *tmp, *tmpl = NULL;
131         if (ast_pthread_mutex_lock(&gsm_lock)) {
132                 ast_log(LOG_WARNING, "Unable to lock gsm list\n");
133                 return;
134         }
135         tmp = glist;
136         while(tmp) {
137                 if (tmp == s) {
138                         if (tmpl)
139                                 tmpl->next = tmp->next;
140                         else
141                                 glist = tmp->next;
142                         break;
143                 }
144                 tmpl = tmp;
145                 tmp = tmp->next;
146         }
147         glistcnt--;
148         if (s->owner) {
149                 s->owner->stream = NULL;
150                 if (s->owner->streamid > -1)
151                         ast_sched_del(s->owner->sched, s->owner->streamid);
152                 s->owner->streamid = -1;
153         }
154         ast_pthread_mutex_unlock(&gsm_lock);
155         ast_update_use_count();
156         if (!tmp) 
157                 ast_log(LOG_WARNING, "Freeing a filestream we don't seem to own\n");
158         close(s->fd);
159         free(s);
160         s = NULL;
161 }
162
163 static int ast_read_callback(void *data)
164 {
165         int retval = 0;
166         int res;
167         int delay = 20;
168         struct ast_filestream *s = data;
169         struct timeval tv;
170         /* Send a frame from the file to the appropriate channel */
171
172         s->fr.frametype = AST_FRAME_VOICE;
173         s->fr.subclass = AST_FORMAT_GSM;
174         s->fr.offset = AST_FRIENDLY_OFFSET;
175         s->fr.samples = 160;
176         s->fr.datalen = 33;
177         s->fr.mallocd = 0;
178         s->fr.data = s->gsm;
179         if ((res = read(s->fd, s->gsm, 33)) != 33) {
180                 if (res)
181                         ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
182                 s->owner->streamid = -1;
183                 return 0;
184         }
185         /* Lastly, process the frame */
186         if (ast_write(s->owner, &s->fr)) {
187                 ast_log(LOG_WARNING, "Failed to write frame\n");
188                 s->owner->streamid = -1;
189                 return 0;
190         }
191         if (s->last.tv_usec || s->last.tv_usec) {
192                 int ms;
193                 gettimeofday(&tv, NULL);
194                 ms = 1000 * (tv.tv_sec - s->last.tv_sec) + 
195                         (tv.tv_usec - s->last.tv_usec) / 1000;
196                 s->last.tv_sec = tv.tv_sec;
197                 s->last.tv_usec = tv.tv_usec;
198                 if ((ms - delay) * (ms - delay) > 4) {
199                         /* Compensate if we're more than 2 ms off */
200                         s->adj -= (ms - delay);
201                 }
202 #if 0
203                 fprintf(stdout, "Delay is %d, adjustment is %d, last was %d\n", delay, s->adj, ms);
204 #endif
205                 delay += s->adj;
206                 if (delay < 1)
207                         delay = 1;
208         } else
209                 gettimeofday(&s->last, NULL);
210         if (s->lasttimeout != delay) {
211                 /* We'll install the next timeout now. */
212                 s->owner->streamid = ast_sched_add(s->owner->sched,
213                                 delay, ast_read_callback, s); 
214                 s->lasttimeout = delay;
215         } else {
216                 /* Just come back again at the same time */
217                 retval = -1;
218         }
219         return retval;
220 }
221
222 static int gsm_apply(struct ast_channel *c, struct ast_filestream *s)
223 {
224         /* Select our owner for this stream, and get the ball rolling. */
225         s->owner = c;
226         return 0;
227 }
228
229 static int gsm_play(struct ast_filestream *s)
230 {
231         ast_read_callback(s);
232         return 0;
233 }
234
235 static int gsm_write(struct ast_filestream *fs, struct ast_frame *f)
236 {
237         int res;
238         unsigned char gsm[66];
239         if (f->frametype != AST_FRAME_VOICE) {
240                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
241                 return -1;
242         }
243         if (f->subclass != AST_FORMAT_GSM) {
244                 ast_log(LOG_WARNING, "Asked to write non-GSM frame (%d)!\n", f->subclass);
245                 return -1;
246         }
247         if (!(f->datalen % 65)) {
248                 /* This is in MSGSM format, need to be converted */
249                 int len=0;
250                 while(len < f->datalen) {
251                         conv65(f->data + len, gsm);
252                         if ((res = write(fs->fd, gsm, 66)) != 66) {
253                                 ast_log(LOG_WARNING, "Bad write (%d/66): %s\n", res, strerror(errno));
254                                 return -1;
255                         }
256                         len += 65;
257                 }
258         } else {
259                 if (f->datalen % 33) {
260                         ast_log(LOG_WARNING, "Invalid data length, %d, should be multiple of 33\n", f->datalen);
261                         return -1;
262                 }
263                 if ((res = write(fs->fd, f->data, f->datalen)) != f->datalen) {
264                                 ast_log(LOG_WARNING, "Bad write (%d/33): %s\n", res, strerror(errno));
265                                 return -1;
266                 }
267         }
268         return 0;
269 }
270
271 static int gsm_seek(struct ast_filestream *fs, long sample_offset, int whence)
272 {
273         off_t offset=0,min,cur,max,distance;
274         
275         min = 0;
276         cur = lseek(fs->fd, 0, SEEK_CUR);
277         max = lseek(fs->fd, 0, SEEK_END);
278         /* have to fudge to frame here, so not fully to sample */
279         distance = (sample_offset/160) * 33;
280         if(whence == SEEK_SET)
281                 offset = distance;
282         if(whence == SEEK_CUR)
283                 offset = distance + cur;
284         if(whence == SEEK_END)
285                 offset = max - distance;
286         offset = (offset > max)?max:offset;
287         offset = (offset < min)?min:offset;
288         return lseek(fs->fd, offset, SEEK_SET);
289 }
290
291 static int gsm_trunc(struct ast_filestream *fs)
292 {
293         return ftruncate(fs->fd, lseek(fs->fd,0,SEEK_CUR));
294 }
295
296 static long gsm_tell(struct ast_filestream *fs)
297 {
298         off_t offset;
299         offset = lseek(fs->fd, 0, SEEK_CUR);
300         return (offset/33)*160;
301 }
302
303 static char *gsm_getcomment(struct ast_filestream *s)
304 {
305         return NULL;
306 }
307
308 int load_module()
309 {
310         return ast_format_register(name, exts, AST_FORMAT_GSM,
311                                                                 gsm_open,
312                                                                 gsm_rewrite,
313                                                                 gsm_apply,
314                                                                 gsm_play,
315                                                                 gsm_write,
316                                                                 gsm_seek,
317                                                                 gsm_trunc,
318                                                                 gsm_tell,
319                                                                 gsm_read,
320                                                                 gsm_close,
321                                                                 gsm_getcomment);
322                                                                 
323                                                                 
324 }
325
326 int unload_module()
327 {
328         struct ast_filestream *tmp, *tmpl;
329         if (ast_pthread_mutex_lock(&gsm_lock)) {
330                 ast_log(LOG_WARNING, "Unable to lock gsm list\n");
331                 return -1;
332         }
333         tmp = glist;
334         while(tmp) {
335                 if (tmp->owner)
336                         ast_softhangup(tmp->owner, AST_SOFTHANGUP_APPUNLOAD);
337                 tmpl = tmp;
338                 tmp = tmp->next;
339                 free(tmpl);
340         }
341         ast_pthread_mutex_unlock(&gsm_lock);
342         return ast_format_unregister(name);
343 }       
344
345 int usecount()
346 {
347         int res;
348         if (ast_pthread_mutex_lock(&gsm_lock)) {
349                 ast_log(LOG_WARNING, "Unable to lock gsm list\n");
350                 return -1;
351         }
352         res = glistcnt;
353         ast_pthread_mutex_unlock(&gsm_lock);
354         return res;
355 }
356
357 char *description()
358 {
359         return desc;
360 }
361
362
363 char *key()
364 {
365         return ASTERISK_GPL_KEY;
366 }