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