]> git.mxchange.org Git - flightgear.git/blob - 3rdparty/iaxclient/lib/iaxclient_lib.c
VS2015 compatability fixes.
[flightgear.git] / 3rdparty / iaxclient / lib / iaxclient_lib.c
1 /*
2  * iaxclient: a cross-platform IAX softphone library
3  *
4  * Copyrights:
5  * Copyright (C) 2003-2006, Horizon Wimba, Inc.
6  * Copyright (C) 2007, Wimba, Inc.
7  *
8  * Contributors:
9  * Steve Kann <stevek@stevek.com>
10  * Michael Van Donselaar <mvand@vandonselaar.org>
11  * Shawn Lawrence <shawn.lawrence@terracecomm.com>
12  * Frik Strecker <frik@gatherworks.com>
13  * Mihai Balea <mihai AT hates DOT ms>
14  * Peter Grayson <jpgrayson@gmail.com>
15  * Bill Cholewka <bcholew@gmail.com>
16  * Erik Bunce <kde@bunce.us>
17  *
18  * This program is free software, distributed under the terms of
19  * the GNU Lesser (Library) General Public License.
20  */
21
22 #include <assert.h>
23
24 #if defined(WIN32) || defined(_WIN32_WCE)
25 #include <stdlib.h>
26 #endif
27
28 /* Win32 has _vsnprintf instead of vsnprintf */
29 #if ! HAVE_VSNPRINTF
30 # if HAVE__VSNPRINTF
31 #  define vsnprintf _vsnprintf
32 # endif
33 #endif
34
35 #include "iaxclient_lib.h"
36 #include "audio_portaudio.h"
37 #include "audio_encode.h"
38 #ifdef USE_VIDEO
39 #include "video.h"
40 #endif
41 #include "iax-client.h"
42 #include "jitterbuf.h"
43
44 #include <stdarg.h>
45
46 #ifdef AUDIO_ALSA
47 #include "audio_alsa.h"
48 #endif
49
50 #define IAXC_ERROR  IAXC_TEXT_TYPE_ERROR
51 #define IAXC_STATUS IAXC_TEXT_TYPE_STATUS
52 #define IAXC_NOTICE IAXC_TEXT_TYPE_NOTICE
53
54 #define DEFAULT_CALLERID_NAME    "Not Available"
55 #define DEFAULT_CALLERID_NUMBER  "7005551212"
56
57 #undef JB_DEBUGGING
58
59 /* global test mode flag */
60 int test_mode = 0;
61
62 /* configurable jitterbuffer options */
63 static long jb_target_extra = -1;
64
65 struct iaxc_registration
66 {
67         struct iax_session *session;
68         struct timeval last;
69         char host[256];
70         char user[256];
71         char pass[256];
72         long refresh;
73         int id;
74         struct iaxc_registration *next;
75 };
76
77 static int next_registration_id = 0;
78 static struct iaxc_registration *registrations = NULL;
79
80 static struct iaxc_audio_driver audio_driver;
81
82 static int audio_format_capability;
83 static int audio_format_preferred;
84
85 // Audio callback behavior
86 // By default apps should let iaxclient handle audio
87 static unsigned int audio_prefs = 0;
88
89 void * post_event_handle = NULL;
90 int post_event_id = 0;
91
92 static int minimum_outgoing_framesize = 160; /* 20ms */
93
94 static MUTEX iaxc_lock;
95 static MUTEX event_queue_lock;
96
97 static int iaxci_bound_port = -1;
98
99 // default to use port 4569 unless set by iaxc_set_preferred_source_udp_port
100 static int source_udp_port = IAX_DEFAULT_PORTNO;
101
102 int iaxci_audio_output_mode = 0; // Normal
103
104 int selected_call; // XXX to be protected by mutex?
105 struct iaxc_call* calls;
106 int max_calls; // number of calls for this library session
107
108 static void service_network();
109 static int service_audio();
110
111 /* external global networking replacements */
112 static iaxc_sendto_t iaxc_sendto = (iaxc_sendto_t)sendto;
113 static iaxc_recvfrom_t iaxc_recvfrom = (iaxc_recvfrom_t)recvfrom;
114
115
116 static THREAD main_proc_thread;
117 #if defined(WIN32) || defined(_WIN32_WCE)
118 static THREADID main_proc_thread_id;
119 #endif
120
121 /* 0 running, 1 should quit, -1 not running */
122 static int main_proc_thread_flag = -1;
123
124 static iaxc_event_callback_t iaxc_event_callback = NULL;
125
126 // Internal queue of events, waiting to be posted once the library
127 // lock is released.
128 static iaxc_event *event_queue = NULL;
129
130 // Lock the library
131 static void get_iaxc_lock()
132 {
133         MUTEXLOCK(&iaxc_lock);
134 }
135
136 int try_iaxc_lock()
137 {
138         return MUTEXTRYLOCK(&iaxc_lock);
139 }
140
141 // Unlock the library and post any events that were queued in the meantime
142 void put_iaxc_lock()
143 {
144         iaxc_event *prev, *event;
145
146         MUTEXLOCK(&event_queue_lock);
147         event = event_queue;
148         event_queue = NULL;
149         MUTEXUNLOCK(&event_queue_lock);
150
151         MUTEXUNLOCK(&iaxc_lock);
152
153         while (event)
154         {
155                 iaxci_post_event(*event);
156                 prev = event;
157                 event = event->next;
158                 free(prev);
159         }
160 }
161
162 EXPORT void iaxc_set_audio_output(int mode)
163 {
164         iaxci_audio_output_mode = mode;
165 }
166
167 long iaxci_usecdiff(struct timeval * t0, struct timeval * t1)
168 {
169         return (t0->tv_sec - t1->tv_sec) * 1000000L + t0->tv_usec - t1->tv_usec;
170 }
171
172 long iaxci_msecdiff(struct timeval * t0, struct timeval * t1)
173 {
174         return iaxci_usecdiff(t0, t1) / 1000L;
175 }
176
177 EXPORT void iaxc_set_event_callback(iaxc_event_callback_t func)
178 {
179         iaxc_event_callback = func;
180 }
181
182 EXPORT int iaxc_set_event_callpost(void *handle, int id)
183 {
184         post_event_handle = handle;
185         post_event_id = id;
186         iaxc_event_callback = iaxci_post_event_callback;
187         return 0;
188 }
189
190 EXPORT void iaxc_free_event(iaxc_event *e)
191 {
192         free(e);
193 }
194
195 EXPORT struct iaxc_ev_levels *iaxc_get_event_levels(iaxc_event *e)
196 {
197         return &e->ev.levels;
198 }
199
200 EXPORT struct iaxc_ev_text *iaxc_get_event_text(iaxc_event *e)
201 {
202         return &e->ev.text;
203 }
204
205 EXPORT struct iaxc_ev_call_state *iaxc_get_event_state(iaxc_event *e)
206 {
207         return &e->ev.call;
208 }
209
210 // Messaging functions
211 static void default_message_callback(const char * message)
212 {
213         //fprintf(stderr, "IAXCLIENT: %s\n", message);
214 }
215
216 // Post Events back to clients
217 void iaxci_post_event(iaxc_event e)
218 {
219         if ( e.type == 0 )
220         {
221                 iaxci_usermsg(IAXC_ERROR,
222                         "Error: something posted to us an invalid event");
223                 return;
224         }
225
226         if ( MUTEXTRYLOCK(&iaxc_lock) )
227         {
228                 iaxc_event **tail;
229
230                 /* We could not obtain the lock. Queue the event. */
231                 MUTEXLOCK(&event_queue_lock);
232                 tail = &event_queue;
233                 e.next = NULL;
234                 while ( *tail )
235                         tail = &(*tail)->next;
236                 *tail = (iaxc_event *)malloc(sizeof(iaxc_event));
237                 memcpy(*tail, &e, sizeof(iaxc_event));
238                 MUTEXUNLOCK(&event_queue_lock);
239                 return;
240         }
241
242         /* TODO: This is not the best. Since we were able to get the
243          * lock, we decide that it is okay to go ahead and do the
244          * callback to the application. This is really nasty because
245          * it gives the appearance of serialized callbacks, but in
246          * reality, we could callback an application multiple times
247          * simultaneously. So, as things stand, an application must
248          * do some locking in their callback function to make it
249          * reentrant. Barf. More ideally, iaxclient would guarantee
250          * serialized callbacks to the application.
251          */
252         MUTEXUNLOCK(&iaxc_lock);
253
254         if ( iaxc_event_callback )
255         {
256                 int rv;
257
258                 rv = iaxc_event_callback(e);
259
260                 if ( e.type == IAXC_EVENT_VIDEO )
261                 {
262                         /* We can free the frame data once it is off the
263                          * event queue and has been processed by the client.
264                          */
265                         free(e.ev.video.data);
266                 }
267                 else if ( e.type == IAXC_EVENT_AUDIO )
268                 {
269                         free(e.ev.audio.data);
270                 }
271
272                 if ( rv < 0 )
273                         default_message_callback(
274                                 "IAXCLIENT: BIG PROBLEM, event callback returned failure!");
275                 // > 0 means processed
276                 if ( rv > 0 )
277                         return;
278
279                 // else, fall through to "defaults"
280         }
281
282         switch ( e.type )
283         {
284                 case IAXC_EVENT_TEXT:
285                         default_message_callback(e.ev.text.message);
286                         // others we just ignore too
287                         return;
288         }
289 }
290
291
292 void iaxci_usermsg(int type, const char *fmt, ...)
293 {
294         va_list args;
295         iaxc_event e;
296
297         e.type = IAXC_EVENT_TEXT;
298         e.ev.text.type = type;
299         e.ev.text.callNo = -1;
300         va_start(args, fmt);
301         vsnprintf(e.ev.text.message, IAXC_EVENT_BUFSIZ, fmt, args);
302         va_end(args);
303
304         iaxci_post_event(e);
305 }
306
307
308 void iaxci_do_levels_callback(float input, float output)
309 {
310         iaxc_event e;
311         e.type = IAXC_EVENT_LEVELS;
312         e.ev.levels.input = input;
313         e.ev.levels.output = output;
314         iaxci_post_event(e);
315 }
316
317 void iaxci_do_state_callback(int callNo)
318 {
319         iaxc_event e;
320         if ( callNo < 0 || callNo >= max_calls )
321                 return;
322         e.type = IAXC_EVENT_STATE;
323         e.ev.call.callNo = callNo;
324         e.ev.call.state = calls[callNo].state;
325         e.ev.call.format = calls[callNo].format;
326         e.ev.call.vformat = calls[callNo].vformat;
327         strncpy(e.ev.call.remote,        calls[callNo].remote,        IAXC_EVENT_BUFSIZ);
328         strncpy(e.ev.call.remote_name,   calls[callNo].remote_name,   IAXC_EVENT_BUFSIZ);
329         strncpy(e.ev.call.local,         calls[callNo].local,         IAXC_EVENT_BUFSIZ);
330         strncpy(e.ev.call.local_context, calls[callNo].local_context, IAXC_EVENT_BUFSIZ);
331         iaxci_post_event(e);
332 }
333
334 void iaxci_do_registration_callback(int id, int reply, int msgcount)
335 {
336         iaxc_event e;
337         e.type = IAXC_EVENT_REGISTRATION;
338         e.ev.reg.id = id;
339         e.ev.reg.reply = reply;
340         e.ev.reg.msgcount = msgcount;
341         iaxci_post_event(e);
342 }
343
344 void iaxci_do_audio_callback(int callNo, unsigned int ts, int source,
345                 int encoded, int format, int size, unsigned char *data)
346 {
347         iaxc_event e;
348
349         e.type = IAXC_EVENT_AUDIO;
350         e.ev.audio.ts = ts;
351         e.ev.audio.encoded = encoded;
352         assert(source == IAXC_SOURCE_REMOTE || source == IAXC_SOURCE_LOCAL);
353         e.ev.audio.source = source;
354         e.ev.audio.size = size;
355         e.ev.audio.callNo = callNo;
356         e.ev.audio.format = format;
357
358         e.ev.audio.data = (unsigned char *)malloc(size);
359
360         if ( !e.ev.audio.data )
361         {
362                 iaxci_usermsg(IAXC_ERROR,
363                                 "failed to allocate memory for audio event");
364                 return;
365         }
366
367         memcpy(e.ev.audio.data, data, size);
368
369         iaxci_post_event(e);
370 }
371
372 void iaxci_do_dtmf_callback(int callNo, char digit)
373 {
374         iaxc_event e;
375         e.type = IAXC_EVENT_DTMF;
376         e.ev.dtmf.callNo = callNo;
377         e.ev.dtmf.digit  = digit;
378         iaxci_post_event(e);
379 }
380
381 static int iaxc_remove_registration_by_id(int id)
382 {
383         struct iaxc_registration *curr, *prev;
384         int count = 0;
385         for ( prev = NULL, curr = registrations; curr != NULL;
386                         prev = curr, curr = curr->next )
387         {
388                 if ( curr->id == id )
389                 {
390                         count++;
391                         if ( curr->session != NULL )
392                                 iax_destroy( curr->session );
393                         if ( prev != NULL )
394                                 prev->next = curr->next;
395                         else
396                                 registrations = curr->next;
397                         free( curr );
398                         break;
399                 }
400         }
401         return count;
402 }
403
404 EXPORT int iaxc_first_free_call()
405 {
406         int i;
407         for ( i = 0; i < max_calls; i++ )
408                 if ( calls[i].state == IAXC_CALL_STATE_FREE )
409                         return i;
410
411         return -1;
412 }
413
414
415 static void iaxc_clear_call(int toDump)
416 {
417         // XXX libiax should handle cleanup, I think..
418         calls[toDump].state = IAXC_CALL_STATE_FREE;
419         calls[toDump].format = 0;
420         calls[toDump].vformat = 0;
421         calls[toDump].session = NULL;
422         iaxci_do_state_callback(toDump);
423 }
424
425 /* select a call.  */
426 /* XXX Locking??  Start/stop audio?? */
427 EXPORT int iaxc_select_call(int callNo)
428 {
429         // continue if already selected?
430         //if ( callNo == selected_call ) return;
431
432         if ( callNo >= max_calls )
433         {
434                 iaxci_usermsg(IAXC_ERROR, "Error: tried to select out_of_range call %d", callNo);
435                 return -1;
436         }
437
438         // callNo < 0 means no call selected (i.e. all on hold)
439         if ( callNo < 0 )
440         {
441                 if ( selected_call >= 0 )
442                 {
443                         calls[selected_call].state &= ~IAXC_CALL_STATE_SELECTED;
444                 }
445                 selected_call = callNo;
446                 return 0;
447         }
448
449         // de-select and notify the old call if not also the new call
450         if ( callNo != selected_call )
451         {
452                 if ( selected_call >= 0 )
453                 {
454                         calls[selected_call].state &= ~IAXC_CALL_STATE_SELECTED;
455                         iaxci_do_state_callback(selected_call);
456                 }
457                 selected_call = callNo;
458                 calls[selected_call].state |= IAXC_CALL_STATE_SELECTED;
459         }
460
461         // if it's an incoming call, and ringing, answer it.
462         if ( !(calls[selected_call].state & IAXC_CALL_STATE_OUTGOING) &&
463               (calls[selected_call].state & IAXC_CALL_STATE_RINGING) )
464         {
465                 iaxc_answer_call(selected_call);
466         } else
467         {
468                 // otherwise just update state (answer does this for us)
469                 iaxci_do_state_callback(selected_call);
470         }
471
472         return 0;
473 }
474
475 /* external API accessor */
476 EXPORT int iaxc_selected_call()
477 {
478         return selected_call;
479 }
480
481 EXPORT void iaxc_set_networking(iaxc_sendto_t st, iaxc_recvfrom_t rf)
482 {
483         iaxc_sendto = st;
484         iaxc_recvfrom = rf;
485 }
486
487 EXPORT void iaxc_set_jb_target_extra( long value )
488 {
489         /* store in jb_target_extra, a static global */
490         jb_target_extra = value;
491 }
492
493 static void jb_errf(const char *fmt, ...)
494 {
495         va_list args;
496         char buf[1024];
497
498         va_start(args, fmt);
499         vsnprintf(buf, 1024, fmt, args);
500         va_end(args);
501
502         iaxci_usermsg(IAXC_ERROR, buf);
503 }
504
505 static void jb_warnf(const char *fmt, ...)
506 {
507         va_list args;
508         char buf[1024];
509
510         va_start(args, fmt);
511         vsnprintf(buf, 1024, fmt, args);
512         va_end(args);
513
514         iaxci_usermsg(IAXC_NOTICE, buf);
515 }
516
517 #ifdef JB_DEBUGGING
518 static void jb_dbgf(const char *fmt, ...)
519 {
520         va_list args;
521
522         va_start(args, fmt);
523         vfprintf(stderr, fmt, args);
524         va_end(args);
525 }
526 #endif
527
528 static void setup_jb_output()
529 {
530 #ifdef JB_DEBUGGING
531         jb_setoutput(jb_errf, jb_warnf, jb_dbgf);
532 #else
533         jb_setoutput(jb_errf, jb_warnf, NULL);
534 #endif
535 }
536
537 // Note: Must be called before iaxc_initialize()
538 EXPORT void iaxc_set_preferred_source_udp_port(int port)
539 {
540         source_udp_port = port;
541 }
542
543 /* For "slow" systems. See iax.c code */
544 EXPORT int iaxc_video_bypass_jitter(int mode)
545 {
546         /* TODO:
547          * 1. When switching from jitter to no-jitter the buffer must be
548          *    flushed of queued video packet and must be sent a key-frame
549          *    to redraw the screen (partially done).
550          * 2. When switching from no-jitter to jitter we must drop all
551          *    enqueued events prior the mode change (must be touched
552          *    iax_sched_del and iax_get_event).
553          */
554         return iax_video_bypass_jitter(calls[selected_call].session,mode);
555 }
556
557 EXPORT int iaxc_get_bind_port()
558 {
559         return iaxci_bound_port;
560 }
561
562 EXPORT int iaxc_initialize(int num_calls)
563 {
564         int i;
565         int port;
566
567         os_init();
568
569         setup_jb_output();
570
571         MUTEXINIT(&iaxc_lock);
572         MUTEXINIT(&event_queue_lock);
573
574         iaxc_set_audio_prefs(0);
575
576         if ( iaxc_recvfrom != (iaxc_recvfrom_t)recvfrom )
577                 iax_set_networking(iaxc_sendto, iaxc_recvfrom);
578
579         /* Note that iax_init() only sets up the receive port when the
580          * sendto/recvfrom functions have not been replaced. We need
581          * to call iaxc_init in either case because there is other
582          * initialization beyond the socket setup that needs to be done.
583          */
584         if ( (port = iax_init(source_udp_port)) < 0 )
585         {
586                 iaxci_usermsg(IAXC_ERROR,
587                                 "Fatal error: failed to initialize iax with port %d",
588                                 port);
589                 return -1;
590         }
591
592         if ( iaxc_recvfrom == (iaxc_recvfrom_t)recvfrom )
593                 iaxci_bound_port = port;
594         else
595                 iaxci_bound_port = -1;
596
597         /* tweak the jitterbuffer settings */
598         iax_set_jb_target_extra( jb_target_extra );
599
600         max_calls = num_calls;
601         /* initialize calls */
602         if ( max_calls <= 0 )
603                 max_calls = 1; /* 0 == Default? */
604
605         /* calloc zeroes for us */
606         calls = (struct iaxc_call *)calloc(sizeof(struct iaxc_call), max_calls);
607         if ( !calls )
608         {
609                 iaxci_usermsg(IAXC_ERROR, "Fatal error: can't allocate memory");
610                 return -1;
611         }
612
613         selected_call = -1;
614
615         for ( i = 0; i < max_calls; i++ )
616         {
617                 strncpy(calls[i].callerid_name,   DEFAULT_CALLERID_NAME,   IAXC_EVENT_BUFSIZ);
618                 strncpy(calls[i].callerid_number, DEFAULT_CALLERID_NUMBER, IAXC_EVENT_BUFSIZ);
619         }
620
621         if ( !test_mode )
622         {
623 #ifdef AUDIO_PA
624                 if ( pa_initialize(&audio_driver, 8000) )
625                 {
626                         iaxci_usermsg(IAXC_ERROR, "failed pa_initialize");
627                         return -1;
628                 }
629 #endif
630 #ifdef AUDIO_ALSA
631                 /* TODO: It is unknown whether this stuff for direct access to
632                 * alsa should be left in iaxclient. We're leaving it in here for
633                 * the time being, but unless it becomes clear that someone cares
634                 * about having it, it will be removed. Also note that portaudio
635                 * is capable of using alsa. This is another reason why this
636                 * direct alsa access may be unneeded.
637                 */
638                 if ( alsa_initialize(&audio_driver, 8000) )
639                         return -1;
640 #endif
641 #ifdef AUDIO_OPENAL
642                 if ( openal_initialize(&audio_driver, 8000) )
643                 {
644                         iaxci_usermsg(IAXC_ERROR, "failed openal_initialize");
645                         return -1;
646                 }
647 #endif
648         }
649 #ifdef USE_VIDEO
650         if ( video_initialize() )
651                 iaxci_usermsg(IAXC_ERROR,
652                                 "iaxc_initialize: cannot initialize video!\n");
653 #endif
654
655         /* Default audio format capabilities */
656         audio_format_capability =
657             IAXC_FORMAT_ULAW |
658             IAXC_FORMAT_ALAW |
659 #ifdef CODEC_GSM
660             IAXC_FORMAT_GSM |
661 #endif
662             IAXC_FORMAT_SPEEX;
663         audio_format_preferred = IAXC_FORMAT_SPEEX;
664
665         return 0;
666 }
667
668 EXPORT void iaxc_shutdown()
669 {
670         iaxc_dump_all_calls();
671
672         get_iaxc_lock();
673
674         if ( !test_mode )
675         {
676                 audio_driver.destroy(&audio_driver);
677 #ifdef USE_VIDEO
678                 video_destroy();
679 #endif
680         }
681         
682         /* destroy enocders and decoders for all existing calls */
683         if ( calls ) 
684         {
685                 int i;
686                 for ( i=0 ; i<max_calls ; i++ ) 
687                 {
688                         if ( calls[i].encoder )
689                                 calls[i].encoder->destroy(calls[i].encoder);
690                         if ( calls[i].decoder )
691                                 calls[i].decoder->destroy(calls[i].decoder);
692                         if ( calls[i].vencoder )
693                                 calls[i].vencoder->destroy(calls[i].vencoder);
694                         if ( calls[i].vdecoder )
695                                 calls[i].vdecoder->destroy(calls[i].vdecoder);
696                 }
697                 free(calls);
698                 calls = NULL;
699         }
700         put_iaxc_lock();
701 #ifdef WIN32
702         //closesocket(iax_get_fd()); //fd:
703 #endif
704
705         free(calls);
706
707         MUTEXDESTROY(&event_queue_lock);
708         MUTEXDESTROY(&iaxc_lock);
709 }
710
711
712 EXPORT void iaxc_set_formats(int preferred, int allowed)
713 {
714         audio_format_capability = allowed;
715         audio_format_preferred = preferred;
716 }
717
718 EXPORT void iaxc_set_min_outgoing_framesize(int samples)
719 {
720         minimum_outgoing_framesize = samples;
721 }
722
723 EXPORT void iaxc_set_callerid(const char * name, const char * number)
724 {
725         int i;
726
727         for ( i = 0; i < max_calls; i++ )
728         {
729                 strncpy(calls[i].callerid_name,   name,   IAXC_EVENT_BUFSIZ);
730                 strncpy(calls[i].callerid_number, number, IAXC_EVENT_BUFSIZ);
731         }
732 }
733
734 static void iaxc_note_activity(int callNo)
735 {
736         if ( callNo < 0 )
737                 return;
738         calls[callNo].last_activity = iax_tvnow();
739 }
740
741 static void iaxc_refresh_registrations()
742 {
743         struct iaxc_registration *cur;
744         struct timeval now;
745
746         now = iax_tvnow();
747
748         for ( cur = registrations; cur != NULL; cur = cur->next )
749         {
750                 // If there is less than three seconds before the registration is about
751                 // to expire, renew it.
752                 if ( iaxci_usecdiff(&now, &cur->last) > (cur->refresh - 3) * 1000 *1000 )
753                 {
754                         if ( cur->session != NULL )
755                         {
756                                 iax_destroy( cur->session );
757                         }
758                         cur->session = iax_session_new();
759                         if ( !cur->session )
760                         {
761                                 iaxci_usermsg(IAXC_ERROR, "Can't make new registration session");
762                                 return;
763                         }
764                         iax_register(cur->session, cur->host, cur->user, cur->pass, cur->refresh);
765                         cur->last = now;
766                 }
767         }
768 }
769
770 #define LOOP_SLEEP 5 // In ms
771 static THREADFUNCDECL(main_proc_thread_func)
772 {
773         static int refresh_registration_count = 0;
774
775         THREADFUNCRET(ret);
776
777         /* Increase Priority */
778         iaxci_prioboostbegin();
779
780         while ( !main_proc_thread_flag )
781         {
782                 get_iaxc_lock();
783
784                 service_network();
785                 if ( !test_mode )
786                         service_audio();
787
788                 // Check registration refresh once a second
789                 if ( refresh_registration_count++ > 1000/LOOP_SLEEP )
790                 {
791                         iaxc_refresh_registrations();
792                         refresh_registration_count = 0;
793                 }
794
795                 put_iaxc_lock();
796
797                 iaxc_millisleep(LOOP_SLEEP);
798         }
799
800         /* Decrease priority */
801         iaxci_prioboostend();
802
803         main_proc_thread_flag = -1;
804
805         return ret;
806 }
807
808 EXPORT int iaxc_start_processing_thread()
809 {
810         main_proc_thread_flag = 0;
811
812         if ( THREADCREATE(main_proc_thread_func, NULL, main_proc_thread,
813                                 main_proc_thread_id) == THREADCREATE_ERROR)
814                 return -1;
815
816         return 0;
817 }
818
819 EXPORT int iaxc_stop_processing_thread()
820 {
821         if ( main_proc_thread_flag >= 0 )
822         {
823                 main_proc_thread_flag = 1;
824                 THREADJOIN(main_proc_thread);
825         }
826
827         return 0;
828 }
829
830 static int service_audio()
831 {
832         /* TODO: maybe we shouldn't allocate 8kB on the stack here. */
833         short buf [4096];
834
835         int want_send_audio =
836                 selected_call >= 0 &&
837                 ((calls[selected_call].state & IAXC_CALL_STATE_OUTGOING) ||
838                  (calls[selected_call].state & IAXC_CALL_STATE_COMPLETE))
839                 && !(audio_prefs & IAXC_AUDIO_PREF_SEND_DISABLE);
840
841         int want_local_audio =
842                 (audio_prefs & IAXC_AUDIO_PREF_RECV_LOCAL_RAW) ||
843                 (audio_prefs & IAXC_AUDIO_PREF_RECV_LOCAL_ENCODED);
844
845         if ( want_local_audio || want_send_audio )
846         {
847                 for ( ;; )
848                 {
849                         int to_read;
850                         int cmin;
851
852                         audio_driver.start(&audio_driver);
853
854                         /* use codec minimum if higher */
855                         cmin = want_send_audio && calls[selected_call].encoder ?
856                                 calls[selected_call].encoder->minimum_frame_size :
857                                 1;
858
859                         to_read = cmin > minimum_outgoing_framesize ?
860                                 cmin : minimum_outgoing_framesize;
861
862                         /* Round up to the next multiple */
863                         if ( to_read % cmin )
864                                 to_read += cmin - (to_read % cmin);
865
866                         if ( to_read > (int)(sizeof(buf) / sizeof(short)) )
867                         {
868                                 fprintf(stderr,
869                                         "internal error: to_read > sizeof(buf)\n");
870                                 exit(1);
871                         }
872
873                         /* Currently pa gives us either all the bits we ask for or none */
874                         if ( audio_driver.input(&audio_driver, buf, &to_read) )
875                         {
876                                 iaxci_usermsg(IAXC_ERROR, "ERROR reading audio\n");
877                                 break;
878                         }
879
880                         /* Frame was not available */
881                         if ( !to_read )
882                                 break;
883
884                         if ( audio_prefs & IAXC_AUDIO_PREF_RECV_LOCAL_RAW )
885                                 iaxci_do_audio_callback(selected_call, 0,
886                                                 IAXC_SOURCE_LOCAL, 0, 0,
887                                                 to_read * 2, (unsigned char *)buf);
888
889                         if ( want_send_audio )
890                                 audio_send_encoded_audio(&calls[selected_call],
891                                                 selected_call, buf,
892                                                 calls[selected_call].format &
893                                                         IAXC_AUDIO_FORMAT_MASK,
894                                                 to_read);
895                 }
896         }
897         else
898         {
899                 static int i = 0;
900
901                 audio_driver.stop(&audio_driver);
902
903                 /*!
904                         \deprecated
905                         Q: Why do we continuously send IAXC_EVENT_LEVELS events
906                    when there is no selected call?
907
908                  A: So that certain users of iaxclient do not have to
909                    reset their vu meters when a call ends -- they can just
910                    count on getting level callbacks. This is a bit of a hack
911                    so any applications relying on this behavior should maybe
912                    be changed.
913                  */
914                 if ( i++ % 50 == 0 )
915                         iaxci_do_levels_callback(AUDIO_ENCODE_SILENCE_DB,
916                                         AUDIO_ENCODE_SILENCE_DB);
917         }
918
919         return 0;
920 }
921
922 /* handle IAX text events */
923 static void handle_text_event(struct iax_event *e, int callNo)
924 {
925         iaxc_event ev;
926         int        len;
927
928         if ( callNo < 0 )
929                 return;
930
931         memset(&ev, 0, sizeof(iaxc_event));
932         ev.type = IAXC_EVENT_TEXT;
933         ev.ev.text.type = IAXC_TEXT_TYPE_IAX;
934         ev.ev.text.callNo = callNo;
935
936         len = e->datalen <= IAXC_EVENT_BUFSIZ - 1 ? e->datalen : IAXC_EVENT_BUFSIZ - 1;
937         strncpy(ev.ev.text.message, (char *) e->data, len);
938         iaxci_post_event(ev);
939 }
940
941 /* handle IAX URL events */
942 void handle_url_event( struct iax_event *e, int callNo )
943 {
944         iaxc_event ev;
945
946         if ( callNo < 0 )
947                 return;
948
949         ev.ev.url.callNo = callNo;
950         ev.type = IAXC_EVENT_URL;
951         strcpy( ev.ev.url.url, "" );
952
953         switch ( e->subclass )
954         {
955                 case AST_HTML_URL:
956                         ev.ev.url.type = IAXC_URL_URL;
957                         if ( e->datalen )
958                         {
959                                 if ( e->datalen > IAXC_EVENT_BUFSIZ )
960                                 {
961                                         fprintf( stderr, "ERROR: URL too long %d > %d\n",
962                                                         e->datalen, IAXC_EVENT_BUFSIZ );
963                                 } else
964                                 {
965                                         strncpy( ev.ev.url.url, (char *) e->data, e->datalen );
966                                 }
967                         }
968                         /* fprintf( stderr, "URL:%s\n", ev.ev.url.url ); */
969                         break;
970                 case AST_HTML_LINKURL:
971                         ev.ev.url.type = IAXC_URL_LINKURL;
972                         /* fprintf( stderr, "LINKURL event\n" ); */
973                         break;
974                 case AST_HTML_LDCOMPLETE:
975                         ev.ev.url.type = IAXC_URL_LDCOMPLETE;
976                         /* fprintf( stderr, "LDCOMPLETE event\n" ); */
977                         break;
978                 case AST_HTML_UNLINK:
979                         ev.ev.url.type = IAXC_URL_UNLINK;
980                         /* fprintf( stderr, "UNLINK event\n" ); */
981                         break;
982                 case AST_HTML_LINKREJECT:
983                         ev.ev.url.type = IAXC_URL_LINKREJECT;
984                         /* fprintf( stderr, "LINKREJECT event\n" ); */
985                         break;
986                 default:
987                         fprintf( stderr, "Unknown URL event %d\n", e->subclass );
988                         break;
989         }
990         iaxci_post_event( ev );
991 }
992
993 /* DANGER: bad things can happen if iaxc_netstat != iax_netstat.. */
994 EXPORT int iaxc_get_netstats(int call, int *rtt, struct iaxc_netstat *local,
995                 struct iaxc_netstat *remote)
996 {
997         return iax_get_netstats(calls[call].session, rtt,
998                         (struct iax_netstat *)local,
999                         (struct iax_netstat *)remote);
1000 }
1001
1002 /* handle IAX text events */
1003 static void generate_netstat_event(int callNo)
1004 {
1005         iaxc_event ev;
1006
1007         if ( callNo < 0 )
1008                 return;
1009
1010         ev.type = IAXC_EVENT_NETSTAT;
1011         ev.ev.netstats.callNo = callNo;
1012
1013         /* only post the event if the session is valid, etc */
1014         if ( !iaxc_get_netstats(callNo, &ev.ev.netstats.rtt,
1015                                 &ev.ev.netstats.local, &ev.ev.netstats.remote))
1016                 iaxci_post_event(ev);
1017 }
1018
1019 static void handle_audio_event(struct iax_event *e, int callNo)
1020 {
1021         int total_consumed = 0;
1022         short fr[4096];
1023         const int fr_samples = sizeof(fr) / sizeof(short);
1024         int samples, format;
1025 #ifdef WIN32
1026         int cycles_max = 100; //fd:
1027 #endif
1028         struct iaxc_call *call;
1029
1030         if ( callNo < 0 )
1031                 return;
1032
1033         call = &calls[callNo];
1034
1035         if ( callNo != selected_call )
1036         {
1037             /* drop audio for unselected call? */
1038             return;
1039         }
1040
1041         samples = fr_samples;
1042         format = call->format & IAXC_AUDIO_FORMAT_MASK;
1043
1044         do
1045         {
1046                 int bytes_decoded;
1047
1048                 int mainbuf_delta = fr_samples - samples;
1049
1050                 bytes_decoded = audio_decode_audio(call,
1051                                 fr,
1052                                 e->data + total_consumed,
1053                                 e->datalen - total_consumed,
1054                                 format,
1055                                 &samples);
1056
1057                 if ( bytes_decoded < 0 )
1058                 {
1059                         iaxci_usermsg(IAXC_STATUS,
1060                                 "Bad or incomplete voice packet. Unable to decode. dropping");
1061                         return;
1062                 }
1063
1064                 /* Pass encoded audio back to the app if required */
1065                 if ( audio_prefs & IAXC_AUDIO_PREF_RECV_REMOTE_ENCODED )
1066                         iaxci_do_audio_callback(callNo, e->ts, IAXC_SOURCE_REMOTE,
1067                                         1, format & IAXC_AUDIO_FORMAT_MASK,
1068                                         e->datalen - total_consumed,
1069                                         e->data + total_consumed);
1070
1071 #ifdef WIN32
1072                 //fd: start: for some reason it loops here. Try to avoid it
1073                 cycles_max--;
1074                 if ( cycles_max < 0 )
1075                 {
1076                         iaxc_millisleep(0);
1077                 }
1078                 //fd: end
1079 #endif
1080                 total_consumed += bytes_decoded;
1081                 if ( audio_prefs & IAXC_AUDIO_PREF_RECV_REMOTE_RAW )
1082                 {
1083                         // audio_decode_audio returns the number of samples.
1084                         // We are using 16 bit samples, so we need to double
1085                         // the number to obtain the size in bytes.
1086                         // format will also be 0 since this is raw audio
1087                         int size = (fr_samples - samples - mainbuf_delta) * 2;
1088                         iaxci_do_audio_callback(callNo, e->ts, IAXC_SOURCE_REMOTE,
1089                                         0, 0, size, (unsigned char *)fr);
1090                 }
1091
1092                 if ( iaxci_audio_output_mode )
1093                         continue;
1094
1095                 if ( !test_mode )
1096                         audio_driver.output(&audio_driver, fr,
1097                             fr_samples - samples - mainbuf_delta);
1098
1099         } while ( total_consumed < e->datalen );
1100 }
1101
1102 #ifdef USE_VIDEO
1103 static void handle_video_event(struct iax_event *e, int callNo)
1104 {
1105         struct iaxc_call *call;
1106
1107         if ( callNo < 0 )
1108                 return;
1109
1110         if ( e->datalen == 0 )
1111         {
1112                 iaxci_usermsg(IAXC_STATUS, "Received 0-size packet. Unable to decode.");
1113                 return;
1114         }
1115
1116         call = &calls[callNo];
1117
1118         if ( callNo != selected_call )
1119         {
1120                 /* drop video for unselected call? */
1121                 return;
1122         }
1123
1124         if ( call->vformat )
1125         {
1126                 if ( video_recv_video(call, selected_call, e->data,
1127                                         e->datalen, e->ts, call->vformat) < 0 )
1128                 {
1129                         iaxci_usermsg(IAXC_STATUS,
1130                                 "Bad or incomplete video packet. Unable to decode.");
1131                         return;
1132                 }
1133         }
1134 }
1135 #endif  /* USE_VIDEO */
1136
1137 static void iaxc_handle_network_event(struct iax_event *e, int callNo)
1138 {
1139         if ( callNo < 0 )
1140                 return;
1141
1142         iaxc_note_activity(callNo);
1143
1144         switch ( e->etype )
1145         {
1146         case IAX_EVENT_NULL:
1147                 break;
1148         case IAX_EVENT_HANGUP:
1149                 iaxci_usermsg(IAXC_STATUS, "Call disconnected by remote");
1150                 // XXX does the session go away now?
1151                 iaxc_clear_call(callNo);
1152                 break;
1153         case IAX_EVENT_REJECT:
1154                 iaxci_usermsg(IAXC_STATUS, "Call rejected by remote");
1155                 iaxc_clear_call(callNo);
1156                 break;
1157         case IAX_EVENT_ACCEPT:
1158                 calls[callNo].format = e->ies.format & IAXC_AUDIO_FORMAT_MASK;
1159                 calls[callNo].vformat = e->ies.format & IAXC_VIDEO_FORMAT_MASK;
1160 #ifdef USE_VIDEO
1161                 if ( !(e->ies.format & IAXC_VIDEO_FORMAT_MASK) )
1162                 {
1163                         iaxci_usermsg(IAXC_NOTICE,
1164                                         "Failed video codec negotiation.");
1165                 }
1166 #endif
1167                 iaxci_usermsg(IAXC_STATUS,"Call %d accepted", callNo);
1168                 break;
1169         case IAX_EVENT_ANSWER:
1170                 calls[callNo].state &= ~IAXC_CALL_STATE_RINGING;
1171                 calls[callNo].state |= IAXC_CALL_STATE_COMPLETE;
1172                 iaxci_do_state_callback(callNo);
1173                 iaxci_usermsg(IAXC_STATUS,"Call %d answered", callNo);
1174                 //iaxc_answer_call(callNo);
1175                 // notify the user?
1176                 break;
1177         case IAX_EVENT_BUSY:
1178                 calls[callNo].state &= ~IAXC_CALL_STATE_RINGING;
1179                 calls[callNo].state |= IAXC_CALL_STATE_BUSY;
1180                 iaxci_do_state_callback(callNo);
1181                 iaxci_usermsg(IAXC_STATUS, "Call %d busy", callNo);
1182                 break;
1183         case IAX_EVENT_VOICE:
1184                 handle_audio_event(e, callNo);
1185                 if ( (calls[callNo].state & IAXC_CALL_STATE_OUTGOING) &&
1186                      (calls[callNo].state & IAXC_CALL_STATE_RINGING) )
1187                 {
1188                         calls[callNo].state &= ~IAXC_CALL_STATE_RINGING;
1189                         calls[callNo].state |= IAXC_CALL_STATE_COMPLETE;
1190                         iaxci_do_state_callback(callNo);
1191                         iaxci_usermsg(IAXC_STATUS,"Call %d progress",
1192                                      callNo);
1193                 }
1194                 break;
1195 #ifdef USE_VIDEO
1196         case IAX_EVENT_VIDEO:
1197                 handle_video_event(e, callNo);
1198                 break;
1199 #endif
1200         case IAX_EVENT_TEXT:
1201                 handle_text_event(e, callNo);
1202                 break;
1203         case IAX_EVENT_RINGA:
1204                 calls[callNo].state |= IAXC_CALL_STATE_RINGING;
1205                 iaxci_do_state_callback(callNo);
1206                 iaxci_usermsg(IAXC_STATUS,"Call %d ringing", callNo);
1207                 break;
1208         case IAX_EVENT_PONG:
1209                 generate_netstat_event(callNo);
1210                 break;
1211         case IAX_EVENT_URL:
1212                 handle_url_event(e, callNo);
1213                 break;
1214         case IAX_EVENT_CNG:
1215                 /* ignore? */
1216                 break;
1217         case IAX_EVENT_TIMEOUT:
1218                 iax_hangup(e->session, "Call timed out");
1219                 iaxci_usermsg(IAXC_STATUS, "Call %d timed out.", callNo);
1220                 iaxc_clear_call(callNo);
1221                 break;
1222         case IAX_EVENT_TRANSFER:
1223                 calls[callNo].state |= IAXC_CALL_STATE_TRANSFER;
1224                 iaxci_do_state_callback(callNo);
1225                 iaxci_usermsg(IAXC_STATUS,"Call %d transfer released", callNo);
1226                 break;
1227         case IAX_EVENT_DTMF:
1228                 iaxci_do_dtmf_callback(callNo,e->subclass);
1229                 iaxci_usermsg(IAXC_STATUS, "DTMF digit %c received", e->subclass);
1230                 break;
1231         default:
1232                 iaxci_usermsg(IAXC_STATUS, "Unknown event: %d for call %d", e->etype, callNo);
1233                 break;
1234         }
1235 }
1236
1237 EXPORT int iaxc_unregister( int id )
1238 {
1239         int count = 0;
1240         get_iaxc_lock();
1241         count = iaxc_remove_registration_by_id(id);
1242         put_iaxc_lock();
1243         return count;
1244 }
1245
1246 EXPORT int iaxc_register(const char * user, const char * pass, const char * host)
1247 {
1248         return iaxc_register_ex(user, pass, host, 60);
1249 }
1250
1251 EXPORT int iaxc_register_ex(const char * user, const char * pass, const char * host, int refresh)
1252 {
1253         struct iaxc_registration *newreg;
1254
1255         newreg = (struct iaxc_registration *)malloc(sizeof (struct iaxc_registration));
1256         if ( !newreg )
1257         {
1258                 iaxci_usermsg(IAXC_ERROR, "Can't make new registration");
1259                 return -1;
1260         }
1261
1262         get_iaxc_lock();
1263         newreg->session = iax_session_new();
1264         if ( !newreg->session )
1265         {
1266                 iaxci_usermsg(IAXC_ERROR, "Can't make new registration session");
1267                 put_iaxc_lock();
1268                 return -1;
1269         }
1270
1271         newreg->last = iax_tvnow();
1272         newreg->refresh = refresh;  
1273
1274         strncpy(newreg->host, host, 256);
1275         strncpy(newreg->user, user, 256);
1276         strncpy(newreg->pass, pass, 256);
1277
1278         /* send out the initial registration with refresh seconds */
1279         iax_register(newreg->session, host, user, pass, refresh);
1280
1281         /* add it to the list; */
1282         newreg->id = ++next_registration_id;
1283         newreg->next = registrations;
1284         registrations = newreg;
1285
1286         put_iaxc_lock();
1287         return newreg->id;
1288 }
1289
1290 static void codec_destroy( int callNo )
1291 {
1292         if ( calls[callNo].encoder )
1293         {
1294                 calls[callNo].encoder->destroy( calls[callNo].encoder );
1295                 calls[callNo].encoder = NULL;
1296         }
1297         if ( calls[callNo].decoder )
1298         {
1299                 calls[callNo].decoder->destroy( calls[callNo].decoder );
1300                 calls[callNo].decoder = NULL;
1301         }
1302         if ( calls[callNo].vdecoder )
1303         {
1304                 calls[callNo].vdecoder->destroy(calls[callNo].vdecoder);
1305                 calls[callNo].vdecoder = NULL;
1306         }
1307         if ( calls[callNo].vencoder )
1308         {
1309                 calls[callNo].vencoder->destroy(calls[callNo].vencoder);
1310                 calls[callNo].vencoder = NULL;
1311         }
1312 }
1313
1314 EXPORT int iaxc_call(const char * num)
1315 {
1316         return iaxc_call_ex(num, NULL, NULL, 1);
1317 }
1318
1319 EXPORT int iaxc_call_ex(const char *num, const char* callerid_name, const char* callerid_number, int video)
1320 {
1321         int video_format_capability = 0;
1322         int video_format_preferred = 0;
1323         int callNo = -1;
1324         struct iax_session *newsession;
1325         char *ext = strstr(num, "/");
1326
1327         get_iaxc_lock();
1328
1329         // if no call is selected, get a new appearance
1330         if ( selected_call < 0 )
1331         {
1332                 callNo = iaxc_first_free_call();
1333         } else
1334         {
1335                 // use selected call if not active, otherwise, get a new appearance
1336                 if ( calls[selected_call].state  & IAXC_CALL_STATE_ACTIVE )
1337                 {
1338                         callNo = iaxc_first_free_call();
1339                 } else
1340                 {
1341                         callNo = selected_call;
1342                 }
1343         }
1344
1345         if ( callNo < 0 )
1346         {
1347                 iaxci_usermsg(IAXC_STATUS, "No free call appearances");
1348                 goto iaxc_call_bail;
1349         }
1350
1351         newsession = iax_session_new();
1352         if ( !newsession )
1353         {
1354                 iaxci_usermsg(IAXC_ERROR, "Can't make new session");
1355                 goto iaxc_call_bail;
1356         }
1357
1358         calls[callNo].session = newsession;
1359
1360         codec_destroy( callNo );
1361
1362         if ( ext )
1363         {
1364                 strncpy(calls[callNo].remote_name, num, IAXC_EVENT_BUFSIZ);
1365                 strncpy(calls[callNo].remote,    ++ext, IAXC_EVENT_BUFSIZ);
1366         } else
1367         {
1368                 strncpy(calls[callNo].remote_name, num, IAXC_EVENT_BUFSIZ);
1369                 strncpy(calls[callNo].remote,      "" , IAXC_EVENT_BUFSIZ);
1370         }
1371
1372         if ( callerid_number != NULL )
1373                 strncpy(calls[callNo].callerid_number, callerid_number, IAXC_EVENT_BUFSIZ);
1374
1375         if ( callerid_name != NULL )
1376                 strncpy(calls[callNo].callerid_name, callerid_name, IAXC_EVENT_BUFSIZ);
1377
1378         strncpy(calls[callNo].local        , calls[callNo].callerid_name, IAXC_EVENT_BUFSIZ);
1379         strncpy(calls[callNo].local_context, "default", IAXC_EVENT_BUFSIZ);
1380
1381         calls[callNo].state = IAXC_CALL_STATE_ACTIVE | IAXC_CALL_STATE_OUTGOING;
1382
1383         /* reset activity and ping "timers" */
1384         iaxc_note_activity(callNo);
1385         calls[callNo].last_ping = calls[callNo].last_activity;
1386
1387 #ifdef USE_VIDEO
1388         if ( video )
1389                 iaxc_video_format_get_cap(&video_format_preferred, &video_format_capability);
1390 #endif
1391
1392         iaxci_usermsg(IAXC_NOTICE, "Originating an %s call",
1393                         video_format_preferred ? "audio+video" : "audio only");
1394         iax_call(calls[callNo].session, calls[callNo].callerid_number,
1395                         calls[callNo].callerid_name, num, NULL, 0,
1396                         audio_format_preferred | video_format_preferred,
1397                         audio_format_capability | video_format_capability);
1398
1399         // does state stuff also
1400         iaxc_select_call(callNo);
1401
1402 iaxc_call_bail:
1403         put_iaxc_lock();
1404
1405         return callNo;
1406 }
1407
1408 EXPORT void iaxc_send_busy_on_incoming_call(int callNo)
1409 {
1410         if ( callNo < 0 )
1411                 return;
1412
1413         iax_busy(calls[callNo].session);
1414 }
1415
1416 EXPORT void iaxc_answer_call(int callNo)
1417 {
1418         if ( callNo < 0 )
1419                 return;
1420
1421         calls[callNo].state |= IAXC_CALL_STATE_COMPLETE;
1422         calls[callNo].state &= ~IAXC_CALL_STATE_RINGING;
1423         iax_answer(calls[callNo].session);
1424         iaxci_do_state_callback(callNo);
1425 }
1426
1427 EXPORT void iaxc_blind_transfer_call(int callNo, const char * dest_extension)
1428 {
1429         if ( callNo < 0 || !(calls[callNo].state & IAXC_CALL_STATE_ACTIVE) )
1430                 return;
1431
1432         iax_transfer(calls[callNo].session, dest_extension);
1433 }
1434
1435 EXPORT void iaxc_setup_call_transfer(int sourceCallNo, int targetCallNo)
1436 {
1437         if ( sourceCallNo < 0 || targetCallNo < 0 ||
1438                         !(calls[sourceCallNo].state & IAXC_CALL_STATE_ACTIVE) ||
1439                         !(calls[targetCallNo].state & IAXC_CALL_STATE_ACTIVE) )
1440                 return;
1441
1442         iax_setup_transfer(calls[sourceCallNo].session, calls[targetCallNo].session);
1443 }
1444
1445 static void iaxc_dump_one_call(int callNo)
1446 {
1447         if ( callNo < 0 )
1448                 return;
1449         if ( calls[callNo].state == IAXC_CALL_STATE_FREE )
1450                 return;
1451
1452         iax_hangup(calls[callNo].session,"Dumped Call");
1453         iaxci_usermsg(IAXC_STATUS, "Hanging up call %d", callNo);
1454         iaxc_clear_call(callNo);
1455 }
1456
1457 EXPORT void iaxc_dump_all_calls(void)
1458 {
1459         int callNo;
1460         get_iaxc_lock();
1461         for ( callNo = 0; callNo < max_calls; callNo++ )
1462                 iaxc_dump_one_call(callNo);
1463         put_iaxc_lock();
1464 }
1465
1466
1467 EXPORT void iaxc_dump_call_number( int callNo )
1468 {
1469         if ( ( callNo >= 0 ) && ( callNo < max_calls ) )
1470         {
1471                 get_iaxc_lock();
1472                 iaxc_dump_one_call(callNo);
1473                 put_iaxc_lock();
1474         }
1475 }
1476
1477 EXPORT void iaxc_dump_call(void)
1478 {
1479         if ( selected_call >= 0 )
1480         {
1481                 get_iaxc_lock();
1482                 iaxc_dump_one_call(selected_call);
1483                 put_iaxc_lock();
1484         }
1485 }
1486
1487 EXPORT void iaxc_reject_call(void)
1488 {
1489         if ( selected_call >= 0 )
1490         {
1491                 iaxc_reject_call_number(selected_call);
1492         }
1493 }
1494
1495 EXPORT void iaxc_reject_call_number( int callNo )
1496 {
1497         if ( ( callNo >= 0 ) && ( callNo < max_calls ) )
1498         {
1499                 get_iaxc_lock();
1500                 iax_reject(calls[callNo].session, "Call rejected manually.");
1501                 iaxc_clear_call(callNo);
1502                 put_iaxc_lock();
1503         }
1504 }
1505
1506 EXPORT void iaxc_send_dtmf(char digit)
1507 {
1508         if ( selected_call >= 0 )
1509         {
1510                 get_iaxc_lock();
1511                 if ( calls[selected_call].state & IAXC_CALL_STATE_ACTIVE )
1512                         iax_send_dtmf(calls[selected_call].session,digit);
1513                 put_iaxc_lock();
1514         }
1515 }
1516
1517 EXPORT void iaxc_send_text(const char * text)
1518 {
1519         if ( selected_call >= 0 )
1520         {
1521                 get_iaxc_lock();
1522                 if ( calls[selected_call].state & IAXC_CALL_STATE_ACTIVE )
1523                         iax_send_text(calls[selected_call].session, text);
1524                 put_iaxc_lock();
1525         }
1526 }
1527
1528 EXPORT void iaxc_send_text_call(int callNo, const char * text)
1529 {
1530         if ( callNo < 0 || !(calls[callNo].state & IAXC_CALL_STATE_ACTIVE) )
1531                 return;
1532
1533         get_iaxc_lock();
1534         if ( calls[callNo].state & IAXC_CALL_STATE_ACTIVE )
1535                 iax_send_text(calls[callNo].session, text);
1536         put_iaxc_lock();
1537 }
1538
1539 EXPORT void iaxc_send_url(const char * url, int link)
1540 {
1541         if ( selected_call >= 0 )
1542         {
1543                 get_iaxc_lock();
1544                 if ( calls[selected_call].state & IAXC_CALL_STATE_ACTIVE )
1545                         iax_send_url(calls[selected_call].session, url, link);
1546                 put_iaxc_lock();
1547         }
1548 }
1549
1550 static int iaxc_find_call_by_session(struct iax_session *session)
1551 {
1552         int i;
1553         for ( i = 0; i < max_calls; i++ )
1554                 if ( calls[i].session == session )
1555                         return i;
1556         return -1;
1557 }
1558
1559 static struct iaxc_registration *iaxc_find_registration_by_session(
1560                 struct iax_session *session)
1561 {
1562         struct iaxc_registration *reg;
1563         for (reg = registrations; reg != NULL; reg = reg->next)
1564                 if ( reg->session == session )
1565                         break;
1566         return reg;
1567 }
1568
1569 static void iaxc_handle_regreply(struct iax_event *e, struct iaxc_registration *reg)
1570 {
1571         iaxci_do_registration_callback(reg->id, e->etype, e->ies.msgcount);
1572
1573         // XXX I think the session is no longer valid.. at least, that's
1574         // what miniphone does, and re-using the session doesn't seem to
1575         // work!
1576         iax_destroy(reg->session);
1577         reg->session = NULL;
1578
1579         if ( e->etype == IAX_EVENT_REGREJ )
1580         {
1581                 // we were rejected, so end the registration
1582                 iaxc_remove_registration_by_id(reg->id);
1583         }
1584 }
1585
1586 /* this is what asterisk does */
1587 static int iaxc_choose_codec(int formats)
1588 {
1589         int i;
1590         static int codecs[] =
1591         {
1592                 IAXC_FORMAT_ULAW,
1593                 IAXC_FORMAT_ALAW,
1594                 IAXC_FORMAT_SLINEAR,
1595                 IAXC_FORMAT_G726,
1596                 IAXC_FORMAT_ADPCM,
1597                 IAXC_FORMAT_GSM,
1598                 IAXC_FORMAT_ILBC,
1599                 IAXC_FORMAT_SPEEX,
1600                 IAXC_FORMAT_LPC10,
1601                 IAXC_FORMAT_G729A,
1602                 IAXC_FORMAT_G723_1,
1603
1604                 /* To negotiate video codec */
1605                 IAXC_FORMAT_JPEG,
1606                 IAXC_FORMAT_PNG,
1607                 IAXC_FORMAT_H261,
1608                 IAXC_FORMAT_H263,
1609                 IAXC_FORMAT_H263_PLUS,
1610                 IAXC_FORMAT_MPEG4,
1611                 IAXC_FORMAT_H264,
1612                 IAXC_FORMAT_THEORA,
1613         };
1614         for ( i = 0; i < (int)(sizeof(codecs) / sizeof(int)); i++ )
1615                 if ( codecs[i] & formats )
1616                         return codecs[i];
1617         return 0;
1618 }
1619
1620 static void iaxc_handle_connect(struct iax_event * e)
1621 {
1622 #ifdef USE_VIDEO
1623         int video_format_capability;
1624         int video_format_preferred;
1625 #endif
1626         int video_format = 0;
1627         int format = 0;
1628         int callno;
1629
1630         callno = iaxc_first_free_call();
1631
1632         if ( callno < 0 )
1633         {
1634                 iaxci_usermsg(IAXC_STATUS,
1635                                 "%i \n Incoming Call, but no appearances",
1636                                 callno);
1637                 // XXX Reject this call!, or just ignore?
1638                 //iax_reject(e->session, "Too many calls, we're busy!");
1639                 iax_accept(e->session, audio_format_preferred & e->ies.capability);
1640                 iax_busy(e->session);
1641                 return;
1642         }
1643
1644         /* negotiate codec */
1645         /* first, try _their_ preferred format */
1646         format = audio_format_capability & e->ies.format;
1647         if ( !format )
1648         {
1649                 /* then, try our preferred format */
1650                 format = audio_format_preferred & e->ies.capability;
1651         }
1652
1653         if ( !format )
1654         {
1655                 /* finally, see if we have one in common */
1656                 format = audio_format_capability & e->ies.capability;
1657
1658                 /* now choose amongst these, if we got one */
1659                 if ( format )
1660                 {
1661                         format = iaxc_choose_codec(format);
1662                 }
1663         }
1664
1665         if ( !format )
1666         {
1667                 iax_reject(e->session, "Could not negotiate common codec");
1668                 return;
1669         }
1670
1671 #ifdef USE_VIDEO
1672         iaxc_video_format_get_cap(&video_format_preferred,
1673                         &video_format_capability);
1674
1675         /* first, see if they even want video */
1676         video_format = (e->ies.format & IAXC_VIDEO_FORMAT_MASK);
1677
1678         if ( video_format )
1679         {
1680                 /* next, try _their_ preferred format */
1681                 video_format &= video_format_capability;
1682
1683                 if ( !video_format )
1684                 {
1685                         /* then, try our preferred format */
1686                         video_format = video_format_preferred &
1687                                 (e->ies.capability & IAXC_VIDEO_FORMAT_MASK);
1688                 }
1689
1690                 if ( !video_format )
1691                 {
1692                         /* finally, see if we have one in common */
1693                         video_format = video_format_capability &
1694                                 (e->ies.capability & IAXC_VIDEO_FORMAT_MASK);
1695
1696                         /* now choose amongst these, if we got one */
1697                         if ( video_format )
1698                         {
1699                                 video_format = iaxc_choose_codec(video_format);
1700                         }
1701                 }
1702
1703                 /* All video negotiations failed, then warn */
1704                 if ( !video_format )
1705                 {
1706                         iaxci_usermsg(IAXC_NOTICE,
1707                                         "Notice: could not negotiate common video codec");
1708                         iaxci_usermsg(IAXC_NOTICE,
1709                                         "Notice: switching to audio-only call");
1710                 }
1711         }
1712 #endif  /* USE_VIDEO */
1713
1714         calls[callno].vformat = video_format;
1715         calls[callno].format = format;
1716
1717         if ( e->ies.called_number )
1718                 strncpy(calls[callno].local, e->ies.called_number,
1719                                 IAXC_EVENT_BUFSIZ);
1720         else
1721                 strncpy(calls[callno].local, "unknown",
1722                                 IAXC_EVENT_BUFSIZ);
1723
1724         if ( e->ies.called_context )
1725                 strncpy(calls[callno].local_context, e->ies.called_context,
1726                                 IAXC_EVENT_BUFSIZ);
1727         else
1728                 strncpy(calls[callno].local_context, "",
1729                                 IAXC_EVENT_BUFSIZ);
1730
1731         if ( e->ies.calling_number )
1732                 strncpy(calls[callno].remote, e->ies.calling_number,
1733                                 IAXC_EVENT_BUFSIZ);
1734         else
1735                 strncpy(calls[callno].remote, "unknown",
1736                                 IAXC_EVENT_BUFSIZ);
1737
1738         if ( e->ies.calling_name )
1739                 strncpy(calls[callno].remote_name, e->ies.calling_name,
1740                                 IAXC_EVENT_BUFSIZ);
1741         else
1742                 strncpy(calls[callno].remote_name, "unknown",
1743                                 IAXC_EVENT_BUFSIZ);
1744
1745         iaxc_note_activity(callno);
1746         iaxci_usermsg(IAXC_STATUS, "Call from (%s)", calls[callno].remote);
1747
1748         codec_destroy( callno );
1749
1750         calls[callno].session = e->session;
1751         calls[callno].state = IAXC_CALL_STATE_ACTIVE|IAXC_CALL_STATE_RINGING;
1752
1753         iax_accept(calls[callno].session, format | video_format);
1754         iax_ring_announce(calls[callno].session);
1755
1756         iaxci_do_state_callback(callno);
1757
1758         iaxci_usermsg(IAXC_STATUS, "Incoming call on line %d", callno);
1759 }
1760
1761 static void service_network()
1762 {
1763         struct iax_event *e = 0;
1764         int callNo;
1765         struct iaxc_registration *reg;
1766
1767         while ( (e = iax_get_event(0)) )
1768         {
1769 #ifdef WIN32
1770                 iaxc_millisleep(0); //fd:
1771 #endif
1772                 // first, see if this is an event for one of our calls.
1773                 callNo = iaxc_find_call_by_session(e->session);
1774                 if ( e->etype == IAX_EVENT_NULL )
1775                 {
1776                         // Should we do something here?
1777                         // Right now we do nothing, just go with the flow
1778                         // and let the event be deallocated.
1779                 } else if ( callNo >= 0 )
1780                 {
1781                         iaxc_handle_network_event(e, callNo);
1782                 } else if ( (reg = iaxc_find_registration_by_session(e->session)) != NULL )
1783                 {
1784                         iaxc_handle_regreply(e,reg);
1785                 } else if ( e->etype == IAX_EVENT_REGACK || e->etype == IAX_EVENT_REGREJ )
1786                 {
1787                         iaxci_usermsg(IAXC_ERROR, "Unexpected registration reply");
1788                 } else if ( e->etype == IAX_EVENT_REGREQ )
1789                 {
1790                         iaxci_usermsg(IAXC_ERROR,
1791                                         "Registration requested by someone, but we don't understand!");
1792                 } else if ( e->etype == IAX_EVENT_CONNECT )
1793                 {
1794                         iaxc_handle_connect(e);
1795                 } else if ( e->etype == IAX_EVENT_TIMEOUT )
1796                 {
1797                         iaxci_usermsg(IAXC_STATUS,
1798                                         "Timeout for a non-existant session. Dropping",
1799                                         e->etype);
1800                 } else
1801                 {
1802                         iaxci_usermsg(IAXC_ERROR,
1803                                         "Event (type %d) for a non-existant session. Dropping",
1804                                         e->etype);
1805                 }
1806                 iax_event_free(e);
1807         }
1808 }
1809
1810 EXPORT int iaxc_audio_devices_get(struct iaxc_audio_device **devs, int *nDevs,
1811                 int *input, int *output, int *ring)
1812 {
1813         if ( test_mode )
1814                 return 0;
1815
1816         *devs = audio_driver.devices;
1817         *nDevs = audio_driver.nDevices;
1818         audio_driver.selected_devices(&audio_driver, input, output, ring);
1819         return 0;
1820 }
1821
1822 EXPORT int iaxc_audio_devices_set(int input, int output, int ring)
1823 {
1824         int ret;
1825
1826         if ( test_mode )
1827                 return 0;
1828
1829         get_iaxc_lock();
1830         ret = audio_driver.select_devices(&audio_driver, input, output, ring);
1831         put_iaxc_lock();
1832         return ret;
1833 }
1834
1835 EXPORT float iaxc_input_level_get()
1836 {
1837         if ( test_mode )
1838                 return 0;
1839
1840         return audio_driver.input_level_get(&audio_driver);
1841 }
1842
1843 EXPORT float iaxc_output_level_get()
1844 {
1845         if ( test_mode )
1846                 return 0;
1847
1848         return audio_driver.output_level_get(&audio_driver);
1849 }
1850
1851 EXPORT int iaxc_input_level_set(float level)
1852 {
1853         if ( test_mode )
1854                 return 0;
1855
1856         return audio_driver.input_level_set(&audio_driver, level);
1857 }
1858
1859 EXPORT int iaxc_output_level_set(float level)
1860 {
1861         if ( test_mode )
1862                 return 0;
1863
1864         return audio_driver.output_level_set(&audio_driver, level);
1865 }
1866
1867 EXPORT int iaxc_play_sound(struct iaxc_sound *s, int ring)
1868 {
1869         int ret;
1870
1871         if ( test_mode )
1872                 return 0;
1873
1874         get_iaxc_lock();
1875         ret = audio_driver.play_sound(s,ring);
1876         put_iaxc_lock();
1877         return ret;
1878 }
1879
1880 EXPORT int iaxc_stop_sound(int id)
1881 {
1882         int ret;
1883
1884         if ( test_mode )
1885                 return 0;
1886
1887         get_iaxc_lock();
1888         ret = audio_driver.stop_sound(id);
1889         put_iaxc_lock();
1890         return ret;
1891 }
1892
1893 EXPORT int iaxc_quelch(int callNo, int MOH)
1894 {
1895         struct iax_session *session = calls[callNo].session;
1896         if ( !session )
1897                 return -1;
1898
1899         return iax_quelch_moh(session, MOH);
1900 }
1901
1902 EXPORT int iaxc_unquelch(int call)
1903 {
1904         return iax_unquelch(calls[call].session);
1905 }
1906
1907 EXPORT int iaxc_mic_boost_get( void )
1908 {
1909         return audio_driver.mic_boost_get( &audio_driver ) ;
1910 }
1911
1912 EXPORT int iaxc_mic_boost_set( int enable )
1913 {
1914         return audio_driver.mic_boost_set( &audio_driver, enable ) ;
1915 }
1916
1917 EXPORT char* iaxc_version(char * ver)
1918 {
1919 #ifndef LIBVER
1920 #define LIBVER ""
1921 #endif
1922         strncpy(ver, LIBVER, IAXC_EVENT_BUFSIZ);
1923         return ver;
1924 }
1925
1926 EXPORT unsigned int iaxc_get_audio_prefs(void)
1927 {
1928         return audio_prefs;
1929 }
1930
1931 EXPORT int iaxc_set_audio_prefs(unsigned int prefs)
1932 {
1933         unsigned int prefs_mask =
1934                 IAXC_AUDIO_PREF_RECV_LOCAL_RAW      |
1935                 IAXC_AUDIO_PREF_RECV_LOCAL_ENCODED  |
1936                 IAXC_AUDIO_PREF_RECV_REMOTE_RAW     |
1937                 IAXC_AUDIO_PREF_RECV_REMOTE_ENCODED |
1938                 IAXC_AUDIO_PREF_SEND_DISABLE;
1939
1940         if ( prefs & ~prefs_mask )
1941                 return -1;
1942
1943         audio_prefs = prefs;
1944         return 0;
1945 }
1946
1947 EXPORT void iaxc_set_test_mode(int tm)
1948 {
1949         test_mode = tm;
1950 }
1951
1952 EXPORT int iaxc_push_audio(void *data, unsigned int size, unsigned int samples)
1953 {
1954         struct iaxc_call *call;
1955
1956         if ( selected_call < 0 )
1957                 return -1;
1958
1959         call = &calls[selected_call];
1960
1961         if ( audio_prefs & IAXC_AUDIO_PREF_SEND_DISABLE )
1962                 return 0;
1963
1964         //fprintf(stderr, "iaxc_push_audio: sending audio size %d\n", size);
1965
1966         if ( iax_send_voice(call->session, call->format, data, size, samples) == -1 )
1967         {
1968                 fprintf(stderr, "iaxc_push_audio: failed to send audio frame of size %d on call %d\n", size, selected_call);
1969                 return -1;
1970         }
1971
1972         return 0;
1973 }
1974
1975 void iaxc_debug_iax_set(int enable)
1976 {
1977 #ifdef DEBUG_SUPPORT
1978         if (enable)
1979                 iax_enable_debug();
1980         else
1981                 iax_disable_debug();
1982 #endif
1983 }
1984