managerimpl.cpp 63.8 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
 *  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>
29
#include <sstream>  
jpbl's avatar
jpbl committed
30
31
32
33
34
35
36
37
38
#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"
39
#include "account.h"
40
#include "sipaccount.h"
jpbl's avatar
jpbl committed
41
#include "audio/audiolayer.h"
42
43
#include "audio/alsalayer.h"
#include "audio/pulselayer.h"
jpbl's avatar
jpbl committed
44
45
#include "audio/tonelist.h"

yanmorin's avatar
   
yanmorin committed
46
#include "accountcreator.h" // create new account
47
48
#include "sipvoiplink.h"

jpbl's avatar
jpbl committed
49
50
51
52
53
54
55
#include "user_cfg.h"

#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)))

Yun Liu's avatar
Yun Liu committed
56
57
58
59
ManagerImpl::ManagerImpl (void) 
	: _hasTriedToRegister(false)
        , _config()
	, _currentCallId2()
60
        , _currentCallMutex()
Yun Liu's avatar
Yun Liu committed
61
62
63
64
        , _codecBuilder(NULL)
        , _audiodriver(NULL)
        , _dtmfKey(NULL)
        , _codecDescriptorMap()
65
        , _toneMutex()
Yun Liu's avatar
Yun Liu committed
66
67
68
69
        , _telephoneTone(NULL)
        , _audiofile()
        , _spkr_volume(0)
        , _mic_volume(0)
70
        , _mutex()
Yun Liu's avatar
Yun Liu committed
71
72
	, _dbus(NULL)
        , _waitingCall()
73
        , _waitingCallMutex()
Yun Liu's avatar
Yun Liu committed
74
75
76
77
78
79
80
81
        , _nbIncomingWaitingCall(0)
        , _path("")
        , _exist(0)
        , _setupLoaded(false)
        , _firewallPort()
        , _firewallAddr("")
        , _hasZeroconf(false)
        , _callAccountMap()
82
        , _callAccountMapMutex()
Yun Liu's avatar
Yun Liu committed
83
        , _accountMap()
jpbl's avatar
jpbl committed
84
{
85
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
}

// never call if we use only the singleton...
ManagerImpl::~ManagerImpl (void) 
{
103
104
    terminate();
    _debug("%s stop correctly.\n", PROGNAME);
jpbl's avatar
jpbl committed
105
106
}

107
  void 
jpbl's avatar
jpbl committed
108
109
ManagerImpl::init() 
{
110
111
    // Load accounts, init map
    loadAccountMap();
112
 
113
    initVolume();
114

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

119
120
    initAudioDriver();
    selectAudioDriver();
jpbl's avatar
jpbl committed
121

122
123
    // Initialize the list of supported audio codecs
    initAudioCodec();
124

125
    AudioLayer *audiolayer = getAudioDriver();
126
    
127
    if (audiolayer != 0) {
128
        unsigned int sampleRate = audiolayer->getSampleRate();
jpbl's avatar
jpbl committed
129

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

134
135
136
        _debugInit("Loading DTMF key");
        _dtmfKey = new DTMF(sampleRate);
    }
137
138
139

    if (audiolayer == 0)
      audiolayer->stopStream();
jpbl's avatar
jpbl committed
140
141
142
143
}

void ManagerImpl::terminate()
{
144
    saveConfig();
jpbl's avatar
jpbl committed
145

146
    unloadAccountMap();
147
  
148
149
    _debug("Unload DTMF Key\n");
    delete _dtmfKey;
jpbl's avatar
jpbl committed
150

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

154
155
    _debug("Unload Telephone Tone\n");
    delete _telephoneTone; _telephoneTone = NULL;
156

157
158
    _debug("Unload Audio Codecs\n");
    _codecDescriptorMap.deleteHandlePointer();
jpbl's avatar
jpbl committed
159
160
}

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

yanmorin's avatar
   
yanmorin committed
166
167
bool
ManagerImpl::hasCurrentCall() {
Emmanuel Milou's avatar
Bug fix    
Emmanuel Milou committed
168
  _debug("Current call ID = %s\n", _currentCallId2.c_str());
yanmorin's avatar
   
yanmorin committed
169
170
  if ( _currentCallId2 != "") {
    return true;
jpbl's avatar
jpbl committed
171
  }
yanmorin's avatar
   
yanmorin committed
172
  return false;
jpbl's avatar
jpbl committed
173
174
}

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

void
yanmorin's avatar
   
yanmorin committed
181
ManagerImpl::switchCall(const CallID& id ) {
182
  ost::MutexLock m(_currentCallMutex);
yanmorin's avatar
   
yanmorin committed
183
  _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
/* Main Thread */ 
191
  bool
yanmorin's avatar
   
yanmorin committed
192
193
ManagerImpl::outgoingCall(const std::string& accountid, const CallID& id, const std::string& to)
{
194
195
    _debug("ManagerImpl::outgoingCall() method \n");

196
197
198
    stopTone(false);
    playTone();

Emmanuel Milou's avatar
Emmanuel Milou committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
    if (!accountExists(accountid)) {
        _debug("! Manager Error: Outgoing Call: account doesn't exist\n");
        return false;
    }
  
    if (getAccountFromCall(id) != AccountNULL) {
        _debug("! Manager Error: Outgoing Call: call id already exists\n");
        return false;
    }
  
    if (hasCurrentCall()) {
        _debug("* Manager Info: there is currently a call, try to hold it\n");
        onHoldCall(getCurrentCallId());
    }
  
    _debug("- Manager Action: Adding Outgoing Call %s on account %s\n", id.data(), accountid.data());
yanmorin's avatar
   
yanmorin committed
215
    associateCallToAccount( id, accountid );
Emmanuel Milou's avatar
Emmanuel Milou committed
216
217
218
219
220
221
222
223
    if ( getAccountLink(accountid)->newOutgoingCall(id, to) ) {
        switchCall(id);
        return true;
    } else {
        callFailure(id);
        _debug("! Manager Error: An error occur, the call was not created\n");
    }
    return false;
jpbl's avatar
jpbl committed
224
225
}

yanmorin's avatar
   
yanmorin committed
226
//THREAD=Main : for outgoing Call
227
  bool
yanmorin's avatar
   
yanmorin committed
228
ManagerImpl::answerCall(const CallID& id)
jpbl's avatar
jpbl committed
229
{
230

231
  stopTone(false); 
232
  _debug("Try to answer call: %s\n", id.data());
yanmorin's avatar
   
yanmorin committed
233
234
235
236
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Answering Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
237
  }
yanmorin's avatar
   
yanmorin committed
238

239
  if (id != getCurrentCallId()) {
Yun Liu's avatar
Yun Liu committed
240
241
242
243
    _debug("* Manager Info: there is currently a call, try to hold it\n");
    onHoldCall(getCurrentCallId());
  }

yanmorin's avatar
   
yanmorin committed
244
245
246
247
  if (!getAccountLink(accountid)->answer(id)) {
    // error when receiving...
    removeCallAccount(id);
    return false;
jpbl's avatar
jpbl committed
248
  }
Alexandre Savard's avatar
Alexandre Savard committed
249

yanmorin's avatar
   
yanmorin committed
250
  // if it was waiting, it's waiting no more
251
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT");
yanmorin's avatar
   
yanmorin committed
252
253
  removeWaitingCall(id);
  switchCall(id);
254
255
256
257
258
 
  std::string codecName = getCurrentCodecName(id);
  _debug("ManagerImpl::hangupCall(): broadcast codec name %s \n",codecName.c_str());
  if (_dbus) _dbus->getCallManager()->currentSelectedCodec(id,codecName.c_str());

yanmorin's avatar
   
yanmorin committed
259
  return true;
jpbl's avatar
jpbl committed
260
261
}

yanmorin's avatar
   
yanmorin committed
262
//THREAD=Main
263
  bool
yanmorin's avatar
   
yanmorin committed
264
ManagerImpl::hangupCall(const CallID& id)
jpbl's avatar
jpbl committed
265
{
Alexandre Savard's avatar
Alexandre Savard committed
266
    _debug("ManagerImpl::hangupCall(): This function is called when user hangup \n");
267
268
269
    PulseLayer *pulselayer;
    AccountID accountid;
    bool returnValue;
Emmanuel Milou's avatar
Emmanuel Milou committed
270

271
    stopTone(true);
yanmorin's avatar
   
yanmorin committed
272

273
274
275
276
277
278
279
280
281
282
    /* Broadcast a signal over DBus */
    if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
  
    accountid = getAccountFromCall( id );
    if (accountid == AccountNULL) {
        /** @todo We should tell the GUI that the call doesn't exist, so
        * it clears up. This can happen. */
        _debug("! Manager Hangup Call: Call doesn't exists\n");
        return false;
    }
Emmanuel Milou's avatar
Emmanuel Milou committed
283

284
    returnValue = getAccountLink(accountid)->hangup(id);
285

286
287
288
    _debug("After voip link hungup!\n");
    removeCallAccount(id);
    switchCall("");
289

290
291
292
293
294
295
    if( _audiodriver->getLayerType() == PULSEAUDIO && getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ) ) {
        pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver());
        if(pulselayer)  pulselayer->restorePulseAppsVolume();
    }
  
    return returnValue;
jpbl's avatar
jpbl committed
296
297
}

yanmorin's avatar
   
yanmorin committed
298
//THREAD=Main
299
  bool
yanmorin's avatar
   
yanmorin committed
300
ManagerImpl::cancelCall (const CallID& id)
jpbl's avatar
jpbl committed
301
{
302
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
303
304
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
305
    _debug("! Manager Cancel Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
306
    return false;
jpbl's avatar
jpbl committed
307
  }
yanmorin's avatar
   
yanmorin committed
308
309
310
311
312
313

  bool returnValue = getAccountLink(accountid)->cancel(id);
  // it could be a waiting call?
  removeWaitingCall(id);
  removeCallAccount(id);
  switchCall("");
314

yanmorin's avatar
   
yanmorin committed
315
  return returnValue;
jpbl's avatar
jpbl committed
316
317
}

yanmorin's avatar
   
yanmorin committed
318
//THREAD=Main
319
  bool
yanmorin's avatar
   
yanmorin committed
320
ManagerImpl::onHoldCall(const CallID& id)
jpbl's avatar
jpbl committed
321
{
322

323
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
324
325
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
326
    _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
327
    return false;
jpbl's avatar
jpbl committed
328
  }
yanmorin's avatar
   
yanmorin committed
329

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

yanmorin's avatar
   
yanmorin committed
332
  bool returnValue = getAccountLink(accountid)->onhold(id);
333

yanmorin's avatar
   
yanmorin committed
334
  removeWaitingCall(id);
335
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HOLD");
yanmorin's avatar
   
yanmorin committed
336
  switchCall("");
337

yanmorin's avatar
   
yanmorin committed
338
339
340
341
  return returnValue;
}

//THREAD=Main
342
  bool
yanmorin's avatar
   
yanmorin committed
343
344
ManagerImpl::offHoldCall(const CallID& id)
{
345
  
346
  stopTone(false);
yanmorin's avatar
   
yanmorin committed
347
348
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
349
    _debug("5 Manager OffHold Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
350
    return false;
jpbl's avatar
jpbl committed
351
  }
352

353
354
355
356
357
  //Place current call on hold if it isn't
  if (hasCurrentCall()) 
  { 
    onHoldCall(getCurrentCallId());
  }
358

359
360
  _debug("Setting OFFHOLD, Account %s, callid %s\n", accountid.c_str(), id.c_str());

alexandresavard's avatar
alexandresavard committed
361
362
363
364
365
366
367
368
369
  bool rec = getAccountLink(accountid)->isRecording(id);
  
  /*
  if(rec)
    _debug("ManagerImpl::offHoldCall(): Record state is true \n");
  else
    _debug("ManagerImpl::offHoldCall(): Record state is false \n");
  */

yanmorin's avatar
   
yanmorin committed
370
  bool returnValue = getAccountLink(accountid)->offhold(id);
alexandresavard's avatar
alexandresavard committed
371
372
373
374
375
376
377

  if (_dbus){ 
    if (rec)
      _dbus->getCallManager()->callStateChanged(id, "UNHOLD_RECORD");
    else 
      _dbus->getCallManager()->callStateChanged(id, "UNHOLD_CURRENT");
  }
yanmorin's avatar
   
yanmorin committed
378
  switchCall(id);
379

380
381
382
383
  std::string codecName = getCurrentCodecName(id);
  _debug("ManagerImpl::hangupCall(): broadcast codec name %s \n",codecName.c_str());
  if (_dbus) _dbus->getCallManager()->currentSelectedCodec(id,codecName.c_str());

jpbl's avatar
jpbl committed
384
385
386
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
387
//THREAD=Main
388
  bool
yanmorin's avatar
   
yanmorin committed
389
ManagerImpl::transferCall(const CallID& id, const std::string& to)
jpbl's avatar
jpbl committed
390
{
391
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
392
393
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
394
    _debug("! Manager Transfer Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
395
    return false;
jpbl's avatar
jpbl committed
396
  }
yanmorin's avatar
   
yanmorin committed
397
398
399
  bool returnValue = getAccountLink(accountid)->transfer(id, to);
  removeWaitingCall(id);
  removeCallAccount(id);
400
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
yanmorin's avatar
   
yanmorin committed
401
402
  switchCall("");
  return returnValue;
jpbl's avatar
jpbl committed
403
404
}

yanmorin's avatar
   
yanmorin committed
405
//THREAD=Main : Call:Incoming
406
  bool
yanmorin's avatar
   
yanmorin committed
407
ManagerImpl::refuseCall (const CallID& id)
jpbl's avatar
jpbl committed
408
{
409
  _debug("ManagerImpl::refuseCall(): method called");
410
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
411
412
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
413
    _debug("! Manager OffHold Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
414
415
416
    return false;
  }
  bool returnValue = getAccountLink(accountid)->refuse(id);
yanmorin's avatar
   
yanmorin committed
417
418
419
420
421
  // if the call was outgoing or established, we didn't refuse it
  // so the method did nothing
  if (returnValue) {
    removeWaitingCall(id);
    removeCallAccount(id);
422
    if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
yanmorin's avatar
   
yanmorin committed
423
424
    switchCall("");
  }
yanmorin's avatar
   
yanmorin committed
425
  return returnValue;
jpbl's avatar
jpbl committed
426
427
}

yanmorin's avatar
   
yanmorin committed
428
//THREAD=Main
429
  bool
jpbl's avatar
jpbl committed
430
431
432
433
434
435
436
437
438
439
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
440
//THREAD=Main
441
 int 
442
ManagerImpl::initRegisterAccounts() 
jpbl's avatar
jpbl committed
443
{
444
    int status; 
445
    bool flag = true;
446
447
448
449
450
    AccountMap::iterator iter;

    _debugInit("Initiate VoIP Links Registration");
    iter = _accountMap.begin();

451
    /* Loop on the account map previously loaded */
452
    while( iter != _accountMap.end() ) {
453
454
455
456
457
458
459
460
461
        if ( iter->second ) {
            iter->second->loadConfig();
            /* If the account is set as enabled, try to register */
            if ( iter->second->isEnabled() ) {
	            status = iter->second->registerVoIPLink();
	            if (status != SUCCESS){
		            flag = false;
                }
            }
462
        }
463
        iter++;
Emmanuel Milou's avatar
Emmanuel Milou committed
464
    }
465

466
467
468
469
    // calls the client notification here in case of errors at startup...
    if( _audiodriver -> getErrorMessage() != -1 )
      notifyErrClient( _audiodriver -> getErrorMessage() );
    
470
    ASSERT( flag, true );
471
    return SUCCESS;
jpbl's avatar
jpbl committed
472
473
}

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

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

    case 1: // Audio way
      break;
    case 2: // rfc 2833
      break;
    default: // unknown - error config?
      break;
jpbl's avatar
jpbl committed
499
500
501
502
  }
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
503
//THREAD=Main | VoIPLink
504
  bool
Emmanuel Milou's avatar
Emmanuel Milou committed
505
ManagerImpl::playDtmf(char code, bool isTalking)
jpbl's avatar
jpbl committed
506
{
507
508
509
510
511
512
513
514
515
516
    int hasToPlayTone, pulselen, layer, size;
    bool ret = false;
    AudioLayer *audiolayer;
    SFLDataFormat *buf;
  
    stopTone(false);
    
    hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_DTMF);
    if (!hasToPlayTone) 
        return false;
jpbl's avatar
jpbl committed
517

518
519
520
521
    // length in milliseconds
    pulselen = getConfigInt(SIGNALISATION, PULSE_LENGTH);
    if (!pulselen)
        return false;
jpbl's avatar
jpbl committed
522

523
524
525
526
    // numbers of int = length in milliseconds / 1000 (number of seconds)
    //                = number of seconds * SAMPLING_RATE by SECONDS
    audiolayer = getAudioDriver();
    layer = audiolayer->getLayerType();
jpbl's avatar
jpbl committed
527

528
529
530
    // fast return, no sound, so no dtmf
    if (audiolayer==0 || _dtmfKey == 0)
        return false;
531

532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
    // number of data sampling in one pulselen depends on samplerate
    // size (n sampling) = time_ms * sampling/s 
    //                     ---------------------
    //                            ms/s
    size = (int)(pulselen * ((float)audiolayer->getSampleRate()/1000));

    // this buffer is for mono
    // TODO <-- this should be global and hide if same size
    buf = new SFLDataFormat[size];

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

    // copy the sound
    if ( _dtmfKey->generateDTMF(buf, size) ) {
        // Put buffer to urgentRingBuffer 
        // put the size in bytes...
        // so size * 1 channel (mono) * sizeof (bytes for the data)
550
        audiolayer->startStream();
551
552
553
        audiolayer->putUrgent (buf, size * sizeof(SFLDataFormat));
    }
    ret = true;
554

555
    // TODO Cache the DTMF
Emmanuel Milou's avatar
Emmanuel Milou committed
556

557
558
559
    delete[] buf; buf = 0;
    
    return ret;
jpbl's avatar
jpbl committed
560
561
}

yanmorin's avatar
   
yanmorin committed
562
// Multi-thread 
jpbl's avatar
jpbl committed
563
564
565
566
567
568
bool
ManagerImpl::incomingCallWaiting() {
  return (_nbIncomingWaitingCall > 0) ? true : false;
}

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

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

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

yanmorin's avatar
   
yanmorin committed
593
594
595
596
///////////////////////////////////////////////////////////////////////////////
// Management of event peer IP-phone 
////////////////////////////////////////////////////////////////////////////////
// SipEvent Thread 
Alexandre Savard's avatar
Alexandre Savard committed
597
bool 
yanmorin's avatar
   
yanmorin committed
598
ManagerImpl::incomingCall(Call* call, const AccountID& accountId) 
jpbl's avatar
jpbl committed
599
{
600
601
    PulseLayer *pulselayer;
    std::string from, number;
602

603
    _debug("Incoming call %s\n", call->getCallId().data());
604

605
    associateCallToAccount(call->getCallId(), accountId);
jpbl's avatar
jpbl committed
606

607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
    if ( !hasCurrentCall() ) {
        call->setConnectionState(Call::Ringing);
        ringtone();
        switchCall(call->getCallId());
    } else {
        addWaitingCall(call->getCallId());
    }

    from = call->getPeerName();
    number = call->getPeerNumber();

    if (from != "" && number != "") {
        from.append(" <");
        from.append(number);
        from.append(">");
    } else if ( from.empty() ) {
        from.append("<");
        from.append(number);
        from.append(">");
    }
627
  
628
629
    /* Broadcast a signal over DBus */
    _dbus->getCallManager()->incomingCall(accountId, call->getCallId(), from);
630
  
631
632
633
634
635
    // Reduce volume of the other pulseaudio-connected audio applications
    if( _audiodriver->getLayerType() == PULSEAUDIO && getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ) ) {
        pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver());
        if(pulselayer)  pulselayer->reducePulseAppsVolume();
    }
636
  
637
    return true;
jpbl's avatar
jpbl committed
638
639
}

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

yanmorin's avatar
   
yanmorin committed
648
//THREAD=VoIP CALL=Outgoing
649
  void
yanmorin's avatar
   
yanmorin committed
650
ManagerImpl::peerAnsweredCall(const CallID& id)
jpbl's avatar
jpbl committed
651
{
yanmorin's avatar
   
yanmorin committed
652
  if (isCurrentCall(id)) {
653
    stopTone(false);
jpbl's avatar
jpbl committed
654
  }
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
655
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT");
Alexandre Savard's avatar
Alexandre Savard committed
656
657
658
659
  
  std::string codecName = getCurrentCodecName(id);
  _debug("ManagerImpl::hangupCall(): broadcast codec name %s \n",codecName.c_str());
  if (_dbus) _dbus->getCallManager()->currentSelectedCodec(id,codecName.c_str());
jpbl's avatar
jpbl committed
660
661
}

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

yanmorin's avatar
   
yanmorin committed
672
//THREAD=VoIP Call=Outgoing/Ingoing
673
  void
yanmorin's avatar
   
yanmorin committed
674
ManagerImpl::peerHungupCall(const CallID& id)
jpbl's avatar
jpbl committed
675
{
676
    _debug("ManagerImpl::peerHungupCall():this function is called when peer hangup \n");
677
678
    PulseLayer *pulselayer;
    AccountID accountid;
679
    bool returnValue;
680
681
682
683
684
685

    accountid = getAccountFromCall( id );
    if (accountid == AccountNULL) {
        _debug("peerHungupCall: Call doesn't exists\n");
        return;
    }
Emmanuel Milou's avatar
Emmanuel Milou committed
686
  
687
688
689
690
691
692
693
694
    /* Broadcast a signal over DBus */
    if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
    
    if (isCurrentCall(id)) {
        stopTone(true);
        switchCall("");
    }

695
    returnValue = getAccountLink(accountid)->peerHungup(id);
696

697
698
    removeWaitingCall(id);
    removeCallAccount(id);
Emmanuel Milou's avatar
Emmanuel Milou committed
699
  
700
701
702
703
    if( _audiodriver->getLayerType() == PULSEAUDIO && getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ) ) {
        pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver());
        if(pulselayer)  pulselayer->restorePulseAppsVolume();
    }
jpbl's avatar
jpbl committed
704
705
}

yanmorin's avatar
   
yanmorin committed
706
//THREAD=VoIP
jpbl's avatar
jpbl committed
707
void
yanmorin's avatar
   
yanmorin committed
708
709
ManagerImpl::callBusy(const CallID& id) {
  _debug("Call busy\n");
710

711
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "BUSY");
yanmorin's avatar
   
yanmorin committed
712
713
714
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
jpbl's avatar
jpbl committed
715
  }
yanmorin's avatar
   
yanmorin committed
716
717
  removeCallAccount(id);
  removeWaitingCall(id);
jpbl's avatar
jpbl committed
718
719
}

yanmorin's avatar
   
yanmorin committed
720
//THREAD=VoIP
721
  void
yanmorin's avatar
   
yanmorin committed
722
723
ManagerImpl::callFailure(const CallID& id) 
{
724
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "FAILURE");
Emmanuel Milou's avatar
Emmanuel Milou committed
725
  _debug("CALL ID = %s\n" , id.c_str());
yanmorin's avatar
   
yanmorin committed
726
727
728
729
730
731
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
  }
  removeCallAccount(id);
  removeWaitingCall(id);
732

jpbl's avatar
jpbl committed
733
734
}

yanmorin's avatar
   
yanmorin committed
735
//THREAD=VoIP
736
  void
Emmanuel Milou's avatar
Emmanuel Milou committed
737
ManagerImpl::startVoiceMessageNotification(const AccountID& accountId, int nb_msg)
jpbl's avatar
jpbl committed
738
{
Emmanuel Milou's avatar
Emmanuel Milou committed
739
  if (_dbus) _dbus->getCallManager()->voiceMailNotify(accountId, nb_msg) ;
jpbl's avatar
jpbl committed
740
741
}

742
void ManagerImpl::connectionStatusNotification(  )
743
{
744
745
746
747
    if (_dbus)
        _dbus->getConfigurationManager()->accountsChanged();
    else
        _debug("Error: DBus connection not found\n");
Emmanuel Milou's avatar
nothing    
Emmanuel Milou committed
748
749
}

jpbl's avatar
jpbl committed
750
751
752
/**
 * Multi Thread
 */
753
754
755
756
757
758
bool ManagerImpl::playATone(Tone::TONEID toneId) 
{
    int hasToPlayTone;
    AudioLoop *audioloop;
    AudioLayer *audiolayer;
    unsigned int nbSamples;
yanmorin's avatar
   
yanmorin committed
759

760
761
762
763
764
    hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
    if (!hasToPlayTone) 
        return false;
    
    audiolayer = getAudioDriver();
765
   
766
767
768
769
770
771
772
773
774
775
776
777
778
    if (_telephoneTone != 0) {
        _toneMutex.enterMutex();
        _telephoneTone->setCurrentTone(toneId);
        _toneMutex.leaveMutex();

        audioloop = getTelephoneTone();
        nbSamples = audioloop->getSize();
        SFLDataFormat buf[nbSamples];
    
        if ( audiolayer ){ 
            audiolayer->putUrgent( buf, nbSamples );
        } else 
            return false;
jpbl's avatar
jpbl committed
779
  }
780
  return true;
jpbl's avatar
jpbl committed
781
782
783
784
785
}

/**
 * Multi Thread
 */
786
787
788
789
void ManagerImpl::stopTone (bool stopAudio=true)
{
    int hasToPlayTone;
    AudioLayer *audiolayer;
yanmorin's avatar
   
yanmorin committed
790

791
792
793
    hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
    if (!hasToPlayTone) 
        return;
794

795
796
797
798
    if (stopAudio) {
        audiolayer = getAudioDriver();
        if (audiolayer) audiolayer->stopStream();
    }
jpbl's avatar
jpbl committed
799

800
801
802
803
804
    _toneMutex.enterMutex();
    if (_telephoneTone != 0) {
        _telephoneTone->setCurrentTone(Tone::TONE_NULL);
    }
    _toneMutex.leaveMutex();
jpbl's avatar
jpbl committed
805

806
807
808
809
    // for ringing tone..
    _toneMutex.enterMutex();
    _audiofile.stop();
    _toneMutex.leaveMutex();
jpbl's avatar
jpbl committed
810
811
812
813
814
}

/**
 * Multi Thread
 */
815
  bool
jpbl's avatar
jpbl committed
816
817
ManagerImpl::playTone()
{
818
  playATone(Tone::TONE_DIALTONE);
Yun Liu's avatar
Yun Liu committed
819
  return true;
jpbl's avatar
jpbl committed
820
821
}

822
823
824
825
826
827
828
/**
 * Multi Thread
 */
  bool
ManagerImpl::playToneWithMessage()
{
  playATone(Tone::TONE_CONGESTION);
Yun Liu's avatar
Yun Liu committed
829
  return true;
830
831
}

jpbl's avatar
jpbl committed
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
/**
 * Multi Thread
 */
void
ManagerImpl::congestion () {
  playATone(Tone::TONE_CONGESTION);
}

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

/**
 * Multi Thread
 */
851
  void
jpbl's avatar
jpbl committed
852
853
ManagerImpl::ringtone() 
{
854
855
856
857
858
859
    std::string ringchoice;
    AudioLayer *audiolayer;
    AudioCodec *codecForTone;
    int layer, samplerate;
    bool loadFile;

860
861
862
863
864
    if( isRingtoneEnabled() )
    {
        //TODO Comment this because it makes the daemon crashes since the main thread
        //synchronizes the ringtone thread.
        
865
        ringchoice = getConfigString(AUDIO, RING_CHOICE);
866
867
868
869
870
871
        //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; 
        }

872
873
874
875
876
877
878
        audiolayer = getAudioDriver();
        layer = audiolayer->getLayerType();
        if (audiolayer == 0)
            return;

        samplerate  = audiolayer->getSampleRate();
        codecForTone = _codecDescriptorMap.getFirstCodecAvailable();
Emmanuel Milou's avatar
Emmanuel Milou committed
879

880
        _toneMutex.enterMutex(); 
881
        loadFile = _audiofile.loadFile(ringchoice, codecForTone , samplerate);
882
        _toneMutex.leaveMutex(); 
883

884
        if (loadFile) {
885
            _toneMutex.enterMutex(); 
886
            _audiofile.start();
887
            _toneMutex.leaveMutex(); 
888
            if(CHECK_INTERFACE( layer, ALSA )){
889
                //ringback();
890
891
892
893
894
895
            }
            else{
                audiolayer->startStream();
            }
        } else {
            ringback();
896
        }
897
898
899
900
901
    
    }
    else
    {
        ringback();
Emmanuel Milou's avatar
Emmanuel Milou committed
902
    }
jpbl's avatar
jpbl committed
903
904
}

905
  AudioLoop*
jpbl's avatar
jpbl committed
906
907
908
ManagerImpl::getTelephoneTone()
{
  if(_telephoneTone != 0) {
909
    ost::MutexLock m(_toneMutex);
jpbl's avatar
jpbl committed
910
911
912
913
914
915
916
    return _telephoneTone->getCurrentTone();
  }
  else {
    return 0;
  }
}

917
  AudioLoop*
jpbl's avatar
jpbl committed
918
919
ManagerImpl::getTelephoneFile()
{
920
  ost::MutexLock m(_toneMutex);
jpbl's avatar
jpbl committed
921
922
923
924
925
926
927
  if(_audiofile.isStarted()) {
    return &_audiofile;
  } else {
    return 0;
  }
}

928
929
930
void ManagerImpl::notificationIncomingCall(void) 
{
    AudioLayer *audiolayer;
jpbl's avatar
jpbl committed
931
    std::ostringstream frequency;
932
933
934
935
936
937
938
939
940
941
942
943
944
    unsigned int samplerate, nbSampling;

    audiolayer = getAudioDriver();
    if (audiolayer != 0) {
        samplerate = audiolayer->getSampleRate();
        frequency << "440/" << FRAME_PER_BUFFER;
        Tone tone(frequency.str(), samplerate);
        nbSampling = tone.getSize();
        SFLDataFormat buf[nbSampling];
        tone.getNext(buf, tone.getSize());
        /* Put the data in the urgent ring buffer */
        audiolayer->putUrgent (buf, sizeof(SFLDataFormat)*nbSampling);
    }
jpbl's avatar
jpbl committed
945
946
947
948
949
}

/**
 * Multi Thread
 */
950
  bool
yanmorin's avatar
   
yanmorin committed
951
ManagerImpl::getStunInfo (StunAddress4& stunSvrAddr, int port) 
jpbl's avatar
jpbl committed
952
953
954
955
{
  StunAddress4 mappedAddr;
  struct in_addr in;
  char* addr;
yanmorin's avatar
   
yanmorin committed
956
957
958
959
960

  //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
961
  if (ok) {
yanmorin's avatar
   
yanmorin committed
962
963
964
    closesocket(fd1);
    //closesocket(fd3);
    //closesocket(fd4);
jpbl's avatar
jpbl committed
965
966
967
968
969
970
    _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
971
    return true;
jpbl's avatar
jpbl committed
972
973
974
  } else {
    _debug("Opening a stun socket pair failed\n");
  }
yanmorin's avatar
   
yanmorin committed
975
  return false;
jpbl's avatar
jpbl committed
976
977
}

978
  bool
yanmorin's avatar
   
yanmorin committed
979
ManagerImpl::behindNat(const std::string& svr, int port)
yanmorin's avatar
   
yanmorin committed
980
981
982
{
  StunAddress4 stunSvrAddr;
  stunSvrAddr.addr = 0;
983

yanmorin's avatar
   
yanmorin committed
984
985
986
987
988
  // 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
989
  }
990

yanmorin's avatar
   
yanmorin committed
991
  // Firewall address
992
  _debug("STUN server: %s\n", svr.data());
yanmorin's avatar
   
yanmorin committed
993
  return getStunInfo(stunSvrAddr, port);
jpbl's avatar
jpbl committed
994
995
}

yanmorin's avatar
   
yanmorin committed
996

jpbl's avatar
jpbl committed
997
998
999
1000
///////////////////////////////////////////////////////////////////////////////
// Private functions
///////////////////////////////////////////////////////////////////////////////
/**