managerimpl.cpp 65 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
232
233
234
235
236
237
  bool isActive = false;

  AccountID currentaccountid = getAccountFromCall( id );
  Call* currentcall = getAccountLink(currentaccountid)->getCall(getCurrentCallId());
  _debug("ManagerImpl::answerCall :: current call->getState %i \n",currentcall->getState());

  if (currentcall->getState() == 1)
      isActive = true;
238

239
  stopTone(false); 
240
  _debug("Try to answer call: %s\n", id.data());
yanmorin's avatar
   
yanmorin committed
241
242
243
244
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
    _debug("Answering Call: Call doesn't exists\n");
    return false;
jpbl's avatar
jpbl committed
245
  }
yanmorin's avatar
   
yanmorin committed
246

247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
  /*
  _debug("_nbIncomingWaitingCall =======>>>>>>>> %i \n",_nbIncomingWaitingCall);
  
  CallIDSet::iterator iter = _waitingCall.begin();
  while (iter != _waitingCall.end()) {
      CallID ident = *iter;
      AccountID acc = getAccountFromCall( ident );
      Call* call = getAccountLink(acc)->getCall(ident);
      _debug("ManagerImpl::answerCall :: incoming call ident: %s \n",ident.c_str());
      _debug("ManagerImpl::answerCall :: incoming call state: %i \n",call->getState());
      ++iter;
  }
  */
  
  //  if (id != getCurrentCallId()) {
  if (isActive) { 
Yun Liu's avatar
Yun Liu committed
263
    _debug("* Manager Info: there is currently a call, try to hold it\n");
264

Yun Liu's avatar
Yun Liu committed
265
266
    onHoldCall(getCurrentCallId());
  }
267
  
Yun Liu's avatar
Yun Liu committed
268

yanmorin's avatar
   
yanmorin committed
269
270
271
272
  if (!getAccountLink(accountid)->answer(id)) {
    // error when receiving...
    removeCallAccount(id);
    return false;
jpbl's avatar
jpbl committed
273
  }
Alexandre Savard's avatar
Alexandre Savard committed
274

yanmorin's avatar
   
yanmorin committed
275
  // if it was waiting, it's waiting no more
276
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT");
yanmorin's avatar
   
yanmorin committed
277
278
  removeWaitingCall(id);
  switchCall(id);
279
280
281
282
283
 
  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
284
  return true;
jpbl's avatar
jpbl committed
285
286
}

yanmorin's avatar
   
yanmorin committed
287
//THREAD=Main
288
  bool
yanmorin's avatar
   
yanmorin committed
289
ManagerImpl::hangupCall(const CallID& id)
jpbl's avatar
jpbl committed
290
{
Alexandre Savard's avatar
Alexandre Savard committed
291
    _debug("ManagerImpl::hangupCall(): This function is called when user hangup \n");
292
293
294
    PulseLayer *pulselayer;
    AccountID accountid;
    bool returnValue;
Emmanuel Milou's avatar
Emmanuel Milou committed
295

296
    stopTone(true);
yanmorin's avatar
   
yanmorin committed
297

298
299
300
301
302
303
304
305
306
307
    /* 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
308

309
    returnValue = getAccountLink(accountid)->hangup(id);
310

311
312
313
    _debug("After voip link hungup!\n");
    removeCallAccount(id);
    switchCall("");
314

315
316
317
318
319
320
    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
321
322
}

yanmorin's avatar
   
yanmorin committed
323
//THREAD=Main
324
  bool
yanmorin's avatar
   
yanmorin committed
325
ManagerImpl::cancelCall (const CallID& id)
jpbl's avatar
jpbl committed
326
{
327
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
328
329
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
330
    _debug("! Manager Cancel Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
331
    return false;
jpbl's avatar
jpbl committed
332
  }
yanmorin's avatar
   
yanmorin committed
333
334
335
336
337
338

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

yanmorin's avatar
   
yanmorin committed
340
  return returnValue;
jpbl's avatar
jpbl committed
341
342
}

yanmorin's avatar
   
yanmorin committed
343
//THREAD=Main
344
  bool
yanmorin's avatar
   
yanmorin committed
345
ManagerImpl::onHoldCall(const CallID& id)
jpbl's avatar
jpbl committed
346
{
347

348
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
349
350
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
351
    _debug("5 Manager On Hold Call: Account ID %s or callid %s doesn't exists\n", accountid.c_str(), id.c_str());
yanmorin's avatar
   
yanmorin committed
352
    return false;
jpbl's avatar
jpbl committed
353
  }
yanmorin's avatar
   
yanmorin committed
354

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

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

yanmorin's avatar
   
yanmorin committed
359
  removeWaitingCall(id);
360
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HOLD");
yanmorin's avatar
   
yanmorin committed
361
  switchCall("");
362

yanmorin's avatar
   
yanmorin committed
363
364
365
366
  return returnValue;
}

//THREAD=Main
367
  bool
yanmorin's avatar
   
yanmorin committed
368
369
ManagerImpl::offHoldCall(const CallID& id)
{
370
  
371
  stopTone(false);
yanmorin's avatar
   
yanmorin committed
372
373
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
374
    _debug("5 Manager OffHold Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
375
    return false;
jpbl's avatar
jpbl committed
376
  }
377

378
379
380
381
382
  //Place current call on hold if it isn't
  if (hasCurrentCall()) 
  { 
    onHoldCall(getCurrentCallId());
  }
383

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

alexandresavard's avatar
alexandresavard committed
386
387
388
389
390
391
392
393
394
  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
395
  bool returnValue = getAccountLink(accountid)->offhold(id);
alexandresavard's avatar
alexandresavard committed
396
397
398
399
400
401
402

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

405
406
407
408
  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
409
410
411
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
412
//THREAD=Main
413
  bool
yanmorin's avatar
   
yanmorin committed
414
ManagerImpl::transferCall(const CallID& id, const std::string& to)
jpbl's avatar
jpbl committed
415
{
416
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
417
418
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
419
    _debug("! Manager Transfer Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
420
    return false;
jpbl's avatar
jpbl committed
421
  }
yanmorin's avatar
   
yanmorin committed
422
423
424
  bool returnValue = getAccountLink(accountid)->transfer(id, to);
  removeWaitingCall(id);
  removeCallAccount(id);
425
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
yanmorin's avatar
   
yanmorin committed
426
427
  switchCall("");
  return returnValue;
jpbl's avatar
jpbl committed
428
429
}

yanmorin's avatar
   
yanmorin committed
430
//THREAD=Main : Call:Incoming
431
  bool
yanmorin's avatar
   
yanmorin committed
432
ManagerImpl::refuseCall (const CallID& id)
jpbl's avatar
jpbl committed
433
{
434
  _debug("ManagerImpl::refuseCall(): method called");
435
  stopTone(true);
yanmorin's avatar
   
yanmorin committed
436
437
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
438
    _debug("! Manager OffHold Call: Call doesn't exists\n");
yanmorin's avatar
   
yanmorin committed
439
440
441
    return false;
  }
  bool returnValue = getAccountLink(accountid)->refuse(id);
yanmorin's avatar
   
yanmorin committed
442
443
444
445
446
  // if the call was outgoing or established, we didn't refuse it
  // so the method did nothing
  if (returnValue) {
    removeWaitingCall(id);
    removeCallAccount(id);
447
    if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
yanmorin's avatar
   
yanmorin committed
448
449
    switchCall("");
  }
yanmorin's avatar
   
yanmorin committed
450
  return returnValue;
jpbl's avatar
jpbl committed
451
452
}

yanmorin's avatar
   
yanmorin committed
453
//THREAD=Main
454
  bool
jpbl's avatar
jpbl committed
455
456
457
458
459
460
461
462
463
464
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
465
//THREAD=Main
466
 int 
467
ManagerImpl::initRegisterAccounts() 
jpbl's avatar
jpbl committed
468
{
469
    int status; 
470
    bool flag = true;
471
472
473
474
475
    AccountMap::iterator iter;

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

476
    /* Loop on the account map previously loaded */
477
    while( iter != _accountMap.end() ) {
478
479
480
481
482
483
484
485
486
        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;
                }
            }
487
        }
488
        iter++;
Emmanuel Milou's avatar
Emmanuel Milou committed
489
    }
490

491
492
493
494
    // calls the client notification here in case of errors at startup...
    if( _audiodriver -> getErrorMessage() != -1 )
      notifyErrClient( _audiodriver -> getErrorMessage() );
    
495
    ASSERT( flag, true );
496
    return SUCCESS;
jpbl's avatar
jpbl committed
497
498
}

yanmorin's avatar
   
yanmorin committed
499
//THREAD=Main
500
  bool 
yanmorin's avatar
   
yanmorin committed
501
ManagerImpl::sendDtmf(const CallID& id, char code)
jpbl's avatar
jpbl committed
502
{
yanmorin's avatar
   
yanmorin committed
503
504
  AccountID accountid = getAccountFromCall( id );
  if (accountid == AccountNULL) {
Emmanuel Milou's avatar
Emmanuel Milou committed
505
506
    //_debug("Send DTMF: call doesn't exists\n");
    playDtmf(code, false);
yanmorin's avatar
   
yanmorin committed
507
508
509
    return false;
  }

jpbl's avatar
jpbl committed
510
  int sendType = getConfigInt(SIGNALISATION, SEND_DTMF_AS);
yanmorin's avatar
   
yanmorin committed
511
  bool returnValue = false;
jpbl's avatar
jpbl committed
512
  switch (sendType) {
513
    case 0: // SIP INFO
Emmanuel Milou's avatar
Emmanuel Milou committed
514
      playDtmf(code , true);
515
516
517
518
519
520
521
522
523
      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
524
525
526
527
  }
  return returnValue;
}

yanmorin's avatar
   
yanmorin committed
528
//THREAD=Main | VoIPLink
529
  bool
Emmanuel Milou's avatar
Emmanuel Milou committed
530
ManagerImpl::playDtmf(char code, bool isTalking)
jpbl's avatar
jpbl committed
531
{
532
533
534
535
536
537
538
539
540
541
    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
542

543
544
545
546
    // length in milliseconds
    pulselen = getConfigInt(SIGNALISATION, PULSE_LENGTH);
    if (!pulselen)
        return false;
jpbl's avatar
jpbl committed
547

548
549
550
551
    // 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
552

553
554
555
    // fast return, no sound, so no dtmf
    if (audiolayer==0 || _dtmfKey == 0)
        return false;
556

557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
    // 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)
575
        audiolayer->startStream();
576
577
578
        audiolayer->putUrgent (buf, size * sizeof(SFLDataFormat));
    }
    ret = true;
579

580
    // TODO Cache the DTMF
Emmanuel Milou's avatar
Emmanuel Milou committed
581

582
583
584
    delete[] buf; buf = 0;
    
    return ret;
jpbl's avatar
jpbl committed
585
586
}

yanmorin's avatar
   
yanmorin committed
587
// Multi-thread 
jpbl's avatar
jpbl committed
588
589
590
591
592
593
bool
ManagerImpl::incomingCallWaiting() {
  return (_nbIncomingWaitingCall > 0) ? true : false;
}

void
yanmorin's avatar
   
yanmorin committed
594
ManagerImpl::addWaitingCall(const CallID& id) {
595
  ost::MutexLock m(_waitingCallMutex);
yanmorin's avatar
   
yanmorin committed
596
  _waitingCall.insert(id);
jpbl's avatar
jpbl committed
597
598
599
600
  _nbIncomingWaitingCall++;
}

void
yanmorin's avatar
   
yanmorin committed
601
ManagerImpl::removeWaitingCall(const CallID& id) {
602
  ost::MutexLock m(_waitingCallMutex);
yanmorin's avatar
   
yanmorin committed
603
604
605
  // should return more than 1 if it erase a call
  if (_waitingCall.erase(id)) {
    _nbIncomingWaitingCall--;
jpbl's avatar
jpbl committed
606
607
608
609
  }
}

bool
yanmorin's avatar
   
yanmorin committed
610
611
612
613
ManagerImpl::isWaitingCall(const CallID& id) {
  CallIDSet::iterator iter = _waitingCall.find(id);
  if (iter != _waitingCall.end()) {
    return false;
jpbl's avatar
jpbl committed
614
  }
yanmorin's avatar
   
yanmorin committed
615
  return true;
jpbl's avatar
jpbl committed
616
617
}

yanmorin's avatar
   
yanmorin committed
618
619
620
621
///////////////////////////////////////////////////////////////////////////////
// Management of event peer IP-phone 
////////////////////////////////////////////////////////////////////////////////
// SipEvent Thread 
Alexandre Savard's avatar
Alexandre Savard committed
622
bool 
yanmorin's avatar
   
yanmorin committed
623
ManagerImpl::incomingCall(Call* call, const AccountID& accountId) 
jpbl's avatar
jpbl committed
624
{
625
626
    PulseLayer *pulselayer;
    std::string from, number;
627

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

630
    associateCallToAccount(call->getCallId(), accountId);
jpbl's avatar
jpbl committed
631

632
633
    _debug("ManagerImpl::incomingCall :: hasCurrentCall() %i \n",hasCurrentCall());

634
635
636
637
    if ( !hasCurrentCall() ) {
        call->setConnectionState(Call::Ringing);
        ringtone();
        switchCall(call->getCallId());
638
639
640
641
    
    }
    /* 
    else {
642
643
        addWaitingCall(call->getCallId());
    }
644
645
646
    */

    addWaitingCall(call->getCallId());
647
648
649
650
651
652
653
654
655
656
657
658
659

    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(">");
    }
660
661
662
663
664
665
666
667
668

    /*
    CallIDSet::iterator iter = _waitingCall.begin();
    while (iter != _waitingCall.end()) {
        CallID ident = *iter;
        _debug("ManagerImpl::incomingCall :: CALL iteration: %s \n",ident.c_str());
        ++iter;
    }
    */
669
  
670
671
    /* Broadcast a signal over DBus */
    _dbus->getCallManager()->incomingCall(accountId, call->getCallId(), from);
672
  
673
674
675
676
677
    // 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();
    }
678
  
679
    return true;
jpbl's avatar
jpbl committed
680
681
}

yanmorin's avatar
   
yanmorin committed
682
683
684
//THREAD=VoIP
void
ManagerImpl::incomingMessage(const AccountID& accountId, const std::string& message) {
685
686
  if (_dbus) {
    _dbus->getCallManager()->incomingMessage(accountId, message);
jpbl's avatar
jpbl committed
687
688
689
  }
}

yanmorin's avatar
   
yanmorin committed
690
//THREAD=VoIP CALL=Outgoing
691
  void
yanmorin's avatar
   
yanmorin committed
692
ManagerImpl::peerAnsweredCall(const CallID& id)
jpbl's avatar
jpbl committed
693
{
yanmorin's avatar
   
yanmorin committed
694
  if (isCurrentCall(id)) {
695
    stopTone(false);
jpbl's avatar
jpbl committed
696
  }
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
697
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT");
Alexandre Savard's avatar
Alexandre Savard committed
698
699
700
701
  
  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
702
703
}

yanmorin's avatar
   
yanmorin committed
704
//THREAD=VoIP Call=Outgoing
705
  void
yanmorin's avatar
   
yanmorin committed
706
ManagerImpl::peerRingingCall(const CallID& id)
jpbl's avatar
jpbl committed
707
{
yanmorin's avatar
   
yanmorin committed
708
  if (isCurrentCall(id)) {
jpbl's avatar
jpbl committed
709
710
    ringback();
  }
Pierre-Luc Beaudoin's avatar
Pierre-Luc Beaudoin committed
711
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "RINGING");
jpbl's avatar
jpbl committed
712
713
}

yanmorin's avatar
   
yanmorin committed
714
//THREAD=VoIP Call=Outgoing/Ingoing
715
  void
yanmorin's avatar
   
yanmorin committed
716
ManagerImpl::peerHungupCall(const CallID& id)
jpbl's avatar
jpbl committed
717
{
718
    _debug("ManagerImpl::peerHungupCall():this function is called when peer hangup \n");
719
720
    PulseLayer *pulselayer;
    AccountID accountid;
721
    bool returnValue;
722
723
724
725
726
727

    accountid = getAccountFromCall( id );
    if (accountid == AccountNULL) {
        _debug("peerHungupCall: Call doesn't exists\n");
        return;
    }
Emmanuel Milou's avatar
Emmanuel Milou committed
728
  
729
730
731
732
733
734
735
736
    /* Broadcast a signal over DBus */
    if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP");
    
    if (isCurrentCall(id)) {
        stopTone(true);
        switchCall("");
    }

737
    returnValue = getAccountLink(accountid)->peerHungup(id);
738

739
740
    removeWaitingCall(id);
    removeCallAccount(id);
Emmanuel Milou's avatar
Emmanuel Milou committed
741
  
742
743
744
745
    if( _audiodriver->getLayerType() == PULSEAUDIO && getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ) ) {
        pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver());
        if(pulselayer)  pulselayer->restorePulseAppsVolume();
    }
jpbl's avatar
jpbl committed
746
747
}

yanmorin's avatar
   
yanmorin committed
748
//THREAD=VoIP
jpbl's avatar
jpbl committed
749
void
yanmorin's avatar
   
yanmorin committed
750
751
ManagerImpl::callBusy(const CallID& id) {
  _debug("Call busy\n");
752

753
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "BUSY");
yanmorin's avatar
   
yanmorin committed
754
755
756
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
jpbl's avatar
jpbl committed
757
  }
yanmorin's avatar
   
yanmorin committed
758
759
  removeCallAccount(id);
  removeWaitingCall(id);
jpbl's avatar
jpbl committed
760
761
}

yanmorin's avatar
   
yanmorin committed
762
//THREAD=VoIP
763
  void
yanmorin's avatar
   
yanmorin committed
764
765
ManagerImpl::callFailure(const CallID& id) 
{
766
  if (_dbus) _dbus->getCallManager()->callStateChanged(id, "FAILURE");
Emmanuel Milou's avatar
Emmanuel Milou committed
767
  _debug("CALL ID = %s\n" , id.c_str());
yanmorin's avatar
   
yanmorin committed
768
769
770
771
772
773
  if (isCurrentCall(id) ) {
    playATone(Tone::TONE_BUSY);
    switchCall("");
  }
  removeCallAccount(id);
  removeWaitingCall(id);
774

jpbl's avatar
jpbl committed
775
776
}

yanmorin's avatar
   
yanmorin committed
777
//THREAD=VoIP
778
  void
Emmanuel Milou's avatar
Emmanuel Milou committed
779
ManagerImpl::startVoiceMessageNotification(const AccountID& accountId, int nb_msg)
jpbl's avatar
jpbl committed
780
{
Emmanuel Milou's avatar
Emmanuel Milou committed
781
  if (_dbus) _dbus->getCallManager()->voiceMailNotify(accountId, nb_msg) ;
jpbl's avatar
jpbl committed
782
783
}

784
void ManagerImpl::connectionStatusNotification(  )
785
{
786
787
788
789
    if (_dbus)
        _dbus->getConfigurationManager()->accountsChanged();
    else
        _debug("Error: DBus connection not found\n");
Emmanuel Milou's avatar
nothing    
Emmanuel Milou committed
790
791
}

jpbl's avatar
jpbl committed
792
793
794
/**
 * Multi Thread
 */
795
796
797
798
799
800
bool ManagerImpl::playATone(Tone::TONEID toneId) 
{
    int hasToPlayTone;
    AudioLoop *audioloop;
    AudioLayer *audiolayer;
    unsigned int nbSamples;
yanmorin's avatar
   
yanmorin committed
801

802
803
804
805
806
    hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
    if (!hasToPlayTone) 
        return false;
    
    audiolayer = getAudioDriver();
807
   
808
809
810
811
812
813
814
815
816
817
818
819
820
    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
821
  }
822
  return true;
jpbl's avatar
jpbl committed
823
824
825
826
827
}

/**
 * Multi Thread
 */
828
829
830
831
void ManagerImpl::stopTone (bool stopAudio=true)
{
    int hasToPlayTone;
    AudioLayer *audiolayer;
yanmorin's avatar
   
yanmorin committed
832

833
834
835
    hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES);
    if (!hasToPlayTone) 
        return;
836

837
838
839
840
    if (stopAudio) {
        audiolayer = getAudioDriver();
        if (audiolayer) audiolayer->stopStream();
    }
jpbl's avatar
jpbl committed
841

842
843
844
845
846
    _toneMutex.enterMutex();
    if (_telephoneTone != 0) {
        _telephoneTone->setCurrentTone(Tone::TONE_NULL);
    }
    _toneMutex.leaveMutex();
jpbl's avatar
jpbl committed
847

848
849
850
851
    // for ringing tone..
    _toneMutex.enterMutex();
    _audiofile.stop();
    _toneMutex.leaveMutex();
jpbl's avatar
jpbl committed
852
853
854
855
856
}

/**
 * Multi Thread
 */
857
  bool
jpbl's avatar
jpbl committed
858
859
ManagerImpl::playTone()
{
860
  playATone(Tone::TONE_DIALTONE);
Yun Liu's avatar
Yun Liu committed
861
  return true;
jpbl's avatar
jpbl committed
862
863
}

864
865
866
867
868
869
870
/**
 * Multi Thread
 */
  bool
ManagerImpl::playToneWithMessage()
{
  playATone(Tone::TONE_CONGESTION);
Yun Liu's avatar
Yun Liu committed
871
  return true;
872
873
}

jpbl's avatar
jpbl committed
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
/**
 * Multi Thread
 */
void
ManagerImpl::congestion () {
  playATone(Tone::TONE_CONGESTION);
}

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

/**
 * Multi Thread
 */
893
  void
jpbl's avatar
jpbl committed
894
895
ManagerImpl::ringtone() 
{
896
897
898
899
900
901
    std::string ringchoice;
    AudioLayer *audiolayer;
    AudioCodec *codecForTone;
    int layer, samplerate;
    bool loadFile;

902
903
904
905
906
    if( isRingtoneEnabled() )
    {
        //TODO Comment this because it makes the daemon crashes since the main thread
        //synchronizes the ringtone thread.
        
907
        ringchoice = getConfigString(AUDIO, RING_CHOICE);
908
909
910
911
912
913
        //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; 
        }

914
915
916
917
918
919
920
        audiolayer = getAudioDriver();
        layer = audiolayer->getLayerType();
        if (audiolayer == 0)
            return;

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

922
        _toneMutex.enterMutex(); 
923
        loadFile = _audiofile.loadFile(ringchoice, codecForTone , samplerate);
924
        _toneMutex.leaveMutex(); 
925

926
        if (loadFile) {
927
            _toneMutex.enterMutex(); 
928
            _audiofile.start();
929
            _toneMutex.leaveMutex(); 
930
            if(CHECK_INTERFACE( layer, ALSA )){
931
                //ringback();
932
933
934
935
936
937
            }
            else{
                audiolayer->startStream();
            }
        } else {
            ringback();
938
        }
939
940
941
942
943
    
    }
    else
    {
        ringback();
Emmanuel Milou's avatar
Emmanuel Milou committed
944
    }
jpbl's avatar
jpbl committed
945
946
}

947
  AudioLoop*
jpbl's avatar
jpbl committed
948
949
950
ManagerImpl::getTelephoneTone()
{
  if(_telephoneTone != 0) {
951
    ost::MutexLock m(_toneMutex);
jpbl's avatar
jpbl committed
952
953
954
955
956
957
958
    return _telephoneTone->getCurrentTone();
  }
  else {
    return 0;
  }
}

959
  AudioLoop*
jpbl's avatar
jpbl committed
960
961
ManagerImpl::getTelephoneFile()
{
962
  ost::MutexLock m(_toneMutex);
jpbl's avatar
jpbl committed
963
964
965
966
967
968
969
  if(_audiofile.isStarted()) {
    return &_audiofile;
  } else {
    return 0;
  }
}

970
971
972
void ManagerImpl::notificationIncomingCall(void) 
{
    AudioLayer *audiolayer;
jpbl's avatar
jpbl committed
973
    std::ostringstream frequency;
974
975
976
977
978
979
980
981
982
983
984
985
986
    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
987
988
989
990
991
}

/**
 * Multi Thread
 */
992
  bool
yanmorin's avatar
   
yanmorin committed
993
ManagerImpl::getStunInfo (StunAddress4& stunSvrAddr, int port) 
jpbl's avatar
jpbl committed
994
995
996
997
{
  StunAddress4 mappedAddr;
  struct in_addr in;
  char* addr;
yanmorin's avatar
   
yanmorin committed
998
999
1000

  //int fd3, fd4;
  // bool ok = stunOpenSocketPair(stunSvrAddr, &mappedAddr, &fd3, &fd4, port);