gsm improvements
[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         } else {
320                 p_tone_name[0]= '\0';
321                 p_tone_dir[0]= '\0';
322                 return;
323         }
324
325         if (!!strncmp(name,"cause_",6))
326                 return;
327
328         /* now we check if the cause exists, otherwhise we use error tone. */
329         if ((p_tone_fetched=open_tone_fetched(p_tone_dir, p_tone_name, &p_tone_codec, 0, 0))) {
330                 p_tone_fetched = NULL;
331                 return;
332         }
333         SPRINT(filename, "%s_loop", p_tone_name);
334         if ((p_tone_fetched=open_tone_fetched(p_tone_dir, filename, &p_tone_codec, 0, 0))) {
335                 p_tone_fetched = NULL;
336                 return;
337         }
338         SPRINT(filename, "%s/%s/%s", SHARE_DATA, p_tone_dir, p_tone_name);
339         if ((fh=open_tone(filename, &p_tone_codec, 0, 0)) >= 0) {
340                 close(fh);
341                 return;
342         }
343         SPRINT(filename, "%s/%s/%s_loop", SHARE_DATA, p_tone_dir, p_tone_name);
344         if ((fh=open_tone(filename, &p_tone_codec, 0, 0)) >= 0) {
345                 close(fh);
346                 return;
347         }
348
349         if (!strcmp(name,"cause_00") || !strcmp(name,"cause_10")) {
350                 PDEBUG(DEBUG_PORT, "PORT(%s) Given Cause 0x%s has no tone, using release tone\n", p_name, name+6);
351                 SPRINT(p_tone_name,"release");
352         } else
353         if (!strcmp(name,"cause_11")) {
354                 PDEBUG(DEBUG_PORT, "PORT(%s) Given Cause 0x%s has no tone, using busy tone\n", p_name, name+6);
355                 SPRINT(p_tone_name,"busy");
356         } else {
357                 PDEBUG(DEBUG_PORT, "PORT(%s) Given Cause 0x%s has no tone, using error tone\n", p_name, name+6);
358                 SPRINT(p_tone_name,"error");
359         }
360 }
361
362
363 /*
364  * set the file in the tone directory for vbox playback
365  * also set the play_eof-flag
366  */
367 void Port::set_vbox_tone(const char *dir, const char *name)
368 {
369         char filename[256];
370
371         p_tone_speed = 1;
372         p_tone_counter = 0;
373         p_tone_codec = CODEC_LAW;
374         p_tone_eof = 1;
375
376         if (p_tone_fh >= 0) {
377                 close(p_tone_fh);
378                 p_tone_fh = -1;
379                 fhuse--;
380         }
381         p_tone_fetched = NULL;
382
383         SPRINT(p_tone_dir,  dir);
384         SPRINT(p_tone_name,  name);
385
386         /* now we check if the cause exists, otherwhise we use error tone. */
387         if (p_tone_dir[0]) {
388                 if ((p_tone_fetched=open_tone_fetched(p_tone_dir, p_tone_name, &p_tone_codec, &p_tone_size, &p_tone_left))) {
389                         PDEBUG(DEBUG_PORT, "PORT(%s) opening fetched tone: %s\n", p_name, p_tone_name);
390                         return;
391                 }
392                 SPRINT(filename, "%s/%s/%s", SHARE_DATA, p_tone_dir, p_tone_name);
393                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) >= 0) {
394                         fhuse++;
395                         PDEBUG(DEBUG_PORT, "PORT(%s) opening tone: %s\n", p_name, filename);
396                         return;
397                 }
398         } else {
399                 SPRINT(filename, "%s", p_tone_name);
400                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) >= 0) {
401                         fhuse++;
402                         PDEBUG(DEBUG_PORT, "PORT(%s) opening tone: %s\n", p_name, filename);
403                         return;
404                 }
405         }
406 }
407
408
409 /*
410  * set the file in the given directory for vbox playback
411  * also set the eof-flag
412  * also set the counter-flag
413  */
414 void Port::set_vbox_play(const char *name, int offset)
415 {
416         struct lcr_msg *message;
417
418         /* use ser_box_tone() */
419         set_vbox_tone("", name);
420         if (p_tone_fh < 0)
421                 return;
422
423         /* enable counter */
424         p_tone_counter = 1;
425
426         /* seek */
427         if (p_tone_name[0]) {
428                 /* send message with counter value */
429                 if (p_tone_size>=0 && ACTIVE_EPOINT(p_epointlist)) {
430                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_TONE_COUNTER);
431                         message->param.counter.current = offset;
432                         message->param.counter.max = p_tone_size;
433                         message_put(message);
434                 }
435         }
436 }
437
438
439 /*
440  * set the playback speed (for recording playback with different speeds)
441  */
442 void Port::set_vbox_speed(int speed)
443 {
444         /* enable vbox play mode */
445         p_tone_speed = speed;
446 }
447
448 /*
449  * read from the given file as specified in port_set_tone and return sample data
450  * if the tone ends, the result may be less samples than requested
451  */
452 int Port::read_audio(unsigned char *buffer, int length)
453 {
454         int l = 0,len;
455         int nodata=0; /* to detect 0-length files and avoid endless reopen */
456         char filename[128];
457         int tone_left_before; /* temp variable to determine the change in p_tone_left */
458
459         /* nothing */
460         if (length == 0)
461                 return(0);
462
463         len = length;
464
465         /* if there is no tone set, use silence */
466         if (!p_tone_name[0])
467                 return(0);
468
469         /* if the file pointer is not open, we open it */
470         if (p_tone_fh<0 && p_tone_fetched==NULL) {
471                 if (p_tone_dir[0]) {
472                         SPRINT(filename, "%s", p_tone_name);
473                         /* if file does not exist */
474                         if (!(p_tone_fetched=open_tone_fetched(p_tone_dir, filename, &p_tone_codec, &p_tone_size, &p_tone_left))) {
475                                 SPRINT(filename, "%s/%s/%s", SHARE_DATA, p_tone_dir, p_tone_name);
476                                 /* if file does not exist */
477                                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0) {
478                                         PDEBUG(DEBUG_PORT, "PORT(%s) no tone: %s\n", p_name, filename);
479                                         goto try_loop;
480                                 }
481                                 fhuse++;
482                         }
483                 } else {
484                         SPRINT(filename, "%s", p_tone_name);
485                         /* if file does not exist */
486                         if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0) {
487                                 PDEBUG(DEBUG_PORT, "PORT(%s) no tone: %s\n", p_name, filename);
488                                 goto try_loop;
489                         }
490                         fhuse++;
491                 }
492                 PDEBUG(DEBUG_PORT, "PORT(%s) opening %stone: %s\n", p_name, p_tone_fetched?"fetched ":"", filename);
493         }
494
495 read_more:
496         /* file descriptor is open read data */
497         tone_left_before = p_tone_left;
498         if (p_tone_fh >= 0) {
499                 l = read_tone(p_tone_fh, buffer, p_tone_codec, len, p_tone_size, &p_tone_left, p_tone_speed);
500                 if (l<0 || l>len) /* paranoia */
501                         l=0;
502                 buffer += l;
503                 len -= l;
504         }
505         if (p_tone_fetched) {
506                 l = read_tone_fetched(&p_tone_fetched, buffer, len, p_tone_size, &p_tone_left, p_tone_speed);
507                 if (l<0 || l>len) /* paranoia */
508                         l=0;
509                 buffer += l;
510                 len -= l;
511         }
512
513         /* if counter is enabled, we check if we have a change */
514         if (p_tone_counter && p_tone_size>=0 && ACTIVE_EPOINT(p_epointlist)) {
515                 /* if we jumed to the next second */
516                 if (((p_tone_size-p_tone_left)/8000) != (p_tone_size-tone_left_before)/8000) {
517 //printf("\nsize=%d left=%d\n\n",p_tone_size,p_tone_left);
518                         struct lcr_msg *message;
519                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_TONE_COUNTER);
520                         message->param.counter.current = (p_tone_size-p_tone_left)/8000;
521                         message->param.counter.max = -1;
522                         message_put(message);
523                 }
524         }
525
526         if (len==0)
527                 return(length-len);
528
529         if (p_tone_fh >= 0) {
530                 close(p_tone_fh);
531                 p_tone_fh = -1;
532                 fhuse--;
533         }
534         p_tone_fetched = NULL;
535
536         if (l)
537                 nodata=0;
538
539         /* if the file has 0-length */
540         if (nodata>1) {
541                 PDEBUG(DEBUG_PORT, "PORT(%s) 0-length loop: %s\n", p_name, filename);
542                 p_tone_name[0]=0;
543                 p_tone_dir[0]=0;
544                 return(length-len);
545         }
546
547         /* if eof is reached, or if the normal file cannot be opened, continue with the loop file if possible */
548 try_loop:
549         if (p_tone_eof && ACTIVE_EPOINT(p_epointlist)) {
550                 struct lcr_msg *message;
551                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_TONE_EOF);
552                 message_put(message);
553         }
554
555         if (p_tone_dir[0]) {
556                 /* if file does not exist */
557                 SPRINT(filename, "%s_loop", p_tone_name);
558                 if (!(p_tone_fetched=open_tone_fetched(p_tone_dir, filename, &p_tone_codec, &p_tone_size, &p_tone_left))) {
559                         SPRINT(filename, "%s/%s/%s_loop", SHARE_DATA, p_tone_dir, p_tone_name);
560                         /* if file does not exist */
561                         if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0) {
562                                 PDEBUG(DEBUG_PORT, "PORT(%s) no tone loop: %s\n",p_name, filename);
563                                 p_tone_dir[0] = '\0';
564                                 p_tone_name[0] = '\0';
565                                 return(length-len);
566                         }
567                         fhuse++;
568                 }
569         } else {
570                 SPRINT(filename, "%s_loop", p_tone_name);
571                 /* if file does not exist */
572                 if ((p_tone_fh=open_tone(filename, &p_tone_codec, &p_tone_size, &p_tone_left)) < 0) {
573                         PDEBUG(DEBUG_PORT, "PORT(%s) no tone loop: %s\n",p_name, filename);
574                         p_tone_dir[0] = '\0';
575                         p_tone_name[0] = '\0';
576                         return(length-len);
577                 }
578                 fhuse++;
579         }
580         nodata++;
581         PDEBUG(DEBUG_PORT, "PORT(%s) opening %stone: %s\n", p_name, p_tone_fetched?"fetched ":"", filename);
582
583         /* now we have opened the loop */
584         goto read_more;
585 }
586
587
588 /* port handler:
589  * process transmission clock */
590 int Port::handler(void)
591 {
592         return(0);
593 }
594
595 /* endpoint sends messages to the port
596  * this is called by the message_epoint inherited by child classes
597  * therefor a return=1 means: stop, no more processing
598  */
599 //extern struct lcr_msg *dddebug;
600 int Port::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
601 {
602         /* check if we got audio data from one remote port */
603         switch(message_id) {
604                 case MESSAGE_TONE: /* play tone */
605                 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);
606                 set_tone(param->tone.dir,param->tone.name);
607                 return(1);
608
609                 case MESSAGE_VBOX_TONE: /* play tone of answering machine */
610                 PDEBUG(DEBUG_PORT, "PORT(%s) set answering machine tone '%s' '%s'\n", p_name, param->tone.dir, param->tone.name);
611                 set_vbox_tone(param->tone.dir, param->tone.name);
612                 return(1);
613
614                 case MESSAGE_VBOX_PLAY: /* play recording of answering machine */
615                 PDEBUG(DEBUG_PORT, "PORT(%s) set answering machine file to play '%s' (offset %d seconds)\n", p_name, param->play.file, param->play.offset);
616                 set_vbox_play(param->play.file, param->play.offset);
617                 return(1);
618
619                 case MESSAGE_VBOX_PLAY_SPEED: /* set speed of playback (recording of answering machine) */
620                 PDEBUG(DEBUG_PORT, "PORT(%s) set answering machine playback speed %d (times)\n", p_name, param->speed);
621                 set_vbox_speed(param->speed);
622                 return(1);
623
624         }
625
626         return(0);
627 }
628
629
630 /* wave header structure */
631 struct fmt {
632         unsigned short  stereo; /* 1 = mono, 2 = stereo */
633         unsigned short  channels; /* number of channels */
634         unsigned int    sample_rate; /* sample rate */
635         unsigned int    data_rate; /* data rate */
636         unsigned short  bytes_sample; /* bytes per sample (all channels) */
637         unsigned short  bits_sample; /* bits per sample (one channel) */
638 };
639
640
641 /*
642  * open record file (actually a wave file with empty header which will be
643  * written before close, because we do not know the size yet)
644  * type=1 record annoucement,  type=0 record audio stream, type=2 record vbox
645  */
646 int Port::open_record(int type, int vbox, int skip, char *extension, int anon_ignore, const char *vbox_email, int vbox_email_file)
647 {
648         /* RIFFxxxxWAVEfmt xxxx(fmt-size)dataxxxx... */
649         char dummyheader[8+4+8+sizeof(fmt)+8];
650         char filename[256];
651
652         if (!extension) {
653                 PERROR("Port(%d) not an extension\n", p_serial);
654                 return(0);
655         }
656         SCPY(p_record_extension, extension);
657         p_record_anon_ignore = anon_ignore;
658         SCPY(p_record_vbox_email, vbox_email);
659         p_record_vbox_email_file = vbox_email_file;
660         
661         if (p_record) {
662                 PERROR("Port(%d) already recording\n", p_serial);
663                 return(0);
664         }
665
666         if (vbox != 0)
667                 SPRINT(filename, "%s/%s/vbox", EXTENSION_DATA, p_record_extension);
668         else
669                 SPRINT(filename, "%s/%s/recordings", EXTENSION_DATA, p_record_extension);
670         if (mkdir(filename, 0755) < 0) {
671                 if (errno != EEXIST) {
672                         PERROR("Port(%d) cannot create directory '%s'\n", p_serial, filename);
673                         return(0);
674                 }
675         }
676
677         if (vbox == 1)
678                 UPRINT(strchr(filename,'\0'), "/announcement");
679         else
680                 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);
681         if (vbox == 2) {
682                 p_record_vbox_year = now_tm->tm_year;
683                 p_record_vbox_mon = now_tm->tm_mon;
684                 p_record_vbox_mday = now_tm->tm_mday;
685                 p_record_vbox_hour = now_tm->tm_hour;
686                 p_record_vbox_min = now_tm->tm_min;
687         }
688
689         /* check, if file exists (especially when an extension calls the same extension) */
690         if (vbox != 1)
691         if ((p_record = fopen(filename, "r"))) {
692                 fclose(p_record);
693                 SCAT(filename, "_2nd");
694         }
695                         
696         p_record = fopen(filename, "w");
697         if (!p_record) {
698                 PERROR("Port(%d) cannot record because file cannot be opened '%s'\n", p_serial, filename);
699                 return(0);
700         }
701         fduse++;
702
703         p_record_type = type;
704         p_record_vbox = vbox;
705         p_record_skip = skip;
706         p_record_length = 0;
707         switch(p_record_type) {
708                 case CODEC_MONO:
709                 case CODEC_STEREO:
710                 case CODEC_8BIT:
711                 fwrite(dummyheader, sizeof(dummyheader), 1, p_record);
712                 break;
713
714                 case CODEC_LAW:
715                 break;
716         }
717         UCPY(p_record_filename, filename);
718
719         PDEBUG(DEBUG_PORT, "Port(%d) recording started with file name '%s'\n", p_serial, filename);
720         return(1);
721 }
722
723
724 /*
725  * close the recoding file, put header in front and rename
726  */
727 void Port::close_record(int beep, int mute)
728 {
729         static signed short beep_mono[256];
730         unsigned int size = 0, wsize = 0;
731         struct fmt fmt;
732         char filename[512], indexname[512];
733         FILE *fp;
734         int i, ii;
735         char number[256], callerid[256];
736         char *p;
737         struct caller_info callerinfo;
738         const char *valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_.-!$%&/()=+*;~";
739
740         if (!p_record)
741                 return;
742         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);
743
744         memcpy(&callerinfo, &p_callerinfo, sizeof(struct caller_info));
745 //      apply_callerid_restriction(p_record_anon_ignore, callerinfo.id, &callerinfo.ntype, &callerinfo.present, &callerinfo.screen, callerinfo.extension, callerinfo.name);
746
747         SCPY(number, p_dialinginfo.id);
748         SCPY(callerid, numberrize_callerinfo(callerinfo.id, callerinfo.ntype, options.national, options.international));
749         if (callerid[0] == '\0') {
750                 if (callerinfo.present == INFO_PRESENT_RESTRICTED)
751                         UCPY(callerid,"anonymous");
752                 else
753                         UCPY(callerid,"unknown");
754         }
755
756         /* change verboten digits */
757         p = callerid;
758         while((p=strchr(p,'*')))
759                 *(p++) = 'x';
760         p = callerid;
761         while((p=strchr(p,'/')))
762                 *(p++) = 'x';
763         p = number;
764         while((p=strchr(p,'*')))
765                 *(p++) = 'x';
766         p = number;
767         while((p=strchr(p,'/')))
768                 *(p++) = 'x';
769         i = 0;
770         ii = strlen(callerid);
771         while(i < ii) {
772                 if (!strchr(valid_chars, callerid[i]))
773                         callerid[i] = '_';
774                 i++;
775         }
776         i = 0;
777         ii = strlen(number);
778         while(i < ii) {
779                 if (!strchr(valid_chars, number[i]))
780                         number[i] = '_';
781                 i++;
782         }
783
784         /* mute */
785         if (mute && p_record_type==CODEC_MONO) {
786                 i = p_record_length;
787                 if (i > mute)
788                         i = mute;       
789                 fseek(p_record, -(i<<1), SEEK_END);
790                 p_record_length -= (i<<1);
791         }
792         /* add beep to the end of recording */
793         if (beep && p_record_type==CODEC_MONO) {
794                 i = 0;
795                 while(i < 256) {
796                         beep_mono[i] = (signed short)(sin((double)i / 5.688888888889 * 2.0 * 3.1415927) * 2000.0);
797                         i++;
798                 }
799                 i = 0;
800                 while(i < beep) {
801                         fwrite(beep_mono, sizeof(beep_mono), 1, p_record);
802                         i += sizeof(beep_mono);
803                         p_record_length += sizeof(beep_mono);
804                 }
805         }
806
807         /* complete header */
808         switch(p_record_type) {
809                 case CODEC_MONO:
810                 case CODEC_STEREO:
811                 case CODEC_8BIT:
812                 /* cue */
813                 fprintf(p_record, "cue %c%c%c%c%c%c%c%c", 4, 0, 0, 0, 0,0,0,0);
814
815                 /* LIST */
816                 fprintf(p_record, "LIST%c%c%c%cadtl", 4, 0, 0, 0);
817
818                 /* go to header */
819                 fseek(p_record, 0, SEEK_SET);
820
821                 /* WAVEfmt xxxx(fmt-size)dataxxxx[data]cue xxxx0000LISTxxxxadtl*/
822                 size = p_record_length;
823                 wsize = 4+8+sizeof(fmt)+8+size+8+4+8+4;
824
825                 /* RIFF */
826                 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));
827
828                 /* WAVE */
829                 fprintf(p_record, "WAVE");
830
831                 /* fmt */
832                 fprintf(p_record, "fmt %c%c%c%c", (unsigned int)sizeof(fmt), 0, 0, 0);
833                 switch(p_record_type) {
834                         case CODEC_MONO:
835                         fmt.stereo = 1;
836                         fmt.channels = 1;
837                         fmt.sample_rate = 8000; /* samples/sec */
838                         fmt.data_rate = 16000; /* full data rate */
839                         fmt.bytes_sample = 2; /* all channels */
840                         fmt.bits_sample = 16; /* one channel */
841                         break;
842
843                         case CODEC_STEREO:
844                         fmt.stereo = 1;
845                         fmt.channels = 2;
846                         fmt.sample_rate = 8000; /* samples/sec */
847                         fmt.data_rate = 32000; /* full data rate */
848                         fmt.bytes_sample = 4; /* all channels */
849                         fmt.bits_sample = 16; /* one channel */
850                         break;
851
852                         case CODEC_8BIT:
853                         fmt.stereo = 1;
854                         fmt.channels = 1;
855                         fmt.sample_rate = 8000; /* samples/sec */
856                         fmt.data_rate = 8000; /* full data rate */
857                         fmt.bytes_sample = 1; /* all channels */
858                         fmt.bits_sample = 8; /* one channel */
859                         break;
860                 }
861                 fwrite(&fmt, sizeof(fmt), 1, p_record);
862
863                 /* data */
864                 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));
865
866                 /* rename file */
867                 if (p_record_vbox == 1)
868                         SPRINT(filename, "%s.wav", p_record_filename);
869                 else
870                         SPRINT(filename, "%s_%s-%s.wav", p_record_filename, callerid, number);
871                 break;
872
873                 case CODEC_LAW:
874                 /* rename file */
875                 if (p_record_vbox == 1)
876                         SPRINT(filename, "%s.isdn", p_record_filename);
877                 else
878                         SPRINT(filename, "%s_%s-%s.isdn", p_record_filename, callerid, number);
879                 break;
880         }
881
882         fclose(p_record);
883         fduse--;
884         p_record = NULL;
885
886         if (rename(p_record_filename, filename) < 0) {
887                 PERROR("Port(%d) cannot rename from '%s' to '%s'\n", p_serial, p_record_filename, filename);
888                 return;
889         }
890
891         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);
892
893         if (p_record_vbox == 2) {
894                 SPRINT(indexname, "%s/%s/vbox/index", EXTENSION_DATA, p_record_extension);
895                 if ((fp = fopen(indexname,"a"))) {
896                         fduse++;
897
898                         /* remove path from file name */
899                         p = filename;
900                         while(strchr(p, '/'))
901                                 p = strchr(p, '/')+1;
902                         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);
903
904                         fclose(fp);
905                         fduse--;
906                 } else {
907                         PERROR("Port(%d) cannot open index file '%s' to append.\n", p_serial, indexname);
908                 }
909
910                 /* send email with sample*/
911                 if (p_record_vbox_email[0]) {
912                         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);
913                 }
914         }
915 }
916
917
918 /*
919  * recording function
920  * Records all data from down and from up into one single stream.
921  * Both streams may have gaps or jitter.
922  * A Jitter buffer for both streams is used to compensate jitter.
923  * 
924  * If one stream (dir) received packets, they are stored to a
925  * buffer to wait for the other stream (dir), so both streams can 
926  * be combined. If the buffer is full, it's content is written
927  * without mixing stream. (assuming only one stram (dir) exists.)
928  * A flag is used to indicate what stream is currently in buffer.
929  *
930  * NOTE: First stereo sample (odd) is from down, second is from up.
931  */
932 void Port::record(unsigned char *data, int length, int dir_fromup)
933 {
934         unsigned char write_buffer[1024], *d;
935         signed short *s;
936         int free, i, ii;
937         signed int sample;
938
939         /* no recording */
940         if (!p_record || !length)
941                 return;
942
943         /* skip data from local caller (dtmf input) */
944         if (p_record_skip && !dir_fromup) {
945                 /* more to skip than we have */
946                 if (p_record_skip > length) {
947                         p_record_skip -= length;
948                         return;
949                 }
950                 /* less to skip */
951                 data += p_record_skip;
952                 length -= p_record_skip;
953                 p_record_skip = 0;
954         }
955
956 //printf("dir=%d len=%d\n", dir_fromup, length);
957
958         free = ((p_record_buffer_readp - p_record_buffer_writep - 1) & RECORD_BUFFER_MASK);
959
960 //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);
961
962         /* the buffer stores the same data stream */
963         if (dir_fromup == p_record_buffer_dir) {
964 same_again:
965
966 //printf("same free=%d length=%d\n", free, length);
967                 /* first write what we can to the buffer */
968                 while(free && length) {
969                         p_record_buffer[p_record_buffer_writep] = audio_law_to_s32[*data++];
970                         p_record_buffer_writep = (p_record_buffer_writep + 1) & RECORD_BUFFER_MASK;
971                         free--;
972                         length--;
973                 }
974                 /* all written, so we return */
975                 if (!length)
976                         return;
977                 /* still data left, buffer is full, so we need to write a chunk to file */
978                 switch(p_record_type) {
979                         case CODEC_MONO:
980                         s = (signed short *)write_buffer;
981                         i = 0;
982                         while(i < 256) {
983                                 *s++ = p_record_buffer[p_record_buffer_readp];
984                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
985                                 i++;
986                         }
987                         fwrite(write_buffer, 512, 1, p_record);
988                         p_record_length += 512;
989                         break;
990
991                         case CODEC_STEREO:
992                         s = (signed short *)write_buffer;
993                         if (p_record_buffer_dir) {
994                                 i = 0;
995                                 while(i < 256) {
996                                         *s++ = 0; /* nothing from down */
997                                         *s++ = p_record_buffer[p_record_buffer_readp];
998                                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
999                                         i++;
1000                                 }
1001                         } else {
1002                                 i = 0;
1003                                 while(i < 256) {
1004                                         *s++ = p_record_buffer[p_record_buffer_readp];
1005                                         *s++ = 0; /* nothing from up */
1006                                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1007                                         i++;
1008                                 }
1009                         }
1010                         fwrite(write_buffer, 1024, 1, p_record);
1011                         p_record_length += 1024;
1012                         break;
1013
1014                         case CODEC_8BIT:
1015                         d = write_buffer;
1016                         i = 0;
1017                         while(i < 256) {
1018                                 *d++ = ((unsigned short)(p_record_buffer[p_record_buffer_readp]+0x8000)) >> 8;
1019                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1020                                 i++;
1021                         }
1022                         fwrite(write_buffer, 512, 1, p_record);
1023                         p_record_length += 512;
1024                         break;
1025
1026                         case CODEC_LAW:
1027                         d = write_buffer;
1028                         i = 0;
1029                         while(i < 256) {
1030                                 *d++ = audio_s16_to_law[p_record_buffer[p_record_buffer_readp] & 0xffff];
1031                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1032                                 i++;
1033                         }
1034                         fwrite(write_buffer, 256, 1, p_record);
1035                         p_record_length += 256;
1036                         break;
1037                 }
1038                 /* because we still have data, we write again */
1039                 free += 256;
1040                 goto same_again;
1041         }
1042         /* the buffer stores the other stream */
1043         
1044 different_again:
1045         /* if buffer empty, change it */
1046         if (p_record_buffer_readp == p_record_buffer_writep) {
1047                 p_record_buffer_dir = dir_fromup;
1048                 goto same_again;
1049         }
1050         /* how much data can we mix ? */
1051         ii = (p_record_buffer_writep - p_record_buffer_readp) & RECORD_BUFFER_MASK;
1052         if (length < ii)
1053                 ii = length;
1054
1055         if (ii > 256)
1056                 ii = 256;
1057 //printf("same ii=%d length=%d\n", ii, length);
1058 //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);
1059
1060         /* write data mixed with the buffer */
1061         switch(p_record_type) {
1062                 case CODEC_MONO:
1063                 s = (signed short *)write_buffer;
1064                 i = 0;
1065                 while(i < ii) {
1066                         sample = p_record_buffer[p_record_buffer_readp]
1067                                 + audio_law_to_s32[*data++];
1068                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1069                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1070                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1071                         *s++ = sample;
1072                         i++;
1073                 }
1074                 fwrite(write_buffer, ii<<1, 1, p_record);
1075                 p_record_length += (ii<<1);
1076                 break;
1077                 
1078                 case CODEC_STEREO:
1079                 s = (signed short *)write_buffer;
1080                 if (p_record_buffer_dir) {
1081                         i = 0;
1082                         while(i < ii) {
1083                                 *s++ = audio_law_to_s32[*data++];
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                         i = 0;
1090                         while(i < ii) {
1091                                 *s++ = p_record_buffer[p_record_buffer_readp];
1092                                 *s++ = audio_law_to_s32[*data++];
1093                                 p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1094                                 i++;
1095                         }
1096                 }
1097                 fwrite(write_buffer, ii<<2, 1, p_record);
1098                 p_record_length += (ii<<2);
1099                 break;
1100                 
1101                 case CODEC_8BIT:
1102                 d = write_buffer;
1103                 i = 0;
1104                 while(i < ii) {
1105                         sample = p_record_buffer[p_record_buffer_readp]
1106                                 + audio_law_to_s32[*data++];
1107                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1108                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1109                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1110                         *d++ = (sample+0x8000) >> 8;
1111                         i++;
1112                 }
1113                 fwrite(write_buffer, ii, 1, p_record);
1114                 p_record_length += ii;
1115                 break;
1116                 
1117                 case CODEC_LAW:
1118                 d = write_buffer;
1119                 i = 0;
1120                 while(i < ii) {
1121                         sample = p_record_buffer[p_record_buffer_readp]
1122                                 + audio_law_to_s32[*data++];
1123                         p_record_buffer_readp = (p_record_buffer_readp + 1) & RECORD_BUFFER_MASK;
1124                         if (sample < SHORT_MIN) sample = SHORT_MIN;
1125                         if (sample > SHORT_MAX) sample = SHORT_MAX;
1126                         *d++ = audio_s16_to_law[sample & 0xffff];
1127                         i++;
1128                 }
1129                 fwrite(write_buffer, ii, 1, p_record);
1130                 p_record_length += ii;
1131                 break;
1132         }
1133         length -= ii;
1134         /* still data */
1135         if (length)
1136                 goto different_again;
1137         /* no data (maybe buffer) */
1138         return;
1139
1140 }
1141
1142