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