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