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