managerimpl.cpp 51 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
6
 *  Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com>
 *
jpbl's avatar
jpbl committed
7
8
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
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
11
 *
jpbl's avatar
jpbl committed
12
13
14
15
 *  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.
16
 *
jpbl's avatar
jpbl committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 *  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"
37
#include "account.h"
jpbl's avatar
jpbl committed
38
39
40
41
#include "audio/audiolayer.h"
#include "audio/audiocodec.h"
#include "audio/tonelist.h"

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

#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;
70
  _dbus = NULL;
jpbl's avatar
jpbl committed
71

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

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

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

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

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

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

#ifdef USE_ZEROCONF
103
  delete _DNSService; _DNSService = 0;
jpbl's avatar
jpbl committed
104
105
106
107
108
109
110
111
#endif

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

void 
ManagerImpl::init() 
{
112
113
114
  // Load accounts, init map
  loadAccountMap();

jpbl's avatar
jpbl committed
115
116
117
118
119
120
  initVolume();

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

121
122
123
  initAudioDriver();
  selectAudioDriver();

jpbl's avatar
jpbl committed
124
125
126
127
128
129
130
131
  initAudioCodec();

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

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

    _debugInit("Loading DTMF key");
135
    _dtmfKey = new DTMF(sampleRate);
jpbl's avatar
jpbl committed
136
137
  }

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

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

  _debug("Unload Audio Driver\n");
153
  delete _audiodriver; _audiodriver = NULL;
jpbl's avatar
jpbl committed
154
155

  _debug("Unload Telephone Tone\n");
156
  delete _telephoneTone; _telephoneTone = NULL;
jpbl's avatar
jpbl committed
157
158
}

yanmorin's avatar
   
yanmorin committed
159
160
161
162
bool
ManagerImpl::isCurrentCall(const CallID& callId) {
  ost::MutexLock m(_currentCallMutex);
  return (_currentCallId2 == callId ? true : false);
jpbl's avatar
jpbl committed
163
164
}

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

yanmorin's avatar
   
yanmorin committed
174
175
176
177
const CallID& 
ManagerImpl::getCurrentCallId() {
  ost::MutexLock m(_currentCallMutex);
  return _currentCallId2;
jpbl's avatar
jpbl committed
178
179
180
}

void
yanmorin's avatar
   
yanmorin committed
181
182
183
ManagerImpl::switchCall(const CallID& id ) {
  ost::MutexLock m(_currentCallMutex);
  _currentCallId2 = id;
jpbl's avatar
jpbl committed
184
185
186
187
188
189
}


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

yanmorin's avatar
   
yanmorin committed
217
218
219
//THREAD=Main : for outgoing Call
bool
ManagerImpl::answerCall(const CallID& id)
jpbl's avatar
jpbl committed
220
{
221
  stopTone(false); 
222
223
224
225
  if (hasCurrentCall()) 
  { 
    onHoldCall(getCurrentCallId());
  }
yanmorin's avatar
   
yanmorin committed
226
227
228
229
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Answering Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
230
  }
yanmorin's avatar
   
yanmorin committed
231
232
233
234
235

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

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

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

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

  bool returnValue = getAccountLink(accountid)->hangup(id);
  removeCallAccount(id);
  switchCall("");
275
276
  
  
yanmorin's avatar
   
yanmorin committed
277
  return returnValue;
jpbl's avatar
jpbl committed
278
279
}

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

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

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

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

yanmorin's avatar
   
yanmorin committed
313
  bool returnValue = getAccountLink(accountid)->onhold(id);
314
  
yanmorin's avatar
   
yanmorin committed
315
  removeWaitingCall(id);
316
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HOLD");
yanmorin's avatar
   
yanmorin committed
317
318
319
320
321
322
323
324
325
  switchCall("");
  
  return returnValue;
}

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

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

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

  return returnValue;
jpbl's avatar
jpbl committed
371
372
}

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

yanmorin's avatar
   
yanmorin committed
380
//THREAD=Main
jpbl's avatar
jpbl committed
381
382
383
384
385
386
387
void
ManagerImpl::unmute() {
  if ( _mic_volume == 0 ) {
    setMicVolume(_mic_volume_before_mute);
  }
}

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

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

yanmorin's avatar
   
yanmorin committed
444
//THREAD=Main
jpbl's avatar
jpbl committed
445
bool
446
ManagerImpl::registerAccount(const AccountID& accountId)
jpbl's avatar
jpbl committed
447
448
449
{
  _debug("Register VoIP Link\n");
  int returnValue = false;
450
451
452
453
454
455
456
  // 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 ) {
457
        iter->second->unregisterVoIPLink();
458
459
460
461
        iter->second->terminate();
      }
      iter++;
    }
462
    returnValue = account->registerVoIPLink();
jpbl's avatar
jpbl committed
463
464
465
466
  }
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
467
//THREAD=Main
jpbl's avatar
jpbl committed
468
bool 
469
ManagerImpl::unregisterAccount(const AccountID& accountId)
jpbl's avatar
jpbl committed
470
471
{
  _debug("Unregister VoIP Link\n");
yanmorin's avatar
   
yanmorin committed
472
473
  int returnValue = false;
  if (accountExists( accountId ) ) {
474
    returnValue = getAccount(accountId)->unregisterVoIPLink();
yanmorin's avatar
   
yanmorin committed
475
476
  }
  return returnValue;
jpbl's avatar
jpbl committed
477
478
}

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

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

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

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

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

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

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

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

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

    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;
  }
563
564

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

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

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

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

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



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

yanmorin's avatar
   
yanmorin committed
613
  associateCallToAccount(call->getCallId(), accountId);
614

yanmorin's avatar
   
yanmorin committed
615
616
  if ( !hasCurrentCall() ) {
    call->setConnectionState(Call::Ringing);
jpbl's avatar
jpbl committed
617
    ringtone();
yanmorin's avatar
   
yanmorin committed
618
    switchCall(call->getCallId());
jpbl's avatar
jpbl committed
619
  } else {
yanmorin's avatar
   
yanmorin committed
620
     addWaitingCall(call->getCallId());
jpbl's avatar
jpbl committed
621
622
  }

yanmorin's avatar
   
yanmorin committed
623
624
625
  std::string from = call->getPeerName();
  std::string number = call->getPeerNumber();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

jpbl's avatar
jpbl committed
886
887
888
889
890
891
  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; 
  }
892
893
894
895
896

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

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

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

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

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

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

bool
yanmorin's avatar
   
yanmorin committed
991
ManagerImpl::behindNat(const std::string& svr, int port)
yanmorin's avatar
   
yanmorin committed
992
993
994
995
996
997
998
999
1000
{
  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;