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