managerimpl.cpp 45.2 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
#include "voIPLink.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)))

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;

yanmorin's avatar
   
yanmorin committed
73
  // sound
jpbl's avatar
jpbl committed
74
75
  _audiodriverPA = NULL;
  _dtmfKey = 0;
yanmorin's avatar
   
yanmorin committed
76
77
78
  _spkr_volume = 0; // Initialize after by init() -> initVolume()
  _mic_volume  = 0;  // Initialize after by init() -> initVolume()
  _mic_volume_before_mute = 0; 
jpbl's avatar
jpbl committed
79
80
81
82
83

  // Call
  _nbIncomingWaitingCall=0;
  _registerState = UNREGISTERED;
  _hasTriedToRegister = false;
yanmorin's avatar
   
yanmorin committed
84

jpbl's avatar
jpbl committed
85
86
  // initialize random generator for call id
  srand (time(NULL));
yanmorin's avatar
   
yanmorin committed
87
88
89
90
91
92
93
94
95
96

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

  // should be call before initConfigFile
  loadAccountMap();
jpbl's avatar
jpbl committed
97
98
99
100
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
}

// 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);
  }

  // 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
164
  unloadAccountMap();
jpbl's avatar
jpbl committed
165
166
167
168
169
170
171
172
173
174
175

  _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;
}

yanmorin's avatar
   
yanmorin committed
176
177
178
179
bool
ManagerImpl::isCurrentCall(const CallID& callId) {
  ost::MutexLock m(_currentCallMutex);
  return (_currentCallId2 == callId ? true : false);
jpbl's avatar
jpbl committed
180
181
}

yanmorin's avatar
   
yanmorin committed
182
183
184
185
186
bool
ManagerImpl::hasCurrentCall() {
  ost::MutexLock m(_currentCallMutex);
  if ( _currentCallId2 != "") {
    return true;
jpbl's avatar
jpbl committed
187
  }
yanmorin's avatar
   
yanmorin committed
188
  return false;
jpbl's avatar
jpbl committed
189
190
}

yanmorin's avatar
   
yanmorin committed
191
192
193
194
const CallID& 
ManagerImpl::getCurrentCallId() {
  ost::MutexLock m(_currentCallMutex);
  return _currentCallId2;
jpbl's avatar
jpbl committed
195
196
197
}

void
yanmorin's avatar
   
yanmorin committed
198
199
200
ManagerImpl::switchCall(const CallID& id ) {
  ost::MutexLock m(_currentCallMutex);
  _currentCallId2 = id;
jpbl's avatar
jpbl committed
201
202
203
204
205
206
}


///////////////////////////////////////////////////////////////////////////////
// Management of events' IP-phone user
///////////////////////////////////////////////////////////////////////////////
yanmorin's avatar
   
yanmorin committed
207
208
209
210
211
212
213
214
215
216
217
218
/* Main Thread */ 
bool
ManagerImpl::outgoingCall(const std::string& accountid, const CallID& id, const std::string& to)
{
  if (!accountExists(accountid)) {
    _debug("Outgoing Call: account doesn't exist\n");
    return false;
  }
  if (getAccountFromCall(id) != AccountNULL) {
    _debug("Outgoing Call: call id already exists\n");
    return false;
  }
yanmorin's avatar
   
yanmorin committed
219
220
221
222
  if (hasCurrentCall()) {
    _debug("There is currently a call, try to hold it\n");
    onHoldCall(getCurrentCallId());
  }
yanmorin's avatar
   
yanmorin committed
223
224
225
226
227
  _debug("Adding Outgoing Call %s on account %s\n", id.data(), accountid.data());
  if ( getAccountLink(accountid)->newOutgoingCall(id, to) ) {
    associateCallToAccount( id, accountid );
    switchCall(id);
    return true;
jpbl's avatar
jpbl committed
228
  } else {
yanmorin's avatar
   
yanmorin committed
229
    _debug("An error occur, the call was not created\n");
jpbl's avatar
jpbl committed
230
  }
yanmorin's avatar
   
yanmorin committed
231
  return false;
jpbl's avatar
jpbl committed
232
233
}

yanmorin's avatar
   
yanmorin committed
234
235
236
//THREAD=Main : for outgoing Call
bool
ManagerImpl::answerCall(const CallID& id)
jpbl's avatar
jpbl committed
237
{
yanmorin's avatar
   
yanmorin committed
238
  stopTone(); 
jpbl's avatar
jpbl committed
239

yanmorin's avatar
   
yanmorin committed
240
241
242
243
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Answering Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
244
  }
yanmorin's avatar
   
yanmorin committed
245
246
247
248
249

  if (!getAccountLink(accountid)->answer(id)) {
    // error when receiving...
    removeCallAccount(id);
    return false;
jpbl's avatar
jpbl committed
250
  }
yanmorin's avatar
   
yanmorin committed
251
252
253
254
255

  // if it was waiting, it's waiting no more
  removeWaitingCall(id);
  switchCall(id);
  return true;
jpbl's avatar
jpbl committed
256
257
}

yanmorin's avatar
   
yanmorin committed
258
259
260
//THREAD=Main
bool 
ManagerImpl::sendTextMessage(const AccountID& accountId, const std::string& to, const std::string& message) 
jpbl's avatar
jpbl committed
261
{
yanmorin's avatar
   
yanmorin committed
262
263
  if (accountExists(accountId)) {
    return getAccountLink(accountId)->sendMessage(to, message);
jpbl's avatar
jpbl committed
264
  }
yanmorin's avatar
   
yanmorin committed
265
  return false;
jpbl's avatar
jpbl committed
266
267
}

yanmorin's avatar
   
yanmorin committed
268
269
270
//THREAD=Main
bool
ManagerImpl::hangupCall(const CallID& id)
jpbl's avatar
jpbl committed
271
{
yanmorin's avatar
   
yanmorin committed
272
273
274
275
276
277
  stopTone();

  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Hangup Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
278
  }
yanmorin's avatar
   
yanmorin committed
279
280
281
282
283
284

  bool returnValue = getAccountLink(accountid)->hangup(id);
  removeCallAccount(id);
  switchCall("");

  return returnValue;
jpbl's avatar
jpbl committed
285
286
}

yanmorin's avatar
   
yanmorin committed
287
288
289
//THREAD=Main
bool
ManagerImpl::cancelCall (const CallID& id)
jpbl's avatar
jpbl committed
290
{
yanmorin's avatar
   
yanmorin committed
291
292
293
294
295
  stopTone();
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Cancel Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
296
  }
yanmorin's avatar
   
yanmorin committed
297
298
299
300
301
302
303
304

  bool returnValue = getAccountLink(accountid)->cancel(id);
  // it could be a waiting call?
  removeWaitingCall(id);
  removeCallAccount(id);
  switchCall("");
  
  return returnValue;
jpbl's avatar
jpbl committed
305
306
}

yanmorin's avatar
   
yanmorin committed
307
308
309
//THREAD=Main
bool
ManagerImpl::onHoldCall(const CallID& id)
jpbl's avatar
jpbl committed
310
311
{
  stopTone();
yanmorin's avatar
   
yanmorin committed
312
313
314
315
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("On Hold Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
316
  }
yanmorin's avatar
   
yanmorin committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333

  bool returnValue = getAccountLink(accountid)->onhold(id);
  removeWaitingCall(id);
  switchCall("");
  
  return returnValue;
}

//THREAD=Main
bool
ManagerImpl::offHoldCall(const CallID& id)
{
  stopTone();
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("OffHold Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
334
  }
yanmorin's avatar
   
yanmorin committed
335
336
337
338
  bool returnValue = getAccountLink(accountid)->offhold(id);
  switchCall(id);

  if (returnValue) {
jpbl's avatar
jpbl committed
339
340
341
342
343
344
345
346
347
    try {
      getAudioDriver()->startStream();
    } catch(...) {
      _debugException("Off hold could not start audio stream");
    }
  }
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
348
349
350
//THREAD=Main
bool
ManagerImpl::transferCall(const CallID& id, const std::string& to)
jpbl's avatar
jpbl committed
351
{
yanmorin's avatar
   
yanmorin committed
352
353
354
355
356
  stopTone();
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Transfer Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
357
  }
yanmorin's avatar
   
yanmorin committed
358
359
360
361
362
363
  bool returnValue = getAccountLink(accountid)->transfer(id, to);
  removeWaitingCall(id);
  removeCallAccount(id);
  switchCall("");

  return returnValue;
jpbl's avatar
jpbl committed
364
365
}

yanmorin's avatar
   
yanmorin committed
366
//THREAD=Main
jpbl's avatar
jpbl committed
367
368
369
370
371
372
void
ManagerImpl::mute() {
  _mic_volume_before_mute = _mic_volume;
  setMicVolume(0);
}

yanmorin's avatar
   
yanmorin committed
373
//THREAD=Main
jpbl's avatar
jpbl committed
374
375
376
377
378
379
380
void
ManagerImpl::unmute() {
  if ( _mic_volume == 0 ) {
    setMicVolume(_mic_volume_before_mute);
  }
}

yanmorin's avatar
   
yanmorin committed
381
382
383
//THREAD=Main : Call:Incoming
bool
ManagerImpl::refuseCall (const CallID& id)
jpbl's avatar
jpbl committed
384
385
{
  stopTone();
yanmorin's avatar
   
yanmorin committed
386
387
388
389
390
391
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("OffHold Call: Call doesn't exists\n");
    return false;
  }
  bool returnValue = getAccountLink(accountid)->refuse(id);
yanmorin's avatar
   
yanmorin committed
392
393
394
395
396
397
398
  // if the call was outgoing or established, we didn't refuse it
  // so the method did nothing
  if (returnValue) {
    removeWaitingCall(id);
    removeCallAccount(id);
    switchCall("");
  }
yanmorin's avatar
   
yanmorin committed
399
  return returnValue;
jpbl's avatar
jpbl committed
400
401
}

yanmorin's avatar
   
yanmorin committed
402
//THREAD=Main
jpbl's avatar
jpbl committed
403
404
405
406
407
408
409
410
411
412
413
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;
}

yanmorin's avatar
   
yanmorin committed
414
//THREAD=Main
jpbl's avatar
jpbl committed
415
416
417
bool
ManagerImpl::initRegisterVoIPLink() 
{
yanmorin's avatar
   
yanmorin committed
418
419
420
421
422
423
  _debugInit("Initiate VoIP Links Registration\n");
  AccountMap::iterator iter = _accountMap.begin();
  while( iter != _accountMap.end() ) {
    if ( iter->second) {
      iter->second->loadConfig();
      if ( iter->second->shouldInitOnStart() ) {
424
425
        if ( iter->second->init() && iter->second->shouldRegisterOnStart()) {
            iter->second->registerAccount();
yanmorin's avatar
   
yanmorin committed
426
        }
427
428
        // init only the first account
        break;
jpbl's avatar
jpbl committed
429
430
      }
    }
yanmorin's avatar
   
yanmorin committed
431
    iter++;
jpbl's avatar
jpbl committed
432
  }
yanmorin's avatar
   
yanmorin committed
433
  return true;
jpbl's avatar
jpbl committed
434
435
}

yanmorin's avatar
   
yanmorin committed
436
//THREAD=Main
jpbl's avatar
jpbl committed
437
bool
yanmorin's avatar
   
yanmorin committed
438
ManagerImpl::registerVoIPLink(const AccountID& accountId)
jpbl's avatar
jpbl committed
439
440
441
{
  _debug("Register VoIP Link\n");
  int returnValue = false;
442
443
444
445
446
447
448
449
450
451
452
453
454
  // right now, we don't support two SIP account
  // so we close everything before registring a new account
  Account* account = getAccount(accountId);
  if (account != 0) {
    AccountMap::iterator iter = _accountMap.begin();
    while ( iter != _accountMap.end() ) {
      if ( iter->second ) {
        iter->second->unregisterAccount();
        iter->second->terminate();
      }
      iter++;
    }
    returnValue = account->registerAccount();
jpbl's avatar
jpbl committed
455
456
457
458
  }
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
459
//THREAD=Main
jpbl's avatar
jpbl committed
460
bool 
yanmorin's avatar
   
yanmorin committed
461
ManagerImpl::unregisterVoIPLink(const AccountID& accountId)
jpbl's avatar
jpbl committed
462
463
{
  _debug("Unregister VoIP Link\n");
yanmorin's avatar
   
yanmorin committed
464
465
  int returnValue = false;
  if (accountExists( accountId ) ) {
466
    returnValue = getAccount(accountId)->unregisterAccount();
yanmorin's avatar
   
yanmorin committed
467
468
  }
  return returnValue;
jpbl's avatar
jpbl committed
469
470
}

yanmorin's avatar
   
yanmorin committed
471
//THREAD=Main
jpbl's avatar
jpbl committed
472
bool 
yanmorin's avatar
   
yanmorin committed
473
ManagerImpl::sendDtmf(const CallID& id, char code)
jpbl's avatar
jpbl committed
474
{
yanmorin's avatar
   
yanmorin committed
475
476
477
478
479
480
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Send DTMF: call doesn't exists\n");
    return false;
  }

jpbl's avatar
jpbl committed
481
  int sendType = getConfigInt(SIGNALISATION, SEND_DTMF_AS);
yanmorin's avatar
   
yanmorin committed
482
  bool returnValue = false;
jpbl's avatar
jpbl committed
483
484
485
  switch (sendType) {
  case 0: // SIP INFO
    playDtmf(code);
yanmorin's avatar
   
yanmorin committed
486
    returnValue = getAccountLink(accountid)->carryingDTMFdigits(id, code);
jpbl's avatar
jpbl committed
487
488
489
490
491
492
493
494
495
496
497
498
    break;

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

yanmorin's avatar
   
yanmorin committed
499
//THREAD=Main | VoIPLink
jpbl's avatar
jpbl committed
500
501
502
503
bool
ManagerImpl::playDtmf(char code)
{
  stopTone();
yanmorin's avatar
   
yanmorin committed
504
505
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_DTMF);
  if (!hasToPlayTone) return false;
jpbl's avatar
jpbl committed
506
507
508
509
510
511
512
513
514
515
516
517

  // 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();
518
519
520
521
522
523
524
525
526
  // number of int16 sampling in one pulselen depends on samplerate
  /** size (n sampling) = time_ms * sampling/s 
                          ---------------------
			         ms/s
   */
  int size = (int)(pulselen * ((float)audiolayer->getSampleRate()/1000));

  // this buffer is for mono or stereo
  int16* _buf = new int16[size*outChannel];
jpbl's avatar
jpbl committed
527
528
529
530
531
  bool returnValue = false;

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

532
  // copy the sound
jpbl's avatar
jpbl committed
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
  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;
}

yanmorin's avatar
   
yanmorin committed
556
557
558


// Multi-thread 
jpbl's avatar
jpbl committed
559
560
bool
ManagerImpl::incomingCallWaiting() {
yanmorin's avatar
   
yanmorin committed
561
  ost::MutexLock m(_waitingCallMutex);
jpbl's avatar
jpbl committed
562
563
564
565
  return (_nbIncomingWaitingCall > 0) ? true : false;
}

void
yanmorin's avatar
   
yanmorin committed
566
567
568
ManagerImpl::addWaitingCall(const CallID& id) {
  ost::MutexLock m(_waitingCallMutex);
  _waitingCall.insert(id);
jpbl's avatar
jpbl committed
569
570
571
572
  _nbIncomingWaitingCall++;
}

void
yanmorin's avatar
   
yanmorin committed
573
574
575
576
577
ManagerImpl::removeWaitingCall(const CallID& id) {
  ost::MutexLock m(_waitingCallMutex);
  // should return more than 1 if it erase a call
  if (_waitingCall.erase(id)) {
    _nbIncomingWaitingCall--;
jpbl's avatar
jpbl committed
578
579
580
581
  }
}

bool
yanmorin's avatar
   
yanmorin committed
582
583
584
585
586
ManagerImpl::isWaitingCall(const CallID& id) {
  ost::MutexLock m(_waitingCallMutex);
  CallIDSet::iterator iter = _waitingCall.find(id);
  if (iter != _waitingCall.end()) {
    return false;
jpbl's avatar
jpbl committed
587
  }
yanmorin's avatar
   
yanmorin committed
588
  return true;
jpbl's avatar
jpbl committed
589
590
591
592
}



yanmorin's avatar
   
yanmorin committed
593
594
595
596
597
598
///////////////////////////////////////////////////////////////////////////////
// Management of event peer IP-phone 
////////////////////////////////////////////////////////////////////////////////
// SipEvent Thread 
bool 
ManagerImpl::incomingCall(Call* call, const AccountID& accountId) 
jpbl's avatar
jpbl committed
599
{
yanmorin's avatar
   
yanmorin committed
600
601
602
603
  _debug("Incoming call\n");
  associateCallToAccount(call->getCallId(), accountId);
  if ( !hasCurrentCall() ) {
    call->setConnectionState(Call::Ringing);
jpbl's avatar
jpbl committed
604
    ringtone();
yanmorin's avatar
   
yanmorin committed
605
    switchCall(call->getCallId());
jpbl's avatar
jpbl committed
606
  } else {
yanmorin's avatar
   
yanmorin committed
607
     addWaitingCall(call->getCallId());
jpbl's avatar
jpbl committed
608
609
  }

yanmorin's avatar
   
yanmorin committed
610
611
612
  std::string from = call->getPeerName();
  std::string number = call->getPeerNumber();

jpbl's avatar
jpbl committed
613
614
615
616
617
  if ( !number.empty() ) {
    from.append(" <");
    from.append(number);
    from.append(">");
  }
yanmorin's avatar
   
yanmorin committed
618
619
620
  _gui->incomingCall(accountId, call->getCallId(), from);

  return true;
jpbl's avatar
jpbl committed
621
622
}

yanmorin's avatar
   
yanmorin committed
623
624
625
//THREAD=VoIP
void
ManagerImpl::incomingMessage(const AccountID& accountId, const std::string& message) {
jpbl's avatar
jpbl committed
626
  if (_gui) {
yanmorin's avatar
   
yanmorin committed
627
    _gui->incomingMessage(accountId, message);
jpbl's avatar
jpbl committed
628
629
630
  }
}

yanmorin's avatar
   
yanmorin committed
631
632
633
//THREAD=VoIP CALL=Outgoing
void
ManagerImpl::peerAnsweredCall(const CallID& id)
jpbl's avatar
jpbl committed
634
{
yanmorin's avatar
   
yanmorin committed
635
  if (isCurrentCall(id)) {
jpbl's avatar
jpbl committed
636
637
    stopTone();
  }
yanmorin's avatar
   
yanmorin committed
638
  if (_gui) _gui->peerAnsweredCall(id);
jpbl's avatar
jpbl committed
639
640
}

yanmorin's avatar
   
yanmorin committed
641
642
643
//THREAD=VoIP Call=Outgoing
void
ManagerImpl::peerRingingCall(const CallID& id)
jpbl's avatar
jpbl committed
644
{
yanmorin's avatar
   
yanmorin committed
645
  if (isCurrentCall(id)) {
jpbl's avatar
jpbl committed
646
647
    ringback();
  }
yanmorin's avatar
   
yanmorin committed
648
  if (_gui) _gui->peerRingingCall(id);
jpbl's avatar
jpbl committed
649
650
}

yanmorin's avatar
   
yanmorin committed
651
652
653
//THREAD=VoIP Call=Outgoing/Ingoing
void
ManagerImpl::peerHungupCall(const CallID& id)
jpbl's avatar
jpbl committed
654
{
yanmorin's avatar
   
yanmorin committed
655
656
657
658
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("peerHungupCall: Call doesn't exists\n");
    return;
jpbl's avatar
jpbl committed
659
  }
yanmorin's avatar
   
yanmorin committed
660
  if (isCurrentCall(id)) {
jpbl's avatar
jpbl committed
661
    stopTone();
yanmorin's avatar
   
yanmorin committed
662
    switchCall("");
jpbl's avatar
jpbl committed
663
  }
yanmorin's avatar
   
yanmorin committed
664
665
  removeWaitingCall(id);
  removeCallAccount(id);
yanmorin's avatar
   
yanmorin committed
666
  if (_gui) _gui->peerHungupCall(id);
jpbl's avatar
jpbl committed
667
668
}

yanmorin's avatar
   
yanmorin committed
669
//THREAD=VoIP
jpbl's avatar
jpbl committed
670
void
yanmorin's avatar
   
yanmorin committed
671
672
673
674
675
ManagerImpl::callBusy(const CallID& id) {
  _debug("Call busy\n");
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
jpbl's avatar
jpbl committed
676
  }
yanmorin's avatar
   
yanmorin committed
677
678
  removeCallAccount(id);
  removeWaitingCall(id);
yanmorin's avatar
   
yanmorin committed
679
  if(_gui) _gui->displayErrorText( id, "Call is busy");
jpbl's avatar
jpbl committed
680
681
}

yanmorin's avatar
   
yanmorin committed
682
//THREAD=VoIP
jpbl's avatar
jpbl committed
683
void
yanmorin's avatar
   
yanmorin committed
684
685
686
687
688
689
690
ManagerImpl::callFailure(const CallID& id) 
{
  _debug("Call failed\n");
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
  }
jpbl's avatar
jpbl committed
691
692
693
  if (_gui) {
    _gui->callFailure(id);
  }
yanmorin's avatar
   
yanmorin committed
694
695
  removeCallAccount(id);
  removeWaitingCall(id);
jpbl's avatar
jpbl committed
696
697
}

yanmorin's avatar
   
yanmorin committed
698
//THREAD=VoIP
jpbl's avatar
jpbl committed
699
void 
yanmorin's avatar
   
yanmorin committed
700
ManagerImpl::displayTextMessage(const CallID& id, const std::string& message)
jpbl's avatar
jpbl committed
701
702
{
  if(_gui) {
yanmorin's avatar
   
yanmorin committed
703
   _gui->displayTextMessage(id, message);
jpbl's avatar
jpbl committed
704
705
706
  }
}

yanmorin's avatar
   
yanmorin committed
707
//THREAD=VoIP
jpbl's avatar
jpbl committed
708
void 
yanmorin's avatar
   
yanmorin committed
709
ManagerImpl::displayErrorText(const CallID& id, const std::string& message)
jpbl's avatar
jpbl committed
710
711
712
713
714
715
716
717
{
  if(_gui) {
    _gui->displayErrorText(id, message);
  } else {
    std::cerr << message << std::endl;
  }
}

yanmorin's avatar
   
yanmorin committed
718
//THREAD=VoIP
jpbl's avatar
jpbl committed
719
void 
yanmorin's avatar
   
yanmorin committed
720
ManagerImpl::displayError (const std::string& error)
jpbl's avatar
jpbl committed
721
722
{
  if(_gui) {
yanmorin's avatar
   
yanmorin committed
723
    _gui->displayError(error);
jpbl's avatar
jpbl committed
724
725
726
  }
}

yanmorin's avatar
   
yanmorin committed
727
//THREAD=VoIP
jpbl's avatar
jpbl committed
728
void 
yanmorin's avatar
   
yanmorin committed
729
ManagerImpl::displayStatus(const std::string& status)
jpbl's avatar
jpbl committed
730
731
732
733
734
735
{
  if(_gui) {
    _gui->displayStatus(status);
  }
}

yanmorin's avatar
   
yanmorin committed
736
//THREAD=VoIP
jpbl's avatar
jpbl committed
737
738
739
740
741
742
743
744
void 
ManagerImpl::displayConfigError (const std::string& message)
{
  if(_gui) {
    _gui->displayConfigError(message);
  }
}

yanmorin's avatar
   
yanmorin committed
745
//THREAD=VoIP
jpbl's avatar
jpbl committed
746
void
yanmorin's avatar
   
yanmorin committed
747
ManagerImpl::startVoiceMessageNotification(const AccountID& accountId, const std::string& nb_msg)
jpbl's avatar
jpbl committed
748
{
yanmorin's avatar
   
yanmorin committed
749
  if (_gui) _gui->sendVoiceNbMessage(accountId, nb_msg);
jpbl's avatar
jpbl committed
750
751
}

yanmorin's avatar
   
yanmorin committed
752
//THREAD=VoIP
jpbl's avatar
jpbl committed
753
void
yanmorin's avatar
   
yanmorin committed
754
ManagerImpl::stopVoiceMessageNotification(const AccountID& accountId)
jpbl's avatar
jpbl committed
755
{
yanmorin's avatar
   
yanmorin committed
756
  if (_gui) _gui->sendVoiceNbMessage(accountId, std::string("0"));
757
} 
jpbl's avatar
jpbl committed
758

yanmorin's avatar
   
yanmorin committed
759
//THREAD=VoIP
jpbl's avatar
jpbl committed
760
void 
yanmorin's avatar
   
yanmorin committed
761
ManagerImpl::registrationSucceed(const AccountID& accountid)
jpbl's avatar
jpbl committed
762
{
763
764
765
766
767
  Account* acc = getAccount(accountid);
  if ( acc ) { 
    acc->setState(true); 
    if (_gui) _gui->sendRegistrationState(accountid, true);
  }
jpbl's avatar
jpbl committed
768
769
}

yanmorin's avatar
   
yanmorin committed
770
//THREAD=VoIP
jpbl's avatar
jpbl committed
771
void 
yanmorin's avatar
   
yanmorin committed
772
ManagerImpl::registrationFailed(const AccountID& accountid)
jpbl's avatar
jpbl committed
773
{
774
775
776
777
778
  Account* acc = getAccount(accountid);
  if ( acc ) { 
    acc->setState(false);
    if (_gui) _gui->sendRegistrationState(accountid, false);
  }
jpbl's avatar
jpbl committed
779
780
781
782
783
784
785
}

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

jpbl's avatar
jpbl committed
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
  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
 */
void 
ManagerImpl::stopTone() {
yanmorin's avatar
   
yanmorin committed
808
809
810
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
  if (!hasToPlayTone) return;

jpbl's avatar
jpbl committed
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
  try {
    getAudioDriver()->stopStream();
  } catch(...) {
    _debugException("Stop tone and stop stream");
  }

  _toneMutex.enterMutex();
  if (_telephoneTone != 0) {
    _telephoneTone->setCurrentTone(Tone::TONE_NULL);
  }
  _toneMutex.leaveMutex();

  // for ringing tone..
  _toneMutex.enterMutex();
  _audiofile.stop();
  _toneMutex.leaveMutex();
}

/**
 * Multi Thread
 */
bool
ManagerImpl::playTone()
{
  return playATone(Tone::TONE_DIALTONE);
}

/**
 * Multi Thread
 */
void
ManagerImpl::congestion () {
  playATone(Tone::TONE_CONGESTION);
}

/**
 * Multi Thread
 */
void
ManagerImpl::ringback () {
  playATone(Tone::TONE_RINGTONE);
}

/**
 * Multi Thread
 */
void
ManagerImpl::ringtone() 
{
yanmorin's avatar
   
yanmorin committed
860
861
862
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
  if (!hasToPlayTone) return;

jpbl's avatar
jpbl committed
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
908
909
910
911
912
913
914
915
  std::string ringchoice = getConfigString(AUDIO, RING_CHOICE);
  //if there is no / inside the path
  if ( ringchoice.find(DIR_SEPARATOR_CH) == std::string::npos ) {
    // check inside global share directory
    ringchoice = std::string(PROGSHAREDIR) + DIR_SEPARATOR_STR + RINGDIR + DIR_SEPARATOR_STR + ringchoice; 
  }
  unsigned int outChannel = getAudioDriver()->getOutChannel();
  _toneMutex.enterMutex(); 
  bool loadFile = _audiofile.loadFile(ringchoice, outChannel);
  _toneMutex.leaveMutex(); 
  if (loadFile) {
    _toneMutex.enterMutex(); 
    _audiofile.start();
    _toneMutex.leaveMutex(); 
    try {
      getAudioDriver()->startStream();
    } catch(...) {
      _debugException("Audio file couldn't start audio stream");
    }
  } else {
    ringback();
  }
}

AudioLoop*
ManagerImpl::getTelephoneTone()
{
  if(_telephoneTone != 0) {
    ost::MutexLock m(_toneMutex);
    return _telephoneTone->getCurrentTone();
  }
  else {
    return 0;
  }
}

AudioLoop*
ManagerImpl::getTelephoneFile()
{
  ost::MutexLock m(_toneMutex);
  if(_audiofile.isStarted()) {
    return &_audiofile;
  } else {
    return 0;
  }
}


/**
 * Use Urgent Buffer
 * By AudioRTP thread
 */
void
yanmorin's avatar
   
yanmorin committed
916
ManagerImpl::notificationIncomingCall(void) {
jpbl's avatar
jpbl committed
917
918
919

  AudioLayer* audiolayer = getAudioDriver();
  if (audiolayer != 0) {
yanmorin's avatar
   
yanmorin committed
920
    unsigned int samplerate = audiolayer->getSampleRate();
jpbl's avatar
jpbl committed
921
922
923
    std::ostringstream frequency;
    frequency << "440/" << FRAME_PER_BUFFER;

yanmorin's avatar
   
yanmorin committed
924
925
926
    Tone tone(frequency.str(), samplerate, audiolayer->getOutChannel());
    unsigned int nbint16 = tone.getSize();
    int16 buf[nbint16];
jpbl's avatar
jpbl committed
927
    tone.getNext(buf, tone.getSize());
yanmorin's avatar
   
yanmorin committed
928
    audiolayer->putUrgent(buf, sizeof(int16)*nbint16);
jpbl's avatar
jpbl committed
929
930
931
932
933
934
  }
}

/**
 * Multi Thread
 */
yanmorin's avatar
   
yanmorin committed
935
936
bool
ManagerImpl::getStunInfo (StunAddress4& stunSvrAddr, int port) 
jpbl's avatar
jpbl committed
937
938
939
940
{
  StunAddress4 mappedAddr;
  struct in_addr in;
  char* addr;
yanmorin's avatar
   
yanmorin committed
941
942
943
944
945

  //int fd3, fd4;
  // bool ok = stunOpenSocketPair(stunSvrAddr, &mappedAddr, &fd3, &fd4, port);
  int fd1 = stunOpenSocket(stunSvrAddr, &mappedAddr, port);
  bool ok = (fd1 == -1 || fd1 == INVALID_SOCKET) ? false : true;
jpbl's avatar
jpbl committed
946
  if (ok) {
yanmorin's avatar
   
yanmorin committed
947
948
949
    closesocket(fd1);
    //closesocket(fd3);
    //closesocket(fd4);
jpbl's avatar
jpbl committed
950
951
952
953
954
955
    _firewallPort = mappedAddr.port;
    // Convert ipv4 address to host byte ordering
    in.s_addr = ntohl (mappedAddr.addr);
    addr = inet_ntoa(in);
    _firewallAddr = std::string(addr);
    _debug("STUN Firewall: [%s:%d]\n", _firewallAddr.data(), _firewallPort);
yanmorin's avatar
   
yanmorin committed
956
    return true;
jpbl's avatar
jpbl committed
957
958
959
  } else {
    _debug("Opening a stun socket pair failed\n");
  }
yanmorin's avatar
   
yanmorin committed
960
  return false;
jpbl's avatar
jpbl committed
961
962
963
}

bool
yanmorin's avatar
   
yanmorin committed
964
ManagerImpl::behindNat(const std::string& svr, int port)
yanmorin's avatar
   
yanmorin committed
965
966
967
968
969
970
971
972
973
{
  StunAddress4 stunSvrAddr;
  stunSvrAddr.addr = 0;
  
  // Convert char* to StunAddress4 structure
  bool ret = stunParseServerName ((char*)svr.data(), stunSvrAddr);
  if (!ret) {
    _debug("SIP: Stun server address (%s) is not valid\n", svr.data());
    return 0;
jpbl's avatar
jpbl committed
974
  }
yanmorin's avatar
   
yanmorin committed
975
976
977
978
  
  // Firewall address
  //_debug("STUN server: %s\n", svr.data());
  return getStunInfo(stunSvrAddr, port);
jpbl's avatar
jpbl committed
979
980
}

yanmorin's avatar
   
yanmorin committed
981

jpbl's avatar
jpbl committed
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///////////////////////////////////////////////////////////////////////////////
// Private functions
///////////////////////////////////////////////////////////////////////////////
/**
 * Initialization: Main Thread
 * @return 1: ok
          -1: error directory
           0: unable to load the setting
           2: file doesn't exist yet
 */
int
ManagerImpl::createSettingsPath (void) {
  _path = std::string(HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR;

  if (mkdir (_path.data(), 0755) != 0) {
    // If directory	creation failed
    if (errno != EEXIST) {
      _debug("Cannot create directory: %s\n", strerror(errno));
      return -1;