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