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