Completed GSM mobile station support with OsmocomBB
[lcr.git] / port.cpp
1 /*****************************************************************************\
2 **                                                                           **
3 ** PBX4Linux                                                                 **
4 **                                                                           **
5 **---------------------------------------------------------------------------**
6 ** Copyright: Andreas Eversberg                                              **
7 **                                                                           **
8 ** port                                                                      **
9 **                                                                           **
10 \*****************************************************************************/ 
11
12 /* HOW TO audio?
13
14 Audio flow has two ways:
15
16 * from channel to the upper layer
17   -> sound from mISDN channel
18   -> announcement from vbox channel
19
20 * from the upper layer to the channel
21   -> sound from remote channel
22
23 Audio is required:
24
25   -> if local or remote channel is not mISDN
26   -> if call is recorded (vbox)
27
28
29 Functions:
30
31 * PmISDN::txfromup
32   -> audio from upper layer is buffered for later transmission to channel
33 * PmISDN::handler
34   -> buffered audio from upper layer or tones are transmitted via system clock
35 * mISDN_handler
36   -> rx-data from port to record() and upper layer
37   -> tx-data from port (dsp) to record()
38 * VboxPort::handler
39   -> streaming announcement to upper layer
40   -> recording announcement
41 * VboxPort::message_epoint
42   -> recording audio message from upper layer
43   
44
45    
46 */
47
48 #include "main.h"
49
50 #define SHORT_MIN -32768
51 #define SHORT_MAX 32767
52
53 class Port *port_first = NULL;
54
55 unsigned int port_serial = 1; /* must be 1, because 0== no port */
56
57
58 /* free epointlist relation
59  */
60 void Port::free_epointlist(struct epoint_list *epointlist)
61 {
62         struct epoint_list *temp, **tempp;
63
64         temp = p_epointlist;
65         tempp = &p_epointlist;
66         while(temp) {
67                 if (temp == epointlist)
68                         break;
69
70                 tempp = &temp->next;
71                 temp = temp->next;
72         }
73         if (temp == 0) {
74                 PERROR("SOFTWARE ERROR: epointlist not in port's list.\n");
75                 return;
76         }
77         /* detach */
78         *tempp=temp->next;
79
80         /* free */
81         PDEBUG(DEBUG_EPOINT, "PORT(%d) removed epoint from port\n", p_serial);
82         FREE(temp, sizeof(struct epoint_list));
83         ememuse--;
84 }
85
86
87 void Port::free_epointid(unsigned int epoint_id)
88 {
89         struct epoint_list *temp, **tempp;
90
91         temp = p_epointlist;
92         tempp = &p_epointlist;
93         while(temp) {
94                 if (temp->epoint_id == epoint_id)
95                         break;
96
97                 tempp = &temp->next;
98                 temp = temp->next;
99         }
100         if (temp == 0) {
101                 PERROR("epoint_id not in port's list.\n");
102                 return;
103         }
104         /* detach */
105         *tempp=temp->next;
106
107         /* free */
108         PDEBUG(DEBUG_EPOINT, "PORT(%d) removed epoint from port\n", p_serial);
109         FREE(temp, sizeof(struct epoint_list));
110         ememuse--;
111 }
112
113
114 /* create new epointlist relation
115  */
116 struct epoint_list *Port::epointlist_new(unsigned int epoint_id)
117 {
118         struct epoint_list *epointlist, **epointlistpointer;
119
120         /* epointlist structure */
121         epointlist = (struct epoint_list *)MALLOC(sizeof(struct epoint_list));
122         if (!epointlist)
123                 FATAL("No memory for epointlist\n");
124         ememuse++;
125         PDEBUG(DEBUG_EPOINT, "PORT(%d) allocating epoint_list.\n", p_serial);
126
127         /* add epoint_list to chain */
128         epointlist->next = NULL;
129         epointlistpointer = &p_epointlist;
130         while(*epointlistpointer)
131                 epointlistpointer = &((*epointlistpointer)->next);
132         *epointlistpointer = epointlist;
133
134         /* link to epoint */
135         epointlist->epoint_id = epoint_id;
136         epointlist->active = 1;
137
138         return(epointlist);
139 }
140
141
142 /*
143  * port constructor
144  */
145 Port::Port(int type, const char *portname, struct port_settings *settings)
146 {
147         class Port *temp, **tempp;
148
149         PDEBUG(DEBUG_PORT, "new port of type %d, name '%s'\n", type, portname);
150
151         /* initialize object */
152         if (settings)
153                 memcpy(&p_settings, settings, sizeof(struct port_settings));
154         else {
155                 memset(&p_settings, 0, sizeof(p_settings));
156         }
157         SCPY(p_name, portname);
158         p_tone_dir[0] = '\0';
159         p_type = type;
160         p_serial = port_serial++;
161         p_tone_fh = -1;
162         p_tone_fetched = NULL;
163         p_tone_name[0] = '\0';
164         p_state = PORT_STATE_IDLE;
165         p_epointlist = NULL;
166         memset(&p_callerinfo, 0, sizeof(p_callerinfo));
167         memset(&p_dialinginfo, 0, sizeof(p_dialinginfo));
168         memset(&p_connectinfo, 0, sizeof(p_connectinfo));
169         memset(&p_redirinfo, 0, sizeof(p_redirinfo));
170         memset(&p_capainfo, 0, sizeof(p_capainfo));
171         p_echotest = 0;
172
173         /* call recording */
174         p_record = NULL;
175         p_record_type = 0;
176         p_record_length = 0;
177         p_record_skip = 0;
178         p_record_filename[0] = '\0';
179         p_record_buffer_readp = 0;
180         p_record_buffer_writep = 0;
181         p_record_buffer_dir = 0;
182
183         /* append port to chain */
184         next = NULL;
185         temp = port_first;
186         tempp = &port_first;
187         while(temp) {
188                 tempp = &temp->next;
189                 temp = temp->next;
190         }
191         *tempp = this;
192
193         classuse++;
194 }
195
196
197 /*
198  * port destructor
199  */
200 Port::~Port(void)
201 {
202         class Port *temp, **tempp;
203         struct lcr_msg *message;
204
205         if (p_record)
206                 close_record(0, 0);
207
208         classuse--;
209
210         PDEBUG(DEBUG_PORT, "removing port of type %d, name '%s'\n", p_type, p_name);
211
212         /* disconnect port from endpoint */
213         while(p_epointlist) {
214                 /* send disconnect */
215                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
216                 message->param.disconnectinfo.cause = 16;
217                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
218                 message_put(message);
219                 /* remove endpoint */
220                 free_epointlist(p_epointlist);
221         }
222
223         /* remove port from chain */
224         temp=port_first;
225         tempp=&port_first;
226         while(temp) {
227                 if (temp == this)
228                         break;
229                 tempp = &temp->next;
230                 temp = temp->next;
231         }
232         if (temp == NULL)
233                 FATAL("PORT(%s) port not in port's list.\n", p_name);
234         /* detach */
235         *tempp=this->next;
236
237         /* close open tones file */
238         if (p_tone_fh >= 0) {
239                 close(p_tone_fh);
240                 p_tone_fh = -1;
241                 fhuse--;
242         }
243         p_tone_fetched = NULL;
244 }
245
246 PORT_STATE_NAMES
247
248 /* set new endpoint state
249  */
250 void Port::new_state(int state)
251 {
252         PDEBUG(DEBUG_PORT, "PORT(%s) new state %s --> %s\n", p_name, state_name[p_state], state_name[state]);
253         p_state = state;
254 }
255
256
257 /*
258  * find the port with port_id
259  */ 
260 class Port *find_port_id(unsigned int port_id)
261 {
262         class Port *port = port_first;
263
264         while(port) {
265 //printf("comparing: '%s' with '%s'\n", name, port->name);
266                 if (port->p_serial == port_id)
267                         return(port);
268                 port = port->next;
269         }
270
271         return(NULL);
272 }
273
274
275 /*
276  * set echotest
277  */
278 void Port::set_echotest(int echotest)
279 {
280         p_echotest = echotest;
281 }
282
283
284 /*
285  * set the file in the tone directory with the given name
286  */
287 void Port::set_tone(const char *dir, const char *name)
288 {
289         int fh;
290         char filename[128];
291
292         if (name == NULL)
293                 name = "";
294
295         if (!dir && !dir[0])
296                 dir = options.tones_dir; /* just in case we have no PmISDN instance */
297
298         /* no counter, no eof, normal speed */
299         p_tone_counter = 0;
300         p_tone_eof = 0;
301         p_tone_speed = 1;
302         p_tone_codec = CODEC_LAW;
303
304         if (p_tone_fh >= 0) {
305                 close(p_tone_fh);
306                 p_tone_fh = -1;
307                 fhuse--;
308         }
309         p_tone_fetched = NULL;
310
311         if (name[0]) {
312                 if (name[0] == '/') {
313                         SPRINT(p_tone_name, "%s", name);
314                         p_tone_dir[0] = '\0';
315                 } else {
316                         SCPY(p_tone_dir, dir);
317                         SCPY(p_tone_name, name);
318                 }
319                 /* trigger playback */
320                 update_load();
321         } else {
322                 p_tone_name[0]= '\0';
323                 p_tone_dir[0]= '\0';
324                 return;
325         }
326
327         if (!!strncmp(name,"cause_",6))
328                 return;
329
330         /* now we check if the cause exists, otherwhise we use error tone. */
331         if ((p_tone_fetched=open_tone_fetched(p_tone_dir, p_tone_name, &p_tone_codec, 0, 0))) {
332                 p_tone_fetched = NULL;
333                 return;
334         }
335         SPRINT(filename, "%s_loop", p_tone_name);
336         if ((p_tone_fetched=open_tone_fetched(p_tone_dir, filename, &p_tone_codec, 0, 0))) {
337                 p_tone_fetched = NULL;
338                 return;
339         }
340         SPRINT(filename, "%s/%s/%s", SHARE_DATA, p_tone_dir, p_tone_name);
341         if ((fh=open_tone(filename, &p_tone_codec, 0, 0)) >= 0) {
342                 close(fh);
343                 return;
344         }
345         SPRINT(filename, "%s/%s/%s_loop", SHARE_DATA, p_tone_dir, p_tone_name);
346         if ((fh=open_tone(filename, &p_tone_codec, 0, 0)) >= 0) {
347                 close(fh);
348                 return;
349         }
350
351         if (!strcmp(name,"cause_00") || !strcmp(name,"cause_10")) {
352                 PDEBUG(DEBUG_PORT, "PORT(%s) Given Cause 0x%s has no tone, using release tone\n", p_name, name+6);
353                 SPRINT(p_tone_name,"release");
354         } else
355         if (!strcmp(name,"cause_11")) {
356                 PDEBUG(DEBUG_PORT, "PORT(%s) Given Cause 0x%s has no tone, using busy tone\n", p_name, name+6);
357                 SPRINT(p_tone_name,"busy");
358         } else {
359                 PDEBUG(DEBUG_PORT, "PORT(%s) Given Cause 0x%s has no tone, using error tone\n", p_name, name+6);
360                 SPRINT(p_tone_name,"error");
361         }
362 }
363
364
365 /*
366  * set the file in the tone directory for vbox playback
367  * also set the play_eof-flag
368  */
369 void Port::set_vbox_tone(const char *dir, const char *name)
370 {
371         char filename[256];
372
373         p_tone_speed = 1;
374         p_tone_counter = 0;
375         p_tone_codec = CODEC_LAW;
376         p_tone_eof = 1;
377
378         if (p_tone_fh >= 0) {
379                 close(p_tone_fh);
380                 p_tone_fh = -1;
381                 fhuse--;
382         }
383         p_tone_fetched = NULL;
384
385         SPRINT(p_tone_dir,  dir);
386         SPRINT(p_tone_name,  name);
387         /* trigger playback */
388         update_load();
389
390         /* now we check if the cause exists, otherwhise we use error tone. */
391         if (p_tone_dir[0]) {
392                 if ((p_tone_fetched=open_tone_fetched(p_tone_dir, p_tone_name, &p_tone_codec, &p_tone_size, &p_tone_left))) {
393                         PDEBUG(DEBUG_PORT, "PORT(%s) opening fetched tone: %s\n", p_name, p_tone_name);
394                         return;
395                 }
396                 SPRINT(filename, "%s/%s/%s", SHARE_DATA, p_tone_dir, p_tone_name);
397                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) >= 0) {
398                         fhuse++;
399                         PDEBUG(DEBUG_PORT, "PORT(%s) opening tone: %s\n", p_name, filename);
400                         return;
401                 }
402         } else {
403                 SPRINT(filename, "%s", p_tone_name);
404                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) >= 0) {
405                         fhuse++;
406                         PDEBUG(DEBUG_PORT, "PORT(%s) opening tone: %s\n", p_name, filename);
407                         return;
408                 }
409         }
410 }
411
412
413 /*
414  * set the file in the given directory for vbox playback
415  * also set the eof-flag
416  * also set the counter-flag
417  */
418 void Port::set_vbox_play(const char *name, int offset)
419 {
420         struct lcr_msg *message;
421
422         /* use ser_box_tone() */
423         set_vbox_tone("", name);
424         if (p_tone_fh < 0)
425                 return;
426
427         /* enable counter */
428         p_tone_counter = 1;
429
430         /* seek */
431         if (p_tone_name[0]) {
432                 /* send message with counter value */
433                 if (p_tone_size>=0 && ACTIVE_EPOINT(p_epointlist)) {
434                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_TONE_COUNTER);
435                         message->param.counter.current = offset;
436                         message->param.counter.max = p_tone_size;
437                         message_put(message);
438                 }
439         }
440 }
441
442
443 /*
444  * set the playback speed (for recording playback with different speeds)
445  */
446 void Port::set_vbox_speed(int speed)
447 {
448         /* enable vbox play mode */
449         p_tone_speed = speed;
450 }
451
452 /*
453  * read from the given file as specified in port_set_tone and return sample data
454  * if the tone ends, the result may be less samples than requested
455  */
456 int Port::read_audio(unsigned char *buffer, int length)
457 {
458         int l = 0,len;
459         int nodata=0; /* to detect 0-length files and avoid endless reopen */
460         char filename[128];
461         int tone_left_before; /* temp variable to determine the change in p_tone_left */
462
463         /* nothing */
464         if (length == 0)
465                 return(0);
466
467         len = length;
468
469         /* if there is no tone set, use silence */
470         if (!p_tone_name[0])
471                 return(0);
472
473         /* if the file pointer is not open, we open it */
474         if (p_tone_fh<0 && p_tone_fetched==NULL) {
475                 if (p_tone_dir[0]) {
476                         SPRINT(filename, "%s", p_tone_name);
477                         /* if file does not exist */
478                         if (!(p_tone_fetched=open_tone_fetched(p_tone_dir, filename, &p_tone_codec, &p_tone_size, &p_tone_left))) {
479                                 SPRINT(filename, "%s/%s/%s", SHARE_DATA, p_tone_dir, p_tone_name);
480                                 /* if file does not exist */
481                                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0) {
482                                         PDEBUG(DEBUG_PORT, "PORT(%s) no tone: %s\n", p_name, filename);
483                                         goto try_loop;
484                                 }
485                                 fhuse++;
486                         }
487                 } else {
488                         SPRINT(filename, "%s", p_tone_name);
489                         /* if file does not exist */
490                         if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0) {
491                                 PDEBUG(DEBUG_PORT, "PORT(%s) no tone: %s\n", p_name, filename);
492                                 goto try_loop;
493                         }
494                         fhuse++;
495                 }
496                 PDEBUG(DEBUG_PORT, "PORT(%s) opening %stone: %s\n", p_name, p_tone_fetched?"fetched ":"", filename);
497         }
498
499 read_more:
500         /* file descriptor is open read data */
501         tone_left_before = p_tone_left;
502         if (p_tone_fh >= 0) {
503                 l = read_tone(p_tone_fh, buffer, p_tone_codec, len, p_tone_size, &p_tone_left, p_tone_speed);
504                 if (l<0 || l>len) /* paranoia */
505                         l=0;
506                 buffer += l;
507                 len -= l;
508         }
509         if (p_tone_fetched) {
510                 l = read_tone_fetched(&p_tone_fetched, buffer, len, p_tone_size, &p_tone_left, p_tone_speed);
511                 if (l<0 || l>len) /* paranoia */
512                         l=0;
513                 buffer += l;
514                 len -= l;
515         }
516
517         /* if counter is enabled, we check if we have a change */
518         if (p_tone_counter && p_tone_size>=0 && ACTIVE_EPOINT(p_epointlist)) {
519                 /* if we jumed to the next second */
520                 if (((p_tone_size-p_tone_left)/8000) != (p_tone_size-tone_left_before)/8000) {
521 //printf("\nsize=%d left=%d\n\n",p_tone_size,p_tone_left);
522                         struct lcr_msg *message;
523                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_TONE_COUNTER);
524                         message->param.counter.current = (p_tone_size-p_tone_left)/8000;
525                         message->param.counter.max = -1;
526                         message_put(message);
527                 }
528         }
529
530         if (len==0)
531                 return(length-len);
532
533         if (p_tone_fh >= 0) {
534                 close(p_tone_fh);
535                 p_tone_fh = -1;
536                 fhuse--;
537         }
538         p_tone_fetched = NULL;
539
540         if (l)
541                 nodata=0;
542
543         /* if the file has 0-length */
544         if (nodata>1) {
545                 PDEBUG(DEBUG_PORT, "PORT(%s) 0-length loop: %s\n", p_name, filename);
546                 p_tone_name[0]=0;
547                 p_tone_dir[0]=0;
548                 return(length-len);
549         }
550
551         /* if eof is reached, or if the normal file cannot be opened, continue with the loop file if possible */
552 try_loop:
553         if (p_tone_eof && ACTIVE_EPOINT(p_epointlist)) {
554                 struct lcr_msg *message;
555                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_TONE_EOF);
556                 message_put(message);
557         }
558
559         if (p_tone_dir[0]) {
560                 /* if file does not exist */
561                 SPRINT(filename, "%s_loop", p_tone_name);
562                 if (!(p_tone_fetched=open_tone_fetched(p_tone_dir, filename, &p_tone_codec, &p_tone_size, &p_tone_left))) {
563                         SPRINT(filename, "%s/%s/%s_loop", SHARE_DATA, p_tone_dir, p_tone_name);
564                         /* if file does not exist */
565                         if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0) {
566                                 PDEBUG(DEBUG_PORT, "PORT(%s) no tone loop: %s\n",p_name, filename);
567                                 p_tone_dir[0] = '\0';
568                                 p_tone_name[0] = '\0';
569                                 return(length-len);
570                         }
571                         fhuse++;
572                 }
573         } else {
574                 SPRINT(filename, "%s_loop", p_tone_name);
575                 /* if file does not exist */
576                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0) {
577                         PDEBUG(DEBUG_PORT, "PORT(%s) no tone loop: %s\n",p_name, filename);
578                         p_tone_dir[0] = '\0';
579                         p_tone_name[0] = '\0';
580                         return(length-len);
581                 }
582                 fhuse++;
583         }
584         nodata++;
585         PDEBUG(DEBUG_PORT, "PORT(%s) opening %stone: %s\n", p_name, p_tone_fetched?"fetched ":"", filename);
586
587         /* now we have opened the loop */
588         goto read_more;
589 }
590
591
592 /* endpoint sends messages to the port
593  * this is called by the message_epoint inherited by child classes
594  * therefor a return=1 means: stop, no more processing
595  */
596 //extern struct lcr_msg *dddebug;
597 int Port::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
598 {
599         /* check if we got audio data from one remote port */
600         switch(message_id) {
601                 case MESSAGE_TONE: /* play tone */
602                 PDEBUG(DEBUG_PORT, "PORT(%s) isdn port with (caller id %s) setting tone '%s' dir '%s'\n", p_name, p_callerinfo.id, param->tone.name, param->tone.dir);
603                 set_tone(param->tone.dir,param->tone.name);
604                 return(1);
605
606                 case MESSAGE_VBOX_TONE: /* play tone of answering machine */
607                 PDEBUG(DEBUG_PORT, "PORT(%s) set answering machine tone '%s' '%s'\n", p_name, param->tone.dir, param->tone.name);
608                 set_vbox_tone(param->tone.dir, param->tone.name);
609                 return(1);
610
611                 case MESSAGE_VBOX_PLAY: /* play recording of answering machine */
612                 PDEBUG(DEBUG_PORT, "PORT(%s) set answering machine file to play '%s' (offset %d seconds)\n", p_name, param->play.file, param->play.offset);
613                 set_vbox_play(param->play.file, param->play.offset);
614                 return(1);
615
616                 case MESSAGE_VBOX_PLAY_SPEED: /* set speed of playback (recording of answering machine) */
617                 PDEBUG(DEBUG_PORT, "PORT(%s) set answering machine playback speed %d (times)\n", p_name, param->speed);
618                 set_vbox_speed(param->speed);
619                 return(1);
620
621         }
622
623         return(0);
624 }
625
626
627 /* wave header structure */
628 struct fmt {
629         unsigned short  stereo; /* 1 = mono, 2 = stereo */
630         unsigned short  channels; /* number of channels */
631         unsigned int    sample_rate; /* sample rate */
632         unsigned int    data_rate; /* data rate */
633         unsigned short  bytes_sample; /* bytes per sample (all channels) */
634         unsigned short  bits_sample; /* bits per sample (one channel) */
635 };
636
637
638 /*
639  * open record file (actually a wave file with empty header which will be
640  * written before close, because we do not know the size yet)
641  * type=1 record annoucement,  type=0 record audio stream, type=2 record vbox
642  */
643 int Port::open_record(int type, int vbox, int skip, char *extension, int anon_ignore, const char *vbox_email, int vbox_email_file)
644 {
645         /* RIFFxxxxWAVEfmt xxxx(fmt-size)dataxxxx... */
646         char dummyheader[8+4+8+sizeof(fmt)+8];
647         char filename[256];
648         time_t now;
649         struct tm *now_tm;
650         int ret;
651
652         if (!extension) {
653                 PERROR("Port(%d) not an extension\n", p_serial);
654                 return(0);
655         }
656         SCPY(p_record_extension, extension);
657         p_record_anon_ignore = anon_ignore;
658         SCPY(p_record_vbox_email, vbox_email);
659         p_record_vbox_email_file = vbox_email_file;
660         
661         if (p_record) {
662                 PERROR("Port(%d) already recording\n", p_serial);
663                 return(0);
664         }
665
666         if (vbox != 0)
667                 SPRINT(filename, "%s/%s/vbox", EXTENSION_DATA, p_record_extension);
668         else
669                 SPRINT(filename, "%s/%s/recordings", EXTENSION_DATA, p_record_extension);
670         if (mkdir(filename, 0755) < 0) {
671                 if (errno != EEXIST) {
672                         PERROR("Port(%d) cannot create directory '%s'\n", p_serial, filename);
673                         return(0);
674                 }
675         }
676
677         if (vbox == 1)
678                 UPRINT(strchr(filename,'\0'), "/announcement");
679         else {
680                 time(&now);
681                 now_tm = localtime(&now);
682                 UPRINT(strchr(filename,'\0'), "/%04d-%02d-%02d_%02d%02d%02d", now_tm->tm_year+1900, now_tm->tm_mon+1, now_tm->tm_mday, now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec);
683         }
684         if (vbox == 2) {
685                 p_record_vbox_year = now_tm->tm_year;
686                 p_record_vbox_mon = now_tm->tm_mon;
687                 p_record_vbox_mday = now_tm->tm_mday;
688                 p_record_vbox_hour = now_tm->tm_hour;
689                 p_record_vbox_min = now_tm->tm_min;
690         }
691
692         /* check, if file exists (especially when an extension calls the same extension) */
693         if (vbox != 1)
694         if ((p_record = fopen(filename, "r"))) {
695                 fclose(p_record);
696                 SCAT(filename, "_2nd");
697         }
698                         
699         p_record = fopen(filename, "w");
700         if (!p_record) {
701                 PERROR("Port(%d) cannot record because file cannot be opened '%s'\n", p_serial, filename);
702                 return(0);
703         }
704         update_rxoff();
705         fduse++;
706
707         p_record_type = type;
708         p_record_vbox = vbox;
709         p_record_skip = skip;
710         p_record_length = 0;
711         switch(p_record_type) {
712                 case CODEC_MONO:
713                 case CODEC_STEREO:
714                 case CODEC_8BIT:
715                 ret = fwrite(dummyheader, sizeof(dummyheader), 1, p_record);
716                 break;
717
718                 case CODEC_LAW:
719                 break;
720         }
721         UCPY(p_record_filename, filename);
722
723         PDEBUG(DEBUG_PORT, "Port(%d) recording started with file name '%s'\n", p_serial, filename);
724         return(1);
725 }
726
727
728 /*
729  * close the recoding file, put header in front and rename
730  */
731 void Port::close_record(int beep, int mute)
732 {
733         static signed short beep_mono[256];
734         unsigned int size = 0, wsize = 0;
735         struct fmt fmt;
736         char filename[512], indexname[512];
737         FILE *fp;
738         int i, ii;
739         char number[256], callerid[256];
740         char *p;
741         struct caller_info callerinfo;
742         const char *valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_.-!$%&/()=+*;~";
743         int ret;
744
745         if (!p_record)
746                 return;
747         PDEBUG(DEBUG_PORT, "data still in record buffer: %d (dir %d)\n", (p_record_buffer_writep - p_record_buffer_readp) & RECORD_BUFFER_MASK, p_record_buffer_dir);
748
749         memcpy(&callerinfo, &p_callerinfo, sizeof(struct caller_info));
750 //      apply_callerid_restriction(p_record_anon_ignore, callerinfo.id, &callerinfo.ntype, &callerinfo.present, &callerinfo.screen, callerinfo.extension, callerinfo.name);
751
752         SCPY(number, p_dialinginfo.id);
753         SCPY(callerid, numberrize_callerinfo(callerinfo.id, callerinfo.ntype, options.national, options.international));
754         if (callerid[0] == '\0') {
755                 if (callerinfo.present == INFO_PRESENT_RESTRICTED)
756                         UCPY(callerid,"anonymous");
757                 else
758                         UCPY(callerid,"unknown");
759         }
760
761         /* change verboten digits */
762         p = callerid;
763         while((p=strchr(p,'*')))
764                 *(p++) = 'x';
765         p = callerid;
766         while((p=strchr(p,'/')))
767                 *(p++) = 'x';
768         p = number;
769         while((p=strchr(p,'*')))
770                 *(p++) = 'x';
771         p = number;
772         while((p=strchr(p,'/')))
773                 *(p++) = 'x';
774         i = 0;
775         ii = strlen(callerid);
776         while(i < ii) {
777                 if (!strchr(valid_chars, callerid[i]))
778                         callerid[i] = '_';
779                 i++;
780         }
781         i = 0;
782         ii = strlen(number);
783         while(i < ii) {
784                 if (!strchr(valid_chars, number[i]))
785                         number[i] = '_';
786                 i++;
787         }
788
789         /* mute */
790         if (mute && p_record_type==CODEC_MONO) {
791                 i = p_record_length;
792                 if (i > mute)
793                         i = mute;       
794                 fseek(p_record, -(i<<1), SEEK_END);
795                 p_record_length -= (i<<1);
796         }
797         /* add beep to the end of recording */
798         if (beep && p_record_type==CODEC_MONO) {
799                 i = 0;
800                 while(i < 256) {
801                         beep_mono[i] = (signed short)(sin((double)i / 5.688888888889 * 2.0 * 3.1415927) * 2000.0);
802                         i++;
803                 }
804                 i = 0;
805                 while(i < beep) {
806                         ret = fwrite(beep_mono, sizeof(beep_mono), 1, p_record);
807                         i += sizeof(beep_mono);
808                         p_record_length += sizeof(beep_mono);
809                 }
810         }
811
812         /* complete header */
813         switch(p_record_type) {
814                 case CODEC_MONO:
815                 case CODEC_STEREO:
816                 case CODEC_8BIT:
817                 /* cue */
818                 fprintf(p_record, "cue %c%c%c%c%c%c%c%c", 4, 0, 0, 0, 0,0,0,0);
819
820                 /* LIST */
821                 fprintf(p_record, "LIST%c%c%c%cadtl", 4, 0, 0, 0);
822
823                 /* go to header */
824                 fseek(p_record, 0, SEEK_SET);
825
826                 /* WAVEfmt xxxx(fmt-size)dataxxxx[data]cue xxxx0000LISTxxxxadtl*/
827                 size = p_record_length;
828                 wsize = 4+8+sizeof(fmt)+8+size+8+4+8+4;
829
830                 /* RIFF */
831                 fprintf(p_record, "RIFF%c%c%c%c", (unsigned char)(wsize&0xff), (unsigned char)((wsize>>8)&0xff), (unsigned char)((wsize>>16)&0xff), (unsigned char)(wsize>>24));
832
833                 /* WAVE */
834                 fprintf(p_record, "WAVE");
835
836                 /* fmt */
837                 fprintf(p_record, "fmt %c%c%c%c", (unsigned int)sizeof(fmt), 0, 0, 0);
838                 switch(p_record_type) {
839                         case CODEC_MONO:
840                         fmt.stereo = 1;
841                         fmt.channels = 1;
842                         fmt.sample_rate = 8000; /* samples/sec */
843                         fmt.data_rate = 16000; /* full data rate */
844                         fmt.bytes_sample = 2; /* all channels */
845                         fmt.bits_sample = 16; /* one channel */
846                         break;
847
848                         case CODEC_STEREO:
849                         fmt.stereo = 1;
850                         fmt.channels = 2;
851                         fmt.sample_rate = 8000; /* samples/sec */
852                         fmt.data_rate = 32000; /* full data rate */
853                         fmt.bytes_sample = 4; /* all channels */
854                         fmt.bits_sample = 16; /* one channel */
855                         break;
856
857                         case CODEC_8BIT:
858                         fmt.stereo = 1;
859                         fmt.channels = 1;
860                         fmt.sample_rate = 8000; /* samples/sec */
861                         fmt.data_rate = 8000; /* full data rate */
862                         fmt.bytes_sample = 1; /* all channels */
863                         fmt.bits_sample = 8; /* one channel */
864                         break;
865                 }
866                 ret = fwrite(&fmt, sizeof(fmt), 1, p_record);
867
868                 /* data */
869                 fprintf(p_record, "data%c%c%c%c", (unsigned char)(size&0xff), (unsigned char)((size>>8)&0xff), (unsigned char)((size>>16)&0xff), (unsigned char)(size>>24));
870
871                 /* rename file */
872                 if (p_record_vbox == 1)
873                         SPRINT(filename, "%s.wav", p_record_filename);
874                 else
875                         SPRINT(filename, "%s_%s-%s.wav", p_record_filename, callerid, number);
876                 break;
877
878                 case CODEC_LAW:
879                 /* rename file */
880                 if (p_record_vbox == 1)
881                         SPRINT(filename, "%s.isdn", p_record_filename);
882                 else
883                         SPRINT(filename, "%s_%s-%s.isdn", p_record_filename, callerid, number);
884                 break;
885         }
886
887         fclose(p_record);
888         fduse--;
889         p_record = NULL;
890         update_rxoff();
891
892         if (rename(p_record_filename, filename) < 0) {
893                 PERROR("Port(%d) cannot rename from '%s' to '%s'\n", p_serial, p_record_filename, filename);
894                 return;
895         }
896
897         PDEBUG(DEBUG_PORT, "Port(%d) recording is written and renamed to '%s' and must have the following size:%lu raw:%lu samples:%lu\n", p_serial, filename, wsize+8, size, size>>1);
898
899         if (p_record_vbox == 2) {
900                 SPRINT(indexname, "%s/%s/vbox/index", EXTENSION_DATA, p_record_extension);
901                 if ((fp = fopen(indexname,"a"))) {
902                         fduse++;
903
904                         /* remove path from file name */
905                         p = filename;
906                         while(strchr(p, '/'))
907                                 p = strchr(p, '/')+1;
908                         fprintf(fp, "%s %d %d %d %d %d %s\n", p, p_record_vbox_year, p_record_vbox_mon, p_record_vbox_mday, p_record_vbox_hour, p_record_vbox_min, callerid);
909
910                         fclose(fp);
911                         fduse--;
912                 } else {
913                         PERROR("Port(%d) cannot open index file '%s' to append.\n", p_serial, indexname);
914                 }
915
916                 /* send email with sample*/
917                 if (p_record_vbox_email[0]) {
918                         send_mail(p_record_vbox_email_file?filename:(char *)"", callerid, callerinfo.extension, callerinfo.name, p_record_vbox_email, p_record_vbox_year, p_record_vbox_mon, p_record_vbox_mday, p_record_vbox_hour, p_record_vbox_min, p_record_extension);
919                 }
920         }
921 }
922
923
924 /*
925  * recording function
926  * Records all data from down and from up into one single stream.
927  * Both streams may have gaps or jitter.
928  * A Jitter buffer for both streams is used to compensate jitter.
929  * 
930  * If one stream (dir) received packets, they are stored to a
931  * buffer to wait for the other stream (dir), so both streams can 
932  * be combined. If the buffer is full, it's content is written
933  * without mixing stream. (assuming only one stram (dir) exists.)
934  * A flag is used to indicate what stream is currently in buffer.
935  *
936  * NOTE: First stereo sample (odd) is from down, second is from up.
937  */
938 void Port::record(unsigned char *data, int length, int dir_fromup)
939 {
940         unsigned char write_buffer[1024], *d;
941         signed short *s;
942         int free, i, ii;
943         signed int sample;
944         int ret;
945
946         /* no recording */
947         if (!p_record || !length)
948                 return;
949
950         /* skip data from local caller (dtmf input) */
951         if (p_record_skip && !dir_fromup) {
952                 /* more to skip than we have */
953                 if (p_record_skip > length) {
954                         p_record_skip -= length;
955                         return;
956                 }
957                 /* less to skip */
958                 data += p_record_skip;
959                 length -= p_record_skip;
960                 p_record_skip = 0;
961         }
962
963 //printf("dir=%d len=%d\n", dir_fromup, length);
964
965         free = ((p_record_buffer_readp - p_record_buffer_writep - 1) & RECORD_BUFFER_MASK);
966
967 //PDEBUG(DEBUG_PORT, "record(data,%d,%d): free=%d, p_record_buffer_dir=%d, p_record_buffer_readp=%d, p_record_buffer_writep=%d.\n", length, dir_fromup, free, p_record_buffer_dir, p_record_buffer_readp, p_record_buffer_writep);
968
969         /* the buffer stores the same data stream */
970         if (dir_fromup == p_record_buffer_dir) {
971 same_again:
972
973 //printf("same free=%d length=%d\n", free, length);
974                 /* first write what we can to the buffer */
975                 while(free && length) {
976                         p_record_buffer[p_record_buffer_writep] = audio_law_to_s32[*data++];
977                         p_record_buffer_writep = (p_record_buffer_writep + 1) & RECORD_BUFFER_MASK;
978                         free--;
979                         length--;
980                 }
981                 /* all written, so we return */
982                 if (!length)
983                         return;
984                 /* still data left, buffer is full, so we need to write a chunk to file */
985                 switch(p_record_type) {
986                         case CODEC_MONO:
987                         s = (signed short *)write_buffer;
988                         i = 0;
989                         while(i < 256) {
990                                 *s++ = p_record_buffer[p_record_buffer_readp];
991                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
992                                 i++;
993                         }
994                         ret = fwrite(write_buffer, 512, 1, p_record);
995                         p_record_length += 512;
996                         break;
997
998                         case CODEC_STEREO:
999                         s = (signed short *)write_buffer;
1000                         if (p_record_buffer_dir) {
1001                                 i = 0;
1002                                 while(i < 256) {
1003                                         *s++ = 0; /* nothing from down */
1004                                         *s++ = p_record_buffer[p_record_buffer_readp];
1005                                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1006                                         i++;
1007                                 }
1008                         } else {
1009                                 i = 0;
1010                                 while(i < 256) {
1011                                         *s++ = p_record_buffer[p_record_buffer_readp];
1012                                         *s++ = 0; /* nothing from up */
1013                                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1014                                         i++;
1015                                 }
1016                         }
1017                         ret = fwrite(write_buffer, 1024, 1, p_record);
1018                         p_record_length += 1024;
1019                         break;
1020
1021                         case CODEC_8BIT:
1022                         d = write_buffer;
1023                         i = 0;
1024                         while(i < 256) {
1025                                 *d++ = ((unsigned short)(p_record_buffer[p_record_buffer_readp]+0x8000)) >> 8;
1026                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1027                                 i++;
1028                         }
1029                         ret = fwrite(write_buffer, 512, 1, p_record);
1030                         p_record_length += 512;
1031                         break;
1032
1033                         case CODEC_LAW:
1034                         d = write_buffer;
1035                         i = 0;
1036                         while(i < 256) {
1037                                 *d++ = audio_s16_to_law[p_record_buffer[p_record_buffer_readp] & 0xffff];
1038                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1039                                 i++;
1040                         }
1041                         ret = fwrite(write_buffer, 256, 1, p_record);
1042                         p_record_length += 256;
1043                         break;
1044                 }
1045                 /* because we still have data, we write again */
1046                 free += 256;
1047                 goto same_again;
1048         }
1049         /* the buffer stores the other stream */
1050         
1051 different_again:
1052         /* if buffer empty, change it */
1053         if (p_record_buffer_readp == p_record_buffer_writep) {
1054                 p_record_buffer_dir = dir_fromup;
1055                 goto same_again;
1056         }
1057         /* how much data can we mix ? */
1058         ii = (p_record_buffer_writep - p_record_buffer_readp) & RECORD_BUFFER_MASK;
1059         if (length < ii)
1060                 ii = length;
1061
1062         if (ii > 256)
1063                 ii = 256;
1064 //printf("same ii=%d length=%d\n", ii, length);
1065 //PDEBUG(DEBUG_PORT, "record(data,%d,%d): free=%d, p_record_buffer_dir=%d, p_record_buffer_readp=%d, p_record_buffer_writep=%d: mixing %d bytes.\n", length, dir_fromup, free, p_record_buffer_dir, p_record_buffer_readp, p_record_buffer_writep, ii);
1066
1067         /* write data mixed with the buffer */
1068         switch(p_record_type) {
1069                 case CODEC_MONO:
1070                 s = (signed short *)write_buffer;
1071                 i = 0;
1072                 while(i < ii) {
1073                         sample = p_record_buffer[p_record_buffer_readp]
1074                                 + audio_law_to_s32[*data++];
1075                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1076                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1077                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1078                         *s++ = sample;
1079                         i++;
1080                 }
1081                 ret = fwrite(write_buffer, ii<<1, 1, p_record);
1082                 p_record_length += (ii<<1);
1083                 break;
1084                 
1085                 case CODEC_STEREO:
1086                 s = (signed short *)write_buffer;
1087                 if (p_record_buffer_dir) {
1088                         i = 0;
1089                         while(i < ii) {
1090                                 *s++ = audio_law_to_s32[*data++];
1091                                 *s++ = p_record_buffer[p_record_buffer_readp];
1092                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1093                                 i++;
1094                         }
1095                 } else {
1096                         i = 0;
1097                         while(i < ii) {
1098                                 *s++ = p_record_buffer[p_record_buffer_readp];
1099                                 *s++ = audio_law_to_s32[*data++];
1100                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1101                                 i++;
1102                         }
1103                 }
1104                 ret = fwrite(write_buffer, ii<<2, 1, p_record);
1105                 p_record_length += (ii<<2);
1106                 break;
1107                 
1108                 case CODEC_8BIT:
1109                 d = write_buffer;
1110                 i = 0;
1111                 while(i < ii) {
1112                         sample = p_record_buffer[p_record_buffer_readp]
1113                                 + audio_law_to_s32[*data++];
1114                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1115                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1116                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1117                         *d++ = (sample+0x8000) >> 8;
1118                         i++;
1119                 }
1120                 ret = fwrite(write_buffer, ii, 1, p_record);
1121                 p_record_length += ii;
1122                 break;
1123                 
1124                 case CODEC_LAW:
1125                 d = write_buffer;
1126                 i = 0;
1127                 while(i < ii) {
1128                         sample = p_record_buffer[p_record_buffer_readp]
1129                                 + audio_law_to_s32[*data++];
1130                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1131                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1132                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1133                         *d++ = audio_s16_to_law[sample & 0xffff];
1134                         i++;
1135                 }
1136                 ret = fwrite(write_buffer, ii, 1, p_record);
1137                 p_record_length += ii;
1138                 break;
1139         }
1140         length -= ii;
1141         /* still data */
1142         if (length)
1143                 goto different_again;
1144         /* no data (maybe buffer) */
1145         return;
1146
1147 }
1148
1149 void Port::update_rxoff(void)
1150 {
1151 }
1152
1153 void Port::update_load(void)
1154 {
1155 }
1156