managerimpl.cpp 44.6 KB
Newer Older
jpbl's avatar
jpbl committed
1
/*
yanmorin's avatar
   
yanmorin committed
2
 *  Copyright (C) 2004-2006 Savoir-Faire Linux inc.
jpbl's avatar
jpbl committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 *  Author: Yan Morin <yan.morin@savoirfairelinux.com>
 *  Author : Laurielle Lea <laurielle.lea@savoirfairelinux.com>
 *                                                                              
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *                                                                              
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *                                                                              
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <errno.h>
#include <time.h>
#include <cstdlib>
#include <iostream>
#include <fstream>

#include <sys/types.h> // mkdir(2)
#include <sys/stat.h>	// mkdir(2)

#include <cc++/socket.h>   // why do I need this here?
#include <ccrtp/channel.h> // why do I need this here?
#include <ccrtp/rtp.h>     // why do I need this here?
#include <cc++/file.h>

#include "manager.h"
#include "audio/audiolayer.h"
#include "audio/audiocodec.h"
#include "audio/tonelist.h"

yanmorin's avatar
   
yanmorin committed
40
#include "accountcreator.h" // create new account
jpbl's avatar
jpbl committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "voIPLink.h"
#include "call.h"

#include "user_cfg.h"
#include "gui/guiframework.h"

#ifdef USE_ZEROCONF
#include "zeroconf/DNSService.h"
#include "zeroconf/DNSServiceTXTRecord.h"
#endif

#define fill_config_str(name, value) \
  (_config.addConfigTreeItem(section, Conf::ConfigTreeItem(std::string(name), std::string(value), type_str)))
#define fill_config_int(name, value) \
  (_config.addConfigTreeItem(section, Conf::ConfigTreeItem(std::string(name), std::string(value), type_int)))

#define DFT_VOIP_LINK 0

ManagerImpl::ManagerImpl (void)
{
  // Init private variables 
  //_error = new Error();

  _hasZeroconf = false;
#ifdef USE_ZEROCONF
  _hasZeroconf = true;
  _DNSService = new DNSService();
#endif

  // setup
  _path = ""; 
  _exist = 0;
  _setupLoaded = false;
  _gui = NULL;

  _audiodriverPA = NULL;
  _dtmfKey = 0;

  // Initialize after by init() -> initVolume()
  _spkr_volume = 0;
  _mic_volume  = 0; 
  _mic_volume_before_mute = 0;

  // Call
  _currentCallId = 0;
  _nbIncomingWaitingCall=0;
  _registerState = UNREGISTERED;
  _hasTriedToRegister = false;
  // initialize random generator for call id
  srand (time(NULL));
yanmorin's avatar
   
yanmorin committed
91
92
93
94
95
96
97
98
99
100

#ifdef TEST
  testAccountMap();
  loadAccountMap();
  testCallAccountMap();
  unloadAccountMap();
#endif

  // should be call before initConfigFile
  loadAccountMap();
jpbl's avatar
jpbl committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
}

// never call if we use only the singleton...
ManagerImpl::~ManagerImpl (void) 
{
  terminate();

#ifdef USE_ZEROCONF
  delete _DNSService; _DNSService = NULL;
#endif

  _debug("%s stop correctly.\n", PROGNAME);
}

void 
ManagerImpl::init() 
{
  initVolume();

  if (_exist == 0) {
    _debug("Cannot create config file in your home directory\n");
  }

  try {
    initAudioDriver();
    selectAudioDriver();
  }
  catch (const portaudio::PaException &e) {
      getAudioDriver()->setErrorMessage(e.paErrorText());
      _debug("Portaudio exception: %s\n", e.paErrorText());
  }
  catch (const portaudio::PaCppException &e) {
      getAudioDriver()->setErrorMessage(e.what());
      _debug("Portaudio exception: %s\n", e.what());
  }
  catch (const std::runtime_error &e) {
      getAudioDriver()->setErrorMessage(e.what());
      _debug("Portaudio exception: %s\n", e.what());
  }
  catch (...) {
      displayError("An unknown exception occured while selecting audio driver.");
      throw;
  }
  initAudioCodec();

  AudioLayer *audiolayer = getAudioDriver();
  if (audiolayer!=0) {
    unsigned int sampleRate = audiolayer->getSampleRate();
    unsigned int outChannel = audiolayer->getOutChannel();

    _debugInit("Load Telephone Tone");
    std::string country = getConfigString(PREFERENCES, ZONE_TONE);
    _telephoneTone = new TelephoneTone(country, sampleRate, outChannel);

    _debugInit("Loading DTMF key");
    _dtmfKey = new DTMF(sampleRate, outChannel);
  }

  _debugInit("Adding new VoIP Link");

  // initRegisterVoIP was here, but we doing it after the gui loaded... 
  // the stun detection is long, so it's a better idea to do it after getEvents
  initZeroconf();
}

void ManagerImpl::terminate()
{
  saveConfig();

yanmorin's avatar
   
yanmorin committed
170
  unloadAccountMap();
jpbl's avatar
jpbl committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

  _debug("Removing calls\n");
  _mutex.enterMutex();
  for(CallVector::iterator pos = _callVector.begin();
      pos != _callVector.end();
      pos++) {
    delete *pos;   *pos = NULL;
  }
  _callVector.clear();
  _mutex.leaveMutex();

  _debug("Unload DTMF Key\n");
  delete _dtmfKey;

  _debug("Unload Audio Driver\n");
  delete _audiodriverPA; _audiodriverPA = NULL;

  _debug("Unload Telephone Tone\n");
  delete _telephoneTone; _telephoneTone = 0;
}

void
ManagerImpl::setGui(GuiFramework* gui)
{
	_gui = gui;
}

/**
 * Multi Thread with _mutex for callVector
 */
Call *
yanmorin's avatar
   
yanmorin committed
202
ManagerImpl::pushBackNewCall(CALLID id, Call::CallType type)
jpbl's avatar
jpbl committed
203
204
{
  ost::MutexLock m(_mutex);
yanmorin's avatar
   
yanmorin committed
205
206

  Call* call = new Call(id, type, getAccountLink(ACCOUNT_SIP0));
jpbl's avatar
jpbl committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
  // Set the wanted voip-link (first of the list)
  _callVector.push_back(call);
  return call;
}

/**
 * Multi Thread with _mutex for callVector
 */
Call*
ManagerImpl::getCall(CALLID id)
{
  //_debug("%10d: Getting call\n", id);
  Call* call = NULL;
  unsigned int size = _callVector.size();
  for (unsigned int i = 0; i < size; i++) {
    call = _callVector.at(i);
    if (call && call->getId() == id) {
      break;
    } else {
      call = NULL;
    }
  }
  return call;
}

/**
 * Multi Thread with _mutex for callVector
 */
void
ManagerImpl::deleteCall (CALLID id)
{
  //_debug("%10d: Deleting call\n", id);
  CallVector::iterator iter = _callVector.begin();
  while(iter!=_callVector.end()) {
    Call *call = *iter;
    if (call != NULL && call->getId() == id) {
      if (call->getFlagNotAnswered() && call->isIncomingType() && call->getState() != Call::NotExist) {
        decWaitingCall();
      }
      delete (*iter); *iter = NULL; 
      call = NULL;
      _callVector.erase(iter);
      return;
    }
    iter++;
  }
}

void
ManagerImpl::setCurrentCallId(CALLID id)
{
  //_debug("%10d: Setting current callid, old one was: %d\n", id, _currentCallId);
  _currentCallId = id;
}

void
ManagerImpl::removeCallFromCurrent(CALLID id)
{
  if ( _currentCallId == id ) {
    //_debug("%10d: Setting current callid, old one was: %d\n", 0, _currentCallId);
    _currentCallId = 0;
  }
}


///////////////////////////////////////////////////////////////////////////////
// Management of events' IP-phone user
///////////////////////////////////////////////////////////////////////////////
/**
 * Main thread
 */
int 
ManagerImpl::outgoingCall (const std::string& to)
{
  CALLID id = generateNewCallId();
  _debug("%10d: Outgoing Call\n", id);
yanmorin's avatar
   
yanmorin committed
283
  Call *call = pushBackNewCall(id, Call::Outgoing);
jpbl's avatar
jpbl committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
  ost::MutexLock m(_mutex);
  call->setState(Call::Progressing);
  call->setCallerIdNumber(to);
  if (call->outgoingCall(to) == 0) {
    return id;
  } else {
    return 0;
  }
}

/**
 * Main thread
 */
bool 
ManagerImpl::sendTextMessage(const std::string&, const std::string& to, const std::string& message) 
{
yanmorin's avatar
   
yanmorin committed
300
  return getAccountLink(ACCOUNT_SIP0)->sendMessage(to, message);
jpbl's avatar
jpbl committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
}

/**
 * User action (main thread)
 * Every Call
 */
int 
ManagerImpl::hangupCall (CALLID id)
{
  _debug("%10d: Hangup Call\n", id);
  stopTone();
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call == NULL) {
    return -1;
  }
  int result = -1;
  if (call->getState() != Call::Error) { 
    result = call->hangup();
  }
  deleteCall(id);
  // current call id or no line selected
  if (id == _currentCallId || _currentCallId == 0) {
    removeCallFromCurrent(id);
  }
  return result;
}

/**
 * User action (main thread)
 * Every Call
 * -1 : call not found
 *  0 : already in this state...
 */
int
ManagerImpl::cancelCall (CALLID id)
{
  _debug("%10d: Cancel Call\n", id);
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call == NULL) { 
    return -1; 
  }
  int result = call->cancel();
  deleteCall(id);
  stopTone();
  return result;
}

/**
 * User action (main thread)
 * Incoming Call
 */
int 
ManagerImpl::answerCall (CALLID id)
{
  _debug("%10d: Answer Call\n", id);
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call == NULL) {
    return -1;
  }
  if (call->getFlagNotAnswered()) {
    decWaitingCall();
    call->setFlagNotAnswered(false);
  }
  if (call->getState() != Call::OnHold) {
    switchCall(id);
  }
  stopTone(); // before answer, don't stop the audio stream after open it
  return call->answer();
}

/**
 * User action (main thread)
 * Every Call
 * @return 0 if it fails, -1 if not present
 */
int 
ManagerImpl::onHoldCall (CALLID id)
{
  _debug("%10d: On Hold Call\n", id);
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call == NULL) {
    return -1;
  }
  removeCallFromCurrent(id);
  if ( call->getState() == Call::OnHold || call->isNotAnswered()) {
    return 1;
  }
  return call->onHold();
}

/**
 * User action (main thread)
 * Every Call
 */
int 
ManagerImpl::offHoldCall (CALLID id)
{
  _debug("%10d: Off Hold Call\n", id);
  ost::MutexLock m(_mutex);
  stopTone();
  Call* call = getCall(id);
  if (call == 0) {
    return -1;
  }
  if (call->getState() == Call::OffHold) {
    return 1;
  }
  setCurrentCallId(id);
  int returnValue = call->offHold();
  // start audio if it's ok
  if (returnValue != -1) {
    try {
      getAudioDriver()->startStream();
    } catch(...) {
      _debugException("Off hold could not start audio stream");
    }
  }
  return returnValue;
}

/**
 * User action (main thread)
 * Every Call
 */
int 
ManagerImpl::transferCall (CALLID id, const std::string& to)
{
  _debug("%10d: Transfer Call to %s\n", id, to.c_str());
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call == 0) {
    return -1;
  }
  removeCallFromCurrent(id);
  return call->transfer(to);
}

/**
 * User action (main thread)
 * All Call
 */
void
ManagerImpl::mute() {
  _mic_volume_before_mute = _mic_volume;
  setMicVolume(0);
}

/**
 * User action (main thread)
 * All Call
 */
void
ManagerImpl::unmute() {
  if ( _mic_volume == 0 ) {
    setMicVolume(_mic_volume_before_mute);
  }
}

/**
 * User action (main thread)
 * Call Incoming
 */
int 
ManagerImpl::refuseCall (CALLID id)
{
  _debug("%10d: Refuse Call\n", id);
  ost::MutexLock m(_mutex);
  Call *call = getCall(id);
  if (call == NULL) {
    return -1;
  }

  if ( call->getState() != Call::Progressing ) {
    return -1;
  }

  int refuse = call->refuse();
  removeCallFromCurrent(id);
  deleteCall(id);
  stopTone();
  return refuse;
}

/**
 * User action (main thread)
 */
bool
ManagerImpl::saveConfig (void)
{
  _debug("Saving Configuration...\n");
  setConfig(AUDIO, VOLUME_SPKR, getSpkrVolume());
  setConfig(AUDIO, VOLUME_MICRO, getMicVolume());

  _setupLoaded = _config.saveConfigTree(_path.data());
  return _setupLoaded;
}

/**
 * Main Thread
 */
bool
ManagerImpl::initRegisterVoIPLink() 
{
  int returnValue = true;
  _debugInit("Initiate VoIP Link Registration\n");
  if (_hasTriedToRegister == false) {
yanmorin's avatar
   
yanmorin committed
511
    if ( getAccount(ACCOUNT_SIP0)->init() ) { 
jpbl's avatar
jpbl committed
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
      // we call here, because it's long...
      // If network is available and exosip is start..
      if (getConfigInt(SIGNALISATION, AUTO_REGISTER) && _exist == 1) {
        registerVoIPLink();
        _hasTriedToRegister = true;
      }
    } else {
      returnValue = false;
    }
  }
  return returnValue;
}


/**
 * Initialize action (main thread)
 * Note that Registration is only send if STUN is not activated
 * @return true if setRegister is call without failure, else return false
 */
bool
ManagerImpl::registerVoIPLink (void)
{
  _debug("Register VoIP Link\n");
  int returnValue = false;
yanmorin's avatar
   
yanmorin committed
536
537
  returnValue = getAccount(ACCOUNT_SIP0)->registerAccount();
  if (returnValue) {
jpbl's avatar
jpbl committed
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
    _registerState = REGISTERED;
  } else {
    _registerState = FAILED;
  }
  return returnValue;
}

/**
 * Terminate action (main thread)
 * @return true if the unregister method is send correctly
 */
bool 
ManagerImpl::unregisterVoIPLink (void)
{
  _debug("Unregister VoIP Link\n");
yanmorin's avatar
   
yanmorin committed
553
	return getAccount(ACCOUNT_SIP0)->unregisterAccount();
jpbl's avatar
jpbl committed
554
555
556
557
558
559
560
561
562
563
564
565
566
}

/**
 * User action (main thread)
 */
bool 
ManagerImpl::sendDtmf (CALLID id, char code)
{
  int sendType = getConfigInt(SIGNALISATION, SEND_DTMF_AS);
  int returnValue = false;
  switch (sendType) {
  case 0: // SIP INFO
    playDtmf(code);
yanmorin's avatar
   
yanmorin committed
567
    getAccountLink(ACCOUNT_SIP0)->carryingDTMFdigits(id, code);
jpbl's avatar
jpbl committed
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
    returnValue = true;
    break;

  case 1: // Audio way
    break;
  case 2: // rfc 2833
    break;
  default: // unknown - error config?
    break;
  }
  return returnValue;
}

/**
 * User action (main thread)
 * Or sip event (dtmf body submit)
 */
bool
ManagerImpl::playDtmf(char code)
{
  stopTone();
yanmorin's avatar
   
yanmorin committed
589
590
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_DTMF);
  if (!hasToPlayTone) return false;
jpbl's avatar
jpbl committed
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736

  // length in milliseconds
  int pulselen = getConfigInt(SIGNALISATION, PULSE_LENGTH);
  if (!pulselen) { return false; }

  // numbers of int = length in milliseconds / 1000 (number of seconds)
  //                = number of seconds * SAMPLING_RATE by SECONDS

  AudioLayer* audiolayer = getAudioDriver();

  // fast return, no sound, so no dtmf
  if (audiolayer==0 || _dtmfKey == 0) { return false; }
  int outChannel = audiolayer->getOutChannel();
  int size = pulselen * (audiolayer->getSampleRate()/1000);

  // this buffer is for mono
  int16* _buf = new int16[size];
  bool returnValue = false;

  // Handle dtmf
  _dtmfKey->startTone(code);

  // copy the sound...
  if ( _dtmfKey->generateDTMF(_buf, size * outChannel) ) {

    // Put buffer to urgentRingBuffer 
    // put the size in bytes...
    // so size * CHANNELS * 2 (bytes for the int16)
    audiolayer->putUrgent(_buf, size * outChannel * sizeof(int16));

    try {
      // We activate the stream if it's not active yet.
      if (!audiolayer->isStreamActive()) {
        audiolayer->startStream();
      } else {
        audiolayer->sleep(pulselen); // in milliseconds
      }
    } catch(...) {
      _debugException("Portaudio exception when playing a dtmf");
    }
    returnValue = true;
  }
  delete[] _buf; _buf = 0;
  return returnValue;
}

///////////////////////////////////////////////////////////////////////////////
// Management of event peer IP-phone 
////////////////////////////////////////////////////////////////////////////////
/**
 * Multi-thread
 */
bool
ManagerImpl::incomingCallWaiting() {
  ost::MutexLock m(_incomingCallMutex);
  return (_nbIncomingWaitingCall > 0) ? true : false;
}

void
ManagerImpl::incWaitingCall() {
  ost::MutexLock m(_incomingCallMutex);
  _nbIncomingWaitingCall++;
  //_debug("incWaitingCall: %d\n", _nbIncomingWaitingCall);
}

void
ManagerImpl::decWaitingCall() {
  ost::MutexLock m(_incomingCallMutex);
  _nbIncomingWaitingCall--;
  //_debug("decWaitingCall: %d\n", _nbIncomingWaitingCall);
}


/**
 * SipEvent Thread
 * Set the call info for incoming call
 */
void
ManagerImpl::callSetInfo(CALLID id, const std::string& name, const std::string& number)
{
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call != 0) {
    call->setCallerIdName(name);
    call->setCallerIdNumber(number);
  }
}

/**
 * SipEvent Thread
 * ask if it can close the call
 */
bool
ManagerImpl::callCanBeClosed(CALLID id) {
  bool returnValue = false;
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call != NULL && call->getState() != Call::Progressing) {
    returnValue = true;
  }
  return returnValue;
}

/**
 * SipEvent Thread
 * ask if it can answer the call
 */
bool
ManagerImpl::callCanBeAnswered(CALLID id) {
  bool returnValue = false;
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call != NULL && ( call->getFlagNotAnswered() || 
       (call->getState()!=Call::OnHold && call->getState()!=Call::OffHold) )) {
    returnValue = true;
  }
  return returnValue;
}

/**
 * SipEvent Thread
 * ask if it can start the sound thread
 */
bool
ManagerImpl::callIsOnHold(CALLID id) {
  bool returnValue = false;
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call != NULL && (call->getState()==Call::OnHold)) {
    returnValue = true;
  }
  return returnValue;
}

/**
 * SipEvent Thread
 */
int 
ManagerImpl::incomingCall (CALLID id, const std::string& name, const std::string& number)
{
  _debug("%10d: Incoming call\n", id);
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call == NULL) {
    return -1;
  }
yanmorin's avatar
   
yanmorin committed
737
  call->setType(Call::Incoming);
jpbl's avatar
jpbl committed
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
  call->setState(Call::Progressing);

  if ( _currentCallId == 0 ) {
    call->setFlagNotAnswered(false);
    ringtone();
    switchCall(id);
  } else {
    incWaitingCall();
  }

  // TODO: Account not yet implemented
  std::string accountId = "acc1";
  std::string from = name;     call->setCallerIdName(name);
  call->setCallerIdNumber(number);
  if ( !number.empty() ) {
    from.append(" <");
    from.append(number);
    from.append(">");
  }
  return _gui->incomingCall(id, accountId, from);
}

/**
 * SipEvent Thread
 * for outgoing message, send by SipEvent
 */
void 
ManagerImpl::incomingMessage(const std::string& message) {
  if (_gui) {
    _gui->incomingMessage(message);
  }
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
void 
ManagerImpl::peerAnsweredCall (CALLID id)
{
  _debug("%10d: Peer Answered Call\n", id);
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call != 0) {
    call->setFlagNotAnswered(false);
    call->setState(Call::Answered);

    stopTone();
    // switch current call
    switchCall(id);
    if (_gui) _gui->peerAnsweredCall(id);
  }
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
int
ManagerImpl::peerRingingCall (CALLID id)
{
  _debug("%10d: Peer Ringing Call\n", id);
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call != 0) {
    call->setState(Call::Ringing);

    // ring
    ringback();
    if (_gui) _gui->peerRingingCall(id);
  }
  return 1;
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
int 
ManagerImpl::peerHungupCall (CALLID id)
{
  _debug("%10d: Peer Hungup Call\n", id);
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if ( call == NULL ) {
    return -1;
  }
  if ( _currentCallId == id ) {
    stopTone();
  }

  if (_gui) _gui->peerHungupCall(id);
  deleteCall(id);
  call->setState(Call::Hungup);

  removeCallFromCurrent(id);
  return 1;
}

/**
 * Multi Thread
 */
void
ManagerImpl::callBusy(CALLID id) {
  _debug("%10d: Call is busy\n", id);
  playATone(Tone::TONE_BUSY);
  ost::MutexLock m(_mutex);
  Call* call = getCall(id);
  if (call != 0) {
    call->setState(Call::Busy);
  }
  deleteCall(id);
  call->setState(Call::Hungup);

  removeCallFromCurrent(id);
}

/**
 * Multi Thread
 */
void
ManagerImpl::callFailure(CALLID id) {
  _debug("%10d: Call failed\n", id);
  playATone(Tone::TONE_BUSY);
  _mutex.enterMutex();
  Call* call = getCall(id);
  if (call != 0) {
    call->setState(Call::Error);
  }
  _mutex.leaveMutex();
  if (_gui) {
    _gui->callFailure(id);
  }
  deleteCall(id);
  call->setState(Call::Hungup);

  removeCallFromCurrent(id);
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
void 
ManagerImpl::displayTextMessage (CALLID id, const std::string& message)
{
  if(_gui) {
    _gui->displayTextMessage(id, message);
  }
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
void 
ManagerImpl::displayErrorText (CALLID id, const std::string& message)
{
  if(_gui) {
    _gui->displayErrorText(id, message);
  } else {
    std::cerr << message << std::endl;
  }
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
void 
yanmorin's avatar
   
yanmorin committed
908
ManagerImpl::displayError (const std::string& error)
jpbl's avatar
jpbl committed
909
910
{
  if(_gui) {
yanmorin's avatar
   
yanmorin committed
911
    _gui->displayError(error);
jpbl's avatar
jpbl committed
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
  }
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
void 
ManagerImpl::displayStatus (const std::string& status)
{
  if(_gui) {
    _gui->displayStatus(status);
  }
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
void 
ManagerImpl::displayConfigError (const std::string& message)
{
  if(_gui) {
    _gui->displayConfigError(message);
  }
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
void
ManagerImpl::startVoiceMessageNotification (const std::string& nb_msg)
{
  if (_gui) _gui->sendVoiceNbMessage(nb_msg);
}

/**
 * SipEvent Thread
 * for outgoing call, send by SipEvent
 */
void
ManagerImpl::stopVoiceMessageNotification (void)
{
  if (_gui) _gui->sendVoiceNbMessage(std::string("0"));
}

/**
 * SipEvent Thread
 */
void 
ManagerImpl::registrationSucceed()
{
  if (_gui) _gui->sendRegistrationState(true);
}

/**
 * SipEvent Thread
 */
void 
ManagerImpl::registrationFailed()
{
  if (_gui) _gui->sendRegistrationState(false);
}

/**
 * Multi Thread
 */
bool 
ManagerImpl::playATone(Tone::TONEID toneId) {
yanmorin's avatar
   
yanmorin committed
982
983
984
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
  if (!hasToPlayTone) return false;

jpbl's avatar
jpbl committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
  if (_telephoneTone != 0) {
    _toneMutex.enterMutex();
    _telephoneTone->setCurrentTone(toneId);
    _toneMutex.leaveMutex();

    try {
      getAudioDriver()->startStream();
    } catch(...) {
      _debugException("Off hold could not start audio stream");
    }
  }
  return true;
}

/**
 * Multi Thread