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