32184a849a3e545d1d27d0b9f5f8ea352f7f309c
[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                 ret = fwrite(dummyheader, sizeof(dummyheader), 1, p_record);
772                 break;
773
774                 case CODEC_LAW:
775                 break;
776         }
777         UCPY(p_record_filename, filename);
778
779         PDEBUG(DEBUG_PORT, "Port(%d) recording started with file name '%s'\n", p_serial, filename);
780         return(1);
781 }
782
783
784 /*
785  * close the recoding file, put header in front and rename
786  */
787 void Port::close_record(int beep, int mute)
788 {
789         static signed short beep_mono[256];
790         unsigned int size = 0, wsize = 0;
791         struct fmt fmt;
792         char filename[512], indexname[512];
793         FILE *fp;
794         int i, ii;
795         char number[256], callerid[256];
796         char *p;
797         struct caller_info callerinfo;
798         const char *valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_.-!$%&/()=+*;~";
799         int __attribute__((__unused__)) ret;
800
801         if (!p_record)
802                 return;
803         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);
804
805         memcpy(&callerinfo, &p_callerinfo, sizeof(struct caller_info));
806 //      apply_callerid_restriction(p_record_anon_ignore, callerinfo.id, &callerinfo.ntype, &callerinfo.present, &callerinfo.screen, callerinfo.extension, callerinfo.name);
807
808         SCPY(number, p_dialinginfo.id);
809         SCPY(callerid, numberrize_callerinfo(callerinfo.id, callerinfo.ntype, options.national, options.international));
810         if (callerid[0] == '\0') {
811                 if (callerinfo.present == INFO_PRESENT_RESTRICTED)
812                         UCPY(callerid,"anonymous");
813                 else
814                         UCPY(callerid,"unknown");
815         }
816
817         /* change verboten digits */
818         p = callerid;
819         while((p=strchr(p,'*')))
820                 *(p++) = 'x';
821         p = callerid;
822         while((p=strchr(p,'/')))
823                 *(p++) = 'x';
824         p = number;
825         while((p=strchr(p,'*')))
826                 *(p++) = 'x';
827         p = number;
828         while((p=strchr(p,'/')))
829                 *(p++) = 'x';
830         i = 0;
831         ii = strlen(callerid);
832         while(i < ii) {
833                 if (!strchr(valid_chars, callerid[i]))
834                         callerid[i] = '_';
835                 i++;
836         }
837         i = 0;
838         ii = strlen(number);
839         while(i < ii) {
840                 if (!strchr(valid_chars, number[i]))
841                         number[i] = '_';
842                 i++;
843         }
844
845         /* mute */
846         if (mute && p_record_type==CODEC_MONO) {
847                 i = p_record_length;
848                 if (i > mute)
849                         i = mute;       
850                 fseek(p_record, -(i<<1), SEEK_END);
851                 p_record_length -= (i<<1);
852         }
853         /* add beep to the end of recording */
854         if (beep && p_record_type==CODEC_MONO) {
855                 i = 0;
856                 while(i < 256) {
857                         beep_mono[i] = (signed short)(sin((double)i / 5.688888888889 * 2.0 * 3.1415927) * 2000.0);
858                         i++;
859                 }
860                 i = 0;
861                 while(i < beep) {
862                         ret = fwrite(beep_mono, sizeof(beep_mono), 1, p_record);
863                         i += sizeof(beep_mono);
864                         p_record_length += sizeof(beep_mono);
865                 }
866         }
867
868         /* complete header */
869         switch(p_record_type) {
870                 case CODEC_MONO:
871                 case CODEC_STEREO:
872                 case CODEC_8BIT:
873                 /* cue */
874                 fprintf(p_record, "cue %c%c%c%c%c%c%c%c", 4, 0, 0, 0, 0,0,0,0);
875
876                 /* LIST */
877                 fprintf(p_record, "LIST%c%c%c%cadtl", 4, 0, 0, 0);
878
879                 /* go to header */
880                 fseek(p_record, 0, SEEK_SET);
881
882                 /* WAVEfmt xxxx(fmt-size)dataxxxx[data]cue xxxx0000LISTxxxxadtl*/
883                 size = p_record_length;
884                 wsize = 4+8+sizeof(fmt)+8+size+8+4+8+4;
885
886                 /* RIFF */
887                 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));
888
889                 /* WAVE */
890                 fprintf(p_record, "WAVE");
891
892                 /* fmt */
893                 fprintf(p_record, "fmt %c%c%c%c", (unsigned int)sizeof(fmt), 0, 0, 0);
894                 switch(p_record_type) {
895                         case CODEC_MONO:
896                         fmt.stereo = 1;
897                         fmt.channels = 1;
898                         fmt.sample_rate = 8000; /* samples/sec */
899                         fmt.data_rate = 16000; /* full data rate */
900                         fmt.bytes_sample = 2; /* all channels */
901                         fmt.bits_sample = 16; /* one channel */
902                         break;
903
904                         case CODEC_STEREO:
905                         fmt.stereo = 1;
906                         fmt.channels = 2;
907                         fmt.sample_rate = 8000; /* samples/sec */
908                         fmt.data_rate = 32000; /* full data rate */
909                         fmt.bytes_sample = 4; /* all channels */
910                         fmt.bits_sample = 16; /* one channel */
911                         break;
912
913                         case CODEC_8BIT:
914                         fmt.stereo = 1;
915                         fmt.channels = 1;
916                         fmt.sample_rate = 8000; /* samples/sec */
917                         fmt.data_rate = 8000; /* full data rate */
918                         fmt.bytes_sample = 1; /* all channels */
919                         fmt.bits_sample = 8; /* one channel */
920                         break;
921                 }
922                 ret = fwrite(&fmt, sizeof(fmt), 1, p_record);
923
924                 /* data */
925                 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));
926
927                 /* rename file */
928                 if (p_record_vbox == 1)
929                         SPRINT(filename, "%s.wav", p_record_filename);
930                 else
931                         SPRINT(filename, "%s_%s-%s.wav", p_record_filename, callerid, number);
932                 break;
933
934                 case CODEC_LAW:
935                 /* rename file */
936                 if (p_record_vbox == 1)
937                         SPRINT(filename, "%s.isdn", p_record_filename);
938                 else
939                         SPRINT(filename, "%s_%s-%s.isdn", p_record_filename, callerid, number);
940                 break;
941         }
942
943         fclose(p_record);
944         fduse--;
945         p_record = NULL;
946         update_rxoff();
947
948         if (rename(p_record_filename, filename) < 0) {
949                 PERROR("Port(%d) cannot rename from '%s' to '%s'\n", p_serial, p_record_filename, filename);
950                 return;
951         }
952
953         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);
954
955         if (p_record_vbox == 2) {
956                 SPRINT(indexname, "%s/%s/vbox/index", EXTENSION_DATA, p_record_extension);
957                 if ((fp = fopen(indexname,"a"))) {
958                         fduse++;
959
960                         /* remove path from file name */
961                         p = filename;
962                         while(strchr(p, '/'))
963                                 p = strchr(p, '/')+1;
964                         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);
965
966                         fclose(fp);
967                         fduse--;
968                 } else {
969                         PERROR("Port(%d) cannot open index file '%s' to append.\n", p_serial, indexname);
970                 }
971
972                 /* send email with sample*/
973                 if (p_record_vbox_email[0]) {
974                         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);
975                 }
976         }
977 }
978
979
980 /*
981  * recording function
982  * Records all data from down and from up into one single stream.
983  * Both streams may have gaps or jitter.
984  * A Jitter buffer for both streams is used to compensate jitter.
985  * 
986  * If one stream (dir) received packets, they are stored to a
987  * buffer to wait for the other stream (dir), so both streams can 
988  * be combined. If the buffer is full, it's content is written
989  * without mixing stream. (assuming only one stram (dir) exists.)
990  * A flag is used to indicate what stream is currently in buffer.
991  *
992  * NOTE: First stereo sample (odd) is from down, second is from up.
993  */
994 void Port::record(unsigned char *data, int length, int dir_fromup)
995 {
996         unsigned char write_buffer[1024], *d;
997         signed short *s;
998         int free, i, ii;
999         signed int sample;
1000         int __attribute__((__unused__)) ret;
1001
1002         /* no recording */
1003         if (!p_record || !length)
1004                 return;
1005
1006         /* skip data from local caller (dtmf input) */
1007         if (p_record_skip && !dir_fromup) {
1008                 /* more to skip than we have */
1009                 if (p_record_skip > length) {
1010                         p_record_skip -= length;
1011                         return;
1012                 }
1013                 /* less to skip */
1014                 data += p_record_skip;
1015                 length -= p_record_skip;
1016                 p_record_skip = 0;
1017         }
1018
1019 //printf("dir=%d len=%d\n", dir_fromup, length);
1020
1021         free = ((p_record_buffer_readp - p_record_buffer_writep - 1) & RECORD_BUFFER_MASK);
1022
1023 //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);
1024
1025         /* the buffer stores the same data stream */
1026         if (dir_fromup == p_record_buffer_dir) {
1027 same_again:
1028
1029 //printf("same free=%d length=%d\n", free, length);
1030                 /* first write what we can to the buffer */
1031                 while(free && length) {
1032                         p_record_buffer[p_record_buffer_writep] = audio_law_to_s32[*data++];
1033                         p_record_buffer_writep = (p_record_buffer_writep + 1) & RECORD_BUFFER_MASK;
1034                         free--;
1035                         length--;
1036                 }
1037                 /* all written, so we return */
1038                 if (!length)
1039                         return;
1040                 /* still data left, buffer is full, so we need to write a chunk to file */
1041                 switch(p_record_type) {
1042                         case CODEC_MONO:
1043                         s = (signed short *)write_buffer;
1044                         i = 0;
1045                         while(i < 256) {
1046                                 *s++ = p_record_buffer[p_record_buffer_readp];
1047                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1048                                 i++;
1049                         }
1050                         ret = fwrite(write_buffer, 512, 1, p_record);
1051                         p_record_length += 512;
1052                         break;
1053
1054                         case CODEC_STEREO:
1055                         s = (signed short *)write_buffer;
1056                         if (p_record_buffer_dir) {
1057                                 i = 0;
1058                                 while(i < 256) {
1059                                         *s++ = 0; /* nothing from down */
1060                                         *s++ = p_record_buffer[p_record_buffer_readp];
1061                                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1062                                         i++;
1063                                 }
1064                         } else {
1065                                 i = 0;
1066                                 while(i < 256) {
1067                                         *s++ = p_record_buffer[p_record_buffer_readp];
1068                                         *s++ = 0; /* nothing from up */
1069                                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1070                                         i++;
1071                                 }
1072                         }
1073                         ret = fwrite(write_buffer, 1024, 1, p_record);
1074                         p_record_length += 1024;
1075                         break;
1076
1077                         case CODEC_8BIT:
1078                         d = write_buffer;
1079                         i = 0;
1080                         while(i < 256) {
1081                                 *d++ = ((unsigned short)(p_record_buffer[p_record_buffer_readp]+0x8000)) >> 8;
1082                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1083                                 i++;
1084                         }
1085                         ret = fwrite(write_buffer, 512, 1, p_record);
1086                         p_record_length += 512;
1087                         break;
1088
1089                         case CODEC_LAW:
1090                         d = write_buffer;
1091                         i = 0;
1092                         while(i < 256) {
1093                                 *d++ = audio_s16_to_law[p_record_buffer[p_record_buffer_readp] & 0xffff];
1094                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1095                                 i++;
1096                         }
1097                         ret = fwrite(write_buffer, 256, 1, p_record);
1098                         p_record_length += 256;
1099                         break;
1100                 }
1101                 /* because we still have data, we write again */
1102                 free += 256;
1103                 goto same_again;
1104         }
1105         /* the buffer stores the other stream */
1106         
1107 different_again:
1108         /* if buffer empty, change it */
1109         if (p_record_buffer_readp == p_record_buffer_writep) {
1110                 p_record_buffer_dir = dir_fromup;
1111                 goto same_again;
1112         }
1113         /* how much data can we mix ? */
1114         ii = (p_record_buffer_writep - p_record_buffer_readp) & RECORD_BUFFER_MASK;
1115         if (length < ii)
1116                 ii = length;
1117
1118         if (ii > 256)
1119                 ii = 256;
1120 //printf("same ii=%d length=%d\n", ii, length);
1121 //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);
1122
1123         /* write data mixed with the buffer */
1124         switch(p_record_type) {
1125                 case CODEC_MONO:
1126                 s = (signed short *)write_buffer;
1127                 i = 0;
1128                 while(i < ii) {
1129                         sample = p_record_buffer[p_record_buffer_readp]
1130                                 + audio_law_to_s32[*data++];
1131                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1132                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1133                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1134                         *s++ = sample;
1135                         i++;
1136                 }
1137                 ret = fwrite(write_buffer, ii<<1, 1, p_record);
1138                 p_record_length += (ii<<1);
1139                 break;
1140                 
1141                 case CODEC_STEREO:
1142                 s = (signed short *)write_buffer;
1143                 if (p_record_buffer_dir) {
1144                         i = 0;
1145                         while(i < ii) {
1146                                 *s++ = audio_law_to_s32[*data++];
1147                                 *s++ = p_record_buffer[p_record_buffer_readp];
1148                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1149                                 i++;
1150                         }
1151                 } else {
1152                         i = 0;
1153                         while(i < ii) {
1154                                 *s++ = p_record_buffer[p_record_buffer_readp];
1155                                 *s++ = audio_law_to_s32[*data++];
1156                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1157                                 i++;
1158                         }
1159                 }
1160                 ret = fwrite(write_buffer, ii<<2, 1, p_record);
1161                 p_record_length += (ii<<2);
1162                 break;
1163                 
1164                 case CODEC_8BIT:
1165                 d = write_buffer;
1166                 i = 0;
1167                 while(i < ii) {
1168                         sample = p_record_buffer[p_record_buffer_readp]
1169                                 + audio_law_to_s32[*data++];
1170                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1171                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1172                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1173                         *d++ = (sample+0x8000) >> 8;
1174                         i++;
1175                 }
1176                 ret = fwrite(write_buffer, ii, 1, p_record);
1177                 p_record_length += ii;
1178                 break;
1179                 
1180                 case CODEC_LAW:
1181                 d = write_buffer;
1182                 i = 0;
1183                 while(i < ii) {
1184                         sample = p_record_buffer[p_record_buffer_readp]
1185                                 + audio_law_to_s32[*data++];
1186                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1187                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1188                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1189                         *d++ = audio_s16_to_law[sample & 0xffff];
1190                         i++;
1191                 }
1192                 ret = fwrite(write_buffer, ii, 1, p_record);
1193                 p_record_length += ii;
1194                 break;
1195         }
1196         length -= ii;
1197         /* still data */
1198         if (length)
1199                 goto different_again;
1200         /* no data (maybe buffer) */
1201         return;
1202
1203 }
1204
1205 void Port::tap(unsigned char *data, int length, int dir_fromup)
1206 {
1207 }
1208
1209 void Port::update_rxoff(void)
1210 {
1211 }
1212
1213 void Port::update_load(void)
1214 {
1215 }
1216
1217
1218 /*
1219  * bridge handling
1220  */
1221
1222 int bridge_timeout(struct lcr_timer *timer, void *instance, int index);
1223
1224 static void remove_bridge(struct port_bridge *bridge, class Port *port)
1225 {
1226         struct port_bridge **temp = &p_bridge_first;
1227         while (*temp) {
1228                 if (*temp == bridge) {
1229                         struct port_bridge_member **memberp = &bridge->first, *member;
1230
1231                         /* loop until we are found */
1232                         while(*memberp) {
1233                                 if ((*memberp)->port == port) {
1234                                         member = *memberp;
1235                                         *memberp = member->next;
1236                                         FREE(member, sizeof(struct port_bridge_member));
1237                                         memuse--;
1238 #ifndef TEST_CONFERENCE
1239                                         if (bridge->first && bridge->first->next && !bridge->first->next->next) {
1240 #else
1241                                         if (bridge->first && !bridge->first->next) {
1242 #endif
1243                                                 PDEBUG(DEBUG_PORT, "bridge %u is no conference anymore\n", bridge->bridge_id);
1244                                                 del_timer(&bridge->timer);
1245                                         }
1246                                         break;
1247                                 }
1248                                 memberp = &((*memberp)->next);
1249                         }
1250                         /* if bridge is empty, remove it */
1251                         if (bridge->first == NULL) {
1252                                 PDEBUG(DEBUG_PORT, "Remove bridge %u\n", bridge->bridge_id);
1253                                 *temp = bridge->next;
1254                                 FREE(bridge, sizeof(struct port_bridge));
1255                                 memuse--;
1256                         }
1257                         return;
1258                 }
1259                 temp = &((*temp)->next);
1260         }
1261         PERROR("Bridge %p not found in list\n", bridge);
1262 }
1263
1264 void Port::bridge(unsigned int bridge_id)
1265 {
1266         struct port_bridge_member **memberp;
1267
1268         /* Remove bridge, if we leave bridge or if we join a different bridge. */
1269         if (p_bridge && bridge_id != p_bridge->bridge_id) {
1270                 PDEBUG(DEBUG_PORT, "Remove port %u from bridge %u, because out new bridge is %u\n", p_serial, p_bridge->bridge_id, bridge_id);
1271                 remove_bridge(p_bridge, this);
1272                 p_bridge = NULL;
1273         }
1274
1275         /* if we leave bridge */
1276         if (!bridge_id)
1277                 return;
1278
1279         /* find bridge */
1280         if (!p_bridge) {
1281                 struct port_bridge *temp = p_bridge_first;
1282
1283                 while (temp) {
1284                         if (temp->bridge_id == bridge_id)
1285                                 break;
1286                         temp = temp->next;
1287                 }
1288                 p_bridge = temp;
1289                 if (p_bridge)
1290                         PDEBUG(DEBUG_PORT, "Port %d found existing bridge %u.\n", p_serial, p_bridge->bridge_id);
1291         }
1292
1293         /* create bridge */
1294         if (!p_bridge) {
1295                 struct port_bridge **temp = &p_bridge_first;
1296
1297                 p_bridge = (struct port_bridge *) MALLOC(sizeof(struct port_bridge));
1298                 memuse++;
1299                 p_bridge->bridge_id = bridge_id;
1300
1301                 /* attach bridge instance to list */
1302                 while (*temp)
1303                         temp = &((*temp)->next);
1304                 *temp = p_bridge;
1305                 PDEBUG(DEBUG_PORT, "Port %d creating not existing bridge %u.\n", p_serial, p_bridge->bridge_id);
1306         }
1307
1308         /* attach to bridge */
1309         memberp = &p_bridge->first;
1310         while(*memberp) {
1311                 if ((*memberp)->port == this) {
1312                         /* already joined */
1313                         return;
1314                 }
1315                 memberp = &((*memberp)->next);
1316         }
1317         *memberp = (struct port_bridge_member *) MALLOC(sizeof(struct port_bridge_member));
1318         memuse++;
1319         (*memberp)->port = this;
1320         /* check if bridge becomes a conference */
1321 #ifndef TEST_CONFERENCE
1322         if (p_bridge->first->next && p_bridge->first->next->next && !p_bridge->first->next->next->next) {
1323                 p_bridge->first->next->next->write_p = 0;
1324                 p_bridge->first->next->next->min_space = 0;
1325                 memset(p_bridge->first->next->next->buffer, silence, sizeof((*memberp)->buffer));
1326 #else
1327         if (p_bridge->first->next && !p_bridge->first->next->next) {
1328 #endif
1329                 p_bridge->first->next->write_p = 0;
1330                 p_bridge->first->next->min_space = 0;
1331                 memset(p_bridge->first->next->buffer, silence, sizeof((*memberp)->buffer));
1332                 p_bridge->first->write_p = 0;
1333                 p_bridge->first->min_space = 0;
1334                 memset(p_bridge->first->buffer, silence, sizeof((*memberp)->buffer));
1335                 memset(p_bridge->sum_buffer, 0, sizeof(p_bridge->sum_buffer));
1336                 p_bridge->read_p = 0;
1337                 add_timer(&p_bridge->timer, bridge_timeout, p_bridge, 0);
1338                 schedule_timer(&p_bridge->timer, 0, 20000); /* 20 MS */
1339                 p_bridge->sample_count = 0;
1340                 PDEBUG(DEBUG_PORT, "bridge %u became a conference\n", p_bridge->bridge_id);
1341         }
1342 }
1343
1344 /* send data to remote Port or add to sum buffer */
1345 int Port::bridge_tx(unsigned char *data, int len)
1346 {
1347         int write_p, space;
1348         struct port_bridge_member *member;
1349         signed long *sum;
1350         unsigned char *buf;
1351
1352 #ifdef WITH_VOOTP
1353         if (p_vootp)
1354                 vootp_encrypt_stream(p_vootp, data, len);
1355 #endif
1356
1357         /* less than two ports, so drop */
1358         if (!p_bridge || !p_bridge->first || !p_bridge->first->next)
1359                 return -EIO;
1360 #ifndef TEST_CONFERENCE
1361         /* two ports, so bridge */
1362         if (!p_bridge->first->next->next) {
1363                 if (p_bridge->first->port == this)
1364                         return p_bridge->first->next->port->bridge_rx(data, len);
1365                 if (p_bridge->first->next->port == this)
1366                         return p_bridge->first->port->bridge_rx(data, len);
1367                 return -EINVAL;
1368         }
1369 #endif
1370         /* more than two ports... */
1371         member = p_bridge->first;
1372         while (member) {
1373                 if (member->port == this)
1374                         break;
1375                 member = member->next;
1376         }
1377         if (!member)
1378                 return -EINVAL;
1379         write_p = member->write_p;
1380         /* calculate space, so write pointer will not overrun (or reach) read pointer in ring buffer */
1381         space = (p_bridge->read_p - write_p - 1) & (BRIDGE_BUFFER - 1);
1382         /* clip len, if it does not fit */
1383         if (space < len)
1384                 len = space;
1385         /* apply audio samples to sum buffer */
1386         sum = p_bridge->sum_buffer;
1387         buf = member->buffer;
1388         while (len--) {
1389                 sum[write_p] += audio_law_to_s32[*data];
1390                 buf[write_p] = *data++;
1391                 write_p = (write_p + 1) & (BRIDGE_BUFFER - 1);
1392         }
1393         /* raise write pointer */
1394         member->write_p = write_p;
1395
1396         return 0;
1397 }
1398
1399 int bridge_timeout(struct lcr_timer *timer, void *instance, int index)
1400 {
1401         struct port_bridge *bridge = (struct port_bridge *)instance;
1402         struct port_bridge_member *member = bridge->first;
1403         unsigned long long timer_time;
1404         signed long *sum, sample;
1405         unsigned char buffer[160], *buf, *d;
1406         int i, read_p, space;
1407         
1408         bridge->sample_count += 160;
1409
1410         /* schedule exactly 20ms from last schedule */
1411         timer_time = timer->timeout.tv_sec * MICRO_SECONDS + timer->timeout.tv_usec;
1412         timer_time += 20000; /* 20 MS */
1413         timer->timeout.tv_sec = timer_time / MICRO_SECONDS;
1414         timer->timeout.tv_usec = timer_time % MICRO_SECONDS;
1415         timer->active = 1;
1416
1417         while (member) {
1418                 /* calculate transmit data */
1419                 read_p = bridge->read_p;
1420                 sum = bridge->sum_buffer;
1421                 buf = member->buffer;
1422                 d = buffer;
1423                 for (i = 0; i < 160; i++) {
1424                         sample = sum[read_p];
1425                         sample -= audio_law_to_s32[buf[read_p]];
1426                         buf[read_p] = silence;
1427                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1428                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1429                         *d++ = audio_s16_to_law[sample & 0xffff];
1430                         read_p = (read_p + 1) & (BRIDGE_BUFFER - 1);
1431                 }
1432                 /* send data */
1433                 member->port->bridge_rx(buffer, 160);
1434                 /* raise write pointer, if read pointer would overrun them */
1435                 space = ((member->write_p - bridge->read_p) & (BRIDGE_BUFFER - 1)) - 160;
1436                 if (space < 0) {
1437                         space = 0;
1438                         member->write_p = read_p;
1439 //                      PDEBUG(DEBUG_PORT, "bridge %u member %d has buffer underrun\n", bridge->bridge_id, member->port->p_serial);
1440                 }
1441                 /* find minimum delay */
1442                 if (space < member->min_space)
1443                         member->min_space = space;
1444                 /* check if we should reduce buffer */
1445                 if (bridge->sample_count >= 8000*5) {
1446                         /* reduce buffer by minimum delay */
1447 //                      PDEBUG(DEBUG_PORT, "bridge %u member %d has min space of %d samples\n", bridge->bridge_id, member->port->p_serial, member->min_space);
1448                         member->write_p = (member->write_p - member->min_space) & (BRIDGE_BUFFER - 1);
1449                         member->min_space = 1000000; /* infinite */
1450                 }
1451                 member = member->next;
1452         }
1453
1454         /* clear sample data */
1455         read_p = bridge->read_p;
1456         sum = bridge->sum_buffer;
1457         for (i = 0; i < 160; i++) {
1458                 sum[read_p] = 0;
1459                 read_p = (read_p + 1) & (BRIDGE_BUFFER - 1);
1460         }
1461
1462         /* raise read pointer */
1463         bridge->read_p = read_p;
1464
1465         if (bridge->sample_count >= 8000*5)
1466                 bridge->sample_count = 0;
1467
1468         return 0;
1469 }
1470
1471
1472 /* receive data from remote Port */
1473 int Port::bridge_rx(unsigned char *data, int len)
1474 {
1475
1476 #ifdef WITH_VOOTP
1477         if (p_vootp)
1478                 vootp_decrypt_stream(p_vootp, data, len);
1479 #endif
1480
1481         return 0;
1482 }
1483
1484 #ifdef WITH_VOOTP
1485 static void vootp_info(void *priv, const char *text)
1486 {
1487         class Port *port = (class Port *)priv;
1488         char display[strlen(text) + 1];
1489
1490         SCPY(display, text);
1491         if (display[0])
1492                 display[strlen(display) - 1] = '\0';
1493
1494         port->set_display(display);
1495 }
1496
1497 void Port::set_vootp(struct param_vootp *vootp)
1498 {
1499         if (p_vootp) {
1500                 vootp_destroy(p_vootp);
1501                 p_vootp = NULL;
1502         }
1503         if (vootp->enable) {
1504                 p_vootp = vootp_create(this, (options.law=='a'), options.otp_dir, NULL, NULL, vootp->id, vootp_info);
1505 //              vootp_loglevel(VOOTP_LOGL_DEBUG);
1506                 if (!p_vootp) {
1507                         struct lcr_msg *message;
1508
1509                         message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_VOOTP);
1510                         message->param.vootp.failed = 1;
1511                         message_put(message);
1512                 }
1513         }
1514 }
1515 #endif