fixes
[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 <stdio.h>
49 #include <string.h>
50 #include <stdlib.h>
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <fcntl.h>
54 #include <unistd.h>
55 #include <errno.h>
56 #include <math.h>
57 #include "main.h"
58
59 #define SHORT_MIN -32768
60 #define SHORT_MAX 32767
61
62 class Port *port_first = NULL;
63
64 unsigned long port_serial = 1; /* must be 1, because 0== no port */
65
66
67 /* free epointlist relation
68  */
69 void Port::free_epointlist(struct epoint_list *epointlist)
70 {
71         struct epoint_list *temp, **tempp;
72
73         temp = p_epointlist;
74         tempp = &p_epointlist;
75         while(temp)
76         {
77                 if (temp == epointlist)
78                         break;
79
80                 tempp = &temp->next;
81                 temp = temp->next;
82         }
83         if (temp == 0)
84         {
85                 PERROR("SOFTWARE ERROR: epointlist not in port's list.\n");
86                 return;
87         }
88         /* detach */
89         *tempp=temp->next;
90
91         /* free */
92         PDEBUG(DEBUG_EPOINT, "PORT(%d) removed epoint from port\n", p_serial);
93         FREE(temp, sizeof(struct epoint_list));
94         ememuse--;
95 }
96
97
98 void Port::free_epointid(unsigned long epoint_id)
99 {
100         struct epoint_list *temp, **tempp;
101
102         temp = p_epointlist;
103         tempp = &p_epointlist;
104         while(temp)
105         {
106                 if (temp->epoint_id == epoint_id)
107                         break;
108
109                 tempp = &temp->next;
110                 temp = temp->next;
111         }
112         if (temp == 0)
113         {
114                 PERROR("epoint_id not in port's list.\n");
115                 return;
116         }
117         /* detach */
118         *tempp=temp->next;
119
120         /* free */
121         PDEBUG(DEBUG_EPOINT, "PORT(%d) removed epoint from port\n", p_serial);
122         FREE(temp, sizeof(struct epoint_list));
123         ememuse--;
124 }
125
126
127 /* create new epointlist relation
128  */
129 struct epoint_list *Port::epointlist_new(unsigned long epoint_id)
130 {
131         struct epoint_list *epointlist, **epointlistpointer;
132
133         /* epointlist structure */
134         epointlist = (struct epoint_list *)MALLOC(sizeof(struct epoint_list));
135         if (!epointlist)
136                 FATAL("No memory for epointlist\n");
137         ememuse++;
138         PDEBUG(DEBUG_EPOINT, "PORT(%d) allocating epoint_list.\n", p_serial);
139
140         /* add epoint_list to chain */
141         epointlist->next = NULL;
142         epointlistpointer = &p_epointlist;
143         while(*epointlistpointer)
144                 epointlistpointer = &((*epointlistpointer)->next);
145         *epointlistpointer = epointlist;
146
147         /* link to epoint */
148         epointlist->epoint_id = epoint_id;
149         epointlist->active = 1;
150
151         return(epointlist);
152 }
153
154
155 /*
156  * port constructor
157  */
158 Port::Port(int type, char *portname, struct port_settings *settings)
159 {
160         class Port *temp, **tempp;
161
162         PDEBUG(DEBUG_PORT, "new port of type %d, name '%s'\n", type, portname);
163
164         /* initialize object */
165         if (settings)
166                 memcpy(&p_settings, settings, sizeof(struct port_settings));
167         else
168         {
169                 memset(&p_settings, 0, sizeof(p_settings));
170                 SCPY(p_settings.tones_dir, options.tones_dir);
171         }
172         SCPY(p_name, portname);
173         SCPY(p_tone_dir, p_settings.tones_dir); // just to be sure
174         p_type = type;
175         p_serial = port_serial++;
176         p_tone_fh = -1;
177         p_tone_fetched = NULL;
178         p_tone_name[0] = '\0';
179         p_state = PORT_STATE_IDLE;
180         p_epointlist = NULL;
181         memset(&p_callerinfo, 0, sizeof(p_callerinfo));
182         memset(&p_dialinginfo, 0, sizeof(p_dialinginfo));
183         memset(&p_connectinfo, 0, sizeof(p_connectinfo));
184         memset(&p_redirinfo, 0, sizeof(p_redirinfo));
185         memset(&p_capainfo, 0, sizeof(p_capainfo));
186         p_echotest = 0;
187
188         /* call recording */
189         p_record = NULL;
190         p_record_type = 0;
191         p_record_length = 0;
192         p_record_skip = 0;
193         p_record_filename[0] = '\0';
194         p_record_buffer_readp = 0;
195         p_record_buffer_writep = 0;
196         p_record_buffer_dir = 0;
197
198         /* append port to chain */
199         next = NULL;
200         temp = port_first;
201         tempp = &port_first;
202         while(temp)
203         {
204                 tempp = &temp->next;
205                 temp = temp->next;
206         }
207         *tempp = this;
208
209         classuse++;
210 }
211
212
213 /*
214  * port destructor
215  */
216 Port::~Port(void)
217 {
218         class Port *temp, **tempp;
219         struct message *message;
220
221         if (p_record)
222                 close_record(0, 0);
223
224         classuse--;
225
226         PDEBUG(DEBUG_PORT, "removing port of type %d, name '%s'\n", p_type, p_name);
227
228         /* disconnect port from endpoint */
229         while(p_epointlist)
230         {
231                 /* send disconnect */
232                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
233                 message->param.disconnectinfo.cause = 16;
234                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
235                 message_put(message);
236                 /* remove endpoint */
237                 free_epointlist(p_epointlist);
238         }
239
240         /* remove port from chain */
241         temp=port_first;
242         tempp=&port_first;
243         while(temp)
244         {
245                 if (temp == this)
246                         break;
247                 tempp = &temp->next;
248                 temp = temp->next;
249         }
250         if (temp == NULL)
251                 FATAL("PORT(%s) port not in port's list.\n", p_name);
252         /* detach */
253         *tempp=this->next;
254
255         /* close open tones file */
256         if (p_tone_fh >= 0)
257         {
258                 close(p_tone_fh);
259                 p_tone_fh = -1;
260                 fhuse--;
261         }
262         p_tone_fetched = NULL;
263 }
264
265 PORT_STATE_NAMES
266
267 /* set new endpoint state
268  */
269 void Port::new_state(int state)
270 {
271         PDEBUG(DEBUG_PORT, "PORT(%s) new state %s --> %s\n", p_name, state_name[p_state], state_name[state]);
272         p_state = state;
273 }
274
275
276 /*
277  * find the port with port_id
278  */ 
279 class Port *find_port_id(unsigned long port_id)
280 {
281         class Port *port = port_first;
282
283         while(port)
284         {
285 //printf("comparing: '%s' with '%s'\n", name, port->name);
286                 if (port->p_serial == port_id)
287                         return(port);
288                 port = port->next;
289         }
290
291         return(NULL);
292 }
293
294
295 /*
296  * set echotest
297  */
298 void Port::set_echotest(int echotest)
299 {
300         p_echotest = echotest;
301 }
302
303
304 /*
305  * set the file in the tone directory with the given name
306  */
307 void Port::set_tone(char *dir, char *name)
308 {
309         int fh;
310         char filename[128];
311
312         if (name == NULL)
313                 name = "";
314
315         /* no counter, no eof, normal speed */
316         p_tone_counter = 0;
317         p_tone_eof = 0;
318         p_tone_speed = 1;
319         p_tone_codec = CODEC_LAW;
320
321         if (p_tone_fh >= 0)
322         {
323                 close(p_tone_fh);
324                 p_tone_fh = -1;
325                 fhuse--;
326         }
327         p_tone_fetched = NULL;
328
329         if (name[0])
330         {
331                 if (name[0] == '/')
332                 {
333                         SPRINT(p_tone_name, "%s", name);
334                         p_tone_dir[0] = '\0';
335                 } else
336                 {
337                         SCPY(p_tone_dir, dir);
338                         SCPY(p_tone_name, name);
339                 }
340         } else
341         {
342                 p_tone_name[0]= '\0';
343                 p_tone_dir[0]= '\0';
344                 return;
345         }
346
347         if (!!strncmp(name,"cause_",6))
348                 return;
349
350         /* now we check if the cause exists, otherwhise we use error tone. */
351         if ((p_tone_fetched=open_tone_fetched(p_tone_dir, p_tone_name, &p_tone_codec, 0, 0)))
352         {
353                 p_tone_fetched = NULL;
354                 return;
355         }
356         SPRINT(filename, "%s_loop", p_tone_name);
357         if ((p_tone_fetched=open_tone_fetched(p_tone_dir, filename, &p_tone_codec, 0, 0)))
358         {
359                 p_tone_fetched = NULL;
360                 return;
361         }
362         SPRINT(filename, "%s/%s/%s", INSTALL_DATA, p_tone_dir, p_tone_name);
363         if ((fh=open_tone(filename, &p_tone_codec, 0, 0)) >= 0)
364         {
365                 close(fh);
366                 return;
367         }
368         SPRINT(filename, "%s/%s/%s_loop", INSTALL_DATA, p_tone_dir, p_tone_name);
369         if ((fh=open_tone(filename, &p_tone_codec, 0, 0)) >= 0)
370         {
371                 close(fh);
372                 return;
373         }
374
375         if (!strcmp(name,"cause_00") || !strcmp(name,"cause_10"))
376         {
377                 PDEBUG(DEBUG_PORT, "PORT(%s) Given Cause 0x%s has no tone, using release tone\n", p_name, name+6);
378                 SPRINT(p_tone_name,"release");
379         } else
380         if (!strcmp(name,"cause_11"))
381         {
382                 PDEBUG(DEBUG_PORT, "PORT(%s) Given Cause 0x%s has no tone, using busy tone\n", p_name, name+6);
383                 SPRINT(p_tone_name,"busy");
384         } else
385         {
386                 PDEBUG(DEBUG_PORT, "PORT(%s) Given Cause 0x%s has no tone, using error tone\n", p_name, name+6);
387                 SPRINT(p_tone_name,"error");
388         }
389 }
390
391
392 /*
393  * set the file in the tone directory for vbox playback
394  * also set the play_eof-flag
395  */
396 void Port::set_vbox_tone(char *dir, char *name)
397 {
398         char filename[256];
399
400         p_tone_speed = 1;
401         p_tone_counter = 0;
402         p_tone_codec = CODEC_LAW;
403         p_tone_eof = 1;
404
405         if (p_tone_fh >= 0)
406         {
407                 close(p_tone_fh);
408                 p_tone_fh = -1;
409                 fhuse--;
410         }
411         p_tone_fetched = NULL;
412
413         SPRINT(p_tone_dir,  dir);
414         SPRINT(p_tone_name,  name);
415
416         /* now we check if the cause exists, otherwhise we use error tone. */
417         if (p_tone_dir[0])
418         {
419                 if ((p_tone_fetched=open_tone_fetched(p_tone_dir, p_tone_name, &p_tone_codec, &p_tone_size, &p_tone_left)))
420                 {
421                         PDEBUG(DEBUG_PORT, "PORT(%s) opening fetched tone: %s\n", p_name, p_tone_name);
422                         return;
423                 }
424                 SPRINT(filename, "%s/%s/%s", INSTALL_DATA, p_tone_dir, p_tone_name);
425                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) >= 0)
426                 {
427                         fhuse++;
428                         PDEBUG(DEBUG_PORT, "PORT(%s) opening tone: %s\n", p_name, filename);
429                         return;
430                 }
431         } else
432         {
433                 SPRINT(filename, "%s", p_tone_name);
434                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) >= 0)
435                 {
436                         fhuse++;
437                         PDEBUG(DEBUG_PORT, "PORT(%s) opening tone: %s\n", p_name, filename);
438                         return;
439                 }
440         }
441 }
442
443
444 /*
445  * set the file in the given directory for vbox playback
446  * also set the eof-flag
447  * also set the counter-flag
448  */
449 void Port::set_vbox_play(char *name, int offset)
450 {
451         signed long size;
452         struct message *message;
453
454         /* use ser_box_tone() */
455         set_vbox_tone("", name);
456         if (p_tone_fh < 0)
457                 return;
458
459         /* enable counter */
460         p_tone_counter = 1;
461
462         /* seek */
463         if (p_tone_name[0])
464         {
465                 /* send message with counter value */
466                 if (p_tone_size>=0 && ACTIVE_EPOINT(p_epointlist))
467                 {
468                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_TONE_COUNTER);
469                         message->param.counter.current = offset;
470                         message->param.counter.max = size;
471                         message_put(message);
472                 }
473         }
474 }
475
476
477 /*
478  * set the playback speed (for recording playback with different speeds)
479  */
480 void Port::set_vbox_speed(int speed)
481 {
482         /* enable vbox play mode */
483         p_tone_speed = speed;
484 }
485
486 /*
487  * read from the given file as specified in port_set_tone and return sample data
488  * if the tone ends, the result may be less samples than requested
489  */
490 int Port::read_audio(unsigned char *buffer, int length)
491 {
492         int l,len;
493         int nodata=0; /* to detect 0-length files and avoid endless reopen */
494         char filename[128];
495         int tone_left_before; /* temp variable to determine the change in p_tone_left */
496
497         /* nothing */
498         if (length == 0)
499                 return(0);
500
501         len = length;
502
503         /* if there is no tone set, use silence */
504         if (!p_tone_name[0])
505                 return(0);
506
507         /* if the file pointer is not open, we open it */
508         if (p_tone_fh<0 && p_tone_fetched==NULL)
509         {
510                 if (p_tone_dir[0])
511                 {
512                         SPRINT(filename, "%s", p_tone_name);
513                         /* if file does not exist */
514                         if (!(p_tone_fetched=open_tone_fetched(p_tone_dir, filename, &p_tone_codec, &p_tone_size, &p_tone_left)))
515                         {
516                                 SPRINT(filename, "%s/%s/%s", INSTALL_DATA, p_tone_dir, p_tone_name);
517                                 /* if file does not exist */
518                                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0)
519                                 {
520                                         PDEBUG(DEBUG_PORT, "PORT(%s) no tone: %s\n", p_name, filename);
521                                         goto try_loop;
522                                 }
523                                 fhuse++;
524                         }
525                 } else
526                 {
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                         {
531                                 PDEBUG(DEBUG_PORT, "PORT(%s) no tone: %s\n", p_name, filename);
532                                 goto try_loop;
533                         }
534                         fhuse++;
535                 }
536                 PDEBUG(DEBUG_PORT, "PORT(%s) opening %stone: %s\n", p_name, p_tone_fetched?"fetched ":"", filename);
537         }
538
539 read_more:
540         /* file descriptor is open read data */
541         tone_left_before = p_tone_left;
542         if (p_tone_fh >= 0)
543         {
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         {
552                 l = read_tone_fetched(&p_tone_fetched, buffer, len, p_tone_size, &p_tone_left, p_tone_speed);
553                 if (l<0 || l>len) /* paranoia */
554                         l=0;
555                 buffer += l;
556                 len -= l;
557         }
558
559         /* if counter is enabled, we check if we have a change */
560         if (p_tone_counter && p_tone_size>=0 && ACTIVE_EPOINT(p_epointlist))
561         {
562                 /* if we jumed to the next second */
563                 if (((p_tone_size-p_tone_left)/8000) != (p_tone_size-tone_left_before)/8000)
564                 {
565 //printf("\nsize=%d left=%d\n\n",p_tone_size,p_tone_left);
566                         struct message *message;
567                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_TONE_COUNTER);
568                         message->param.counter.current = (p_tone_size-p_tone_left)/8000;
569                         message->param.counter.max = -1;
570                         message_put(message);
571                 }
572         }
573
574         if (len==0)
575                 return(length-len);
576
577         if (p_tone_fh >= 0)
578         {
579                 close(p_tone_fh);
580                 p_tone_fh = -1;
581                 fhuse--;
582         }
583         p_tone_fetched = NULL;
584
585         if (l)
586                 nodata=0;
587
588         /* if the file has 0-length */
589         if (nodata>1)
590         {
591                 PDEBUG(DEBUG_PORT, "PORT(%s) 0-length loop: %s\n", p_name, filename);
592                 p_tone_name[0]=0;
593                 p_tone_dir[0]=0;
594                 return(length-len);
595         }
596
597         /* if eof is reached, or if the normal file cannot be opened, continue with the loop file if possible */
598 try_loop:
599         if (p_tone_eof && ACTIVE_EPOINT(p_epointlist))
600         {
601                 struct message *message;
602                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_TONE_EOF);
603                 message_put(message);
604         }
605
606         if (p_tone_dir[0])
607         {
608                 /* if file does not exist */
609                 SPRINT(filename, "%s_loop", p_tone_name);
610                 if (!(p_tone_fetched=open_tone_fetched(p_tone_dir, filename, &p_tone_codec, &p_tone_size, &p_tone_left)))
611                 {
612                         SPRINT(filename, "%s/%s/%s_loop", INSTALL_DATA, p_tone_dir, p_tone_name);
613                         /* if file does not exist */
614                         if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0)
615                         {
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         } else
624         {
625                 SPRINT(filename, "%s_loop", p_tone_name);
626                 /* if file does not exist */
627                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0)
628                 {
629                         PDEBUG(DEBUG_PORT, "PORT(%s) no tone loop: %s\n",p_name, filename);
630                         p_tone_dir[0] = '\0';
631                         p_tone_name[0] = '\0';
632                         return(length-len);
633                 }
634                 fhuse++;
635         }
636         nodata++;
637         PDEBUG(DEBUG_PORT, "PORT(%s) opening %stone: %s\n", p_name, p_tone_fetched?"fetched ":"", filename);
638
639         /* now we have opened the loop */
640         goto read_more;
641 }
642
643
644 /* port handler:
645  * process transmission clock */
646 int Port::handler(void)
647 {
648         return(0);
649 }
650
651 /* endpoint sends messages to the port
652  * this is called by the message_epoint inherited by child classes
653  * therefor a return=1 means: stop, no more processing
654  */
655 //extern struct message *dddebug;
656 int Port::message_epoint(unsigned long epoint_id, int message_id, union parameter *param)
657 {
658         /* check if we got audio data from one remote port */
659         switch(message_id)
660         {
661                 case MESSAGE_TONE: /* play tone */
662                 PDEBUG(DEBUG_PORT, "PORT(%s) isdn port with (caller id %s) setting tone '%s' dir '%s'\n", p_name, p_callerinfo.id, param->tone.name, param->tone.dir);
663                 set_tone(param->tone.dir,param->tone.name);
664                 return(1);
665
666                 case MESSAGE_VBOX_TONE: /* play tone of answering machine */
667                 PDEBUG(DEBUG_PORT, "PORT(%s) set answering machine tone '%s' '%s'\n", p_name, param->tone.dir, param->tone.name);
668                 set_vbox_tone(param->tone.dir, param->tone.name);
669                 return(1);
670
671                 case MESSAGE_VBOX_PLAY: /* play recording of answering machine */
672                 PDEBUG(DEBUG_PORT, "PORT(%s) set answering machine file to play '%s' (offset %d seconds)\n", p_name, param->play.file, param->play.offset);
673                 set_vbox_play(param->play.file, param->play.offset);
674                 return(1);
675
676                 case MESSAGE_VBOX_PLAY_SPEED: /* set speed of playback (recording of answering machine) */
677                 PDEBUG(DEBUG_PORT, "PORT(%s) set answering machine playback speed %d (times)\n", p_name, param->speed);
678                 set_vbox_speed(param->speed);
679                 return(1);
680
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 long   sample_rate; /* sample rate */
692         unsigned long   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, 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
709         if (!extension)
710         {
711                 PERROR("Port(%d) not an extension\n", p_serial);
712                 return(0);
713         }
714         SCPY(p_record_extension, extension);
715         p_record_anon_ignore = anon_ignore;
716         SCPY(p_record_vbox_email, vbox_email);
717         p_record_vbox_email_file = vbox_email_file;
718         
719         if (p_record)
720         {
721                 PERROR("Port(%d) already recording\n", p_serial);
722                 return(0);
723         }
724
725         if (vbox != 0)
726                 SPRINT(filename, "%s/%s/%s/vbox", INSTALL_DATA, options.extensions_dir, p_record_extension);
727         else
728                 SPRINT(filename, "%s/%s/%s/recordings", INSTALL_DATA, options.extensions_dir, p_record_extension);
729         if (mkdir(filename, 0755) < 0)
730         {
731                 if (errno != EEXIST)
732                 {
733                         PERROR("Port(%d) cannot create directory '%s'\n", p_serial, filename);
734                         return(0);
735                 }
736         }
737
738         if (vbox == 1)
739                 UPRINT(strchr(filename,'\0'), "/announcement");
740         else
741                 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);
742         if (vbox == 2)
743         {
744                 p_record_vbox_year = now_tm->tm_year;
745                 p_record_vbox_mon = now_tm->tm_mon;
746                 p_record_vbox_mday = now_tm->tm_mday;
747                 p_record_vbox_hour = now_tm->tm_hour;
748                 p_record_vbox_min = now_tm->tm_min;
749         }
750
751         /* check, if file exists (especially when an extension calls the same extension) */
752         if (vbox != 1)
753         if ((p_record = fopen(filename, "r")))
754         {
755                 fclose(p_record);
756                 SCAT(filename, "_2nd");
757         }
758                         
759         p_record = fopen(filename, "w");
760         if (!p_record)
761         {
762                 PERROR("Port(%d) cannot record because file cannot be opened '%s'\n", p_serial, filename);
763                 return(0);
764         }
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         {
773                 case CODEC_MONO:
774                 case CODEC_STEREO:
775                 case CODEC_8BIT:
776                 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 long size, wsize;
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         char *valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_.-!$%&/()=+*;~";
804
805         if (!p_record)
806                 return;
807         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);
808
809         memcpy(&callerinfo, &p_callerinfo, sizeof(struct caller_info));
810 //      apply_callerid_restriction(p_record_anon_ignore, callerinfo.id, &callerinfo.ntype, &callerinfo.present, &callerinfo.screen, callerinfo.extension, callerinfo.name);
811
812         SCPY(number, p_dialinginfo.id);
813         SCPY(callerid, numberrize_callerinfo(callerinfo.id, callerinfo.ntype));
814         if (callerid[0] == '\0')
815         {
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         {
839                 if (!strchr(valid_chars, callerid[i]))
840                         callerid[i] = '_';
841                 i++;
842         }
843         i = 0;
844         ii = strlen(number);
845         while(i < ii)
846         {
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         {
855                 i = p_record_length;
856                 if (i > mute)
857                         i = mute;       
858                 fseek(p_record, -(i<<1), SEEK_END);
859                 p_record_length -= (i<<1);
860         }
861         /* add beep to the end of recording */
862         if (beep && p_record_type==CODEC_MONO)
863         {
864                 i = 0;
865                 while(i < 256)
866                 {
867                         beep_mono[i] = (signed short)(sin((double)i / 5.688888888889 * 2.0 * 3.1415927) * 2000.0);
868                         i++;
869                 }
870                 i = 0;
871                 while(i < beep)
872                 {
873                         fwrite(beep_mono, sizeof(beep_mono), 1, p_record);
874                         i += sizeof(beep_mono);
875                         p_record_length += sizeof(beep_mono);
876                 }
877         }
878
879         /* complete header */
880         switch(p_record_type)
881         {
882                 case CODEC_MONO:
883                 case CODEC_STEREO:
884                 case CODEC_8BIT:
885                 /* cue */
886                 fprintf(p_record, "cue %c%c%c%c%c%c%c%c", 4, 0, 0, 0, 0,0,0,0);
887
888                 /* LIST */
889                 fprintf(p_record, "LIST%c%c%c%cadtl", 4, 0, 0, 0);
890
891                 /* go to header */
892                 fseek(p_record, 0, SEEK_SET);
893
894                 /* WAVEfmt xxxx(fmt-size)dataxxxx[data]cue xxxx0000LISTxxxxadtl*/
895                 size = p_record_length;
896                 wsize = 4+8+sizeof(fmt)+8+size+8+4+8+4;
897
898                 /* RIFF */
899                 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));
900
901                 /* WAVE */
902                 fprintf(p_record, "WAVE");
903
904                 /* fmt */
905                 fprintf(p_record, "fmt %c%c%c%c", sizeof(fmt), 0, 0, 0);
906                 switch(p_record_type)
907                 {
908                         case CODEC_MONO:
909                         fmt.stereo = 1;
910                         fmt.channels = 1;
911                         fmt.sample_rate = 8000; /* samples/sec */
912                         fmt.data_rate = 16000; /* full data rate */
913                         fmt.bytes_sample = 2; /* all channels */
914                         fmt.bits_sample = 16; /* one channel */
915                         break;
916
917                         case CODEC_STEREO:
918                         fmt.stereo = 1;
919                         fmt.channels = 2;
920                         fmt.sample_rate = 8000; /* samples/sec */
921                         fmt.data_rate = 32000; /* full data rate */
922                         fmt.bytes_sample = 4; /* all channels */
923                         fmt.bits_sample = 16; /* one channel */
924                         break;
925
926                         case CODEC_8BIT:
927                         fmt.stereo = 1;
928                         fmt.channels = 1;
929                         fmt.sample_rate = 8000; /* samples/sec */
930                         fmt.data_rate = 8000; /* full data rate */
931                         fmt.bytes_sample = 1; /* all channels */
932                         fmt.bits_sample = 8; /* one channel */
933                         break;
934                 }
935                 fwrite(&fmt, sizeof(fmt), 1, p_record);
936
937                 /* data */
938                 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));
939
940                 /* rename file */
941                 if (p_record_vbox == 1)
942                         SPRINT(filename, "%s.wav", p_record_filename);
943                 else
944                         SPRINT(filename, "%s_%s-%s.wav", p_record_filename, callerid, number);
945                 break;
946
947                 case CODEC_LAW:
948                 /* rename file */
949                 if (p_record_vbox == 1)
950                         SPRINT(filename, "%s.isdn", p_record_filename);
951                 else
952                         SPRINT(filename, "%s_%s-%s.isdn", p_record_filename, callerid, number);
953                 break;
954         }
955
956         fclose(p_record);
957         fduse--;
958         p_record = NULL;
959
960         if (rename(p_record_filename, filename) < 0)
961         {
962                 PERROR("Port(%d) cannot rename from '%s' to '%s'\n", p_serial, p_record_filename, filename);
963                 return;
964         }
965
966         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);
967
968         if (p_record_vbox == 2)
969         {
970                 SPRINT(indexname, "%s/%s/%s/vbox/index", INSTALL_DATA, options.extensions_dir, p_record_extension);
971                 if ((fp = fopen(indexname,"a")))
972                 {
973                         fduse++;
974
975                         /* remove path from file name */
976                         p = filename;
977                         while(strchr(p, '/'))
978                                 p = strchr(p, '/')+1;
979                         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);
980
981                         fclose(fp);
982                         fduse--;
983                 } else
984                 {
985                         PERROR("Port(%d) cannot open index file '%s' to append.\n", p_serial, indexname);
986                 }
987
988                 /* send email with sample*/
989                 if (p_record_vbox_email[0])
990                 {
991                         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);
992                 }
993         }
994 }
995
996
997 /*
998  * recording function
999  * Records all data from down and from up into one single stream.
1000  * Both streams may have gaps or jitter.
1001  * A Jitter buffer for both streams is used to compensate jitter.
1002  * 
1003  * If one stream (dir) received packets, they are stored to a
1004  * buffer to wait for the other stream (dir), so both streams can 
1005  * be combined. If the buffer is full, it's content is written
1006  * without mixing stream. (assuming only one stram (dir) exists.)
1007  * A flag is used to indicate what stream is currently in buffer.
1008  *
1009  * NOTE: First stereo sample (odd) is from down, second is from up.
1010  */
1011 void Port::record(unsigned char *data, int length, int dir_fromup)
1012 {
1013         unsigned char write_buffer[1024], *d;
1014         signed short *s;
1015         int free, i, ii;
1016         signed long sample;
1017
1018         /* no recording */
1019         if (!p_record || !length)
1020                 return;
1021
1022         /* skip data from local caller (dtmf input) */
1023         if (p_record_skip && !dir_fromup)
1024         {
1025                 /* more to skip than we have */
1026                 if (p_record_skip > length)
1027                 {
1028                         p_record_skip -= length;
1029                         return;
1030                 }
1031                 /* less to skip */
1032                 data += p_record_skip;
1033                 length -= p_record_skip;
1034                 p_record_skip = 0;
1035         }
1036
1037 //printf("dir=%d len=%d\n", dir_fromup, length);
1038
1039         free = ((p_record_buffer_readp - p_record_buffer_writep - 1) & RECORD_BUFFER_MASK);
1040
1041 //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);
1042
1043         /* the buffer stores the same data stream */
1044         if (dir_fromup == p_record_buffer_dir)
1045         {
1046 same_again:
1047
1048 //printf("same free=%d length=%d\n", free, length);
1049                 /* first write what we can to the buffer */
1050                 while(free && length)
1051                 {
1052                         p_record_buffer[p_record_buffer_writep] = audio_law_to_s32[*data++];
1053                         p_record_buffer_writep = (p_record_buffer_writep + 1) & RECORD_BUFFER_MASK;
1054                         free--;
1055                         length--;
1056                 }
1057                 /* all written, so we return */
1058                 if (!length)
1059                         return;
1060                 /* still data left, buffer is full, so we need to write a chunk to file */
1061                 switch(p_record_type)
1062                 {
1063                         case CODEC_MONO:
1064                         s = (signed short *)write_buffer;
1065                         i = 0;
1066                         while(i < 256)
1067                         {
1068                                 *s++ = p_record_buffer[p_record_buffer_readp];
1069                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1070                                 i++;
1071                         }
1072                         fwrite(write_buffer, 512, 1, p_record);
1073                         p_record_length += 512;
1074                         break;
1075
1076                         case CODEC_STEREO:
1077                         s = (signed short *)write_buffer;
1078                         if (p_record_buffer_dir)
1079                         {
1080                                 i = 0;
1081                                 while(i < 256)
1082                                 {
1083                                         *s++ = 0; /* nothing from down */
1084                                         *s++ = p_record_buffer[p_record_buffer_readp];
1085                                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1086                                         i++;
1087                                 }
1088                         } else
1089                         {
1090                                 i = 0;
1091                                 while(i < 256)
1092                                 {
1093                                         *s++ = p_record_buffer[p_record_buffer_readp];
1094                                         *s++ = 0; /* nothing from up */
1095                                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1096                                         i++;
1097                                 }
1098                         }
1099                         fwrite(write_buffer, 1024, 1, p_record);
1100                         p_record_length += 1024;
1101                         break;
1102
1103                         case CODEC_8BIT:
1104                         d = write_buffer;
1105                         i = 0;
1106                         while(i < 256)
1107                         {
1108                                 *d++ = ((unsigned short)(p_record_buffer[p_record_buffer_readp]+0x8000)) >> 8;
1109                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1110                                 i++;
1111                         }
1112                         fwrite(write_buffer, 512, 1, p_record);
1113                         p_record_length += 512;
1114                         break;
1115
1116                         case CODEC_LAW:
1117                         d = write_buffer;
1118                         i = 0;
1119                         while(i < 256)
1120                         {
1121                                 *d++ = audio_s16_to_law[p_record_buffer[p_record_buffer_readp] & 0xffff];
1122                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1123                                 i++;
1124                         }
1125                         fwrite(write_buffer, 256, 1, p_record);
1126                         p_record_length += 256;
1127                         break;
1128                 }
1129                 /* because we still have data, we write again */
1130                 free += 256;
1131                 goto same_again;
1132         }
1133         /* the buffer stores the other stream */
1134         
1135 different_again:
1136         /* if buffer empty, change it */
1137         if (p_record_buffer_readp == p_record_buffer_writep)
1138         {
1139                 p_record_buffer_dir = dir_fromup;
1140                 goto same_again;
1141         }
1142         /* how much data can we mix ? */
1143         ii = (p_record_buffer_writep - p_record_buffer_readp) & RECORD_BUFFER_MASK;
1144         if (length < ii)
1145                 ii = length;
1146
1147         if (ii > 256)
1148                 ii = 256;
1149 //printf("same ii=%d length=%d\n", ii, length);
1150 //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);
1151
1152         /* write data mixed with the buffer */
1153         switch(p_record_type)
1154         {
1155                 case CODEC_MONO:
1156                 s = (signed short *)write_buffer;
1157                 i = 0;
1158                 while(i < ii)
1159                 {
1160                         sample = p_record_buffer[p_record_buffer_readp]
1161                                 + audio_law_to_s32[*data++];
1162                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1163                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1164                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1165                         *s++ = sample;
1166                         i++;
1167                 }
1168                 fwrite(write_buffer, ii<<1, 1, p_record);
1169                 p_record_length += (ii<<1);
1170                 break;
1171                 
1172                 case CODEC_STEREO:
1173                 s = (signed short *)write_buffer;
1174                 if (p_record_buffer_dir)
1175                 {
1176                         i = 0;
1177                         while(i < ii)
1178                         {
1179                                 *s++ = audio_law_to_s32[*data++];
1180                                 *s++ = p_record_buffer[p_record_buffer_readp];
1181                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1182                                 i++;
1183                         }
1184                 } else
1185                 {
1186                         i = 0;
1187                         while(i < ii)
1188                         {
1189                                 *s++ = p_record_buffer[p_record_buffer_readp];
1190                                 *s++ = audio_law_to_s32[*data++];
1191                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1192                                 i++;
1193                         }
1194                 }
1195                 fwrite(write_buffer, ii<<2, 1, p_record);
1196                 p_record_length += (ii<<2);
1197                 break;
1198                 
1199                 case CODEC_8BIT:
1200                 d = write_buffer;
1201                 i = 0;
1202                 while(i < ii)
1203                 {
1204                         sample = p_record_buffer[p_record_buffer_readp]
1205                                 + audio_law_to_s32[*data++];
1206                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1207                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1208                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1209                         *d++ = (sample+0x8000) >> 8;
1210                         i++;
1211                 }
1212                 fwrite(write_buffer, ii, 1, p_record);
1213                 p_record_length += ii;
1214                 break;
1215                 
1216                 case CODEC_LAW:
1217                 d = write_buffer;
1218                 i = 0;
1219                 while(i < ii)
1220                 {
1221                         sample = p_record_buffer[p_record_buffer_readp]
1222                                 + audio_law_to_s32[*data++];
1223                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1224                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1225                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1226                         *d++ = audio_s16_to_law[sample & 0xffff];
1227                         i++;
1228                 }
1229                 fwrite(write_buffer, ii, 1, p_record);
1230                 p_record_length += ii;
1231                 break;
1232         }
1233         length -= ii;
1234         /* still data */
1235         if (length)
1236                 goto different_again;
1237         /* no data (maybe buffer) */
1238         return;
1239
1240 }
1241
1242