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