managerimpl.cpp 47.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
 *  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"
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
36
#include "sipaccount.h"
jpbl's avatar
jpbl committed
37
38
39
40
#include "audio/audiolayer.h"
#include "audio/audiocodec.h"
#include "audio/tonelist.h"

yanmorin's avatar
   
yanmorin committed
41
#include "accountcreator.h" // create new account
42
#include "voiplink.h"
jpbl's avatar
jpbl committed
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

#include "user_cfg.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 
  _hasZeroconf = false;
#ifdef USE_ZEROCONF
  _hasZeroconf = true;
  _DNSService = new DNSService();
#endif

  // setup
  _path = ""; 
  _exist = 0;
  _setupLoaded = false;
69
  _dbus = NULL;
jpbl's avatar
jpbl committed
70

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

  // Call
  _nbIncomingWaitingCall=0;
  _hasTriedToRegister = false;
yanmorin's avatar
   
yanmorin committed
81

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

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

  // should be call before initConfigFile
  loadAccountMap();
jpbl's avatar
jpbl committed
94
95
96
97
98
99
100
101
}

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

#ifdef USE_ZEROCONF
102
  delete _DNSService; _DNSService = 0;
jpbl's avatar
jpbl committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#endif

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

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

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

117
118
119
  initAudioDriver();
  selectAudioDriver();

jpbl's avatar
jpbl committed
120
121
122
123
124
125
126
127
  initAudioCodec();

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

    _debugInit("Load Telephone Tone");
    std::string country = getConfigString(PREFERENCES, ZONE_TONE);
128
    _telephoneTone = new TelephoneTone(country, sampleRate);
jpbl's avatar
jpbl committed
129
130

    _debugInit("Loading DTMF key");
131
    _dtmfKey = new DTMF(sampleRate);
jpbl's avatar
jpbl committed
132
133
134
135
136
137
138
139
140
141
142
  }

  // 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
143
  unloadAccountMap();
jpbl's avatar
jpbl committed
144
145
146
147
148

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

  _debug("Unload Audio Driver\n");
149
  delete _audiodriver; _audiodriver = 0;
jpbl's avatar
jpbl committed
150
151
152
153
154

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

yanmorin's avatar
   
yanmorin committed
155
156
157
158
bool
ManagerImpl::isCurrentCall(const CallID& callId) {
  ost::MutexLock m(_currentCallMutex);
  return (_currentCallId2 == callId ? true : false);
jpbl's avatar
jpbl committed
159
160
}

yanmorin's avatar
   
yanmorin committed
161
162
163
164
165
bool
ManagerImpl::hasCurrentCall() {
  ost::MutexLock m(_currentCallMutex);
  if ( _currentCallId2 != "") {
    return true;
jpbl's avatar
jpbl committed
166
  }
yanmorin's avatar
   
yanmorin committed
167
  return false;
jpbl's avatar
jpbl committed
168
169
}

yanmorin's avatar
   
yanmorin committed
170
171
172
173
const CallID& 
ManagerImpl::getCurrentCallId() {
  ost::MutexLock m(_currentCallMutex);
  return _currentCallId2;
jpbl's avatar
jpbl committed
174
175
176
}

void
yanmorin's avatar
   
yanmorin committed
177
178
179
ManagerImpl::switchCall(const CallID& id ) {
  ost::MutexLock m(_currentCallMutex);
  _currentCallId2 = id;
jpbl's avatar
jpbl committed
180
181
182
183
184
185
}


///////////////////////////////////////////////////////////////////////////////
// Management of events' IP-phone user
///////////////////////////////////////////////////////////////////////////////
yanmorin's avatar
   
yanmorin committed
186
187
188
189
190
/* Main Thread */ 
bool
ManagerImpl::outgoingCall(const std::string& accountid, const CallID& id, const std::string& to)
{
  if (!accountExists(accountid)) {
191
    _debug("! Manager Error: Outgoing Call: account doesn't exist\n");
yanmorin's avatar
   
yanmorin committed
192
193
194
    return false;
  }
  if (getAccountFromCall(id) != AccountNULL) {
195
    _debug("! Manager Error: Outgoing Call: call id already exists\n");
yanmorin's avatar
   
yanmorin committed
196
197
    return false;
  }
yanmorin's avatar
   
yanmorin committed
198
  if (hasCurrentCall()) {
199
    _debug("* Manager Info: there is currently a call, try to hold it\n");
yanmorin's avatar
   
yanmorin committed
200
201
    onHoldCall(getCurrentCallId());
  }
202
  _debug("- Manager Action: Adding Outgoing Call %s on account %s\n", id.data(), accountid.data());
yanmorin's avatar
   
yanmorin committed
203
204
205
206
  if ( getAccountLink(accountid)->newOutgoingCall(id, to) ) {
    associateCallToAccount( id, accountid );
    switchCall(id);
    return true;
jpbl's avatar
jpbl committed
207
  } else {
208
    _debug("! Manager Error: An error occur, the call was not created\n");
jpbl's avatar
jpbl committed
209
  }
yanmorin's avatar
   
yanmorin committed
210
  return false;
jpbl's avatar
jpbl committed
211
212
}

yanmorin's avatar
   
yanmorin committed
213
214
215
//THREAD=Main : for outgoing Call
bool
ManagerImpl::answerCall(const CallID& id)
jpbl's avatar
jpbl committed
216
{
217
  stopTone(false); 
jpbl's avatar
jpbl committed
218

yanmorin's avatar
   
yanmorin committed
219
220
221
222
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Answering Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
223
  }
yanmorin's avatar
   
yanmorin committed
224
225
226

  if (!getAccountLink(accountid)->answer(id)) {
    // error when receiving...
227
    
yanmorin's avatar
   
yanmorin committed
228
229
    removeCallAccount(id);
    return false;
jpbl's avatar
jpbl committed
230
  }
yanmorin's avatar
   
yanmorin committed
231
232
233
234
235

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

yanmorin's avatar
   
yanmorin committed
238
239
240
//THREAD=Main
bool 
ManagerImpl::sendTextMessage(const AccountID& accountId, const std::string& to, const std::string& message) 
jpbl's avatar
jpbl committed
241
{
yanmorin's avatar
   
yanmorin committed
242
243
  if (accountExists(accountId)) {
    return getAccountLink(accountId)->sendMessage(to, message);
jpbl's avatar
jpbl committed
244
  }
yanmorin's avatar
   
yanmorin committed
245
  return false;
jpbl's avatar
jpbl committed
246
247
}

yanmorin's avatar
   
yanmorin committed
248
249
250
//THREAD=Main
bool
ManagerImpl::hangupCall(const CallID& id)
jpbl's avatar
jpbl committed
251
{
252
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
253
254
255

  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
256
    _debug("! Manager Hangup Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
257
    return false;
jpbl's avatar
jpbl committed
258
  }
yanmorin's avatar
   
yanmorin committed
259
260
261
262
263
264

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

  return returnValue;
jpbl's avatar
jpbl committed
265
266
}

yanmorin's avatar
   
yanmorin committed
267
268
269
//THREAD=Main
bool
ManagerImpl::cancelCall (const CallID& id)
jpbl's avatar
jpbl committed
270
{
271
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
272
273
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
274
    _debug("! Manager Cancel Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
275
    return false;
jpbl's avatar
jpbl committed
276
  }
yanmorin's avatar
   
yanmorin committed
277
278
279
280
281
282
283
284

  bool returnValue = getAccountLink(accountid)->cancel(id);
  // it could be a waiting call?
  removeWaitingCall(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::onHoldCall(const CallID& id)
jpbl's avatar
jpbl committed
290
{
291
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
292
293
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
294
    _debug("5 Manager On Hold Call: Account ID %s or callid %s desn't exists\n", accountid.c_str(), id.c_str());
yanmorin's avatar
   
yanmorin committed
295
    return false;
jpbl's avatar
jpbl committed
296
  }
yanmorin's avatar
   
yanmorin committed
297
298
299
300
301
302
303
304
305
306
307
308

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

//THREAD=Main
bool
ManagerImpl::offHoldCall(const CallID& id)
{
309
  stopTone(false);
yanmorin's avatar
   
yanmorin committed
310
311
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
312
    _debug("5 Manager OffHold Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
313
    return false;
jpbl's avatar
jpbl committed
314
  }
yanmorin's avatar
   
yanmorin committed
315
316
317
318
  bool returnValue = getAccountLink(accountid)->offhold(id);
  switchCall(id);

  if (returnValue) {
jpbl's avatar
jpbl committed
319
320
321
    try {
      getAudioDriver()->startStream();
    } catch(...) {
322
      _debugException("! Manager Off hold could not start audio stream");
jpbl's avatar
jpbl committed
323
324
325
326
327
    }
  }
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
328
329
330
//THREAD=Main
bool
ManagerImpl::transferCall(const CallID& id, const std::string& to)
jpbl's avatar
jpbl committed
331
{
332
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
333
334
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
335
    _debug("! Manager Transfer Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
336
    return false;
jpbl's avatar
jpbl committed
337
  }
yanmorin's avatar
   
yanmorin committed
338
339
340
341
342
343
  bool returnValue = getAccountLink(accountid)->transfer(id, to);
  removeWaitingCall(id);
  removeCallAccount(id);
  switchCall("");

  return returnValue;
jpbl's avatar
jpbl committed
344
345
}

yanmorin's avatar
   
yanmorin committed
346
//THREAD=Main
jpbl's avatar
jpbl committed
347
348
349
350
351
352
void
ManagerImpl::mute() {
  _mic_volume_before_mute = _mic_volume;
  setMicVolume(0);
}

yanmorin's avatar
   
yanmorin committed
353
//THREAD=Main
jpbl's avatar
jpbl committed
354
355
356
357
358
359
360
void
ManagerImpl::unmute() {
  if ( _mic_volume == 0 ) {
    setMicVolume(_mic_volume_before_mute);
  }
}

yanmorin's avatar
   
yanmorin committed
361
362
363
//THREAD=Main : Call:Incoming
bool
ManagerImpl::refuseCall (const CallID& id)
jpbl's avatar
jpbl committed
364
{
365
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
366
367
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
368
    _debug("! Manager OffHold Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
369
370
371
    return false;
  }
  bool returnValue = getAccountLink(accountid)->refuse(id);
yanmorin's avatar
   
yanmorin committed
372
373
374
375
376
377
378
  // 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
379
  return returnValue;
jpbl's avatar
jpbl committed
380
381
}

yanmorin's avatar
   
yanmorin committed
382
//THREAD=Main
jpbl's avatar
jpbl committed
383
384
385
386
387
388
389
390
391
392
393
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
394
//THREAD=Main
jpbl's avatar
jpbl committed
395
396
397
bool
ManagerImpl::initRegisterVoIPLink() 
{
398
  _debugInit("Initiate VoIP Links Registration");
yanmorin's avatar
   
yanmorin committed
399
400
401
402
403
  AccountMap::iterator iter = _accountMap.begin();
  while( iter != _accountMap.end() ) {
    if ( iter->second) {
      iter->second->loadConfig();
      if ( iter->second->shouldInitOnStart() ) {
404
405
        if ( iter->second->init() && iter->second->shouldRegisterOnStart()) {
            iter->second->registerAccount();
yanmorin's avatar
   
yanmorin committed
406
        }
407
408
        // init only the first account
        break;
jpbl's avatar
jpbl committed
409
410
      }
    }
yanmorin's avatar
   
yanmorin committed
411
    iter++;
jpbl's avatar
jpbl committed
412
  }
yanmorin's avatar
   
yanmorin committed
413
  return true;
jpbl's avatar
jpbl committed
414
415
}

yanmorin's avatar
   
yanmorin committed
416
//THREAD=Main
jpbl's avatar
jpbl committed
417
bool
yanmorin's avatar
   
yanmorin committed
418
ManagerImpl::registerVoIPLink(const AccountID& accountId)
jpbl's avatar
jpbl committed
419
420
421
{
  _debug("Register VoIP Link\n");
  int returnValue = false;
422
423
424
425
426
427
428
429
430
431
432
433
434
  // 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
435
436
437
438
  }
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
439
//THREAD=Main
jpbl's avatar
jpbl committed
440
bool 
yanmorin's avatar
   
yanmorin committed
441
ManagerImpl::unregisterVoIPLink(const AccountID& accountId)
jpbl's avatar
jpbl committed
442
443
{
  _debug("Unregister VoIP Link\n");
yanmorin's avatar
   
yanmorin committed
444
445
  int returnValue = false;
  if (accountExists( accountId ) ) {
446
    returnValue = getAccount(accountId)->unregisterAccount();
yanmorin's avatar
   
yanmorin committed
447
448
  }
  return returnValue;
jpbl's avatar
jpbl committed
449
450
}

yanmorin's avatar
   
yanmorin committed
451
//THREAD=Main
jpbl's avatar
jpbl committed
452
bool 
yanmorin's avatar
   
yanmorin committed
453
ManagerImpl::sendDtmf(const CallID& id, char code)
jpbl's avatar
jpbl committed
454
{
yanmorin's avatar
   
yanmorin committed
455
456
457
458
459
460
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Send DTMF: call doesn't exists\n");
    return false;
  }

jpbl's avatar
jpbl committed
461
  int sendType = getConfigInt(SIGNALISATION, SEND_DTMF_AS);
yanmorin's avatar
   
yanmorin committed
462
  bool returnValue = false;
jpbl's avatar
jpbl committed
463
464
465
  switch (sendType) {
  case 0: // SIP INFO
    playDtmf(code);
yanmorin's avatar
   
yanmorin committed
466
    returnValue = getAccountLink(accountid)->carryingDTMFdigits(id, code);
jpbl's avatar
jpbl committed
467
468
469
470
471
472
473
474
475
476
477
478
    break;

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

yanmorin's avatar
   
yanmorin committed
479
//THREAD=Main | VoIPLink
jpbl's avatar
jpbl committed
480
481
482
bool
ManagerImpl::playDtmf(char code)
{
483
484
485
486
  // HERE are the variable:
  // - boolean variable to play or not (config)
  // - length in milliseconds to play
  // - sample of audiolayer
487
  stopTone(false);
yanmorin's avatar
   
yanmorin committed
488
489
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_DTMF);
  if (!hasToPlayTone) return false;
jpbl's avatar
jpbl committed
490
491
492
493
494
495
496
497
498
499
500

  // 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; }
501
502
503
504
  // number of data sampling in one pulselen depends on samplerate
  // size (n sampling) = time_ms * sampling/s 
  //                     ---------------------
  //                            ms/s
505
506
  int size = (int)(pulselen * ((float)audiolayer->getSampleRate()/1000));

507
508
509
  // this buffer is for mono
  // TODO <-- this should be global and hide if same size
  SFLDataFormat* _buf = new SFLDataFormat[size];
jpbl's avatar
jpbl committed
510
511
512
513
514
  bool returnValue = false;

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

515
  // copy the sound
516
  if ( _dtmfKey->generateDTMF(_buf, size) ) {
jpbl's avatar
jpbl committed
517
518
519

    // Put buffer to urgentRingBuffer 
    // put the size in bytes...
520
521
    // so size * 1 channel (mono) * sizeof (bytes for the data)
    audiolayer->putUrgent(_buf, size * sizeof(SFLDataFormat));
jpbl's avatar
jpbl committed
522
523
524
525
526
527
528
529
530
531
532
533
534

    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;
  }
535
536

  // TODO: add caching
jpbl's avatar
jpbl committed
537
538
539
540
  delete[] _buf; _buf = 0;
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
541
542
543


// Multi-thread 
jpbl's avatar
jpbl committed
544
545
bool
ManagerImpl::incomingCallWaiting() {
yanmorin's avatar
   
yanmorin committed
546
  ost::MutexLock m(_waitingCallMutex);
jpbl's avatar
jpbl committed
547
548
549
550
  return (_nbIncomingWaitingCall > 0) ? true : false;
}

void
yanmorin's avatar
   
yanmorin committed
551
552
553
ManagerImpl::addWaitingCall(const CallID& id) {
  ost::MutexLock m(_waitingCallMutex);
  _waitingCall.insert(id);
jpbl's avatar
jpbl committed
554
555
556
557
  _nbIncomingWaitingCall++;
}

void
yanmorin's avatar
   
yanmorin committed
558
559
560
561
562
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
563
564
565
566
  }
}

bool
yanmorin's avatar
   
yanmorin committed
567
568
569
570
571
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
572
  }
yanmorin's avatar
   
yanmorin committed
573
  return true;
jpbl's avatar
jpbl committed
574
575
576
577
}



yanmorin's avatar
   
yanmorin committed
578
579
580
581
582
583
///////////////////////////////////////////////////////////////////////////////
// Management of event peer IP-phone 
////////////////////////////////////////////////////////////////////////////////
// SipEvent Thread 
bool 
ManagerImpl::incomingCall(Call* call, const AccountID& accountId) 
jpbl's avatar
jpbl committed
584
{
yanmorin's avatar
   
yanmorin committed
585
  _debug("Incoming call\n");
586

yanmorin's avatar
   
yanmorin committed
587
  associateCallToAccount(call->getCallId(), accountId);
588

yanmorin's avatar
   
yanmorin committed
589
590
  if ( !hasCurrentCall() ) {
    call->setConnectionState(Call::Ringing);
jpbl's avatar
jpbl committed
591
    ringtone();
yanmorin's avatar
   
yanmorin committed
592
    switchCall(call->getCallId());
jpbl's avatar
jpbl committed
593
  } else {
yanmorin's avatar
   
yanmorin committed
594
     addWaitingCall(call->getCallId());
jpbl's avatar
jpbl committed
595
596
  }

yanmorin's avatar
   
yanmorin committed
597
598
599
  std::string from = call->getPeerName();
  std::string number = call->getPeerNumber();

600
  if (from != "" && number != "") {
jpbl's avatar
jpbl committed
601
602
603
    from.append(" <");
    from.append(number);
    from.append(">");
604
605
606
607
  } else if ( from.empty() ) {
    from.append("<");
    from.append(number);
    from.append(">");
jpbl's avatar
jpbl committed
608
  }
609
  _dbus->getCallManager()->incomingCall(accountId, call->getCallId(), from);
yanmorin's avatar
   
yanmorin committed
610
  return true;
jpbl's avatar
jpbl committed
611
612
}

yanmorin's avatar
   
yanmorin committed
613
614
615
//THREAD=VoIP
void
ManagerImpl::incomingMessage(const AccountID& accountId, const std::string& message) {
616
617
  if (_dbus) {
    _dbus->getCallManager()->incomingMessage(accountId, message);
jpbl's avatar
jpbl committed
618
619
620
  }
}

yanmorin's avatar
   
yanmorin committed
621
622
623
//THREAD=VoIP CALL=Outgoing
void
ManagerImpl::peerAnsweredCall(const CallID& id)
jpbl's avatar
jpbl committed
624
{
yanmorin's avatar
   
yanmorin committed
625
  if (isCurrentCall(id)) {
626
    stopTone(false);
jpbl's avatar
jpbl committed
627
  }
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
628
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT");
jpbl's avatar
jpbl committed
629
630
}

yanmorin's avatar
   
yanmorin committed
631
632
633
//THREAD=VoIP Call=Outgoing
void
ManagerImpl::peerRingingCall(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
    ringback();
  }
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
638
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "RINGING");
jpbl's avatar
jpbl committed
639
640
}

yanmorin's avatar
   
yanmorin committed
641
642
643
//THREAD=VoIP Call=Outgoing/Ingoing
void
ManagerImpl::peerHungupCall(const CallID& id)
jpbl's avatar
jpbl committed
644
{
yanmorin's avatar
   
yanmorin committed
645
646
647
648
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("peerHungupCall: Call doesn't exists\n");
    return;
jpbl's avatar
jpbl committed
649
  }
yanmorin's avatar
   
yanmorin committed
650
  if (isCurrentCall(id)) {
651
    stopTone(true);
yanmorin's avatar
   
yanmorin committed
652
    switchCall("");
jpbl's avatar
jpbl committed
653
  }
yanmorin's avatar
   
yanmorin committed
654
655
  removeWaitingCall(id);
  removeCallAccount(id);
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
656
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
jpbl's avatar
jpbl committed
657
658
}

yanmorin's avatar
   
yanmorin committed
659
//THREAD=VoIP
jpbl's avatar
jpbl committed
660
void
yanmorin's avatar
   
yanmorin committed
661
662
663
664
665
ManagerImpl::callBusy(const CallID& id) {
  _debug("Call busy\n");
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
jpbl's avatar
jpbl committed
666
  }
yanmorin's avatar
   
yanmorin committed
667
668
  removeCallAccount(id);
  removeWaitingCall(id);
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
669
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "BUSY");
jpbl's avatar
jpbl committed
670
671
}

yanmorin's avatar
   
yanmorin committed
672
//THREAD=VoIP
jpbl's avatar
jpbl committed
673
void
yanmorin's avatar
   
yanmorin committed
674
675
676
677
678
679
680
681
682
ManagerImpl::callFailure(const CallID& id) 
{
  _debug("Call failed\n");
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
  }
  removeCallAccount(id);
  removeWaitingCall(id);
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
683
684
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "FAILURE");
  
jpbl's avatar
jpbl committed
685
686
}

yanmorin's avatar
   
yanmorin committed
687
//THREAD=VoIP
jpbl's avatar
jpbl committed
688
void 
yanmorin's avatar
   
yanmorin committed
689
ManagerImpl::displayTextMessage(const CallID& id, const std::string& message)
jpbl's avatar
jpbl committed
690
{
691
  /*if(_gui) {
yanmorin's avatar
   
yanmorin committed
692
   _gui->displayTextMessage(id, message);
693
  }*/
jpbl's avatar
jpbl committed
694
695
}

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

yanmorin's avatar
   
yanmorin committed
707
//THREAD=VoIP
jpbl's avatar
jpbl committed
708
void 
yanmorin's avatar
   
yanmorin committed
709
ManagerImpl::displayError (const std::string& error)
jpbl's avatar
jpbl committed
710
{
711
  /*if(_gui) {
yanmorin's avatar
   
yanmorin committed
712
    _gui->displayError(error);
713
  }*/
jpbl's avatar
jpbl committed
714
715
}

yanmorin's avatar
   
yanmorin committed
716
//THREAD=VoIP
jpbl's avatar
jpbl committed
717
void 
yanmorin's avatar
   
yanmorin committed
718
ManagerImpl::displayStatus(const std::string& status)
jpbl's avatar
jpbl committed
719
{
720
  /*if(_gui) {
jpbl's avatar
jpbl committed
721
    _gui->displayStatus(status);
722
  }*/
jpbl's avatar
jpbl committed
723
724
}

yanmorin's avatar
   
yanmorin committed
725
//THREAD=VoIP
jpbl's avatar
jpbl committed
726
727
728
void 
ManagerImpl::displayConfigError (const std::string& message)
{
729
  /*if(_gui) {
jpbl's avatar
jpbl committed
730
    _gui->displayConfigError(message);
731
  }*/
jpbl's avatar
jpbl committed
732
733
}

yanmorin's avatar
   
yanmorin committed
734
//THREAD=VoIP
jpbl's avatar
jpbl committed
735
void
yanmorin's avatar
   
yanmorin committed
736
ManagerImpl::startVoiceMessageNotification(const AccountID& accountId, const std::string& nb_msg)
jpbl's avatar
jpbl committed
737
{
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
738
  if (_dbus) _dbus->getCallManager()->voiceMailNotify(accountId, atoi(nb_msg.c_str()) );
jpbl's avatar
jpbl committed
739
740
}

yanmorin's avatar
   
yanmorin committed
741
//THREAD=VoIP
jpbl's avatar
jpbl committed
742
void
yanmorin's avatar
   
yanmorin committed
743
ManagerImpl::stopVoiceMessageNotification(const AccountID& accountId)
jpbl's avatar
jpbl committed
744
{
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
745
  if (_dbus) _dbus->getCallManager()->voiceMailNotify(accountId, 0 );
746
} 
jpbl's avatar
jpbl committed
747

yanmorin's avatar
   
yanmorin committed
748
//THREAD=VoIP
jpbl's avatar
jpbl committed
749
void 
yanmorin's avatar
   
yanmorin committed
750
ManagerImpl::registrationSucceed(const AccountID& accountid)
jpbl's avatar
jpbl committed
751
{
752
  Account* acc = getAccount(accountid);
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
753
 if ( acc ) { 
754
    acc->setState(true); 
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
755
    if (_dbus) _dbus->getConfigurationManager()->accountsChanged();
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
756
  }
jpbl's avatar
jpbl committed
757
758
}

yanmorin's avatar
   
yanmorin committed
759
//THREAD=VoIP
jpbl's avatar
jpbl committed
760
void 
yanmorin's avatar
   
yanmorin committed
761
ManagerImpl::registrationFailed(const AccountID& accountid)
jpbl's avatar
jpbl committed
762
{
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
763
  Account* acc = getAccount(accountid);
764
765
  if ( acc ) { 
    acc->setState(false);
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
766
    if (_dbus) _dbus->getConfigurationManager()->accountsChanged();
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
767
  }
jpbl's avatar
jpbl committed
768
769
770
771
772
773
774
}

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

jpbl's avatar
jpbl committed
778
779
780
781
782
783
  if (_telephoneTone != 0) {
    _toneMutex.enterMutex();
    _telephoneTone->setCurrentTone(toneId);
    _toneMutex.leaveMutex();

    try {
784
785
      AudioLayer* audiolayer = getAudioDriver();
      if (audiolayer) { audiolayer->startStream(); }
jpbl's avatar
jpbl committed
786
787
    } catch(...) {
      _debugException("Off hold could not start audio stream");
788
      return false;
jpbl's avatar
jpbl committed
789
790
791
792
793
794
795
796
797
    }
  }
  return true;
}

/**
 * Multi Thread
 */
void 
798
ManagerImpl::stopTone(bool stopAudio=true) {
yanmorin's avatar
   
yanmorin committed
799
800
801
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
  if (!hasToPlayTone) return;

802
803
804
805
806
807
808
  if (stopAudio) {
    try {
      AudioLayer* audiolayer = getAudioDriver();
      if (audiolayer) { audiolayer->stopStream(); }
    } catch(...) {
      _debugException("Stop tone and stop stream");
    }
jpbl's avatar
jpbl committed
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
  }

  _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()
{
829
830
  //return playATone(Tone::TONE_DIALTONE);
  playATone(Tone::TONE_DIALTONE);
jpbl's avatar
jpbl committed
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
}

/**
 * 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
855
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
856
  if (!hasToPlayTone) { return; }
yanmorin's avatar
   
yanmorin committed
857

jpbl's avatar
jpbl committed
858
859
860
861
862
863
  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; 
  }
864
865
866
867
868

  AudioLayer* audiolayer = getAudioDriver();
  if (audiolayer==0) { return; }
  int sampleRate  = audiolayer->getSampleRate();

jpbl's avatar
jpbl committed
869
  _toneMutex.enterMutex(); 
870
  bool loadFile = _audiofile.loadFile(ringchoice, sampleRate);
jpbl's avatar
jpbl committed
871
872
873
874
875
876
  _toneMutex.leaveMutex(); 
  if (loadFile) {
    _toneMutex.enterMutex(); 
    _audiofile.start();
    _toneMutex.leaveMutex(); 
    try {
877
      audiolayer->startStream();
jpbl's avatar
jpbl committed
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
    } 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
915
ManagerImpl::notificationIncomingCall(void) {
jpbl's avatar
jpbl committed
916
917
918

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

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

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

  //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
945
  if (ok) {
yanmorin's avatar
   
yanmorin committed
946
947
948
    closesocket(fd1);
    //closesocket(fd3);
    //closesocket(fd4);
jpbl's avatar
jpbl committed
949
950
951
952
953
954
    _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
955
    return true;
jpbl's avatar
jpbl committed
956
957
958
  } else {
    _debug("Opening a stun socket pair failed\n");
  }
yanmorin's avatar
   
yanmorin committed
959
  return false;
jpbl's avatar
jpbl committed
960
961
962
}

bool
yanmorin's avatar
   
yanmorin committed
963
ManagerImpl::behindNat(const std::string& svr, int port)
yanmorin's avatar
   
yanmorin committed
964
965
966
967
968
969
970
971
972
{
  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
973
  }
yanmorin's avatar
   
yanmorin committed
974
975
976
977
  
  // Firewall address
  //_debug("STUN server: %s\n", svr.data());
  return getStunInfo(stunSvrAddr, port);
jpbl's avatar
jpbl committed
978
979
}

yanmorin's avatar
   
yanmorin committed
980

jpbl's avatar
jpbl committed
981
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;
    }