managerimpl.cpp 62.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
 *  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
128
    if (audiolayer!=0) {
        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);
    }
jpbl's avatar
jpbl committed
137
138
139
140
}

void ManagerImpl::terminate()
{
141
    saveConfig();
jpbl's avatar
jpbl committed
142

143
    unloadAccountMap();
144
  
145
146
    _debug("Unload DTMF Key\n");
    delete _dtmfKey;
jpbl's avatar
jpbl committed
147

148
149
    _debug("Unload Audio Driver\n");
    delete _audiodriver; _audiodriver = NULL;
jpbl's avatar
jpbl committed
150

151
152
    _debug("Unload Telephone Tone\n");
    delete _telephoneTone; _telephoneTone = NULL;
153

154
155
    _debug("Unload Audio Codecs\n");
    _codecDescriptorMap.deleteHandlePointer();
jpbl's avatar
jpbl committed
156
157
}

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

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

yanmorin's avatar
   
yanmorin committed
172
173
174
const CallID& 
ManagerImpl::getCurrentCallId() {
  return _currentCallId2;
jpbl's avatar
jpbl committed
175
176
177
}

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


///////////////////////////////////////////////////////////////////////////////
// Management of events' IP-phone user
///////////////////////////////////////////////////////////////////////////////
yanmorin's avatar
   
yanmorin committed
187
/* Main Thread */ 
188
  bool
yanmorin's avatar
   
yanmorin committed
189
190
ManagerImpl::outgoingCall(const std::string& accountid, const CallID& id, const std::string& to)
{
191
192
    _debug("ManagerImpl::outgoingCall() method \n");

Emmanuel Milou's avatar
Emmanuel Milou committed
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
    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
209
    associateCallToAccount( id, accountid );
Emmanuel Milou's avatar
Emmanuel Milou committed
210
211
212
213
214
215
216
217
    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
218
219
}

yanmorin's avatar
   
yanmorin committed
220
//THREAD=Main : for outgoing Call
221
  bool
yanmorin's avatar
   
yanmorin committed
222
ManagerImpl::answerCall(const CallID& id)
jpbl's avatar
jpbl committed
223
{
224
  stopTone(false); 
225
  _debug("Try to answer call: %s\n", id.data());
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
  if (id != getCurrentCallId()) {
Yun Liu's avatar
Yun Liu committed
233
234
235
236
    _debug("* Manager Info: there is currently a call, try to hold it\n");
    onHoldCall(getCurrentCallId());
  }

yanmorin's avatar
   
yanmorin committed
237
238
239
240
  if (!getAccountLink(accountid)->answer(id)) {
    // error when receiving...
    removeCallAccount(id);
    return false;
jpbl's avatar
jpbl committed
241
  }
242
  
yanmorin's avatar
   
yanmorin committed
243
  // if it was waiting, it's waiting no more
244
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT");
yanmorin's avatar
   
yanmorin committed
245
246
247
  removeWaitingCall(id);
  switchCall(id);
  return true;
jpbl's avatar
jpbl committed
248
249
}

yanmorin's avatar
   
yanmorin committed
250
//THREAD=Main
251
  bool
yanmorin's avatar
   
yanmorin committed
252
ManagerImpl::hangupCall(const CallID& id)
jpbl's avatar
jpbl committed
253
{
254
  _debug("ManagerImpl::hangupCall(): This function is called when user hangup \n");
255
256
257
    PulseLayer *pulselayer;
    AccountID accountid;
    bool returnValue;
Emmanuel Milou's avatar
Emmanuel Milou committed
258

259
    stopTone(true);
yanmorin's avatar
   
yanmorin committed
260

261
262
263
264
265
266
267
268
269
270
    /* 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
271

272
    returnValue = getAccountLink(accountid)->hangup(id);
273

274
275
276
    _debug("After voip link hungup!\n");
    removeCallAccount(id);
    switchCall("");
277

278
279
280
281
282
283
    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
284
285
}

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

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

yanmorin's avatar
   
yanmorin committed
303
  return returnValue;
jpbl's avatar
jpbl committed
304
305
}

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

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

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

yanmorin's avatar
   
yanmorin committed
321
  removeWaitingCall(id);
322
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HOLD");
yanmorin's avatar
   
yanmorin committed
323
  switchCall("");
324

yanmorin's avatar
   
yanmorin committed
325
326
327
328
  return returnValue;
}

//THREAD=Main
329
  bool
yanmorin's avatar
   
yanmorin committed
330
331
ManagerImpl::offHoldCall(const CallID& id)
{
332
  stopTone(false);
yanmorin's avatar
   
yanmorin committed
333
334
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
335
    _debug("5 Manager OffHold Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
336
    return false;
jpbl's avatar
jpbl committed
337
  }
338

339
340
341
342
343
  //Place current call on hold if it isn't
  if (hasCurrentCall()) 
  { 
    onHoldCall(getCurrentCallId());
  }
344

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

alexandresavard's avatar
alexandresavard committed
347
348
349
350
351
352
353
354
355
  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
356
  bool returnValue = getAccountLink(accountid)->offhold(id);
alexandresavard's avatar
alexandresavard committed
357
358
359
360
361
362
363

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

jpbl's avatar
jpbl committed
366
367
368
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
369
//THREAD=Main
370
  bool
yanmorin's avatar
   
yanmorin committed
371
ManagerImpl::transferCall(const CallID& id, const std::string& to)
jpbl's avatar
jpbl committed
372
{
373
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
374
375
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
376
    _debug("! Manager Transfer Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
377
    return false;
jpbl's avatar
jpbl committed
378
  }
yanmorin's avatar
   
yanmorin committed
379
380
381
  bool returnValue = getAccountLink(accountid)->transfer(id, to);
  removeWaitingCall(id);
  removeCallAccount(id);
382
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
yanmorin's avatar
   
yanmorin committed
383
384
  switchCall("");
  return returnValue;
jpbl's avatar
jpbl committed
385
386
}

yanmorin's avatar
   
yanmorin committed
387
//THREAD=Main : Call:Incoming
388
  bool
yanmorin's avatar
   
yanmorin committed
389
ManagerImpl::refuseCall (const CallID& id)
jpbl's avatar
jpbl committed
390
{
391
  _debug("ManagerImpl::refuseCall(): method called");
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
411
  bool
jpbl's avatar
jpbl committed
412
413
414
415
416
417
418
419
420
421
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
423
 int 
424
ManagerImpl::initRegisterAccounts() 
jpbl's avatar
jpbl committed
425
{
426
    int status; 
427
    bool flag = true;
428
429
430
431
432
    AccountMap::iterator iter;

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

433
    /* Loop on the account map previously loaded */
434
    while( iter != _accountMap.end() ) {
435
436
437
438
439
440
441
442
443
        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;
                }
            }
444
        }
445
        iter++;
Emmanuel Milou's avatar
Emmanuel Milou committed
446
    }
447

448
449
450
451
    // calls the client notification here in case of errors at startup...
    if( _audiodriver -> getErrorMessage() != -1 )
      notifyErrClient( _audiodriver -> getErrorMessage() );
    
452
    ASSERT( flag, true );
453
    return SUCCESS;
jpbl's avatar
jpbl committed
454
455
}

yanmorin's avatar
   
yanmorin committed
456
//THREAD=Main
457
  bool 
yanmorin's avatar
   
yanmorin committed
458
ManagerImpl::sendDtmf(const CallID& id, char code)
jpbl's avatar
jpbl committed
459
{
yanmorin's avatar
   
yanmorin committed
460
461
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
Emmanuel Milou's avatar
Emmanuel Milou committed
462
463
    //_debug("Send DTMF: call doesn't exists\n");
    playDtmf(code, false);
yanmorin's avatar
   
yanmorin committed
464
465
466
    return false;
  }

jpbl's avatar
jpbl committed
467
  int sendType = getConfigInt(SIGNALISATION, SEND_DTMF_AS);
yanmorin's avatar
   
yanmorin committed
468
  bool returnValue = false;
jpbl's avatar
jpbl committed
469
  switch (sendType) {
470
    case 0: // SIP INFO
Emmanuel Milou's avatar
Emmanuel Milou committed
471
      playDtmf(code , true);
472
473
474
475
476
477
478
479
480
      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
481
482
483
484
  }
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
485
//THREAD=Main | VoIPLink
486
  bool
Emmanuel Milou's avatar
Emmanuel Milou committed
487
ManagerImpl::playDtmf(char code, bool isTalking)
jpbl's avatar
jpbl committed
488
{
489
490
491
492
493
494
495
496
497
498
    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
499

500
501
502
503
    // length in milliseconds
    pulselen = getConfigInt(SIGNALISATION, PULSE_LENGTH);
    if (!pulselen)
        return false;
jpbl's avatar
jpbl committed
504

505
506
507
508
    // 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
509

510
511
512
    // fast return, no sound, so no dtmf
    if (audiolayer==0 || _dtmfKey == 0)
        return false;
513

514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
    // 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)
532
        audiolayer->startStream();
533
534
535
        audiolayer->putUrgent (buf, size * sizeof(SFLDataFormat));
    }
    ret = true;
536

537
    // TODO Cache the DTMF
Emmanuel Milou's avatar
Emmanuel Milou committed
538

539
540
541
    delete[] buf; buf = 0;
    
    return ret;
jpbl's avatar
jpbl committed
542
543
}

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

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

void
yanmorin's avatar
   
yanmorin committed
558
ManagerImpl::removeWaitingCall(const CallID& id) {
559
  ost::MutexLock m(_waitingCallMutex);
yanmorin's avatar
   
yanmorin committed
560
561
562
  // should return more than 1 if it erase a call
  if (_waitingCall.erase(id)) {
    _nbIncomingWaitingCall--;
jpbl's avatar
jpbl committed
563
564
565
566
  }
}

bool
yanmorin's avatar
   
yanmorin committed
567
568
569
570
ManagerImpl::isWaitingCall(const CallID& id) {
  CallIDSet::iterator iter = _waitingCall.find(id);
  if (iter != _waitingCall.end()) {
    return false;
jpbl's avatar
jpbl committed
571
  }
yanmorin's avatar
   
yanmorin committed
572
  return true;
jpbl's avatar
jpbl committed
573
574
}

yanmorin's avatar
   
yanmorin committed
575
576
577
578
///////////////////////////////////////////////////////////////////////////////
// Management of event peer IP-phone 
////////////////////////////////////////////////////////////////////////////////
// SipEvent Thread 
Alexandre Savard's avatar
Alexandre Savard committed
579
bool 
yanmorin's avatar
   
yanmorin committed
580
ManagerImpl::incomingCall(Call* call, const AccountID& accountId) 
jpbl's avatar
jpbl committed
581
{
582
583
    PulseLayer *pulselayer;
    std::string from, number;
584

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

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

589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
    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(">");
    }
609
  
610
611
    /* Broadcast a signal over DBus */
    _dbus->getCallManager()->incomingCall(accountId, call->getCallId(), from);
612
  
613
614
615
616
617
    // 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();
    }
618
  
619
    return true;
jpbl's avatar
jpbl committed
620
621
}

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

yanmorin's avatar
   
yanmorin committed
630
//THREAD=VoIP CALL=Outgoing
631
  void
yanmorin's avatar
   
yanmorin committed
632
ManagerImpl::peerAnsweredCall(const CallID& id)
jpbl's avatar
jpbl committed
633
{
yanmorin's avatar
   
yanmorin committed
634
  if (isCurrentCall(id)) {
635
    stopTone(false);
jpbl's avatar
jpbl committed
636
  }
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
637
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT");
jpbl's avatar
jpbl committed
638
639
}

yanmorin's avatar
   
yanmorin committed
640
//THREAD=VoIP Call=Outgoing
641
  void
yanmorin's avatar
   
yanmorin committed
642
ManagerImpl::peerRingingCall(const CallID& id)
jpbl's avatar
jpbl committed
643
{
yanmorin's avatar
   
yanmorin committed
644
  if (isCurrentCall(id)) {
jpbl's avatar
jpbl committed
645
646
    ringback();
  }
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
647
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "RINGING");
jpbl's avatar
jpbl committed
648
649
}

yanmorin's avatar
   
yanmorin committed
650
//THREAD=VoIP Call=Outgoing/Ingoing
651
  void
yanmorin's avatar
   
yanmorin committed
652
ManagerImpl::peerHungupCall(const CallID& id)
jpbl's avatar
jpbl committed
653
{
654
    _debug("ManagerImpl::peerHungupCall():this function is called when peer hangup \n");
655
656
    PulseLayer *pulselayer;
    AccountID accountid;
657
    bool returnValue;
658
659
660
661
662
663

    accountid = getAccountFromCall( id );
    if (accountid == AccountNULL) {
        _debug("peerHungupCall: Call doesn't exists\n");
        return;
    }
Emmanuel Milou's avatar
Emmanuel Milou committed
664
  
665
666
667
668
669
670
671
672
    /* Broadcast a signal over DBus */
    if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
    
    if (isCurrentCall(id)) {
        stopTone(true);
        switchCall("");
    }

673
    returnValue = getAccountLink(accountid)->peerHungup(id);
674

675
676
    removeWaitingCall(id);
    removeCallAccount(id);
Emmanuel Milou's avatar
Emmanuel Milou committed
677
  
678
679
680
681
    if( _audiodriver->getLayerType() == PULSEAUDIO && getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ) ) {
        pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver());
        if(pulselayer)  pulselayer->restorePulseAppsVolume();
    }
jpbl's avatar
jpbl committed
682
683
}

yanmorin's avatar
   
yanmorin committed
684
//THREAD=VoIP
jpbl's avatar
jpbl committed
685
void
yanmorin's avatar
   
yanmorin committed
686
687
ManagerImpl::callBusy(const CallID& id) {
  _debug("Call busy\n");
688

689
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "BUSY");
yanmorin's avatar
   
yanmorin committed
690
691
692
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
jpbl's avatar
jpbl committed
693
  }
yanmorin's avatar
   
yanmorin committed
694
695
  removeCallAccount(id);
  removeWaitingCall(id);
jpbl's avatar
jpbl committed
696
697
}

yanmorin's avatar
   
yanmorin committed
698
//THREAD=VoIP
699
  void
yanmorin's avatar
   
yanmorin committed
700
701
ManagerImpl::callFailure(const CallID& id) 
{
702
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "FAILURE");
Emmanuel Milou's avatar
Emmanuel Milou committed
703
  _debug("CALL ID = %s\n" , id.c_str());
yanmorin's avatar
   
yanmorin committed
704
705
706
707
708
709
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
  }
  removeCallAccount(id);
  removeWaitingCall(id);
710

jpbl's avatar
jpbl committed
711
712
}

yanmorin's avatar
   
yanmorin committed
713
//THREAD=VoIP
714
  void
Emmanuel Milou's avatar
Emmanuel Milou committed
715
ManagerImpl::startVoiceMessageNotification(const AccountID& accountId, int nb_msg)
jpbl's avatar
jpbl committed
716
{
Emmanuel Milou's avatar
Emmanuel Milou committed
717
  if (_dbus) _dbus->getCallManager()->voiceMailNotify(accountId, nb_msg) ;
jpbl's avatar
jpbl committed
718
719
}

720
void ManagerImpl::connectionStatusNotification(  )
721
{
722
723
724
725
    if (_dbus)
        _dbus->getConfigurationManager()->accountsChanged();
    else
        _debug("Error: DBus connection not found\n");
Emmanuel Milou's avatar
nothing    
Emmanuel Milou committed
726
727
}

jpbl's avatar
jpbl committed
728
729
730
/**
 * Multi Thread
 */
731
732
733
734
735
736
bool ManagerImpl::playATone(Tone::TONEID toneId) 
{
    int hasToPlayTone;
    AudioLoop *audioloop;
    AudioLayer *audiolayer;
    unsigned int nbSamples;
yanmorin's avatar
   
yanmorin committed
737

738
739
740
741
742
    hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
    if (!hasToPlayTone) 
        return false;
    
    audiolayer = getAudioDriver();
jpbl's avatar
jpbl committed
743

744
745
746
747
748
749
750
751
752
753
754
755
756
    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
757
  }
758
  return true;
jpbl's avatar
jpbl committed
759
760
761
762
763
}

/**
 * Multi Thread
 */
764
765
766
767
void ManagerImpl::stopTone (bool stopAudio=true)
{
    int hasToPlayTone;
    AudioLayer *audiolayer;
yanmorin's avatar
   
yanmorin committed
768

769
770
771
    hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
    if (!hasToPlayTone) 
        return;
772

773
774
775
776
    if (stopAudio) {
        audiolayer = getAudioDriver();
        if (audiolayer) audiolayer->stopStream();
    }
jpbl's avatar
jpbl committed
777

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

784
785
786
787
    // for ringing tone..
    _toneMutex.enterMutex();
    _audiofile.stop();
    _toneMutex.leaveMutex();
jpbl's avatar
jpbl committed
788
789
790
791
792
}

/**
 * Multi Thread
 */
793
  bool
jpbl's avatar
jpbl committed
794
795
ManagerImpl::playTone()
{
796
  playATone(Tone::TONE_DIALTONE);
Yun Liu's avatar
Yun Liu committed
797
  return true;
jpbl's avatar
jpbl committed
798
799
}

800
801
802
803
804
805
806
/**
 * Multi Thread
 */
  bool
ManagerImpl::playToneWithMessage()
{
  playATone(Tone::TONE_CONGESTION);
Yun Liu's avatar
Yun Liu committed
807
  return true;
808
809
}

jpbl's avatar
jpbl committed
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
/**
 * Multi Thread
 */
void
ManagerImpl::congestion () {
  playATone(Tone::TONE_CONGESTION);
}

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

/**
 * Multi Thread
 */
829
  void
jpbl's avatar
jpbl committed
830
831
ManagerImpl::ringtone() 
{
832
833
834
835
836
837
    std::string ringchoice;
    AudioLayer *audiolayer;
    AudioCodec *codecForTone;
    int layer, samplerate;
    bool loadFile;

838
839
840
841
842
    if( isRingtoneEnabled() )
    {
        //TODO Comment this because it makes the daemon crashes since the main thread
        //synchronizes the ringtone thread.
        
843
        ringchoice = getConfigString(AUDIO, RING_CHOICE);
844
845
846
847
848
849
        //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; 
        }

850
851
852
853
854
855
856
        audiolayer = getAudioDriver();
        layer = audiolayer->getLayerType();
        if (audiolayer == 0)
            return;

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

858
        _toneMutex.enterMutex(); 
859
        loadFile = _audiofile.loadFile(ringchoice, codecForTone , samplerate);
860
        _toneMutex.leaveMutex(); 
861

862
        if (loadFile) {
863
            _toneMutex.enterMutex(); 
864
            _audiofile.start();
865
            _toneMutex.leaveMutex(); 
866
            if(CHECK_INTERFACE( layer, ALSA )){
867
                //ringback();
868
869
870
871
872
873
            }
            else{
                audiolayer->startStream();
            }
        } else {
            ringback();
874
        }
875
876
877
878
879
    
    }
    else
    {
        ringback();
Emmanuel Milou's avatar
Emmanuel Milou committed
880
    }
jpbl's avatar
jpbl committed
881
882
}

883
  AudioLoop*
jpbl's avatar
jpbl committed
884
885
886
ManagerImpl::getTelephoneTone()
{
  if(_telephoneTone != 0) {
887
    ost::MutexLock m(_toneMutex);
jpbl's avatar
jpbl committed
888
889
890
891
892
893
894
    return _telephoneTone->getCurrentTone();
  }
  else {
    return 0;
  }
}

895
  AudioLoop*
jpbl's avatar
jpbl committed
896
897
ManagerImpl::getTelephoneFile()
{
898
  ost::MutexLock m(_toneMutex);
jpbl's avatar
jpbl committed
899
900
901
902
903
904
905
  if(_audiofile.isStarted()) {
    return &_audiofile;
  } else {
    return 0;
  }
}

906
907
908
void ManagerImpl::notificationIncomingCall(void) 
{
    AudioLayer *audiolayer;
jpbl's avatar
jpbl committed
909
    std::ostringstream frequency;
910
911
912
913
914
915
916
917
918
919
920
921
922
    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
923
924
925
926
927
}

/**
 * Multi Thread
 */
928
  bool
yanmorin's avatar
   
yanmorin committed
929
ManagerImpl::getStunInfo (StunAddress4& stunSvrAddr, int port) 
jpbl's avatar
jpbl committed
930
931
932
933
{
  StunAddress4 mappedAddr;
  struct in_addr in;
  char* addr;
yanmorin's avatar
   
yanmorin committed
934
935
936
937
938

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

956
  bool
yanmorin's avatar
   
yanmorin committed
957
ManagerImpl::behindNat(const std::string& svr, int port)
yanmorin's avatar
   
yanmorin committed
958
959
960
{
  StunAddress4 stunSvrAddr;
  stunSvrAddr.addr = 0;
961

yanmorin's avatar
   
yanmorin committed
962
963
964
965
966
  // 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
967
  }
968

yanmorin's avatar
   
yanmorin committed
969
  // Firewall address
970
  _debug("STUN server: %s\n", svr.data());
yanmorin's avatar
   
yanmorin committed
971
  return getStunInfo(stunSvrAddr, port);
jpbl's avatar
jpbl committed
972
973
}

yanmorin's avatar
   
yanmorin committed
974

jpbl's avatar
jpbl committed
975
976
977
978
979
980
///////////////////////////////////////////////////////////////////////////////
// Private functions
///////////////////////////////////////////////////////////////////////////////
/**
 * Initialization: Main Thread
 * @return 1: ok
981
 -1: error directory
jpbl's avatar
jpbl committed
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
 */
int
ManagerImpl::createSettingsPath (void) {
  _path = std::string(HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR;

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

  // Load user's configuration
  _path = _path + DIR_SEPARATOR_STR + PROGNAME + "rc";
997
  return 1;
jpbl's avatar
jpbl committed
998
999
1000
}

/**