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