managerimpl.cpp 58.3 KB
Newer Older
jpbl's avatar
jpbl committed
1
/*
2
3
 *  Copyright (C) 2004-2007 Savoir-Faire Linux inc.
 *  Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com>
jpbl's avatar
jpbl committed
4
 *  Author: Yan Morin <yan.morin@savoirfairelinux.com>
5
 *  Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com>
6
 *  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
7
 *  Author: Guillaume Carmel-Archambault <guillaume.carmel-archambault@savoirfairelinux.com>
8
 *
jpbl's avatar
jpbl committed
9
10
 *  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
11
 *  the Free Software Foundation; either version 3 of the License, or
jpbl's avatar
jpbl committed
12
 *  (at your option) any later version.
13
 *
jpbl's avatar
jpbl committed
14
15
16
17
 *  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.
18
 *
jpbl's avatar
jpbl committed
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 *  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>

38
39
#include <boost/tokenizer.hpp>

jpbl's avatar
jpbl committed
40
#include "manager.h"
41
#include "account.h"
jpbl's avatar
jpbl committed
42
43
44
#include "audio/audiolayer.h"
#include "audio/tonelist.h"

yanmorin's avatar
   
yanmorin committed
45
#include "accountcreator.h" // create new account
46
#include "voiplink.h"
jpbl's avatar
jpbl committed
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 "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;
73
  _dbus = NULL;
jpbl's avatar
jpbl committed
74

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

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

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

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

  // should be call before initConfigFile
97
  // loadAccountMap();, called in init() now.
jpbl's avatar
jpbl committed
98
99
100
101
102
103
104
105
}

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

#ifdef USE_ZEROCONF
106
  delete _DNSService; _DNSService = 0;
jpbl's avatar
jpbl committed
107
108
109
110
111
112
113
114
#endif

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

void 
ManagerImpl::init() 
{
115
116
117
  // Load accounts, init map
  loadAccountMap();

jpbl's avatar
jpbl committed
118
119
120
121
122
123
  initVolume();

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

124
125
126
  initAudioDriver();
  selectAudioDriver();

127
  // Initialize the list of supported audio codecs
jpbl's avatar
jpbl committed
128
129
130
131
132
133
134
135
  initAudioCodec();

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

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

    _debugInit("Loading DTMF key");
139
    _dtmfKey = new DTMF(sampleRate);
jpbl's avatar
jpbl committed
140
141
  }

142
  // initRegisterAccounts was here, but we doing it after the gui loaded... 
jpbl's avatar
jpbl committed
143
144
145
146
147
148
149
150
  // 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
151
  unloadAccountMap();
jpbl's avatar
jpbl committed
152
153
154
155
156

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

  _debug("Unload Audio Driver\n");
157
  delete _audiodriver; _audiodriver = NULL;
jpbl's avatar
jpbl committed
158
159

  _debug("Unload Telephone Tone\n");
160
  delete _telephoneTone; _telephoneTone = NULL;
jpbl's avatar
jpbl committed
161
162
}

yanmorin's avatar
   
yanmorin committed
163
164
165
166
bool
ManagerImpl::isCurrentCall(const CallID& callId) {
  ost::MutexLock m(_currentCallMutex);
  return (_currentCallId2 == callId ? true : false);
jpbl's avatar
jpbl committed
167
168
}

yanmorin's avatar
   
yanmorin committed
169
170
171
bool
ManagerImpl::hasCurrentCall() {
  ost::MutexLock m(_currentCallMutex);
Emmanuel Milou's avatar
Bug fix    
Emmanuel Milou committed
172
  _debug("Current call ID = %s\n", _currentCallId2.c_str());
yanmorin's avatar
   
yanmorin committed
173
174
  if ( _currentCallId2 != "") {
    return true;
jpbl's avatar
jpbl committed
175
  }
yanmorin's avatar
   
yanmorin committed
176
  return false;
jpbl's avatar
jpbl committed
177
178
}

yanmorin's avatar
   
yanmorin committed
179
180
181
182
const CallID& 
ManagerImpl::getCurrentCallId() {
  ost::MutexLock m(_currentCallMutex);
  return _currentCallId2;
jpbl's avatar
jpbl committed
183
184
185
}

void
yanmorin's avatar
   
yanmorin committed
186
187
188
ManagerImpl::switchCall(const CallID& id ) {
  ost::MutexLock m(_currentCallMutex);
  _currentCallId2 = id;
jpbl's avatar
jpbl committed
189
190
191
192
193
194
}


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

yanmorin's avatar
   
yanmorin committed
222
223
224
//THREAD=Main : for outgoing Call
bool
ManagerImpl::answerCall(const CallID& id)
jpbl's avatar
jpbl committed
225
{
226
  stopTone(false); 
Emmanuel Milou's avatar
Bug fix    
Emmanuel Milou committed
227
  /*if (hasCurrentCall()) 
228
229
  { 
    onHoldCall(getCurrentCallId());
Emmanuel Milou's avatar
Bug fix    
Emmanuel Milou committed
230
  }*/
yanmorin's avatar
   
yanmorin committed
231
232
233
234
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Answering Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
235
  }
yanmorin's avatar
   
yanmorin committed
236
237
238
239
240

  if (!getAccountLink(accountid)->answer(id)) {
    // error when receiving...
    removeCallAccount(id);
    return false;
jpbl's avatar
jpbl committed
241
  }
yanmorin's avatar
   
yanmorin committed
242

243
244
245
  //Place current call on hold if it isn't
  
  
yanmorin's avatar
   
yanmorin committed
246
  // if it was waiting, it's waiting no more
247
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT");
yanmorin's avatar
   
yanmorin committed
248
249
250
  removeWaitingCall(id);
  switchCall(id);
  return true;
jpbl's avatar
jpbl committed
251
252
}

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

yanmorin's avatar
   
yanmorin committed
263
264
265
//THREAD=Main
bool
ManagerImpl::hangupCall(const CallID& id)
jpbl's avatar
jpbl committed
266
{
267
  stopTone(true);
268
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
yanmorin's avatar
   
yanmorin committed
269
270
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
271
272
    /** @todo We should tell the GUI that the call doesn't exist, so
     * it clears up. This can happen. */
273
    _debug("! Manager Hangup Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
274
    return false;
jpbl's avatar
jpbl committed
275
  }
yanmorin's avatar
   
yanmorin committed
276
277
278
279

  bool returnValue = getAccountLink(accountid)->hangup(id);
  removeCallAccount(id);
  switchCall("");
280
281
  
  
yanmorin's avatar
   
yanmorin committed
282
  return returnValue;
jpbl's avatar
jpbl committed
283
284
}

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

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

yanmorin's avatar
   
yanmorin committed
305
306
307
//THREAD=Main
bool
ManagerImpl::onHoldCall(const CallID& id)
jpbl's avatar
jpbl committed
308
{
309
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
310
311
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
312
    _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
313
    return false;
jpbl's avatar
jpbl committed
314
  }
yanmorin's avatar
   
yanmorin committed
315

316
317
  _debug("Setting ONHOLD, Account %s, callid %s\n", accountid.c_str(), id.c_str());

yanmorin's avatar
   
yanmorin committed
318
  bool returnValue = getAccountLink(accountid)->onhold(id);
319
  
yanmorin's avatar
   
yanmorin committed
320
  removeWaitingCall(id);
321
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HOLD");
yanmorin's avatar
   
yanmorin committed
322
323
324
325
326
327
328
329
330
  switchCall("");
  
  return returnValue;
}

//THREAD=Main
bool
ManagerImpl::offHoldCall(const CallID& id)
{
331
  stopTone(false);
yanmorin's avatar
   
yanmorin committed
332
333
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
334
    _debug("5 Manager OffHold Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
335
    return false;
jpbl's avatar
jpbl committed
336
  }
337
338
339
340
341
342
343
  
  //Place current call on hold if it isn't
  if (hasCurrentCall()) 
  { 
    onHoldCall(getCurrentCallId());
  }
  
344
345
  _debug("Setting OFFHOLD, Account %s, callid %s\n", accountid.c_str(), id.c_str());

yanmorin's avatar
   
yanmorin committed
346
  bool returnValue = getAccountLink(accountid)->offhold(id);
347
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "UNHOLD");
yanmorin's avatar
   
yanmorin committed
348
349
  switchCall(id);
  if (returnValue) {
jpbl's avatar
jpbl committed
350
351
352
    try {
      getAudioDriver()->startStream();
    } catch(...) {
353
      _debugException("! Manager Off hold could not start audio stream");
jpbl's avatar
jpbl committed
354
355
356
357
358
    }
  }
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
359
360
361
//THREAD=Main
bool
ManagerImpl::transferCall(const CallID& id, const std::string& to)
jpbl's avatar
jpbl committed
362
{
363
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
364
365
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
366
    _debug("! Manager Transfer Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
367
    return false;
jpbl's avatar
jpbl committed
368
  }
yanmorin's avatar
   
yanmorin committed
369
370
371
  bool returnValue = getAccountLink(accountid)->transfer(id, to);
  removeWaitingCall(id);
  removeCallAccount(id);
372
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
yanmorin's avatar
   
yanmorin committed
373
374
375
  switchCall("");

  return returnValue;
jpbl's avatar
jpbl committed
376
377
}

yanmorin's avatar
   
yanmorin committed
378
//THREAD=Main
jpbl's avatar
jpbl committed
379
380
381
382
383
384
void
ManagerImpl::mute() {
  _mic_volume_before_mute = _mic_volume;
  setMicVolume(0);
}

yanmorin's avatar
   
yanmorin committed
385
//THREAD=Main
jpbl's avatar
jpbl committed
386
387
388
389
390
391
392
void
ManagerImpl::unmute() {
  if ( _mic_volume == 0 ) {
    setMicVolume(_mic_volume_before_mute);
  }
}

yanmorin's avatar
   
yanmorin committed
393
394
395
//THREAD=Main : Call:Incoming
bool
ManagerImpl::refuseCall (const CallID& id)
jpbl's avatar
jpbl committed
396
{
397
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
398
399
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
400
    _debug("! Manager OffHold Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
401
402
403
    return false;
  }
  bool returnValue = getAccountLink(accountid)->refuse(id);
yanmorin's avatar
   
yanmorin committed
404
405
406
407
408
  // if the call was outgoing or established, we didn't refuse it
  // so the method did nothing
  if (returnValue) {
    removeWaitingCall(id);
    removeCallAccount(id);
409
    if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
yanmorin's avatar
   
yanmorin committed
410
411
    switchCall("");
  }
yanmorin's avatar
   
yanmorin committed
412
  return returnValue;
jpbl's avatar
jpbl committed
413
414
}

yanmorin's avatar
   
yanmorin committed
415
//THREAD=Main
jpbl's avatar
jpbl committed
416
417
418
419
420
421
422
423
424
425
426
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
427
//THREAD=Main
jpbl's avatar
jpbl committed
428
bool
429
ManagerImpl::initRegisterAccounts() 
jpbl's avatar
jpbl committed
430
{
431
  _debugInit("Initiate VoIP Links Registration");
yanmorin's avatar
   
yanmorin committed
432
433
434
435
  AccountMap::iterator iter = _accountMap.begin();
  while( iter != _accountMap.end() ) {
    if ( iter->second) {
      iter->second->loadConfig();
436
      if ( iter->second->isEnabled() ) {
437
	iter->second->registerVoIPLink();
jpbl's avatar
jpbl committed
438
439
      }
    }
yanmorin's avatar
   
yanmorin committed
440
    iter++;
jpbl's avatar
jpbl committed
441
  }
yanmorin's avatar
   
yanmorin committed
442
  return true;
jpbl's avatar
jpbl committed
443
444
}

yanmorin's avatar
   
yanmorin committed
445
//THREAD=Main
446
// Currently unused
jpbl's avatar
jpbl committed
447
bool
448
ManagerImpl::registerAccount(const AccountID& accountId)
jpbl's avatar
jpbl committed
449
{
450
451
  _debug("Register one VoIP Link\n");

452
453
454
455
456
457
458
  // 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 ) {
459
        iter->second->unregisterVoIPLink();
460
461
462
      }
      iter++;
    }
463
    account->registerVoIPLink();
jpbl's avatar
jpbl committed
464
  }
465
  return true;
jpbl's avatar
jpbl committed
466
467
}

yanmorin's avatar
   
yanmorin committed
468
//THREAD=Main
469
// Currently unused
jpbl's avatar
jpbl committed
470
bool 
471
ManagerImpl::unregisterAccount(const AccountID& accountId)
jpbl's avatar
jpbl committed
472
{
473
474
  _debug("Unregister one VoIP Link\n");

yanmorin's avatar
   
yanmorin committed
475
  if (accountExists( accountId ) ) {
476
    getAccount(accountId)->unregisterVoIPLink();
yanmorin's avatar
   
yanmorin committed
477
  }
478
  return true;
jpbl's avatar
jpbl committed
479
480
}

yanmorin's avatar
   
yanmorin committed
481
//THREAD=Main
jpbl's avatar
jpbl committed
482
bool 
yanmorin's avatar
   
yanmorin committed
483
ManagerImpl::sendDtmf(const CallID& id, char code)
jpbl's avatar
jpbl committed
484
{
yanmorin's avatar
   
yanmorin committed
485
486
487
488
489
490
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Send DTMF: call doesn't exists\n");
    return false;
  }

jpbl's avatar
jpbl committed
491
  int sendType = getConfigInt(SIGNALISATION, SEND_DTMF_AS);
yanmorin's avatar
   
yanmorin committed
492
  bool returnValue = false;
jpbl's avatar
jpbl committed
493
494
495
  switch (sendType) {
  case 0: // SIP INFO
    playDtmf(code);
yanmorin's avatar
   
yanmorin committed
496
    returnValue = getAccountLink(accountid)->carryingDTMFdigits(id, code);
jpbl's avatar
jpbl committed
497
498
499
500
501
502
503
504
505
506
507
508
    break;

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

yanmorin's avatar
   
yanmorin committed
509
//THREAD=Main | VoIPLink
jpbl's avatar
jpbl committed
510
511
512
bool
ManagerImpl::playDtmf(char code)
{
513
514
515
516
  // HERE are the variable:
  // - boolean variable to play or not (config)
  // - length in milliseconds to play
  // - sample of audiolayer
517
  stopTone(false);
yanmorin's avatar
   
yanmorin committed
518
519
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_DTMF);
  if (!hasToPlayTone) return false;
jpbl's avatar
jpbl committed
520
521
522
523
524
525
526
527
528
529
530

  // 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; }
531
532
533
534
  // number of data sampling in one pulselen depends on samplerate
  // size (n sampling) = time_ms * sampling/s 
  //                     ---------------------
  //                            ms/s
535
536
  int size = (int)(pulselen * ((float)audiolayer->getSampleRate()/1000));

537
538
539
  // 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
540
541
542
543
544
  bool returnValue = false;

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

545
  // copy the sound
546
  if ( _dtmfKey->generateDTMF(_buf, size) ) {
jpbl's avatar
jpbl committed
547
548
549

    // Put buffer to urgentRingBuffer 
    // put the size in bytes...
550
551
    // so size * 1 channel (mono) * sizeof (bytes for the data)
    audiolayer->putUrgent(_buf, size * sizeof(SFLDataFormat));
jpbl's avatar
jpbl committed
552
553
554
555
556
557
558
559
560
561
562
563
564

    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;
  }
565
566

  // TODO: add caching
jpbl's avatar
jpbl committed
567
568
569
570
  delete[] _buf; _buf = 0;
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
571
// Multi-thread 
jpbl's avatar
jpbl committed
572
573
bool
ManagerImpl::incomingCallWaiting() {
yanmorin's avatar
   
yanmorin committed
574
  ost::MutexLock m(_waitingCallMutex);
jpbl's avatar
jpbl committed
575
576
577
578
  return (_nbIncomingWaitingCall > 0) ? true : false;
}

void
yanmorin's avatar
   
yanmorin committed
579
580
581
ManagerImpl::addWaitingCall(const CallID& id) {
  ost::MutexLock m(_waitingCallMutex);
  _waitingCall.insert(id);
jpbl's avatar
jpbl committed
582
583
584
585
  _nbIncomingWaitingCall++;
}

void
yanmorin's avatar
   
yanmorin committed
586
587
588
589
590
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
591
592
593
594
  }
}

bool
yanmorin's avatar
   
yanmorin committed
595
596
597
598
599
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
600
  }
yanmorin's avatar
   
yanmorin committed
601
  return true;
jpbl's avatar
jpbl committed
602
603
604
605
}



yanmorin's avatar
   
yanmorin committed
606
607
608
609
610
611
///////////////////////////////////////////////////////////////////////////////
// Management of event peer IP-phone 
////////////////////////////////////////////////////////////////////////////////
// SipEvent Thread 
bool 
ManagerImpl::incomingCall(Call* call, const AccountID& accountId) 
jpbl's avatar
jpbl committed
612
{
yanmorin's avatar
   
yanmorin committed
613
  _debug("Incoming call\n");
614

yanmorin's avatar
   
yanmorin committed
615
  associateCallToAccount(call->getCallId(), accountId);
616

yanmorin's avatar
   
yanmorin committed
617
  if ( !hasCurrentCall() ) {
Emmanuel Milou's avatar
Bug fix    
Emmanuel Milou committed
618
    _debug("INCOMING CALL!!!!!!\n");
yanmorin's avatar
   
yanmorin committed
619
    call->setConnectionState(Call::Ringing);
jpbl's avatar
jpbl committed
620
    ringtone();
yanmorin's avatar
   
yanmorin committed
621
    switchCall(call->getCallId());
jpbl's avatar
jpbl committed
622
  } else {
yanmorin's avatar
   
yanmorin committed
623
     addWaitingCall(call->getCallId());
jpbl's avatar
jpbl committed
624
625
  }

yanmorin's avatar
   
yanmorin committed
626
627
628
  std::string from = call->getPeerName();
  std::string number = call->getPeerNumber();

629
  if (from != "" && number != "") {
jpbl's avatar
jpbl committed
630
631
632
    from.append(" <");
    from.append(number);
    from.append(">");
633
634
635
636
  } else if ( from.empty() ) {
    from.append("<");
    from.append(number);
    from.append(">");
jpbl's avatar
jpbl committed
637
  }
638
  _dbus->getCallManager()->incomingCall(accountId, call->getCallId(), from);
yanmorin's avatar
   
yanmorin committed
639
  return true;
jpbl's avatar
jpbl committed
640
641
}

yanmorin's avatar
   
yanmorin committed
642
643
644
//THREAD=VoIP
void
ManagerImpl::incomingMessage(const AccountID& accountId, const std::string& message) {
645
646
  if (_dbus) {
    _dbus->getCallManager()->incomingMessage(accountId, message);
jpbl's avatar
jpbl committed
647
648
649
  }
}

yanmorin's avatar
   
yanmorin committed
650
651
652
//THREAD=VoIP CALL=Outgoing
void
ManagerImpl::peerAnsweredCall(const CallID& id)
jpbl's avatar
jpbl committed
653
{
yanmorin's avatar
   
yanmorin committed
654
  if (isCurrentCall(id)) {
655
    stopTone(false);
jpbl's avatar
jpbl committed
656
  }
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
657
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT");
jpbl's avatar
jpbl committed
658
659
}

yanmorin's avatar
   
yanmorin committed
660
661
662
//THREAD=VoIP Call=Outgoing
void
ManagerImpl::peerRingingCall(const CallID& id)
jpbl's avatar
jpbl committed
663
{
yanmorin's avatar
   
yanmorin committed
664
  if (isCurrentCall(id)) {
jpbl's avatar
jpbl committed
665
666
    ringback();
  }
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
667
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "RINGING");
jpbl's avatar
jpbl committed
668
669
}

yanmorin's avatar
   
yanmorin committed
670
671
672
//THREAD=VoIP Call=Outgoing/Ingoing
void
ManagerImpl::peerHungupCall(const CallID& id)
jpbl's avatar
jpbl committed
673
{
yanmorin's avatar
   
yanmorin committed
674
675
676
677
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("peerHungupCall: Call doesn't exists\n");
    return;
jpbl's avatar
jpbl committed
678
  }
679
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
yanmorin's avatar
   
yanmorin committed
680
  if (isCurrentCall(id)) {
681
    stopTone(true);
yanmorin's avatar
   
yanmorin committed
682
    switchCall("");
jpbl's avatar
jpbl committed
683
  }
yanmorin's avatar
   
yanmorin committed
684
685
  removeWaitingCall(id);
  removeCallAccount(id);
686
  
jpbl's avatar
jpbl committed
687
688
}

yanmorin's avatar
   
yanmorin committed
689
//THREAD=VoIP
jpbl's avatar
jpbl committed
690
void
yanmorin's avatar
   
yanmorin committed
691
692
ManagerImpl::callBusy(const CallID& id) {
  _debug("Call busy\n");
693
694
  
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "BUSY");
yanmorin's avatar
   
yanmorin committed
695
696
697
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
jpbl's avatar
jpbl committed
698
  }
yanmorin's avatar
   
yanmorin committed
699
700
  removeCallAccount(id);
  removeWaitingCall(id);
jpbl's avatar
jpbl committed
701
702
}

yanmorin's avatar
   
yanmorin committed
703
//THREAD=VoIP
jpbl's avatar
jpbl committed
704
void
yanmorin's avatar
   
yanmorin committed
705
706
707
ManagerImpl::callFailure(const CallID& id) 
{
  _debug("Call failed\n");
708
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "FAILURE");
yanmorin's avatar
   
yanmorin committed
709
710
711
712
713
714
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
  }
  removeCallAccount(id);
  removeWaitingCall(id);
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
715
  
jpbl's avatar
jpbl committed
716
717
}

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

yanmorin's avatar
   
yanmorin committed
727
//THREAD=VoIP
jpbl's avatar
jpbl committed
728
void 
yanmorin's avatar
   
yanmorin committed
729
ManagerImpl::displayErrorText(const CallID& id, const std::string& message)
jpbl's avatar
jpbl committed
730
{
731
  /*if(_gui) {
jpbl's avatar
jpbl committed
732
733
734
    _gui->displayErrorText(id, message);
  } else {
    std::cerr << message << std::endl;
735
  }*/
jpbl's avatar
jpbl committed
736
737
}

yanmorin's avatar
   
yanmorin committed
738
//THREAD=VoIP
jpbl's avatar
jpbl committed
739
void 
yanmorin's avatar
   
yanmorin committed
740
ManagerImpl::displayError (const std::string& error)
jpbl's avatar
jpbl committed
741
{
742
  /*if(_gui) {
yanmorin's avatar
   
yanmorin committed
743
    _gui->displayError(error);
744
  }*/
jpbl's avatar
jpbl committed
745
746
}

yanmorin's avatar
   
yanmorin committed
747
//THREAD=VoIP
jpbl's avatar
jpbl committed
748
void 
yanmorin's avatar
   
yanmorin committed
749
ManagerImpl::displayStatus(const std::string& status)
jpbl's avatar
jpbl committed
750
{
751
  /*if(_gui) {
jpbl's avatar
jpbl committed
752
    _gui->displayStatus(status);
753
  }*/
jpbl's avatar
jpbl committed
754
755
}

yanmorin's avatar
   
yanmorin committed
756
//THREAD=VoIP
jpbl's avatar
jpbl committed
757
758
759
void 
ManagerImpl::displayConfigError (const std::string& message)
{
760
  /*if(_gui) {
jpbl's avatar
jpbl committed
761
    _gui->displayConfigError(message);
762
  }*/
jpbl's avatar
jpbl committed
763
764
}

yanmorin's avatar
   
yanmorin committed
765
//THREAD=VoIP
jpbl's avatar
jpbl committed
766
void
yanmorin's avatar
   
yanmorin committed
767
ManagerImpl::startVoiceMessageNotification(const AccountID& accountId, const std::string& nb_msg)
jpbl's avatar
jpbl committed
768
{
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
769
  if (_dbus) _dbus->getCallManager()->voiceMailNotify(accountId, atoi(nb_msg.c_str()) );
jpbl's avatar
jpbl committed
770
771
}

yanmorin's avatar
   
yanmorin committed
772
//THREAD=VoIP
jpbl's avatar
jpbl committed
773
void
yanmorin's avatar
   
yanmorin committed
774
ManagerImpl::stopVoiceMessageNotification(const AccountID& accountId)
jpbl's avatar
jpbl committed
775
{
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
776
  if (_dbus) _dbus->getCallManager()->voiceMailNotify(accountId, 0 );
777
} 
jpbl's avatar
jpbl committed
778

yanmorin's avatar
   
yanmorin committed
779
//THREAD=VoIP
jpbl's avatar
jpbl committed
780
void 
yanmorin's avatar
   
yanmorin committed
781
ManagerImpl::registrationSucceed(const AccountID& accountid)
jpbl's avatar
jpbl committed
782
{
783
  Account* acc = getAccount(accountid);
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
784
 if ( acc ) { 
785
    //acc->setState(true); 
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
786
    if (_dbus) _dbus->getConfigurationManager()->accountsChanged();
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
787
  }
jpbl's avatar
jpbl committed
788
789
}

yanmorin's avatar
   
yanmorin committed
790
//THREAD=VoIP
jpbl's avatar
jpbl committed
791
void 
yanmorin's avatar
   
yanmorin committed
792
ManagerImpl::registrationFailed(const AccountID& accountid)
jpbl's avatar
jpbl committed
793
{
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
794
  Account* acc = getAccount(accountid);
795
  if ( acc ) { 
796
    //acc->setState(false);
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
797
    if (_dbus) _dbus->getConfigurationManager()->accountsChanged();
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
798
  }
jpbl's avatar
jpbl committed
799
800
801
802
803
804
805
}

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

jpbl's avatar
jpbl committed
809
810
811
812
813
814
  if (_telephoneTone != 0) {
    _toneMutex.enterMutex();
    _telephoneTone->setCurrentTone(toneId);
    _toneMutex.leaveMutex();

    try {
815
816
      AudioLayer* audiolayer = getAudioDriver();
      if (audiolayer) { audiolayer->startStream(); }
jpbl's avatar
jpbl committed
817
818
    } catch(...) {
      _debugException("Off hold could not start audio stream");
819
      return false;
jpbl's avatar
jpbl committed
820
821
822
823
824
825
826
827
828
    }
  }
  return true;
}

/**
 * Multi Thread
 */
void 
829
ManagerImpl::stopTone(bool stopAudio=true) {
yanmorin's avatar
   
yanmorin committed
830
831
832
  int hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
  if (!hasToPlayTone) return;

833
834
835
836
837
838
839
  if (stopAudio) {
    try {
      AudioLayer* audiolayer = getAudioDriver();
      if (audiolayer) { audiolayer->stopStream(); }
    } catch(...) {
      _debugException("Stop tone and stop stream");
    }
jpbl's avatar
jpbl committed
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
  }

  _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()
{
860
861
  //return playATone(Tone::TONE_DIALTONE);
  playATone(Tone::TONE_DIALTONE);
jpbl's avatar
jpbl committed
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
}

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

jpbl's avatar
jpbl committed
889
890
891
892
893
894
  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; 
  }
895
896
897
898
899

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

jpbl's avatar
jpbl committed
900
  _toneMutex.enterMutex(); 
901
  bool loadFile = _audiofile.loadFile(ringchoice, sampleRate);
jpbl's avatar
jpbl committed
902
903
904
905
906
907
  _toneMutex.leaveMutex(); 
  if (loadFile) {
    _toneMutex.enterMutex(); 
    _audiofile.start();
    _toneMutex.leaveMutex(); 
    try {
908
      audiolayer->startStream();
jpbl's avatar
jpbl committed
909
910
911
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
    } 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
946
ManagerImpl::notificationIncomingCall(void) {
jpbl's avatar
jpbl committed
947
948
949

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

954
955
956
    Tone tone(frequency.str(), samplerate);
    unsigned int nbSampling = tone.getSize();
    SFLDataFormat buf[nbSampling];
jpbl's avatar
jpbl committed
957
    tone.getNext(buf, tone.getSize());
958
    audiolayer->putUrgent(buf, sizeof(SFLDataFormat)*nbSampling);
jpbl's avatar
jpbl committed
959
960
961
962
963
964
  }
}

/**
 * Multi Thread
 */
yanmorin's avatar
   
yanmorin committed
965
966
bool
ManagerImpl::getStunInfo (StunAddress4& stunSvrAddr, int port) 
jpbl's avatar
jpbl committed
967
968
969
970
{
  StunAddress4 mappedAddr;
  struct in_addr in;
  char* addr;
yanmorin's avatar
   
yanmorin committed
971
972
973
974
975

  //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
976
  if (ok) {
yanmorin's avatar
   
yanmorin committed
977
978
979
    closesocket(fd1);
    //closesocket(fd3);
    //closesocket(fd4);
jpbl's avatar
jpbl committed
980
981
982
983
984
985
    _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
986
    return true;
jpbl's avatar
jpbl committed
987
988
989
  } else {
    _debug("Opening a stun socket pair failed\n");
  }
yanmorin's avatar
   
yanmorin committed
990
  return false;
jpbl's avatar
jpbl committed
991
992
993
}

bool
yanmorin's avatar
   
yanmorin committed
994
ManagerImpl::behindNat(const std::string& svr, int port)
yanmorin's avatar
   
yanmorin committed
995
996
997
{
  StunAddress4 stunSvrAddr;
  stunSvrAddr.addr = 0;
Emmanuel Milou's avatar
Bug fix    
Emmanuel Milou committed
998
   
yanmorin's avatar
   
yanmorin committed
999
1000
  // Convert char* to StunAddress4 structure
  bool ret = stunParseServerName ((char*)svr.data(), stunSvrAddr);