diff --git a/astylerc b/astylerc index 14177d0fa0ef4086ca0e03957f3f17361d80b493..0170fbdc9431c1f5875bf75231dd88f8c692b06c 100644 --- a/astylerc +++ b/astylerc @@ -5,7 +5,7 @@ # Savoir-faire Linux Inc # http://www.sflphone.org -style=kr # Kernighan & Ritchie style formatting/indenting uses linux bracket +style=k&r # Kernighan & Ritchie style formatting/indenting uses linux bracket indent=spaces=4 # Use spaces instead of tabs for indentation indent-classes # Indent 'class' and 'struct' blocks so that the blocks 'public:', 'protected:' and 'private:' are indented indent-switches # Indent 'switch' blocks so that the 'case X:' statements are indented in the switch block diff --git a/sflphone-common/src/account.cpp b/sflphone-common/src/account.cpp index 66f78f4786547b35207a70e04b7861a4e61c8835..6b369c10d5ce6e7320af4ba56ee81ac4ff649423 100644 --- a/sflphone-common/src/account.cpp +++ b/sflphone-common/src/account.cpp @@ -34,81 +34,87 @@ #include "manager.h" Account::Account (const AccountID& accountID, std::string type) : - _accountID (accountID) - , _link (NULL) - , _enabled (true) - , _type (type) - , _codecOrder () - , _codecStr("") - , _ringtonePath("/usr/share/sflphone/ringtones/konga.ul") - , _ringtoneEnabled(true) - , _displayName("") - , _useragent("SFLphone") + _accountID (accountID) + , _link (NULL) + , _enabled (true) + , _type (type) + , _codecOrder () + , _codecStr ("") + , _ringtonePath ("/usr/share/sflphone/ringtones/konga.ul") + , _ringtoneEnabled (true) + , _displayName ("") + , _useragent ("SFLphone") { - setRegistrationState (Unregistered); + setRegistrationState (Unregistered); } Account::~Account() { } -void Account::loadConfig() { +void Account::loadConfig() +{ - // If IAX is not supported, do not register this account + // If IAX is not supported, do not register this account #ifndef USE_IAX - if (_type == "IAX") - _enabled = false; + + if (_type == "IAX") + _enabled = false; + #endif - loadAudioCodecs (); + loadAudioCodecs (); } -void Account::setRegistrationState (RegistrationState state) { +void Account::setRegistrationState (RegistrationState state) +{ - if (state != _registrationState) { - _debug ("Account: set registration state"); - _registrationState = state; + if (state != _registrationState) { + _debug ("Account: set registration state"); + _registrationState = state; - // Notify the client - Manager::instance().connectionStatusNotification(); - } + // Notify the client + Manager::instance().connectionStatusNotification(); + } } -void Account::loadAudioCodecs (void) { - - // if the user never set the codec list, use the default configuration for this account - if(_codecStr == "") { - _info ("Account: use the default order"); - Manager::instance ().getCodecDescriptorMap ().setDefaultOrder(); - } - // else retrieve the one set in the user config file - else { - std::vector<std::string> active_list = Manager::instance ().retrieveActiveCodecs(); - // This property is now set per account basis - // std::string s = Manager::instance ().getConfigString (_accountID, "ActiveCodecs"); - setActiveCodecs (Manager::instance ().unserialize (_codecStr)); - } +void Account::loadAudioCodecs (void) +{ + + // if the user never set the codec list, use the default configuration for this account + if (_codecStr == "") { + _info ("Account: use the default order"); + Manager::instance ().getCodecDescriptorMap ().setDefaultOrder(); + } + // else retrieve the one set in the user config file + else { + std::vector<std::string> active_list = Manager::instance ().retrieveActiveCodecs(); + // This property is now set per account basis + // std::string s = Manager::instance ().getConfigString (_accountID, "ActiveCodecs"); + setActiveCodecs (Manager::instance ().unserialize (_codecStr)); + } } -void Account::setActiveCodecs (const std::vector <std::string> &list) { - - _codecOrder.clear(); - // list contains the ordered payload of active codecs picked by the user for this account - // we used the CodecOrder vector to save the order. - int i=0; - int payload; - size_t size = list.size(); - - while ( (unsigned int) i < size) { - payload = std::atoi (list[i].data()); - _info ("Account: Adding codec with RTP payload=%i", payload); - //if (Manager::instance ().getCodecDescriptorMap ().isCodecLoaded (payload)) { - _codecOrder.push_back ( (AudioCodecType) payload); - //} - i++; - } - - // setConfig - _codecStr = Manager::instance ().serialize (list); +void Account::setActiveCodecs (const std::vector <std::string> &list) +{ + + _codecOrder.clear(); + // list contains the ordered payload of active codecs picked by the user for this account + // we used the CodecOrder vector to save the order. + int i=0; + int payload; + size_t size = list.size(); + + while ( (unsigned int) i < size) { + payload = std::atoi (list[i].data()); + _info ("Account: Adding codec with RTP payload=%i", payload); + //if (Manager::instance ().getCodecDescriptorMap ().isCodecLoaded (payload)) { + _codecOrder.push_back ( (AudioCodecType) payload); + //} + i++; + } + + // setConfig + _codecStr = Manager::instance ().serialize (list); } diff --git a/sflphone-common/src/accountcreator.cpp b/sflphone-common/src/accountcreator.cpp index 8bf74f3cb3e51bf70624834bd95fe7a43af36b14..92bfa59376d1a3c8c8e8479ef4007802342a6f5c 100644 --- a/sflphone-common/src/accountcreator.cpp +++ b/sflphone-common/src/accountcreator.cpp @@ -50,26 +50,26 @@ AccountCreator::createAccount (AccountType type, AccountID accountID) { switch (type) { - case SIP_ACCOUNT: { - _debug("AccountCreator: create account %s", accountID.c_str()); - return new SIPAccount (accountID); - break; - } - case SIP_DIRECT_IP_ACCOUNT: { - _debug("AccountCreator: create account IP2IP_PROFILE"); - return new SIPAccount (IP2IP_PROFILE); - break; - } + case SIP_ACCOUNT: { + _debug ("AccountCreator: create account %s", accountID.c_str()); + return new SIPAccount (accountID); + break; + } + case SIP_DIRECT_IP_ACCOUNT: { + _debug ("AccountCreator: create account IP2IP_PROFILE"); + return new SIPAccount (IP2IP_PROFILE); + break; + } #ifdef USE_IAX - case IAX_ACCOUNT: { - _debug("AccountCreator: create account %s", accountID.c_str()); - return new IAXAccount (accountID); - break; - } + case IAX_ACCOUNT: { + _debug ("AccountCreator: create account %s", accountID.c_str()); + return new IAXAccount (accountID); + break; + } #endif - default: - _error("AccountCreator: Error: unknown account type"); + default: + _error ("AccountCreator: Error: unknown account type"); } return 0; diff --git a/sflphone-common/src/audio/alsa/alsalayer.cpp b/sflphone-common/src/audio/alsa/alsalayer.cpp index 1914560d0e04df03be8d9d9917b5ee163944b273..1518ecd835fda1fb666ec945034ff12a7e5de4c9 100644 --- a/sflphone-common/src/audio/alsa/alsalayer.cpp +++ b/sflphone-common/src/audio/alsa/alsalayer.cpp @@ -39,7 +39,7 @@ int framesPerBufferAlsa = 2048; AlsaLayer::AlsaLayer (ManagerImpl* manager) : AudioLayer (manager , ALSA) , _PlaybackHandle (NULL) - , _RingtoneHandle (NULL) + , _RingtoneHandle (NULL) , _CaptureHandle (NULL) , _periodSize() , _audioPlugin() @@ -59,7 +59,7 @@ AlsaLayer::AlsaLayer (ManagerImpl* manager) // _audioThread = new AudioThread (this); // _audioThread = NULL; _urgentRingBuffer.createReadPointer(); - + AudioLayer::_echocancelstate = true; AudioLayer::_noisesuppressstate = true; } @@ -111,9 +111,9 @@ AlsaLayer::openDevice (int indexIn, int indexOut, int indexRing, int sampleRate, if (stream == SFL_PCM_BOTH && is_capture_open() == true && is_playback_open() == true) { closeCaptureStream(); closePlaybackStream(); - } else if((stream == SFL_PCM_CAPTURE || stream == SFL_PCM_BOTH) && is_capture_open() == true) + } else if ( (stream == SFL_PCM_CAPTURE || stream == SFL_PCM_BOTH) && is_capture_open() == true) closeCaptureStream (); - else if((stream == SFL_PCM_PLAYBACK || stream == SFL_PCM_BOTH) && is_playback_open () == true) + else if ( (stream == SFL_PCM_PLAYBACK || stream == SFL_PCM_BOTH) && is_playback_open () == true) closePlaybackStream (); _indexIn = indexIn; @@ -136,16 +136,16 @@ AlsaLayer::openDevice (int indexIn, int indexOut, int indexRing, int sampleRate, _converter = new SamplerateConverter (_audioSampleRate, 1000); AudioLayer::_echoCancel = new EchoCancel(); - AudioLayer::_echoCanceller = new AudioProcessing(static_cast<Algorithm *>(_echoCancel)); + AudioLayer::_echoCanceller = new AudioProcessing (static_cast<Algorithm *> (_echoCancel)); - AudioLayer::_echoCancel->setEchoCancelState(AudioLayer::_echocancelstate); - AudioLayer::_echoCancel->setNoiseSuppressState(AudioLayer::_noisesuppressstate); + AudioLayer::_echoCancel->setEchoCancelState (AudioLayer::_echocancelstate); + AudioLayer::_echoCancel->setNoiseSuppressState (AudioLayer::_noisesuppressstate); AudioLayer::_dcblocker = new DcBlocker(); - AudioLayer::_audiofilter = new AudioProcessing(static_cast<Algorithm *>(_dcblocker)); + AudioLayer::_audiofilter = new AudioProcessing (static_cast<Algorithm *> (_dcblocker)); - return true; + return true; } void @@ -153,33 +153,32 @@ AlsaLayer::startStream (void) { _debug ("Audio: Start stream"); - if(_audiofilter) - _audiofilter->resetAlgorithm(); + if (_audiofilter) + _audiofilter->resetAlgorithm(); - if(_echoCanceller) - _echoCanceller->resetAlgorithm(); + if (_echoCanceller) + _echoCanceller->resetAlgorithm(); - if(is_playback_running() && is_capture_running() ) + if (is_playback_running() && is_capture_running()) return; std::string pcmp; std::string pcmr; std::string pcmc; - if(_audioPlugin == PCM_DMIX_DSNOOP) { - pcmp = buildDeviceTopo (PCM_DMIX, _indexOut, 0); - pcmr = buildDeviceTopo (PCM_DMIX, _indexRing, 0); - pcmc = buildDeviceTopo(PCM_DSNOOP, _indexIn, 0); - } - else { - pcmp = buildDeviceTopo (_audioPlugin, _indexOut, 0); - pcmr = buildDeviceTopo (_audioPlugin, _indexRing, 0); - pcmc = buildDeviceTopo(_audioPlugin, _indexIn, 0); + if (_audioPlugin == PCM_DMIX_DSNOOP) { + pcmp = buildDeviceTopo (PCM_DMIX, _indexOut, 0); + pcmr = buildDeviceTopo (PCM_DMIX, _indexRing, 0); + pcmc = buildDeviceTopo (PCM_DSNOOP, _indexIn, 0); + } else { + pcmp = buildDeviceTopo (_audioPlugin, _indexOut, 0); + pcmr = buildDeviceTopo (_audioPlugin, _indexRing, 0); + pcmc = buildDeviceTopo (_audioPlugin, _indexIn, 0); } - _debug("pcmp: %s, index %d", pcmp.c_str(), _indexOut); - _debug("pcmr: %s, index %d", pcmr.c_str(), _indexRing); - _debug("pcmc: %s, index %d", pcmc.c_str(), _indexIn); + _debug ("pcmp: %s, index %d", pcmp.c_str(), _indexOut); + _debug ("pcmr: %s, index %d", pcmr.c_str(), _indexRing); + _debug ("pcmc: %s, index %d", pcmc.c_str(), _indexIn); if (!is_playback_open()) { open_device (pcmp, pcmc, pcmr, SFL_PCM_PLAYBACK); @@ -255,22 +254,22 @@ bool AlsaLayer::isCaptureActive (void) } -void AlsaLayer::setEchoCancelState(bool state) +void AlsaLayer::setEchoCancelState (bool state) { - // if a stream already running - if(AudioLayer::_echoCancel) - _echoCancel->setEchoCancelState(state); + // if a stream already running + if (AudioLayer::_echoCancel) + _echoCancel->setEchoCancelState (state); - AudioLayer::_echocancelstate = state; + AudioLayer::_echocancelstate = state; } -void AlsaLayer::setNoiseSuppressState(bool state) +void AlsaLayer::setNoiseSuppressState (bool state) { - // if a stream already opened - if(AudioLayer::_echoCancel) - _echoCancel->setNoiseSuppressState(state); + // if a stream already opened + if (AudioLayer::_echoCancel) + _echoCancel->setNoiseSuppressState (state); - AudioLayer::_noisesuppressstate = state; + AudioLayer::_noisesuppressstate = state; } @@ -343,12 +342,12 @@ void AlsaLayer::stopPlaybackStream (void) { int err; - if(_RingtoneHandle && is_playback_running()) { - _debug("Audio: Stop ALSA ringtone"); + if (_RingtoneHandle && is_playback_running()) { + _debug ("Audio: Stop ALSA ringtone"); - if( (err = snd_pcm_drop(_RingtoneHandle)) < 0) { - _debug("Audio: Error: Stop ALSA ringtone: %s", snd_strerror(err)); - } + if ( (err = snd_pcm_drop (_RingtoneHandle)) < 0) { + _debug ("Audio: Error: Stop ALSA ringtone: %s", snd_strerror (err)); + } } if (_PlaybackHandle && is_playback_running()) { @@ -372,16 +371,16 @@ void AlsaLayer::closePlaybackStream (void) if (is_playback_open()) { - _debug("Audio: Close ALSA playback"); + _debug ("Audio: Close ALSA playback"); - if(_RingtoneHandle) { - if((err = snd_pcm_close(_RingtoneHandle)) < 0) { - _warn("Audio: Error: Closing ALSA ringtone: %s", snd_strerror(err)); - } + if (_RingtoneHandle) { + if ( (err = snd_pcm_close (_RingtoneHandle)) < 0) { + _warn ("Audio: Error: Closing ALSA ringtone: %s", snd_strerror (err)); + } } if ( (err = snd_pcm_close (_PlaybackHandle)) < 0) - _warn("Audio: Error: Closing ALSA playback: %s", snd_strerror (err)); + _warn ("Audio: Error: Closing ALSA playback: %s", snd_strerror (err)); else close_playback (); } @@ -493,9 +492,8 @@ bool AlsaLayer::alsa_set_params (snd_pcm_t *pcm_handle, int type, int rate) if ( (err = snd_pcm_hw_params_set_rate_near (pcm_handle, hwparams, &exact_ivalue, &dir) < 0)) { _debugAlsa ("Audio: Error: Cannot set sample rate (%s)", snd_strerror (err)); return false; - } - else - _debug("Audio: Set audio rate to %d", rate); + } else + _debug ("Audio: Set audio rate to %d", rate); if (dir!= 0) { _debugAlsa ("Audio: Error: (%i) The choosen rate %d Hz is not supported by your hardware.Using %d Hz instead. ",type ,rate, exact_ivalue); @@ -581,8 +579,8 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, _debug ("Audio: Open playback device (and ringtone)"); - if ((err = snd_pcm_open(&_PlaybackHandle, pcm_p.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { - _warn("Audio: Error while opening playback device %s", pcm_p.c_str()); + if ( (err = snd_pcm_open (&_PlaybackHandle, pcm_p.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { + _warn ("Audio: Error while opening playback device %s", pcm_p.c_str()); setErrorMessage (ALSA_PLAYBACK_DEVICE); close_playback (); return false; @@ -595,19 +593,19 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, return false; } - if (getIndexOut() != getIndexRing()) { + if (getIndexOut() != getIndexRing()) { - if((err = snd_pcm_open(&_RingtoneHandle, pcm_r.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { - _warn("Audio: Error: Opening ringtone device %s", pcm_r.c_str()); - // setErrorMessage(ALSA_RINGTONE_DEVICE); - } + if ( (err = snd_pcm_open (&_RingtoneHandle, pcm_r.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { + _warn ("Audio: Error: Opening ringtone device %s", pcm_r.c_str()); + // setErrorMessage(ALSA_RINGTONE_DEVICE); + } - if(!alsa_set_params(_RingtoneHandle, 1, getSampleRate())) { - _warn("Audio: Error: Ringtone failed"); - snd_pcm_close(_RingtoneHandle); - - } - } + if (!alsa_set_params (_RingtoneHandle, 1, getSampleRate())) { + _warn ("Audio: Error: Ringtone failed"); + snd_pcm_close (_RingtoneHandle); + + } + } open_playback (); } @@ -616,8 +614,8 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, _debug ("Audio: Open capture device"); - if ((err = snd_pcm_open(&_CaptureHandle, pcm_c.c_str(), SND_PCM_STREAM_CAPTURE, 0)) < 0){ - _warn("Audio: Error: Opening capture device %s", pcm_c.c_str()); + if ( (err = snd_pcm_open (&_CaptureHandle, pcm_c.c_str(), SND_PCM_STREAM_CAPTURE, 0)) < 0) { + _warn ("Audio: Error: Opening capture device %s", pcm_c.c_str()); setErrorMessage (ALSA_CAPTURE_DEVICE); close_capture (); @@ -625,7 +623,7 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, } if (!alsa_set_params (_CaptureHandle, 0, 8000)) { - _warn("Audio: Error: Capture failed"); + _warn ("Audio: Error: Capture failed"); snd_pcm_close (_CaptureHandle); close_capture (); return false; @@ -636,7 +634,7 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, // prepare_capture (); } - + return true; } @@ -663,7 +661,7 @@ AlsaLayer::write (void* buffer, int length, snd_pcm_t * handle) case -EIO: //_debugAlsa(" XRUN playback ignored (%s)", snd_strerror(err)); - handle_xrun_playback(handle); + handle_xrun_playback (handle); if (snd_pcm_writei (handle, buffer , frames) <0) _debugAlsa ("Audio: XRUN handling failed"); @@ -759,13 +757,13 @@ AlsaLayer::handle_xrun_playback (snd_pcm_t *handle) snd_pcm_status_t* status; snd_pcm_status_alloca (&status); - if ( (state = snd_pcm_status (handle, status)) < 0) - _debugAlsa ("Audio: Error: Cannot get playback handle status (%s)" , snd_strerror (state)); + if ( (state = snd_pcm_status (handle, status)) < 0) + _debugAlsa ("Audio: Error: Cannot get playback handle status (%s)" , snd_strerror (state)); else { state = snd_pcm_status_get_state (status); if (state == SND_PCM_STATE_XRUN) { - _debug("Audio: audio device in state SND_PCM_STATE_XRUN, restart device"); + _debug ("Audio: audio device in state SND_PCM_STATE_XRUN, restart device"); stopPlaybackStream (); preparePlaybackStream (); @@ -796,7 +794,7 @@ AlsaLayer::buildDeviceTopo (std::string plugin, int card, int subdevice) pcm.append (ss1.str()); } - _debug("Audio: Device topo: %s", pcm.c_str()); + _debug ("Audio: Device topo: %s", pcm.c_str()); return pcm; } @@ -807,7 +805,7 @@ AlsaLayer::getSoundCardsInfo (int stream) std::vector<std::string> cards_id; HwIDPair p; - _debug("Audio: Get sound cards info: "); + _debug ("Audio: Get sound cards info: "); snd_ctl_t* handle; snd_ctl_card_info_t *info; @@ -899,7 +897,7 @@ AlsaLayer::soundCardGetIndex (std::string description) return 0; } -void AlsaLayer::audioCallback(void) +void AlsaLayer::audioCallback (void) { int toGet, urgentAvailBytes, normalAvailBytes; @@ -920,13 +918,13 @@ void AlsaLayer::audioCallback(void) // framePerBuffer are the number of data for one channel (left) urgentAvailBytes = _urgentRingBuffer.AvailForGet(); - if(!_PlaybackHandle || !_CaptureHandle) - return; + if (!_PlaybackHandle || !_CaptureHandle) + return; - snd_pcm_wait(_PlaybackHandle, 20); + snd_pcm_wait (_PlaybackHandle, 20); - int playbackAvailSmpl = snd_pcm_avail_update(_PlaybackHandle); - int playbackAvailBytes = playbackAvailSmpl*sizeof(SFLDataFormat); + int playbackAvailSmpl = snd_pcm_avail_update (_PlaybackHandle); + int playbackAvailBytes = playbackAvailSmpl*sizeof (SFLDataFormat); // _debug("PLAYBACK: %d", playbackAvailSmpl); if (urgentAvailBytes > 0) { @@ -957,18 +955,17 @@ void AlsaLayer::audioCallback(void) free (out); out = 0; - - } - else if (file_tone && !_RingtoneHandle && (normalAvailBytes <= 0)) { - out = (SFLDataFormat *) malloc (playbackAvailBytes); - file_tone->getNext (out, playbackAvailSmpl, spkrVolume); - write (out, playbackAvailBytes, _PlaybackHandle); + } else if (file_tone && !_RingtoneHandle && (normalAvailBytes <= 0)) { - free (out); - out = NULL; + out = (SFLDataFormat *) malloc (playbackAvailBytes); + file_tone->getNext (out, playbackAvailSmpl, spkrVolume); + write (out, playbackAvailBytes, _PlaybackHandle); + + free (out); + out = NULL; - } else { + } else { // If nothing urgent, play the regular sound samples @@ -983,9 +980,9 @@ void AlsaLayer::audioCallback(void) double upsampleFactor = (double) _audioSampleRate / _mainBufferSampleRate; maxNbSamplesToGet = (int) ( (double) playbackAvailSmpl / upsampleFactor); - maxNbBytesToGet = maxNbSamplesToGet * sizeof (SFLDataFormat); + maxNbBytesToGet = maxNbSamplesToGet * sizeof (SFLDataFormat); - } + } toGet = (normalAvailBytes < (int) maxNbBytesToGet) ? normalAvailBytes : maxNbBytesToGet; @@ -995,9 +992,9 @@ void AlsaLayer::audioCallback(void) getMainBuffer()->getData (out, toGet, spkrVolume); - // TODO: Audio processing should be performed inside mainbuffer - // to avoid such problem - AudioLayer::_echoCancel->setSamplingRate(_mainBufferSampleRate); + // TODO: Audio processing should be performed inside mainbuffer + // to avoid such problem + AudioLayer::_echoCancel->setSamplingRate (_mainBufferSampleRate); if (_mainBufferSampleRate && ( (int) _audioSampleRate != _mainBufferSampleRate)) { @@ -1018,18 +1015,18 @@ void AlsaLayer::audioCallback(void) } else { - write (out, toGet, _PlaybackHandle); + write (out, toGet, _PlaybackHandle); } - // Copy far-end signal in echo canceller to adapt filter coefficient - AudioLayer::_echoCanceller->putData(out, toGet); + // Copy far-end signal in echo canceller to adapt filter coefficient + AudioLayer::_echoCanceller->putData (out, toGet); } else { - if (!tone && !file_tone) { + if (!tone && !file_tone) { - SFLDataFormat *zeros = (SFLDataFormat*)malloc(playbackAvailBytes); + SFLDataFormat *zeros = (SFLDataFormat*) malloc (playbackAvailBytes); bzero (zeros, playbackAvailBytes); write (zeros, playbackAvailBytes, _PlaybackHandle); @@ -1049,29 +1046,29 @@ void AlsaLayer::audioCallback(void) if (file_tone && _RingtoneHandle) { - int ringtoneAvailSmpl = snd_pcm_avail_update(_RingtoneHandle); - int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof(SFLDataFormat); + int ringtoneAvailSmpl = snd_pcm_avail_update (_RingtoneHandle); + int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof (SFLDataFormat); - // _debug("RINGTONE: %d", ringtoneAvailSmpl); + // _debug("RINGTONE: %d", ringtoneAvailSmpl); - out = (SFLDataFormat *) malloc(ringtoneAvailBytes); - file_tone->getNext (out, ringtoneAvailSmpl, spkrVolume); - write (out, ringtoneAvailBytes, _RingtoneHandle); + out = (SFLDataFormat *) malloc (ringtoneAvailBytes); + file_tone->getNext (out, ringtoneAvailSmpl, spkrVolume); + write (out, ringtoneAvailBytes, _RingtoneHandle); - free (out); - out = NULL; + free (out); + out = NULL; } else if (_RingtoneHandle) { - int ringtoneAvailSmpl = snd_pcm_avail_update(_RingtoneHandle); - int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof(SFLDataFormat); + int ringtoneAvailSmpl = snd_pcm_avail_update (_RingtoneHandle); + int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof (SFLDataFormat); - out = (SFLDataFormat *) malloc(ringtoneAvailBytes); - memset(out, 0, ringtoneAvailBytes); - write(out, ringtoneAvailBytes, _RingtoneHandle); + out = (SFLDataFormat *) malloc (ringtoneAvailBytes); + memset (out, 0, ringtoneAvailBytes); + write (out, ringtoneAvailBytes, _RingtoneHandle); - free(out); - out = NULL; + free (out); + out = NULL; } // Additionally handle the mic's audio stream @@ -1081,7 +1078,7 @@ void AlsaLayer::audioCallback(void) SFLDataFormat* in; SFLDataFormat echoCancelledMic[5000]; - memset(echoCancelledMic, 0, 5000); + memset (echoCancelledMic, 0, 5000); // snd_pcm_sframes_t micAvailAlsa; in = 0; @@ -1112,28 +1109,28 @@ void AlsaLayer::audioCallback(void) // _debug("nb_sample_up %i", nb_sample_up); nbSample = _converter->downsampleData ( (SFLDataFormat*) in, rsmpl_out, _mainBufferSampleRate, _audioSampleRate, nb_sample_up); - _audiofilter->processAudio (rsmpl_out, nbSample*sizeof(SFLDataFormat)); + _audiofilter->processAudio (rsmpl_out, nbSample*sizeof (SFLDataFormat)); - // echo cancellation processing - int sampleready = AudioLayer::_echoCanceller->processAudio(rsmpl_out, echoCancelledMic, nbSample*sizeof(SFLDataFormat)); + // echo cancellation processing + int sampleready = AudioLayer::_echoCanceller->processAudio (rsmpl_out, echoCancelledMic, nbSample*sizeof (SFLDataFormat)); // getMainBuffer()->putData (rsmpl_out, nbSample * sizeof (SFLDataFormat), 100); - getMainBuffer()->putData ( echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); + getMainBuffer()->putData (echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); free (rsmpl_out); rsmpl_out = 0; } else { - - SFLDataFormat* filter_out = (SFLDataFormat*) malloc (framesPerBufferAlsa * sizeof (SFLDataFormat)); - _audiofilter->processAudio (in, filter_out, toPut); - - int sampleready = AudioLayer::_echoCanceller->processAudio(filter_out, echoCancelledMic, toPut); + SFLDataFormat* filter_out = (SFLDataFormat*) malloc (framesPerBufferAlsa * sizeof (SFLDataFormat)); - getMainBuffer()->putData (echoCancelledMic, sampleready*sizeof(SFLDataFormat), 100); - free(rsmpl_out); + _audiofilter->processAudio (in, filter_out, toPut); + + int sampleready = AudioLayer::_echoCanceller->processAudio (filter_out, echoCancelledMic, toPut); + + getMainBuffer()->putData (echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); + free (rsmpl_out); } } diff --git a/sflphone-common/src/audio/audioloop.cpp b/sflphone-common/src/audio/audioloop.cpp index 67626daa59f7936922d914efcb4b25fa5f7d9c2f..efa48629d32dd63d5fd2cfac371a6f839e823de7 100644 --- a/sflphone-common/src/audio/audioloop.cpp +++ b/sflphone-common/src/audio/audioloop.cpp @@ -64,7 +64,7 @@ AudioLoop::getNext (SFLDataFormat* output, int nb, short volume) bcopy (_buffer+pos, output, block*sizeof (SFLDataFormat)); // short>char conversion if (volume!=100) { - for (int i=0;i<block;i++) { + for (int i=0; i<block; i++) { *output = (*output * volume) /100; output++; } diff --git a/sflphone-common/src/audio/audioprocessing.cpp b/sflphone-common/src/audio/audioprocessing.cpp index 264bbef498d8ab4b054bf1fa5e134507d30d8f6f..de68b1d146ae529b13a6c038751b0e35e1752023 100644 --- a/sflphone-common/src/audio/audioprocessing.cpp +++ b/sflphone-common/src/audio/audioprocessing.cpp @@ -33,47 +33,48 @@ -AudioProcessing::AudioProcessing(Algorithm *_algo) : _algorithm(_algo) {} +AudioProcessing::AudioProcessing (Algorithm *_algo) : _algorithm (_algo) {} -AudioProcessing::~AudioProcessing(void){} +AudioProcessing::~AudioProcessing (void) {} -void AudioProcessing::resetAlgorithm(void) +void AudioProcessing::resetAlgorithm (void) { - if(_algorithm) - _algorithm->reset(); + if (_algorithm) + _algorithm->reset(); } -int AudioProcessing::getData(SFLDataFormat *outputData) +int AudioProcessing::getData (SFLDataFormat *outputData) { - if(_algorithm) - return _algorithm->getData(outputData); - else - return 0; + if (_algorithm) + return _algorithm->getData (outputData); + else + return 0; } -void AudioProcessing::putData(SFLDataFormat *inputData, int nbBytes) +void AudioProcessing::putData (SFLDataFormat *inputData, int nbBytes) { - if(_algorithm) - _algorithm->putData(inputData, nbBytes); + if (_algorithm) + _algorithm->putData (inputData, nbBytes); } -void AudioProcessing::processAudio(SFLDataFormat *inputData, int nbBytes) +void AudioProcessing::processAudio (SFLDataFormat *inputData, int nbBytes) { - if(_algorithm) - _algorithm->process(inputData, nbBytes); + if (_algorithm) + _algorithm->process (inputData, nbBytes); } -int AudioProcessing::processAudio(SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) +int AudioProcessing::processAudio (SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) { - if(_algorithm) - return _algorithm->process(inputData, outputData, nbBytes); - else - return 0; + if (_algorithm) + return _algorithm->process (inputData, outputData, nbBytes); + else + return 0; } -void AudioProcessing::processAudio(SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) { - if(_algorithm) - _algorithm->process(micData, spkrData, outputData, nbBytes); +void AudioProcessing::processAudio (SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) +{ + if (_algorithm) + _algorithm->process (micData, spkrData, outputData, nbBytes); } diff --git a/sflphone-common/src/audio/audiorecord.cpp b/sflphone-common/src/audio/audiorecord.cpp index 491996185d70713f17304630842f19358789f995..4abc0093ebc7583e055f07643ba823e0c19096fb 100644 --- a/sflphone-common/src/audio/audiorecord.cpp +++ b/sflphone-common/src/audio/audiorecord.cpp @@ -104,12 +104,12 @@ void AudioRecord::initFileName (std::string peerNumber) if (fileType_ == FILE_RAW) { if (strstr (fileName_, ".raw") == NULL) { - _debug("AudioRecord: concatenate .raw file extension: name : %s", fileName_); + _debug ("AudioRecord: concatenate .raw file extension: name : %s", fileName_); fName.append (".raw"); } } else if (fileType_ == FILE_WAV) { if (strstr (fileName_, ".wav") == NULL) { - _debug("AudioRecord: concatenate .wav file extension: name : %s", fileName_); + _debug ("AudioRecord: concatenate .wav file extension: name : %s", fileName_); fName.append (".wav"); } } @@ -196,18 +196,16 @@ bool AudioRecord::setRecording() { if (isOpenFile()) { - if (!recordingEnabled_) { - _info ("AudioRecording: Start recording"); - recordingEnabled_ = true; - } - else { - recordingEnabled_ = false; - _info ("AudioRecording: Stop recording"); - } - } - else { + if (!recordingEnabled_) { + _info ("AudioRecording: Start recording"); + recordingEnabled_ = true; + } else { + recordingEnabled_ = false; + _info ("AudioRecording: Stop recording"); + } + } else { openFile(); - + recordingEnabled_ = true; // once opend file, start recording } @@ -275,7 +273,7 @@ void AudioRecord::createFilename() // fileName_ = out.str(); strncpy (fileName_, out.str().c_str(), 8192); - _info("AudioRecord: create filename for this call %s ", fileName_); + _info ("AudioRecord: create filename for this call %s ", fileName_); } bool AudioRecord::setRawFile() @@ -305,7 +303,7 @@ bool AudioRecord::setWavFile() fp = fopen (savePath_.c_str(), "wb"); if (!fp) { - _warn("AudioRecord: Error: could not create WAV file."); + _warn ("AudioRecord: Error: could not create WAV file."); return false; } @@ -333,7 +331,7 @@ bool AudioRecord::setWavFile() if (fwrite (&hdr, 4, 11, fp) != 11) { - _warn("AudioRecord: Error: could not write WAV header for file. "); + _warn ("AudioRecord: Error: could not write WAV header for file. "); return false; } @@ -363,7 +361,7 @@ bool AudioRecord::openExistingWavFile() fp = fopen (fileName_, "rb+"); if (!fp) { - _warn("AudioRecord: Error: could not open WAV file!"); + _warn ("AudioRecord: Error: could not open WAV file!"); return false; } @@ -373,7 +371,7 @@ bool AudioRecord::openExistingWavFile() _warn ("AudioRecord: Error: Couldn't seek offset 40 in the file "); if (fread (&byteCounter_, 4, 1, fp)) - _warn("AudioRecord: Error: bytecounter Read successfully "); + _warn ("AudioRecord: Error: bytecounter Read successfully "); if (fseek (fp, 0 , SEEK_END) != 0) _warn ("AudioRecord: Error: Couldn't seek at the en of the file "); @@ -406,29 +404,33 @@ void AudioRecord::closeWavFile() return; } - _debug("AudioRecord: Close wave file"); + _debug ("AudioRecord: Close wave file"); SINT32 bytes = byteCounter_ * channels_; fseek (fp, 40, SEEK_SET); // jump to data length - if (ferror (fp)) + + if (ferror (fp)) _warn ("AudioRecord: Error: can't reach offset 40 while closing"); fwrite (&bytes, sizeof (SINT32), 1, fp); - if (ferror (fp)) + + if (ferror (fp)) _warn ("AudioRecord: Error: can't write bytes for data length "); bytes = byteCounter_ * channels_ + 44; // + 44 for the wave header fseek (fp, 4, SEEK_SET); // jump to file size - if (ferror (fp)) + + if (ferror (fp)) _warn ("AudioRecord: Error: can't reach offset 4"); fwrite (&bytes, 4, 1, fp); - if (ferror (fp)) - _warn("AudioRecord: Error: can't reach offset 4"); + + if (ferror (fp)) + _warn ("AudioRecord: Error: can't reach offset 4"); if (fclose (fp) != 0) @@ -471,7 +473,7 @@ void AudioRecord::recMicData (SFLDataFormat* buffer, int nSamples) void AudioRecord::recData (SFLDataFormat* buffer, int nSamples) { - if (recordingEnabled_) { + if (recordingEnabled_) { if (fp == 0) { _debug ("AudioRecord: Can't record data, a file has not yet been opened!"); @@ -499,7 +501,7 @@ void AudioRecord::recData (SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int if (recordingEnabled_) { - _debug("Recording enabled"); + _debug ("Recording enabled"); if (fp == 0) { _debug ("AudioRecord: Can't record data, a file has not yet been opened!"); diff --git a/sflphone-common/src/audio/audiorecorder.cpp b/sflphone-common/src/audio/audiorecorder.cpp index b12a3016e92b7de9cdf37a3e940059782e7a11ce..d5763aaa3c3b32012c678f29783810a7bd8afd90 100644 --- a/sflphone-common/src/audio/audiorecorder.cpp +++ b/sflphone-common/src/audio/audiorecorder.cpp @@ -39,7 +39,7 @@ AudioRecorder::AudioRecorder (AudioRecord *arec, MainBuffer *mb) : Thread() ++count; - std::string id("processid_"); + std::string id ("processid_"); // convert count into string std::string s; @@ -47,10 +47,10 @@ AudioRecorder::AudioRecorder (AudioRecord *arec, MainBuffer *mb) : Thread() out << count; s = out.str(); - recorderId = id.append(s); + recorderId = id.append (s); arecord = arec; - mbuffer = mb; + mbuffer = mb; } @@ -61,19 +61,19 @@ void AudioRecorder::run (void) { SFLDataFormat buffer[10000]; - while(true) { + while (true) { - if(!mbuffer) - _warn("AudioRecorder: Error: No instance of ringbuffer"); + if (!mbuffer) + _warn ("AudioRecorder: Error: No instance of ringbuffer"); - int availBytes = mbuffer->availForGet(recorderId); + int availBytes = mbuffer->availForGet (recorderId); - if(availBytes > 0) { + if (availBytes > 0) { - arecord->recData(buffer, availBytes/sizeof(SFLDataFormat)); - } + arecord->recData (buffer, availBytes/sizeof (SFLDataFormat)); + } - sleep(20); + sleep (20); } diff --git a/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp b/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp index 85f53cf09e5e31ca623104932c608b8d3e56283b..76884ef124cb5fb627218eabdaf89ea29847d0de 100644 --- a/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp +++ b/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp @@ -64,7 +64,7 @@ AudioRtpFactory::~AudioRtpFactory() stop(); } -void AudioRtpFactory::initAudioRtpConfig(SIPCall *ca) +void AudioRtpFactory::initAudioRtpConfig (SIPCall *ca) { assert (ca); @@ -95,6 +95,7 @@ void AudioRtpFactory::initAudioRtpSession (SIPCall * ca) ost::MutexLock m (_audioRtpThreadMutex); _debug ("Srtp enable: %d ", _srtpEnabled); + if (_srtpEnabled) { std::string zidFilename (Manager::instance().getConfigString (SIGNALISATION, ZRTP_ZIDFILE)); @@ -115,14 +116,14 @@ void AudioRtpFactory::initAudioRtpSession (SIPCall * ca) case Sdes: - _rtpSession = new AudioSrtpSession (&Manager::instance(), ca); + _rtpSession = new AudioSrtpSession (&Manager::instance(), ca); _rtpSessionType = Sdes; - ca->getLocalSDP()->set_srtp_crypto(static_cast<AudioSrtpSession *> (_rtpSession)->getLocalCryptoInfo()); - break; + ca->getLocalSDP()->set_srtp_crypto (static_cast<AudioSrtpSession *> (_rtpSession)->getLocalCryptoInfo()); + break; default: - _debug("Unsupported Rtp Session Exception Type!"); + _debug ("Unsupported Rtp Session Exception Type!"); throw UnsupportedRtpSessionType(); } } else { @@ -141,15 +142,17 @@ void AudioRtpFactory::start (AudioCodec* audiocodec) switch (_rtpSessionType) { case Sdes: - if (static_cast<AudioSrtpSession *> (_rtpSession)->startRtpThread(audiocodec) != 0) { + + if (static_cast<AudioSrtpSession *> (_rtpSession)->startRtpThread (audiocodec) != 0) { throw AudioRtpFactoryException ("RTP: Error: Failed to start AudioSRtpSession thread"); } - break; + + break; case Symmetric: _debug ("Starting symmetric rtp thread"); - if (static_cast<AudioSymmetricRtpSession *> (_rtpSession)->startRtpThread(audiocodec) != 0) { + if (static_cast<AudioSymmetricRtpSession *> (_rtpSession)->startRtpThread (audiocodec) != 0) { throw AudioRtpFactoryException ("RTP: Error: Failed to start AudioSymmetricRtpSession thread"); } @@ -157,9 +160,10 @@ void AudioRtpFactory::start (AudioCodec* audiocodec) case Zrtp: - if (static_cast<AudioZrtpSession *> (_rtpSession)->startRtpThread(audiocodec) != 0) { + if (static_cast<AudioZrtpSession *> (_rtpSession)->startRtpThread (audiocodec) != 0) { throw AudioRtpFactoryException ("RTP: Error: Failed to start AudioZrtpSession thread"); } + break; } } @@ -167,7 +171,7 @@ void AudioRtpFactory::start (AudioCodec* audiocodec) void AudioRtpFactory::stop (void) { ost::MutexLock mutex (_audioRtpThreadMutex); - _info("RTP: Stopping audio rtp session"); + _info ("RTP: Stopping audio rtp session"); if (_rtpSession == NULL) { _debugException ("RTP: Error: _rtpSession is null when trying to stop. Returning."); @@ -178,8 +182,8 @@ void AudioRtpFactory::stop (void) switch (_rtpSessionType) { case Sdes: - delete static_cast<AudioSrtpSession *> (_rtpSession); - break; + delete static_cast<AudioSrtpSession *> (_rtpSession); + break; case Symmetric: delete static_cast<AudioSymmetricRtpSession *> (_rtpSession); @@ -193,13 +197,14 @@ void AudioRtpFactory::stop (void) _rtpSession = NULL; } catch (...) { _debugException ("RTP: Error: Exception caught when stopping the audio rtp session"); - throw AudioRtpFactoryException("RTP: Error: caught exception in AudioRtpFactory::stop"); + throw AudioRtpFactoryException ("RTP: Error: caught exception in AudioRtpFactory::stop"); } } void AudioRtpFactory::updateDestinationIpAddress (void) { _info ("RTP: Updating IP address"); + if (_rtpSession == NULL) { throw AudioRtpFactoryException ("RTP: Error: _rtpSession was null when trying to update IP address"); } @@ -207,26 +212,26 @@ void AudioRtpFactory::updateDestinationIpAddress (void) switch (_rtpSessionType) { case Sdes: - static_cast<AudioSrtpSession *> (_rtpSession)->updateDestinationIpAddress(); - break; + static_cast<AudioSrtpSession *> (_rtpSession)->updateDestinationIpAddress(); + break; case Symmetric: static_cast<AudioSymmetricRtpSession *> (_rtpSession)->updateDestinationIpAddress(); break; case Zrtp: - static_cast<AudioZrtpSession *> (_rtpSession)->updateDestinationIpAddress(); + static_cast<AudioZrtpSession *> (_rtpSession)->updateDestinationIpAddress(); break; } } sfl::AudioSymmetricRtpSession * AudioRtpFactory::getAudioSymetricRtpSession() { - if ( (_rtpSessionType == Symmetric) && (_rtpSessionType != NULL)) { - return static_cast<AudioSymmetricRtpSession *> (_rtpSession); - } else { - throw AudioRtpFactoryException("RTP: Error: _rtpSession is NULL in getAudioSymetricRtpSession"); - } + if ( (_rtpSessionType == Symmetric) && (_rtpSessionType != NULL)) { + return static_cast<AudioSymmetricRtpSession *> (_rtpSession); + } else { + throw AudioRtpFactoryException ("RTP: Error: _rtpSession is NULL in getAudioSymetricRtpSession"); + } } sfl::AudioZrtpSession * AudioRtpFactory::getAudioZrtpSession() @@ -234,35 +239,35 @@ sfl::AudioZrtpSession * AudioRtpFactory::getAudioZrtpSession() if ( (_rtpSessionType == Zrtp) && (_rtpSessionType != NULL)) { return static_cast<AudioZrtpSession *> (_rtpSession); } else { - throw AudioRtpFactoryException("RTP: Error: _rtpSession is NULL in getAudioZrtpSession"); + throw AudioRtpFactoryException ("RTP: Error: _rtpSession is NULL in getAudioZrtpSession"); } } -void AudioRtpFactory::setRemoteCryptoInfo(sfl::SdesNegotiator& nego) +void AudioRtpFactory::setRemoteCryptoInfo (sfl::SdesNegotiator& nego) { - if ( _rtpSession && _rtpSessionType && (_rtpSessionType == Sdes)) { - static_cast<AudioSrtpSession *> (_rtpSession)->setRemoteCryptoInfo(nego); - } - else { - throw AudioRtpFactoryException("RTP: Error: _rtpSession is NULL in setRemoteCryptoInfo"); + if (_rtpSession && _rtpSessionType && (_rtpSessionType == Sdes)) { + static_cast<AudioSrtpSession *> (_rtpSession)->setRemoteCryptoInfo (nego); + } else { + throw AudioRtpFactoryException ("RTP: Error: _rtpSession is NULL in setRemoteCryptoInfo"); } } -void AudioRtpFactory::sendDtmfDigit(int digit) { - switch(_rtpSessionType) { +void AudioRtpFactory::sendDtmfDigit (int digit) +{ + switch (_rtpSessionType) { - case Sdes: - static_cast<AudioSrtpSession *> (_rtpSession)->putDtmfEvent(digit); - break; + case Sdes: + static_cast<AudioSrtpSession *> (_rtpSession)->putDtmfEvent (digit); + break; - case Symmetric: - static_cast<AudioSymmetricRtpSession *> (_rtpSession)->putDtmfEvent(digit); - break; + case Symmetric: + static_cast<AudioSymmetricRtpSession *> (_rtpSession)->putDtmfEvent (digit); + break; - case Zrtp: - static_cast<AudioZrtpSession *> (_rtpSession)->putDtmfEvent(digit); - break; - } + case Zrtp: + static_cast<AudioZrtpSession *> (_rtpSession)->putDtmfEvent (digit); + break; + } } } diff --git a/sflphone-common/src/audio/audiortp/AudioSrtpSession.cpp b/sflphone-common/src/audio/audiortp/AudioSrtpSession.cpp index 0aa05810b1bd8426bfaca39377f7973e1eaeb51b..72960650f4f9eb6d0d4ae485c6a7422380e33fea 100644 --- a/sflphone-common/src/audio/audiortp/AudioSrtpSession.cpp +++ b/sflphone-common/src/audio/audiortp/AudioSrtpSession.cpp @@ -51,12 +51,12 @@ namespace sfl AudioSrtpSession::AudioSrtpSession (ManagerImpl * manager, SIPCall * sipcall) : ost::SymmetricRTPSession (ost::InetHostAddress (sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort()), AudioRtpSession<AudioSrtpSession> (manager, sipcall), - _localCryptoSuite(0), - _remoteCryptoSuite(0), - _localMasterKeyLength(0), - _localMasterSaltLength(0), - _remoteMasterKeyLength(0), - _remoteMasterSaltLength(0) + _localCryptoSuite (0), + _remoteCryptoSuite (0), + _localMasterKeyLength (0), + _localMasterSaltLength (0), + _remoteMasterKeyLength (0), + _remoteMasterSaltLength (0) { @@ -66,19 +66,20 @@ AudioSrtpSession::AudioSrtpSession (ManagerImpl * manager, SIPCall * sipcall) : initializeLocalCryptoContext(); // Set local crypto context in ccrtp - _localCryptoCtx->deriveSrtpKeys(0); + _localCryptoCtx->deriveSrtpKeys (0); - setOutQueueCryptoContext(_localCryptoCtx); + setOutQueueCryptoContext (_localCryptoCtx); } - -std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() { - _debug("Get Cryptographic info from this rtp session"); +std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() +{ + + _debug ("Get Cryptographic info from this rtp session"); std::vector<std::string> crypto_vector; - // @TODO we should return a vector containing supported + // @TODO we should return a vector containing supported // cryptographic context tagged 1, 2, 3... std::string tag = "1"; @@ -92,32 +93,33 @@ std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() { // srtp_keys.append("|2^20|1:32"); // generate crypto attribute - std::string crypto_attr = tag.append(" "); - crypto_attr += crypto_suite.append(" "); + std::string crypto_attr = tag.append (" "); + crypto_attr += crypto_suite.append (" "); crypto_attr += srtp_keys; - _debug("%s", crypto_attr.c_str()); + _debug ("%s", crypto_attr.c_str()); - crypto_vector.push_back(crypto_attr); + crypto_vector.push_back (crypto_attr); return crypto_vector; } -void AudioSrtpSession::setRemoteCryptoInfo(sfl::SdesNegotiator& nego) { +void AudioSrtpSession::setRemoteCryptoInfo (sfl::SdesNegotiator& nego) +{ - _debug("Set remote Cryptographic info for Srtp"); + _debug ("Set remote Cryptographic info for Srtp"); // decode keys - unBase64ConcatenatedKeys(nego.getKeyInfo()); + unBase64ConcatenatedKeys (nego.getKeyInfo()); // init crypto content int Srtp session initializeRemoteCryptoContext(); - setInQueueCryptoContext(_remoteCryptoCtx); + setInQueueCryptoContext (_remoteCryptoCtx); } -void AudioSrtpSession::initializeLocalMasterKey(void) +void AudioSrtpSession::initializeLocalMasterKey (void) { // @TODO key may have different length depending on cipher suite @@ -128,10 +130,11 @@ void AudioSrtpSession::initializeLocalMasterKey(void) // Generate ryptographically strong pseudo-random bytes int err; - if((err = RAND_bytes(random_key, _localMasterKeyLength)) != 1) - _debug("Error occured while generating cryptographically strong pseudo-random key"); - memcpy(_localMasterKey, random_key, _localMasterKeyLength); + if ( (err = RAND_bytes (random_key, _localMasterKeyLength)) != 1) + _debug ("Error occured while generating cryptographically strong pseudo-random key"); + + memcpy (_localMasterKey, random_key, _localMasterKeyLength); /* printf("Local Master: "); @@ -144,21 +147,22 @@ void AudioSrtpSession::initializeLocalMasterKey(void) } -void AudioSrtpSession::initializeLocalMasterSalt(void) +void AudioSrtpSession::initializeLocalMasterSalt (void) { - // @TODO key may have different length depending on cipher suite - _localMasterSaltLength = sfl::CryptoSuites[_localCryptoSuite].masterSaltLength / 8; + // @TODO key may have different length depending on cipher suite + _localMasterSaltLength = sfl::CryptoSuites[_localCryptoSuite].masterSaltLength / 8; // Allocate memory for key unsigned char *random_key = new unsigned char[_localMasterSaltLength]; // Generate ryptographically strong pseudo-random bytes int err; - if((err = RAND_bytes(random_key, _localMasterSaltLength)) != 1) - _debug("Error occured while generating cryptographically strong pseudo-random key"); - memcpy(_localMasterSalt, random_key, _localMasterSaltLength); + if ( (err = RAND_bytes (random_key, _localMasterSaltLength)) != 1) + _debug ("Error occured while generating cryptographically strong pseudo-random key"); + + memcpy (_localMasterSalt, random_key, _localMasterSaltLength); return; @@ -174,22 +178,22 @@ std::string AudioSrtpSession::getBase64ConcatenatedKeys() uint8 concatKeys[concatLength]; // concatenate keys - memcpy((void*)concatKeys, (void*)_localMasterKey, _localMasterKeyLength); - memcpy((void*)(concatKeys + _localMasterKeyLength), (void*)_localMasterSalt, _localMasterSaltLength); + memcpy ( (void*) concatKeys, (void*) _localMasterKey, _localMasterKeyLength); + memcpy ( (void*) (concatKeys + _localMasterKeyLength), (void*) _localMasterSalt, _localMasterSaltLength); // encode concatenated keys in base64 - char *output = encodeBase64((unsigned char*)concatKeys, concatLength); + char *output = encodeBase64 ( (unsigned char*) concatKeys, concatLength); // init string containing encoded data - std::string keys(output); + std::string keys (output); - free(output); + free (output); return keys; } -void AudioSrtpSession::unBase64ConcatenatedKeys(std::string base64keys) +void AudioSrtpSession::unBase64ConcatenatedKeys (std::string base64keys) { _remoteMasterKeyLength = sfl::CryptoSuites[1].masterKeyLength / 8; @@ -199,113 +203,113 @@ void AudioSrtpSession::unBase64ConcatenatedKeys(std::string base64keys) int length; // pointer to binary data - char *dataptr = (char*)base64keys.data(); + char *dataptr = (char*) base64keys.data(); // decode concatenated binary keys - char *output = decodeBase64((unsigned char*)dataptr, strlen(dataptr), &length); + char *output = decodeBase64 ( (unsigned char*) dataptr, strlen (dataptr), &length); // copy master and slt respectively - memcpy((void*)_remoteMasterKey, (void*)output, _remoteMasterKeyLength); - memcpy((void*)_remoteMasterSalt, (void*)(output + _remoteMasterKeyLength), _remoteMasterSaltLength); + memcpy ( (void*) _remoteMasterKey, (void*) output, _remoteMasterKeyLength); + memcpy ( (void*) _remoteMasterSalt, (void*) (output + _remoteMasterKeyLength), _remoteMasterSaltLength); - free(output); + free (output); } -void AudioSrtpSession::initializeRemoteCryptoContext(void) +void AudioSrtpSession::initializeRemoteCryptoContext (void) { CryptoSuiteDefinition crypto = sfl::CryptoSuites[_localCryptoSuite]; - _remoteCryptoCtx = new ost::CryptoContext(0x0, - 0, // roc, - 0L, // keydr, - SrtpEncryptionAESCM, // encryption algo - SrtpAuthenticationSha1Hmac, // authtication algo - _remoteMasterKey, - _remoteMasterKeyLength, - _remoteMasterSalt, - _remoteMasterSaltLength, - crypto.encryptionKeyLength / 8, - crypto.srtpAuthKeyLength / 8, - 112 / 8, // session salt len - crypto.srtpAuthTagLength / 8); - + _remoteCryptoCtx = new ost::CryptoContext (0x0, + 0, // roc, + 0L, // keydr, + SrtpEncryptionAESCM, // encryption algo + SrtpAuthenticationSha1Hmac, // authtication algo + _remoteMasterKey, + _remoteMasterKeyLength, + _remoteMasterSalt, + _remoteMasterSaltLength, + crypto.encryptionKeyLength / 8, + crypto.srtpAuthKeyLength / 8, + 112 / 8, // session salt len + crypto.srtpAuthTagLength / 8); + } -void AudioSrtpSession::initializeLocalCryptoContext(void) +void AudioSrtpSession::initializeLocalCryptoContext (void) { CryptoSuiteDefinition crypto = sfl::CryptoSuites[_localCryptoSuite]; - _localCryptoCtx = new ost::CryptoContext(OutgoingDataQueue::getLocalSSRC(), - 0, // roc, - 0L, // keydr, - SrtpEncryptionAESCM, // encryption algo - SrtpAuthenticationSha1Hmac, // authtication algo - _localMasterKey, - _localMasterKeyLength, - _localMasterSalt, - _localMasterSaltLength, - crypto.encryptionKeyLength / 8, - crypto.srtpAuthKeyLength / 8, - 112 / 8, // session salt len - crypto.srtpAuthTagLength / 8); + _localCryptoCtx = new ost::CryptoContext (OutgoingDataQueue::getLocalSSRC(), + 0, // roc, + 0L, // keydr, + SrtpEncryptionAESCM, // encryption algo + SrtpAuthenticationSha1Hmac, // authtication algo + _localMasterKey, + _localMasterKeyLength, + _localMasterSalt, + _localMasterSaltLength, + crypto.encryptionKeyLength / 8, + crypto.srtpAuthKeyLength / 8, + 112 / 8, // session salt len + crypto.srtpAuthTagLength / 8); } #pragma GCC diagnostic ignored "-Wunused-value" -char* AudioSrtpSession::encodeBase64(unsigned char *input, int length) +char* AudioSrtpSession::encodeBase64 (unsigned char *input, int length) { BIO *b64, *bmem; BUF_MEM *bptr ; - char *buffer = (char *)malloc(2*length); - memset(buffer, 0, 2*length); + char *buffer = (char *) malloc (2*length); + memset (buffer, 0, 2*length); // init decoder - b64 = BIO_new(BIO_f_base64()); - BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); + b64 = BIO_new (BIO_f_base64()); + BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL); // init internal buffer - bmem = BIO_new(BIO_s_mem()); + bmem = BIO_new (BIO_s_mem()); // create decoder chain - b64 = BIO_push(b64, bmem); + b64 = BIO_push (b64, bmem); - BIO_write(b64, input, length); - BIO_flush(b64); + BIO_write (b64, input, length); + BIO_flush (b64); // get pointer to data - BIO_get_mem_ptr(b64, &bptr); + BIO_get_mem_ptr (b64, &bptr); // copy result in output buffer (-1 since we do not want the EOF character) - strncpy(buffer, (char*)(bptr->data), bptr->length); + strncpy (buffer, (char*) (bptr->data), bptr->length); - BIO_free_all(bmem); + BIO_free_all (bmem); - return buffer; + return buffer; } #pragma GCC diagnostic error "-Wunused-value" -char* AudioSrtpSession::decodeBase64(unsigned char *input, int length, int *length_out) +char* AudioSrtpSession::decodeBase64 (unsigned char *input, int length, int *length_out) { BIO *b64, *bmem; - char *buffer = (char *)malloc(length); - memset(buffer, 0, length); + char *buffer = (char *) malloc (length); + memset (buffer, 0, length); // init decoder and read-only BIO buffer - b64 = BIO_new(BIO_f_base64()); - BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); + b64 = BIO_new (BIO_f_base64()); + BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL); // init internal buffer - bmem = BIO_new_mem_buf(input, length); + bmem = BIO_new_mem_buf (input, length); // create encoder chain - bmem = BIO_push(b64, bmem); + bmem = BIO_push (b64, bmem); - *length_out = BIO_read(bmem, buffer, length); + *length_out = BIO_read (bmem, buffer, length); - BIO_free_all(bmem); + BIO_free_all (bmem); return buffer; diff --git a/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp b/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp index b0be6b719eb86162e593d510d69191bb757df665..88bed90421d930d038f84a4944da1f88a2fc6936 100644 --- a/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp +++ b/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp @@ -55,7 +55,7 @@ ZrtpSessionCallback::ZrtpSessionCallback (SIPCall *sipcall) : return; } - _info("Zrtp: Initialize callbacks"); + _info ("Zrtp: Initialize callbacks"); /** * Information Map diff --git a/sflphone-common/src/audio/codecs/celtcodec.cpp b/sflphone-common/src/audio/codecs/celtcodec.cpp index b3e31012bcf6bc1d16aaf1ddc4ef2ad04309c008..f7df26faf66510d110a3ef5ab13175fbe00e088f 100644 --- a/sflphone-common/src/audio/codecs/celtcodec.cpp +++ b/sflphone-common/src/audio/codecs/celtcodec.cpp @@ -58,32 +58,32 @@ class Celt : public AudioCodec _mode = celt_mode_create (_clockRate, _frameSize, &error); - if(error != CELT_OK) { - switch(error) { - case CELT_BAD_ARG: - printf("Celt: Error: An (or more) invalid argument (e.g. out of range)\n"); - break; - case CELT_INVALID_MODE: - printf("Celt: Error: The mode struct passed is invalid\n"); - break; - case CELT_INTERNAL_ERROR: - printf("Celt: Error: An internal error was detected\n"); - break; - case CELT_CORRUPTED_DATA: - printf("Celt: Error: The data passed (e.g. compressed data to decoder) is corrupted\n"); - break; - case CELT_UNIMPLEMENTED: - printf("Celt: Error: Invalid/unsupported request numbe\n"); - break; - case CELT_INVALID_STATE: - printf("Celt: Error: An encoder or decoder structure is invalid or already freed\n"); - break; - case CELT_ALLOC_FAIL: - printf("Celt: Error: Memory allocation has failed\n"); - break; - default: - printf("Celt: Error"); - } + if (error != CELT_OK) { + switch (error) { + case CELT_BAD_ARG: + printf ("Celt: Error: An (or more) invalid argument (e.g. out of range)\n"); + break; + case CELT_INVALID_MODE: + printf ("Celt: Error: The mode struct passed is invalid\n"); + break; + case CELT_INTERNAL_ERROR: + printf ("Celt: Error: An internal error was detected\n"); + break; + case CELT_CORRUPTED_DATA: + printf ("Celt: Error: The data passed (e.g. compressed data to decoder) is corrupted\n"); + break; + case CELT_UNIMPLEMENTED: + printf ("Celt: Error: Invalid/unsupported request numbe\n"); + break; + case CELT_INVALID_STATE: + printf ("Celt: Error: An encoder or decoder structure is invalid or already freed\n"); + break; + case CELT_ALLOC_FAIL: + printf ("Celt: Error: Memory allocation has failed\n"); + break; + default: + printf ("Celt: Error"); + } } @@ -105,10 +105,10 @@ class Celt : public AudioCodec _dec = celt_decoder_create (_mode, _channel, &error); celt_encoder_ctl (_enc, CELT_SET_COMPLEXITY (2)); - celt_decoder_ctl(_dec, CELT_SET_COMPLEXITY (2)); + celt_decoder_ctl (_dec, CELT_SET_COMPLEXITY (2)); - celt_encoder_ctl (_enc, CELT_SET_PREDICTION(2)); - celt_decoder_ctl(_dec, CELT_SET_PREDICTION(2)); + celt_encoder_ctl (_enc, CELT_SET_PREDICTION (2)); + celt_decoder_ctl (_dec, CELT_SET_PREDICTION (2)); } @@ -121,7 +121,7 @@ class Celt : public AudioCodec celt_encoder_destroy (_enc); celt_decoder_destroy (_dec); - celt_mode_destroy(_mode); + celt_mode_destroy (_mode); } virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { diff --git a/sflphone-common/src/audio/codecs/codecDescriptor.cpp b/sflphone-common/src/audio/codecs/codecDescriptor.cpp index 268a6010d780dac542d7e3ceaa63e78759b6d994..c39be481860e5497e66e64b8ea7b88f1f9891c78 100644 --- a/sflphone-common/src/audio/codecs/codecDescriptor.cpp +++ b/sflphone-common/src/audio/codecs/codecDescriptor.cpp @@ -48,7 +48,7 @@ CodecDescriptor::~CodecDescriptor() void CodecDescriptor::deleteHandlePointer (void) { - _debug("CodecDesccriptor: Delete codec handle pointers"); + _debug ("CodecDesccriptor: Delete codec handle pointers"); for (int i = 0 ; (unsigned int) i < _CodecInMemory.size() ; i++) { unloadCodec (_CodecInMemory[i]); @@ -75,7 +75,8 @@ CodecDescriptor::init() } } -void CodecDescriptor::setDefaultOrder() { +void CodecDescriptor::setDefaultOrder() +{ _defaultCodecOrder.clear(); CodecsMap::iterator iter = _CodecsMap.begin(); @@ -115,7 +116,8 @@ CodecDescriptor::getCodec (AudioCodecType payload) return NULL; } -double CodecDescriptor::getBitRate (AudioCodecType payload) { +double CodecDescriptor::getBitRate (AudioCodecType payload) +{ CodecsMap::iterator iter = _CodecsMap.find (payload); @@ -125,7 +127,8 @@ double CodecDescriptor::getBitRate (AudioCodecType payload) { return 0.0; } -double CodecDescriptor::getBandwidthPerCall (AudioCodecType payload) { +double CodecDescriptor::getBandwidthPerCall (AudioCodecType payload) +{ CodecsMap::iterator iter = _CodecsMap.find (payload); @@ -135,7 +138,8 @@ double CodecDescriptor::getBandwidthPerCall (AudioCodecType payload) { return 0.0; } -int CodecDescriptor::getSampleRate (AudioCodecType payload) { +int CodecDescriptor::getSampleRate (AudioCodecType payload) +{ CodecsMap::iterator iter = _CodecsMap.find (payload); @@ -145,7 +149,8 @@ int CodecDescriptor::getSampleRate (AudioCodecType payload) { return 0; } -void CodecDescriptor::saveActiveCodecs (const std::vector<std::string>& list) { +void CodecDescriptor::saveActiveCodecs (const std::vector<std::string>& list) +{ _defaultCodecOrder.clear(); // list contains the ordered payload of active codecs picked by the user @@ -166,7 +171,8 @@ void CodecDescriptor::saveActiveCodecs (const std::vector<std::string>& list) { } } -std::vector<AudioCodec*> CodecDescriptor::scanCodecDirectory (void) { +std::vector<AudioCodec*> CodecDescriptor::scanCodecDirectory (void) +{ std::vector<AudioCodec*> codecs; std::string tmp; @@ -206,7 +212,8 @@ std::vector<AudioCodec*> CodecDescriptor::scanCodecDirectory (void) { return codecs; } -AudioCodec* CodecDescriptor::loadCodec (std::string path) { +AudioCodec* CodecDescriptor::loadCodec (std::string path) +{ CodecHandlePointer p; using std::cerr; @@ -232,7 +239,8 @@ AudioCodec* CodecDescriptor::loadCodec (std::string path) { } -void CodecDescriptor::unloadCodec (CodecHandlePointer p) { +void CodecDescriptor::unloadCodec (CodecHandlePointer p) +{ using std::cerr; destroy_t* destroyCodec = (destroy_t*) dlsym (p.second , "destroy"); @@ -245,7 +253,8 @@ void CodecDescriptor::unloadCodec (CodecHandlePointer p) { dlclose (p.second); } -AudioCodec* CodecDescriptor::instantiateCodec (AudioCodecType payload) { +AudioCodec* CodecDescriptor::instantiateCodec (AudioCodecType payload) +{ using std::cerr; @@ -262,6 +271,7 @@ AudioCodec* CodecDescriptor::instantiateCodec (AudioCodecType payload) { return a; } + iter++; } @@ -270,7 +280,8 @@ AudioCodec* CodecDescriptor::instantiateCodec (AudioCodecType payload) { -AudioCodec* CodecDescriptor::getFirstCodecAvailable (void) { +AudioCodec* CodecDescriptor::getFirstCodecAvailable (void) +{ CodecsMap::iterator iter = _CodecsMap.begin(); @@ -280,7 +291,8 @@ AudioCodec* CodecDescriptor::getFirstCodecAvailable (void) { return NULL; } -bool CodecDescriptor::seemsValid (std::string lib) { +bool CodecDescriptor::seemsValid (std::string lib) +{ // The name of the shared library seems valid <==> it looks like libcodec_xxx.so // We check this @@ -302,6 +314,7 @@ bool CodecDescriptor::seemsValid (std::string lib) { #ifdef HAVE_SPEEX_CODEC // Nothing special #else + if (lib.substr (begin.length() , lib.length() - begin.length() - end.length()) == SPEEX_STRING_DESCRIPTION) return false; @@ -310,6 +323,7 @@ bool CodecDescriptor::seemsValid (std::string lib) { #ifdef HAVE_GSM_CODEC // Nothing special #else + if (lib.substr (begin.length() , lib.length() - begin.length() - end.length()) == GSM_STRING_DESCRIPTION) return false; @@ -318,6 +332,7 @@ bool CodecDescriptor::seemsValid (std::string lib) { #ifdef BUILD_ILBC // Nothing special #else + if (lib.substr (begin.length() , lib.length() - begin.length() - end.length()) == ILBC_STRING_DESCRIPTION) return false; @@ -346,7 +361,8 @@ CodecDescriptor::alreadyInCache (std::string lib) return false; } -bool CodecDescriptor::isCodecLoaded (int payload) { +bool CodecDescriptor::isCodecLoaded (int payload) +{ CodecsMap::iterator iter = _CodecsMap.begin(); @@ -360,32 +376,33 @@ bool CodecDescriptor::isCodecLoaded (int payload) { return false; } -std::vector <std::string> CodecDescriptor::getCodecSpecifications (const int32_t& payload) { +std::vector <std::string> CodecDescriptor::getCodecSpecifications (const int32_t& payload) +{ - _debug ("CodecDescriptor: Gathering codec specifications for payload %i", payload); + _debug ("CodecDescriptor: Gathering codec specifications for payload %i", payload); - std::vector<std::string> v; + std::vector<std::string> v; std::stringstream ss; - // Add the name of the codec + // Add the name of the codec v.push_back (getCodecName ( (AudioCodecType) payload)); - // Add the sample rate + // Add the sample rate ss << getSampleRate ( (AudioCodecType) payload); v.push_back ( (ss.str()).data()); ss.str (""); - // Add the bit rate + // Add the bit rate ss << getBitRate ( (AudioCodecType) payload); v.push_back ( (ss.str()).data()); ss.str (""); - // Add the bandwidth information + // Add the bandwidth information ss << getBandwidthPerCall ( (AudioCodecType) payload); v.push_back ( (ss.str()).data()); ss.str (""); - return v; + return v; } diff --git a/sflphone-common/src/audio/codecs/gsmcodec.cpp b/sflphone-common/src/audio/codecs/gsmcodec.cpp index fef1d7a2c42943fbee8115ef0624ca9b609bae21..cb38d60cf6d453a52536629bc3ebeee212bdbe02 100644 --- a/sflphone-common/src/audio/codecs/gsmcodec.cpp +++ b/sflphone-common/src/audio/codecs/gsmcodec.cpp @@ -31,8 +31,7 @@ #include "audiocodec.h" -extern "C" -{ +extern "C" { #include <gsm/gsm.h> } diff --git a/sflphone-common/src/audio/codecs/speexcodec_nb.cpp b/sflphone-common/src/audio/codecs/speexcodec_nb.cpp index fdad5f29dc9facfc789d0c67b97967b220a90d4d..3061d5e7c5879a2f5f028a61485d75fd9a4bc9ce 100644 --- a/sflphone-common/src/audio/codecs/speexcodec_nb.cpp +++ b/sflphone-common/src/audio/codecs/speexcodec_nb.cpp @@ -45,7 +45,7 @@ class Speex : public AudioCodec _speex_enc_bits(), _speex_dec_state(), _speex_enc_state(), - _speex_frame_size() { + _speex_frame_size() { _clockRate = 8000; _frameSize = 160; // samples, 20 ms at 8kHz _channel = 1; diff --git a/sflphone-common/src/audio/codecs/speexcodec_ub.cpp b/sflphone-common/src/audio/codecs/speexcodec_ub.cpp index 47494fb99c79c9427052e1f9bd86b6bf06bf18a9..34885a3c592363b4baf1339aeba291b8bf3cadcf 100644 --- a/sflphone-common/src/audio/codecs/speexcodec_ub.cpp +++ b/sflphone-common/src/audio/codecs/speexcodec_ub.cpp @@ -44,7 +44,7 @@ class Speex : public AudioCodec _speex_enc_bits(), _speex_dec_state(), _speex_enc_state(), - _speex_frame_size() { + _speex_frame_size() { _clockRate = 32000; _frameSize = 640; // 20 ms at 32 kHz _channel = 1; diff --git a/sflphone-common/src/audio/codecs/speexcodec_wb.cpp b/sflphone-common/src/audio/codecs/speexcodec_wb.cpp index d9fda3e3af502b0dfcdc6d24c864b46942b1e64b..0409ee2427044ff177bd4a0baf76f88a726d8a9f 100644 --- a/sflphone-common/src/audio/codecs/speexcodec_wb.cpp +++ b/sflphone-common/src/audio/codecs/speexcodec_wb.cpp @@ -44,7 +44,7 @@ class Speex : public AudioCodec _speex_enc_bits(), _speex_dec_state(), _speex_enc_state(), - _speex_frame_size() { + _speex_frame_size() { _clockRate = 16000; _frameSize = 320; // 20 ms at 16 kHz _channel = 1; diff --git a/sflphone-common/src/audio/dcblocker.cpp b/sflphone-common/src/audio/dcblocker.cpp index 06505b428207bc3c25639497e1f06f78ef2285bb..bb373f1b012d3c25fd6cc84c953b63e3d57f8739 100644 --- a/sflphone-common/src/audio/dcblocker.cpp +++ b/sflphone-common/src/audio/dcblocker.cpp @@ -30,27 +30,31 @@ #include "dcblocker.h" -DcBlocker::DcBlocker() : _y(0), _x(0), _xm1(0), _ym1(0) {} +DcBlocker::DcBlocker() : _y (0), _x (0), _xm1 (0), _ym1 (0) {} DcBlocker::~DcBlocker() {} void DcBlocker::reset() { - _y = 0; - _x = 0; - _xm1 = 0; - _ym1 = 0; + _y = 0; + _x = 0; + _xm1 = 0; + _ym1 = 0; } -void DcBlocker::putData(SFLDataFormat *inputData UNUSED, int nbBytes UNUSED) {} +void DcBlocker::putData (SFLDataFormat *inputData UNUSED, int nbBytes UNUSED) {} -int DcBlocker::getData(SFLDataFormat *outputData UNUSED) { return 0; } +int DcBlocker::getData (SFLDataFormat *outputData UNUSED) +{ + return 0; +} void DcBlocker::process (SFLDataFormat *data, int nbBytes) { // y(n) = x(n) - x(n-1) + R y(n-1) , R = 0.9999 - int nbSamples = nbBytes / sizeof(SFLDataFormat); + int nbSamples = nbBytes / sizeof (SFLDataFormat); + for (int i = 0; i < nbSamples; i++) { _x = data[i]; @@ -63,9 +67,11 @@ void DcBlocker::process (SFLDataFormat *data, int nbBytes) } } -int DcBlocker::process(SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) { +int DcBlocker::process (SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) +{ + + int nbSamples = nbBytes / sizeof (SFLDataFormat); - int nbSamples = nbBytes / sizeof(SFLDataFormat); for (int i = 0; i < nbSamples; i++) { _x = inputData[i]; @@ -77,8 +83,8 @@ int DcBlocker::process(SFLDataFormat *inputData, SFLDataFormat *outputData, int outputData[i] = _y; } - return 0; + return 0; } -void DcBlocker::process(SFLDataFormat *micData UNUSED, SFLDataFormat *spkrData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED) {} +void DcBlocker::process (SFLDataFormat *micData UNUSED, SFLDataFormat *spkrData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED) {} diff --git a/sflphone-common/src/audio/delaydetection.cpp b/sflphone-common/src/audio/delaydetection.cpp index 16326c12e9070f04b9ccf2c3d1d48de966a2bef3..e05739ce17cabde5500d464e826094d8f3115b77 100644 --- a/sflphone-common/src/audio/delaydetection.cpp +++ b/sflphone-common/src/audio/delaydetection.cpp @@ -37,79 +37,85 @@ // decimation filter coefficient float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03630817, 0.02944626, - 0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722, - -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204, - 0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179, - 0.1160644, 0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299, - 0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834, - -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367, - 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, - 0.05616626, 0.07473655, -0.09870257}; -std::vector<double> ird(decimationCoefs, decimationCoefs + sizeof(decimationCoefs)/sizeof(float)); + 0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722, + -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204, + 0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179, + 0.1160644, 0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299, + 0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834, + -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367, + 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, + 0.05616626, 0.07473655, -0.09870257 + }; +std::vector<double> ird (decimationCoefs, decimationCoefs + sizeof (decimationCoefs) /sizeof (float)); // decimation filter coefficient float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113, - 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, - -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563, - 0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507, - -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, - 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034}; -std::vector<double> irb(bandpassCoefs, bandpassCoefs + sizeof(bandpassCoefs)/sizeof(float)); - - -FirFilter::FirFilter(std::vector<double> ir) : _length(ir.size()), - _impulseResponse(ir), - _count(0) + 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, + -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563, + 0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507, + -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, + 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034 + }; +std::vector<double> irb (bandpassCoefs, bandpassCoefs + sizeof (bandpassCoefs) /sizeof (float)); + + +FirFilter::FirFilter (std::vector<double> ir) : _length (ir.size()), + _impulseResponse (ir), + _count (0) { - memset(_taps, 0, sizeof(double)*MAXFILTERSIZE); + memset (_taps, 0, sizeof (double) *MAXFILTERSIZE); } FirFilter::~FirFilter() {} -float FirFilter::getOutputSample(float inputSample) +float FirFilter::getOutputSample (float inputSample) { - _taps[_count] = inputSample; - double result = 0.0; - int index = _count; - for(int i = 0; i < _length; i++) { - result = result + _impulseResponse[i] * _taps[index--]; - if(index < 0) - index = _length-1; - } - _count++; - if(_count >= _length) - _count = 0; - - return result; + _taps[_count] = inputSample; + double result = 0.0; + int index = _count; + + for (int i = 0; i < _length; i++) { + result = result + _impulseResponse[i] * _taps[index--]; + + if (index < 0) + index = _length-1; + } + + _count++; + + if (_count >= _length) + _count = 0; + + return result; } -void FirFilter::reset(void) +void FirFilter::reset (void) { - for(int i = 0; i < _length; i++) { - _impulseResponse[i] = 0.0; - } + for (int i = 0; i < _length; i++) { + _impulseResponse[i] = 0.0; + } } -DelayDetection::DelayDetection() : _internalState(WaitForSpeaker), _decimationFilter(ird), _bandpassFilter(irb), _segmentSize(DELAY_BUFF_SIZE), _downsamplingFactor(8) +DelayDetection::DelayDetection() : _internalState (WaitForSpeaker), _decimationFilter (ird), _bandpassFilter (irb), _segmentSize (DELAY_BUFF_SIZE), _downsamplingFactor (8) { _micDownSize = WINDOW_SIZE / _downsamplingFactor; _spkrDownSize = DELAY_BUFF_SIZE / _downsamplingFactor; - memset(_spkrReference, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_capturedData, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_spkrReferenceDown, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_captureDataDown, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_spkrReferenceFilter, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_captureDataFilter, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_correlationResult, 0, sizeof(float)*DELAY_BUFF_SIZE*2); + memset (_spkrReference, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_capturedData, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_spkrReferenceDown, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_captureDataDown, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_spkrReferenceFilter, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_captureDataFilter, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_correlationResult, 0, sizeof (float) *DELAY_BUFF_SIZE*2); } -DelayDetection::~DelayDetection(){} +DelayDetection::~DelayDetection() {} -void DelayDetection::reset() +void DelayDetection::reset() { _nbMicSampleStored = 0; _nbSpkrSampleStored = 0; @@ -117,205 +123,221 @@ void DelayDetection::reset() _decimationFilter.reset(); _bandpassFilter.reset(); - memset(_spkrReference, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_capturedData, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_spkrReferenceDown, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_captureDataDown, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_spkrReferenceFilter, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_captureDataFilter, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_correlationResult, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - + memset (_spkrReference, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_capturedData, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_spkrReferenceDown, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_captureDataDown, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_spkrReferenceFilter, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_captureDataFilter, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_correlationResult, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + _internalState = WaitForSpeaker; } -void DelayDetection::putData(SFLDataFormat *inputData, int nbBytes) +void DelayDetection::putData (SFLDataFormat *inputData, int nbBytes) { - // Machine may already got a spkr and is waiting for mic or computing correlation - if(_nbSpkrSampleStored == WINDOW_SIZE) - return; + // Machine may already got a spkr and is waiting for mic or computing correlation + if (_nbSpkrSampleStored == WINDOW_SIZE) + return; - int nbSamples = nbBytes/sizeof(SFLDataFormat); + int nbSamples = nbBytes/sizeof (SFLDataFormat); - if((_nbSpkrSampleStored + nbSamples) > WINDOW_SIZE) - nbSamples = WINDOW_SIZE - _nbSpkrSampleStored; - + if ( (_nbSpkrSampleStored + nbSamples) > WINDOW_SIZE) + nbSamples = WINDOW_SIZE - _nbSpkrSampleStored; - if (nbSamples) { - float tmp[nbSamples]; - float down[nbSamples]; + if (nbSamples) { - convertInt16ToFloat32(inputData, tmp, nbSamples); - memcpy(_spkrReference+_nbSpkrSampleStored, tmp, nbSamples*sizeof(float)); + float tmp[nbSamples]; + float down[nbSamples]; - downsampleData(tmp, down, nbSamples, _downsamplingFactor); - bandpassFilter(down, nbSamples/_downsamplingFactor); - memcpy(_spkrReferenceDown+(_nbSpkrSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor)*sizeof(float)); - - _nbSpkrSampleStored += nbSamples; + convertInt16ToFloat32 (inputData, tmp, nbSamples); + memcpy (_spkrReference+_nbSpkrSampleStored, tmp, nbSamples*sizeof (float)); - } + downsampleData (tmp, down, nbSamples, _downsamplingFactor); + bandpassFilter (down, nbSamples/_downsamplingFactor); + memcpy (_spkrReferenceDown+ (_nbSpkrSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor) *sizeof (float)); - // Update the state - _internalState = WaitForMic; + _nbSpkrSampleStored += nbSamples; + } + + // Update the state + _internalState = WaitForMic; + +} + +int DelayDetection::getData (SFLDataFormat *outputData UNUSED) +{ + return 0; } -int DelayDetection::getData(SFLDataFormat *outputData UNUSED) { return 0; } +void DelayDetection::process (SFLDataFormat *inputData, int nbBytes) +{ -void DelayDetection::process(SFLDataFormat *inputData, int nbBytes) { + if (_internalState != WaitForMic) + return; - if(_internalState != WaitForMic) - return; + int nbSamples = nbBytes/sizeof (SFLDataFormat); - int nbSamples = nbBytes/sizeof(SFLDataFormat); + if ( (_nbMicSampleStored + nbSamples) > DELAY_BUFF_SIZE) + nbSamples = DELAY_BUFF_SIZE - _nbMicSampleStored; - if((_nbMicSampleStored + nbSamples) > DELAY_BUFF_SIZE) - nbSamples = DELAY_BUFF_SIZE - _nbMicSampleStored; + if (nbSamples) { + float tmp[nbSamples]; + float down[nbSamples]; - if(nbSamples) { - float tmp[nbSamples]; - float down[nbSamples]; + convertInt16ToFloat32 (inputData, tmp, nbSamples); + memcpy (_capturedData+_nbMicSampleStored, tmp, nbSamples); - convertInt16ToFloat32(inputData, tmp, nbSamples); - memcpy(_capturedData+_nbMicSampleStored, tmp, nbSamples); + downsampleData (tmp, down, nbSamples, _downsamplingFactor); - downsampleData(tmp, down, nbSamples, _downsamplingFactor); + memcpy (_captureDataDown+ (_nbMicSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor) *sizeof (float)); - memcpy(_captureDataDown+(_nbMicSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor)*sizeof(float)); + _nbMicSampleStored += nbSamples; - _nbMicSampleStored += nbSamples; + } - } + if (_nbMicSampleStored == DELAY_BUFF_SIZE) + _internalState = ComputeCorrelation; + else + return; - if(_nbMicSampleStored == DELAY_BUFF_SIZE) - _internalState = ComputeCorrelation; - else - return; + _debug ("_spkrDownSize: %d, _micDownSize: %d", _spkrDownSize, _micDownSize); + crossCorrelate (_spkrReferenceDown, _captureDataDown, _correlationResult, _micDownSize, _spkrDownSize); - _debug("_spkrDownSize: %d, _micDownSize: %d", _spkrDownSize, _micDownSize); - crossCorrelate(_spkrReferenceDown, _captureDataDown, _correlationResult, _micDownSize, _spkrDownSize); + int maxIndex = getMaxIndex (_correlationResult, _spkrDownSize); - int maxIndex = getMaxIndex(_correlationResult, _spkrDownSize); + _debug ("MaxIndex: %d", maxIndex); +} - _debug("MaxIndex: %d", maxIndex); +int DelayDetection::process (SFLDataFormat *intputData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED) +{ + return 0; } -int DelayDetection::process(SFLDataFormat *intputData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED) { return 0; } +void DelayDetection::process (SFLDataFormat *micData UNUSED, SFLDataFormat *spkrData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED) {} -void DelayDetection::process(SFLDataFormat *micData UNUSED, SFLDataFormat *spkrData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED) {} +void DelayDetection::crossCorrelate (float *ref, float *seg, float *res, int refSize, int segSize) +{ -void DelayDetection::crossCorrelate(float *ref, float *seg, float *res, int refSize, int segSize) { + _debug ("CrossCorrelate"); - _debug("CrossCorrelate"); + // Output has same size as the + int rsize = refSize; + int ssize = segSize; + int tmpsize = segSize-refSize+1; - // Output has same size as the - int rsize = refSize; - int ssize = segSize; - int tmpsize = segSize-refSize+1; + // perform autocorrelation on reference signal + float acref = correlate (ref, ref, rsize); - // perform autocorrelation on reference signal - float acref = correlate(ref, ref, rsize); - - // perform crossrelation on signal - float acseg = 0.0; - float r; - while(--tmpsize) { - --ssize; - acseg = correlate(seg+tmpsize, seg+tmpsize, rsize); - res[ssize] = correlate(ref, seg+tmpsize, rsize); - r = sqrt(acref*acseg); + // perform crossrelation on signal + float acseg = 0.0; + float r; - if(r < 0.0000001) - res[ssize] = 0.0; - else - res[ssize] = res[ssize] / r; - } - - // perform crosscorrelation on zerro padded region - int i = 0; - while(rsize) { - acseg = correlate(seg, seg, rsize); - res[ssize-1] = correlate(ref+i, seg, rsize); - r = sqrt(acref*acseg); - - if(r < 0.0001) - res[ssize-1] = 0.0; - else - res[ssize-1] = res[ssize-1] / r; - - --rsize; - --ssize; - ++i; - } + while (--tmpsize) { + --ssize; + acseg = correlate (seg+tmpsize, seg+tmpsize, rsize); + res[ssize] = correlate (ref, seg+tmpsize, rsize); + r = sqrt (acref*acseg); + + if (r < 0.0000001) + res[ssize] = 0.0; + else + res[ssize] = res[ssize] / r; + } + + // perform crosscorrelation on zerro padded region + int i = 0; + + while (rsize) { + acseg = correlate (seg, seg, rsize); + res[ssize-1] = correlate (ref+i, seg, rsize); + r = sqrt (acref*acseg); + + if (r < 0.0001) + res[ssize-1] = 0.0; + else + res[ssize-1] = res[ssize-1] / r; + + --rsize; + --ssize; + ++i; + } } -double DelayDetection::correlate(float *sig1, float *sig2, short size) { +double DelayDetection::correlate (float *sig1, float *sig2, short size) +{ + + short s = size; - short s = size; + double ac = 0.0; - double ac = 0.0; - while(s--) - ac += sig1[s]*sig2[s]; + while (s--) + ac += sig1[s]*sig2[s]; - return ac; + return ac; } -void DelayDetection::convertInt16ToFloat32(SFLDataFormat *input, float *output, int nbSamples) { +void DelayDetection::convertInt16ToFloat32 (SFLDataFormat *input, float *output, int nbSamples) +{ #define S2F_FACTOR .000030517578125f; - int len = nbSamples; + int len = nbSamples; - while(len) { - len--; - output[len] = (float)input[len] * S2F_FACTOR; - } + while (len) { + len--; + output[len] = (float) input[len] * S2F_FACTOR; + } } -void DelayDetection::downsampleData(float *input, float *output, int nbSamples, int factor) { +void DelayDetection::downsampleData (float *input, float *output, int nbSamples, int factor) +{ + + int _src_err; - int _src_err; + SRC_STATE *_src_state = src_new (SRC_LINEAR, 1, &_src_err); - SRC_STATE *_src_state = src_new (SRC_LINEAR, 1, &_src_err); + double downfactor = 1.0 / (double) factor; - double downfactor = 1.0 / (double)factor; + if (downfactor != 1.0) { + SRC_DATA src_data; + src_data.data_in = input; + src_data.data_out = output; + src_data.input_frames = nbSamples; + src_data.output_frames = nbSamples / factor; + src_data.src_ratio = downfactor; + src_data.end_of_input = 0; // More data will come - if (downfactor != 1.0) { - SRC_DATA src_data; - src_data.data_in = input; - src_data.data_out = output; - src_data.input_frames = nbSamples; - src_data.output_frames = nbSamples / factor; - src_data.src_ratio = downfactor; - src_data.end_of_input = 0; // More data will come - - src_process (_src_state, &src_data); - } + src_process (_src_state, &src_data); + } } -void DelayDetection::bandpassFilter(float *input, int nbSamples) { +void DelayDetection::bandpassFilter (float *input, int nbSamples) +{ - for(int i = 0; i < nbSamples; i++) { - input[i] = _bandpassFilter.getOutputSample(input[i]); + for (int i = 0; i < nbSamples; i++) { + input[i] = _bandpassFilter.getOutputSample (input[i]); } } -int DelayDetection::getMaxIndex(float *data, int size) { +int DelayDetection::getMaxIndex (float *data, int size) +{ - float max = 0.0; - int k; + float max = 0.0; + int k; - for(int i = 0; i < size; i++) { - if(data[i] >= max) { - max = data[i]; - k = i; + for (int i = 0; i < size; i++) { + if (data[i] >= max) { + max = data[i]; + k = i; + } } - } - return k; + return k; } diff --git a/sflphone-common/src/audio/echocancel.cpp b/sflphone-common/src/audio/echocancel.cpp index 612b1dbed76796b44102813c77eb7450ae5bf8c6..e6e2a3c92fbec4e3d7c6002da27466eaee400b3f 100644 --- a/sflphone-common/src/audio/echocancel.cpp +++ b/sflphone-common/src/audio/echocancel.cpp @@ -32,574 +32,592 @@ // #include <fstream> -EchoCancel::EchoCancel(int smplRate, int frameLength) : _samplingRate(smplRate), - _frameLength(frameLength), - _smplPerFrame(0), - _smplPerSeg(0), - _nbSegmentPerFrame(0), - _micHistoryLength(0), - _spkrHistoryLength(0), - _alpha(0.01), - _spkrLevelMem(0), - _micLevelMem(0), - _spkrLevel(0), - _micLevel(0), - _spkrHistCnt(0), - _micHistCnt(0), - _amplFactor(0.0), - _lastAmplFactor(0.0), - _amplDelayIndexIn(0), - _amplDelayIndexOut(0), - _adaptDone(false), - _adaptStarted(false), - _adaptCnt(0), - _spkrAdaptCnt(0), - _micAdaptCnt(0), - _spkrAdaptSize(SPKR_ADAPT_SIZE), - _micAdaptSize(MIC_ADAPT_SIZE), - _correlationSize(0), - _processedByte(0), - _echoActive(true), - _noiseActive(true) +EchoCancel::EchoCancel (int smplRate, int frameLength) : _samplingRate (smplRate), + _frameLength (frameLength), + _smplPerFrame (0), + _smplPerSeg (0), + _nbSegmentPerFrame (0), + _micHistoryLength (0), + _spkrHistoryLength (0), + _alpha (0.01), + _spkrLevelMem (0), + _micLevelMem (0), + _spkrLevel (0), + _micLevel (0), + _spkrHistCnt (0), + _micHistCnt (0), + _amplFactor (0.0), + _lastAmplFactor (0.0), + _amplDelayIndexIn (0), + _amplDelayIndexOut (0), + _adaptDone (false), + _adaptStarted (false), + _adaptCnt (0), + _spkrAdaptCnt (0), + _micAdaptCnt (0), + _spkrAdaptSize (SPKR_ADAPT_SIZE), + _micAdaptSize (MIC_ADAPT_SIZE), + _correlationSize (0), + _processedByte (0), + _echoActive (true), + _noiseActive (true) { - _debug("EchoCancel: Instantiate echo canceller"); - - - // micFile = new ofstream("micData", ofstream::binary); - // echoFile = new ofstream("echoData", ofstream::binary); - // spkrFile = new ofstream("spkrData", ofstream::binary); - - micLevelData = new ofstream("micLevelData", ofstream::binary); - spkrLevelData = new ofstream("spkrLevelData", ofstream::binary); - - - _micData = new RingBuffer(50000); - _spkrData = new RingBuffer(50000); - _spkrDataOut = new RingBuffer(50000); - - _micData->createReadPointer(); - _spkrData->createReadPointer(); - _spkrDataOut->createReadPointer(); - - // variable used to sync mic and spkr - _spkrStoped = true; - - _smplPerFrame = (_samplingRate * _frameLength) / MS_PER_SEC; - _smplPerSeg = (_samplingRate * SEGMENT_LENGTH) / MS_PER_SEC; - _micHistoryLength = MIC_LENGTH / SEGMENT_LENGTH; - _spkrHistoryLength = SPKR_LENGTH / SEGMENT_LENGTH; - _nbSegmentPerFrame = _frameLength / SEGMENT_LENGTH; - - _noiseState = speex_preprocess_state_init(_smplPerFrame, _samplingRate); - int i=1; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DENOISE, &i); - i=-20; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); - i=0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC, &i); - i=8000; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); - i=16000; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); - i=0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB, &i); - float f=0.0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); - f=0.0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); - i = 0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_VAD, &i); - - - memset(_avgSpkrLevelHist, 0, BUFF_SIZE*sizeof(int)); - memset(_avgMicLevelHist, 0, BUFF_SIZE*sizeof(int)); - - memset(_delayLineAmplify, 0, MAX_DELAY_LINE_AMPL*sizeof(float)); - - _amplDelayIndexIn = 0; - _amplDelayIndexOut = 0; - - _correlationSize = _spkrAdaptSize; - + _debug ("EchoCancel: Instantiate echo canceller"); + + + // micFile = new ofstream("micData", ofstream::binary); + // echoFile = new ofstream("echoData", ofstream::binary); + // spkrFile = new ofstream("spkrData", ofstream::binary); + + micLevelData = new ofstream ("micLevelData", ofstream::binary); + spkrLevelData = new ofstream ("spkrLevelData", ofstream::binary); + + + _micData = new RingBuffer (50000); + _spkrData = new RingBuffer (50000); + _spkrDataOut = new RingBuffer (50000); + + _micData->createReadPointer(); + _spkrData->createReadPointer(); + _spkrDataOut->createReadPointer(); + + // variable used to sync mic and spkr + _spkrStoped = true; + + _smplPerFrame = (_samplingRate * _frameLength) / MS_PER_SEC; + _smplPerSeg = (_samplingRate * SEGMENT_LENGTH) / MS_PER_SEC; + _micHistoryLength = MIC_LENGTH / SEGMENT_LENGTH; + _spkrHistoryLength = SPKR_LENGTH / SEGMENT_LENGTH; + _nbSegmentPerFrame = _frameLength / SEGMENT_LENGTH; + + _noiseState = speex_preprocess_state_init (_smplPerFrame, _samplingRate); + int i=1; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DENOISE, &i); + i=-20; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); + i=0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC, &i); + i=8000; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); + i=16000; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); + i=0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB, &i); + float f=0.0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); + f=0.0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); + i = 0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_VAD, &i); + + + memset (_avgSpkrLevelHist, 0, BUFF_SIZE*sizeof (int)); + memset (_avgMicLevelHist, 0, BUFF_SIZE*sizeof (int)); + + memset (_delayLineAmplify, 0, MAX_DELAY_LINE_AMPL*sizeof (float)); + + _amplDelayIndexIn = 0; + _amplDelayIndexOut = 0; + + _correlationSize = _spkrAdaptSize; + } -EchoCancel::~EchoCancel() +EchoCancel::~EchoCancel() { - _debug("EchoCancel: Delete echo canceller"); + _debug ("EchoCancel: Delete echo canceller"); + + delete _micData; + _micData = NULL; - delete _micData; - _micData = NULL; + delete _spkrData; + _spkrData = NULL; - delete _spkrData; - _spkrData = NULL; + speex_preprocess_state_destroy (_noiseState); - speex_preprocess_state_destroy(_noiseState); - - // micFile->close(); - // spkrFile->close(); - // echoFile->close(); + // micFile->close(); + // spkrFile->close(); + // echoFile->close(); - // delete micFile; - // delete spkrFile; - // delete echoFile; + // delete micFile; + // delete spkrFile; + // delete echoFile; - micLevelData->close(); - spkrLevelData->close(); - delete micLevelData; - delete spkrLevelData; + micLevelData->close(); + spkrLevelData->close(); + delete micLevelData; + delete spkrLevelData; } void EchoCancel::reset() { - _debug("EchoCancel: Reset internal state, Sampling rate %d, Frame size %d", _samplingRate, _smplPerFrame); - - memset(_avgSpkrLevelHist, 0, BUFF_SIZE*sizeof(int)); - memset(_avgMicLevelHist, 0, BUFF_SIZE*sizeof(int)); - - _spkrLevel = 0; - _micLevel = 0; - _spkrHistCnt = 0; - _micHistCnt = 0; - _amplFactor = 0.0; - _lastAmplFactor = 0.0; - - _smplPerFrame = (_samplingRate * _frameLength) / MS_PER_SEC; - _smplPerSeg = (_samplingRate * SEGMENT_LENGTH) / MS_PER_SEC; - _micHistoryLength = MIC_LENGTH / SEGMENT_LENGTH; - _spkrHistoryLength = SPKR_LENGTH / SEGMENT_LENGTH; - _nbSegmentPerFrame = _frameLength / SEGMENT_LENGTH; - - memset(_delayLineAmplify, 0, MAX_DELAY_LINE_AMPL*sizeof(float)); - - _amplDelayIndexIn = 0; - _amplDelayIndexOut = ECHO_LENGTH / SEGMENT_LENGTH; - - _adaptDone = false; - _adaptStarted = false; - _adaptCnt = 0; - _spkrAdaptCnt = 0; - _micAdaptCnt = 0; - - _micData->flushAll(); - _spkrData->flushAll(); - _spkrDataOut->flushAll(); - - speex_preprocess_state_destroy(_noiseState); - - _noiseState = speex_preprocess_state_init(_smplPerFrame, _samplingRate); - int i=1; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DENOISE, &i); - i=-10; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); - i=0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC, &i); - i=8000; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); - i=16000; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); - i=0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB, &i); - float f=0.0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); - f=0.0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); - - _spkrStoped = true; - - _processedByte = 0; + _debug ("EchoCancel: Reset internal state, Sampling rate %d, Frame size %d", _samplingRate, _smplPerFrame); + + memset (_avgSpkrLevelHist, 0, BUFF_SIZE*sizeof (int)); + memset (_avgMicLevelHist, 0, BUFF_SIZE*sizeof (int)); + + _spkrLevel = 0; + _micLevel = 0; + _spkrHistCnt = 0; + _micHistCnt = 0; + _amplFactor = 0.0; + _lastAmplFactor = 0.0; + + _smplPerFrame = (_samplingRate * _frameLength) / MS_PER_SEC; + _smplPerSeg = (_samplingRate * SEGMENT_LENGTH) / MS_PER_SEC; + _micHistoryLength = MIC_LENGTH / SEGMENT_LENGTH; + _spkrHistoryLength = SPKR_LENGTH / SEGMENT_LENGTH; + _nbSegmentPerFrame = _frameLength / SEGMENT_LENGTH; + + memset (_delayLineAmplify, 0, MAX_DELAY_LINE_AMPL*sizeof (float)); + + _amplDelayIndexIn = 0; + _amplDelayIndexOut = ECHO_LENGTH / SEGMENT_LENGTH; + + _adaptDone = false; + _adaptStarted = false; + _adaptCnt = 0; + _spkrAdaptCnt = 0; + _micAdaptCnt = 0; + + _micData->flushAll(); + _spkrData->flushAll(); + _spkrDataOut->flushAll(); + + speex_preprocess_state_destroy (_noiseState); + + _noiseState = speex_preprocess_state_init (_smplPerFrame, _samplingRate); + int i=1; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DENOISE, &i); + i=-10; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); + i=0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC, &i); + i=8000; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); + i=16000; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); + i=0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB, &i); + float f=0.0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); + f=0.0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); + + _spkrStoped = true; + + _processedByte = 0; } -void EchoCancel::putData(SFLDataFormat *inputData, int nbBytes) +void EchoCancel::putData (SFLDataFormat *inputData, int nbBytes) { - _delayDetector.putData(inputData, nbBytes); + _delayDetector.putData (inputData, nbBytes); - if(_spkrStoped) { - _debug("EchoCancel: Flush data"); - _micData->flushAll(); - _spkrData->flushAll(); - _spkrStoped = false; - } + if (_spkrStoped) { + _debug ("EchoCancel: Flush data"); + _micData->flushAll(); + _spkrData->flushAll(); + _spkrStoped = false; + } - // Put data in speaker ring buffer - _spkrData->Put(inputData, nbBytes); + // Put data in speaker ring buffer + _spkrData->Put (inputData, nbBytes); } -int EchoCancel::getData(SFLDataFormat *outputData) +int EchoCancel::getData (SFLDataFormat *outputData) { - int copied = 0; + int copied = 0; - if(_processedByte > 0) { - copied = _spkrDataOut->Get(outputData, _processedByte); - _processedByte = 0; - } + if (_processedByte > 0) { + copied = _spkrDataOut->Get (outputData, _processedByte); + _processedByte = 0; + } - return copied; + return copied; } -void EchoCancel::process(SFLDataFormat *data UNUSED, int nbBytes UNUSED) {} +void EchoCancel::process (SFLDataFormat *data UNUSED, int nbBytes UNUSED) {} -int EchoCancel::process(SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) +int EchoCancel::process (SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) { - _delayDetector.process(inputData, nbBytes); + _delayDetector.process (inputData, nbBytes); + + if (_spkrStoped) { + bcopy (inputData, outputData, nbBytes); + return nbBytes; + } - if(_spkrStoped) { - bcopy(inputData, outputData, nbBytes); - return nbBytes; - } + int byteSize = _smplPerFrame*sizeof (SFLDataFormat); - int byteSize = _smplPerFrame*sizeof(SFLDataFormat); + // init temporary buffers + memset (_tmpSpkr, 0, BUFF_SIZE*sizeof (SFLDataFormat)); + memset (_tmpMic, 0, BUFF_SIZE*sizeof (SFLDataFormat)); + memset (_tmpOut, 0, BUFF_SIZE*sizeof (SFLDataFormat)); - // init temporary buffers - memset(_tmpSpkr, 0, BUFF_SIZE*sizeof(SFLDataFormat)); - memset(_tmpMic, 0, BUFF_SIZE*sizeof(SFLDataFormat)); - memset(_tmpOut, 0, BUFF_SIZE*sizeof(SFLDataFormat)); + // Put mic data in ringbuffer + _micData->Put (inputData, nbBytes); - // Put mic data in ringbuffer - _micData->Put(inputData, nbBytes); + // Store data for synchronization + int spkrAvail = _spkrData->AvailForGet(); + int micAvail = _micData->AvailForGet(); - // Store data for synchronization - int spkrAvail = _spkrData->AvailForGet(); - int micAvail = _micData->AvailForGet(); + // Init number of frame processed + int nbFrame = 0; - // Init number of frame processed - int nbFrame = 0; + // Get data from mic and speaker internal buffer + // while((spkrAvail >= byteSize) && (micAvail >= byteSize)) { + while (micAvail >= byteSize) { - // Get data from mic and speaker internal buffer - // while((spkrAvail >= byteSize) && (micAvail >= byteSize)) { - while(micAvail >= byteSize) { + if (spkrAvail >= byteSize) { - if(spkrAvail >= byteSize) { + // get synchronized data + _spkrData->Get (_tmpSpkr, byteSize); + _micData->Get (_tmpMic, byteSize); - // get synchronized data - _spkrData->Get(_tmpSpkr, byteSize); - _micData->Get(_tmpMic, byteSize); - - // micFile->write((const char *)_tmpMic, byteSize); - // spkrFile->write((const char *)_tmpSpkr, byteSize); + // micFile->write((const char *)_tmpMic, byteSize); + // spkrFile->write((const char *)_tmpSpkr, byteSize); #ifdef HAVE_LIBSPEEX_DSP - _debug("OK"); + _debug ("OK"); + + // Remove noise + if (_noiseActive) + speex_preprocess_run (_noiseState, _tmpMic); - // Remove noise - if(_noiseActive) - speex_preprocess_run(_noiseState, _tmpMic); #endif - // Processed echo cancellation - performEchoCancel(_tmpMic, _tmpSpkr, _tmpOut); + // Processed echo cancellation + performEchoCancel (_tmpMic, _tmpSpkr, _tmpOut); - // echoFile->write((const char *)_tmpOut, byteSize); + // echoFile->write((const char *)_tmpOut, byteSize); - bcopy(_tmpOut, outputData+(nbFrame*_smplPerFrame), byteSize); + bcopy (_tmpOut, outputData+ (nbFrame*_smplPerFrame), byteSize); - // used to sync with speaker - _processedByte += byteSize; + // used to sync with speaker + _processedByte += byteSize; - spkrAvail = _spkrData->AvailForGet(); - micAvail = _micData->AvailForGet(); + spkrAvail = _spkrData->AvailForGet(); + micAvail = _micData->AvailForGet(); - // increment nb of frame processed - ++nbFrame; - } - else { - _micData->Get(_tmpMic, byteSize); + // increment nb of frame processed + ++nbFrame; + } else { + _micData->Get (_tmpMic, byteSize); - performEchoCancelNoSpkr(_tmpMic, _tmpOut); + performEchoCancelNoSpkr (_tmpMic, _tmpOut); - bcopy(_tmpOut, outputData+(nbFrame*_smplPerFrame), byteSize); - ++nbFrame; - } + bcopy (_tmpOut, outputData+ (nbFrame*_smplPerFrame), byteSize); + ++nbFrame; + } - spkrAvail = _spkrData->AvailForGet(); - micAvail = _micData->AvailForGet(); - } + spkrAvail = _spkrData->AvailForGet(); + micAvail = _micData->AvailForGet(); + } - // if spkrAvail is twice the size of a frame discard it, this data is late and won't be used - if(spkrAvail > (2*byteSize)) { - _spkrData->Discard(spkrAvail-(2*byteSize)); - } + // if spkrAvail is twice the size of a frame discard it, this data is late and won't be used + if (spkrAvail > (2*byteSize)) { + _spkrData->Discard (spkrAvail- (2*byteSize)); + } - return nbFrame * _smplPerFrame; + return nbFrame * _smplPerFrame; } -void EchoCancel::process(SFLDataFormat *micData UNUSED, SFLDataFormat *spkrData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED){ +void EchoCancel::process (SFLDataFormat *micData UNUSED, SFLDataFormat *spkrData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED) +{ } -void EchoCancel::setSamplingRate(int smplRate) { - - if (smplRate != _samplingRate) { - _samplingRate = smplRate; +void EchoCancel::setSamplingRate (int smplRate) +{ + + if (smplRate != _samplingRate) { + _samplingRate = smplRate; - reset(); - } + reset(); + } } -void EchoCancel::performEchoCancel(SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData) { +void EchoCancel::performEchoCancel (SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData) +{ - for(int k = 0; k < _nbSegmentPerFrame; k++) { + for (int k = 0; k < _nbSegmentPerFrame; k++) { - updateEchoCancel(micData+(k*_smplPerSeg), spkrData+(k*_smplPerSeg)); + updateEchoCancel (micData+ (k*_smplPerSeg), spkrData+ (k*_smplPerSeg)); - _spkrLevel = getMaxAmplitude(_avgSpkrLevelHist, _spkrHistoryLength); - _micLevel = getMaxAmplitude(_avgMicLevelHist, _micHistoryLength)/6; + _spkrLevel = getMaxAmplitude (_avgSpkrLevelHist, _spkrHistoryLength); + _micLevel = getMaxAmplitude (_avgMicLevelHist, _micHistoryLength) /6; - if(_spkrLevel >= MIN_SIG_LEVEL) { - if(_micLevel > _spkrLevel) { - increaseFactor(0.2); - } - else { - _amplFactor = 0.0; - } - } - else { - increaseFactor(0.01); - } + if (_spkrLevel >= MIN_SIG_LEVEL) { + if (_micLevel > _spkrLevel) { + increaseFactor (0.2); + } else { + _amplFactor = 0.0; + } + } else { + increaseFactor (0.01); + } - // lowpass filtering - float amplify = (_lastAmplFactor + _amplFactor) / 2; - _lastAmplFactor = _amplFactor; + // lowpass filtering + float amplify = (_lastAmplFactor + _amplFactor) / 2; + _lastAmplFactor = _amplFactor; - if(!_echoActive) - amplify = 1.0; + if (!_echoActive) + amplify = 1.0; - amplifySignal(micData+(k*_smplPerSeg), outputData+(k*_smplPerSeg), amplify); - - } + amplifySignal (micData+ (k*_smplPerSeg), outputData+ (k*_smplPerSeg), amplify); + + } } -void EchoCancel::performEchoCancelNoSpkr(SFLDataFormat *micData, SFLDataFormat *outputData) { +void EchoCancel::performEchoCancelNoSpkr (SFLDataFormat *micData, SFLDataFormat *outputData) +{ + + for (int k = 0; k < _nbSegmentPerFrame; k++) { - for(int k = 0; k < _nbSegmentPerFrame; k++) { + updateMicLevel (micData); - updateMicLevel(micData); + _micLevel = getMaxAmplitude (_avgMicLevelHist, _micHistoryLength) /6; - _micLevel = getMaxAmplitude(_avgMicLevelHist, _micHistoryLength)/6; - if(_micLevel > MIN_SIG_LEVEL) { - increaseFactor(0.2); - } + if (_micLevel > MIN_SIG_LEVEL) { + increaseFactor (0.2); + } - // lowpass filtering - float amplify = (_lastAmplFactor + _amplFactor) / 2; - _lastAmplFactor = _amplFactor; + // lowpass filtering + float amplify = (_lastAmplFactor + _amplFactor) / 2; + _lastAmplFactor = _amplFactor; - if(!_echoActive) - amplify = 1.0; + if (!_echoActive) + amplify = 1.0; - amplifySignal(micData+(k*_smplPerSeg), outputData+(k*_smplPerSeg), amplify); - } + amplifySignal (micData+ (k*_smplPerSeg), outputData+ (k*_smplPerSeg), amplify); + } } -void EchoCancel::updateMicLevel(SFLDataFormat *micData) { +void EchoCancel::updateMicLevel (SFLDataFormat *micData) +{ - int micLvl = computeAmplitudeLevel(micData, _smplPerSeg); + int micLvl = computeAmplitudeLevel (micData, _smplPerSeg); - SFLDataFormat tempMicLevel[_smplPerSeg]; + SFLDataFormat tempMicLevel[_smplPerSeg]; - _micLevelMem = estimatePower(micData, tempMicLevel, _smplPerSeg, _micLevelMem); + _micLevelMem = estimatePower (micData, tempMicLevel, _smplPerSeg, _micLevelMem); - _avgMicLevelHist[_micHistCnt++] = micLvl+1; + _avgMicLevelHist[_micHistCnt++] = micLvl+1; - if(_micHistCnt >= _micHistoryLength) - _micHistCnt = 0; + if (_micHistCnt >= _micHistoryLength) + _micHistCnt = 0; - micLevelData->write((const char*)tempMicLevel, sizeof(SFLDataFormat)*_smplPerSeg); + micLevelData->write ( (const char*) tempMicLevel, sizeof (SFLDataFormat) *_smplPerSeg); } -void EchoCancel::updateSpkrLevel(SFLDataFormat *spkrData) { +void EchoCancel::updateSpkrLevel (SFLDataFormat *spkrData) +{ - int spkrLvl = computeAmplitudeLevel(spkrData, _smplPerSeg); + int spkrLvl = computeAmplitudeLevel (spkrData, _smplPerSeg); - SFLDataFormat tempSpkrLevel[_smplPerSeg]; + SFLDataFormat tempSpkrLevel[_smplPerSeg]; - _spkrLevelMem = estimatePower(spkrData, tempSpkrLevel, _smplPerSeg, _spkrLevelMem); + _spkrLevelMem = estimatePower (spkrData, tempSpkrLevel, _smplPerSeg, _spkrLevelMem); - _avgSpkrLevelHist[_spkrHistCnt++] = spkrLvl+1; + _avgSpkrLevelHist[_spkrHistCnt++] = spkrLvl+1; - if(_spkrHistCnt >= _spkrHistoryLength) - _spkrHistCnt = 0; + if (_spkrHistCnt >= _spkrHistoryLength) + _spkrHistCnt = 0; - spkrLevelData->write((const char*)tempSpkrLevel, sizeof(SFLDataFormat)*_smplPerSeg); + spkrLevelData->write ( (const char*) tempSpkrLevel, sizeof (SFLDataFormat) *_smplPerSeg); } -void EchoCancel::updateEchoCancel(SFLDataFormat *micData, SFLDataFormat *spkrData) { - - // Add 1 to make sure we are not dividing by 0 - updateMicLevel(micData); - updateSpkrLevel(spkrData); +void EchoCancel::updateEchoCancel (SFLDataFormat *micData, SFLDataFormat *spkrData) +{ - /* - // if adaptation done, stop here - // if(_adaptDone) - if(true) - return; + // Add 1 to make sure we are not dividing by 0 + updateMicLevel (micData); + updateSpkrLevel (spkrData); - // start learning only if there is data played through speaker - if(!_adaptStarted) { - if(spkrLvl > MIN_SIG_LEVEL) - _adaptStarted = true; - else + /* + // if adaptation done, stop here + // if(_adaptDone) + if(true) return; - } - if(_spkrAdaptCnt < _spkrAdaptSize) - _spkrAdaptArray[_spkrAdaptCnt++] = spkrLvl; + // start learning only if there is data played through speaker + if(!_adaptStarted) { + if(spkrLvl > MIN_SIG_LEVEL) + _adaptStarted = true; + else + return; + } + + if(_spkrAdaptCnt < _spkrAdaptSize) + _spkrAdaptArray[_spkrAdaptCnt++] = spkrLvl; - if(_micAdaptCnt < _micAdaptSize) - _micAdaptArray[_micAdaptCnt++] = micLvl; + if(_micAdaptCnt < _micAdaptSize) + _micAdaptArray[_micAdaptCnt++] = micLvl; - // perform correlation if spkr size is reached - if(_adaptCnt > _spkrAdaptSize) { - int k = _adaptCnt - _spkrAdaptSize; - _correlationArray[k] = performCorrelation(_spkrAdaptArray, _micAdaptArray+k, _correlationSize); - } + // perform correlation if spkr size is reached + if(_adaptCnt > _spkrAdaptSize) { + int k = _adaptCnt - _spkrAdaptSize; + _correlationArray[k] = performCorrelation(_spkrAdaptArray, _micAdaptArray+k, _correlationSize); + } - _adaptCnt++; + _adaptCnt++; - // if we captured a full echo - if(_adaptCnt == _micAdaptSize) { - _adaptDone = true; - _amplDelayIndexOut = 0;// getMaximumIndex(_correlationArray, _correlationSize); - } - */ + // if we captured a full echo + if(_adaptCnt == _micAdaptSize) { + _adaptDone = true; + _amplDelayIndexOut = 0;// getMaximumIndex(_correlationArray, _correlationSize); + } + */ } -int EchoCancel::computeAmplitudeLevel(SFLDataFormat *data, int size) { +int EchoCancel::computeAmplitudeLevel (SFLDataFormat *data, int size) +{ + + int level = 0; - int level = 0; + for (int i = 0; i < size; i++) { + if (data[i] >= 0.0) + level += (int) data[i]; + else + level -= (int) data[i]; + } - for(int i = 0; i < size; i++) { - if(data[i] >= 0.0) - level += (int)data[i]; - else - level -= (int)data[i]; - } + level = level / _smplPerSeg; - level = level / _smplPerSeg; + return level; - return level; - } -SFLDataFormat EchoCancel::estimatePower(SFLDataFormat *data, SFLDataFormat *ampl, int size, SFLDataFormat mem) { +SFLDataFormat EchoCancel::estimatePower (SFLDataFormat *data, SFLDataFormat *ampl, int size, SFLDataFormat mem) +{ - float memFactor = 1.0 - _alpha; + float memFactor = 1.0 - _alpha; - for (int i = 0; i < size; i++) { - mem = (SFLDataFormat)(memFactor*(float)mem + abs(_alpha*(float)data[i])); - ampl[i] = mem; - } + for (int i = 0; i < size; i++) { + mem = (SFLDataFormat) (memFactor* (float) mem + abs (_alpha* (float) data[i])); + ampl[i] = mem; + } - return mem; + return mem; } -int EchoCancel::getMaxAmplitude(int *data, int size) { +int EchoCancel::getMaxAmplitude (int *data, int size) +{ - SFLDataFormat level = 0.0; + SFLDataFormat level = 0.0; - for(int i = 0; i < size; i++) { - if(data[i] >= level) - level = data[i]; - } + for (int i = 0; i < size; i++) { + if (data[i] >= level) + level = data[i]; + } - return (int)level; + return (int) level; } -void EchoCancel::amplifySignal(SFLDataFormat *micData, SFLDataFormat *outputData, float amplify) { - - // for(int i = 0; i < _smplPerSeg; i++) - // outputData[i] = micData[i]; +void EchoCancel::amplifySignal (SFLDataFormat *micData, SFLDataFormat *outputData, float amplify) +{ - // Use delayed amplification factor due to sound card latency - // do not increment amplitude array if adaptation is not done - // if (_adaptDone) { - if (true) { - for(int i = 0; i < _smplPerSeg; i++) { - outputData[i] = (SFLDataFormat)(((float)micData[i])*_delayLineAmplify[_amplDelayIndexOut]); - } - _amplDelayIndexOut++; - _delayLineAmplify[_amplDelayIndexIn++] = amplify; - } - else { - for(int i = 0; i < _smplPerSeg; i++) { - outputData[i] = micData[i]; + // for(int i = 0; i < _smplPerSeg; i++) + // outputData[i] = micData[i]; + + // Use delayed amplification factor due to sound card latency + // do not increment amplitude array if adaptation is not done + // if (_adaptDone) { + if (true) { + for (int i = 0; i < _smplPerSeg; i++) { + outputData[i] = (SFLDataFormat) ( ( (float) micData[i]) *_delayLineAmplify[_amplDelayIndexOut]); + } + + _amplDelayIndexOut++; + _delayLineAmplify[_amplDelayIndexIn++] = amplify; + } else { + for (int i = 0; i < _smplPerSeg; i++) { + outputData[i] = micData[i]; + } + + return; } - return; - } - if(_amplDelayIndexOut >= MAX_DELAY_LINE_AMPL) - _amplDelayIndexOut = 0; + if (_amplDelayIndexOut >= MAX_DELAY_LINE_AMPL) + _amplDelayIndexOut = 0; - if(_amplDelayIndexIn >= MAX_DELAY_LINE_AMPL) - _amplDelayIndexIn = 0; + if (_amplDelayIndexIn >= MAX_DELAY_LINE_AMPL) + _amplDelayIndexIn = 0; } -void EchoCancel::increaseFactor(float factor) { +void EchoCancel::increaseFactor (float factor) +{ - // Get 200 ms to get back to full amplitude - _amplFactor += factor; + // Get 200 ms to get back to full amplitude + _amplFactor += factor; - if(_amplFactor > 1.0) - _amplFactor = 1.0; + if (_amplFactor > 1.0) + _amplFactor = 1.0; } -void EchoCancel::decreaseFactor() { +void EchoCancel::decreaseFactor() +{ - // Takes about 50 ms to react - _amplFactor -= 0.2; + // Takes about 50 ms to react + _amplFactor -= 0.2; - if(_amplFactor < 0.0) - _amplFactor = 0.0; + if (_amplFactor < 0.0) + _amplFactor = 0.0; } -int EchoCancel::performCorrelation(int *data1, int *data2, int size) { +int EchoCancel::performCorrelation (int *data1, int *data2, int size) +{ + + int correlation = 0; + + while (size) { + size--; + correlation += data1[size] * data2[size]; + } - int correlation = 0; - while(size) { - size--; - correlation += data1[size] * data2[size]; - } - return correlation; + return correlation; } -int EchoCancel::getMaximumIndex(int *data, int size) { +int EchoCancel::getMaximumIndex (int *data, int size) +{ + + int index = size; + int max = data[size-1]; + + while (size) { + size--; - int index = size; - int max = data[size-1]; - - while(size) { - size--; - if(data[size] > max) { - index = size; - max = data[size]; + if (data[size] > max) { + index = size; + max = data[size]; + } } - } - return index; + return index; } diff --git a/sflphone-common/src/audio/jitterbuf.cpp b/sflphone-common/src/audio/jitterbuf.cpp old mode 100755 new mode 100644 index 510317cfeda83c538a6d5769eacfc173c6113960..4881498853e1ca7604e16d3bd6eee865b85d4dbc --- a/sflphone-common/src/audio/jitterbuf.cpp +++ b/sflphone-common/src/audio/jitterbuf.cpp @@ -51,831 +51,856 @@ static jb_output_function_t warnf, errf, dbgf; -void jb_setoutput(jb_output_function_t err, jb_output_function_t warn, jb_output_function_t dbg) +void jb_setoutput (jb_output_function_t err, jb_output_function_t warn, jb_output_function_t dbg) { - errf = err; - warnf = warn; - dbgf = dbg; + errf = err; + warnf = warn; + dbgf = dbg; } -static void increment_losspct(jitterbuf *jb) +static void increment_losspct (jitterbuf *jb) { - jb->info.losspct = (100000 + 499 * jb->info.losspct)/500; + jb->info.losspct = (100000 + 499 * jb->info.losspct) /500; } -static void decrement_losspct(jitterbuf *jb) +static void decrement_losspct (jitterbuf *jb) { - jb->info.losspct = (499 * jb->info.losspct)/500; + jb->info.losspct = (499 * jb->info.losspct) /500; } -void jb_reset(jitterbuf *jb) +void jb_reset (jitterbuf *jb) { - /* only save settings */ - jb_conf s = jb->info.conf; - memset(jb, 0, sizeof(*jb)); - jb->info.conf = s; - - /* initialize length, using the default value */ - jb->info.current = jb->info.target = jb->info.conf.target_extra = JB_TARGET_EXTRA; - jb->info.silence_begin_ts = -1; + /* only save settings */ + jb_conf s = jb->info.conf; + memset (jb, 0, sizeof (*jb)); + jb->info.conf = s; + + /* initialize length, using the default value */ + jb->info.current = jb->info.target = jb->info.conf.target_extra = JB_TARGET_EXTRA; + jb->info.silence_begin_ts = -1; } -jitterbuf * jb_new() +jitterbuf * jb_new() { - jitterbuf *jb; + jitterbuf *jb; - if (!(jb = (jitterbuf *)malloc(sizeof(*jb)))) - return NULL; + if (! (jb = (jitterbuf *) malloc (sizeof (*jb)))) + return NULL; - jb_reset(jb); + jb_reset (jb); - jb_dbg2("jb_new() = %x\n", jb); - return jb; + jb_dbg2 ("jb_new() = %x\n", jb); + return jb; } -void jb_destroy(jitterbuf *jb) +void jb_destroy (jitterbuf *jb) { - jb_frame *frame; - jb_dbg2("jb_destroy(%x)\n", jb); - - /* free all the frames on the "free list" */ - frame = jb->free; - while (frame != NULL) { - jb_frame *next = frame->next; - free(frame); - frame = next; - } - - /* free ourselves! */ - free(jb); + jb_frame *frame; + jb_dbg2 ("jb_destroy(%x)\n", jb); + + /* free all the frames on the "free list" */ + frame = jb->free; + + while (frame != NULL) { + jb_frame *next = frame->next; + free (frame); + frame = next; + } + + /* free ourselves! */ + free (jb); } #if 0 -static int longcmp(const void *a, const void *b) +static int longcmp (const void *a, const void *b) { - return *(long *)a - *(long *)b; + return * (long *) a - * (long *) b; } #endif -/*! \brief simple history manipulation +/*! \brief simple history manipulation \note maybe later we can make the history buckets variable size, or something? */ /* drop parameter determines whether we will drop outliers to minimize * delay */ -static int history_put(jitterbuf *jb, long ts, long now) +static int history_put (jitterbuf *jb, long ts, long now) { - long delay = now - (ts - jb->info.resync_offset); - long threshold = 2 * jb->info.jitter + jb->info.conf.resync_threshold; - long kicked; - - /* don't add special/negative times to history */ - if (ts <= 0) - return 0; - - /* check for drastic change in delay */ - if (jb->info.conf.resync_threshold != -1) { - if (abs(delay - jb->info.last_delay) > threshold) { - jb->info.cnt_delay_discont++; - if (jb->info.cnt_delay_discont > 3) { - /* resync the jitterbuffer */ - jb->info.cnt_delay_discont = 0; - jb->hist_ptr = 0; - jb->hist_maxbuf_valid = 0; - - jb_warn("Resyncing the jb. last_delay %ld, this delay %ld, threshold %ld, new offset %ld\n", jb->info.last_delay, delay, threshold, ts - now); - jb->info.resync_offset = ts - now; - jb->info.last_delay = delay = 0; /* after resync, frame is right on time */ - } else { - return -1; - } - } else { - jb->info.last_delay = delay; - jb->info.cnt_delay_discont = 0; - } - } - - kicked = jb->history[jb->hist_ptr % JB_HISTORY_SZ]; - - jb->history[(jb->hist_ptr++) % JB_HISTORY_SZ] = delay; - - /* optimization; the max/min buffers don't need to be recalculated, if this packet's - * entry doesn't change them. This happens if this packet is not involved, _and_ any packet - * that got kicked out of the history is also not involved - * We do a number of comparisons, but it's probably still worthwhile, because it will usually - * succeed, and should be a lot faster than going through all 500 packets in history */ - if (!jb->hist_maxbuf_valid) - return 0; - - /* don't do this until we've filled history - * (reduces some edge cases below) */ - if (jb->hist_ptr < JB_HISTORY_SZ) - goto invalidate; - - /* if the new delay would go into min */ - if (delay < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) - goto invalidate; - - /* or max.. */ - if (delay > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) - goto invalidate; - - /* or the kicked delay would be in min */ - if (kicked <= jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) - goto invalidate; - - if (kicked >= jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) - goto invalidate; - - /* if we got here, we don't need to invalidate, 'cause this delay didn't - * affect things */ - return 0; - /* end optimization */ + long delay = now - (ts - jb->info.resync_offset); + long threshold = 2 * jb->info.jitter + jb->info.conf.resync_threshold; + long kicked; + + /* don't add special/negative times to history */ + if (ts <= 0) + return 0; + + /* check for drastic change in delay */ + if (jb->info.conf.resync_threshold != -1) { + if (abs (delay - jb->info.last_delay) > threshold) { + jb->info.cnt_delay_discont++; + + if (jb->info.cnt_delay_discont > 3) { + /* resync the jitterbuffer */ + jb->info.cnt_delay_discont = 0; + jb->hist_ptr = 0; + jb->hist_maxbuf_valid = 0; + + jb_warn ("Resyncing the jb. last_delay %ld, this delay %ld, threshold %ld, new offset %ld\n", jb->info.last_delay, delay, threshold, ts - now); + jb->info.resync_offset = ts - now; + jb->info.last_delay = delay = 0; /* after resync, frame is right on time */ + } else { + return -1; + } + } else { + jb->info.last_delay = delay; + jb->info.cnt_delay_discont = 0; + } + } + + kicked = jb->history[jb->hist_ptr % JB_HISTORY_SZ]; + + jb->history[ (jb->hist_ptr++) % JB_HISTORY_SZ] = delay; + + /* optimization; the max/min buffers don't need to be recalculated, if this packet's + * entry doesn't change them. This happens if this packet is not involved, _and_ any packet + * that got kicked out of the history is also not involved + * We do a number of comparisons, but it's probably still worthwhile, because it will usually + * succeed, and should be a lot faster than going through all 500 packets in history */ + if (!jb->hist_maxbuf_valid) + return 0; + + /* don't do this until we've filled history + * (reduces some edge cases below) */ + if (jb->hist_ptr < JB_HISTORY_SZ) + goto invalidate; + + /* if the new delay would go into min */ + if (delay < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) + goto invalidate; + + /* or max.. */ + if (delay > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) + goto invalidate; + + /* or the kicked delay would be in min */ + if (kicked <= jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) + goto invalidate; + + if (kicked >= jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) + goto invalidate; + + /* if we got here, we don't need to invalidate, 'cause this delay didn't + * affect things */ + return 0; + /* end optimization */ invalidate: - jb->hist_maxbuf_valid = 0; - return 0; + jb->hist_maxbuf_valid = 0; + return 0; } -static void history_calc_maxbuf(jitterbuf *jb) +static void history_calc_maxbuf (jitterbuf *jb) { - int i,j; - - if (jb->hist_ptr == 0) - return; - - - /* initialize maxbuf/minbuf to the latest value */ - for (i=0;i<JB_HISTORY_MAXBUF_SZ;i++) { -/* - * jb->hist_maxbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ]; - * jb->hist_minbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ]; - */ - jb->hist_maxbuf[i] = JB_LONGMIN; - jb->hist_minbuf[i] = JB_LONGMAX; - } - - /* use insertion sort to populate maxbuf */ - /* we want it to be the top "n" values, in order */ - - /* start at the beginning, or JB_HISTORY_SZ frames ago */ - i = (jb->hist_ptr > JB_HISTORY_SZ) ? (jb->hist_ptr - JB_HISTORY_SZ) : 0; - - for (;i<jb->hist_ptr;i++) { - long toins = jb->history[i % JB_HISTORY_SZ]; - - /* if the maxbuf should get this */ - if (toins > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) { - - /* insertion-sort it into the maxbuf */ - for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) { - /* found where it fits */ - if (toins > jb->hist_maxbuf[j]) { - /* move over */ - memmove(jb->hist_maxbuf + j + 1, jb->hist_maxbuf + j, (JB_HISTORY_MAXBUF_SZ - (j + 1)) * sizeof(jb->hist_maxbuf[0])); - /* insert */ - jb->hist_maxbuf[j] = toins; - - break; - } - } - } - - /* if the minbuf should get this */ - if (toins < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) { - - /* insertion-sort it into the maxbuf */ - for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) { - /* found where it fits */ - if (toins < jb->hist_minbuf[j]) { - /* move over */ - memmove(jb->hist_minbuf + j + 1, jb->hist_minbuf + j, (JB_HISTORY_MAXBUF_SZ - (j + 1)) * sizeof(jb->hist_minbuf[0])); - /* insert */ - jb->hist_minbuf[j] = toins; - - break; - } - } - } - - if (0) { - int k; - _debug("toins = %ld\n", toins); - _debug("maxbuf ="); - for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++) - _debug("%ld ", jb->hist_maxbuf[k]); - _debug("\nminbuf ="); - for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++) - _debug("%ld ", jb->hist_minbuf[k]); - _debug("\n"); - } - } - - jb->hist_maxbuf_valid = 1; + int i,j; + + if (jb->hist_ptr == 0) + return; + + + /* initialize maxbuf/minbuf to the latest value */ + for (i=0; i<JB_HISTORY_MAXBUF_SZ; i++) { + /* + * jb->hist_maxbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ]; + * jb->hist_minbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ]; + */ + jb->hist_maxbuf[i] = JB_LONGMIN; + jb->hist_minbuf[i] = JB_LONGMAX; + } + + /* use insertion sort to populate maxbuf */ + /* we want it to be the top "n" values, in order */ + + /* start at the beginning, or JB_HISTORY_SZ frames ago */ + i = (jb->hist_ptr > JB_HISTORY_SZ) ? (jb->hist_ptr - JB_HISTORY_SZ) : 0; + + for (; i<jb->hist_ptr; i++) { + long toins = jb->history[i % JB_HISTORY_SZ]; + + /* if the maxbuf should get this */ + if (toins > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) { + + /* insertion-sort it into the maxbuf */ + for (j=0; j<JB_HISTORY_MAXBUF_SZ; j++) { + /* found where it fits */ + if (toins > jb->hist_maxbuf[j]) { + /* move over */ + memmove (jb->hist_maxbuf + j + 1, jb->hist_maxbuf + j, (JB_HISTORY_MAXBUF_SZ - (j + 1)) * sizeof (jb->hist_maxbuf[0])); + /* insert */ + jb->hist_maxbuf[j] = toins; + + break; + } + } + } + + /* if the minbuf should get this */ + if (toins < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) { + + /* insertion-sort it into the maxbuf */ + for (j=0; j<JB_HISTORY_MAXBUF_SZ; j++) { + /* found where it fits */ + if (toins < jb->hist_minbuf[j]) { + /* move over */ + memmove (jb->hist_minbuf + j + 1, jb->hist_minbuf + j, (JB_HISTORY_MAXBUF_SZ - (j + 1)) * sizeof (jb->hist_minbuf[0])); + /* insert */ + jb->hist_minbuf[j] = toins; + + break; + } + } + } + + if (0) { + int k; + _debug ("toins = %ld\n", toins); + _debug ("maxbuf ="); + + for (k=0; k<JB_HISTORY_MAXBUF_SZ; k++) + _debug ("%ld ", jb->hist_maxbuf[k]); + + _debug ("\nminbuf ="); + + for (k=0; k<JB_HISTORY_MAXBUF_SZ; k++) + _debug ("%ld ", jb->hist_minbuf[k]); + + _debug ("\n"); + } + } + + jb->hist_maxbuf_valid = 1; } -static void history_get(jitterbuf *jb) +static void history_get (jitterbuf *jb) { - long max, min, jitter; - int idx; - int count; + long max, min, jitter; + int idx; + int count; - if (!jb->hist_maxbuf_valid) - history_calc_maxbuf(jb); + if (!jb->hist_maxbuf_valid) + history_calc_maxbuf (jb); - /* count is how many items in history we're examining */ - count = (jb->hist_ptr < JB_HISTORY_SZ) ? jb->hist_ptr : JB_HISTORY_SZ; + /* count is how many items in history we're examining */ + count = (jb->hist_ptr < JB_HISTORY_SZ) ? jb->hist_ptr : JB_HISTORY_SZ; - /* idx is the "n"ths highest/lowest that we'll look for */ - idx = count * JB_HISTORY_DROPPCT / 100; + /* idx is the "n"ths highest/lowest that we'll look for */ + idx = count * JB_HISTORY_DROPPCT / 100; - /* sanity checks for idx */ - if (idx > (JB_HISTORY_MAXBUF_SZ - 1)) - idx = JB_HISTORY_MAXBUF_SZ - 1; + /* sanity checks for idx */ + if (idx > (JB_HISTORY_MAXBUF_SZ - 1)) + idx = JB_HISTORY_MAXBUF_SZ - 1; - if (idx < 0) { - jb->info.min = 0; - jb->info.jitter = 0; - return; - } + if (idx < 0) { + jb->info.min = 0; + jb->info.jitter = 0; + return; + } - max = jb->hist_maxbuf[idx]; - min = jb->hist_minbuf[idx]; + max = jb->hist_maxbuf[idx]; + min = jb->hist_minbuf[idx]; - jitter = max - min; + jitter = max - min; - /* these debug stmts compare the difference between looking at the absolute jitter, and the - * values we get by throwing away the outliers */ - // printf("[%ld] min=%ld, max=%ld, jitter=%ld\n", index, min, max, jitter); - // printf("[%ld] min=%ld, max=%ld, jitter=%ld\n", 0, jb->hist_minbuf[0], jb->hist_maxbuf[0], jb->hist_maxbuf[0]-jb->hist_minbuf[0]); + /* these debug stmts compare the difference between looking at the absolute jitter, and the + * values we get by throwing away the outliers */ + // printf("[%ld] min=%ld, max=%ld, jitter=%ld\n", index, min, max, jitter); + // printf("[%ld] min=%ld, max=%ld, jitter=%ld\n", 0, jb->hist_minbuf[0], jb->hist_maxbuf[0], jb->hist_maxbuf[0]-jb->hist_minbuf[0]); - jb->info.min = min; - jb->info.jitter = jitter; + jb->info.min = min; + jb->info.jitter = jitter; } /* returns 1 if frame was inserted into head of queue, 0 otherwise */ -static int queue_put(jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts) +static int queue_put (jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts) { - jb_frame *frame; - jb_frame *p; - int head = 0; - long resync_ts = ts - jb->info.resync_offset; - - if ((frame = jb->free)) { - jb->free = frame->next; - } else if (!(frame = (jb_frame *)malloc(sizeof(*frame)))) { - jb_err("cannot allocate frame\n"); - return 0; - } - - jb->info.frames_cur++; - - frame->data = data; - frame->ts = resync_ts; - frame->ms = ms; - frame->type = type; - - /* - * frames are a circular list, jb-frames points to to the lowest ts, - * jb->frames->prev points to the highest ts - */ - - if (!jb->frames) { /* queue is empty */ - jb->frames = frame; - frame->next = frame; - frame->prev = frame; - head = 1; - } else if (resync_ts < jb->frames->ts) { - frame->next = jb->frames; - frame->prev = jb->frames->prev; - - frame->next->prev = frame; - frame->prev->next = frame; - - /* frame is out of order */ - jb->info.frames_ooo++; - - jb->frames = frame; - head = 1; - } else { - p = jb->frames; - - /* frame is out of order */ - if (resync_ts < p->prev->ts) jb->info.frames_ooo++; - - while (resync_ts < p->prev->ts && p->prev != jb->frames) - p = p->prev; - - frame->next = p; - frame->prev = p->prev; - - frame->next->prev = frame; - frame->prev->next = frame; - } - return head; + jb_frame *frame; + jb_frame *p; + int head = 0; + long resync_ts = ts - jb->info.resync_offset; + + if ( (frame = jb->free)) { + jb->free = frame->next; + } else if (! (frame = (jb_frame *) malloc (sizeof (*frame)))) { + jb_err ("cannot allocate frame\n"); + return 0; + } + + jb->info.frames_cur++; + + frame->data = data; + frame->ts = resync_ts; + frame->ms = ms; + frame->type = type; + + /* + * frames are a circular list, jb-frames points to to the lowest ts, + * jb->frames->prev points to the highest ts + */ + + if (!jb->frames) { /* queue is empty */ + jb->frames = frame; + frame->next = frame; + frame->prev = frame; + head = 1; + } else if (resync_ts < jb->frames->ts) { + frame->next = jb->frames; + frame->prev = jb->frames->prev; + + frame->next->prev = frame; + frame->prev->next = frame; + + /* frame is out of order */ + jb->info.frames_ooo++; + + jb->frames = frame; + head = 1; + } else { + p = jb->frames; + + /* frame is out of order */ + if (resync_ts < p->prev->ts) jb->info.frames_ooo++; + + while (resync_ts < p->prev->ts && p->prev != jb->frames) + p = p->prev; + + frame->next = p; + frame->prev = p->prev; + + frame->next->prev = frame; + frame->prev->next = frame; + } + + return head; } -static long queue_next(jitterbuf *jb) +static long queue_next (jitterbuf *jb) { - if (jb->frames) - return jb->frames->ts; - else - return -1; + if (jb->frames) + return jb->frames->ts; + else + return -1; } -static long queue_last(jitterbuf *jb) +static long queue_last (jitterbuf *jb) { - if (jb->frames) - return jb->frames->prev->ts; - else - return -1; + if (jb->frames) + return jb->frames->prev->ts; + else + return -1; } -static jb_frame *_queue_get(jitterbuf *jb, long ts, int all) +static jb_frame *_queue_get (jitterbuf *jb, long ts, int all) { - jb_frame *frame; - frame = jb->frames; + jb_frame *frame; + frame = jb->frames; - if (!frame) - return NULL; + if (!frame) + return NULL; - _debug("queue_get: ASK %ld FIRST %ld\n", ts, frame->ts); + _debug ("queue_get: ASK %ld FIRST %ld\n", ts, frame->ts); - if (all || ts >= frame->ts) { - /* remove this frame */ - frame->prev->next = frame->next; - frame->next->prev = frame->prev; + if (all || ts >= frame->ts) { + /* remove this frame */ + frame->prev->next = frame->next; + frame->next->prev = frame->prev; - if (frame->next == frame) - jb->frames = NULL; - else - jb->frames = frame->next; + if (frame->next == frame) + jb->frames = NULL; + else + jb->frames = frame->next; - /* insert onto "free" single-linked list */ - frame->next = jb->free; - jb->free = frame; + /* insert onto "free" single-linked list */ + frame->next = jb->free; + jb->free = frame; - jb->info.frames_cur--; + jb->info.frames_cur--; - /* we return the frame pointer, even though it's on free list, - * but caller must copy data */ - return frame; - } + /* we return the frame pointer, even though it's on free list, + * but caller must copy data */ + return frame; + } - return NULL; + return NULL; } -static jb_frame *queue_get(jitterbuf *jb, long ts) +static jb_frame *queue_get (jitterbuf *jb, long ts) { - return _queue_get(jb,ts,0); + return _queue_get (jb,ts,0); } -static jb_frame *queue_getall(jitterbuf *jb) +static jb_frame *queue_getall (jitterbuf *jb) { - return _queue_get(jb,0,1); + return _queue_get (jb,0,1); } /* some diagnostics */ -void jb_dbginfo(jitterbuf *jb) +void jb_dbginfo (jitterbuf *jb) { - _debug("\njb info: fin=%ld fout=%ld flate=%ld flost=%ld fdrop=%ld fcur=%ld\n", - jb->info.frames_in, jb->info.frames_out, jb->info.frames_late, jb->info.frames_lost, jb->info.frames_dropped, jb->info.frames_cur); - - _debug("jitter=%ld current=%ld target=%ld min=%ld sil=%ld len=%ld len/fcur=%ld\n", - jb->info.jitter, jb->info.current, jb->info.target, jb->info.min, jb->info.silence_begin_ts, jb->info.current - jb->info.min, - jb->info.frames_cur ? (jb->info.current - jb->info.min)/jb->info.frames_cur : -8); - if (jb->info.frames_in > 0) - _debug("jb info: Loss PCT = %ld%%, Late PCT = %ld%%\n", - jb->info.frames_lost * 100/(jb->info.frames_in + jb->info.frames_lost), - jb->info.frames_late * 100/jb->info.frames_in); - _debug("jb info: queue %ld -> %ld. last_ts %ld (queue len: %ld) last_ms %ld\n\n", - queue_next(jb), - queue_last(jb), - jb->info.next_voice_ts, - queue_last(jb) - queue_next(jb), - jb->info.last_voice_ms); + _debug ("\njb info: fin=%ld fout=%ld flate=%ld flost=%ld fdrop=%ld fcur=%ld\n", + jb->info.frames_in, jb->info.frames_out, jb->info.frames_late, jb->info.frames_lost, jb->info.frames_dropped, jb->info.frames_cur); + + _debug ("jitter=%ld current=%ld target=%ld min=%ld sil=%ld len=%ld len/fcur=%ld\n", + jb->info.jitter, jb->info.current, jb->info.target, jb->info.min, jb->info.silence_begin_ts, jb->info.current - jb->info.min, + jb->info.frames_cur ? (jb->info.current - jb->info.min) /jb->info.frames_cur : -8); + + if (jb->info.frames_in > 0) + _debug ("jb info: Loss PCT = %ld%%, Late PCT = %ld%%\n", + jb->info.frames_lost * 100/ (jb->info.frames_in + jb->info.frames_lost), + jb->info.frames_late * 100/jb->info.frames_in); + + _debug ("jb info: queue %ld -> %ld. last_ts %ld (queue len: %ld) last_ms %ld\n\n", + queue_next (jb), + queue_last (jb), + jb->info.next_voice_ts, + queue_last (jb) - queue_next (jb), + jb->info.last_voice_ms); } #ifdef DEEP_DEBUG -static void jb_chkqueue(jitterbuf *jb) +static void jb_chkqueue (jitterbuf *jb) { - int i=0; - jb_frame *p = jb->frames; - - if (!p) { - return; - } - - do { - if (p->next == NULL) { - jb_err("Queue is BROKEN at item [%d]", i); - } - i++; - p=p->next; - } while (p->next != jb->frames); + int i=0; + jb_frame *p = jb->frames; + + if (!p) { + return; + } + + do { + if (p->next == NULL) { + jb_err ("Queue is BROKEN at item [%d]", i); + } + + i++; + p=p->next; + } while (p->next != jb->frames); } -static void jb_dbgqueue(jitterbuf *jb) +static void jb_dbgqueue (jitterbuf *jb) { - int i=0; - jb_frame *p = jb->frames; + int i=0; + jb_frame *p = jb->frames; - jb_dbg("queue: "); + jb_dbg ("queue: "); - if (!p) { - jb_dbg("EMPTY\n"); - return; - } + if (!p) { + jb_dbg ("EMPTY\n"); + return; + } - do { - jb_dbg("[%d]=%ld ", i++, p->ts); - p=p->next; - } while (p->next != jb->frames); + do { + jb_dbg ("[%d]=%ld ", i++, p->ts); + p=p->next; + } while (p->next != jb->frames); - jb_dbg("\n"); + jb_dbg ("\n"); } #endif -jb_return_code jb_put(jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts, long now) +jb_return_code jb_put (jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts, long now) { - long numts; - - _debug("jb_put(%p,%p,%ld,%ld,%ld)\n", jb, data, ms, ts, now); - - numts = 0; - if (jb->frames) - numts = jb->frames->prev->ts - jb->frames->ts; - - _debug("numts %ld\n", numts); - - if (numts >= jb->info.conf.max_jitterbuf) { - if (!jb->dropem) { - _debug("Attempting to exceed Jitterbuf max %ld timeslots\n", - jb->info.conf.max_jitterbuf); - jb->dropem = 1; - } - jb->info.frames_dropped++; - return JB_DROP; - } else { - jb->dropem = 0; - } - - if (type == JB_TYPE_VOICE) { - /* presently, I'm only adding VOICE frames to history and drift calculations; mostly because with the - * IAX integrations, I'm sending retransmitted control frames with their awkward timestamps through */ - if (history_put(jb,ts,now)) { - jb->info.frames_dropped++; - return JB_DROP; - } - } - - jb->info.frames_in++; - - /* if put into head of queue, caller needs to reschedule */ - if (queue_put(jb,data,type,ms,ts)) { - return JB_SCHED; - } - return JB_OK; + long numts; + + _debug ("jb_put(%p,%p,%ld,%ld,%ld)\n", jb, data, ms, ts, now); + + numts = 0; + + if (jb->frames) + numts = jb->frames->prev->ts - jb->frames->ts; + + _debug ("numts %ld\n", numts); + + if (numts >= jb->info.conf.max_jitterbuf) { + if (!jb->dropem) { + _debug ("Attempting to exceed Jitterbuf max %ld timeslots\n", + jb->info.conf.max_jitterbuf); + jb->dropem = 1; + } + + jb->info.frames_dropped++; + return JB_DROP; + } else { + jb->dropem = 0; + } + + if (type == JB_TYPE_VOICE) { + /* presently, I'm only adding VOICE frames to history and drift calculations; mostly because with the + * IAX integrations, I'm sending retransmitted control frames with their awkward timestamps through */ + if (history_put (jb,ts,now)) { + jb->info.frames_dropped++; + return JB_DROP; + } + } + + jb->info.frames_in++; + + /* if put into head of queue, caller needs to reschedule */ + if (queue_put (jb,data,type,ms,ts)) { + return JB_SCHED; + } + + return JB_OK; } -static enum jb_return_code _jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl) +static enum jb_return_code _jb_get (jitterbuf *jb, jb_frame *frameout, long now, long interpl) { - jb_frame *frame; - long diff; - static int dbg_cnt = 0; - - _debug("_jb_get\n"); - - /*if ((now - jb_next(jb)) > 2 * jb->info.last_voice_ms) jb_warn("SCHED: %ld", (now - jb_next(jb))); */ - /* get jitter info */ - history_get(jb); - - if (dbg_cnt && dbg_cnt % 50 == 0) { - jb_dbg("\n"); - } - dbg_cnt++; - - /* target */ - jb->info.target = jb->info.jitter + jb->info.min + jb->info.conf.target_extra; - - /* if a hard clamp was requested, use it */ - if ((jb->info.conf.max_jitterbuf) && ((jb->info.target - jb->info.min) > jb->info.conf.max_jitterbuf)) { - _debug("clamping target from %ld to %ld\n", (jb->info.target - jb->info.min), jb->info.conf.max_jitterbuf); - jb->info.target = jb->info.min + jb->info.conf.max_jitterbuf; - } - - diff = jb->info.target - jb->info.current; - - _debug("diff = %ld lms=%ld last = %ld now = %ld, djust delay = %ld\n", diff, - jb->info.last_voice_ms, jb->info.last_adjustment, now); - - /* let's work on non-silent case first */ - if (!jb->info.silence_begin_ts) { - - /* - if(diff > 0) - printf("diff > 0\n"); - - if((jb->info.last_adjustment + JB_ADJUST_DELAY) < now) - printf("(jb->info.last_adjustment + JB_ADJUST_DELAY) < now\n"); - - if((diff > queue_last(jb) - queue_next(jb))) - printf("diff > queue_last(jb) - queue_next(jb)\n"); - */ - _debug("** Non-silent case update timing info **\n"); - _debug("diff %ld\n", diff); - _debug("jb->info.last_adjustment %ld\n", jb->info.last_adjustment); - _debug("JB_ADJUST_DELAY %ld\n", JB_ADJUST_DELAY); - _debug("now %ld\n", now); - - /* we want to grow */ - if ((diff > 0) && - /* we haven't grown in the delay length */ - (((jb->info.last_adjustment + JB_ADJUST_DELAY) < now) || - /* we need to grow more than the "length" we have left */ - (diff > queue_last(jb) - queue_next(jb)) ) ) { - - - - - /* grow by interp frame length */ - jb->info.current += interpl; - jb->info.next_voice_ts += interpl; - jb->info.last_voice_ms = interpl; - jb->info.last_adjustment = now; - jb->info.cnt_contig_interp++; - if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) { - jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current; - } - - _debug("Non silent case\n"); - return JB_INTERP; - } - - _debug("queue get\n"); - - frame = queue_get(jb, jb->info.next_voice_ts - jb->info.current); - - if(!frame) - _debug("frame not valid\n"); - - /* not a voice frame; just return it. */ - if (frame && frame->type != JB_TYPE_VOICE) { - if (frame->type == JB_TYPE_SILENCE) { - jb->info.silence_begin_ts = frame->ts; - jb->info.cnt_contig_interp = 0; - } - - *frameout = *frame; - jb->info.frames_out++; - _debug("Not a voice packet\n"); - return JB_OK; - } - - - /* voice frame is later than expected */ - if (frame && frame->ts + jb->info.current < jb->info.next_voice_ts) { - if (frame->ts + jb->info.current > jb->info.next_voice_ts - jb->info.last_voice_ms) { - /* either we interpolated past this frame in the last jb_get */ - /* or the frame is still in order, but came a little too quick */ - *frameout = *frame; - /* reset expectation for next frame */ - jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms; - jb->info.frames_out++; - decrement_losspct(jb); - jb->info.cnt_contig_interp = 0; - _debug("Either we interpolated past this frame in the last jb_get" \ - "or the frame is still in order, but came a little too quick\n"); - return JB_OK; - } else { - /* voice frame is late */ - *frameout = *frame; - jb->info.frames_out++; - decrement_losspct(jb); - jb->info.frames_late++; - jb->info.frames_lost--; - _debug("Voice frame is late\n"); - _debug("late: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb)); - return JB_DROP; - } - } - - /* keep track of frame sizes, to allow for variable sized-frames */ - if (frame && frame->ms > 0) { - jb->info.last_voice_ms = frame->ms; - } - - /* we want to shrink; shrink at 1 frame / 500ms */ - /* unless we don't have a frame, then shrink 1 frame */ - /* every 80ms (though perhaps we can shrink even faster */ - /* in this case) */ - if (diff < -jb->info.conf.target_extra && - ((!frame && jb->info.last_adjustment + 80 < now) || - (jb->info.last_adjustment + 500 < now))) { - - jb->info.last_adjustment = now; - jb->info.cnt_contig_interp = 0; - - if (frame) { - *frameout = *frame; - /* shrink by frame size we're throwing out */ - jb->info.current -= frame->ms; - jb->info.frames_out++; - decrement_losspct(jb); - jb->info.frames_dropped++; - _debug("Shrink by frame size we're throwing out"); - return JB_DROP; - } else { - /* shrink by last_voice_ms */ - jb->info.current -= jb->info.last_voice_ms; - jb->info.frames_lost++; - increment_losspct(jb); - jb_dbg("S"); - _debug("No frames, shrink by last_voice_ms"); - return JB_NOFRAME; - } - } - - /* lost frame */ - if (!frame) { - /* this is a bit of a hack for now, but if we're close to - * target, and we find a missing frame, it makes sense to - * grow, because the frame might just be a bit late; - * otherwise, we presently get into a pattern where we return - * INTERP for the lost frame, then it shows up next, and we - * throw it away because it's late */ - /* I've recently only been able to replicate this using - * iaxclient talking to app_echo on asterisk. In this case, - * my outgoing packets go through asterisk's (old) - * jitterbuffer, and then might get an unusual increasing delay - * there if it decides to grow?? */ - /* Update: that might have been a different bug, that has been fixed.. - * But, this still seemed like a good idea, except that it ended up making a single actual - * lost frame get interpolated two or more times, when there was "room" to grow, so it might - * be a bit of a bad idea overall */ - /*if (diff > -1 * jb->info.last_voice_ms) { - jb->info.current += jb->info.last_voice_ms; - jb->info.last_adjustment = now; - jb_warn("g"); - return JB_INTERP; - } */ - jb->info.frames_lost++; - increment_losspct(jb); - jb->info.next_voice_ts += interpl; - jb->info.last_voice_ms = interpl; - jb->info.cnt_contig_interp++; - if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) { - jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current; - } - - return JB_INTERP; - } - - /* normal case; return the frame, increment stuff */ - *frameout = *frame; - jb->info.next_voice_ts += frame->ms; - jb->info.frames_out++; - jb->info.cnt_contig_interp = 0; - decrement_losspct(jb); - jb_dbg("v"); - return JB_OK; - } else { - - _debug("Silence???\n"); - /* TODO: after we get the non-silent case down, we'll make the - * silent case -- basically, we'll just grow and shrink faster - * here, plus handle next_voice_ts a bit differently */ - - /* to disable silent special case altogether, just uncomment this: */ - /* jb->info.silence_begin_ts = 0; */ - - /* shrink interpl len every 10ms during silence */ - if (diff < -jb->info.conf.target_extra && - jb->info.last_adjustment + 10 <= now) { - jb->info.current -= interpl; - jb->info.last_adjustment = now; - } - - frame = queue_get(jb, now - jb->info.current); - if (!frame) { - return JB_NOFRAME; - } else if (frame->type != JB_TYPE_VOICE) { - /* normal case; in silent mode, got a non-voice frame */ - *frameout = *frame; - jb->info.frames_out++; - return JB_OK; - } - if (frame->ts < jb->info.silence_begin_ts) { - /* voice frame is late */ - *frameout = *frame; - jb->info.frames_out++; - decrement_losspct(jb); - jb->info.frames_late++; - jb->info.frames_lost--; - jb_dbg("l"); - /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb)); - jb_warninfo(jb); */ - return JB_DROP; - } else { - /* voice frame */ - /* try setting current to target right away here */ - jb->info.current = jb->info.target; - jb->info.silence_begin_ts = 0; - jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms; - jb->info.last_voice_ms = frame->ms; - jb->info.frames_out++; - decrement_losspct(jb); - *frameout = *frame; - jb_dbg("V"); - return JB_OK; - } - } + jb_frame *frame; + long diff; + static int dbg_cnt = 0; + + _debug ("_jb_get\n"); + + /*if ((now - jb_next(jb)) > 2 * jb->info.last_voice_ms) jb_warn("SCHED: %ld", (now - jb_next(jb))); */ + /* get jitter info */ + history_get (jb); + + if (dbg_cnt && dbg_cnt % 50 == 0) { + jb_dbg ("\n"); + } + + dbg_cnt++; + + /* target */ + jb->info.target = jb->info.jitter + jb->info.min + jb->info.conf.target_extra; + + /* if a hard clamp was requested, use it */ + if ( (jb->info.conf.max_jitterbuf) && ( (jb->info.target - jb->info.min) > jb->info.conf.max_jitterbuf)) { + _debug ("clamping target from %ld to %ld\n", (jb->info.target - jb->info.min), jb->info.conf.max_jitterbuf); + jb->info.target = jb->info.min + jb->info.conf.max_jitterbuf; + } + + diff = jb->info.target - jb->info.current; + + _debug ("diff = %ld lms=%ld last = %ld now = %ld, djust delay = %ld\n", diff, + jb->info.last_voice_ms, jb->info.last_adjustment, now); + + /* let's work on non-silent case first */ + if (!jb->info.silence_begin_ts) { + + /* + if(diff > 0) + printf("diff > 0\n"); + + if((jb->info.last_adjustment + JB_ADJUST_DELAY) < now) + printf("(jb->info.last_adjustment + JB_ADJUST_DELAY) < now\n"); + + if((diff > queue_last(jb) - queue_next(jb))) + printf("diff > queue_last(jb) - queue_next(jb)\n"); + */ + _debug ("** Non-silent case update timing info **\n"); + _debug ("diff %ld\n", diff); + _debug ("jb->info.last_adjustment %ld\n", jb->info.last_adjustment); + _debug ("JB_ADJUST_DELAY %ld\n", JB_ADJUST_DELAY); + _debug ("now %ld\n", now); + + /* we want to grow */ + if ( (diff > 0) && + /* we haven't grown in the delay length */ + ( ( (jb->info.last_adjustment + JB_ADJUST_DELAY) < now) || + /* we need to grow more than the "length" we have left */ + (diff > queue_last (jb) - queue_next (jb)))) { + + + + + /* grow by interp frame length */ + jb->info.current += interpl; + jb->info.next_voice_ts += interpl; + jb->info.last_voice_ms = interpl; + jb->info.last_adjustment = now; + jb->info.cnt_contig_interp++; + + if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) { + jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current; + } + + _debug ("Non silent case\n"); + return JB_INTERP; + } + + _debug ("queue get\n"); + + frame = queue_get (jb, jb->info.next_voice_ts - jb->info.current); + + if (!frame) + _debug ("frame not valid\n"); + + /* not a voice frame; just return it. */ + if (frame && frame->type != JB_TYPE_VOICE) { + if (frame->type == JB_TYPE_SILENCE) { + jb->info.silence_begin_ts = frame->ts; + jb->info.cnt_contig_interp = 0; + } + + *frameout = *frame; + jb->info.frames_out++; + _debug ("Not a voice packet\n"); + return JB_OK; + } + + + /* voice frame is later than expected */ + if (frame && frame->ts + jb->info.current < jb->info.next_voice_ts) { + if (frame->ts + jb->info.current > jb->info.next_voice_ts - jb->info.last_voice_ms) { + /* either we interpolated past this frame in the last jb_get */ + /* or the frame is still in order, but came a little too quick */ + *frameout = *frame; + /* reset expectation for next frame */ + jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms; + jb->info.frames_out++; + decrement_losspct (jb); + jb->info.cnt_contig_interp = 0; + _debug ("Either we interpolated past this frame in the last jb_get" \ + "or the frame is still in order, but came a little too quick\n"); + return JB_OK; + } else { + /* voice frame is late */ + *frameout = *frame; + jb->info.frames_out++; + decrement_losspct (jb); + jb->info.frames_late++; + jb->info.frames_lost--; + _debug ("Voice frame is late\n"); + _debug ("late: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next (jb)); + return JB_DROP; + } + } + + /* keep track of frame sizes, to allow for variable sized-frames */ + if (frame && frame->ms > 0) { + jb->info.last_voice_ms = frame->ms; + } + + /* we want to shrink; shrink at 1 frame / 500ms */ + + /* unless we don't have a frame, then shrink 1 frame */ + + /* every 80ms (though perhaps we can shrink even faster */ + + /* in this case) */ + if (diff < -jb->info.conf.target_extra && + ( (!frame && jb->info.last_adjustment + 80 < now) || + (jb->info.last_adjustment + 500 < now))) { + + jb->info.last_adjustment = now; + jb->info.cnt_contig_interp = 0; + + if (frame) { + *frameout = *frame; + /* shrink by frame size we're throwing out */ + jb->info.current -= frame->ms; + jb->info.frames_out++; + decrement_losspct (jb); + jb->info.frames_dropped++; + _debug ("Shrink by frame size we're throwing out"); + return JB_DROP; + } else { + /* shrink by last_voice_ms */ + jb->info.current -= jb->info.last_voice_ms; + jb->info.frames_lost++; + increment_losspct (jb); + jb_dbg ("S"); + _debug ("No frames, shrink by last_voice_ms"); + return JB_NOFRAME; + } + } + + /* lost frame */ + if (!frame) { + /* this is a bit of a hack for now, but if we're close to + * target, and we find a missing frame, it makes sense to + * grow, because the frame might just be a bit late; + * otherwise, we presently get into a pattern where we return + * INTERP for the lost frame, then it shows up next, and we + * throw it away because it's late */ + /* I've recently only been able to replicate this using + * iaxclient talking to app_echo on asterisk. In this case, + * my outgoing packets go through asterisk's (old) + * jitterbuffer, and then might get an unusual increasing delay + * there if it decides to grow?? */ + /* Update: that might have been a different bug, that has been fixed.. + * But, this still seemed like a good idea, except that it ended up making a single actual + * lost frame get interpolated two or more times, when there was "room" to grow, so it might + * be a bit of a bad idea overall */ + /*if (diff > -1 * jb->info.last_voice_ms) { + jb->info.current += jb->info.last_voice_ms; + jb->info.last_adjustment = now; + jb_warn("g"); + return JB_INTERP; + } */ + jb->info.frames_lost++; + increment_losspct (jb); + jb->info.next_voice_ts += interpl; + jb->info.last_voice_ms = interpl; + jb->info.cnt_contig_interp++; + + if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) { + jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current; + } + + return JB_INTERP; + } + + /* normal case; return the frame, increment stuff */ + *frameout = *frame; + jb->info.next_voice_ts += frame->ms; + jb->info.frames_out++; + jb->info.cnt_contig_interp = 0; + decrement_losspct (jb); + jb_dbg ("v"); + return JB_OK; + } else { + + _debug ("Silence???\n"); + /* TODO: after we get the non-silent case down, we'll make the + * silent case -- basically, we'll just grow and shrink faster + * here, plus handle next_voice_ts a bit differently */ + + /* to disable silent special case altogether, just uncomment this: */ + /* jb->info.silence_begin_ts = 0; */ + + /* shrink interpl len every 10ms during silence */ + if (diff < -jb->info.conf.target_extra && + jb->info.last_adjustment + 10 <= now) { + jb->info.current -= interpl; + jb->info.last_adjustment = now; + } + + frame = queue_get (jb, now - jb->info.current); + + if (!frame) { + return JB_NOFRAME; + } else if (frame->type != JB_TYPE_VOICE) { + /* normal case; in silent mode, got a non-voice frame */ + *frameout = *frame; + jb->info.frames_out++; + return JB_OK; + } + + if (frame->ts < jb->info.silence_begin_ts) { + /* voice frame is late */ + *frameout = *frame; + jb->info.frames_out++; + decrement_losspct (jb); + jb->info.frames_late++; + jb->info.frames_lost--; + jb_dbg ("l"); + /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb)); + jb_warninfo(jb); */ + return JB_DROP; + } else { + /* voice frame */ + /* try setting current to target right away here */ + jb->info.current = jb->info.target; + jb->info.silence_begin_ts = 0; + jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms; + jb->info.last_voice_ms = frame->ms; + jb->info.frames_out++; + decrement_losspct (jb); + *frameout = *frame; + jb_dbg ("V"); + return JB_OK; + } + } } -long jb_next(jitterbuf *jb) +long jb_next (jitterbuf *jb) { - if (jb->info.silence_begin_ts) { - if (jb->frames) { - long next = queue_next(jb); - history_get(jb); - /* shrink during silence */ - if (jb->info.target - jb->info.current < -jb->info.conf.target_extra) - return jb->info.last_adjustment + 10; - return next + jb->info.target; - } - else - return JB_LONGMAX; - } else { - return jb->info.next_voice_ts; - } + if (jb->info.silence_begin_ts) { + if (jb->frames) { + long next = queue_next (jb); + history_get (jb); + + /* shrink during silence */ + if (jb->info.target - jb->info.current < -jb->info.conf.target_extra) + return jb->info.last_adjustment + 10; + + return next + jb->info.target; + } else + return JB_LONGMAX; + } else { + return jb->info.next_voice_ts; + } } -enum jb_return_code jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl) +enum jb_return_code jb_get (jitterbuf *jb, jb_frame *frameout, long now, long interpl) { - _debug("\n***** JB_GET *****\n\n"); + _debug ("\n***** JB_GET *****\n\n"); - enum jb_return_code ret = _jb_get(jb, frameout, now, interpl); + enum jb_return_code ret = _jb_get (jb, frameout, now, interpl); #if 0 - static int lastts=0; - int thists = ((ret == JB_OK) || (ret == JB_DROP)) ? frameout->ts : 0; - jb_warn("jb_get(%x,%x,%ld) = %d (%d)\n", jb, frameout, now, ret, thists); - if (thists && thists < lastts) jb_warn("XXXX timestamp roll-back!!!\n"); - lastts = thists; + static int lastts=0; + int thists = ( (ret == JB_OK) || (ret == JB_DROP)) ? frameout->ts : 0; + jb_warn ("jb_get(%x,%x,%ld) = %d (%d)\n", jb, frameout, now, ret, thists); + + if (thists && thists < lastts) jb_warn ("XXXX timestamp roll-back!!!\n"); + + lastts = thists; #endif - if (ret == JB_INTERP) - frameout->ms = jb->info.last_voice_ms; - - return ret; + + if (ret == JB_INTERP) + frameout->ms = jb->info.last_voice_ms; + + return ret; } -enum jb_return_code jb_getall(jitterbuf *jb, jb_frame *frameout) +enum jb_return_code jb_getall (jitterbuf *jb, jb_frame *frameout) { - jb_frame *frame; - frame = queue_getall(jb); + jb_frame *frame; + frame = queue_getall (jb); - if (!frame) { - return JB_NOFRAME; - } + if (!frame) { + return JB_NOFRAME; + } - *frameout = *frame; - return JB_OK; + *frameout = *frame; + return JB_OK; } -enum jb_return_code jb_getinfo(jitterbuf *jb, jb_info *stats) +enum jb_return_code jb_getinfo (jitterbuf *jb, jb_info *stats) { - history_get(jb); + history_get (jb); - *stats = jb->info; + *stats = jb->info; - return JB_OK; + return JB_OK; } -enum jb_return_code jb_setconf(jitterbuf *jb, jb_conf *conf) +enum jb_return_code jb_setconf (jitterbuf *jb, jb_conf *conf) { - /* take selected settings from the struct */ - - jb->info.conf.max_jitterbuf = conf->max_jitterbuf; - jb->info.conf.resync_threshold = conf->resync_threshold; - jb->info.conf.max_contig_interp = conf->max_contig_interp; - - /* -1 indicates use of the default JB_TARGET_EXTRA value */ - jb->info.conf.target_extra = ( conf->target_extra == -1 ) - ? JB_TARGET_EXTRA - : conf->target_extra - ; - - /* update these to match new target_extra setting */ - jb->info.current = jb->info.conf.target_extra; - jb->info.target = jb->info.conf.target_extra; - - return JB_OK; + /* take selected settings from the struct */ + + jb->info.conf.max_jitterbuf = conf->max_jitterbuf; + jb->info.conf.resync_threshold = conf->resync_threshold; + jb->info.conf.max_contig_interp = conf->max_contig_interp; + + /* -1 indicates use of the default JB_TARGET_EXTRA value */ + jb->info.conf.target_extra = (conf->target_extra == -1) + ? JB_TARGET_EXTRA + : conf->target_extra + ; + + /* update these to match new target_extra setting */ + jb->info.current = jb->info.conf.target_extra; + jb->info.target = jb->info.conf.target_extra; + + return JB_OK; } diff --git a/sflphone-common/src/audio/mainbuffer.cpp b/sflphone-common/src/audio/mainbuffer.cpp index 4c15008b0d5d0ee2264bebc2b77052b25b87354d..22dce225430a6924adcc13b8947912758b58b10b 100644 --- a/sflphone-common/src/audio/mainbuffer.cpp +++ b/sflphone-common/src/audio/mainbuffer.cpp @@ -42,13 +42,14 @@ MainBuffer::MainBuffer() : _internalSamplingRate (8000) MainBuffer::~MainBuffer() { - delete [] mixBuffer; mixBuffer = NULL; + delete [] mixBuffer; + mixBuffer = NULL; } void MainBuffer::setInternalSamplingRate (int sr) { - // ost::MutexLock guard (_mutex); + // ost::MutexLock guard (_mutex); if (sr != _internalSamplingRate) { @@ -56,7 +57,7 @@ void MainBuffer::setInternalSamplingRate (int sr) flushAllBuffers(); - Manager::instance().audioSamplingRateChanged(); + Manager::instance().audioSamplingRateChanged(); } } @@ -92,7 +93,8 @@ bool MainBuffer::removeCallIDSet (CallID set_id) if (callid_set != NULL) { if (_callIDMap.erase (set_id) != 0) { - delete callid_set; callid_set = NULL; + delete callid_set; + callid_set = NULL; return true; } else { _debug ("removeCallIDSet error while removing callid set %s!", set_id.c_str()); @@ -160,7 +162,7 @@ bool MainBuffer::removeRingBuffer (CallID call_id) if (ring_buffer != NULL) { if (_ringBufferMap.erase (call_id) != 0) { - delete ring_buffer; + delete ring_buffer; return true; } else { _error ("BufferManager: Error: Fail to delete ringbuffer %s!", call_id.c_str()); @@ -176,7 +178,7 @@ bool MainBuffer::removeRingBuffer (CallID call_id) void MainBuffer::bindCallID (CallID call_id1, CallID call_id2) { - // ost::MutexLock guard (_mutex); + // ost::MutexLock guard (_mutex); RingBuffer* ring_buffer; CallIDSet* callid_set; @@ -203,19 +205,19 @@ void MainBuffer::bindCallID (CallID call_id1, CallID call_id2) } -void MainBuffer::bindHalfDuplexOut(CallID process_id, CallID call_id) +void MainBuffer::bindHalfDuplexOut (CallID process_id, CallID call_id) { - // This method is used only for active calls, if this call does not exist, do nothing - if(!getRingBuffer(call_id)) - return; - - if(!getCallIDSet(process_id)) - createCallIDSet(process_id); + // This method is used only for active calls, if this call does not exist, do nothing + if (!getRingBuffer (call_id)) + return; + + if (!getCallIDSet (process_id)) + createCallIDSet (process_id); - getRingBuffer(call_id)->createReadPointer(process_id); + getRingBuffer (call_id)->createReadPointer (process_id); - addCallIDtoSet(process_id, call_id); + addCallIDtoSet (process_id, call_id); } @@ -223,7 +225,7 @@ void MainBuffer::bindHalfDuplexOut(CallID process_id, CallID call_id) void MainBuffer::unBindCallID (CallID call_id1, CallID call_id2) { - // ost::MutexLock guard (_mutex); + // ost::MutexLock guard (_mutex); removeCallIDfromSet (call_id1, call_id2); removeCallIDfromSet (call_id2, call_id1); @@ -246,41 +248,41 @@ void MainBuffer::unBindCallID (CallID call_id1, CallID call_id2) ringbuffer = getRingBuffer (call_id1); if (ringbuffer) { - ringbuffer->removeReadPointer (call_id2); - - if (ringbuffer->getNbReadPointer() == 0) { - removeCallIDSet (call_id1); - removeRingBuffer (call_id1); - } + ringbuffer->removeReadPointer (call_id2); + + if (ringbuffer->getNbReadPointer() == 0) { + removeCallIDSet (call_id1); + removeRingBuffer (call_id1); + } } } -void MainBuffer::unBindHalfDuplexOut(CallID process_id, CallID call_id) +void MainBuffer::unBindHalfDuplexOut (CallID process_id, CallID call_id) { - removeCallIDfromSet(process_id, call_id); + removeCallIDfromSet (process_id, call_id); + + RingBuffer* ringbuffer = getRingBuffer (call_id); + + if (ringbuffer) { + ringbuffer->removeReadPointer (process_id); + + if (ringbuffer->getNbReadPointer() == 0) { + removeCallIDSet (call_id); + removeRingBuffer (call_id); + } + } else { + _debug ("Error: did not found ringbuffer %s", process_id.c_str()); + removeCallIDSet (process_id); + } - RingBuffer* ringbuffer = getRingBuffer(call_id); - if(ringbuffer) { - ringbuffer->removeReadPointer(process_id); + CallIDSet* callid_set = getCallIDSet (process_id); - if(ringbuffer->getNbReadPointer() == 0) { - removeCallIDSet(call_id); - removeRingBuffer(call_id); + if (callid_set) { + if (callid_set->empty()) + removeCallIDSet (process_id); } - } - else { - _debug("Error: did not found ringbuffer %s", process_id.c_str()); - removeCallIDSet(process_id); - } - - - CallIDSet* callid_set = getCallIDSet(process_id); - if(callid_set) { - if(callid_set->empty()) - removeCallIDSet(process_id); - } } @@ -312,27 +314,27 @@ void MainBuffer::unBindAll (CallID call_id) } -void MainBuffer::unBindAllHalfDuplexOut(CallID process_id) +void MainBuffer::unBindAllHalfDuplexOut (CallID process_id) { - CallIDSet* callid_set = getCallIDSet(process_id); + CallIDSet* callid_set = getCallIDSet (process_id); - if(!callid_set) - return; + if (!callid_set) + return; - if(callid_set->empty()) - return; + if (callid_set->empty()) + return; - CallIDSet temp_set = *callid_set; + CallIDSet temp_set = *callid_set; - CallIDSet::iterator iter_set = temp_set.begin(); + CallIDSet::iterator iter_set = temp_set.begin(); - while(iter_set != temp_set.end()) { - CallID call_id_in_set = *iter_set; - unBindCallID(process_id, call_id_in_set); + while (iter_set != temp_set.end()) { + CallID call_id_in_set = *iter_set; + unBindCallID (process_id, call_id_in_set); - iter_set++; - } + iter_set++; + } } @@ -397,7 +399,7 @@ int MainBuffer::getData (void *buffer, int toCopy, unsigned short volume, CallID return 0; } else { - memset(buffer, 0, nbSmplToCopy*sizeof(SFLDataFormat)); + memset (buffer, 0, nbSmplToCopy*sizeof (SFLDataFormat)); int size = 0; @@ -405,9 +407,9 @@ int MainBuffer::getData (void *buffer, int toCopy, unsigned short volume, CallID while (iter_id != callid_set->end()) { - memset(mixBuffer, 0, toCopy); + memset (mixBuffer, 0, toCopy); - size = getDataByID(mixBuffer, toCopy, volume, (CallID) (*iter_id), call_id); + size = getDataByID (mixBuffer, toCopy, volume, (CallID) (*iter_id), call_id); if (size > 0) { for (int k = 0; k < nbSmplToCopy; k++) { @@ -464,7 +466,7 @@ int MainBuffer::availForGet (CallID call_id) int nb_bytes; CallIDSet::iterator iter_id = callid_set->begin(); - syncBuffers(call_id); + syncBuffers (call_id); for (iter_id = callid_set->begin(); iter_id != callid_set->end(); iter_id++) { nb_bytes = availForGetByID (*iter_id, call_id); @@ -483,13 +485,13 @@ int MainBuffer::availForGetByID (CallID call_id, CallID reader_id) { if ( (call_id != default_id) && (reader_id == call_id)) { - _error("MainBuffer: Error: RingBuffer has a readpointer on tiself"); + _error ("MainBuffer: Error: RingBuffer has a readpointer on tiself"); } RingBuffer* ringbuffer = getRingBuffer (call_id); if (ringbuffer == NULL) { - _error("MainBuffer: Error: RingBuffer does not exist"); + _error ("MainBuffer: Error: RingBuffer does not exist"); return 0; } else return ringbuffer->AvailForGet (reader_id); @@ -545,7 +547,7 @@ int MainBuffer::discardByID (int toDiscard, CallID call_id, CallID reader_id) void MainBuffer::flush (CallID call_id) { - // ost::MutexLock guard (_mutex); + // ost::MutexLock guard (_mutex); CallIDSet* callid_set = getCallIDSet (call_id); @@ -572,7 +574,7 @@ void MainBuffer::flush (CallID call_id) void MainBuffer::flushDefault() { - // ost::MutexLock guard (_mutex); + // ost::MutexLock guard (_mutex); flushByID (default_id, default_id); @@ -602,10 +604,10 @@ void MainBuffer::flushAllBuffers() } } -void MainBuffer:: syncBuffers(CallID call_id) +void MainBuffer:: syncBuffers (CallID call_id) { - - CallIDSet* callid_set = getCallIDSet(call_id); + + CallIDSet* callid_set = getCallIDSet (call_id); if (callid_set == NULL) return; @@ -629,15 +631,16 @@ void MainBuffer:: syncBuffers(CallID call_id) // compute mean nb byte in buffers for (iter_id = callid_set->begin(); iter_id != callid_set->end(); iter_id++) { nbBuffers++; - mean_nbBytes += availForGetByID (*iter_id, call_id); + mean_nbBytes += availForGetByID (*iter_id, call_id); } + mean_nbBytes = mean_nbBytes / (float) nbBuffers; - + // resync buffers in this conference according to the computed mean for (iter_id = callid_set->begin(); iter_id != callid_set->end(); iter_id++) { - if(availForGetByID (*iter_id, call_id) > (mean_nbBytes + 640)) - discardByID (640, *iter_id, call_id); + if (availForGetByID (*iter_id, call_id) > (mean_nbBytes + 640)) + discardByID (640, *iter_id, call_id); } } diff --git a/sflphone-common/src/audio/pulseaudio/audiostream.cpp b/sflphone-common/src/audio/pulseaudio/audiostream.cpp index 8898fcdc39a8187dd46230c85d764b85c9a7bafa..23729214652aaf485b5805b20a238d28db077857 100644 --- a/sflphone-common/src/audio/pulseaudio/audiostream.cpp +++ b/sflphone-common/src/audio/pulseaudio/audiostream.cpp @@ -58,12 +58,12 @@ AudioStream::~AudioStream() } bool -AudioStream::connectStream(std::string* deviceName) +AudioStream::connectStream (std::string* deviceName) { ost::MutexLock guard (_mutex); if (!_audiostream) - _audiostream = createStream (_context, deviceName); + _audiostream = createStream (_context, deviceName); return true; } @@ -82,7 +82,7 @@ bool AudioStream::drainStream (void) { if (_audiostream) { - _info("Audio: Draining stream"); + _info ("Audio: Draining stream"); pa_operation * operation; pa_threaded_mainloop_lock (_mainloop); @@ -90,7 +90,7 @@ AudioStream::drainStream (void) if ( (operation = pa_stream_drain (_audiostream, success_cb, _mainloop))) { while (pa_operation_get_state (operation) != PA_OPERATION_DONE) { if (!_context || pa_context_get_state (_context) != PA_CONTEXT_READY || !_audiostream || pa_stream_get_state (_audiostream) != PA_STREAM_READY) { - _warn("Audio: Connection died: %s", _context ? pa_strerror (pa_context_errno (_context)) : "NULL"); + _warn ("Audio: Connection died: %s", _context ? pa_strerror (pa_context_errno (_context)) : "NULL"); pa_operation_unref (operation); break; } else { @@ -108,7 +108,7 @@ AudioStream::drainStream (void) bool AudioStream::disconnectStream (void) { - _info("Audio: Destroy audio streams"); + _info ("Audio: Destroy audio streams"); pa_threaded_mainloop_lock (_mainloop); @@ -137,7 +137,7 @@ AudioStream::stream_state_callback (pa_stream* s, void* user_data) { pa_threaded_mainloop *m; - _info("Audio: The state of the stream changed"); + _info ("Audio: The state of the stream changed"); assert (s); char str[PA_SAMPLE_SPEC_SNPRINT_MAX]; @@ -148,7 +148,7 @@ AudioStream::stream_state_callback (pa_stream* s, void* user_data) switch (pa_stream_get_state (s)) { case PA_STREAM_CREATING: - _info("Audio: Stream is creating..."); + _info ("Audio: Stream is creating..."); break; case PA_STREAM_TERMINATED: @@ -157,14 +157,14 @@ AudioStream::stream_state_callback (pa_stream* s, void* user_data) case PA_STREAM_READY: _info ("Audio: Stream successfully created, connected to %s", pa_stream_get_device_name (s)); - // pa_buffer_attr *buffattr = (pa_buffer_attr *)pa_xmalloc (sizeof(pa_buffer_attr)); - _debug("Audio: maxlength %u", pa_stream_get_buffer_attr(s)->maxlength); - _debug("Audio: tlength %u", pa_stream_get_buffer_attr(s)->tlength); - _debug("Audio: prebug %u", pa_stream_get_buffer_attr(s)->prebuf); - _debug("Audio: minreq %u", pa_stream_get_buffer_attr(s)->minreq); - _debug("Audio: fragsize %u", pa_stream_get_buffer_attr(s)->fragsize); - _debug("Audio: samplespec %s", pa_sample_spec_snprint(str, sizeof(str), pa_stream_get_sample_spec(s))); - // pa_xfree (buffattr); + // pa_buffer_attr *buffattr = (pa_buffer_attr *)pa_xmalloc (sizeof(pa_buffer_attr)); + _debug ("Audio: maxlength %u", pa_stream_get_buffer_attr (s)->maxlength); + _debug ("Audio: tlength %u", pa_stream_get_buffer_attr (s)->tlength); + _debug ("Audio: prebug %u", pa_stream_get_buffer_attr (s)->prebuf); + _debug ("Audio: minreq %u", pa_stream_get_buffer_attr (s)->minreq); + _debug ("Audio: fragsize %u", pa_stream_get_buffer_attr (s)->fragsize); + _debug ("Audio: samplespec %s", pa_sample_spec_snprint (str, sizeof (str), pa_stream_get_sample_spec (s))); + // pa_xfree (buffattr); break; case PA_STREAM_UNCONNECTED: @@ -174,7 +174,7 @@ AudioStream::stream_state_callback (pa_stream* s, void* user_data) case PA_STREAM_FAILED: default: - _warn("Audio: Error - Sink/Source doesn't exists: %s" , pa_strerror (pa_context_errno (pa_stream_get_context (s)))); + _warn ("Audio: Error - Sink/Source doesn't exists: %s" , pa_strerror (pa_context_errno (pa_stream_get_context (s)))); exit (0); break; } @@ -200,7 +200,7 @@ AudioStream::createStream (pa_context* c, std::string *deviceName) assert (pa_sample_spec_valid (&_sample_spec)); assert (pa_channel_map_valid (&channel_map)); - _info("Audio: Create pulseaudio stream"); + _info ("Audio: Create pulseaudio stream"); pa_buffer_attr* attributes = (pa_buffer_attr*) malloc (sizeof (pa_buffer_attr)); @@ -215,52 +215,53 @@ AudioStream::createStream (pa_context* c, std::string *deviceName) attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec); // -1; attributes->tlength = pa_usec_to_bytes (40 * PA_USEC_PER_MSEC, &_sample_spec); attributes->prebuf = 0; - attributes->fragsize = pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); + attributes->fragsize = pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); attributes->minreq = (uint32_t) -1; - - pa_threaded_mainloop_lock(_mainloop); - if(deviceName) - pa_stream_connect_playback (s , deviceName->c_str(), attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); - else - pa_stream_connect_playback (s , NULL, attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); + pa_threaded_mainloop_lock (_mainloop); + + if (deviceName) + pa_stream_connect_playback (s , deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); + else + pa_stream_connect_playback (s , NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); - pa_threaded_mainloop_unlock(_mainloop); + pa_threaded_mainloop_unlock (_mainloop); } else if (_streamType == CAPTURE_STREAM) { - attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec);// (uint32_t) -1; - attributes->tlength = pa_usec_to_bytes (40 * PA_USEC_PER_MSEC, &_sample_spec);// pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); - attributes->prebuf = 0; + attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec);// (uint32_t) -1; + attributes->tlength = pa_usec_to_bytes (40 * PA_USEC_PER_MSEC, &_sample_spec);// pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); + attributes->prebuf = 0; attributes->fragsize = pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); // pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); - attributes->minreq = (uint32_t) -1; + attributes->minreq = (uint32_t) -1; + + pa_threaded_mainloop_lock (_mainloop); - pa_threaded_mainloop_lock(_mainloop); + if (deviceName) + pa_stream_connect_record (s, deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); + else + pa_stream_connect_record (s, NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); - if(deviceName) - pa_stream_connect_record (s, deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); - else - pa_stream_connect_record (s, NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); + pa_threaded_mainloop_unlock (_mainloop); - pa_threaded_mainloop_unlock(_mainloop); - } else if (_streamType == RINGTONE_STREAM) { - attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec);; - attributes->tlength = pa_usec_to_bytes(40 * PA_USEC_PER_MSEC, &_sample_spec); - attributes->prebuf = 0; - attributes->fragsize = pa_usec_to_bytes(20 * PA_USEC_PER_MSEC, &_sample_spec); - attributes->minreq = (uint32_t) -1; + attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec);; + attributes->tlength = pa_usec_to_bytes (40 * PA_USEC_PER_MSEC, &_sample_spec); + attributes->prebuf = 0; + attributes->fragsize = pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); + attributes->minreq = (uint32_t) -1; - pa_threaded_mainloop_lock(_mainloop); - if(deviceName) - pa_stream_connect_playback(s, deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); - else - pa_stream_connect_playback(s, NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY), NULL, NULL); + pa_threaded_mainloop_lock (_mainloop); + + if (deviceName) + pa_stream_connect_playback (s, deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); + else + pa_stream_connect_playback (s, NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY), NULL, NULL); - pa_threaded_mainloop_unlock(_mainloop); + pa_threaded_mainloop_unlock (_mainloop); } else if (_streamType == UPLOAD_STREAM) { pa_stream_connect_upload (s , 1024); diff --git a/sflphone-common/src/audio/pulseaudio/pulselayer.cpp b/sflphone-common/src/audio/pulseaudio/pulselayer.cpp old mode 100755 new mode 100644 index 0d9afc8c9d03f522de46c86733fc077765fbd923..a4638126a4b60a416e8e60da7da0c4d2befb4988 --- a/sflphone-common/src/audio/pulseaudio/pulselayer.cpp +++ b/sflphone-common/src/audio/pulseaudio/pulselayer.cpp @@ -36,7 +36,8 @@ int framesPerBuffer = 2048; -static void playback_callback (pa_stream* s, size_t bytes, void* userdata) { +static void playback_callback (pa_stream* s, size_t bytes, void* userdata) +{ assert (s && bytes); assert (bytes > 0); @@ -44,170 +45,176 @@ static void playback_callback (pa_stream* s, size_t bytes, void* userdata) { } -static void capture_callback (pa_stream* s, size_t bytes, void* userdata) { +static void capture_callback (pa_stream* s, size_t bytes, void* userdata) +{ assert (s && bytes); assert (bytes > 0); static_cast<PulseLayer*> (userdata)->processCaptureData(); - + } -static void ringtone_callback (pa_stream* s, size_t bytes, void* userdata) { +static void ringtone_callback (pa_stream* s, size_t bytes, void* userdata) +{ - assert(s && bytes); - assert(bytes > 0); + assert (s && bytes); + assert (bytes > 0); static_cast<PulseLayer*> (userdata)->processRingtoneData(); } -static void stream_moved_callback(pa_stream *s, void *userdata UNUSED) { +static void stream_moved_callback (pa_stream *s, void *userdata UNUSED) +{ - _debug("stream_moved_callback: stream %d to %d", pa_stream_get_index(s), pa_stream_get_device_index(s)); + _debug ("stream_moved_callback: stream %d to %d", pa_stream_get_index (s), pa_stream_get_device_index (s)); } -static void latency_update_callback(pa_stream *p, void *userdata UNUSED) { +static void latency_update_callback (pa_stream *p, void *userdata UNUSED) +{ pa_usec_t r_usec; - pa_stream_get_latency (p, &r_usec, NULL); + pa_stream_get_latency (p, &r_usec, NULL); + + _debug ("Audio: Stream letency update %0.0f ms for device %s", (float) r_usec/1000, pa_stream_get_device_name (p)); + _debug ("Audio: maxlength %u", pa_stream_get_buffer_attr (p)->maxlength); + _debug ("Audio: tlength %u", pa_stream_get_buffer_attr (p)->tlength); + _debug ("Audio: prebuf %u", pa_stream_get_buffer_attr (p)->prebuf); + _debug ("Audio: minreq %u", pa_stream_get_buffer_attr (p)->minreq); + _debug ("Audio: fragsize %u", pa_stream_get_buffer_attr (p)->fragsize); - _debug("Audio: Stream letency update %0.0f ms for device %s", (float)r_usec/1000, pa_stream_get_device_name(p)); - _debug("Audio: maxlength %u", pa_stream_get_buffer_attr(p)->maxlength); - _debug("Audio: tlength %u", pa_stream_get_buffer_attr(p)->tlength); - _debug("Audio: prebuf %u", pa_stream_get_buffer_attr(p)->prebuf); - _debug("Audio: minreq %u", pa_stream_get_buffer_attr(p)->minreq); - _debug("Audio: fragsize %u", pa_stream_get_buffer_attr(p)->fragsize); - } -static void sink_input_info_callback(pa_context *c UNUSED, const pa_sink_info *i, int eol, void *userdata) { - char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; - - if(!eol) { - - printf("Sink %u\n" - " Name: %s\n" - " Driver: %s\n" - " Description: %s\n" - " Sample Specification: %s\n" - " Channel Map: %s\n" - " Owner Module: %u\n" - " Volume: %s\n" - " Monitor Source: %u\n" - " Latency: %0.0f usec\n" - " Flags: %s%s%s\n", - i->index, - i->name, - i->driver, - i->description, - pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec), - pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map), - i->owner_module, - i->mute ? "muted" : pa_cvolume_snprint(cv, sizeof(cv), &i->volume), - i->monitor_source, - (double) i->latency, - i->flags & PA_SINK_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", - i->flags & PA_SINK_LATENCY ? "LATENCY " : "", - i->flags & PA_SINK_HARDWARE ? "HARDWARE" : ""); - - std::string deviceName(i->name); - ((PulseLayer *)userdata)->getSinkList()->push_back(deviceName); - - } +static void sink_input_info_callback (pa_context *c UNUSED, const pa_sink_info *i, int eol, void *userdata) +{ + char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; + + if (!eol) { + + printf ("Sink %u\n" + " Name: %s\n" + " Driver: %s\n" + " Description: %s\n" + " Sample Specification: %s\n" + " Channel Map: %s\n" + " Owner Module: %u\n" + " Volume: %s\n" + " Monitor Source: %u\n" + " Latency: %0.0f usec\n" + " Flags: %s%s%s\n", + i->index, + i->name, + i->driver, + i->description, + pa_sample_spec_snprint (s, sizeof (s), &i->sample_spec), + pa_channel_map_snprint (cm, sizeof (cm), &i->channel_map), + i->owner_module, + i->mute ? "muted" : pa_cvolume_snprint (cv, sizeof (cv), &i->volume), + i->monitor_source, + (double) i->latency, + i->flags & PA_SINK_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", + i->flags & PA_SINK_LATENCY ? "LATENCY " : "", + i->flags & PA_SINK_HARDWARE ? "HARDWARE" : ""); + + std::string deviceName (i->name); + ( (PulseLayer *) userdata)->getSinkList()->push_back (deviceName); + + } } -static void source_input_info_callback(pa_context *c UNUSED, const pa_source_info *i, int eol, void *userdata) { +static void source_input_info_callback (pa_context *c UNUSED, const pa_source_info *i, int eol, void *userdata) +{ char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; - if(!eol) { - - printf("Sink %u\n" - " Name: %s\n" - " Driver: %s\n" - " Description: %s\n" - " Sample Specification: %s\n" - " Channel Map: %s\n" - " Owner Module: %u\n" - " Volume: %s\n" - " Monitor if Sink: %u\n" - " Latency: %0.0f usec\n" - " Flags: %s%s%s\n", - i->index, - i->name, - i->driver, - i->description, - pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec), - pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map), - i->owner_module, - i->mute ? "muted" : pa_cvolume_snprint(cv, sizeof(cv), &i->volume), - i->monitor_of_sink, - (double) i->latency, - i->flags & PA_SOURCE_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", - i->flags & PA_SOURCE_LATENCY ? "LATENCY " : "", - i->flags & PA_SOURCE_HARDWARE ? "HARDWARE" : ""); - - std::string deviceName(i->name); - ((PulseLayer *)userdata)->getSourceList()->push_back(deviceName); - - } + if (!eol) { + + printf ("Sink %u\n" + " Name: %s\n" + " Driver: %s\n" + " Description: %s\n" + " Sample Specification: %s\n" + " Channel Map: %s\n" + " Owner Module: %u\n" + " Volume: %s\n" + " Monitor if Sink: %u\n" + " Latency: %0.0f usec\n" + " Flags: %s%s%s\n", + i->index, + i->name, + i->driver, + i->description, + pa_sample_spec_snprint (s, sizeof (s), &i->sample_spec), + pa_channel_map_snprint (cm, sizeof (cm), &i->channel_map), + i->owner_module, + i->mute ? "muted" : pa_cvolume_snprint (cv, sizeof (cv), &i->volume), + i->monitor_of_sink, + (double) i->latency, + i->flags & PA_SOURCE_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", + i->flags & PA_SOURCE_LATENCY ? "LATENCY " : "", + i->flags & PA_SOURCE_HARDWARE ? "HARDWARE" : ""); + + std::string deviceName (i->name); + ( (PulseLayer *) userdata)->getSourceList()->push_back (deviceName); + + } } -static void context_changed_callback(pa_context* c, pa_subscription_event_type_t t, uint32_t idx UNUSED, void* userdata UNUSED) +static void context_changed_callback (pa_context* c, pa_subscription_event_type_t t, uint32_t idx UNUSED, void* userdata UNUSED) { - switch(t) { - - case PA_SUBSCRIPTION_EVENT_SINK: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SINK"); - ((PulseLayer *)userdata)->getSinkList()->clear(); - pa_context_get_sink_info_list(c, sink_input_info_callback, userdata); - break; - case PA_SUBSCRIPTION_EVENT_SOURCE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SOURCE"); - ((PulseLayer *)userdata)->getSourceList()->clear(); - pa_context_get_source_info_list(c, source_input_info_callback, userdata); - break; - case PA_SUBSCRIPTION_EVENT_SINK_INPUT: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SINK_INPUT"); - break; - case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT"); - break; - case PA_SUBSCRIPTION_EVENT_MODULE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_MODULE"); - break; - case PA_SUBSCRIPTION_EVENT_CLIENT: - _debug("Audio: PA_SUBSCRIPTION_EVENT_CLIENT"); - break; - case PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE"); - break; - case PA_SUBSCRIPTION_EVENT_SERVER: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SERVER"); - break; - case PA_SUBSCRIPTION_EVENT_CARD: - _debug("Audio: PA_SUBSCRIPTION_EVENT_CARD"); - break; - case PA_SUBSCRIPTION_EVENT_FACILITY_MASK: - _debug("Audio: PA_SUBSCRIPTION_EVENT_FACILITY_MASK"); - break; - case PA_SUBSCRIPTION_EVENT_CHANGE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_CHANGE"); - break; - case PA_SUBSCRIPTION_EVENT_REMOVE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_REMOVE"); - ((PulseLayer *)userdata)->getSinkList()->clear(); - ((PulseLayer *)userdata)->getSourceList()->clear(); - pa_context_get_sink_info_list(c, sink_input_info_callback, userdata); - pa_context_get_source_info_list(c, source_input_info_callback, userdata); - break; - case PA_SUBSCRIPTION_EVENT_TYPE_MASK: - _debug("Audio: PA_SUBSCRIPTION_EVENT_TYPE_MASK"); - break; - default: - _debug("Audio: Unknown event type"); - - } + switch (t) { + + case PA_SUBSCRIPTION_EVENT_SINK: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SINK"); + ( (PulseLayer *) userdata)->getSinkList()->clear(); + pa_context_get_sink_info_list (c, sink_input_info_callback, userdata); + break; + case PA_SUBSCRIPTION_EVENT_SOURCE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SOURCE"); + ( (PulseLayer *) userdata)->getSourceList()->clear(); + pa_context_get_source_info_list (c, source_input_info_callback, userdata); + break; + case PA_SUBSCRIPTION_EVENT_SINK_INPUT: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SINK_INPUT"); + break; + case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT"); + break; + case PA_SUBSCRIPTION_EVENT_MODULE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_MODULE"); + break; + case PA_SUBSCRIPTION_EVENT_CLIENT: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_CLIENT"); + break; + case PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE"); + break; + case PA_SUBSCRIPTION_EVENT_SERVER: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SERVER"); + break; + case PA_SUBSCRIPTION_EVENT_CARD: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_CARD"); + break; + case PA_SUBSCRIPTION_EVENT_FACILITY_MASK: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_FACILITY_MASK"); + break; + case PA_SUBSCRIPTION_EVENT_CHANGE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_CHANGE"); + break; + case PA_SUBSCRIPTION_EVENT_REMOVE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_REMOVE"); + ( (PulseLayer *) userdata)->getSinkList()->clear(); + ( (PulseLayer *) userdata)->getSourceList()->clear(); + pa_context_get_sink_info_list (c, sink_input_info_callback, userdata); + pa_context_get_source_info_list (c, source_input_info_callback, userdata); + break; + case PA_SUBSCRIPTION_EVENT_TYPE_MASK: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_TYPE_MASK"); + break; + default: + _debug ("Audio: Unknown event type"); + + } } static void playback_underflow_callback (pa_stream* s UNUSED, void* userdata UNUSED) @@ -224,12 +231,12 @@ PulseLayer::PulseLayer (ManagerImpl* manager) : AudioLayer (manager , PULSEAUDIO) , context (NULL) , m (NULL) - , playback(NULL) - , record(NULL) - , ringtone(NULL) + , playback (NULL) + , record (NULL) + , ringtone (NULL) { _urgentRingBuffer.createReadPointer(); - + is_started = false; AudioLayer::_echocancelstate = true; @@ -257,7 +264,7 @@ PulseLayer::~PulseLayer (void) delete AudioLayer::_echoCancel; AudioLayer::_echoCancel = NULL; - + delete AudioLayer::_echoCanceller; AudioLayer::_echoCanceller = NULL; @@ -283,11 +290,11 @@ PulseLayer::openLayer (void) { if (!is_started) { - _info("Audio: Open Pulseaudio layer"); + _info ("Audio: Open Pulseaudio layer"); - connectPulseAudioServer(); + connectPulseAudioServer(); - is_started = true; + is_started = true; } @@ -296,10 +303,10 @@ PulseLayer::openLayer (void) bool PulseLayer::closeLayer (void) { - _info("Audio: Close Pulseaudio layer"); + _info ("Audio: Close Pulseaudio layer"); disconnectAudioStream(); - + if (m) { pa_threaded_mainloop_stop (m); } @@ -322,62 +329,64 @@ PulseLayer::closeLayer (void) void PulseLayer::connectPulseAudioServer (void) { - _info("Audio: Connect to Pulseaudio server"); + _info ("Audio: Connect to Pulseaudio server"); setenv ("PULSE_PROP_media.role", "phone", 1); pa_context_flags_t flag = PA_CONTEXT_NOAUTOSPAWN ; if (!m) { - - // Instantiate a mainloop - _info("Audio: Creating PulseAudio mainloop"); - if (!(m = pa_threaded_mainloop_new())) - _warn ("Audio: Error: while creating pulseaudio mainloop"); - - assert(m); + + // Instantiate a mainloop + _info ("Audio: Creating PulseAudio mainloop"); + + if (! (m = pa_threaded_mainloop_new())) + _warn ("Audio: Error: while creating pulseaudio mainloop"); + + assert (m); } - if(!context) { + if (!context) { // Instantiate a context if (! (context = pa_context_new (pa_threaded_mainloop_get_api (m) , "SFLphone"))) - _warn ("Audio: Error: while creating pulseaudio context"); + _warn ("Audio: Error: while creating pulseaudio context"); - assert(context); + assert (context); } // set context state callback before starting the mainloop pa_context_set_state_callback (context, context_state_callback, this); - _info("Audio: Connect the context to the server"); + _info ("Audio: Connect the context to the server"); + if (pa_context_connect (context, NULL , flag , NULL) < 0) { - _warn("Audio: Error: Could not connect context to the server"); + _warn ("Audio: Error: Could not connect context to the server"); } // Lock the loop before starting it pa_threaded_mainloop_lock (m); if (pa_threaded_mainloop_start (m) < 0) - _warn("Audio: Error: Failed to start pulseaudio mainloop"); + _warn ("Audio: Error: Failed to start pulseaudio mainloop"); + + pa_threaded_mainloop_wait (m); + - pa_threaded_mainloop_wait(m); - - // Run the main loop if (pa_context_get_state (context) != PA_CONTEXT_READY) { - _warn("Audio: Error: connecting to pulse audio server"); + _warn ("Audio: Error: connecting to pulse audio server"); } pa_threaded_mainloop_unlock (m); - _info("Audio: Context creation done"); + _info ("Audio: Context creation done"); } void PulseLayer::context_state_callback (pa_context* c, void* user_data) { - _info("Audio: The state of the context changed"); + _info ("Audio: The state of the context changed"); PulseLayer* pulse = (PulseLayer*) user_data; assert (c && pulse->m); @@ -393,11 +402,11 @@ void PulseLayer::context_state_callback (pa_context* c, void* user_data) case PA_CONTEXT_READY: _debug ("Audio: Connection to PulseAudio server established"); - pa_threaded_mainloop_signal(pulse->m, 0); - pa_context_subscribe (c, (pa_subscription_mask_t)(PA_SUBSCRIPTION_MASK_SINK| - PA_SUBSCRIPTION_MASK_SOURCE), NULL, pulse); - pa_context_set_subscribe_callback (c, context_changed_callback, pulse); - pulse->updateSinkList(); + pa_threaded_mainloop_signal (pulse->m, 0); + pa_context_subscribe (c, (pa_subscription_mask_t) (PA_SUBSCRIPTION_MASK_SINK| + PA_SUBSCRIPTION_MASK_SOURCE), NULL, pulse); + pa_context_set_subscribe_callback (c, context_changed_callback, pulse); + pulse->updateSinkList(); break; case PA_CONTEXT_TERMINATED: @@ -407,7 +416,7 @@ void PulseLayer::context_state_callback (pa_context* c, void* user_data) case PA_CONTEXT_FAILED: default: - _warn("Audio: Error : %s" , pa_strerror (pa_context_errno (c))); + _warn ("Audio: Error : %s" , pa_strerror (pa_context_errno (c))); pulse->disconnectAudioStream(); exit (0); break; @@ -425,74 +434,78 @@ bool PulseLayer::openDevice (int indexIn UNUSED, int indexOut UNUSED, int indexR _converter = new SamplerateConverter (_audioSampleRate, 1000); // Instantiate the algorithm - AudioLayer::_echoCancel = new EchoCancel(_audioSampleRate, _frameSize); - AudioLayer::_echoCanceller = new AudioProcessing(static_cast<Algorithm *>(_echoCancel)); + AudioLayer::_echoCancel = new EchoCancel (_audioSampleRate, _frameSize); + AudioLayer::_echoCanceller = new AudioProcessing (static_cast<Algorithm *> (_echoCancel)); AudioLayer::_dcblocker = new DcBlocker(); - AudioLayer::_audiofilter = new AudioProcessing(static_cast<Algorithm *>(_dcblocker)); + AudioLayer::_audiofilter = new AudioProcessing (static_cast<Algorithm *> (_dcblocker)); return true; } -void PulseLayer::updateSinkList(void) { +void PulseLayer::updateSinkList (void) +{ - _debug("Audio: Update sink list"); + _debug ("Audio: Update sink list"); - getSinkList()->clear(); + getSinkList()->clear(); - pa_context_get_sink_info_list(context, sink_input_info_callback, this); + pa_context_get_sink_info_list (context, sink_input_info_callback, this); } -void PulseLayer::updateSourceList(void) { - _debug("Audio: Update source list"); +void PulseLayer::updateSourceList (void) +{ + _debug ("Audio: Update source list"); - getSourceList()->clear(); + getSourceList()->clear(); - pa_context_get_source_info_list(context, source_input_info_callback, this); + pa_context_get_source_info_list (context, source_input_info_callback, this); } -bool PulseLayer::inSinkList(std::string deviceName) { - // _debug("Audio: in device list %s", deviceName.c_str()); +bool PulseLayer::inSinkList (std::string deviceName) +{ + // _debug("Audio: in device list %s", deviceName.c_str()); - DeviceList::iterator iter = _sinkList.begin(); + DeviceList::iterator iter = _sinkList.begin(); - // _debug("_deviceList.size() %d", _sinkList.size()); + // _debug("_deviceList.size() %d", _sinkList.size()); - while(iter != _sinkList.end()) { - if (*iter == deviceName) { - // _debug("device name in list: %s", (*iter).c_str()); - return true; - } + while (iter != _sinkList.end()) { + if (*iter == deviceName) { + // _debug("device name in list: %s", (*iter).c_str()); + return true; + } - iter++; - } + iter++; + } - return false; + return false; } -bool PulseLayer::inSourceList(std::string deviceName) { - - DeviceList::iterator iter = _sourceList.begin(); +bool PulseLayer::inSourceList (std::string deviceName) +{ - while(iter != _sourceList.end()) { + DeviceList::iterator iter = _sourceList.begin(); - if(*iter == deviceName) { - return true; - } + while (iter != _sourceList.end()) { - iter++; - } + if (*iter == deviceName) { + return true; + } - return false; + iter++; + } + + return false; } bool PulseLayer::createStreams (pa_context* c) { - _info("Audio: Create streams"); + _info ("Audio: Create streams"); // _debug("Device list size %d", getDevicelist()->size()); @@ -500,9 +513,9 @@ bool PulseLayer::createStreams (pa_context* c) std::string recordDevice = _manager->audioPreference.getDeviceRecord(); std::string ringtoneDevice = _manager->audioPreference.getDeviceRingtone(); - _debug("Audio: Device stored in config for playback: %s", playbackDevice.c_str()); - _debug("Audio: Device stored in config for ringtone: %s", recordDevice.c_str()); - _debug("Audio: Device stored in config for record: %s", ringtoneDevice.c_str()); + _debug ("Audio: Device stored in config for playback: %s", playbackDevice.c_str()); + _debug ("Audio: Device stored in config for ringtone: %s", recordDevice.c_str()); + _debug ("Audio: Device stored in config for record: %s", ringtoneDevice.c_str()); PulseLayerType * playbackParam = new PulseLayerType(); playbackParam->context = c; @@ -510,20 +523,21 @@ bool PulseLayer::createStreams (pa_context* c) playbackParam->description = PLAYBACK_STREAM_NAME; playbackParam->volume = _manager->getSpkrVolume(); playbackParam->mainloop = m; - - playback = new AudioStream(playbackParam, _audioSampleRate); - if(inSinkList(playbackDevice)) { - playback->connectStream(&playbackDevice); - } - else { - playback->connectStream(NULL); + + playback = new AudioStream (playbackParam, _audioSampleRate); + + if (inSinkList (playbackDevice)) { + playback->connectStream (&playbackDevice); + } else { + playback->connectStream (NULL); } + pa_stream_set_write_callback (playback->pulseStream(), playback_callback, this); pa_stream_set_overflow_callback (playback->pulseStream(), playback_overflow_callback, this); pa_stream_set_underflow_callback (playback->pulseStream(), playback_underflow_callback, this); // pa_stream_set_suspended_callback(playback->pulseStream(), stream_suspended_callback, this); - pa_stream_set_moved_callback(playback->pulseStream(), stream_moved_callback, this); - pa_stream_set_latency_update_callback(playback->pulseStream(), latency_update_callback, this); + pa_stream_set_moved_callback (playback->pulseStream(), stream_moved_callback, this); + pa_stream_set_latency_update_callback (playback->pulseStream(), latency_update_callback, this); delete playbackParam; PulseLayerType * recordParam = new PulseLayerType(); @@ -534,18 +548,19 @@ bool PulseLayer::createStreams (pa_context* c) recordParam->mainloop = m; record = new AudioStream (recordParam, _audioSampleRate); - if(inSourceList(recordDevice)) { - record->connectStream(&recordDevice); + + if (inSourceList (recordDevice)) { + record->connectStream (&recordDevice); + } else { + record->connectStream (NULL); } - else { - record->connectStream(NULL); - } + pa_stream_set_read_callback (record->pulseStream() , capture_callback, this); // pa_stream_set_suspended_callback(record->pulseStream(), stream_suspended_callback, this); - pa_stream_set_moved_callback(record->pulseStream(), stream_moved_callback, this); - pa_stream_set_latency_update_callback(record->pulseStream(), latency_update_callback, this); + pa_stream_set_moved_callback (record->pulseStream(), stream_moved_callback, this); + pa_stream_set_latency_update_callback (record->pulseStream(), latency_update_callback, this); delete recordParam; - + PulseLayerType * ringtoneParam = new PulseLayerType(); ringtoneParam->context = c; ringtoneParam->type = RINGTONE_STREAM; @@ -554,14 +569,15 @@ bool PulseLayer::createStreams (pa_context* c) ringtoneParam->mainloop = m; ringtone = new AudioStream (ringtoneParam, _audioSampleRate); - if(inSourceList(ringtoneDevice)) { - ringtone->connectStream(&ringtoneDevice); - } - else { - ringtone->connectStream(NULL); + + if (inSourceList (ringtoneDevice)) { + ringtone->connectStream (&ringtoneDevice); + } else { + ringtone->connectStream (NULL); } - pa_stream_set_write_callback(ringtone->pulseStream(), ringtone_callback, this); - pa_stream_set_moved_callback(ringtone->pulseStream(), stream_moved_callback, this); + + pa_stream_set_write_callback (ringtone->pulseStream(), ringtone_callback, this); + pa_stream_set_moved_callback (ringtone->pulseStream(), stream_moved_callback, this); delete ringtoneParam; pa_threaded_mainloop_signal (m , 0); @@ -575,7 +591,7 @@ bool PulseLayer::createStreams (pa_context* c) bool PulseLayer::disconnectAudioStream (void) { - _info("Audio: Disconnect audio stream"); + _info ("Audio: Disconnect audio stream"); closePlaybackStream(); closeCaptureStream(); @@ -591,9 +607,9 @@ void PulseLayer::closeCaptureStream (void) { if (record) { - std::string deviceName(pa_stream_get_device_name(record->pulseStream())); - _debug("Audio: record device to be stored in config: %s", deviceName.c_str()); - _manager->audioPreference.setDeviceRecord(deviceName); + std::string deviceName (pa_stream_get_device_name (record->pulseStream())); + _debug ("Audio: record device to be stored in config: %s", deviceName.c_str()); + _manager->audioPreference.setDeviceRecord (deviceName); delete record; record=NULL; } @@ -603,19 +619,19 @@ void PulseLayer::closeCaptureStream (void) void PulseLayer::closePlaybackStream (void) { if (playback) { - std::string deviceName(pa_stream_get_device_name(playback->pulseStream())); - _debug("Audio: playback device to be stored in config: %s", deviceName.c_str()); - _manager->audioPreference.setDevicePlayback(deviceName); + std::string deviceName (pa_stream_get_device_name (playback->pulseStream())); + _debug ("Audio: playback device to be stored in config: %s", deviceName.c_str()); + _manager->audioPreference.setDevicePlayback (deviceName); delete playback; playback=NULL; } - if(ringtone) { - std::string deviceName(pa_stream_get_device_name(ringtone->pulseStream())); - _debug("Audio: ringtone device to be stored in config: %s", deviceName.c_str()); - _manager->audioPreference.setDeviceRingtone(deviceName); + if (ringtone) { + std::string deviceName (pa_stream_get_device_name (ringtone->pulseStream())); + _debug ("Audio: ringtone device to be stored in config: %s", deviceName.c_str()); + _manager->audioPreference.setDeviceRingtone (deviceName); delete ringtone; - ringtone = NULL; + ringtone = NULL; } } @@ -631,15 +647,15 @@ int PulseLayer::canGetMic() void PulseLayer::startStream (void) { - if(_audiofilter) - _audiofilter->resetAlgorithm(); + if (_audiofilter) + _audiofilter->resetAlgorithm(); - if(_echoCanceller) - _echoCanceller->resetAlgorithm(); + if (_echoCanceller) + _echoCanceller->resetAlgorithm(); // Create Streams - if(!playback || !record) - createStreams(context); + if (!playback || !record) + createStreams (context); // Flush outside the if statement: every time start stream is @@ -655,19 +671,19 @@ void PulseLayer::stopStream (void) { - _info("Audio: Stop audio stream"); + _info ("Audio: Stop audio stream"); - pa_threaded_mainloop_lock (m); + pa_threaded_mainloop_lock (m); - if(playback) - pa_stream_flush (playback->pulseStream(), NULL, NULL); + if (playback) + pa_stream_flush (playback->pulseStream(), NULL, NULL); - if(record) - pa_stream_flush (record->pulseStream(), NULL, NULL); + if (record) + pa_stream_flush (record->pulseStream(), NULL, NULL); - pa_threaded_mainloop_unlock (m); + pa_threaded_mainloop_unlock (m); - disconnectAudioStream(); + disconnectAudioStream(); } @@ -700,14 +716,14 @@ void PulseLayer::processCaptureData (void) void PulseLayer::processRingtoneData (void) { // handle ringtone playback - if(ringtone && (ringtone)->pulseStream() && (pa_stream_get_state(ringtone->pulseStream()) == PA_STREAM_READY)) { - - // If the playback buffer is full, we don't overflow it; wait for it to have free space - if(pa_stream_writable_size(ringtone->pulseStream()) == 0) - return; - - ringtoneToSpeaker(); - } + if (ringtone && (ringtone)->pulseStream() && (pa_stream_get_state (ringtone->pulseStream()) == PA_STREAM_READY)) { + + // If the playback buffer is full, we don't overflow it; wait for it to have free space + if (pa_stream_writable_size (ringtone->pulseStream()) == 0) + return; + + ringtoneToSpeaker(); + } } @@ -731,22 +747,22 @@ void PulseLayer::processData (void) } -void PulseLayer::setEchoCancelState(bool state) +void PulseLayer::setEchoCancelState (bool state) { - // if a stream already running - if(AudioLayer::_echoCancel) - _echoCancel->setEchoCancelState(state); + // if a stream already running + if (AudioLayer::_echoCancel) + _echoCancel->setEchoCancelState (state); - AudioLayer::_echocancelstate = state; + AudioLayer::_echocancelstate = state; } -void PulseLayer::setNoiseSuppressState(bool state) +void PulseLayer::setNoiseSuppressState (bool state) { - // if a stream already opened - if(AudioLayer::_echoCancel) - _echoCancel->setNoiseSuppressState(state); + // if a stream already opened + if (AudioLayer::_echoCancel) + _echoCancel->setNoiseSuppressState (state); - AudioLayer::_noisesuppressstate = state; + AudioLayer::_noisesuppressstate = state; } @@ -789,19 +805,19 @@ void PulseLayer::writeToSpeaker (void) // Get ringtone AudioLoop* tone = _manager->getTelephoneTone(); - // We must test if data have been received from network in case of early media - normalAvailBytes = getMainBuffer()->availForGet(); + // We must test if data have been received from network in case of early media + normalAvailBytes = getMainBuffer()->availForGet(); // flush remaining samples in _urgentRingBuffer flushUrgent(); - if ((tone != 0) && (normalAvailBytes <= 0)) { + if ( (tone != 0) && (normalAvailBytes <= 0)) { if (playback->getStreamState() == PA_STREAM_READY) { out = (SFLDataFormat*) pa_xmalloc (writeableSize); int copied = tone->getNext (out, writeableSize / sizeof (SFLDataFormat), 100); - + pa_stream_write (playback->pulseStream(), out, copied * sizeof (SFLDataFormat), NULL, 0, PA_SEEK_RELATIVE); pa_xfree (out); @@ -842,9 +858,9 @@ void PulseLayer::writeToSpeaker (void) getMainBuffer()->getData (out, byteToGet, 100); - // TODO: Audio processing should be performed inside mainbuffer - // to avoid such problem - AudioLayer::_echoCancel->setSamplingRate(_mainBufferSampleRate); + // TODO: Audio processing should be performed inside mainbuffer + // to avoid such problem + AudioLayer::_echoCancel->setSamplingRate (_mainBufferSampleRate); // test if resampling is required if (_mainBufferSampleRate && ( (int) _audioSampleRate != _mainBufferSampleRate)) { @@ -857,7 +873,7 @@ void PulseLayer::writeToSpeaker (void) int nbSample = _converter->upsampleData ( (SFLDataFormat*) out, rsmpl_out, _mainBufferSampleRate, _audioSampleRate, nb_sample_down); if ( (nbSample*sizeof (SFLDataFormat)) > (unsigned int) writeableSize) - _warn("Audio: Error: nbsbyte exceed buffer length"); + _warn ("Audio: Error: nbsbyte exceed buffer length"); pa_stream_write (playback->pulseStream(), rsmpl_out, nbSample*sizeof (SFLDataFormat), NULL, 0, PA_SEEK_RELATIVE); @@ -869,9 +885,9 @@ void PulseLayer::writeToSpeaker (void) } - - // Copy far-end signal in echo canceller to adapt filter coefficient - // AudioLayer::_echoCanceller->putData(out, byteToGet); + + // Copy far-end signal in echo canceller to adapt filter coefficient + // AudioLayer::_echoCanceller->putData(out, byteToGet); pa_xfree (out); @@ -905,13 +921,13 @@ void PulseLayer::readFromMic (void) size_t r; SFLDataFormat echoCancelledMic[10000]; - memset(echoCancelledMic, 0, 10000*sizeof(SFLDataFormat)); + memset (echoCancelledMic, 0, 10000*sizeof (SFLDataFormat)); int readableSize = pa_stream_readable_size (record->pulseStream()); if (pa_stream_peek (record->pulseStream() , (const void**) &data , &r) < 0 || !data) { - _warn("Audio: Error capture stream peek failed: %s" , pa_strerror (pa_context_errno (context))); + _warn ("Audio: Error capture stream peek failed: %s" , pa_strerror (pa_context_errno (context))); } if (data != 0) { @@ -927,42 +943,42 @@ void PulseLayer::readFromMic (void) int nb_sample_up = nbSample; - // captureFile->write ((const char *)data, nbSample*sizeof(SFLDataFormat)); + // captureFile->write ((const char *)data, nbSample*sizeof(SFLDataFormat)); nbSample = _converter->downsampleData ( (SFLDataFormat *) data, rsmpl_out, _mainBufferSampleRate, _audioSampleRate, nb_sample_up); - // captureRsmplFile->write ((const char *)rsmpl_out, nbSample*sizeof(SFLDataFormat)); + // captureRsmplFile->write ((const char *)rsmpl_out, nbSample*sizeof(SFLDataFormat)); // remove dc offset - _audiofilter->processAudio(rsmpl_out, nbSample*sizeof(SFLDataFormat)); + _audiofilter->processAudio (rsmpl_out, nbSample*sizeof (SFLDataFormat)); - // captureFilterFile->write ((const char *)rsmpl_out, nbSample*sizeof(SFLDataFormat)); + // captureFilterFile->write ((const char *)rsmpl_out, nbSample*sizeof(SFLDataFormat)); - // echo cancellation processing - // int sampleready = _echoCanceller->processAudio(rsmpl_out, echoCancelledMic, nbSample*sizeof(SFLDataFormat)); + // echo cancellation processing + // int sampleready = _echoCanceller->processAudio(rsmpl_out, echoCancelledMic, nbSample*sizeof(SFLDataFormat)); // getMainBuffer()->putData ( (void*) rsmpl_out, nbSample*sizeof (SFLDataFormat), 100); - // if(sampleready) - // getMainBuffer()->putData ( echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); - getMainBuffer()->putData ( rsmpl_out, nbSample*sizeof (SFLDataFormat), 100); + // if(sampleready) + // getMainBuffer()->putData ( echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); + getMainBuffer()->putData (rsmpl_out, nbSample*sizeof (SFLDataFormat), 100); pa_xfree (rsmpl_out); } else { - SFLDataFormat* filter_out = (SFLDataFormat*) pa_xmalloc (r); + SFLDataFormat* filter_out = (SFLDataFormat*) pa_xmalloc (r); - // remove dc offset - _audiofilter->processAudio((SFLDataFormat *)data, filter_out, r); + // remove dc offset + _audiofilter->processAudio ( (SFLDataFormat *) data, filter_out, r); - // echo cancellation processing - // int sampleready = _echoCanceller->processAudio((SFLDataFormat *)filter_out, echoCancelledMic, r); + // echo cancellation processing + // int sampleready = _echoCanceller->processAudio((SFLDataFormat *)filter_out, echoCancelledMic, r); // no resampling required // getMainBuffer()->putData (echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); - getMainBuffer()->putData (filter_out, r, 100); + getMainBuffer()->putData (filter_out, r, 100); - pa_xfree(filter_out); + pa_xfree (filter_out); } @@ -970,43 +986,42 @@ void PulseLayer::readFromMic (void) } if (pa_stream_drop (record->pulseStream()) < 0) { - _warn("Audio: Error: capture stream drop failed: %s" , pa_strerror( pa_context_errno( context) )); + _warn ("Audio: Error: capture stream drop failed: %s" , pa_strerror (pa_context_errno (context))); } } -void PulseLayer::ringtoneToSpeaker(void) +void PulseLayer::ringtoneToSpeaker (void) { - AudioLoop* file_tone = _manager->getTelephoneFile(); + AudioLoop* file_tone = _manager->getTelephoneFile(); - SFLDataFormat* out; + SFLDataFormat* out; - int writableSize = pa_stream_writable_size(ringtone->pulseStream()); + int writableSize = pa_stream_writable_size (ringtone->pulseStream()); - if (file_tone) { + if (file_tone) { - if(ringtone->getStreamState() == PA_STREAM_READY) { - - out = (SFLDataFormat *)pa_xmalloc(writableSize); - int copied = file_tone->getNext(out, writableSize/sizeof(SFLDataFormat), 100); - pa_stream_write(ringtone->pulseStream(), out, copied*sizeof(SFLDataFormat), NULL, 0, PA_SEEK_RELATIVE); + if (ringtone->getStreamState() == PA_STREAM_READY) { - pa_xfree(out); - } - } - else { + out = (SFLDataFormat *) pa_xmalloc (writableSize); + int copied = file_tone->getNext (out, writableSize/sizeof (SFLDataFormat), 100); + pa_stream_write (ringtone->pulseStream(), out, copied*sizeof (SFLDataFormat), NULL, 0, PA_SEEK_RELATIVE); - if(ringtone->getStreamState() == PA_STREAM_READY) { + pa_xfree (out); + } + } else { + + if (ringtone->getStreamState() == PA_STREAM_READY) { + + out = (SFLDataFormat*) pa_xmalloc (writableSize); + memset (out, 0, writableSize); + pa_stream_write (ringtone->pulseStream(), out, writableSize, NULL, 0, PA_SEEK_RELATIVE); - out = (SFLDataFormat*)pa_xmalloc(writableSize); - memset(out, 0, writableSize); - pa_stream_write(ringtone->pulseStream(), out, writableSize, NULL, 0, PA_SEEK_RELATIVE); - - pa_xfree(out); + pa_xfree (out); + } } - } - + } diff --git a/sflphone-common/src/audio/recordable.cpp b/sflphone-common/src/audio/recordable.cpp index 8371bf7ec8b52a82763e3b4ea90a51944eafd48b..799bb814533b46d24905d101131f55fa0a3490c7 100644 --- a/sflphone-common/src/audio/recordable.cpp +++ b/sflphone-common/src/audio/recordable.cpp @@ -30,7 +30,7 @@ #include "recordable.h" #include "manager.h" -Recordable::Recordable() : recorder(&recAudio, Manager::instance().getMainBuffer()) +Recordable::Recordable() : recorder (&recAudio, Manager::instance().getMainBuffer()) { FILE_TYPE fileType = FILE_WAV; diff --git a/sflphone-common/src/audio/ringbuffer.cpp b/sflphone-common/src/audio/ringbuffer.cpp index c38b4c2212018afe37a8b2aa54fac577a2de4e88..cf7b9ecdfd38ae03cd9a0bef6c9dbaa52d31e757 100644 --- a/sflphone-common/src/audio/ringbuffer.cpp +++ b/sflphone-common/src/audio/ringbuffer.cpp @@ -109,7 +109,7 @@ RingBuffer::getLen (CallID call_id) int length = (mEnd + mBufferSize - mStart) % mBufferSize; - + // _debug(" *RingBuffer::getLen: buffer_id %s, call_id %s, mStart %i, mEnd %i, length %i, buffersie %i", buffer_id.c_str(), call_id.c_str(), mStart, mEnd, length, mBufferSize); return length; @@ -271,7 +271,7 @@ RingBuffer::Put (void* buffer, int toCopy, unsigned short volume) //fprintf(stderr, "has %d put %d\t", len, block); bcopy (src, mBuffer + pos, block); - src += block; + src += block; pos = (pos + block) % mBufferSize; @@ -295,7 +295,7 @@ RingBuffer::AvailForGet (CallID call_id) { // Used space - return getLen(call_id); + return getLen (call_id); } // Get will move 'toCopy' bytes from the internal FIFO to 'buffer' diff --git a/sflphone-common/src/audio/sound/tone.cpp b/sflphone-common/src/audio/sound/tone.cpp index aaff9fa4f411278d18fb42144585b4132df63d0e..7a0ffe6de7a5de2c8808b4e2d6d5caa69396f17c 100644 --- a/sflphone-common/src/audio/sound/tone.cpp +++ b/sflphone-common/src/audio/sound/tone.cpp @@ -42,9 +42,9 @@ #define TABLE_LENGTH 4096 double TWOPI = 2 * M_PI; -Tone::Tone (const std::string& definition, unsigned int sampleRate) : AudioLoop(), _sampleRate (sampleRate), _xhigher(0.0), _xlower(0.0) +Tone::Tone (const std::string& definition, unsigned int sampleRate) : AudioLoop(), _sampleRate (sampleRate), _xhigher (0.0), _xlower (0.0) { - fillWavetable(); + fillWavetable(); genBuffer (definition); // allocate memory with definition parameter } @@ -116,7 +116,7 @@ Tone::genBuffer (const std::string& definition) } // Generate SAMPLING_RATE samples of sinus, buffer is the result - _debug("genSin(%d, %d)", freq1, freq2); + _debug ("genSin(%d, %d)", freq1, freq2); genSin (bufferPos, freq1, freq2, count); // To concatenate the different buffers for each section. @@ -143,67 +143,67 @@ Tone::genBuffer (const std::string& definition) void Tone::fillWavetable() { - double tableSize = (double)TABLE_LENGTH; + double tableSize = (double) TABLE_LENGTH; - for(int i = 0; i < TABLE_LENGTH; i++) { - _wavetable[i] = sin( ((double)i / (tableSize - 1.0)) * TWOPI ); - } + for (int i = 0; i < TABLE_LENGTH; i++) { + _wavetable[i] = sin ( ( (double) i / (tableSize - 1.0)) * TWOPI); + } } double -Tone::interpolate(double x) +Tone::interpolate (double x) { - int xi_0, xi_1; - double yi_0, yi_1, A, B; + int xi_0, xi_1; + double yi_0, yi_1, A, B; - xi_0 = (int)x; - xi_1 = xi_0+1; + xi_0 = (int) x; + xi_1 = xi_0+1; - yi_0 =_wavetable[xi_0]; - yi_1 = _wavetable[xi_1]; + yi_0 =_wavetable[xi_0]; + yi_1 = _wavetable[xi_1]; - A = (x - xi_0); - B = 1.0 - A; + A = (x - xi_0); + B = 1.0 - A; - return A*yi_0 + B*yi_1; + return A*yi_0 + B*yi_1; } void Tone::genSin (SFLDataFormat* buffer, int frequency1, int frequency2, int nb) { - _xhigher = 0.0; - _xlower = 0.0; + _xhigher = 0.0; + _xlower = 0.0; - double sr = (double)_sampleRate; - double tableSize = (double)TABLE_LENGTH; + double sr = (double) _sampleRate; + double tableSize = (double) TABLE_LENGTH; - double N_h = sr / (double) (frequency1); - double N_l = sr / (double) (frequency2); + double N_h = sr / (double) (frequency1); + double N_l = sr / (double) (frequency2); - double dx_h = tableSize / N_h; - double dx_l = tableSize / N_l; + double dx_h = tableSize / N_h; + double dx_l = tableSize / N_l; - double x_h = _xhigher; - double x_l = _xlower; + double x_h = _xhigher; + double x_l = _xlower; - double amp = (double)SFLDataAmplitude; + double amp = (double) SFLDataAmplitude; - for (int t = 0; t < nb; t ++) { - buffer[t] = (int16)(amp*(interpolate(x_h) + interpolate(x_l))); - x_h += dx_h; - x_l += dx_l; + for (int t = 0; t < nb; t ++) { + buffer[t] = (int16) (amp* (interpolate (x_h) + interpolate (x_l))); + x_h += dx_h; + x_l += dx_l; - if(x_h > tableSize) { - x_h -= tableSize; - } + if (x_h > tableSize) { + x_h -= tableSize; + } - if(x_l > tableSize) { - x_l -= tableSize; - } - } + if (x_l > tableSize) { + x_l -= tableSize; + } + } - _xhigher = x_h; - _xlower = x_l; + _xhigher = x_h; + _xlower = x_l; } diff --git a/sflphone-common/src/audio/speexechocancel.cpp b/sflphone-common/src/audio/speexechocancel.cpp index c956af0f9774cb253e8fcbc8954612cc3cfa72cc..a85a4caccbefae407483d480746b72202beef973 100644 --- a/sflphone-common/src/audio/speexechocancel.cpp +++ b/sflphone-common/src/audio/speexechocancel.cpp @@ -27,54 +27,54 @@ #define FILTER_LENGTH 800 -SpeexEchoCancel::SpeexEchoCancel() +SpeexEchoCancel::SpeexEchoCancel() { - _debug("EchoCancel: Instantiate echo canceller"); + _debug ("EchoCancel: Instantiate echo canceller"); - int samplingRate = 8000; + int samplingRate = 8000; - _echoState = speex_echo_state_init(FRAME_SIZE, FILTER_LENGTH); - _preState = speex_preprocess_state_init(FRAME_SIZE, samplingRate); + _echoState = speex_echo_state_init (FRAME_SIZE, FILTER_LENGTH); + _preState = speex_preprocess_state_init (FRAME_SIZE, samplingRate); - speex_echo_ctl(_echoState, SPEEX_ECHO_SET_SAMPLING_RATE, &samplingRate); - speex_preprocess_ctl(_preState, SPEEX_PREPROCESS_SET_ECHO_STATE, _echoState); + speex_echo_ctl (_echoState, SPEEX_ECHO_SET_SAMPLING_RATE, &samplingRate); + speex_preprocess_ctl (_preState, SPEEX_PREPROCESS_SET_ECHO_STATE, _echoState); - micFile = new ofstream("micData", ofstream::binary); - echoFile = new ofstream("echoData", ofstream::binary); - spkrFile = new ofstream("spkrData", ofstream::binary); + micFile = new ofstream ("micData", ofstream::binary); + echoFile = new ofstream ("echoData", ofstream::binary); + spkrFile = new ofstream ("spkrData", ofstream::binary); - _micData = new RingBuffer(10000); - _spkrData = new RingBuffer(10000); + _micData = new RingBuffer (10000); + _spkrData = new RingBuffer (10000); - _micData->createReadPointer(); - _spkrData->createReadPointer(); + _micData->createReadPointer(); + _spkrData->createReadPointer(); - _spkrStoped = true; + _spkrStoped = true; } -SpeexEchoCancel::~SpeexEchoCancel() +SpeexEchoCancel::~SpeexEchoCancel() { - _debug("EchoCancel: Delete echo canceller"); + _debug ("EchoCancel: Delete echo canceller"); - speex_echo_state_destroy(_echoState); - _echoState = NULL; + speex_echo_state_destroy (_echoState); + _echoState = NULL; - speex_preprocess_state_destroy(_preState); - _preState = NULL; + speex_preprocess_state_destroy (_preState); + _preState = NULL; - delete _micData; - _micData = NULL; + delete _micData; + _micData = NULL; - delete _spkrData; - _spkrData = NULL; + delete _spkrData; + _spkrData = NULL; - micFile->close(); - spkrFile->close(); - echoFile->close(); + micFile->close(); + spkrFile->close(); + echoFile->close(); - delete micFile; - delete spkrFile; - delete echoFile; + delete micFile; + delete spkrFile; + delete echoFile; } void SpeexEchoCancel::reset() @@ -82,82 +82,83 @@ void SpeexEchoCancel::reset() } -void SpeexEchoCancel::putData(SFLDataFormat *inputData, int nbBytes) +void SpeexEchoCancel::putData (SFLDataFormat *inputData, int nbBytes) { - // std::cout << "putData nbBytes: " << nbBytes << std::endl; + // std::cout << "putData nbBytes: " << nbBytes << std::endl; - if(_spkrStoped) { - _micData->flushAll(); - _spkrData->flushAll(); - _spkrStoped = false; - } + if (_spkrStoped) { + _micData->flushAll(); + _spkrData->flushAll(); + _spkrStoped = false; + } - // Put data in speaker ring buffer - _spkrData->Put(inputData, nbBytes); + // Put data in speaker ring buffer + _spkrData->Put (inputData, nbBytes); - // In case we use libspeex internal buffer - // (require capture and playback stream to be synchronized) - // speex_echo_playback(_echoState, inputData); + // In case we use libspeex internal buffer + // (require capture and playback stream to be synchronized) + // speex_echo_playback(_echoState, inputData); } -void SpeexEchoCancel::process(SFLDataFormat *data UNUSED, int nbBytes UNUSED) {} +void SpeexEchoCancel::process (SFLDataFormat *data UNUSED, int nbBytes UNUSED) {} -int SpeexEchoCancel::process(SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) +int SpeexEchoCancel::process (SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) { - if(_spkrStoped) { - return 0; - } + if (_spkrStoped) { + return 0; + } - int byteSize = FRAME_SIZE*2; + int byteSize = FRAME_SIZE*2; - // init temporary buffers - memset(_tmpSpkr, 0, 5000); - memset(_tmpMic, 0, 5000); - memset(_tmpOut, 0, 5000); + // init temporary buffers + memset (_tmpSpkr, 0, 5000); + memset (_tmpMic, 0, 5000); + memset (_tmpOut, 0, 5000); - // Put mic data in ringbuffer - _micData->Put(inputData, nbBytes); + // Put mic data in ringbuffer + _micData->Put (inputData, nbBytes); - // Store data for synchronization - int spkrAvail = _spkrData->AvailForGet(); - int micAvail = _micData->AvailForGet(); + // Store data for synchronization + int spkrAvail = _spkrData->AvailForGet(); + int micAvail = _micData->AvailForGet(); - // Init number of frame processed - int nbFrame = 0; + // Init number of frame processed + int nbFrame = 0; - // Get data from mic and speaker - while((spkrAvail > byteSize) && (micAvail > byteSize)) { + // Get data from mic and speaker + while ( (spkrAvail > byteSize) && (micAvail > byteSize)) { - // get synchronized data - _spkrData->Get(_tmpSpkr, byteSize); - _micData->Get(_tmpMic, byteSize); + // get synchronized data + _spkrData->Get (_tmpSpkr, byteSize); + _micData->Get (_tmpMic, byteSize); - speex_preprocess_run(_preState, _tmpMic); + speex_preprocess_run (_preState, _tmpMic); - micFile->write ((const char *)_tmpMic, byteSize); - spkrFile->write ((const char *)_tmpSpkr, byteSize); + micFile->write ( (const char *) _tmpMic, byteSize); + spkrFile->write ( (const char *) _tmpSpkr, byteSize); - // Processed echo cancellation - speex_echo_cancellation(_echoState, _tmpMic, _tmpSpkr, _tmpOut); + // Processed echo cancellation + speex_echo_cancellation (_echoState, _tmpMic, _tmpSpkr, _tmpOut); - // speex_preprocess_run(_preState, _tmpOut); + // speex_preprocess_run(_preState, _tmpOut); - bcopy(_tmpOut, outputData+(nbFrame*FRAME_SIZE), byteSize); + bcopy (_tmpOut, outputData+ (nbFrame*FRAME_SIZE), byteSize); - echoFile->write ((const char *)_tmpOut, byteSize); + echoFile->write ( (const char *) _tmpOut, byteSize); - spkrAvail = _spkrData->AvailForGet(); - micAvail = _micData->AvailForGet(); + spkrAvail = _spkrData->AvailForGet(); + micAvail = _micData->AvailForGet(); - // increment nb of frame processed - ++nbFrame; - } + // increment nb of frame processed + ++nbFrame; + } - return nbFrame * FRAME_SIZE; + return nbFrame * FRAME_SIZE; } -void SpeexEchoCancel::process(SFLDataFormat *micData UNUSED, SFLDataFormat *spkrData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED){ +void SpeexEchoCancel::process (SFLDataFormat *micData UNUSED, SFLDataFormat *spkrData UNUSED, SFLDataFormat *outputData UNUSED, int nbBytes UNUSED) +{ } diff --git a/sflphone-common/src/call.cpp b/sflphone-common/src/call.cpp index c640ad77b80d9e49f999cf2d142a21e8aadb9433..51a3d4546360ac7e7ac3a970d8d65cddb18a61f4 100644 --- a/sflphone-common/src/call.cpp +++ b/sflphone-common/src/call.cpp @@ -194,29 +194,29 @@ Call::setRecording() Recordable::recAudio.setRecording(); // Start recording - if(!recordStatus) { + if (!recordStatus) { - MainBuffer *mbuffer = Manager::instance().getMainBuffer(); - CallID process_id = Recordable::recorder.getRecorderID(); + MainBuffer *mbuffer = Manager::instance().getMainBuffer(); + CallID process_id = Recordable::recorder.getRecorderID(); - mbuffer->bindHalfDuplexOut(process_id, _id); - mbuffer->bindHalfDuplexOut(process_id); + mbuffer->bindHalfDuplexOut (process_id, _id); + mbuffer->bindHalfDuplexOut (process_id); } // Stop recording else { - MainBuffer *mbuffer = Manager::instance().getMainBuffer(); - CallID process_id = Recordable::recorder.getRecorderID(); + MainBuffer *mbuffer = Manager::instance().getMainBuffer(); + CallID process_id = Recordable::recorder.getRecorderID(); - mbuffer->unBindHalfDuplexOut(process_id, _id); - mbuffer->unBindHalfDuplexOut(process_id); + mbuffer->unBindHalfDuplexOut (process_id, _id); + mbuffer->unBindHalfDuplexOut (process_id); } Manager::instance().getMainBuffer()->stateInfo(); Recordable::recorder.start(); - + return recordStatus; } diff --git a/sflphone-common/src/conference.cpp b/sflphone-common/src/conference.cpp index 8ac1ce32820676f198dae5854c27001cc2cfa5eb..3e645628ddc70a52c88fac9f0337a1380e66f7b7 100644 --- a/sflphone-common/src/conference.cpp +++ b/sflphone-common/src/conference.cpp @@ -160,51 +160,52 @@ ParticipantSet Conference::getParticipantList() -bool Conference::setRecording() { +bool Conference::setRecording() +{ - bool recordStatus = Recordable::recAudio.isRecording(); + bool recordStatus = Recordable::recAudio.isRecording(); - Recordable::recAudio.setRecording(); + Recordable::recAudio.setRecording(); - // start recording - if(!recordStatus){ + // start recording + if (!recordStatus) { - MainBuffer *mbuffer = Manager::instance().getMainBuffer(); + MainBuffer *mbuffer = Manager::instance().getMainBuffer(); - ParticipantSet::iterator iter = _participants.begin(); + ParticipantSet::iterator iter = _participants.begin(); - CallID process_id = Recordable::recorder.getRecorderID(); + CallID process_id = Recordable::recorder.getRecorderID(); - while(iter != _participants.end()) { - mbuffer->bindHalfDuplexOut(process_id, *iter); - iter++; - } + while (iter != _participants.end()) { + mbuffer->bindHalfDuplexOut (process_id, *iter); + iter++; + } - mbuffer->bindHalfDuplexOut(process_id); + mbuffer->bindHalfDuplexOut (process_id); - Recordable::recorder.start(); + Recordable::recorder.start(); - } - // stop recording - else { + } + // stop recording + else { - MainBuffer *mbuffer = Manager::instance().getMainBuffer(); + MainBuffer *mbuffer = Manager::instance().getMainBuffer(); - ParticipantSet::iterator iter = _participants.begin(); + ParticipantSet::iterator iter = _participants.begin(); - CallID process_id = Recordable::recorder.getRecorderID(); + CallID process_id = Recordable::recorder.getRecorderID(); - while(iter != _participants.end()) { - mbuffer->unBindHalfDuplexOut(process_id, *iter); - iter++; - } + while (iter != _participants.end()) { + mbuffer->unBindHalfDuplexOut (process_id, *iter); + iter++; + } - mbuffer->unBindHalfDuplexOut(process_id); + mbuffer->unBindHalfDuplexOut (process_id); - // Recordable::recorder.start(); + // Recordable::recorder.start(); - } + } - return recordStatus; + return recordStatus; } diff --git a/sflphone-common/src/config/config.cpp b/sflphone-common/src/config/config.cpp old mode 100755 new mode 100644 index 9f735964de9e45de8aa005817d8b7b714f6d13ac..839c992020a885ca1369f1d7ff5f2d5de533a60c --- a/sflphone-common/src/config/config.cpp +++ b/sflphone-common/src/config/config.cpp @@ -212,14 +212,14 @@ ConfigTree::getConfigTreeItem (const std::string& section, const std::string& it SectionMap::iterator iter = _sections.find (section); if (iter == _sections.end()) { - // _error("ConfigTree: Error: Did not found section %s in config tree", section.c_str()); + // _error("ConfigTree: Error: Did not found section %s in config tree", section.c_str()); return NULL; } ItemMap::iterator iterItem = iter->second->find (itemName); if (iterItem == iter->second->end()) { - // _error("ConfigTree: Error: Did not found item %s in config tree", itemName.c_str()); + // _error("ConfigTree: Error: Did not found item %s in config tree", itemName.c_str()); return NULL; } @@ -282,7 +282,7 @@ ConfigTree::saveConfigTree (const std::string& fileName) file.open (fileName.data(), std::fstream::out); if (!file.is_open()) { - _error("ConfigTree: Error: Could not open %s configuration file", fileName.c_str()); + _error ("ConfigTree: Error: Could not open %s configuration file", fileName.c_str()); return false; } @@ -306,7 +306,7 @@ ConfigTree::saveConfigTree (const std::string& fileName) file.close(); if (chmod (fileName.c_str(), S_IRUSR | S_IWUSR)) { - _error("ConfigTree: Error: Failed to set permission on configuration: %s",strerror (errno)); + _error ("ConfigTree: Error: Failed to set permission on configuration: %s",strerror (errno)); } return true; @@ -380,15 +380,16 @@ ConfigTree::populateFromFile (const std::string& fileName) if (key.length() > 0 && val.length() > 0) { setConfigTreeItem (section, key, val); } - /* - if (key.length() > 0) { - if(val.length() > 0) - setConfigTreeItem (section, key, val); - else - setConfigTreeItem (section, key, ""); - } - */ + /* + if (key.length() > 0) { + + if(val.length() > 0) + setConfigTreeItem (section, key, val); + else + setConfigTreeItem (section, key, ""); + } + */ } } } diff --git a/sflphone-common/src/config/yamlemitter.cpp b/sflphone-common/src/config/yamlemitter.cpp old mode 100755 new mode 100644 index 1eb51e2cfb6d68880ef576d799e3de5ddfe1168d..3b6ba5c0c35d50e2e6d6b8a0071239f9d380a424 --- a/sflphone-common/src/config/yamlemitter.cpp +++ b/sflphone-common/src/config/yamlemitter.cpp @@ -32,337 +32,336 @@ #include <stdio.h> #include "../global.h" -namespace Conf { +namespace Conf +{ -YamlEmitter::YamlEmitter(const char *file) : filename(file), isFirstAccount(true) +YamlEmitter::YamlEmitter (const char *file) : filename (file), isFirstAccount (true) { - open(); + open(); } -YamlEmitter::~YamlEmitter() +YamlEmitter::~YamlEmitter() { - close(); + close(); } -void YamlEmitter::open() +void YamlEmitter::open() { - fd = fopen(filename.c_str(), "wb"); + fd = fopen (filename.c_str(), "wb"); - if(!fd) - throw YamlEmitterException("Could not open file descriptor"); + if (!fd) + throw YamlEmitterException ("Could not open file descriptor"); - if(!yaml_emitter_initialize(&emitter)) - throw YamlEmitterException("Could not initialize emitter"); + if (!yaml_emitter_initialize (&emitter)) + throw YamlEmitterException ("Could not initialize emitter"); - // Use unicode format - yaml_emitter_set_unicode(&emitter, 1); + // Use unicode format + yaml_emitter_set_unicode (&emitter, 1); - yaml_emitter_set_output_file(&emitter, fd); + yaml_emitter_set_output_file (&emitter, fd); - yaml_document_initialize(&document, NULL, NULL, NULL, 0, 0); + yaml_document_initialize (&document, NULL, NULL, NULL, 0, 0); - // Init the main configuration mapping - if((topLevelMapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not create top level mapping"); + // Init the main configuration mapping + if ( (topLevelMapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not create top level mapping"); } -void YamlEmitter::close() +void YamlEmitter::close() { - // yaml_emitter_delete(&emitter); - - if(!fd) - throw YamlEmitterException("File descriptor not valid"); - - fclose(fd); - /* - if(!fclose(fd)) - throw YamlEmitterException("Error closing file descriptor"); - */ - - yaml_document_delete(&document); + // yaml_emitter_delete(&emitter); + + if (!fd) + throw YamlEmitterException ("File descriptor not valid"); + + fclose (fd); + /* + if(!fclose(fd)) + throw YamlEmitterException("Error closing file descriptor"); + */ + + yaml_document_delete (&document); } void YamlEmitter::read() {} -void YamlEmitter::write() +void YamlEmitter::write() { } void YamlEmitter::serializeData() { - yaml_emitter_dump(&emitter, &document); + yaml_emitter_dump (&emitter, &document); } -void YamlEmitter::serializeAccount(MappingNode *map) +void YamlEmitter::serializeAccount (MappingNode *map) { - std::string accountstr("accounts"); - - int accountid, accountmapping; + std::string accountstr ("accounts"); - _debug("YamlEmitter: Serialize account"); + int accountid, accountmapping; - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing account"); + _debug ("YamlEmitter: Serialize account"); - if(isFirstAccount) { - // accountSequence need to be static outside this scope since reused each time an account is written - if((accountid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)accountstr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add preference scalar to document"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing account"); - if((accountSequence = yaml_document_add_sequence (&document, NULL, YAML_BLOCK_SEQUENCE_STYLE)) == 0) - throw YamlEmitterException("Could not add sequence to document"); + if (isFirstAccount) { + // accountSequence need to be static outside this scope since reused each time an account is written + if ( (accountid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) accountstr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add preference scalar to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, accountid, accountSequence)) - throw YamlEmitterException("Could not add mapping pair to top level mapping"); - - isFirstAccount = false; - } + if ( (accountSequence = yaml_document_add_sequence (&document, NULL, YAML_BLOCK_SEQUENCE_STYLE)) == 0) + throw YamlEmitterException ("Could not add sequence to document"); - if((accountmapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add account mapping to document"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, accountid, accountSequence)) + throw YamlEmitterException ("Could not add mapping pair to top level mapping"); - if(!yaml_document_append_sequence_item (&document, accountSequence, accountmapping)) - throw YamlEmitterException("Could not append account mapping to sequence"); + isFirstAccount = false; + } + + if ( (accountmapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add account mapping to document"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + if (!yaml_document_append_sequence_item (&document, accountSequence, accountmapping)) + throw YamlEmitterException ("Could not append account mapping to sequence"); + + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(accountmapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (accountmapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializePreference(MappingNode *map) +void YamlEmitter::serializePreference (MappingNode *map) { - std::string preferencestr("preferences"); + std::string preferencestr ("preferences"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize preference"); + _debug ("YamlEmitter: Serialize preference"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeVoipPreference(MappingNode *map) +void YamlEmitter::serializeVoipPreference (MappingNode *map) { - std::string preferencestr("voipPreferences"); + std::string preferencestr ("voipPreferences"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize voip preference"); + _debug ("YamlEmitter: Serialize voip preference"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeAddressbookPreference(MappingNode *map) +void YamlEmitter::serializeAddressbookPreference (MappingNode *map) { - std::string preferencestr("addressbook"); + std::string preferencestr ("addressbook"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize addressbook preferences"); + _debug ("YamlEmitter: Serialize addressbook preferences"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeHooksPreference(MappingNode *map) +void YamlEmitter::serializeHooksPreference (MappingNode *map) { - std::string preferencestr("hooks"); + std::string preferencestr ("hooks"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize hooks preferences"); + _debug ("YamlEmitter: Serialize hooks preferences"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeAudioPreference(MappingNode *map) +void YamlEmitter::serializeAudioPreference (MappingNode *map) { - std::string preferencestr("audio"); + std::string preferencestr ("audio"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize hooks preferences"); + _debug ("YamlEmitter: Serialize hooks preferences"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeShortcutPreference(MappingNode *map) +void YamlEmitter::serializeShortcutPreference (MappingNode *map) { - std::string preferencestr("shortcuts"); + std::string preferencestr ("shortcuts"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize shortcuts preferences"); + _debug ("YamlEmitter: Serialize shortcuts preferences"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::addMappingItem(int mappingid, Key key, YamlNode *node) +void YamlEmitter::addMappingItem (int mappingid, Key key, YamlNode *node) { - if(node->getType() == SCALAR) { + if (node->getType() == SCALAR) { - int temp1, temp2; + int temp1, temp2; - ScalarNode *sclr = (ScalarNode *)node; + ScalarNode *sclr = (ScalarNode *) node; - if((temp1 = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (temp1 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((temp2 = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)sclr->getValue().c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (temp2 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) sclr->getValue().c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if(!yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2)) - throw YamlEmitterException("Could not append mapping pair to mapping"); + if (!yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2)) + throw YamlEmitterException ("Could not append mapping pair to mapping"); - } - else if(node->getType() == MAPPING){ + } else if (node->getType() == MAPPING) { - int temp1, temp2; + int temp1, temp2; - if((temp1 = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (temp1 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((temp2 = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (temp2 = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if(!yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2)) - throw YamlEmitterException("Could not add mapping pair to mapping"); + if (!yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2)) + throw YamlEmitterException ("Could not add mapping pair to mapping"); - MappingNode *map = (MappingNode *)node; - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); - - while(iter != internalmap->end()) { - addMappingItem(temp2, iter->first, iter->second); - iter++; - } - } - else - throw YamlEmitterException("Unknown node type while adding mapping node"); + MappingNode *map = (MappingNode *) node; + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); + + while (iter != internalmap->end()) { + addMappingItem (temp2, iter->first, iter->second); + iter++; + } + } else + throw YamlEmitterException ("Unknown node type while adding mapping node"); } diff --git a/sflphone-common/src/config/yamlengine.cpp b/sflphone-common/src/config/yamlengine.cpp old mode 100755 new mode 100644 index 10022a189dcf817c5e6547b5eb9d519c5807a59c..9e2aa30dafb21e370c9179012f994eb555875a07 --- a/sflphone-common/src/config/yamlengine.cpp +++ b/sflphone-common/src/config/yamlengine.cpp @@ -32,50 +32,47 @@ #include "../global.h" -namespace Conf { +namespace Conf +{ YamlEngine::YamlEngine() {} YamlEngine::~YamlEngine() {} -void YamlEngine::openConfigFile() +void YamlEngine::openConfigFile() { - Conf::YamlParser *parser = NULL; - - try { - parser = new Conf::YamlParser("sequence.yml"); - } - catch (Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } - - try { - parser->serializeEvents(); - } - catch(Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } - - try { - document = parser->composeEvents(); - } - catch(Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } - - try { - delete parser; - parser = NULL; - } - catch (Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } + Conf::YamlParser *parser = NULL; + + try { + parser = new Conf::YamlParser ("sequence.yml"); + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } + + try { + parser->serializeEvents(); + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } + + try { + document = parser->composeEvents(); + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } + + try { + delete parser; + parser = NULL; + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } } -void YamlEngine::closeConfigFile() +void YamlEngine::closeConfigFile() { - + } void YamlEngine::read() {} diff --git a/sflphone-common/src/config/yamlnode.cpp b/sflphone-common/src/config/yamlnode.cpp old mode 100755 new mode 100644 index 7a28a6cfa66bfd2545f7cb97b4d1e5cdf5eca1bc..00a3aa1d8db8a99ea4baf13e922ec37c4c7e4732 --- a/sflphone-common/src/config/yamlnode.cpp +++ b/sflphone-common/src/config/yamlnode.cpp @@ -31,64 +31,64 @@ #include "yamlnode.h" #include "src/global.h" -namespace Conf { +namespace Conf +{ -void YamlDocument::addNode(YamlNode *node) +void YamlDocument::addNode (YamlNode *node) { - Sequence::iterator it = doc.end(); - doc.insert(it, node); + Sequence::iterator it = doc.end(); + doc.insert (it, node); } YamlNode *YamlDocument::popNode() { - Sequence::iterator it = doc.begin(); - YamlNode *node = doc.front(); + Sequence::iterator it = doc.begin(); + YamlNode *node = doc.front(); - //removed element's destructor is called - doc.pop_front(); + //removed element's destructor is called + doc.pop_front(); - return node; + return node; } -void MappingNode::addNode(YamlNode *node) +void MappingNode::addNode (YamlNode *node) { - Mapping::iterator it = map.end(); - map.insert(it, std::pair<Key, YamlNode *>(tmpKey, node)); + Mapping::iterator it = map.end(); + map.insert (it, std::pair<Key, YamlNode *> (tmpKey, node)); } -void MappingNode::setKeyValue(Key key, YamlNode *value) +void MappingNode::setKeyValue (Key key, YamlNode *value) { - Mapping::iterator it = map.end(); - map.insert(it, std::pair<Key, YamlNode *>(key, value)); + Mapping::iterator it = map.end(); + map.insert (it, std::pair<Key, YamlNode *> (key, value)); } -void MappingNode::removeKeyValue(Key key) +void MappingNode::removeKeyValue (Key key) { -Mapping::iterator it = map.find(key); - map.erase(it); + Mapping::iterator it = map.find (key); + map.erase (it); } -YamlNode *MappingNode::getValue(Key key) +YamlNode *MappingNode::getValue (Key key) { - Mapping::iterator it = map.find(key); - - if(it != map.end()) { - return it->second; - } - else { - _debug("MappingNode: Could not find %s", key.c_str()); - return NULL; - } + Mapping::iterator it = map.find (key); + + if (it != map.end()) { + return it->second; + } else { + _debug ("MappingNode: Could not find %s", key.c_str()); + return NULL; + } } -void SequenceNode::addNode(YamlNode *node) +void SequenceNode::addNode (YamlNode *node) { - Sequence::iterator it = seq.end(); - seq.insert(it, node); + Sequence::iterator it = seq.end(); + seq.insert (it, node); } } diff --git a/sflphone-common/src/config/yamlparser.cpp b/sflphone-common/src/config/yamlparser.cpp index 08a436ad281719bae74cc6f2caf02f531531ab2a..b4d8c5de47ac3afd76f36f778bbffa970b7ff614 100644 --- a/sflphone-common/src/config/yamlparser.cpp +++ b/sflphone-common/src/config/yamlparser.cpp @@ -35,448 +35,449 @@ #include "yamlnode.h" #include <stdio.h> -namespace Conf { - -YamlParser::YamlParser(const char *file) : filename(file) - , accountSequence(NULL) - , preferenceSequence(NULL) - , addressbookSequence(NULL) - , audioSequence(NULL) - , hooksSequence(NULL) - , voiplinkSequence(NULL) - , shortcutSequence(NULL) +namespace Conf { - memset(buffer, 0, PARSER_BUFFERSIZE); - open(); +YamlParser::YamlParser (const char *file) : filename (file) + , accountSequence (NULL) + , preferenceSequence (NULL) + , addressbookSequence (NULL) + , audioSequence (NULL) + , hooksSequence (NULL) + , voiplinkSequence (NULL) + , shortcutSequence (NULL) +{ + memset (buffer, 0, PARSER_BUFFERSIZE); + + open(); } -YamlParser::~YamlParser() +YamlParser::~YamlParser() { - close(); + close(); } -void YamlParser::open() +void YamlParser::open() { - fd = fopen(filename.c_str(), "rb"); + fd = fopen (filename.c_str(), "rb"); - if(!fd) - throw YamlParserException("Could not open file descriptor"); + if (!fd) + throw YamlParserException ("Could not open file descriptor"); - if(!yaml_parser_initialize(&parser)) - throw YamlParserException("Could not open file descriptor"); + if (!yaml_parser_initialize (&parser)) + throw YamlParserException ("Could not open file descriptor"); - yaml_parser_set_input_file(&parser, fd); + yaml_parser_set_input_file (&parser, fd); } -void YamlParser::close() +void YamlParser::close() { - yaml_parser_delete(&parser); + yaml_parser_delete (&parser); - if(!fd) - throw YamlParserException("File descriptor not valid"); + if (!fd) + throw YamlParserException ("File descriptor not valid"); - fclose(fd); - // if(!fclose(fd)) + fclose (fd); + // if(!fclose(fd)) // throw YamlParserException("Error closing file descriptor"); - + } -void YamlParser::serializeEvents() +void YamlParser::serializeEvents() { - bool done = false; - yaml_event_t event; + bool done = false; + yaml_event_t event; - while(!done) { + while (!done) { - if(!yaml_parser_parse(&parser, &event)) - throw YamlParserException("Error while parsing"); + if (!yaml_parser_parse (&parser, &event)) + throw YamlParserException ("Error while parsing"); - done = (event.type == YAML_STREAM_END_EVENT); - - if(eventNumber > PARSER_MAXEVENT) - throw YamlParserException("Reached maximum of event"); + done = (event.type == YAML_STREAM_END_EVENT); - if(!copyEvent(&(events[eventNumber++]), &event)) - throw YamlParserException("Error copying event"); + if (eventNumber > PARSER_MAXEVENT) + throw YamlParserException ("Reached maximum of event"); - } + if (!copyEvent (& (events[eventNumber++]), &event)) + throw YamlParserException ("Error copying event"); + + } } -int YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) +int YamlParser::copyEvent (yaml_event_t *event_to, yaml_event_t *event_from) { - switch (event_from->type) { - case YAML_STREAM_START_EVENT: { - // _debug("YAML_STREAM_START_EVENT"); - return yaml_stream_start_event_initialize(event_to, - event_from->data.stream_start.encoding); - } - - case YAML_STREAM_END_EVENT: { - //_debug("YAML_STREAM_END_EVENT"); - return yaml_stream_end_event_initialize(event_to); - } - - case YAML_DOCUMENT_START_EVENT: { - // _debug("YAML_DOCUMENT_START_EVENT"); - return yaml_document_start_event_initialize(event_to, - event_from->data.document_start.version_directive, - event_from->data.document_start.tag_directives.start, - event_from->data.document_start.tag_directives.end, - event_from->data.document_start.implicit); - } - - case YAML_DOCUMENT_END_EVENT: { - // _debug("YAML_DOCUMENT_END_EVENT"); - return yaml_document_end_event_initialize(event_to, - event_from->data.document_end.implicit); - } - case YAML_ALIAS_EVENT:{ - // _debug("YAML_ALIAS_EVENT"); - return yaml_alias_event_initialize(event_to, - event_from->data.alias.anchor); - } - case YAML_SCALAR_EVENT: { - // _debug("YAML_SCALAR_EVENT"); - return yaml_scalar_event_initialize(event_to, - event_from->data.scalar.anchor, - event_from->data.scalar.tag, - event_from->data.scalar.value, - event_from->data.scalar.length, - event_from->data.scalar.plain_implicit, - event_from->data.scalar.quoted_implicit, - event_from->data.scalar.style); - } - case YAML_SEQUENCE_START_EVENT: { - // _debug("YAML_SEQUENCE_START_EVENT"); - return yaml_sequence_start_event_initialize(event_to, - event_from->data.sequence_start.anchor, - event_from->data.sequence_start.tag, - event_from->data.sequence_start.implicit, - event_from->data.sequence_start.style); - } - case YAML_SEQUENCE_END_EVENT: { - // _debug("YAML_SEQUENCE_END_EVENT"); - return yaml_sequence_end_event_initialize(event_to); - } - case YAML_MAPPING_START_EVENT: { - // _debug("YAML_MAPPING_START_EVENT"); - return yaml_mapping_start_event_initialize(event_to, - event_from->data.mapping_start.anchor, - event_from->data.mapping_start.tag, - event_from->data.mapping_start.implicit, - event_from->data.mapping_start.style); - } - case YAML_MAPPING_END_EVENT: { - // _debug("YAML_MAPPING_END_EVENT"); - return yaml_mapping_end_event_initialize(event_to); - - } - default: - assert(1); - - } - - return 0; + switch (event_from->type) { + case YAML_STREAM_START_EVENT: { + // _debug("YAML_STREAM_START_EVENT"); + return yaml_stream_start_event_initialize (event_to, + event_from->data.stream_start.encoding); + } + + case YAML_STREAM_END_EVENT: { + //_debug("YAML_STREAM_END_EVENT"); + return yaml_stream_end_event_initialize (event_to); + } + + case YAML_DOCUMENT_START_EVENT: { + // _debug("YAML_DOCUMENT_START_EVENT"); + return yaml_document_start_event_initialize (event_to, + event_from->data.document_start.version_directive, + event_from->data.document_start.tag_directives.start, + event_from->data.document_start.tag_directives.end, + event_from->data.document_start.implicit); + } + + case YAML_DOCUMENT_END_EVENT: { + // _debug("YAML_DOCUMENT_END_EVENT"); + return yaml_document_end_event_initialize (event_to, + event_from->data.document_end.implicit); + } + case YAML_ALIAS_EVENT: { + // _debug("YAML_ALIAS_EVENT"); + return yaml_alias_event_initialize (event_to, + event_from->data.alias.anchor); + } + case YAML_SCALAR_EVENT: { + // _debug("YAML_SCALAR_EVENT"); + return yaml_scalar_event_initialize (event_to, + event_from->data.scalar.anchor, + event_from->data.scalar.tag, + event_from->data.scalar.value, + event_from->data.scalar.length, + event_from->data.scalar.plain_implicit, + event_from->data.scalar.quoted_implicit, + event_from->data.scalar.style); + } + case YAML_SEQUENCE_START_EVENT: { + // _debug("YAML_SEQUENCE_START_EVENT"); + return yaml_sequence_start_event_initialize (event_to, + event_from->data.sequence_start.anchor, + event_from->data.sequence_start.tag, + event_from->data.sequence_start.implicit, + event_from->data.sequence_start.style); + } + case YAML_SEQUENCE_END_EVENT: { + // _debug("YAML_SEQUENCE_END_EVENT"); + return yaml_sequence_end_event_initialize (event_to); + } + case YAML_MAPPING_START_EVENT: { + // _debug("YAML_MAPPING_START_EVENT"); + return yaml_mapping_start_event_initialize (event_to, + event_from->data.mapping_start.anchor, + event_from->data.mapping_start.tag, + event_from->data.mapping_start.implicit, + event_from->data.mapping_start.style); + } + case YAML_MAPPING_END_EVENT: { + // _debug("YAML_MAPPING_END_EVENT"); + return yaml_mapping_end_event_initialize (event_to); + + } + default: + assert (1); + + } + + return 0; } -YamlDocument *YamlParser::composeEvents() { +YamlDocument *YamlParser::composeEvents() +{ - // _debug("YamlParser: Compose Events"); + // _debug("YamlParser: Compose Events"); - if(eventNumber == 0) - throw YamlParserException("No event available"); + if (eventNumber == 0) + throw YamlParserException ("No event available"); - if(events[0].type != YAML_STREAM_START_EVENT) - throw YamlParserException("Parsing does not start with stream start"); + if (events[0].type != YAML_STREAM_START_EVENT) + throw YamlParserException ("Parsing does not start with stream start"); - eventIndex = 0; + eventIndex = 0; - processStream(); + processStream(); - return doc; + return doc; } -void YamlParser::processStream () { +void YamlParser::processStream () +{ - // _debug("YamlParser: process stream"); + // _debug("YamlParser: process stream"); - while((eventIndex < eventNumber) && (events[eventIndex].type != YAML_STREAM_END_EVENT)) { + while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_STREAM_END_EVENT)) { - if(events[eventIndex].type == YAML_DOCUMENT_START_EVENT) - processDocument(); + if (events[eventIndex].type == YAML_DOCUMENT_START_EVENT) + processDocument(); - eventIndex++; - } + eventIndex++; + } - if(events[eventIndex].type != YAML_STREAM_END_EVENT) - throw YamlParserException("Did not found end of stream"); + if (events[eventIndex].type != YAML_STREAM_END_EVENT) + throw YamlParserException ("Did not found end of stream"); } void YamlParser::processDocument() { - // _debug("YamlParser: process document"); - - doc = new YamlDocument(); - - if(!doc) - throw YamlParserException("Not able to create new document"); - - while((eventIndex < eventNumber) && (events[eventIndex].type != YAML_DOCUMENT_END_EVENT)) { - - switch(events[eventIndex].type){ - case YAML_SCALAR_EVENT: - processScalar((YamlNode *)doc); - break; - case YAML_SEQUENCE_START_EVENT: - processSequence((YamlNode *)doc); - break; - case YAML_MAPPING_START_EVENT: - processMapping((YamlNode *)doc); - break; - default: - break; + // _debug("YamlParser: process document"); + + doc = new YamlDocument(); + + if (!doc) + throw YamlParserException ("Not able to create new document"); + + while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_DOCUMENT_END_EVENT)) { + + switch (events[eventIndex].type) { + case YAML_SCALAR_EVENT: + processScalar ( (YamlNode *) doc); + break; + case YAML_SEQUENCE_START_EVENT: + processSequence ( (YamlNode *) doc); + break; + case YAML_MAPPING_START_EVENT: + processMapping ( (YamlNode *) doc); + break; + default: + break; + } + + eventIndex++; } - eventIndex++; - } + if (events[eventIndex].type != YAML_DOCUMENT_END_EVENT) + throw YamlParserException ("Did not found end of document"); - if(events[eventIndex].type != YAML_DOCUMENT_END_EVENT) - throw YamlParserException("Did not found end of document"); - } -void YamlParser::processScalar(YamlNode *topNode) +void YamlParser::processScalar (YamlNode *topNode) { - // _debug("YamlParser: process scalar"); - - if(!topNode) - throw YamlParserException("No container for scalar"); - - char buffer[1000]; - snprintf(buffer, 1000, "%s", events[eventIndex].data.scalar.value); - // _debug("and the scalar is: %s", buffer); - - ScalarNode *sclr = new ScalarNode(buffer, topNode); - - switch(topNode->getType()) { - case DOCUMENT: - ((YamlDocument *)(topNode))->addNode(sclr); - break; - case SEQUENCE: - ((SequenceNode *)(topNode))->addNode(sclr); - break; - case MAPPING: - ((MappingNode *)(topNode))->addNode(sclr); - case SCALAR: - default: - break; - } + // _debug("YamlParser: process scalar"); + + if (!topNode) + throw YamlParserException ("No container for scalar"); + + char buffer[1000]; + snprintf (buffer, 1000, "%s", events[eventIndex].data.scalar.value); + // _debug("and the scalar is: %s", buffer); + + ScalarNode *sclr = new ScalarNode (buffer, topNode); + + switch (topNode->getType()) { + case DOCUMENT: + ( (YamlDocument *) (topNode))->addNode (sclr); + break; + case SEQUENCE: + ( (SequenceNode *) (topNode))->addNode (sclr); + break; + case MAPPING: + ( (MappingNode *) (topNode))->addNode (sclr); + case SCALAR: + default: + break; + } } -void YamlParser::processSequence(YamlNode *topNode) +void YamlParser::processSequence (YamlNode *topNode) { - _debug("YamlParser: process sequence"); - - if(!topNode) - throw YamlParserException("No container for sequence"); - - SequenceNode *seq = new SequenceNode(topNode); - - switch(topNode->getType()) { - case DOCUMENT: - ((YamlDocument *)(topNode))->addNode(seq); - break; - case SEQUENCE: - ((SequenceNode *)(topNode))->addNode(seq); - break; - case MAPPING: - ((MappingNode *)(topNode))->addNode(seq); - case SCALAR: - default: - break; - } - - eventIndex++; - - while((eventIndex < eventNumber) && (events[eventIndex].type != YAML_SEQUENCE_END_EVENT)) { - - switch(events[eventIndex].type){ - case YAML_SCALAR_EVENT: - processScalar(seq); - break; - case YAML_SEQUENCE_START_EVENT: - processSequence(seq); - break; - case YAML_MAPPING_START_EVENT: - processMapping(seq); - break; - default: - break; + _debug ("YamlParser: process sequence"); + + if (!topNode) + throw YamlParserException ("No container for sequence"); + + SequenceNode *seq = new SequenceNode (topNode); + + switch (topNode->getType()) { + case DOCUMENT: + ( (YamlDocument *) (topNode))->addNode (seq); + break; + case SEQUENCE: + ( (SequenceNode *) (topNode))->addNode (seq); + break; + case MAPPING: + ( (MappingNode *) (topNode))->addNode (seq); + case SCALAR: + default: + break; } eventIndex++; - } - if(events[eventIndex].type != YAML_SEQUENCE_END_EVENT) - throw YamlParserException("Did not found end of sequence"); + while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_SEQUENCE_END_EVENT)) { + + switch (events[eventIndex].type) { + case YAML_SCALAR_EVENT: + processScalar (seq); + break; + case YAML_SEQUENCE_START_EVENT: + processSequence (seq); + break; + case YAML_MAPPING_START_EVENT: + processMapping (seq); + break; + default: + break; + } + + eventIndex++; + } + + if (events[eventIndex].type != YAML_SEQUENCE_END_EVENT) + throw YamlParserException ("Did not found end of sequence"); } -void YamlParser::processMapping(YamlNode *topNode) +void YamlParser::processMapping (YamlNode *topNode) { - // _debug("YamlParser: process mapping"); - - if(!topNode) - throw YamlParserException("No container for mapping"); - - MappingNode *map = new MappingNode(topNode); - - switch(topNode->getType()) { - case DOCUMENT: - ((YamlDocument *)(topNode))->addNode(map); - break; - case SEQUENCE: - ((SequenceNode *)(topNode))->addNode(map); - break; - case MAPPING: - ((MappingNode *)(topNode))->addNode(map); - case SCALAR: - default: - break; - } - - eventIndex++; - - while((eventIndex < eventNumber) && (events[eventIndex].type != YAML_MAPPING_END_EVENT)) { - - if(events[eventIndex].type != YAML_SCALAR_EVENT) - throw YamlParserException("Mapping not followed by a key"); - - char buffer[1000]; - snprintf(buffer, 1000, "%s", events[eventIndex].data.scalar.value); - map->setTmpKey(Key(buffer)); - // _debug("KEY %s", buffer); - - eventIndex++; - - switch(events[eventIndex].type){ - case YAML_SCALAR_EVENT: - processScalar(map); - break; - case YAML_SEQUENCE_START_EVENT: - processSequence(map); - break; - case YAML_MAPPING_START_EVENT: - processMapping(map); - break; - default: - break; + // _debug("YamlParser: process mapping"); + + if (!topNode) + throw YamlParserException ("No container for mapping"); + + MappingNode *map = new MappingNode (topNode); + + switch (topNode->getType()) { + case DOCUMENT: + ( (YamlDocument *) (topNode))->addNode (map); + break; + case SEQUENCE: + ( (SequenceNode *) (topNode))->addNode (map); + break; + case MAPPING: + ( (MappingNode *) (topNode))->addNode (map); + case SCALAR: + default: + break; } eventIndex++; - } - if(events[eventIndex].type != YAML_MAPPING_END_EVENT) - throw YamlParserException("Did not found end of mapping"); -} - -void YamlParser::constructNativeData() { - - Sequence *seq; - - seq = doc->getSequence(); - - Sequence::iterator iter = seq->begin(); - - while(iter != seq->end()) { - - switch((*iter)->getType()){ - case SCALAR: - // _debug("construct scalar"); - throw YamlParserException("No scalar allowed at document level, expect a mapping"); - break; - case SEQUENCE: - // _debug("construct sequence"); - throw YamlParserException("No sequence allowed at document level, expect a mapping"); - break; - case MAPPING: { - // _debug("construct mapping"); - MappingNode *map = (MappingNode *)(*iter); - mainNativeDataMapping(map); - break; - } - default: - throw YamlParserException("Unknown type in configuration file, expect a mapping"); - break; + while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_MAPPING_END_EVENT)) { + + if (events[eventIndex].type != YAML_SCALAR_EVENT) + throw YamlParserException ("Mapping not followed by a key"); + + char buffer[1000]; + snprintf (buffer, 1000, "%s", events[eventIndex].data.scalar.value); + map->setTmpKey (Key (buffer)); + // _debug("KEY %s", buffer); + + eventIndex++; + + switch (events[eventIndex].type) { + case YAML_SCALAR_EVENT: + processScalar (map); + break; + case YAML_SEQUENCE_START_EVENT: + processSequence (map); + break; + case YAML_MAPPING_START_EVENT: + processMapping (map); + break; + default: + break; + } + + eventIndex++; } - iter++; - } - + if (events[eventIndex].type != YAML_MAPPING_END_EVENT) + throw YamlParserException ("Did not found end of mapping"); } +void YamlParser::constructNativeData() +{ -void YamlParser::mainNativeDataMapping(MappingNode *map) { + Sequence *seq; - - Mapping::iterator iter = map->getMapping()->begin(); + seq = doc->getSequence(); - Key accounts("accounts"); - Key addressbook("addressbook"); - Key audio("audio"); - Key hooks("hooks"); - Key preferences("preferences"); - Key voiplink("voipPreferences"); - Key shortcuts("shortcuts"); + Sequence::iterator iter = seq->begin(); - while(iter != map->getMapping()->end()) { + while (iter != seq->end()) { + + switch ( (*iter)->getType()) { + case SCALAR: + // _debug("construct scalar"); + throw YamlParserException ("No scalar allowed at document level, expect a mapping"); + break; + case SEQUENCE: + // _debug("construct sequence"); + throw YamlParserException ("No sequence allowed at document level, expect a mapping"); + break; + case MAPPING: { + // _debug("construct mapping"); + MappingNode *map = (MappingNode *) (*iter); + mainNativeDataMapping (map); + break; + } + default: + throw YamlParserException ("Unknown type in configuration file, expect a mapping"); + break; + } + + iter++; - _debug("Iterating: %s", iter->first.c_str()); - if(accounts.compare(iter->first) == 0) { - _debug("YamlParser: Adding voip account preferences"); - accountSequence = (SequenceNode *)(iter->second); - } - else if(addressbook.compare(iter->first) == 0) { - _debug("YamlParser: Adding addressbook preference"); - addressbookSequence = (SequenceNode *)(iter->second); - } - else if(audio.compare(iter->first) == 0) { - _debug("YamlParser: Adding audio preference"); - audioSequence = (SequenceNode *)(iter->second); - } - else if(hooks.compare(iter->first) == 0) { - _debug("YamlParser: Adding hooks preference"); - hooksSequence = (SequenceNode *)(iter->second); - } - else if(preferences.compare(iter->first) == 0) { - _debug("YamlParser: Adding preference preference"); - preferenceSequence = (SequenceNode *)(iter->second); - } - else if(voiplink.compare(iter->first) == 0) { - _debug("YamlParser: Adding voip preference"); - voiplinkSequence = (SequenceNode *)(iter->second); } - else if(shortcuts.compare(iter->first) == 0) { - _debug("YamlParser: Adding shortcut preference"); - shortcutSequence = (SequenceNode *)(iter->second); + +} + + +void YamlParser::mainNativeDataMapping (MappingNode *map) +{ + + + Mapping::iterator iter = map->getMapping()->begin(); + + Key accounts ("accounts"); + Key addressbook ("addressbook"); + Key audio ("audio"); + Key hooks ("hooks"); + Key preferences ("preferences"); + Key voiplink ("voipPreferences"); + Key shortcuts ("shortcuts"); + + while (iter != map->getMapping()->end()) { + + _debug ("Iterating: %s", iter->first.c_str()); + + if (accounts.compare (iter->first) == 0) { + _debug ("YamlParser: Adding voip account preferences"); + accountSequence = (SequenceNode *) (iter->second); + } else if (addressbook.compare (iter->first) == 0) { + _debug ("YamlParser: Adding addressbook preference"); + addressbookSequence = (SequenceNode *) (iter->second); + } else if (audio.compare (iter->first) == 0) { + _debug ("YamlParser: Adding audio preference"); + audioSequence = (SequenceNode *) (iter->second); + } else if (hooks.compare (iter->first) == 0) { + _debug ("YamlParser: Adding hooks preference"); + hooksSequence = (SequenceNode *) (iter->second); + } else if (preferences.compare (iter->first) == 0) { + _debug ("YamlParser: Adding preference preference"); + preferenceSequence = (SequenceNode *) (iter->second); + } else if (voiplink.compare (iter->first) == 0) { + _debug ("YamlParser: Adding voip preference"); + voiplinkSequence = (SequenceNode *) (iter->second); + } else if (shortcuts.compare (iter->first) == 0) { + _debug ("YamlParser: Adding shortcut preference"); + shortcutSequence = (SequenceNode *) (iter->second); + } else + throw YamlParserException ("Unknow map key in configuration"); + + iter++; } - else - throw YamlParserException("Unknow map key in configuration"); - iter++; - } - // _debug("Done"); + // _debug("Done"); } } diff --git a/sflphone-common/src/dbus/callmanager.cpp b/sflphone-common/src/dbus/callmanager.cpp index 5662b4640408d9c59180242f98385f3b938c1a6c..4a12567c8bc8e9b0d9c8d1db873438a8e346e406 100644 --- a/sflphone-common/src/dbus/callmanager.cpp +++ b/sflphone-common/src/dbus/callmanager.cpp @@ -58,12 +58,12 @@ CallManager::placeCall (const std::string& accountID, void CallManager::placeCallFirstAccount (const std::string& callID, - const std::string& to) + const std::string& to) { if (to == "") { - _warn("CallManager: Warning: No number entered, call stopped"); - return; + _warn ("CallManager: Warning: No number entered, call stopped"); + return; } std::vector< std::string > accountOrder = Manager::instance().loadAccountOrder(); @@ -71,47 +71,50 @@ CallManager::placeCallFirstAccount (const std::string& callID, Account *account; - _debug("AccountOrder size: %d", accountOrder.size()); + _debug ("AccountOrder size: %d", accountOrder.size()); - if(accountOrder.size() > 0) { + if (accountOrder.size() > 0) { - iter = accountOrder.begin(); + iter = accountOrder.begin(); - while(iter != accountOrder.end()) { - account = Manager::instance().getAccount(*iter); - if((*iter != IP2IP_PROFILE) && account->isEnabled()) { - Manager::instance().outgoingCall (*iter, callID, to); - return; - } + while (iter != accountOrder.end()) { + account = Manager::instance().getAccount (*iter); - iter++; - } - } - else { - _error("AccountOrder is empty"); - // If accountOrder is empty fallback on accountList (which has no preference order) - std::vector< std::string > accountList = Manager::instance().getAccountList(); - iter = accountList.begin(); - - - _error("AccountList size: %d", accountList.size()); - if(accountList.size() > 0) { - while(iter != accountList.end()) { - _error("iter"); - account = Manager::instance().getAccount(*iter); - if((*iter != IP2IP_PROFILE) && account->isEnabled()) { - _error("makecall"); - Manager::instance().outgoingCall(*iter, callID, to); - return; - } - iter++; - } - - } + if ( (*iter != IP2IP_PROFILE) && account->isEnabled()) { + Manager::instance().outgoingCall (*iter, callID, to); + return; + } + + iter++; + } + } else { + _error ("AccountOrder is empty"); + // If accountOrder is empty fallback on accountList (which has no preference order) + std::vector< std::string > accountList = Manager::instance().getAccountList(); + iter = accountList.begin(); + + + _error ("AccountList size: %d", accountList.size()); + + if (accountList.size() > 0) { + while (iter != accountList.end()) { + _error ("iter"); + account = Manager::instance().getAccount (*iter); + + if ( (*iter != IP2IP_PROFILE) && account->isEnabled()) { + _error ("makecall"); + Manager::instance().outgoingCall (*iter, callID, to); + return; + } + + iter++; + } + + } } - - _warn("CallManager: Warning: No enabled account found, call stopped"); - + + _warn ("CallManager: Warning: No enabled account found, call stopped"); + } void @@ -261,7 +264,7 @@ CallManager::getConferenceList (void) std::vector< std::string > CallManager::getParticipantList (const std::string& confID) { - _debug("CallManager: Get Participant list for conference %s", confID.c_str()); + _debug ("CallManager: Get Participant list for conference %s", confID.c_str()); return Manager::instance().getParticipantList (confID); } diff --git a/sflphone-common/src/dbus/configurationmanager.cpp b/sflphone-common/src/dbus/configurationmanager.cpp old mode 100755 new mode 100644 index 51efa50b5fe86fbac31a26a3fc84e4daca641af5..68d659ff958c0a040ab316358a7f0f00976b6a2d --- a/sflphone-common/src/dbus/configurationmanager.cpp +++ b/sflphone-common/src/dbus/configurationmanager.cpp @@ -38,519 +38,595 @@ #include "sip/sipaccount.h" const char* ConfigurationManager::SERVER_PATH = - "/org/sflphone/SFLphone/ConfigurationManager"; - -ConfigurationManager::ConfigurationManager(DBus::Connection& connection) : - DBus::ObjectAdaptor(connection, SERVER_PATH) { - shortcutsKeys.push_back("pick_up"); - shortcutsKeys.push_back("hang_up"); - shortcutsKeys.push_back("popup_window"); - shortcutsKeys.push_back("toggle_pick_up_hang_up"); - shortcutsKeys.push_back("toggle_hold"); + "/org/sflphone/SFLphone/ConfigurationManager"; + +ConfigurationManager::ConfigurationManager (DBus::Connection& connection) : + DBus::ObjectAdaptor (connection, SERVER_PATH) +{ + shortcutsKeys.push_back ("pick_up"); + shortcutsKeys.push_back ("hang_up"); + shortcutsKeys.push_back ("popup_window"); + shortcutsKeys.push_back ("toggle_pick_up_hang_up"); + shortcutsKeys.push_back ("toggle_hold"); } -std::map<std::string, std::string> ConfigurationManager::getAccountDetails( - const std::string& accountID) { +std::map<std::string, std::string> ConfigurationManager::getAccountDetails ( + const std::string& accountID) +{ - _debug("ConfigurationManager: get account details %s", accountID.c_str()); - return Manager::instance().getAccountDetails(accountID); + _debug ("ConfigurationManager: get account details %s", accountID.c_str()); + return Manager::instance().getAccountDetails (accountID); } -std::map<std::string, std::string> ConfigurationManager::getTlsSettingsDefault( - void) { +std::map<std::string, std::string> ConfigurationManager::getTlsSettingsDefault ( + void) +{ - std::map<std::string, std::string> tlsSettingsDefault; + std::map<std::string, std::string> tlsSettingsDefault; - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_LISTENER_PORT, DEFAULT_SIP_TLS_PORT)); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_CA_LIST_FILE, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_CERTIFICATE_FILE, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_PRIVATE_KEY_FILE, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>(TLS_PASSWORD, - "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>(TLS_METHOD, - "TLSv1")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>(TLS_CIPHERS, - "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_SERVER_NAME, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_VERIFY_SERVER, "true")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_VERIFY_CLIENT, "true")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_REQUIRE_CLIENT_CERTIFICATE, "true")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_NEGOTIATION_TIMEOUT_SEC, "2")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_NEGOTIATION_TIMEOUT_MSEC, "0")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_LISTENER_PORT, DEFAULT_SIP_TLS_PORT)); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_CA_LIST_FILE, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_CERTIFICATE_FILE, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_PRIVATE_KEY_FILE, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_PASSWORD, + "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_METHOD, + "TLSv1")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_CIPHERS, + "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_SERVER_NAME, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_VERIFY_SERVER, "true")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_VERIFY_CLIENT, "true")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_REQUIRE_CLIENT_CERTIFICATE, "true")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_NEGOTIATION_TIMEOUT_SEC, "2")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_NEGOTIATION_TIMEOUT_MSEC, "0")); - return tlsSettingsDefault; + return tlsSettingsDefault; } -std::map<std::string, std::string> ConfigurationManager::getIp2IpDetails(void) { +std::map<std::string, std::string> ConfigurationManager::getIp2IpDetails (void) +{ - std::map<std::string, std::string> ip2ipAccountDetails; + std::map<std::string, std::string> ip2ipAccountDetails; - SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(IP2IP_PROFILE); + SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); - if(!sipaccount) { - _error("ConfigurationManager: could not find account"); - return ip2ipAccountDetails; - } + if (!sipaccount) { + _error ("ConfigurationManager: could not find account"); + return ip2ipAccountDetails; + } - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ACCOUNT_ID, IP2IP_PROFILE)); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(SRTP_KEY_EXCHANGE, sipaccount->getSrtpKeyExchange())); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(SRTP_ENABLE, sipaccount->getSrtpEnable() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(SRTP_RTP_FALLBACK, sipaccount->getSrtpFallback() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ZRTP_DISPLAY_SAS, sipaccount->getZrtpDisplaySas() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ZRTP_HELLO_HASH, sipaccount->getZrtpHelloHash() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ZRTP_NOT_SUPP_WARNING, sipaccount->getZrtpNotSuppWarning() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ZRTP_DISPLAY_SAS_ONCE, sipaccount->getZrtpDiaplaySasOnce() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(LOCAL_INTERFACE, sipaccount->getLocalInterface())); - std::stringstream portstr; portstr << sipaccount->getLocalPort(); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(LOCAL_PORT, portstr.str())); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ACCOUNT_ID, IP2IP_PROFILE)); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, sipaccount->getSrtpKeyExchange())); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (SRTP_ENABLE, sipaccount->getSrtpEnable() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (SRTP_RTP_FALLBACK, sipaccount->getSrtpFallback() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, sipaccount->getZrtpDisplaySas() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_HELLO_HASH, sipaccount->getZrtpHelloHash() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, sipaccount->getZrtpNotSuppWarning() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, sipaccount->getZrtpDiaplaySasOnce() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (LOCAL_INTERFACE, sipaccount->getLocalInterface())); + std::stringstream portstr; + portstr << sipaccount->getLocalPort(); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (LOCAL_PORT, portstr.str())); - std::map<std::string, std::string> tlsSettings; - tlsSettings = getTlsSettings(); - std::copy(tlsSettings.begin(), tlsSettings.end(), std::inserter( - ip2ipAccountDetails, ip2ipAccountDetails.end())); + std::map<std::string, std::string> tlsSettings; + tlsSettings = getTlsSettings(); + std::copy (tlsSettings.begin(), tlsSettings.end(), std::inserter ( + ip2ipAccountDetails, ip2ipAccountDetails.end())); - return ip2ipAccountDetails; + return ip2ipAccountDetails; } -void ConfigurationManager::setIp2IpDetails(const std::map<std::string, - std::string>& details) { - std::map<std::string, std::string> map_cpy = details; - std::map<std::string, std::string>::iterator it; +void ConfigurationManager::setIp2IpDetails (const std::map<std::string, + std::string>& details) +{ + std::map<std::string, std::string> map_cpy = details; + std::map<std::string, std::string>::iterator it; - SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(IP2IP_PROFILE); + SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); - if(!sipaccount) { - _error("ConfigurationManager: could not find account"); - } - + if (!sipaccount) { + _error ("ConfigurationManager: could not find account"); + } - it = map_cpy.find(LOCAL_INTERFACE); - if (it != details.end()) sipaccount->setLocalInterface(it->second); - it = map_cpy.find(LOCAL_PORT); - if (it != details.end()) sipaccount->setLocalPort(atoi(it->second.data())); + it = map_cpy.find (LOCAL_INTERFACE); - it = map_cpy.find(SRTP_ENABLE); - if (it != details.end()) sipaccount->setSrtpEnable((it->second == "true")); + if (it != details.end()) sipaccount->setLocalInterface (it->second); - it = map_cpy.find(SRTP_RTP_FALLBACK); - if (it != details.end()) sipaccount->setSrtpFallback((it->second == "true")); + it = map_cpy.find (LOCAL_PORT); - it = map_cpy.find(SRTP_KEY_EXCHANGE); - if (it != details.end()) sipaccount->setSrtpKeyExchange(it->second); + if (it != details.end()) sipaccount->setLocalPort (atoi (it->second.data())); - it = map_cpy.find(ZRTP_DISPLAY_SAS); - if (it != details.end()) sipaccount->setZrtpDisplaySas((it->second == "true")); + it = map_cpy.find (SRTP_ENABLE); - it = map_cpy.find(ZRTP_NOT_SUPP_WARNING); - if (it != details.end()) sipaccount->setZrtpNotSuppWarning((it->second == "true")); + if (it != details.end()) sipaccount->setSrtpEnable ( (it->second == "true")); - it = map_cpy.find(ZRTP_HELLO_HASH); - if (it != details.end()) sipaccount->setZrtpHelloHash((it->second == "true")); + it = map_cpy.find (SRTP_RTP_FALLBACK); - it = map_cpy.find(ZRTP_DISPLAY_SAS_ONCE); - if (it != details.end()) sipaccount->setZrtpDiaplaySasOnce((it->second == "true")); + if (it != details.end()) sipaccount->setSrtpFallback ( (it->second == "true")); - setTlsSettings(details); + it = map_cpy.find (SRTP_KEY_EXCHANGE); - Manager::instance().saveConfig(); + if (it != details.end()) sipaccount->setSrtpKeyExchange (it->second); - // Update account details to the client side - accountsChanged(); + it = map_cpy.find (ZRTP_DISPLAY_SAS); - // Reload account settings from config - Manager::instance().getAccount(IP2IP_PROFILE)->loadConfig(); + if (it != details.end()) sipaccount->setZrtpDisplaySas ( (it->second == "true")); + + it = map_cpy.find (ZRTP_NOT_SUPP_WARNING); + + if (it != details.end()) sipaccount->setZrtpNotSuppWarning ( (it->second == "true")); + + it = map_cpy.find (ZRTP_HELLO_HASH); + + if (it != details.end()) sipaccount->setZrtpHelloHash ( (it->second == "true")); + + it = map_cpy.find (ZRTP_DISPLAY_SAS_ONCE); + + if (it != details.end()) sipaccount->setZrtpDiaplaySasOnce ( (it->second == "true")); + + setTlsSettings (details); + + Manager::instance().saveConfig(); + + // Update account details to the client side + accountsChanged(); + + // Reload account settings from config + Manager::instance().getAccount (IP2IP_PROFILE)->loadConfig(); } -std::map<std::string, std::string> ConfigurationManager::getTlsSettings() { +std::map<std::string, std::string> ConfigurationManager::getTlsSettings() +{ - std::map<std::string, std::string> tlsSettings; + std::map<std::string, std::string> tlsSettings; - SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(IP2IP_PROFILE); + SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); - if(!sipaccount) - return tlsSettings; + if (!sipaccount) + return tlsSettings; - std::stringstream portstr; portstr << sipaccount->getTlsListenerPort(); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_LISTENER_PORT, portstr.str())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_ENABLE, sipaccount->getTlsEnable())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_CA_LIST_FILE, sipaccount->getTlsCaListFile())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_CERTIFICATE_FILE, sipaccount->getTlsCertificateFile())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_PRIVATE_KEY_FILE, sipaccount->getTlsPrivateKeyFile())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_PASSWORD, sipaccount->getTlsPassword())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_METHOD, sipaccount->getTlsMethod())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_CIPHERS, sipaccount->getTlsCiphers())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_SERVER_NAME, sipaccount->getTlsServerName())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_VERIFY_SERVER, sipaccount->getTlsVerifyServer() ? "true" : "false")); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_VERIFY_CLIENT, sipaccount->getTlsVerifyClient() ? "true" : "false")); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_REQUIRE_CLIENT_CERTIFICATE, sipaccount->getTlsRequireClientCertificate() ? "true" : "false")); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_NEGOTIATION_TIMEOUT_SEC, sipaccount->getTlsNegotiationTimeoutSec())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_NEGOTIATION_TIMEOUT_MSEC, sipaccount->getTlsNegotiationTimeoutMsec())); + std::stringstream portstr; + portstr << sipaccount->getTlsListenerPort(); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_LISTENER_PORT, portstr.str())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_ENABLE, sipaccount->getTlsEnable())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_CA_LIST_FILE, sipaccount->getTlsCaListFile())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, sipaccount->getTlsCertificateFile())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, sipaccount->getTlsPrivateKeyFile())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_PASSWORD, sipaccount->getTlsPassword())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_METHOD, sipaccount->getTlsMethod())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_CIPHERS, sipaccount->getTlsCiphers())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_SERVER_NAME, sipaccount->getTlsServerName())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_VERIFY_SERVER, sipaccount->getTlsVerifyServer() ? "true" : "false")); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, sipaccount->getTlsVerifyClient() ? "true" : "false")); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, sipaccount->getTlsRequireClientCertificate() ? "true" : "false")); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, sipaccount->getTlsNegotiationTimeoutSec())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, sipaccount->getTlsNegotiationTimeoutMsec())); - return tlsSettings; + return tlsSettings; } -void ConfigurationManager::setTlsSettings(const std::map<std::string, std::string>& details) { +void ConfigurationManager::setTlsSettings (const std::map<std::string, std::string>& details) +{ + + std::map<std::string, std::string> map_cpy = details; + std::map<std::string, std::string>::iterator it; + + SIPAccount * sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); + + if (!sipaccount) { + _debug ("ConfigurationManager: Error: No valid account in set TLS settings"); + return; + } + + it = map_cpy.find (TLS_LISTENER_PORT); + + if (it != details.end()) sipaccount->setTlsListenerPort (atoi (it->second.data())); - std::map<std::string, std::string> map_cpy = details; - std::map<std::string, std::string>::iterator it; + it = map_cpy.find (TLS_ENABLE); - SIPAccount * sipaccount = (SIPAccount *)Manager::instance().getAccount(IP2IP_PROFILE); + if (it != details.end()) sipaccount->setTlsEnable (it->second); - if(!sipaccount) { - _debug("ConfigurationManager: Error: No valid account in set TLS settings"); - return; - } + it = map_cpy.find (TLS_CA_LIST_FILE); - it = map_cpy.find(TLS_LISTENER_PORT); - if (it != details.end()) sipaccount->setTlsListenerPort(atoi(it->second.data())); + if (it != map_cpy.end()) sipaccount->setTlsCaListFile (it->second); - it = map_cpy.find(TLS_ENABLE); - if (it != details.end()) sipaccount->setTlsEnable(it->second); + it = map_cpy.find (TLS_CERTIFICATE_FILE); - it = map_cpy.find(TLS_CA_LIST_FILE); - if (it != map_cpy.end()) sipaccount->setTlsCaListFile(it->second); + if (it != map_cpy.end()) sipaccount->setTlsCertificateFile (it->second); - it = map_cpy.find(TLS_CERTIFICATE_FILE); - if (it != map_cpy.end()) sipaccount->setTlsCertificateFile(it->second); + it = map_cpy.find (TLS_PRIVATE_KEY_FILE); - it = map_cpy.find(TLS_PRIVATE_KEY_FILE); - if (it != map_cpy.end()) sipaccount->setTlsPrivateKeyFile(it->second); + if (it != map_cpy.end()) sipaccount->setTlsPrivateKeyFile (it->second); - it = map_cpy.find(TLS_PASSWORD); - if (it != map_cpy.end()) sipaccount->setTlsPassword(it->second); + it = map_cpy.find (TLS_PASSWORD); - it = map_cpy.find(TLS_METHOD); - if (it != map_cpy.end()) sipaccount->setTlsMethod(it->second); + if (it != map_cpy.end()) sipaccount->setTlsPassword (it->second); - it = map_cpy.find(TLS_CIPHERS); - if (it != map_cpy.end()) sipaccount->setTlsCiphers(it->second); + it = map_cpy.find (TLS_METHOD); - it = map_cpy.find(TLS_SERVER_NAME); - if (it != map_cpy.end()) sipaccount->setTlsServerName(it->second); + if (it != map_cpy.end()) sipaccount->setTlsMethod (it->second); - it = map_cpy.find(TLS_VERIFY_CLIENT); - if (it != map_cpy.end()) sipaccount->setTlsVerifyClient((it->second == "true") ? true : false); + it = map_cpy.find (TLS_CIPHERS); - it = map_cpy.find(TLS_REQUIRE_CLIENT_CERTIFICATE); - if (it != map_cpy.end()) sipaccount->setTlsRequireClientCertificate((it->second == "true") ? true : false); + if (it != map_cpy.end()) sipaccount->setTlsCiphers (it->second); - it = map_cpy.find(TLS_NEGOTIATION_TIMEOUT_SEC); - if (it != map_cpy.end()) sipaccount->setTlsNegotiationTimeoutSec(it->second); + it = map_cpy.find (TLS_SERVER_NAME); - it = map_cpy.find(TLS_NEGOTIATION_TIMEOUT_MSEC); - if (it != map_cpy.end()) sipaccount->setTlsNegotiationTimeoutMsec(it->second); + if (it != map_cpy.end()) sipaccount->setTlsServerName (it->second); - Manager::instance().saveConfig(); + it = map_cpy.find (TLS_VERIFY_CLIENT); - // Update account details to the client side - accountsChanged(); + if (it != map_cpy.end()) sipaccount->setTlsVerifyClient ( (it->second == "true") ? true : false); + + it = map_cpy.find (TLS_REQUIRE_CLIENT_CERTIFICATE); + + if (it != map_cpy.end()) sipaccount->setTlsRequireClientCertificate ( (it->second == "true") ? true : false); + + it = map_cpy.find (TLS_NEGOTIATION_TIMEOUT_SEC); + + if (it != map_cpy.end()) sipaccount->setTlsNegotiationTimeoutSec (it->second); + + it = map_cpy.find (TLS_NEGOTIATION_TIMEOUT_MSEC); + + if (it != map_cpy.end()) sipaccount->setTlsNegotiationTimeoutMsec (it->second); + + Manager::instance().saveConfig(); + + // Update account details to the client side + accountsChanged(); } -std::map<std::string, std::string> ConfigurationManager::getCredential( - const std::string& accountID, const int32_t& index) { +std::map<std::string, std::string> ConfigurationManager::getCredential ( + const std::string& accountID, const int32_t& index) +{ + + Account *account = Manager::instance().getAccount (accountID); - Account *account = Manager::instance().getAccount(accountID); + std::map<std::string, std::string> credentialInformation; - std::map<std::string, std::string> credentialInformation; + if (account->getType() != "SIP") + return credentialInformation; - if(account->getType() != "SIP") - return credentialInformation; + SIPAccount *sipaccount = (SIPAccount *) account; - SIPAccount *sipaccount = (SIPAccount *)account; - - if(index == 0) { - std::string username = sipaccount->getUsername(); - std::string password = sipaccount->getPassword(); + if (index == 0) { + std::string username = sipaccount->getUsername(); + std::string password = sipaccount->getPassword(); std::string realm = sipaccount->getRealm(); - credentialInformation.insert(std::pair<std::string, std::string>(USERNAME, username)); - credentialInformation.insert(std::pair<std::string, std::string>(PASSWORD, password)); - credentialInformation.insert(std::pair<std::string, std::string>(REALM, realm)); - } - else { + credentialInformation.insert (std::pair<std::string, std::string> (USERNAME, username)); + credentialInformation.insert (std::pair<std::string, std::string> (PASSWORD, password)); + credentialInformation.insert (std::pair<std::string, std::string> (REALM, realm)); + } else { - // TODO: implement for extra credentials - std::string username = sipaccount->getUsername(); - std::string password = sipaccount->getPassword(); - std::string realm = sipaccount->getRealm(); + // TODO: implement for extra credentials + std::string username = sipaccount->getUsername(); + std::string password = sipaccount->getPassword(); + std::string realm = sipaccount->getRealm(); - credentialInformation.insert(std::pair<std::string, std::string>(USERNAME, username)); - credentialInformation.insert(std::pair<std::string, std::string>(PASSWORD, password)); - credentialInformation.insert(std::pair<std::string, std::string>(REALM, realm)); - } + credentialInformation.insert (std::pair<std::string, std::string> (USERNAME, username)); + credentialInformation.insert (std::pair<std::string, std::string> (PASSWORD, password)); + credentialInformation.insert (std::pair<std::string, std::string> (REALM, realm)); + } - return credentialInformation; + return credentialInformation; } -int32_t ConfigurationManager::getNumberOfCredential( - const std::string& accountID) { +int32_t ConfigurationManager::getNumberOfCredential ( + const std::string& accountID) +{ - SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(accountID); - return sipaccount->getCredentialCount(); + SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount (accountID); + return sipaccount->getCredentialCount(); } -void ConfigurationManager::setCredential(const std::string& accountID, - const int32_t& index, const std::map<std::string, std::string>& details) { - Manager::instance().setCredential(accountID, index, details); +void ConfigurationManager::setCredential (const std::string& accountID, + const int32_t& index, const std::map<std::string, std::string>& details) +{ + Manager::instance().setCredential (accountID, index, details); } -void ConfigurationManager::deleteAllCredential(const std::string& accountID) { - Manager::instance().deleteAllCredential(accountID); +void ConfigurationManager::deleteAllCredential (const std::string& accountID) +{ + Manager::instance().deleteAllCredential (accountID); } -void ConfigurationManager::setAccountDetails(const std::string& accountID, - const std::map<std::string, std::string>& details) { - Manager::instance().setAccountDetails(accountID, details); +void ConfigurationManager::setAccountDetails (const std::string& accountID, + const std::map<std::string, std::string>& details) +{ + Manager::instance().setAccountDetails (accountID, details); } -void ConfigurationManager::sendRegister(const std::string& accountID, - const int32_t& expire) { - Manager::instance().sendRegister(accountID, expire); +void ConfigurationManager::sendRegister (const std::string& accountID, + const int32_t& expire) +{ + Manager::instance().sendRegister (accountID, expire); } -std::string ConfigurationManager::addAccount(const std::map<std::string, - std::string>& details) { - return Manager::instance().addAccount(details); +std::string ConfigurationManager::addAccount (const std::map<std::string, + std::string>& details) +{ + return Manager::instance().addAccount (details); } -void ConfigurationManager::removeAccount(const std::string& accoundID) { - return Manager::instance().removeAccount(accoundID); +void ConfigurationManager::removeAccount (const std::string& accoundID) +{ + return Manager::instance().removeAccount (accoundID); } -std::vector<std::string> ConfigurationManager::getAccountList() { - return Manager::instance().getAccountList(); +std::vector<std::string> ConfigurationManager::getAccountList() +{ + return Manager::instance().getAccountList(); } //TODO -std::vector<std::string> ConfigurationManager::getToneLocaleList() { - std::vector<std::string> ret; - return ret; +std::vector<std::string> ConfigurationManager::getToneLocaleList() +{ + std::vector<std::string> ret; + return ret; } //TODO -std::string ConfigurationManager::getVersion() { - std::string ret(""); - return ret; +std::string ConfigurationManager::getVersion() +{ + std::string ret (""); + return ret; } //TODO -std::vector<std::string> ConfigurationManager::getRingtoneList() { - std::vector<std::string> ret; - return ret; +std::vector<std::string> ConfigurationManager::getRingtoneList() +{ + std::vector<std::string> ret; + return ret; } /** * Send the list of all codecs loaded to the client through DBus. * Can stay global, as only the active codecs will be set per accounts */ -std::vector<std::string> ConfigurationManager::getCodecList(void) { +std::vector<std::string> ConfigurationManager::getCodecList (void) +{ - std::vector<std::string> list; + std::vector<std::string> list; - CodecsMap codecs = Manager::instance().getCodecDescriptorMap().getCodecsMap(); - CodecsMap::iterator iter = codecs.begin(); + CodecsMap codecs = Manager::instance().getCodecDescriptorMap().getCodecsMap(); + CodecsMap::iterator iter = codecs.begin(); - while (iter != codecs.end()) { - std::stringstream ss; + while (iter != codecs.end()) { + std::stringstream ss; - if (iter->second != NULL) { - ss << iter->first; - list.push_back((ss.str()).data()); - } + if (iter->second != NULL) { + ss << iter->first; + list.push_back ( (ss.str()).data()); + } - iter++; - } + iter++; + } - return list; + return list; } -std::vector<std::string> ConfigurationManager::getSupportedTlsMethod(void) { - std::vector<std::string> method; - method.push_back("Default"); - method.push_back("TLSv1"); - method.push_back("SSLv2"); - method.push_back("SSLv3"); - method.push_back("SSLv23"); - return method; +std::vector<std::string> ConfigurationManager::getSupportedTlsMethod (void) +{ + std::vector<std::string> method; + method.push_back ("Default"); + method.push_back ("TLSv1"); + method.push_back ("SSLv2"); + method.push_back ("SSLv3"); + method.push_back ("SSLv23"); + return method; } -std::vector<std::string> ConfigurationManager::getCodecDetails( - const int32_t& payload) { +std::vector<std::string> ConfigurationManager::getCodecDetails ( + const int32_t& payload) +{ - return Manager::instance().getCodecDescriptorMap().getCodecSpecifications( - payload); + return Manager::instance().getCodecDescriptorMap().getCodecSpecifications ( + payload); } -std::vector<std::string> ConfigurationManager::getActiveCodecList( - const std::string& accountID) { +std::vector<std::string> ConfigurationManager::getActiveCodecList ( + const std::string& accountID) +{ + + _debug ("Send active codec list for account %s", accountID.c_str ()); - _debug("Send active codec list for account %s", accountID.c_str ()); + std::vector<std::string> v; + Account *acc; + CodecOrder active; + unsigned int i = 0; + size_t size; - std::vector<std::string> v; - Account *acc; - CodecOrder active; - unsigned int i = 0; - size_t size; + acc = Manager::instance().getAccount (accountID); - acc = Manager::instance().getAccount(accountID); - if (acc != NULL) { - active = acc->getActiveCodecs(); - size = active.size(); - while (i < size) { - std::stringstream ss; - ss << active[i]; - v.push_back((ss.str()).data()); - i++; - } - } + if (acc != NULL) { + active = acc->getActiveCodecs(); + size = active.size(); - return v; + while (i < size) { + std::stringstream ss; + ss << active[i]; + v.push_back ( (ss.str()).data()); + i++; + } + } + + return v; } -void ConfigurationManager::setActiveCodecList( - const std::vector<std::string>& list, const std::string& accountID) { +void ConfigurationManager::setActiveCodecList ( + const std::vector<std::string>& list, const std::string& accountID) +{ + + _debug ("ConfigurationManager: Active codec list received"); - _debug ("ConfigurationManager: Active codec list received"); + Account *acc; - Account *acc; + // Save the codecs list per account + acc = Manager::instance().getAccount (accountID); - // Save the codecs list per account - acc = Manager::instance().getAccount(accountID); - if (acc != NULL) { - acc->setActiveCodecs(list); - } + if (acc != NULL) { + acc->setActiveCodecs (list); + } } -std::vector<std::string> ConfigurationManager::getAudioPluginList() { +std::vector<std::string> ConfigurationManager::getAudioPluginList() +{ - std::vector<std::string> v; + std::vector<std::string> v; - v.push_back(PCM_DEFAULT); - // v.push_back(PCM_DMIX); - v.push_back(PCM_DMIX_DSNOOP); + v.push_back (PCM_DEFAULT); + // v.push_back(PCM_DMIX); + v.push_back (PCM_DMIX_DSNOOP); - return v; + return v; } -void ConfigurationManager::setInputAudioPlugin(const std::string& audioPlugin) { - return Manager::instance().setInputAudioPlugin(audioPlugin); +void ConfigurationManager::setInputAudioPlugin (const std::string& audioPlugin) +{ + return Manager::instance().setInputAudioPlugin (audioPlugin); } -void ConfigurationManager::setOutputAudioPlugin(const std::string& audioPlugin) { - return Manager::instance().setOutputAudioPlugin(audioPlugin); +void ConfigurationManager::setOutputAudioPlugin (const std::string& audioPlugin) +{ + return Manager::instance().setOutputAudioPlugin (audioPlugin); } -std::vector<std::string> ConfigurationManager::getAudioOutputDeviceList() { - return Manager::instance().getAudioOutputDeviceList(); +std::vector<std::string> ConfigurationManager::getAudioOutputDeviceList() +{ + return Manager::instance().getAudioOutputDeviceList(); } -std::vector<std::string> ConfigurationManager::getAudioInputDeviceList() { - return Manager::instance().getAudioInputDeviceList(); +std::vector<std::string> ConfigurationManager::getAudioInputDeviceList() +{ + return Manager::instance().getAudioInputDeviceList(); } -void ConfigurationManager::setAudioOutputDevice(const int32_t& index) { - return Manager::instance().setAudioDevice(index, SFL_PCM_PLAYBACK); +void ConfigurationManager::setAudioOutputDevice (const int32_t& index) +{ + return Manager::instance().setAudioDevice (index, SFL_PCM_PLAYBACK); } -void ConfigurationManager::setAudioInputDevice(const int32_t& index) { - return Manager::instance().setAudioDevice(index, SFL_PCM_CAPTURE); +void ConfigurationManager::setAudioInputDevice (const int32_t& index) +{ + return Manager::instance().setAudioDevice (index, SFL_PCM_CAPTURE); } -void ConfigurationManager::setAudioRingtoneDevice(const int32_t& index) { - return Manager::instance().setAudioDevice(index, SFL_PCM_RINGTONE); +void ConfigurationManager::setAudioRingtoneDevice (const int32_t& index) +{ + return Manager::instance().setAudioDevice (index, SFL_PCM_RINGTONE); } -std::vector<std::string> ConfigurationManager::getCurrentAudioDevicesIndex() { - return Manager::instance().getCurrentAudioDevicesIndex(); +std::vector<std::string> ConfigurationManager::getCurrentAudioDevicesIndex() +{ + return Manager::instance().getCurrentAudioDevicesIndex(); } -int32_t ConfigurationManager::getAudioDeviceIndex(const std::string& name) { - return Manager::instance().getAudioDeviceIndex(name); +int32_t ConfigurationManager::getAudioDeviceIndex (const std::string& name) +{ + return Manager::instance().getAudioDeviceIndex (name); } -std::string ConfigurationManager::getCurrentAudioOutputPlugin(void) { - return Manager::instance().getCurrentAudioOutputPlugin(); +std::string ConfigurationManager::getCurrentAudioOutputPlugin (void) +{ + return Manager::instance().getCurrentAudioOutputPlugin(); } -std::string ConfigurationManager::getEchoCancelState(void) { - return Manager::instance().getEchoCancelState(); +std::string ConfigurationManager::getEchoCancelState (void) +{ + return Manager::instance().getEchoCancelState(); } -void ConfigurationManager::setEchoCancelState(const std::string& state) { - Manager::instance().setEchoCancelState(state); +void ConfigurationManager::setEchoCancelState (const std::string& state) +{ + Manager::instance().setEchoCancelState (state); } -std::string ConfigurationManager::getNoiseSuppressState(void) { - return Manager::instance().getNoiseSuppressState(); +std::string ConfigurationManager::getNoiseSuppressState (void) +{ + return Manager::instance().getNoiseSuppressState(); } -void ConfigurationManager::setNoiseSuppressState(const std::string& state) { - Manager::instance().setNoiseSuppressState(state); +void ConfigurationManager::setNoiseSuppressState (const std::string& state) +{ + Manager::instance().setNoiseSuppressState (state); } -std::vector<std::string> ConfigurationManager::getPlaybackDeviceList() { - std::vector<std::string> ret; - return ret; +std::vector<std::string> ConfigurationManager::getPlaybackDeviceList() +{ + std::vector<std::string> ret; + return ret; } -std::vector<std::string> ConfigurationManager::getRecordDeviceList() { - std::vector<std::string> ret; - return ret; +std::vector<std::string> ConfigurationManager::getRecordDeviceList() +{ + std::vector<std::string> ret; + return ret; } -bool ConfigurationManager::isMd5CredentialHashing(void) { - return Manager::instance().preferences.getMd5Hash(); +bool ConfigurationManager::isMd5CredentialHashing (void) +{ + return Manager::instance().preferences.getMd5Hash(); } -void ConfigurationManager::setMd5CredentialHashing(const bool& enabled) { - Manager::instance().preferences.setMd5Hash(enabled); +void ConfigurationManager::setMd5CredentialHashing (const bool& enabled) +{ + Manager::instance().preferences.setMd5Hash (enabled); } -int32_t ConfigurationManager::isIax2Enabled(void) { - return Manager::instance().isIax2Enabled(); +int32_t ConfigurationManager::isIax2Enabled (void) +{ + return Manager::instance().isIax2Enabled(); } -void ConfigurationManager::ringtoneEnabled(const std::string& accountID) { - Manager::instance().ringtoneEnabled(accountID); +void ConfigurationManager::ringtoneEnabled (const std::string& accountID) +{ + Manager::instance().ringtoneEnabled (accountID); } -int32_t ConfigurationManager::isRingtoneEnabled(const std::string& accountID) { - return Manager::instance().isRingtoneEnabled(accountID); +int32_t ConfigurationManager::isRingtoneEnabled (const std::string& accountID) +{ + return Manager::instance().isRingtoneEnabled (accountID); } -std::string ConfigurationManager::getRingtoneChoice(const std::string& accountID) { - return Manager::instance().getRingtoneChoice(accountID); +std::string ConfigurationManager::getRingtoneChoice (const std::string& accountID) +{ + return Manager::instance().getRingtoneChoice (accountID); } -void ConfigurationManager::setRingtoneChoice(const std::string& accountID, const std::string& tone) { - Manager::instance().setRingtoneChoice(accountID, tone); +void ConfigurationManager::setRingtoneChoice (const std::string& accountID, const std::string& tone) +{ + Manager::instance().setRingtoneChoice (accountID, tone); } -std::string ConfigurationManager::getRecordPath(void) { - return Manager::instance().getRecordPath(); +std::string ConfigurationManager::getRecordPath (void) +{ + return Manager::instance().getRecordPath(); } -void ConfigurationManager::setRecordPath(const std::string& recPath) { - Manager::instance().setRecordPath(recPath); +void ConfigurationManager::setRecordPath (const std::string& recPath) +{ + Manager::instance().setRecordPath (recPath); } /* @@ -579,12 +655,14 @@ void ConfigurationManager::setVolumeControls(const bool& display) { } */ -int32_t ConfigurationManager::getHistoryLimit(void) { - return Manager::instance().getHistoryLimit(); +int32_t ConfigurationManager::getHistoryLimit (void) +{ + return Manager::instance().getHistoryLimit(); } -void ConfigurationManager::setHistoryLimit(const int32_t& days) { - Manager::instance().setHistoryLimit(days); +void ConfigurationManager::setHistoryLimit (const int32_t& days) +{ + Manager::instance().setHistoryLimit (days); } /* @@ -621,122 +699,140 @@ int32_t ConfigurationManager::getNotify(void) { } */ -void ConfigurationManager::setAudioManager(const int32_t& api) { - Manager::instance().setAudioManager(api); +void ConfigurationManager::setAudioManager (const int32_t& api) +{ + Manager::instance().setAudioManager (api); } -int32_t ConfigurationManager::getAudioManager(void) { - return Manager::instance().getAudioManager(); +int32_t ConfigurationManager::getAudioManager (void) +{ + return Manager::instance().getAudioManager(); } -void ConfigurationManager::setMailNotify(void) { - Manager::instance().setMailNotify(); +void ConfigurationManager::setMailNotify (void) +{ + Manager::instance().setMailNotify(); } -int32_t ConfigurationManager::getMailNotify(void) { - return Manager::instance().getMailNotify(); +int32_t ConfigurationManager::getMailNotify (void) +{ + return Manager::instance().getMailNotify(); } -std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings( - void) { - return Manager::instance().getAddressbookSettings(); +std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings ( + void) +{ + return Manager::instance().getAddressbookSettings(); } -void ConfigurationManager::setAddressbookSettings(const std::map<std::string, - int32_t>& settings) { - Manager::instance().setAddressbookSettings(settings); +void ConfigurationManager::setAddressbookSettings (const std::map<std::string, + int32_t>& settings) +{ + Manager::instance().setAddressbookSettings (settings); } -std::vector<std::string> ConfigurationManager::getAddressbookList(void) { - return Manager::instance().getAddressbookList(); +std::vector<std::string> ConfigurationManager::getAddressbookList (void) +{ + return Manager::instance().getAddressbookList(); } -void ConfigurationManager::setAddressbookList( - const std::vector<std::string>& list) { - Manager::instance().setAddressbookList(list); +void ConfigurationManager::setAddressbookList ( + const std::vector<std::string>& list) +{ + Manager::instance().setAddressbookList (list); } -std::map<std::string, std::string> ConfigurationManager::getHookSettings(void) { - return Manager::instance().getHookSettings(); +std::map<std::string, std::string> ConfigurationManager::getHookSettings (void) +{ + return Manager::instance().getHookSettings(); } -void ConfigurationManager::setHookSettings(const std::map<std::string, - std::string>& settings) { - Manager::instance().setHookSettings(settings); +void ConfigurationManager::setHookSettings (const std::map<std::string, + std::string>& settings) +{ + Manager::instance().setHookSettings (settings); } -void ConfigurationManager::setAccountsOrder(const std::string& order) { - Manager::instance().setAccountsOrder(order); +void ConfigurationManager::setAccountsOrder (const std::string& order) +{ + Manager::instance().setAccountsOrder (order); } -std::map<std::string, std::string> ConfigurationManager::getHistory(void) { - return Manager::instance().send_history_to_client(); +std::map<std::string, std::string> ConfigurationManager::getHistory (void) +{ + return Manager::instance().send_history_to_client(); } -void ConfigurationManager::setHistory( - const std::map<std::string, std::string>& entries) { - Manager::instance().receive_history_from_client(entries); +void ConfigurationManager::setHistory ( + const std::map<std::string, std::string>& entries) +{ + Manager::instance().receive_history_from_client (entries); } -std::string ConfigurationManager::getAddrFromInterfaceName( - const std::string& interface) { +std::string ConfigurationManager::getAddrFromInterfaceName ( + const std::string& interface) +{ - std::string address = SIPVoIPLink::instance("")->getInterfaceAddrFromName( - interface); + std::string address = SIPVoIPLink::instance ("")->getInterfaceAddrFromName ( + interface); - return address; + return address; } -std::vector<std::string> ConfigurationManager::getAllIpInterface(void) { +std::vector<std::string> ConfigurationManager::getAllIpInterface (void) +{ - std::vector<std::string> vector; - SIPVoIPLink * sipLink = NULL; - sipLink = SIPVoIPLink::instance(""); + std::vector<std::string> vector; + SIPVoIPLink * sipLink = NULL; + sipLink = SIPVoIPLink::instance (""); - if (sipLink != NULL) { - vector = sipLink->getAllIpInterface(); - } + if (sipLink != NULL) { + vector = sipLink->getAllIpInterface(); + } - return vector; + return vector; } -std::vector<std::string> ConfigurationManager::getAllIpInterfaceByName(void) { - std::vector<std::string> vector; - SIPVoIPLink * sipLink = NULL; - sipLink = SIPVoIPLink::instance(""); +std::vector<std::string> ConfigurationManager::getAllIpInterfaceByName (void) +{ + std::vector<std::string> vector; + SIPVoIPLink * sipLink = NULL; + sipLink = SIPVoIPLink::instance (""); - if (sipLink != NULL) { - vector = sipLink->getAllIpInterfaceByName(); - } + if (sipLink != NULL) { + vector = sipLink->getAllIpInterfaceByName(); + } - return vector; + return vector; } -std::map<std::string, std::string> ConfigurationManager::getShortcuts() { +std::map<std::string, std::string> ConfigurationManager::getShortcuts() +{ - return Manager::instance().shortcutPreferences.getShortcuts(); + return Manager::instance().shortcutPreferences.getShortcuts(); } -void ConfigurationManager::setShortcuts( - const std::map<std::string, std::string>& shortcutsMap) { +void ConfigurationManager::setShortcuts ( + const std::map<std::string, std::string>& shortcutsMap) +{ + + std::map<std::string, std::string> map_cpy = shortcutsMap; + /* + std::map<std::string, std::string> map_cpy = shortcutsMap; + std::map<std::string, std::string>::iterator it; - std::map<std::string, std::string> map_cpy = shortcutsMap; - /* - std::map<std::string, std::string> map_cpy = shortcutsMap; - std::map<std::string, std::string>::iterator it; + for (int i = 0; i < (int)shortcutsKeys.size(); i++) { + std::string key = shortcutsKeys.at(i); + it = map_cpy.find(key); + if (it != shortcutsMap.end()) { - for (int i = 0; i < (int)shortcutsKeys.size(); i++) { - std::string key = shortcutsKeys.at(i); - it = map_cpy.find(key); - if (it != shortcutsMap.end()) { - - Manager::instance().setConfig("Shortcuts", key, it->second); - } - } - */ - Manager::instance().shortcutPreferences.setShortcuts(map_cpy); + Manager::instance().setConfig("Shortcuts", key, it->second); + } + } + */ + Manager::instance().shortcutPreferences.setShortcuts (map_cpy); - Manager::instance().saveConfig(); + Manager::instance().saveConfig(); } diff --git a/sflphone-common/src/dbus/dbusmanagerimpl.cpp b/sflphone-common/src/dbus/dbusmanagerimpl.cpp index 1c70b42df81d09bb5d7bfd4820d57ebfcdb22e9c..93ca99589c6083ff4e340c2bdc97c3d6fe1ba0e2 100644 --- a/sflphone-common/src/dbus/dbusmanagerimpl.cpp +++ b/sflphone-common/src/dbus/dbusmanagerimpl.cpp @@ -53,7 +53,7 @@ DBusManagerImpl::exec() _instanceManager = new Instance (sessionConnection); #ifdef USE_NETWORKMANAGER - _networkManager = new NetworkManager(systemConnection, "/org/freedesktop/NetworkManager", ""); + _networkManager = new NetworkManager (systemConnection, "/org/freedesktop/NetworkManager", ""); #endif // Register accounts diff --git a/sflphone-common/src/dbus/networkmanager.cpp b/sflphone-common/src/dbus/networkmanager.cpp index 2e106167591b267648886a046fa168819d471d4a..80fc2ad5e88bf0d4e2b7710ea9b6f94c430dcb5b 100644 --- a/sflphone-common/src/dbus/networkmanager.cpp +++ b/sflphone-common/src/dbus/networkmanager.cpp @@ -40,51 +40,51 @@ using namespace std; const string NetworkManager::statesString[5] = {"unknown", "asleep", "connecting", "connected", "disconnected"}; -string NetworkManager::stateAsString(const uint32_t& state) +string NetworkManager::stateAsString (const uint32_t& state) { - return statesString[state]; + return statesString[state]; } -void NetworkManager::StateChanged(const uint32_t& state) +void NetworkManager::StateChanged (const uint32_t& state) { - _warn("Network state changed: %s", stateAsString(state).c_str()); + _warn ("Network state changed: %s", stateAsString (state).c_str()); } -void NetworkManager::PropertiesChanged(const std::map< std::string, ::DBus::Variant >& argin0) +void NetworkManager::PropertiesChanged (const std::map< std::string, ::DBus::Variant >& argin0) { - const map< string, ::DBus::Variant >::const_iterator iter = argin0.begin(); + const map< string, ::DBus::Variant >::const_iterator iter = argin0.begin(); - string message = iter->first; + string message = iter->first; - _warn("Properties changed: %s", iter->first.c_str()); -/* - DBus::Variant variant = iter->second; - DBus::MessageIter i = variant.reader(); - cout << i.type() << endl;// 97 - cout << (char )i.type() << endl; - cout << (char)i.array_type() << endl; + _warn ("Properties changed: %s", iter->first.c_str()); + /* + DBus::Variant variant = iter->second; + DBus::MessageIter i = variant.reader(); + cout << i.type() << endl;// 97 + cout << (char )i.type() << endl; + cout << (char)i.array_type() << endl; - cout << i.is_array() << endl;// 1 - cout << i.is_dict() << endl;// 0 - cout << i.array_type() << endl;// 111 + cout << i.is_array() << endl;// 1 + cout << i.is_dict() << endl;// 0 + cout << i.array_type() << endl;// 111 - int size; - ::DBus::Path* value = new ::DBus::Path[10]; - size = i.get_array(value); - cout << "length: " << size << endl; + int size; + ::DBus::Path* value = new ::DBus::Path[10]; + size = i.get_array(value); + cout << "length: " << size << endl; - while (!i.at_end()) - { - char **array = new char*[2]; - size_t length = i.get_array(&array); - cout << "length: " << length << endl; - i = i.recurse(); - } -*/ - Manager::instance().registerAccounts(); + while (!i.at_end()) + { + char **array = new char*[2]; + size_t length = i.get_array(&array); + cout << "length: " << length << endl; + i = i.recurse(); + } + */ + Manager::instance().registerAccounts(); } -NetworkManager::NetworkManager(DBus::Connection& connection, const DBus::Path& path, const char* destination): DBus::ObjectProxy (connection, path, destination) +NetworkManager::NetworkManager (DBus::Connection& connection, const DBus::Path& path, const char* destination) : DBus::ObjectProxy (connection, path, destination) { } diff --git a/sflphone-common/src/history/historymanager.cpp b/sflphone-common/src/history/historymanager.cpp index 54fa6d1eb614b40a17f35f645f5b5e02b53f6ac4..909f20fd06945ed9a1f0a6022280df1569667493 100644 --- a/sflphone-common/src/history/historymanager.cpp +++ b/sflphone-common/src/history/historymanager.cpp @@ -43,14 +43,15 @@ HistoryManager::HistoryManager () HistoryManager::~HistoryManager () { - HistoryItemMap::iterator iter = _history_items.begin(); - - HistoryItem * item; - while(iter != _history_items.end()){ - item = iter->second; - delete item; - iter++; - } + HistoryItemMap::iterator iter = _history_items.begin(); + + HistoryItem * item; + + while (iter != _history_items.end()) { + item = iter->second; + delete item; + iter++; + } // Clear the history map _history_items.clear (); diff --git a/sflphone-common/src/hooks/urlhook.cpp b/sflphone-common/src/hooks/urlhook.cpp index f74aa00ef0794c41f15e84bb96d2040b5e476f40..d9191309de71760d77a26df608a93fd8449f3e0b 100644 --- a/sflphone-common/src/hooks/urlhook.cpp +++ b/sflphone-common/src/hooks/urlhook.cpp @@ -40,32 +40,33 @@ int UrlHook::addAction (std::string field_value, std::string command) { std::string command_bg; - std::string temp; - std::vector <std::string> args; - size_t pos; - unsigned int i; + std::string temp; + std::vector <std::string> args; + size_t pos; + unsigned int i; - /* Escape the '&' char to not discard $_GET parameters in the URL - #2659 */ - while ( (pos = field_value.find ("&", 0)) != std::string::npos) { + /* Escape the '&' char to not discard $_GET parameters in the URL - #2659 */ + while ( (pos = field_value.find ("&", 0)) != std::string::npos) { temp = field_value.substr (0, pos); field_value.erase (0, pos + 1); - args.push_back (temp); - std::cout << temp << " " << std::endl; - } + args.push_back (temp); + std::cout << temp << " " << std::endl; + } command_bg = command + " "; - pos = args.size (); - for (i=0; i<pos; i++) { - // Escape the "&" - command_bg += args[i] + "\\&"; - } + pos = args.size (); - // Retrieve the last argument - command_bg += field_value; + for (i=0; i<pos; i++) { + // Escape the "&" + command_bg += args[i] + "\\&"; + } + + // Retrieve the last argument + command_bg += field_value; /* Execute the command in the background to not block the application */ - command_bg += "&"; + command_bg += "&"; /* Execute a system call */ return RUN_COMMAND (command_bg.c_str()); diff --git a/sflphone-common/src/iax/iaxaccount.cpp b/sflphone-common/src/iax/iaxaccount.cpp index b0af8857985bf151b953dbaa3b45900b2b2bf06f..ee4428aaba68048e3c13a84ae27482974c069f3c 100644 --- a/sflphone-common/src/iax/iaxaccount.cpp +++ b/sflphone-common/src/iax/iaxaccount.cpp @@ -47,148 +47,192 @@ IAXAccount::~IAXAccount() _link = NULL; } -void IAXAccount::serialize(Conf::YamlEmitter *emitter) +void IAXAccount::serialize (Conf::YamlEmitter *emitter) { - _debug("IaxAccount: serialize %s", _accountID.c_str()); - - Conf::MappingNode accountmap(NULL); - - Conf::ScalarNode id(Account::_accountID); - Conf::ScalarNode username(Account::_username); - Conf::ScalarNode password(Account::_password); - Conf::ScalarNode alias(Account::_alias); - Conf::ScalarNode hostname(Account::_hostname); - Conf::ScalarNode enable(_enabled ? "true" : "false"); - Conf::ScalarNode type(Account::_type); - Conf::ScalarNode mailbox("97"); - - Conf::ScalarNode codecs(_codecStr); - Conf::ScalarNode displayName(_displayName); - - accountmap.setKeyValue(aliasKey, &alias); - accountmap.setKeyValue(typeKey, &type); - accountmap.setKeyValue(idKey, &id); - accountmap.setKeyValue(usernameKey, &username); - accountmap.setKeyValue(passwordKey, &password); - accountmap.setKeyValue(hostnameKey, &hostname); - accountmap.setKeyValue(accountEnableKey, &enable); - accountmap.setKeyValue(mailboxKey, &mailbox); - - accountmap.setKeyValue(displayNameKey, &displayName); - accountmap.setKeyValue(codecsKey, &codecs); - - try{ - emitter->serializeAccount(&accountmap); - } - catch (Conf::YamlEmitterException &e) { - _error("ConfigTree: %s", e.what()); - } + _debug ("IaxAccount: serialize %s", _accountID.c_str()); + + Conf::MappingNode accountmap (NULL); + + Conf::ScalarNode id (Account::_accountID); + Conf::ScalarNode username (Account::_username); + Conf::ScalarNode password (Account::_password); + Conf::ScalarNode alias (Account::_alias); + Conf::ScalarNode hostname (Account::_hostname); + Conf::ScalarNode enable (_enabled ? "true" : "false"); + Conf::ScalarNode type (Account::_type); + Conf::ScalarNode mailbox ("97"); + + Conf::ScalarNode codecs (_codecStr); + Conf::ScalarNode displayName (_displayName); + + accountmap.setKeyValue (aliasKey, &alias); + accountmap.setKeyValue (typeKey, &type); + accountmap.setKeyValue (idKey, &id); + accountmap.setKeyValue (usernameKey, &username); + accountmap.setKeyValue (passwordKey, &password); + accountmap.setKeyValue (hostnameKey, &hostname); + accountmap.setKeyValue (accountEnableKey, &enable); + accountmap.setKeyValue (mailboxKey, &mailbox); + + accountmap.setKeyValue (displayNameKey, &displayName); + accountmap.setKeyValue (codecsKey, &codecs); + + try { + emitter->serializeAccount (&accountmap); + } catch (Conf::YamlEmitterException &e) { + _error ("ConfigTree: %s", e.what()); + } } -void IAXAccount::unserialize(Conf::MappingNode *map) +void IAXAccount::unserialize (Conf::MappingNode *map) { - Conf::ScalarNode *val; - - _debug("IaxAccount: Unserialize"); - - val = (Conf::ScalarNode *)(map->getValue(aliasKey)); - if(val) { _alias = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(typeKey)); - if(val) { _type = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(idKey)); - if(val) { _accountID = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(usernameKey)); - if(val) { _username = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(passwordKey)); - if(val) { _password = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(hostnameKey)); - if(val) { _hostname = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(accountEnableKey)); - if(val) { _enabled = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); - - val = (Conf::ScalarNode *)(map->getValue(codecsKey)); - if(val) { _codecStr = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(displayNameKey)); - if(val) { _displayName = val->getValue(); val = NULL; } + Conf::ScalarNode *val; + + _debug ("IaxAccount: Unserialize"); + + val = (Conf::ScalarNode *) (map->getValue (aliasKey)); + + if (val) { + _alias = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (typeKey)); + + if (val) { + _type = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (idKey)); + + if (val) { + _accountID = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (usernameKey)); + + if (val) { + _username = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (passwordKey)); + + if (val) { + _password = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (hostnameKey)); + + if (val) { + _hostname = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (accountEnableKey)); + + if (val) { + _enabled = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); + + val = (Conf::ScalarNode *) (map->getValue (codecsKey)); + + if (val) { + _codecStr = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (displayNameKey)); + + if (val) { + _displayName = val->getValue(); + val = NULL; + } } -void IAXAccount::setAccountDetails(const std::map<std::string, std::string>& details) +void IAXAccount::setAccountDetails (const std::map<std::string, std::string>& details) { - std::map<std::string, std::string> map_cpy; - std::map<std::string, std::string>::iterator iter; - - _debug("IaxAccount: Set account details: %s", _accountID.c_str()); - - // Work on a copy - map_cpy = details; - - std::string alias; - std::string type; - std::string hostname; - std::string username; - std::string password; - std::string mailbox; - std::string accountEnable; - - std::string ua_name; - - // Account setting common to SIP and IAX - find_in_map(CONFIG_ACCOUNT_ALIAS, alias) - find_in_map(CONFIG_ACCOUNT_TYPE, type) - find_in_map(HOSTNAME, hostname) - find_in_map(USERNAME, username) - find_in_map(PASSWORD, password) - find_in_map(CONFIG_ACCOUNT_MAILBOX, mailbox); - find_in_map(CONFIG_ACCOUNT_ENABLE, accountEnable); - - setAlias(alias); - setType(type); - setUsername(username); - setHostname(hostname); - setPassword(password); - setEnabled((accountEnable.compare("true") == 0) ? true : false); - - std::string displayName; - find_in_map(DISPLAY_NAME, displayName) - setDisplayName(displayName); - - find_in_map(USERAGENT, ua_name) - setUseragent(ua_name); + std::map<std::string, std::string> map_cpy; + std::map<std::string, std::string>::iterator iter; + + _debug ("IaxAccount: Set account details: %s", _accountID.c_str()); + + // Work on a copy + map_cpy = details; + + std::string alias; + std::string type; + std::string hostname; + std::string username; + std::string password; + std::string mailbox; + std::string accountEnable; + + std::string ua_name; + + // Account setting common to SIP and IAX + find_in_map (CONFIG_ACCOUNT_ALIAS, alias) + find_in_map (CONFIG_ACCOUNT_TYPE, type) + find_in_map (HOSTNAME, hostname) + find_in_map (USERNAME, username) + find_in_map (PASSWORD, password) + find_in_map (CONFIG_ACCOUNT_MAILBOX, mailbox); + find_in_map (CONFIG_ACCOUNT_ENABLE, accountEnable); + + setAlias (alias); + setType (type); + setUsername (username); + setHostname (hostname); + setPassword (password); + setEnabled ( (accountEnable.compare ("true") == 0) ? true : false); + + std::string displayName; + find_in_map (DISPLAY_NAME, displayName) + setDisplayName (displayName); + + find_in_map (USERAGENT, ua_name) + setUseragent (ua_name); } std::map<std::string, std::string> IAXAccount::getAccountDetails() { - std::map<std::string, std::string> a; - - _debug("IaxAccount: get account details %s", _accountID.c_str()); - - a.insert(std::pair<std::string, std::string>(ACCOUNT_ID, _accountID)); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ALIAS, getAlias())); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ENABLE, isEnabled() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_TYPE, getType())); - a.insert(std::pair<std::string, std::string>(HOSTNAME, getHostname())); - a.insert(std::pair<std::string, std::string>(USERNAME, getUsername())); - a.insert(std::pair<std::string, std::string>(PASSWORD, getPassword())); - - RegistrationState state = Unregistered; - std::string registrationStateCode; - std::string registrationStateDescription; - - state = getRegistrationState(); - int code = getRegistrationStateDetailed().first; - std::stringstream out; out << code; - registrationStateCode = out.str(); - registrationStateDescription = getRegistrationStateDetailed().second; - - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATUS, Manager::instance().mapStateNumberToString(state))); - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATE_CODE, registrationStateCode)); - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); - a.insert(std::pair<std::string, std::string>(USERAGENT, getUseragent())); - - return a; + std::map<std::string, std::string> a; + + _debug ("IaxAccount: get account details %s", _accountID.c_str()); + + a.insert (std::pair<std::string, std::string> (ACCOUNT_ID, _accountID)); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, getAlias())); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ENABLE, isEnabled() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_TYPE, getType())); + a.insert (std::pair<std::string, std::string> (HOSTNAME, getHostname())); + a.insert (std::pair<std::string, std::string> (USERNAME, getUsername())); + a.insert (std::pair<std::string, std::string> (PASSWORD, getPassword())); + + RegistrationState state = Unregistered; + std::string registrationStateCode; + std::string registrationStateDescription; + + state = getRegistrationState(); + int code = getRegistrationStateDetailed().first; + std::stringstream out; + out << code; + registrationStateCode = out.str(); + registrationStateDescription = getRegistrationStateDetailed().second; + + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATUS, Manager::instance().mapStateNumberToString (state))); + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_CODE, registrationStateCode)); + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); + a.insert (std::pair<std::string, std::string> (USERAGENT, getUseragent())); + + return a; } diff --git a/sflphone-common/src/iax/iaxcall.cpp b/sflphone-common/src/iax/iaxcall.cpp index 7964df857fdf82434c65277334068f0b97d34bf1..52bc6c7c5bfb50285a8240acf061fffe0f12ccbe 100644 --- a/sflphone-common/src/iax/iaxcall.cpp +++ b/sflphone-common/src/iax/iaxcall.cpp @@ -39,172 +39,173 @@ IAXCall::IAXCall (const CallID& id, Call::CallType type) : Call (id, type), _ses IAXCall::~IAXCall() { - _session = NULL; // just to be sure to don't have unknown pointer, do not delete it! + _session = NULL; // just to be sure to don't have unknown pointer, do not delete it! } - void +void IAXCall::setFormat (int format) { - _format = format; - - _info ("IAX set supported format: "); - - switch (format) { - - case AST_FORMAT_ULAW: - _info("PCMU"); - setAudioCodec (PAYLOAD_CODEC_ULAW); - break; - - case AST_FORMAT_GSM: - _info ("GSM"); - setAudioCodec (PAYLOAD_CODEC_GSM); - break; - - case AST_FORMAT_ALAW: - _info ("ALAW"); - setAudioCodec (PAYLOAD_CODEC_ALAW); - break; - - case AST_FORMAT_ILBC: - _info ("ILBC"); - setAudioCodec (PAYLOAD_CODEC_ILBC_20); - break; - - case AST_FORMAT_SPEEX: - _info ("SPEEX"); - setAudioCodec (PAYLOAD_CODEC_SPEEX_8000); - break; - - default: - _info ("Error audio codec type %i not supported!", format); - setAudioCodec ( (AudioCodecType) -1); - break; - } + _format = format; + + _info ("IAX set supported format: "); + + switch (format) { + + case AST_FORMAT_ULAW: + _info ("PCMU"); + setAudioCodec (PAYLOAD_CODEC_ULAW); + break; + + case AST_FORMAT_GSM: + _info ("GSM"); + setAudioCodec (PAYLOAD_CODEC_GSM); + break; + + case AST_FORMAT_ALAW: + _info ("ALAW"); + setAudioCodec (PAYLOAD_CODEC_ALAW); + break; + + case AST_FORMAT_ILBC: + _info ("ILBC"); + setAudioCodec (PAYLOAD_CODEC_ILBC_20); + break; + + case AST_FORMAT_SPEEX: + _info ("SPEEX"); + setAudioCodec (PAYLOAD_CODEC_SPEEX_8000); + break; + + default: + _info ("Error audio codec type %i not supported!", format); + setAudioCodec ( (AudioCodecType) -1); + break; + } } - int +int IAXCall::getSupportedFormat (std::string accountID) { - CodecOrder map; - int format = 0; - unsigned int iter; - Account *account; - - _info ("IAX get supported format: "); - - account = Manager::instance().getAccount (accountID); - if (account != NULL) { - map = account->getActiveCodecs(); - } - else { - _error ("No IAx account could be found"); - } - - for (iter=0 ; iter < map.size() ; iter++) { - switch (map[iter]) { - - case PAYLOAD_CODEC_ULAW: - _info ("PCMU "); - format |= AST_FORMAT_ULAW; - break; - - case PAYLOAD_CODEC_GSM: - _info ("GSM "); - format |= AST_FORMAT_GSM; - break; - - case PAYLOAD_CODEC_ALAW: - _info ("PCMA "); - format |= AST_FORMAT_ALAW; - break; - - case PAYLOAD_CODEC_ILBC_20: - _info ("ILBC "); - format |= AST_FORMAT_ILBC; - break; - - case PAYLOAD_CODEC_SPEEX_8000: - _info ("SPEEX "); - format |= AST_FORMAT_SPEEX; - break; - - default: - break; - } - } - - return format; + CodecOrder map; + int format = 0; + unsigned int iter; + Account *account; + + _info ("IAX get supported format: "); + + account = Manager::instance().getAccount (accountID); + + if (account != NULL) { + map = account->getActiveCodecs(); + } else { + _error ("No IAx account could be found"); + } + + for (iter=0 ; iter < map.size() ; iter++) { + switch (map[iter]) { + + case PAYLOAD_CODEC_ULAW: + _info ("PCMU "); + format |= AST_FORMAT_ULAW; + break; + + case PAYLOAD_CODEC_GSM: + _info ("GSM "); + format |= AST_FORMAT_GSM; + break; + + case PAYLOAD_CODEC_ALAW: + _info ("PCMA "); + format |= AST_FORMAT_ALAW; + break; + + case PAYLOAD_CODEC_ILBC_20: + _info ("ILBC "); + format |= AST_FORMAT_ILBC; + break; + + case PAYLOAD_CODEC_SPEEX_8000: + _info ("SPEEX "); + format |= AST_FORMAT_SPEEX; + break; + + default: + break; + } + } + + return format; } -int IAXCall::getFirstMatchingFormat (int needles, std::string accountID) { +int IAXCall::getFirstMatchingFormat (int needles, std::string accountID) +{ + + Account *account; + CodecOrder map; + int format = 0; + unsigned int iter; - Account *account; - CodecOrder map; - int format = 0; - unsigned int iter; + _debug ("IAX get first matching codec: "); - _debug ("IAX get first matching codec: "); + account = Manager::instance().getAccount (accountID); - account = Manager::instance().getAccount (accountID); - if (account != NULL) { - map = account->getActiveCodecs(); - } - else { - _error ("No IAx account could be found"); - } + if (account != NULL) { + map = account->getActiveCodecs(); + } else { + _error ("No IAx account could be found"); + } - for (iter=0 ; iter < map.size() ; iter++) { - switch (map[iter]) { + for (iter=0 ; iter < map.size() ; iter++) { + switch (map[iter]) { - case PAYLOAD_CODEC_ULAW: - _debug ("PCMU"); - format = AST_FORMAT_ULAW; - break; + case PAYLOAD_CODEC_ULAW: + _debug ("PCMU"); + format = AST_FORMAT_ULAW; + break; - case PAYLOAD_CODEC_GSM: - _debug ("GSM"); - format = AST_FORMAT_GSM; - break; + case PAYLOAD_CODEC_GSM: + _debug ("GSM"); + format = AST_FORMAT_GSM; + break; - case PAYLOAD_CODEC_ALAW: - _debug ("PCMA"); - format = AST_FORMAT_ALAW; - break; + case PAYLOAD_CODEC_ALAW: + _debug ("PCMA"); + format = AST_FORMAT_ALAW; + break; - case PAYLOAD_CODEC_ILBC_20: - _debug ("ILBC"); - format = AST_FORMAT_ILBC; - break; + case PAYLOAD_CODEC_ILBC_20: + _debug ("ILBC"); + format = AST_FORMAT_ILBC; + break; - case PAYLOAD_CODEC_SPEEX_8000: - _debug ("SPEEX"); - format = AST_FORMAT_SPEEX; - break; + case PAYLOAD_CODEC_SPEEX_8000: + _debug ("SPEEX"); + format = AST_FORMAT_SPEEX; + break; - default: - break; - } + default: + break; + } - // Return the first that matches - if (format & needles) - return format; + // Return the first that matches + if (format & needles) + return format; - } + } - return 0; + return 0; } CodecDescriptor& IAXCall::getCodecMap() { - return _codecMap; + return _codecMap; } AudioCodecType IAXCall::getAudioCodec() { - return _audioCodec; + return _audioCodec; } diff --git a/sflphone-common/src/iax/iaxvoiplink.cpp b/sflphone-common/src/iax/iaxvoiplink.cpp index 6e2f09eaea1283f3112e50b31f7d5614d876a3a7..a9d4f117ea361c1fdba5731c715dcc57b9b2c77e 100644 --- a/sflphone-common/src/iax/iaxvoiplink.cpp +++ b/sflphone-common/src/iax/iaxvoiplink.cpp @@ -413,18 +413,18 @@ IAXVoIPLink::sendRegister (AccountID id UNUSED) IAXAccount *account; bool result; - _debug("IAX: Sending registration"); + _debug ("IAX: Sending registration"); result = false; account = dynamic_cast<IAXAccount *> (getAccountPtr()); if (account->getHostname().empty()) { - _error("IAX: Error: Account hostname is empty"); + _error ("IAX: Error: Account hostname is empty"); return false; } if (account->getUsername().empty()) { - _error("IAX: Error: Account username is empty"); + _error ("IAX: Error: Account username is empty"); return false; } diff --git a/sflphone-common/src/logger.cpp b/sflphone-common/src/logger.cpp index 9269553817df1e55b73465fba9445a6cb1b64fd3..efcfc8b5c762826685168541812295779e6cc6cb 100644 --- a/sflphone-common/src/logger.cpp +++ b/sflphone-common/src/logger.cpp @@ -41,69 +41,63 @@ namespace Logger bool consoleLog = false; bool debugMode = false; -void log(const int level, const char* format, ...) +void log (const int level, const char* format, ...) { - if(!debugMode && level == LOG_DEBUG) - return; + if (!debugMode && level == LOG_DEBUG) + return; - va_list ap; - string prefix = "<> "; - char buffer[4096]; - string message = ""; - string color_prefix = ""; + va_list ap; + string prefix = "<> "; + char buffer[4096]; + string message = ""; + string color_prefix = ""; - switch(level) - { - case LOG_ERR: - { - prefix = "<error> "; - color_prefix = RED; - break; - } - case LOG_WARNING: - { - prefix = "<warning> "; - color_prefix = LIGHT_RED; - break; - } - case LOG_INFO: - { - prefix = "<info> "; - color_prefix = ""; - break; - } - case LOG_DEBUG: - { - prefix = "<debug> "; - color_prefix = ""; - break; - } - } - - va_start(ap, format); - vsprintf(buffer, format, ap); - va_end(ap); + switch (level) { + case LOG_ERR: { + prefix = "<error> "; + color_prefix = RED; + break; + } + case LOG_WARNING: { + prefix = "<warning> "; + color_prefix = LIGHT_RED; + break; + } + case LOG_INFO: { + prefix = "<info> "; + color_prefix = ""; + break; + } + case LOG_DEBUG: { + prefix = "<debug> "; + color_prefix = ""; + break; + } + } - message = buffer; - message = prefix + message; + va_start (ap, format); + vsprintf (buffer, format, ap); + va_end (ap); - syslog(level, message.c_str()); + message = buffer; + message = prefix + message; - if(consoleLog) - { - message = color_prefix + message + END_COLOR + "\n"; - fprintf(stderr, message.c_str()); - } + syslog (level, message.c_str()); + + if (consoleLog) { + message = color_prefix + message + END_COLOR + "\n"; + fprintf (stderr, message.c_str()); + } } -void setConsoleLog(bool c) +void setConsoleLog (bool c) { - Logger::consoleLog = c; + Logger::consoleLog = c; } -void setDebugMode(bool d) +void setDebugMode (bool d) { - Logger::debugMode = d; + Logger::debugMode = d; } } diff --git a/sflphone-common/src/main.cpp b/sflphone-common/src/main.cpp index aca2e1f1547ccfcf0770eddbd476ccf90b87253b..4e4c581c39317de2b7f579b92219a23a83955e67 100644 --- a/sflphone-common/src/main.cpp +++ b/sflphone-common/src/main.cpp @@ -48,170 +48,168 @@ using namespace std; using namespace ost; -CommandOptionArg level( - "log-level", "l", "Log level (not yet implemented)" +CommandOptionArg level ( + "log-level", "l", "Log level (not yet implemented)" ); -CommandOptionNoArg console( - "console", "c", "Log in console (instead of syslog)" +CommandOptionNoArg console ( + "console", "c", "Log in console (instead of syslog)" ); -CommandOptionNoArg debug( - "debug", "d", "Debug mode (more verbose)" +CommandOptionNoArg debug ( + "debug", "d", "Debug mode (more verbose)" ); -CommandOptionNoArg help( - "help", "h", "Print help" +CommandOptionNoArg help ( + "help", "h", "Print help" ); int main (int argc, char **argv) { - int exit_code = 0; + int exit_code = 0; - Logger::setConsoleLog(false); - Logger::setDebugMode(false); + Logger::setConsoleLog (false); + Logger::setDebugMode (false); - CommandOptionParse * args = makeCommandOptionParse(argc, argv, ""); + CommandOptionParse * args = makeCommandOptionParse (argc, argv, ""); - printf ("SFLphone Daemon %s, by Savoir-Faire Linux 2004-2009\n", VERSION); - printf ("http://www.sflphone.org/\n"); + printf ("SFLphone Daemon %s, by Savoir-Faire Linux 2004-2009\n", VERSION); + printf ("http://www.sflphone.org/\n"); - if ( help.numSet ) { - cerr << args->printUsage(); - ::exit(0); - } + if (help.numSet) { + cerr << args->printUsage(); + ::exit (0); + } - if ( args->argsHaveError() ) { - cerr << args->printErrors(); - cerr << args->printUsage(); - ::exit(1); - } + if (args->argsHaveError()) { + cerr << args->printErrors(); + cerr << args->printUsage(); + ::exit (1); + } - if( console.numSet ) - { - _info("Console logging activated"); - Logger::setConsoleLog(true); - } + if (console.numSet) { + _info ("Console logging activated"); + Logger::setConsoleLog (true); + } - if( debug.numSet ) - { - _info("Debug mode activated"); - Logger::setDebugMode(true); - } + if (debug.numSet) { + _info ("Debug mode activated"); + Logger::setDebugMode (true); + } - delete args; + delete args; - FILE *fp; - char homepid[128]; - char sfldir[128]; + FILE *fp; + char homepid[128]; + char sfldir[128]; - unsigned int iPid = getpid(); - char cPid[64], cOldPid[64]; - sprintf (cPid,"%d", iPid); - std::string xdg_cache, xdg_env, path; + unsigned int iPid = getpid(); + char cPid[64], cOldPid[64]; + sprintf (cPid,"%d", iPid); + std::string xdg_cache, xdg_env, path; - xdg_cache = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".cache/"; + xdg_cache = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".cache/"; - if (XDG_CACHE_HOME != NULL) { - xdg_env = std::string (XDG_CACHE_HOME); - (xdg_env.length() > 0) ? path = xdg_env - : path = xdg_cache; - } else - path = xdg_cache; + if (XDG_CACHE_HOME != NULL) { + xdg_env = std::string (XDG_CACHE_HOME); + (xdg_env.length() > 0) ? path = xdg_env + : path = xdg_cache; + } else + path = xdg_cache; - sprintf (sfldir, "%s", path.c_str ()); + sprintf (sfldir, "%s", path.c_str ()); - path = path + "sflphone"; + path = path + "sflphone"; - sprintf (homepid, "%s/%s", path.c_str (), PIDFILE); + sprintf (homepid, "%s/%s", path.c_str (), PIDFILE); - if ( (fp = fopen (homepid,"r")) == NULL) { - // Check if $XDG_CACHE_HOME directory exists or not. - DIR *dir; + if ( (fp = fopen (homepid,"r")) == NULL) { + // Check if $XDG_CACHE_HOME directory exists or not. + DIR *dir; - if ( (dir = opendir (sfldir)) == NULL) { - //Create it - if (mkdir (sfldir, 0755) != 0) { - fprintf (stderr, "Creating directory %s failed. Exited.", sfldir); - exit (-1); - } + if ( (dir = opendir (sfldir)) == NULL) { + //Create it + if (mkdir (sfldir, 0755) != 0) { + fprintf (stderr, "Creating directory %s failed. Exited.", sfldir); + exit (-1); } + } - // Then create the sflphone directory inside the $XDG_CACHE_HOME dir - sprintf (sfldir, "%s", path.c_str ()); - - if ( (dir = opendir (sfldir)) == NULL) { - //Create it - if (mkdir (sfldir, 0755) != 0) { - fprintf (stderr, "Creating directory %s failed. Exited.", sfldir); - exit (-1); - } - } + // Then create the sflphone directory inside the $XDG_CACHE_HOME dir + sprintf (sfldir, "%s", path.c_str ()); - // PID file doesn't exists, create and write pid in it - if ( (fp = fopen (homepid,"w")) == NULL) { - fprintf (stderr, "Creating PID file %s failed. Exited.", homepid); + if ( (dir = opendir (sfldir)) == NULL) { + //Create it + if (mkdir (sfldir, 0755) != 0) { + fprintf (stderr, "Creating directory %s failed. Exited.", sfldir); exit (-1); - } else { - fputs (cPid , fp); - fclose (fp); } + } + + // PID file doesn't exists, create and write pid in it + if ( (fp = fopen (homepid,"w")) == NULL) { + fprintf (stderr, "Creating PID file %s failed. Exited.", homepid); + exit (-1); } else { - // PID file exists. Check the former process still alive or not. If alive, give user a hint. - char *res; - res = fgets (cOldPid, 64, fp); + fputs (cPid , fp); + fclose (fp); + } + } else { + // PID file exists. Check the former process still alive or not. If alive, give user a hint. + char *res; + res = fgets (cOldPid, 64, fp); - if (res == NULL) perror ("Error getting string from stream"); + if (res == NULL) perror ("Error getting string from stream"); - else { - fclose (fp); + else { + fclose (fp); - if (kill (atoi (cOldPid), 0) == SUCCESS) { - fprintf (stderr, "There is already a sflphoned daemon running in the system. Starting Failed."); + if (kill (atoi (cOldPid), 0) == SUCCESS) { + fprintf (stderr, "There is already a sflphoned daemon running in the system. Starting Failed."); + exit (-1); + } else { + if ( (fp = fopen (homepid,"w")) == NULL) { + fprintf (stderr, "Writing to PID file %s failed. Exited.", homepid); exit (-1); } else { - if ( (fp = fopen (homepid,"w")) == NULL) { - fprintf (stderr, "Writing to PID file %s failed. Exited.", homepid); - exit (-1); - } else { - fputs (cPid , fp); - fclose (fp); - } - + fputs (cPid , fp); + fclose (fp); } - } - } - - int sessionPort = 0; - if (argc == 2) { - char* ptrPort = strstr (argv[1], "--port="); - - if (ptrPort != 0) { - sessionPort = atoi (ptrPort+7); } } + } - bool initOK = false; - - try { - // TODO Use $XDG_CONFIG_HOME to save the config file (which default to $HOME/.config) - Manager::instance().initConfigFile(); - Manager::instance().init(); - initOK = true; - } catch (std::exception &e) { - std::cerr << e.what() << std::endl; - exit_code = -1; - } catch (...) { - fprintf (stderr, "An exception occured when initializing the system."); - exit_code = -1; - } + int sessionPort = 0; + + if (argc == 2) { + char* ptrPort = strstr (argv[1], "--port="); - if (initOK) { - Manager::instance().setDBusManager (&DBusManager::instance()); - exit_code = DBusManager::instance().exec(); // UI Loop + if (ptrPort != 0) { + sessionPort = atoi (ptrPort+7); } + } + + bool initOK = false; + + try { + // TODO Use $XDG_CONFIG_HOME to save the config file (which default to $HOME/.config) + Manager::instance().initConfigFile(); + Manager::instance().init(); + initOK = true; + } catch (std::exception &e) { + std::cerr << e.what() << std::endl; + exit_code = -1; + } catch (...) { + fprintf (stderr, "An exception occured when initializing the system."); + exit_code = -1; + } + + if (initOK) { + Manager::instance().setDBusManager (&DBusManager::instance()); + exit_code = DBusManager::instance().exec(); // UI Loop + } return exit_code; } diff --git a/sflphone-common/src/managerimpl.cpp b/sflphone-common/src/managerimpl.cpp old mode 100755 new mode 100644 index f946e4ed561d7c0123362e1b23ac00a38e6f5509..99e4c75c1d1f9b3df424d323f59a3302a3922f64 --- a/sflphone-common/src/managerimpl.cpp +++ b/sflphone-common/src/managerimpl.cpp @@ -73,131 +73,144 @@ #define MD5_APPEND(pms,buf,len) pj_md5_update(pms, (const pj_uint8_t*)buf, len) // Default account used to get default parametersa if requested by client (to build ne account) -SIPAccount defaultAccount("default"); +SIPAccount defaultAccount ("default"); ManagerImpl::ManagerImpl (void) : - _hasTriedToRegister(false), _config(), _currentCallId2(), - _currentCallMutex(), _codecBuilder(NULL), _audiodriver(NULL), - _dtmfKey(NULL), _codecDescriptorMap(), _toneMutex(), - _telephoneTone(NULL), _audiofile(), _spkr_volume(0), - _mic_volume(0), _mutex(), _dbus(NULL), _waitingCall(), - _waitingCallMutex(), _nbIncomingWaitingCall(0), _path(""), - _exist(0), _setupLoaded(false), _callAccountMap(), - _callAccountMapMutex(), _callConfigMap(), _accountMap(), - _directIpAccount(NULL), _cleaner(NULL), _history(NULL) { - - // initialize random generator for call id - srand(time(NULL)); - - _cleaner = new NumberCleaner(); - _history = new HistoryManager(); + _hasTriedToRegister (false), _config(), _currentCallId2(), + _currentCallMutex(), _codecBuilder (NULL), _audiodriver (NULL), + _dtmfKey (NULL), _codecDescriptorMap(), _toneMutex(), + _telephoneTone (NULL), _audiofile(), _spkr_volume (0), + _mic_volume (0), _mutex(), _dbus (NULL), _waitingCall(), + _waitingCallMutex(), _nbIncomingWaitingCall (0), _path (""), + _exist (0), _setupLoaded (false), _callAccountMap(), + _callAccountMapMutex(), _callConfigMap(), _accountMap(), + _directIpAccount (NULL), _cleaner (NULL), _history (NULL) +{ + + // initialize random generator for call id + srand (time (NULL)); + + _cleaner = new NumberCleaner(); + _history = new HistoryManager(); #ifdef TEST - testAccountMap(); - loadAccountMap(); - testCallAccountMap(); - unloadAccountMap(); + testAccountMap(); + loadAccountMap(); + testCallAccountMap(); + unloadAccountMap(); #endif - // should be call before initConfigFile - // loadAccountMap();, called in init() now. + // should be call before initConfigFile + // loadAccountMap();, called in init() now. } // never call if we use only the singleton... -ManagerImpl::~ManagerImpl (void) { - // terminate(); - delete _cleaner; _cleaner = NULL; - delete _history; _history = NULL; +ManagerImpl::~ManagerImpl (void) +{ + // terminate(); + delete _cleaner; + _cleaner = NULL; + delete _history; + _history = NULL; - _debug ("Manager: %s stop correctly.", PROGNAME); + _debug ("Manager: %s stop correctly.", PROGNAME); } -void ManagerImpl::init () { +void ManagerImpl::init () +{ - _debug("Manager: Init"); + _debug ("Manager: Init"); - // Load accounts, init map - buildConfiguration(); + // Load accounts, init map + buildConfiguration(); - _debug("Manager: account map loaded"); + _debug ("Manager: account map loaded"); - initVolume(); + initVolume(); - if (_exist == 0) { - _warn ("Manager: Cannot create config file in your home directory"); - } + if (_exist == 0) { + _warn ("Manager: Cannot create config file in your home directory"); + } - initAudioDriver(); + initAudioDriver(); - selectAudioDriver(); + selectAudioDriver(); - // Initialize the list of supported audio codecs - initAudioCodec(); + // Initialize the list of supported audio codecs + initAudioCodec(); - AudioLayer *audiolayer = getAudioDriver(); + AudioLayer *audiolayer = getAudioDriver(); - if (audiolayer) { - unsigned int sampleRate = audiolayer->getSampleRate(); + if (audiolayer) { + unsigned int sampleRate = audiolayer->getSampleRate(); - _debugInit ("Manager: Load telephone tone"); - std::string country = preferences.getZoneToneChoice(); - _telephoneTone = new TelephoneTone(country, sampleRate); + _debugInit ("Manager: Load telephone tone"); + std::string country = preferences.getZoneToneChoice(); + _telephoneTone = new TelephoneTone (country, sampleRate); - _debugInit ("Manager: Loading DTMF key"); - _dtmfKey = new DTMF(sampleRate); - } + _debugInit ("Manager: Loading DTMF key"); + _dtmfKey = new DTMF (sampleRate); + } - // Load the history - _history->load_history(preferences.getHistoryLimit()); + // Load the history + _history->load_history (preferences.getHistoryLimit()); } -void ManagerImpl::terminate () { +void ManagerImpl::terminate () +{ - _debug ("Manager: Terminate "); - saveConfig(); + _debug ("Manager: Terminate "); + saveConfig(); - unloadAccountMap(); + unloadAccountMap(); - _debug ("Manager: Unload DTMF key"); - delete _dtmfKey; + _debug ("Manager: Unload DTMF key"); + delete _dtmfKey; - _debug("Manager: Unload telephone tone"); - delete _telephoneTone; _telephoneTone = NULL; + _debug ("Manager: Unload telephone tone"); + delete _telephoneTone; + _telephoneTone = NULL; - _debug ("Manager: Unload audio driver"); - delete _audiodriver; _audiodriver = NULL; + _debug ("Manager: Unload audio driver"); + delete _audiodriver; + _audiodriver = NULL; - _debug ("Manager: Unload telephone tone"); - delete _telephoneTone; _telephoneTone = NULL; + _debug ("Manager: Unload telephone tone"); + delete _telephoneTone; + _telephoneTone = NULL; - _debug ("Manager: Unload audio codecs "); - _codecDescriptorMap.deleteHandlePointer(); + _debug ("Manager: Unload audio codecs "); + _codecDescriptorMap.deleteHandlePointer(); } -bool ManagerImpl::isCurrentCall (const CallID& callId) { - return (_currentCallId2 == callId ? true : false); +bool ManagerImpl::isCurrentCall (const CallID& callId) +{ + return (_currentCallId2 == callId ? true : false); } -bool ManagerImpl::hasCurrentCall () { - // _debug ("ManagerImpl::hasCurrentCall current call ID = %s", _currentCallId2.c_str()); +bool ManagerImpl::hasCurrentCall () +{ + // _debug ("ManagerImpl::hasCurrentCall current call ID = %s", _currentCallId2.c_str()); - if (_currentCallId2 != "") { - return true; - } + if (_currentCallId2 != "") { + return true; + } - return false; + return false; } const CallID& -ManagerImpl::getCurrentCallId () { - return _currentCallId2; +ManagerImpl::getCurrentCallId () +{ + return _currentCallId2; } -void ManagerImpl::switchCall (const CallID& id) { - ost::MutexLock m(_currentCallMutex); - _debug ("----- Switch current call id to %s -----", id.c_str()); - _currentCallId2 = id; +void ManagerImpl::switchCall (const CallID& id) +{ + ost::MutexLock m (_currentCallMutex); + _debug ("----- Switch current call id to %s -----", id.c_str()); + _currentCallId2 = id; } /////////////////////////////////////////////////////////////////////////////// @@ -206,1817 +219,1868 @@ void ManagerImpl::switchCall (const CallID& id) { /* Main Thread */ bool ManagerImpl::outgoingCall (const std::string& account_id, - const CallID& call_id, const std::string& to) { + const CallID& call_id, const std::string& to) +{ - std::string pattern, to_cleaned; - Call::CallConfiguration callConfig; - SIPVoIPLink *siplink; + std::string pattern, to_cleaned; + Call::CallConfiguration callConfig; + SIPVoIPLink *siplink; - _debug ("Manager: New outgoing call %s to %s", call_id.c_str(), to.c_str()); + _debug ("Manager: New outgoing call %s to %s", call_id.c_str(), to.c_str()); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - if(hookPreference.getNumberEnabled()) - _cleaner->set_phone_number_prefix(hookPreference.getNumberAddPrefix()); - else - _cleaner->set_phone_number_prefix(""); + if (hookPreference.getNumberEnabled()) + _cleaner->set_phone_number_prefix (hookPreference.getNumberAddPrefix()); + else + _cleaner->set_phone_number_prefix (""); - to_cleaned = _cleaner->clean(to); + to_cleaned = _cleaner->clean (to); - /* Check what kind of call we are dealing with */ - check_call_configuration(call_id, to_cleaned, &callConfig); + /* Check what kind of call we are dealing with */ + check_call_configuration (call_id, to_cleaned, &callConfig); - // in any cases we have to detach from current communication - if (hasCurrentCall()) { + // in any cases we have to detach from current communication + if (hasCurrentCall()) { - _debug ("Manager: Has current call (%s) put it onhold", current_call_id.c_str()); - // if this is not a conferenceand this and is not a conference participant - if (!isConference(current_call_id) && !participToConference(current_call_id)) { - onHoldCall(current_call_id); - } else if (isConference(current_call_id) && !participToConference(call_id)) { - detachParticipant(default_id, current_call_id); - } - } + _debug ("Manager: Has current call (%s) put it onhold", current_call_id.c_str()); - if (callConfig == Call::IPtoIP) { - _debug ("Manager: Start IP2IP call"); - /* We need to retrieve the sip voiplink instance */ - siplink = SIPVoIPLink::instance(""); + // if this is not a conferenceand this and is not a conference participant + if (!isConference (current_call_id) && !participToConference (current_call_id)) { + onHoldCall (current_call_id); + } else if (isConference (current_call_id) && !participToConference (call_id)) { + detachParticipant (default_id, current_call_id); + } + } - if (siplink->new_ip_to_ip_call(call_id, to_cleaned)) { - switchCall(call_id); - return true; - } else { - callFailure(call_id); - } + if (callConfig == Call::IPtoIP) { + _debug ("Manager: Start IP2IP call"); + /* We need to retrieve the sip voiplink instance */ + siplink = SIPVoIPLink::instance (""); - return false; - } + if (siplink->new_ip_to_ip_call (call_id, to_cleaned)) { + switchCall (call_id); + return true; + } else { + callFailure (call_id); + } - _debug("Manager: Selecting account %s", account_id.c_str()); - if (!accountExists(account_id)) { - _error ("Manager: Error: Account doesn't exist in new outgoing call"); - return false; - } + return false; + } + + _debug ("Manager: Selecting account %s", account_id.c_str()); - if (getAccountFromCall(call_id) != AccountNULL) { - _error ("Manager: Error: Call id already exists in outgoing call"); - return false; - } + if (!accountExists (account_id)) { + _error ("Manager: Error: Account doesn't exist in new outgoing call"); + return false; + } - _debug ("Manager: Adding Outgoing Call %s on account %s", call_id.data(), account_id.data()); - associateCallToAccount(call_id, account_id); + if (getAccountFromCall (call_id) != AccountNULL) { + _error ("Manager: Error: Call id already exists in outgoing call"); + return false; + } - if (getAccountLink(account_id)->newOutgoingCall(call_id, to_cleaned)) { - switchCall(call_id); - return true; - } else { - callFailure(call_id); - _debug ("Manager: Error: An error occur, the call was not created"); - } + _debug ("Manager: Adding Outgoing Call %s on account %s", call_id.data(), account_id.data()); + associateCallToAccount (call_id, account_id); - return false; + if (getAccountLink (account_id)->newOutgoingCall (call_id, to_cleaned)) { + switchCall (call_id); + return true; + } else { + callFailure (call_id); + _debug ("Manager: Error: An error occur, the call was not created"); + } + + return false; } //THREAD=Main : for outgoing Call -bool ManagerImpl::answerCall (const CallID& call_id) { +bool ManagerImpl::answerCall (const CallID& call_id) +{ - _debug ("ManagerImpl: Answer call %s", call_id.c_str()); + _debug ("ManagerImpl: Answer call %s", call_id.c_str()); - stopTone(); + stopTone(); - // store the current call id - CallID current_call_id = getCurrentCallId(); + // store the current call id + CallID current_call_id = getCurrentCallId(); - AccountID account_id = getAccountFromCall(call_id); + AccountID account_id = getAccountFromCall (call_id); - if (account_id == AccountNULL) { - _debug (" answerCall: AccountId is null"); - } + if (account_id == AccountNULL) { + _debug (" answerCall: AccountId is null"); + } - Call* call = NULL; + Call* call = NULL; - call = getAccountLink(account_id)->getCall(call_id); + call = getAccountLink (account_id)->getCall (call_id); - if (call == NULL) { - _debug (" answerCall: Call is null"); - } + if (call == NULL) { + _debug (" answerCall: Call is null"); + } - // in any cases we have to detach from current communication - if (hasCurrentCall()) { + // in any cases we have to detach from current communication + if (hasCurrentCall()) { - _debug (" answerCall: Currently conversing with %s", current_call_id.c_str()); - // if it is not a conference and is not a conference participant + _debug (" answerCall: Currently conversing with %s", current_call_id.c_str()); + // if it is not a conference and is not a conference participant - if (!isConference(current_call_id) && !participToConference( - current_call_id)) { - _debug (" answerCall: Put the current call (%s) on hold", current_call_id.c_str()); - onHoldCall(current_call_id); - } + if (!isConference (current_call_id) && !participToConference ( + current_call_id)) { + _debug (" answerCall: Put the current call (%s) on hold", current_call_id.c_str()); + onHoldCall (current_call_id); + } - // if we are talking to a conference and we are answering an incoming call - else if (isConference(current_call_id) - && !participToConference(call_id)) { - _debug (" answerCall: Detach main participant from conference"); - detachParticipant(default_id, current_call_id); - } + // if we are talking to a conference and we are answering an incoming call + else if (isConference (current_call_id) + && !participToConference (call_id)) { + _debug (" answerCall: Detach main participant from conference"); + detachParticipant (default_id, current_call_id); + } - } + } - if (!getAccountLink(account_id)->answer(call_id)) { - // error when receiving... - removeCallAccount(call_id); - return false; - } + if (!getAccountLink (account_id)->answer (call_id)) { + // error when receiving... + removeCallAccount (call_id); + return false; + } - // if it was waiting, it's waiting no more - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "CURRENT"); + // if it was waiting, it's waiting no more + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "CURRENT"); - // std::string codecName = Manager::instance().getCurrentCodecName (call_id); - // if (_dbus) _dbus->getCallManager()->currentSelectedCodec (call_id, codecName.c_str()); + // std::string codecName = Manager::instance().getCurrentCodecName (call_id); + // if (_dbus) _dbus->getCallManager()->currentSelectedCodec (call_id, codecName.c_str()); - removeWaitingCall(call_id); + removeWaitingCall (call_id); - // if we dragged this call into a conference already - if (participToConference(call_id)) { + // if we dragged this call into a conference already + if (participToConference (call_id)) { - // AccountID currentAccountId; - // Call* call = NULL; + // AccountID currentAccountId; + // Call* call = NULL; - // currentAccountId = getAccountFromCall (call_id); - // call = getAccountLink (currentAccountId)->getCall (call_id); + // currentAccountId = getAccountFromCall (call_id); + // call = getAccountLink (currentAccountId)->getCall (call_id); - switchCall(call->getConfId()); - } else { - switchCall(call_id); - } + switchCall (call->getConfId()); + } else { + switchCall (call_id); + } - return true; + return true; } //THREAD=Main -bool ManagerImpl::hangupCall (const CallID& call_id) { - - _info("Manager: Hangup call %s", call_id.c_str()); +bool ManagerImpl::hangupCall (const CallID& call_id) +{ - PulseLayer *pulselayer; - AccountID account_id; - bool returnValue = true; + _info ("Manager: Hangup call %s", call_id.c_str()); - // store the current call id - CallID current_call_id = getCurrentCallId(); + PulseLayer *pulselayer; + AccountID account_id; + bool returnValue = true; - stopTone(); + // store the current call id + CallID current_call_id = getCurrentCallId(); - /* Broadcast a signal over DBus */ - _debug ("Manager: Send DBUS call state change (HUNGUP) for id %s", call_id.c_str()); + stopTone(); - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "HUNGUP"); + /* Broadcast a signal over DBus */ + _debug ("Manager: Send DBUS call state change (HUNGUP) for id %s", call_id.c_str()); - if (participToConference(call_id)) { + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "HUNGUP"); - Conference *conf = getConferenceFromCallID(call_id); + if (participToConference (call_id)) { - if (conf != NULL) { - // remove this participant - removeParticipant(call_id); + Conference *conf = getConferenceFromCallID (call_id); - processRemainingParticipant(current_call_id, conf); - } + if (conf != NULL) { + // remove this participant + removeParticipant (call_id); - } else { - // we are not participating to a conference, current call switched to "" - if (!isConference(current_call_id)) - switchCall(""); - } + processRemainingParticipant (current_call_id, conf); + } - /* Direct IP to IP call */ - if (getConfigFromCall(call_id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)->hangup(call_id); - } - /* Classic call, attached to an account */ - else { - account_id = getAccountFromCall(call_id); + } else { + // we are not participating to a conference, current call switched to "" + if (!isConference (current_call_id)) + switchCall (""); + } - // Account may be NULL if call have not been sent yet - if (account_id == AccountNULL) { - _error ("Manager: Error: account id is NULL in hangup"); - returnValue = false; - } else { - returnValue = getAccountLink(account_id)->hangup(call_id); - removeCallAccount(call_id); - } - } + /* Direct IP to IP call */ + if (getConfigFromCall (call_id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)->hangup (call_id); + } + /* Classic call, attached to an account */ + else { + account_id = getAccountFromCall (call_id); + + // Account may be NULL if call have not been sent yet + if (account_id == AccountNULL) { + _error ("Manager: Error: account id is NULL in hangup"); + returnValue = false; + } else { + returnValue = getAccountLink (account_id)->hangup (call_id); + removeCallAccount (call_id); + } + } - int nbCalls = getCallList().size(); + int nbCalls = getCallList().size(); - AudioLayer *audiolayer = getAudioDriver(); + AudioLayer *audiolayer = getAudioDriver(); - // stop streams - if (audiolayer && (nbCalls <= 0)) { - _debug ("Manager: stop audio stream, ther is only %i call(s) remaining", nbCalls); - audiolayer->stopStream(); - } + // stop streams + if (audiolayer && (nbCalls <= 0)) { + _debug ("Manager: stop audio stream, ther is only %i call(s) remaining", nbCalls); + audiolayer->stopStream(); + } - if (_audiodriver->getLayerType() == PULSEAUDIO) { - pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); - } + if (_audiodriver->getLayerType() == PULSEAUDIO) { + pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); + } - return returnValue; + return returnValue; } -bool ManagerImpl::hangupConference (const ConfID& id) { +bool ManagerImpl::hangupConference (const ConfID& id) +{ - _debug ("Manager: Hangup conference %s", id.c_str()); + _debug ("Manager: Hangup conference %s", id.c_str()); - Conference *conf; - ConferenceMap::iterator iter_conf = _conferencemap.find(id); + Conference *conf; + ConferenceMap::iterator iter_conf = _conferencemap.find (id); - AccountID currentAccountId; + AccountID currentAccountId; - // Call* call = NULL; + // Call* call = NULL; - if (iter_conf != _conferencemap.end()) { - conf = iter_conf->second; + if (iter_conf != _conferencemap.end()) { + conf = iter_conf->second; - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _debug ("Manager: Hangup onference participant %s", (*iter_participant).c_str()); + while (iter_participant != participants.end()) { + _debug ("Manager: Hangup onference participant %s", (*iter_participant).c_str()); - hangupCall(*iter_participant); + hangupCall (*iter_participant); - iter_participant++; + iter_participant++; - } + } - } + } - switchCall(""); + switchCall (""); - return true; + return true; } //THREAD=Main -bool ManagerImpl::cancelCall (const CallID& id) { - AccountID accountid; - bool returnValue; +bool ManagerImpl::cancelCall (const CallID& id) +{ + AccountID accountid; + bool returnValue; - _debug("Manager: Cancel call"); + _debug ("Manager: Cancel call"); - stopTone(); + stopTone(); - /* Direct IP to IP call */ + /* Direct IP to IP call */ - if (getConfigFromCall(id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)->cancel(id); - } + if (getConfigFromCall (id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)->cancel (id); + } - /* Classic call, attached to an account */ - else { - accountid = getAccountFromCall(id); + /* Classic call, attached to an account */ + else { + accountid = getAccountFromCall (id); - if (accountid == AccountNULL) { - _debug ("! Manager Cancel Call: Call doesn't exists"); - return false; - } + if (accountid == AccountNULL) { + _debug ("! Manager Cancel Call: Call doesn't exists"); + return false; + } - returnValue = getAccountLink(accountid)->cancel(id); + returnValue = getAccountLink (accountid)->cancel (id); - removeCallAccount(id); - } + removeCallAccount (id); + } - // it could be a waiting call? - removeWaitingCall(id); + // it could be a waiting call? + removeWaitingCall (id); - switchCall(""); + switchCall (""); - return returnValue; + return returnValue; } //THREAD=Main -bool ManagerImpl::onHoldCall (const CallID& call_id) { - AccountID account_id; - bool returnValue; +bool ManagerImpl::onHoldCall (const CallID& call_id) +{ + AccountID account_id; + bool returnValue; - _debug ("Manager: Put call %s on hold", call_id.c_str()); + _debug ("Manager: Put call %s on hold", call_id.c_str()); - stopTone(); + stopTone(); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - /* Direct IP to IP call */ + /* Direct IP to IP call */ - if (getConfigFromCall(call_id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)-> onhold(call_id); - } + if (getConfigFromCall (call_id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)-> onhold (call_id); + } - /* Classic call, attached to an account */ - else { - account_id = getAccountFromCall(call_id); + /* Classic call, attached to an account */ + else { + account_id = getAccountFromCall (call_id); - if (account_id == AccountNULL) { - _debug ("Manager: Account ID %s or callid %s doesn't exists in call onHold", account_id.c_str(), call_id.c_str()); - return false; - } + if (account_id == AccountNULL) { + _debug ("Manager: Account ID %s or callid %s doesn't exists in call onHold", account_id.c_str(), call_id.c_str()); + return false; + } - returnValue = getAccountLink(account_id)->onhold(call_id); - } + returnValue = getAccountLink (account_id)->onhold (call_id); + } - removeWaitingCall(call_id); + removeWaitingCall (call_id); - // keeps current call id if the action is not holding this call or a new outgoing call + // keeps current call id if the action is not holding this call or a new outgoing call - if (current_call_id == call_id) { + if (current_call_id == call_id) { - switchCall(""); - } + switchCall (""); + } - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "HOLD"); + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "HOLD"); - return returnValue; + return returnValue; } //THREAD=Main -bool ManagerImpl::offHoldCall (const CallID& call_id) { +bool ManagerImpl::offHoldCall (const CallID& call_id) +{ - AccountID account_id; - bool returnValue, is_rec; - std::string codecName; + AccountID account_id; + bool returnValue, is_rec; + std::string codecName; - is_rec = false; + is_rec = false; - _debug ("Manager: Put call %s off hold", call_id.c_str()); + _debug ("Manager: Put call %s off hold", call_id.c_str()); - stopTone(); + stopTone(); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - //Place current call on hold if it isn't + //Place current call on hold if it isn't - if (hasCurrentCall()) { - // if this is not a conferenceand this and is not a conference participant - if (!isConference(current_call_id) && !participToConference( - current_call_id)) { - onHoldCall(current_call_id); - } else if (isConference(current_call_id) && !participToConference( - call_id)) { - detachParticipant(default_id, current_call_id); - } - } + if (hasCurrentCall()) { + // if this is not a conferenceand this and is not a conference participant + if (!isConference (current_call_id) && !participToConference ( + current_call_id)) { + onHoldCall (current_call_id); + } else if (isConference (current_call_id) && !participToConference ( + call_id)) { + detachParticipant (default_id, current_call_id); + } + } - // switch current call id to id since sipvoip link need it to amke a call - // switchCall(id); + // switch current call id to id since sipvoip link need it to amke a call + // switchCall(id); - /* Direct IP to IP call */ - if (getConfigFromCall(call_id) == Call::IPtoIP) { - // is_rec = SIPVoIPLink::instance (AccountNULL)-> isRecording (call_id); - returnValue = SIPVoIPLink::instance(AccountNULL)-> offhold(call_id); - } + /* Direct IP to IP call */ + if (getConfigFromCall (call_id) == Call::IPtoIP) { + // is_rec = SIPVoIPLink::instance (AccountNULL)-> isRecording (call_id); + returnValue = SIPVoIPLink::instance (AccountNULL)-> offhold (call_id); + } - /* Classic call, attached to an account */ - else { - account_id = getAccountFromCall(call_id); + /* Classic call, attached to an account */ + else { + account_id = getAccountFromCall (call_id); - if (account_id == AccountNULL) { - _warn ("Manager: Error: Call doesn't exists in off hold"); - return false; - } + if (account_id == AccountNULL) { + _warn ("Manager: Error: Call doesn't exists in off hold"); + return false; + } - _debug ("Manager: Setting offhold, Account %s, callid %s", account_id.c_str(), call_id.c_str()); + _debug ("Manager: Setting offhold, Account %s, callid %s", account_id.c_str(), call_id.c_str()); - is_rec = getAccountLink(account_id)->getCall(call_id)->isRecording(); - returnValue = getAccountLink(account_id)->offhold(call_id); - } + is_rec = getAccountLink (account_id)->getCall (call_id)->isRecording(); + returnValue = getAccountLink (account_id)->offhold (call_id); + } - if (_dbus) { - if (is_rec) - _dbus->getCallManager()->callStateChanged(call_id, "UNHOLD_RECORD"); - else - _dbus->getCallManager()->callStateChanged(call_id, "UNHOLD_CURRENT"); + if (_dbus) { + if (is_rec) + _dbus->getCallManager()->callStateChanged (call_id, "UNHOLD_RECORD"); + else + _dbus->getCallManager()->callStateChanged (call_id, "UNHOLD_CURRENT"); - } + } - if (participToConference(call_id)) { + if (participToConference (call_id)) { - AccountID currentAccountId; - Call* call = NULL; + AccountID currentAccountId; + Call* call = NULL; - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); - switchCall(call->getConfId()); + switchCall (call->getConfId()); - } else { - switchCall(call_id); - _audiodriver->flushMain(); - } + } else { + switchCall (call_id); + _audiodriver->flushMain(); + } - return returnValue; + return returnValue; } //THREAD=Main -bool ManagerImpl::transferCall (const CallID& call_id, const std::string& to) { - AccountID accountid; - bool returnValue; +bool ManagerImpl::transferCall (const CallID& call_id, const std::string& to) +{ + AccountID accountid; + bool returnValue; - _info("Manager: Transfer call %s", call_id.c_str()); + _info ("Manager: Transfer call %s", call_id.c_str()); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - // Direct IP to IP call - if (getConfigFromCall(call_id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)-> transfer(call_id, to); - } - // Classic call, attached to an account - else { + // Direct IP to IP call + if (getConfigFromCall (call_id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)-> transfer (call_id, to); + } + // Classic call, attached to an account + else { - accountid = getAccountFromCall(call_id); + accountid = getAccountFromCall (call_id); - if (accountid == AccountNULL) { - _warn ("Manager: Call doesn't exists"); - return false; - } + if (accountid == AccountNULL) { + _warn ("Manager: Call doesn't exists"); + return false; + } - returnValue = getAccountLink(accountid)->transfer(call_id, to); + returnValue = getAccountLink (accountid)->transfer (call_id, to); - } + } - // remove waiting call in case we make transfer without even answer - removeWaitingCall(call_id); + // remove waiting call in case we make transfer without even answer + removeWaitingCall (call_id); - return returnValue; + return returnValue; } -void ManagerImpl::transferFailed () { +void ManagerImpl::transferFailed () +{ - _debug("UserAgent: Transfer failed"); + _debug ("UserAgent: Transfer failed"); - if (_dbus) - _dbus->getCallManager()->transferFailed(); + if (_dbus) + _dbus->getCallManager()->transferFailed(); } -void ManagerImpl::transferSucceded () { +void ManagerImpl::transferSucceded () +{ - _debug("UserAgent: Transfer succeded"); + _debug ("UserAgent: Transfer succeded"); - if (_dbus) - _dbus->getCallManager()->transferSucceded(); + if (_dbus) + _dbus->getCallManager()->transferSucceded(); } //THREAD=Main : Call:Incoming -bool ManagerImpl::refuseCall (const CallID& id) { - AccountID accountid; - bool returnValue; +bool ManagerImpl::refuseCall (const CallID& id) +{ + AccountID accountid; + bool returnValue; - _debug("Manager: Refuse call %s", id.c_str()); + _debug ("Manager: Refuse call %s", id.c_str()); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - stopTone(); + stopTone(); - int nbCalls = getCallList().size(); + int nbCalls = getCallList().size(); - // AudioLayer* audiolayer = getAudioDriver(); + // AudioLayer* audiolayer = getAudioDriver(); - if (nbCalls <= 1) { - _debug (" refuseCall: stop audio stream, there is only %i call(s) remaining", nbCalls); + if (nbCalls <= 1) { + _debug (" refuseCall: stop audio stream, there is only %i call(s) remaining", nbCalls); - AudioLayer* audiolayer = getAudioDriver(); - audiolayer->stopStream(); - } + AudioLayer* audiolayer = getAudioDriver(); + audiolayer->stopStream(); + } - /* Direct IP to IP call */ + /* Direct IP to IP call */ - if (getConfigFromCall(id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)-> refuse(id); - } + if (getConfigFromCall (id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)-> refuse (id); + } - /* Classic call, attached to an account */ - else { - accountid = getAccountFromCall(id); + /* Classic call, attached to an account */ + else { + accountid = getAccountFromCall (id); - if (accountid == AccountNULL) { - _warn ("Manager: Call doesn't exists"); - return false; - } + if (accountid == AccountNULL) { + _warn ("Manager: Call doesn't exists"); + return false; + } - returnValue = getAccountLink(accountid)->refuse(id); + returnValue = getAccountLink (accountid)->refuse (id); - removeCallAccount(id); - } + removeCallAccount (id); + } - // if the call was outgoing or established, we didn't refuse it - // so the method did nothing - if (returnValue) { - removeWaitingCall(id); + // if the call was outgoing or established, we didn't refuse it + // so the method did nothing + if (returnValue) { + removeWaitingCall (id); - if (_dbus) - _dbus->getCallManager()->callStateChanged(id, "HUNGUP"); - } + if (_dbus) + _dbus->getCallManager()->callStateChanged (id, "HUNGUP"); + } - return returnValue; + return returnValue; } Conference* -ManagerImpl::createConference (const CallID& id1, const CallID& id2) { - _debug ("Manager: Create conference with call %s and %s", id1.c_str(), id2.c_str()); +ManagerImpl::createConference (const CallID& id1, const CallID& id2) +{ + _debug ("Manager: Create conference with call %s and %s", id1.c_str(), id2.c_str()); - Conference* conf = new Conference(); + Conference* conf = new Conference(); - conf->add(id1); - conf->add(id2); + conf->add (id1); + conf->add (id2); - // Add conference to map - _conferencemap.insert( std::pair<CallID, Conference*>(conf->getConfID(), conf)); + // Add conference to map + _conferencemap.insert (std::pair<CallID, Conference*> (conf->getConfID(), conf)); - // broadcast a signal over dbus - _dbus->getCallManager()->conferenceCreated(conf->getConfID()); + // broadcast a signal over dbus + _dbus->getCallManager()->conferenceCreated (conf->getConfID()); - return conf; + return conf; } -void ManagerImpl::removeConference (const ConfID& conference_id) { +void ManagerImpl::removeConference (const ConfID& conference_id) +{ - _debug ("Manager: Remove conference %s", conference_id.c_str()); + _debug ("Manager: Remove conference %s", conference_id.c_str()); - Conference* conf = NULL; + Conference* conf = NULL; - _debug ("Manager: number of participant: %d", (int) _conferencemap.size()); - ConferenceMap::iterator iter = _conferencemap.find(conference_id); + _debug ("Manager: number of participant: %d", (int) _conferencemap.size()); + ConferenceMap::iterator iter = _conferencemap.find (conference_id); - if (iter != _conferencemap.end()) { - conf = iter->second; - } + if (iter != _conferencemap.end()) { + conf = iter->second; + } - if (conf == NULL) { - _error ("Manager: Error: Conference not found"); - return; - } + if (conf == NULL) { + _error ("Manager: Error: Conference not found"); + return; + } - // We now need to bind the audio to the remain participant + // We now need to bind the audio to the remain participant - // Unbind main participant audio from conference - _audiodriver->getMainBuffer()->unBindAll(default_id); + // Unbind main participant audio from conference + _audiodriver->getMainBuffer()->unBindAll (default_id); - ParticipantSet participants = conf->getParticipantList(); + ParticipantSet participants = conf->getParticipantList(); - // bind main participant audio to remaining conference call - ParticipantSet::iterator iter_p = participants.begin(); + // bind main participant audio to remaining conference call + ParticipantSet::iterator iter_p = participants.begin(); - if (iter_p != participants.end()) { + if (iter_p != participants.end()) { - _audiodriver->getMainBuffer()->bindCallID(*iter_p, default_id); - } + _audiodriver->getMainBuffer()->bindCallID (*iter_p, default_id); + } - // Then remove the conference from the conference map - if (_conferencemap.erase(conference_id) == 1) - _debug ("Manager: Conference %s removed successfully", conference_id.c_str()); - else - _error ("Manager: Error: Cannot remove conference: %s", conference_id.c_str()); + // Then remove the conference from the conference map + if (_conferencemap.erase (conference_id) == 1) + _debug ("Manager: Conference %s removed successfully", conference_id.c_str()); + else + _error ("Manager: Error: Cannot remove conference: %s", conference_id.c_str()); - // broadcast a signal over dbus - _dbus->getCallManager()->conferenceRemoved(conference_id); + // broadcast a signal over dbus + _dbus->getCallManager()->conferenceRemoved (conference_id); } Conference* -ManagerImpl::getConferenceFromCallID (const CallID& call_id) { - AccountID account_id; - Call* call = NULL; +ManagerImpl::getConferenceFromCallID (const CallID& call_id) +{ + AccountID account_id; + Call* call = NULL; - account_id = getAccountFromCall(call_id); - call = getAccountLink(account_id)->getCall(call_id); + account_id = getAccountFromCall (call_id); + call = getAccountLink (account_id)->getCall (call_id); - ConferenceMap::iterator iter = _conferencemap.find(call->getConfId()); + ConferenceMap::iterator iter = _conferencemap.find (call->getConfId()); - if (iter != _conferencemap.end()) { - return iter->second; - } else { - return NULL; - } + if (iter != _conferencemap.end()) { + return iter->second; + } else { + return NULL; + } } -void ManagerImpl::holdConference (const CallID& id) { - _debug ("Manager: Hold conference()"); +void ManagerImpl::holdConference (const CallID& id) +{ + _debug ("Manager: Hold conference()"); - Conference *conf; - ConferenceMap::iterator iter_conf = _conferencemap.find(id); + Conference *conf; + ConferenceMap::iterator iter_conf = _conferencemap.find (id); - AccountID currentAccountId; + AccountID currentAccountId; - Call* call = NULL; + Call* call = NULL; - if (iter_conf != _conferencemap.end()) { - conf = iter_conf->second; + if (iter_conf != _conferencemap.end()) { + conf = iter_conf->second; - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _debug (" holdConference: participant %s", (*iter_participant).c_str()); - currentAccountId = getAccountFromCall(*iter_participant); - call = getAccountLink(currentAccountId)->getCall(*iter_participant); + while (iter_participant != participants.end()) { + _debug (" holdConference: participant %s", (*iter_participant).c_str()); + currentAccountId = getAccountFromCall (*iter_participant); + call = getAccountLink (currentAccountId)->getCall (*iter_participant); - switchCall(*iter_participant); - onHoldCall(*iter_participant); + switchCall (*iter_participant); + onHoldCall (*iter_participant); - iter_participant++; + iter_participant++; - } + } - conf->setState(Conference::Hold); + conf->setState (Conference::Hold); - _dbus->getCallManager()->conferenceChanged(conf->getConfID(), - conf->getStateStr()); + _dbus->getCallManager()->conferenceChanged (conf->getConfID(), + conf->getStateStr()); - } + } } -void ManagerImpl::unHoldConference (const CallID& id) { +void ManagerImpl::unHoldConference (const CallID& id) +{ - _debug ("Manager: Unhold conference()"); + _debug ("Manager: Unhold conference()"); - Conference *conf; - ConferenceMap::iterator iter_conf = _conferencemap.find(id); + Conference *conf; + ConferenceMap::iterator iter_conf = _conferencemap.find (id); - AccountID currentAccountId; + AccountID currentAccountId; - Call* call = NULL; + Call* call = NULL; - if (iter_conf != _conferencemap.end()) { - conf = iter_conf->second; + if (iter_conf != _conferencemap.end()) { + conf = iter_conf->second; - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _debug (" unholdConference: participant %s", (*iter_participant).c_str()); - currentAccountId = getAccountFromCall(*iter_participant); - call = getAccountLink(currentAccountId)->getCall(*iter_participant); + while (iter_participant != participants.end()) { + _debug (" unholdConference: participant %s", (*iter_participant).c_str()); + currentAccountId = getAccountFromCall (*iter_participant); + call = getAccountLink (currentAccountId)->getCall (*iter_participant); - offHoldCall(*iter_participant); + offHoldCall (*iter_participant); - iter_participant++; + iter_participant++; - } + } - conf->setState(Conference::Active_Atached); + conf->setState (Conference::Active_Atached); - _dbus->getCallManager()->conferenceChanged(conf->getConfID(), - conf->getStateStr()); + _dbus->getCallManager()->conferenceChanged (conf->getConfID(), + conf->getStateStr()); - } + } } -bool ManagerImpl::isConference (const CallID& id) { - ConferenceMap::iterator iter = _conferencemap.find(id); +bool ManagerImpl::isConference (const CallID& id) +{ + ConferenceMap::iterator iter = _conferencemap.find (id); - if (iter == _conferencemap.end()) { - return false; - } else { - return true; - } + if (iter == _conferencemap.end()) { + return false; + } else { + return true; + } } -bool ManagerImpl::participToConference (const CallID& call_id) { +bool ManagerImpl::participToConference (const CallID& call_id) +{ - AccountID accountId; + AccountID accountId; - Call* call = NULL; + Call* call = NULL; - accountId = getAccountFromCall(call_id); - call = getAccountLink(accountId)->getCall(call_id); + accountId = getAccountFromCall (call_id); + call = getAccountLink (accountId)->getCall (call_id); - if (call == NULL) { - return false; + if (call == NULL) { + return false; - } + } - if (call->getConfId() == "") { - return false; - } else { + if (call->getConfId() == "") { + return false; + } else { - return true; - } + return true; + } } -void ManagerImpl::addParticipant (const CallID& call_id, const CallID& conference_id) { - _debug ("ManagerImpl: Add participant %s to %s", call_id.c_str(), conference_id.c_str()); +void ManagerImpl::addParticipant (const CallID& call_id, const CallID& conference_id) +{ + _debug ("ManagerImpl: Add participant %s to %s", call_id.c_str(), conference_id.c_str()); - std::map<std::string, std::string> call_details = getCallDetails(call_id); + std::map<std::string, std::string> call_details = getCallDetails (call_id); - ConferenceMap::iterator iter = _conferencemap.find(conference_id); - std::map<std::string, std::string>::iterator iter_details; + ConferenceMap::iterator iter = _conferencemap.find (conference_id); + std::map<std::string, std::string>::iterator iter_details; - // store the current call id (it will change in offHoldCall or in answerCall) - CallID current_call_id = getCurrentCallId(); + // store the current call id (it will change in offHoldCall or in answerCall) + CallID current_call_id = getCurrentCallId(); - // detach from the conference and switch to this conference + // detach from the conference and switch to this conference - if (current_call_id != call_id) { - if (isConference(current_call_id)) { - detachParticipant(default_id, current_call_id); - } else - onHoldCall(current_call_id); - } + if (current_call_id != call_id) { + if (isConference (current_call_id)) { + detachParticipant (default_id, current_call_id); + } else + onHoldCall (current_call_id); + } - // TODO: remove this ugly hack => There should be different calls when double clicking - // a conference to add main participant to it, or (in this case) adding a participant - // toconference - switchCall(""); + // TODO: remove this ugly hack => There should be different calls when double clicking + // a conference to add main participant to it, or (in this case) adding a participant + // toconference + switchCall (""); - addMainParticipant(conference_id); + addMainParticipant (conference_id); - _debug (" addParticipant: enter main process"); + _debug (" addParticipant: enter main process"); - if (iter != _conferencemap.end()) { + if (iter != _conferencemap.end()) { - Conference* conf = iter->second; - switchCall(conf->getConfID()); + Conference* conf = iter->second; + switchCall (conf->getConfID()); - AccountID currentAccountId; - Call* call = NULL; + AccountID currentAccountId; + Call* call = NULL; - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); - call->setConfId(conf->getConfID()); + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); + call->setConfId (conf->getConfID()); - conf->add(call_id); + conf->add (call_id); - iter_details = call_details.find("CALL_STATE"); + iter_details = call_details.find ("CALL_STATE"); - _debug (" addParticipant: call state: %s", iter_details->second.c_str()); + _debug (" addParticipant: call state: %s", iter_details->second.c_str()); - if (iter_details->second == "HOLD") { - _debug (" OFFHOLD %s", call_id.c_str()); + if (iter_details->second == "HOLD") { + _debug (" OFFHOLD %s", call_id.c_str()); - // offHoldCall create a new rtp session which use addStream to bind participant - offHoldCall(call_id); - } else if (iter_details->second == "INCOMING") { - _debug (" ANSWER %s", call_id.c_str()); - // answerCall create a new rtp session which use addStream to bind participant - answerCall(call_id); - } else if (iter_details->second == "CURRENT") { - // Already a curent call, so we beed to reset audio stream bindings manually - _audiodriver->getMainBuffer()->unBindAll(call_id); - conf->bindParticipant(call_id); - } + // offHoldCall create a new rtp session which use addStream to bind participant + offHoldCall (call_id); + } else if (iter_details->second == "INCOMING") { + _debug (" ANSWER %s", call_id.c_str()); + // answerCall create a new rtp session which use addStream to bind participant + answerCall (call_id); + } else if (iter_details->second == "CURRENT") { + // Already a curent call, so we beed to reset audio stream bindings manually + _audiodriver->getMainBuffer()->unBindAll (call_id); + conf->bindParticipant (call_id); + } - // _dbus->getCallManager()->conferenceChanged(conference_id, conf->getStateStr()); + // _dbus->getCallManager()->conferenceChanged(conference_id, conf->getStateStr()); - ParticipantSet participants = conf->getParticipantList(); + ParticipantSet participants = conf->getParticipantList(); - // reset ring buffer for all conference participant - ParticipantSet::iterator iter_p = participants.begin(); + // reset ring buffer for all conference participant + ParticipantSet::iterator iter_p = participants.begin(); - while (iter_p != participants.end()) { + while (iter_p != participants.end()) { - // flush conference participants only - _audiodriver->getMainBuffer()->flush(*iter_p); + // flush conference participants only + _audiodriver->getMainBuffer()->flush (*iter_p); - iter_p++; - } + iter_p++; + } - _audiodriver->getMainBuffer()->flush(default_id); - } else { - _debug (" addParticipant: Error, conference %s conference_id not found!", conference_id.c_str()); - } + _audiodriver->getMainBuffer()->flush (default_id); + } else { + _debug (" addParticipant: Error, conference %s conference_id not found!", conference_id.c_str()); + } } -void ManagerImpl::addMainParticipant (const CallID& conference_id) { - if (hasCurrentCall()) { - CallID current_call_id = getCurrentCallId(); +void ManagerImpl::addMainParticipant (const CallID& conference_id) +{ + if (hasCurrentCall()) { + CallID current_call_id = getCurrentCallId(); - if (isConference(current_call_id)) { - detachParticipant(default_id, current_call_id); - } else { - onHoldCall(current_call_id); - } - } + if (isConference (current_call_id)) { + detachParticipant (default_id, current_call_id); + } else { + onHoldCall (current_call_id); + } + } - ConferenceMap::iterator iter = _conferencemap.find(conference_id); + ConferenceMap::iterator iter = _conferencemap.find (conference_id); - Conference *conf = NULL; + Conference *conf = NULL; - if (iter != _conferencemap.end()) { - conf = iter->second; + if (iter != _conferencemap.end()) { + conf = iter->second; - ParticipantSet participants = conf->getParticipantList(); + ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _audiodriver->getMainBuffer()->bindCallID(*iter_participant, - default_id); + while (iter_participant != participants.end()) { + _audiodriver->getMainBuffer()->bindCallID (*iter_participant, + default_id); - iter_participant++; - } + iter_participant++; + } - // Reset ringbuffer's readpointers - iter_participant = participants.begin(); + // Reset ringbuffer's readpointers + iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _audiodriver->getMainBuffer()->flush(*iter_participant); + while (iter_participant != participants.end()) { + _audiodriver->getMainBuffer()->flush (*iter_participant); - iter_participant++; - } + iter_participant++; + } - _audiodriver->getMainBuffer()->flush(default_id); + _audiodriver->getMainBuffer()->flush (default_id); - conf->setState(Conference::Active_Atached); + conf->setState (Conference::Active_Atached); - _dbus->getCallManager()->conferenceChanged(conference_id, - conf->getStateStr()); + _dbus->getCallManager()->conferenceChanged (conference_id, + conf->getStateStr()); - } + } - switchCall(conference_id); + switchCall (conference_id); } -void ManagerImpl::joinParticipant (const CallID& call_id1, const CallID& call_id2) { - - _debug ("Manager: Join participants %s, %s", call_id1.c_str(), call_id2.c_str()); - - std::map<std::string, std::string> call1_details = getCallDetails(call_id1); - std::map<std::string, std::string> call2_details = getCallDetails(call_id2); - - std::map<std::string, std::string>::iterator iter_details; - - // Test if we have valid call ids - iter_details = call1_details.find("PEER_NUMBER"); - if(iter_details->second == "Unknown") { - _error("Manager: Error: Id %s is not a valid call", call_id1.c_str()); - return; - } +void ManagerImpl::joinParticipant (const CallID& call_id1, const CallID& call_id2) +{ - iter_details = call2_details.find("PEER_NUMBER"); - if(iter_details->second == "Unknown") { - _error("Manager: Error: Id %s is not a valid call", call_id2.c_str()); - return; - } + _debug ("Manager: Join participants %s, %s", call_id1.c_str(), call_id2.c_str()); - AccountID currentAccountId; - Call* call = NULL; + std::map<std::string, std::string> call1_details = getCallDetails (call_id1); + std::map<std::string, std::string> call2_details = getCallDetails (call_id2); - CallID current_call_id = getCurrentCallId(); - _debug ("Manager: current_call_id %s", current_call_id.c_str()); + std::map<std::string, std::string>::iterator iter_details; - // detach from the conference and switch to this conference - if ((current_call_id != call_id1) && (current_call_id != call_id2)) { + // Test if we have valid call ids + iter_details = call1_details.find ("PEER_NUMBER"); - // If currently in a conference - if (isConference(current_call_id)) - detachParticipant(default_id, current_call_id); - // If currently in a call - else - onHoldCall(current_call_id); - } - - _debug ("Manager: Create a conference"); + if (iter_details->second == "Unknown") { + _error ("Manager: Error: Id %s is not a valid call", call_id1.c_str()); + return; + } - Conference *conf = createConference(call_id1, call_id2); - switchCall(conf->getConfID()); + iter_details = call2_details.find ("PEER_NUMBER"); - currentAccountId = getAccountFromCall(call_id1); - call = getAccountLink(currentAccountId)->getCall(call_id1); - call->setConfId(conf->getConfID()); + if (iter_details->second == "Unknown") { + _error ("Manager: Error: Id %s is not a valid call", call_id2.c_str()); + return; + } - iter_details = call1_details.find("CALL_STATE"); - _debug ("Manager: Process call %s state: %s", call_id1.c_str(), iter_details->second.c_str()); + AccountID currentAccountId; + Call* call = NULL; - if (iter_details->second == "HOLD") { - offHoldCall(call_id1); - } else if (iter_details->second == "INCOMING") { - answerCall(call_id1); - } else if (iter_details->second == "CURRENT") { - _audiodriver->getMainBuffer()->unBindAll(call_id1); - conf->bindParticipant(call_id1); - } else if (iter_details->second == "INACTIVE") { - answerCall(call_id1); - } else { - _warn ("Manager: Call state not recognized"); - } + CallID current_call_id = getCurrentCallId(); + _debug ("Manager: current_call_id %s", current_call_id.c_str()); - currentAccountId = getAccountFromCall(call_id2); + // detach from the conference and switch to this conference + if ( (current_call_id != call_id1) && (current_call_id != call_id2)) { - call = getAccountLink(currentAccountId)->getCall(call_id2); - call->setConfId(conf->getConfID()); + // If currently in a conference + if (isConference (current_call_id)) + detachParticipant (default_id, current_call_id); + // If currently in a call + else + onHoldCall (current_call_id); + } - iter_details = call2_details.find("CALL_STATE"); - _debug ("Manager: Process call %s state: %s", call_id2.c_str(), iter_details->second.c_str()); + _debug ("Manager: Create a conference"); + + Conference *conf = createConference (call_id1, call_id2); + switchCall (conf->getConfID()); + + currentAccountId = getAccountFromCall (call_id1); + call = getAccountLink (currentAccountId)->getCall (call_id1); + call->setConfId (conf->getConfID()); + + iter_details = call1_details.find ("CALL_STATE"); + _debug ("Manager: Process call %s state: %s", call_id1.c_str(), iter_details->second.c_str()); + + if (iter_details->second == "HOLD") { + offHoldCall (call_id1); + } else if (iter_details->second == "INCOMING") { + answerCall (call_id1); + } else if (iter_details->second == "CURRENT") { + _audiodriver->getMainBuffer()->unBindAll (call_id1); + conf->bindParticipant (call_id1); + } else if (iter_details->second == "INACTIVE") { + answerCall (call_id1); + } else { + _warn ("Manager: Call state not recognized"); + } - if (iter_details->second == "HOLD") { - offHoldCall(call_id2); - } else if (iter_details->second == "INCOMING") { - answerCall(call_id2); - } else if (iter_details->second == "CURRENT") { - _audiodriver->getMainBuffer()->unBindAll(call_id2); - conf->bindParticipant(call_id2); - } else if (iter_details->second == "INACTIVE") { - answerCall(call_id2); - } else { - _warn ("Manager: Call state not recognized"); - } + currentAccountId = getAccountFromCall (call_id2); + + call = getAccountLink (currentAccountId)->getCall (call_id2); + call->setConfId (conf->getConfID()); + + iter_details = call2_details.find ("CALL_STATE"); + _debug ("Manager: Process call %s state: %s", call_id2.c_str(), iter_details->second.c_str()); + + if (iter_details->second == "HOLD") { + offHoldCall (call_id2); + } else if (iter_details->second == "INCOMING") { + answerCall (call_id2); + } else if (iter_details->second == "CURRENT") { + _audiodriver->getMainBuffer()->unBindAll (call_id2); + conf->bindParticipant (call_id2); + } else if (iter_details->second == "INACTIVE") { + answerCall (call_id2); + } else { + _warn ("Manager: Call state not recognized"); + } - if (_audiodriver) - _audiodriver->getMainBuffer()->stateInfo(); + if (_audiodriver) + _audiodriver->getMainBuffer()->stateInfo(); } void ManagerImpl::detachParticipant (const CallID& call_id, - const CallID& current_id) { + const CallID& current_id) +{ - _debug ("Manager: Detach participant %s from conference", call_id.c_str()); + _debug ("Manager: Detach participant %s from conference", call_id.c_str()); - CallID current_call_id = current_id; + CallID current_call_id = current_id; - current_call_id = getCurrentCallId(); + current_call_id = getCurrentCallId(); - if (call_id != default_id) { - AccountID currentAccountId; - Call* call = NULL; + if (call_id != default_id) { + AccountID currentAccountId; + Call* call = NULL; - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); - // TODO: add conference_id as a second parameter - ConferenceMap::iterator iter = _conferencemap.find(call->getConfId()); + // TODO: add conference_id as a second parameter + ConferenceMap::iterator iter = _conferencemap.find (call->getConfId()); - Conference *conf = getConferenceFromCallID(call_id); + Conference *conf = getConferenceFromCallID (call_id); - if (conf != NULL) { + if (conf != NULL) { - _debug ("Manager: Detaching participant %s", call_id.c_str()); - std::map<std::string, std::string> call_details = getCallDetails( - call_id); - std::map<std::string, std::string>::iterator iter_details; + _debug ("Manager: Detaching participant %s", call_id.c_str()); + std::map<std::string, std::string> call_details = getCallDetails ( + call_id); + std::map<std::string, std::string>::iterator iter_details; - iter_details = call_details.find("CALL_STATE"); + iter_details = call_details.find ("CALL_STATE"); - if (iter_details->second == "RINGING") { + if (iter_details->second == "RINGING") { - removeParticipant(call_id); - } - else { - onHoldCall(call_id); - removeParticipant(call_id); - processRemainingParticipant(current_call_id, conf); + removeParticipant (call_id); + } else { + onHoldCall (call_id); + removeParticipant (call_id); + processRemainingParticipant (current_call_id, conf); - _dbus->getCallManager()->conferenceChanged(conf->getConfID(), - conf->getStateStr()); - } - } - else { + _dbus->getCallManager()->conferenceChanged (conf->getConfID(), + conf->getStateStr()); + } + } else { - _debug ("Manager: Call is not conferencing, cannot detach"); + _debug ("Manager: Call is not conferencing, cannot detach"); - } - } - else { - _debug ("Manager: Unbind main participant from all"); - _audiodriver->getMainBuffer()->unBindAll(default_id); + } + } else { + _debug ("Manager: Unbind main participant from all"); + _audiodriver->getMainBuffer()->unBindAll (default_id); - if (isConference(current_call_id)) { + if (isConference (current_call_id)) { - ConferenceMap::iterator iter = _conferencemap.find(current_call_id); - Conference *conf = iter->second; + ConferenceMap::iterator iter = _conferencemap.find (current_call_id); + Conference *conf = iter->second; - conf->setState(Conference::Active_Detached); + conf->setState (Conference::Active_Detached); - _dbus->getCallManager()->conferenceChanged(conf->getConfID(), - conf->getStateStr()); - } + _dbus->getCallManager()->conferenceChanged (conf->getConfID(), + conf->getStateStr()); + } - switchCall(""); + switchCall (""); - } + } } -void ManagerImpl::removeParticipant (const CallID& call_id) { - _debug ("Manager: Remove participant %s", call_id.c_str()); +void ManagerImpl::removeParticipant (const CallID& call_id) +{ + _debug ("Manager: Remove participant %s", call_id.c_str()); - // TODO: add conference_id as a second parameter - Conference* conf; + // TODO: add conference_id as a second parameter + Conference* conf; - AccountID currentAccountId; - Call* call = NULL; + AccountID currentAccountId; + Call* call = NULL; - // this call is no more a conference participant - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); + // this call is no more a conference participant + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); - ConferenceMap conf_map = _conferencemap; - ConferenceMap::iterator iter = conf_map.find(call->getConfId()); + ConferenceMap conf_map = _conferencemap; + ConferenceMap::iterator iter = conf_map.find (call->getConfId()); - if (iter == conf_map.end()) { - _debug ("Manager: Error: No conference created, cannot remove participant"); - } else { + if (iter == conf_map.end()) { + _debug ("Manager: Error: No conference created, cannot remove participant"); + } else { - conf = iter->second; + conf = iter->second; - _debug ("Manager: Remove participant %s", call_id.c_str()); - conf->remove(call_id); - call->setConfId(""); + _debug ("Manager: Remove participant %s", call_id.c_str()); + conf->remove (call_id); + call->setConfId (""); - } + } - if (_audiodriver) - _audiodriver->getMainBuffer()->stateInfo(); + if (_audiodriver) + _audiodriver->getMainBuffer()->stateInfo(); } void ManagerImpl::processRemainingParticipant (CallID current_call_id, - Conference *conf) { + Conference *conf) +{ - _debug ("Manager: Process remaining %d participant(s) from conference %s", - conf->getNbParticipants(), conf->getConfID().c_str()); + _debug ("Manager: Process remaining %d participant(s) from conference %s", + conf->getNbParticipants(), conf->getConfID().c_str()); - if (conf->getNbParticipants() > 1) { + if (conf->getNbParticipants() > 1) { - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - // Reset ringbuffer's readpointers - iter_participant = participants.begin(); + // Reset ringbuffer's readpointers + iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _audiodriver->getMainBuffer()->flush(*iter_participant); + while (iter_participant != participants.end()) { + _audiodriver->getMainBuffer()->flush (*iter_participant); - iter_participant++; - } + iter_participant++; + } - _audiodriver->getMainBuffer()->flush(default_id); + _audiodriver->getMainBuffer()->flush (default_id); - } else if (conf->getNbParticipants() == 1) { + } else if (conf->getNbParticipants() == 1) { - _debug ("Manager: Only one remaining participant"); + _debug ("Manager: Only one remaining participant"); - AccountID currentAccountId; - Call* call = NULL; + AccountID currentAccountId; + Call* call = NULL; - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - // bind main participant to remaining conference call - if (iter_participant != participants.end()) { + // bind main participant to remaining conference call + if (iter_participant != participants.end()) { - // this call is no more a conference participant - currentAccountId = getAccountFromCall(*iter_participant); - call = getAccountLink(currentAccountId)->getCall(*iter_participant); - call->setConfId(""); + // this call is no more a conference participant + currentAccountId = getAccountFromCall (*iter_participant); + call = getAccountLink (currentAccountId)->getCall (*iter_participant); + call->setConfId (""); - // if we are not listening to this conference + // if we are not listening to this conference - if (current_call_id != conf->getConfID()) { - onHoldCall(call->getCallId()); - } else { - switchCall(*iter_participant); - } - } + if (current_call_id != conf->getConfID()) { + onHoldCall (call->getCallId()); + } else { + switchCall (*iter_participant); + } + } - removeConference(conf->getConfID()); + removeConference (conf->getConfID()); - } else { + } else { - _debug ("Manager: No remaining participant, remove conference"); + _debug ("Manager: No remaining participant, remove conference"); - removeConference(conf->getConfID()); + removeConference (conf->getConfID()); - switchCall(""); - } + switchCall (""); + } } void ManagerImpl::joinConference (const CallID& conf_id1, - const CallID& conf_id2) { - _debug ("Manager: Join conference %s, %s", conf_id1.c_str(), conf_id2.c_str()); + const CallID& conf_id2) +{ + _debug ("Manager: Join conference %s, %s", conf_id1.c_str(), conf_id2.c_str()); - ConferenceMap::iterator iter; + ConferenceMap::iterator iter; - Conference *conf1 = NULL; - Conference *conf2 = NULL; + Conference *conf1 = NULL; + Conference *conf2 = NULL; - iter = _conferencemap.find(conf_id1); + iter = _conferencemap.find (conf_id1); - if (iter != _conferencemap.end()) { - conf1 = iter->second; - } - else { - _error("Manager: Error: Not a valid conference ID"); - return; - } + if (iter != _conferencemap.end()) { + conf1 = iter->second; + } else { + _error ("Manager: Error: Not a valid conference ID"); + return; + } - iter = _conferencemap.find(conf_id2); + iter = _conferencemap.find (conf_id2); - if (iter != _conferencemap.end()) { - conf2 = iter->second; - } - else { - _error("Manager: Error: Not a valid conference ID"); - return; - } + if (iter != _conferencemap.end()) { + conf2 = iter->second; + } else { + _error ("Manager: Error: Not a valid conference ID"); + return; + } - ParticipantSet participants = conf1->getParticipantList(); + ParticipantSet participants = conf1->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - detachParticipant(*iter_participant, ""); - addParticipant(*iter_participant, conf_id2); + while (iter_participant != participants.end()) { + detachParticipant (*iter_participant, ""); + addParticipant (*iter_participant, conf_id2); - iter_participant++; - } + iter_participant++; + } - // detachParticipant(default_id, ""); + // detachParticipant(default_id, ""); } -void ManagerImpl::addStream (const CallID& call_id) { +void ManagerImpl::addStream (const CallID& call_id) +{ + + _debug ("Manager: Add audio stream %s", call_id.c_str()); - _debug ("Manager: Add audio stream %s", call_id.c_str()); + AccountID currentAccountId; + Call* call = NULL; - AccountID currentAccountId; - Call* call = NULL; + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); + if (participToConference (call_id)) { - if (participToConference(call_id)) { + _debug ("Manager: Add stream to conference"); - _debug("Manager: Add stream to conference"); + // bind to conference participant + ConferenceMap::iterator iter = _conferencemap.find (call->getConfId()); - // bind to conference participant - ConferenceMap::iterator iter = _conferencemap.find(call->getConfId()); + if (iter != _conferencemap.end()) { + Conference* conf = iter->second; - if (iter != _conferencemap.end()) { - Conference* conf = iter->second; + conf->bindParticipant (call_id); - conf->bindParticipant(call_id); + ParticipantSet participants = conf->getParticipantList(); + // reset ring buffer for all conference participant + ParticipantSet::iterator iter_p = participants.begin(); - ParticipantSet participants = conf->getParticipantList(); - // reset ring buffer for all conference participant - ParticipantSet::iterator iter_p = participants.begin(); + while (iter_p != participants.end()) { - while (iter_p != participants.end()) { + // to avoid puting onhold the call + // switchCall(""); + _audiodriver->getMainBuffer()->flush (*iter_p); - // to avoid puting onhold the call - // switchCall(""); - _audiodriver->getMainBuffer()->flush(*iter_p); - - iter_p++; - } + iter_p++; + } - _audiodriver->getMainBuffer()->flush(default_id); - } + _audiodriver->getMainBuffer()->flush (default_id); + } - } else { + } else { - _debug("Manager: Add stream to call"); + _debug ("Manager: Add stream to call"); - // bind to main - getAudioDriver()->getMainBuffer()->bindCallID(call_id); - - // _audiodriver->getMainBuffer()->flush(default_id); - _audiodriver->flushUrgent(); - _audiodriver->flushMain(); + // bind to main + getAudioDriver()->getMainBuffer()->bindCallID (call_id); - } + // _audiodriver->getMainBuffer()->flush(default_id); + _audiodriver->flushUrgent(); + _audiodriver->flushMain(); - if (_audiodriver) - _audiodriver->getMainBuffer()->stateInfo(); + } + + if (_audiodriver) + _audiodriver->getMainBuffer()->stateInfo(); } -void ManagerImpl::removeStream (const CallID& call_id) { - _debug ("Manager: Remove audio stream %s", call_id.c_str()); +void ManagerImpl::removeStream (const CallID& call_id) +{ + _debug ("Manager: Remove audio stream %s", call_id.c_str()); - getAudioDriver()->getMainBuffer()->unBindAll(call_id); + getAudioDriver()->getMainBuffer()->unBindAll (call_id); - if (participToConference(call_id)) { - removeParticipant(call_id); - } + if (participToConference (call_id)) { + removeParticipant (call_id); + } - if (_audiodriver) - _audiodriver->getMainBuffer()->stateInfo(); + if (_audiodriver) + _audiodriver->getMainBuffer()->stateInfo(); } //THREAD=Main -bool ManagerImpl::saveConfig (void) { - _debug ("Manager: Saving Configuration to XDG directory %s ... ", _path.c_str()); - audioPreference.setVolumemic(getMicVolume()); - audioPreference.setVolumespkr(getSpkrVolume()); - - AccountMap::iterator iter = _accountMap.begin(); - - try{ - // emitter = new Conf::YamlEmitter("sequenceEmitter.yml"); - emitter = new Conf::YamlEmitter(_path.c_str()); - - while(iter != _accountMap.end()) { - _debug("Manager: Saving account: %s", iter->first.c_str()); - if(iter->first == "") { - iter++; - continue; - } - iter->second->serialize(emitter); - iter++; - } - - preferences.serialize(emitter); - voipPreferences.serialize(emitter); - addressbookPreference.serialize(emitter); - hookPreference.serialize(emitter); - audioPreference.serialize(emitter); - shortcutPreferences.serialize(emitter); - - emitter->serializeData(); - - delete emitter; - } - catch (Conf::YamlEmitterException &e) { - _error("ConfigTree: %s", e.what()); - } - - // _setupLoaded = _config.saveConfigTree(_path.data()); - return _setupLoaded; +bool ManagerImpl::saveConfig (void) +{ + _debug ("Manager: Saving Configuration to XDG directory %s ... ", _path.c_str()); + audioPreference.setVolumemic (getMicVolume()); + audioPreference.setVolumespkr (getSpkrVolume()); + + AccountMap::iterator iter = _accountMap.begin(); + + try { + // emitter = new Conf::YamlEmitter("sequenceEmitter.yml"); + emitter = new Conf::YamlEmitter (_path.c_str()); + + while (iter != _accountMap.end()) { + _debug ("Manager: Saving account: %s", iter->first.c_str()); + + if (iter->first == "") { + iter++; + continue; + } + + iter->second->serialize (emitter); + iter++; + } + + preferences.serialize (emitter); + voipPreferences.serialize (emitter); + addressbookPreference.serialize (emitter); + hookPreference.serialize (emitter); + audioPreference.serialize (emitter); + shortcutPreferences.serialize (emitter); + + emitter->serializeData(); + + delete emitter; + } catch (Conf::YamlEmitterException &e) { + _error ("ConfigTree: %s", e.what()); + } + + // _setupLoaded = _config.saveConfigTree(_path.data()); + return _setupLoaded; } //THREAD=Main -bool ManagerImpl::sendDtmf (const CallID& id, char code) { +bool ManagerImpl::sendDtmf (const CallID& id, char code) +{ - AccountID accountid = getAccountFromCall(id); + AccountID accountid = getAccountFromCall (id); - bool returnValue = false; + bool returnValue = false; - playDtmf(code); + playDtmf (code); - CallAccountMap::iterator iter = _callAccountMap.find(id); + CallAccountMap::iterator iter = _callAccountMap.find (id); - // Make sure the call exist before sending DTMF, ths could be simply call dialing - if(iter != _callAccountMap.end()) - returnValue = getAccountLink(accountid)->carryingDTMFdigits(id, code); + // Make sure the call exist before sending DTMF, ths could be simply call dialing + if (iter != _callAccountMap.end()) + returnValue = getAccountLink (accountid)->carryingDTMFdigits (id, code); - return returnValue; + return returnValue; } //THREAD=Main | VoIPLink -bool ManagerImpl::playDtmf (char code) { - int pulselen, layer, size; - bool ret = false; - AudioLayer *audiolayer; - SFLDataFormat *buf; - - stopTone(); - - bool hasToPlayTone = voipPreferences.getPlayDtmf(); - - if (!hasToPlayTone) { - _debug ("Manager: playDtmf: Do not have to play a tone..."); - return false; - } +bool ManagerImpl::playDtmf (char code) +{ + int pulselen, layer, size; + bool ret = false; + AudioLayer *audiolayer; + SFLDataFormat *buf; - // length in milliseconds - pulselen = voipPreferences.getPulseLength(); + stopTone(); - if (!pulselen) { - _debug ("Manager: playDtmf: Pulse length is not set..."); - return false; - } + bool hasToPlayTone = voipPreferences.getPlayDtmf(); - // numbers of int = length in milliseconds / 1000 (number of seconds) - // = number of seconds * SAMPLING_RATE by SECONDS - audiolayer = getAudioDriver(); + if (!hasToPlayTone) { + _debug ("Manager: playDtmf: Do not have to play a tone..."); + return false; + } - layer = audiolayer->getLayerType(); + // length in milliseconds + pulselen = voipPreferences.getPulseLength(); - // fast return, no sound, so no dtmf - if (audiolayer == 0 || _dtmfKey == 0) { - _debug ("Manager: playDtmf: Error no audio layer..."); - return false; - } + if (!pulselen) { + _debug ("Manager: playDtmf: Pulse length is not set..."); + return false; + } - // 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); + // numbers of int = length in milliseconds / 1000 (number of seconds) + // = number of seconds * SAMPLING_RATE by SECONDS + audiolayer = getAudioDriver(); - // this buffer is for mono - // TODO <-- this should be global and hide if same size - buf = new SFLDataFormat[size]; + layer = audiolayer->getLayerType(); - // Handle dtmf - _dtmfKey->startTone(code); + // fast return, no sound, so no dtmf + if (audiolayer == 0 || _dtmfKey == 0) { + _debug ("Manager: playDtmf: Error no audio layer..."); + return false; + } - // 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) - // audiolayer->flushUrgent(); - audiolayer->startStream(); - audiolayer->putUrgent(buf, size * sizeof(SFLDataFormat)); - } + // 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) + // audiolayer->flushUrgent(); + audiolayer->startStream(); + audiolayer->putUrgent (buf, size * sizeof (SFLDataFormat)); + } - ret = true; + ret = true; - // TODO Cache the DTMF + // TODO Cache the DTMF - delete[] buf; - buf = 0; + delete[] buf; + buf = 0; - return ret; + return ret; } // Multi-thread -bool ManagerImpl::incomingCallWaiting () { - return (_nbIncomingWaitingCall > 0) ? true : false; +bool ManagerImpl::incomingCallWaiting () +{ + return (_nbIncomingWaitingCall > 0) ? true : false; } -void ManagerImpl::addWaitingCall (const CallID& id) { +void ManagerImpl::addWaitingCall (const CallID& id) +{ - _info("Manager: Add waiting call %s (%d calls)", id.c_str(), _nbIncomingWaitingCall); + _info ("Manager: Add waiting call %s (%d calls)", id.c_str(), _nbIncomingWaitingCall); - ost::MutexLock m(_waitingCallMutex); - _waitingCall.insert(id); - _nbIncomingWaitingCall++; + ost::MutexLock m (_waitingCallMutex); + _waitingCall.insert (id); + _nbIncomingWaitingCall++; } -void ManagerImpl::removeWaitingCall (const CallID& id) { +void ManagerImpl::removeWaitingCall (const CallID& id) +{ - _info("Manager: Remove waiting call %s (%d calls)", id.c_str(), _nbIncomingWaitingCall); + _info ("Manager: Remove waiting call %s (%d calls)", id.c_str(), _nbIncomingWaitingCall); - ost::MutexLock m(_waitingCallMutex); - // should return more than 1 if it erase a call + ost::MutexLock m (_waitingCallMutex); + // should return more than 1 if it erase a call - if (_waitingCall.erase(id)) { - _nbIncomingWaitingCall--; - } + if (_waitingCall.erase (id)) { + _nbIncomingWaitingCall--; + } } -bool ManagerImpl::isWaitingCall (const CallID& id) { - CallIDSet::iterator iter = _waitingCall.find(id); +bool ManagerImpl::isWaitingCall (const CallID& id) +{ + CallIDSet::iterator iter = _waitingCall.find (id); - if (iter != _waitingCall.end()) { - return false; - } + if (iter != _waitingCall.end()) { + return false; + } - return true; + return true; } /////////////////////////////////////////////////////////////////////////////// // Management of event peer IP-phone //////////////////////////////////////////////////////////////////////////////// // SipEvent Thread -bool ManagerImpl::incomingCall (Call* call, const AccountID& accountId) { +bool ManagerImpl::incomingCall (Call* call, const AccountID& accountId) +{ - std::string from, number, display_name, display; + std::string from, number, display_name, display; - if(!call) - _error("Manager: Error: no call at this point"); + if (!call) + _error ("Manager: Error: no call at this point"); - stopTone(); + stopTone(); - _debug ("Manager: Incoming call %s for account %s", call->getCallId().data(), accountId.c_str()); + _debug ("Manager: Incoming call %s for account %s", call->getCallId().data(), accountId.c_str()); - associateCallToAccount(call->getCallId(), accountId); + associateCallToAccount (call->getCallId(), accountId); - // If account is null it is an ip to ip call - if (accountId == AccountNULL) { - associateConfigToCall(call->getCallId(), Call::IPtoIP); - } - else { - // strip sip: which is not required and bring confusion with ip to ip calls - // when placing new call from history (if call is IAX, do nothing) - std::string peerNumber = call->getPeerNumber(); + // If account is null it is an ip to ip call + if (accountId == AccountNULL) { + associateConfigToCall (call->getCallId(), Call::IPtoIP); + } else { + // strip sip: which is not required and bring confusion with ip to ip calls + // when placing new call from history (if call is IAX, do nothing) + std::string peerNumber = call->getPeerNumber(); - int startIndex = peerNumber.find("sip:"); + int startIndex = peerNumber.find ("sip:"); - if (startIndex != (int) string::npos) { - std::string strippedPeerNumber = peerNumber.substr(startIndex + 4); - call->setPeerNumber(strippedPeerNumber); - } + if (startIndex != (int) string::npos) { + std::string strippedPeerNumber = peerNumber.substr (startIndex + 4); + call->setPeerNumber (strippedPeerNumber); + } - } + } - if (!hasCurrentCall()) { - _debug ("Manager: Has no current call"); + if (!hasCurrentCall()) { + _debug ("Manager: Has no current call"); - call->setConnectionState(Call::Ringing); - ringtone(accountId); + call->setConnectionState (Call::Ringing); + ringtone (accountId); - } - else { - _debug ("Manager: has current call"); - } + } else { + _debug ("Manager: has current call"); + } - addWaitingCall(call->getCallId()); + addWaitingCall (call->getCallId()); - from = call->getPeerName(); - number = call->getPeerNumber(); - display_name = call->getDisplayName(); + from = call->getPeerName(); + number = call->getPeerNumber(); + display_name = call->getDisplayName(); - if (from != "" && number != "") { - from.append(" <"); - from.append(number); - from.append(">"); - } else if (from.empty()) { - from.append("<"); - from.append(number); - from.append(">"); - } + if (from != "" && number != "") { + from.append (" <"); + from.append (number); + from.append (">"); + } else if (from.empty()) { + from.append ("<"); + from.append (number); + from.append (">"); + } - /* Broadcast a signal over DBus */ - _debug ("Manager: From: %s, Number: %s, Display Name: %s", from.c_str(), number.c_str(), display_name.c_str()); + /* Broadcast a signal over DBus */ + _debug ("Manager: From: %s, Number: %s, Display Name: %s", from.c_str(), number.c_str(), display_name.c_str()); - display = display_name; - display.append(" "); - display.append(from); + display = display_name; + display.append (" "); + display.append (from); - if (_dbus) - _dbus->getCallManager()->incomingCall(accountId, call->getCallId(), display.c_str()); + if (_dbus) + _dbus->getCallManager()->incomingCall (accountId, call->getCallId(), display.c_str()); - return true; + return true; } //THREAD=VoIP void ManagerImpl::incomingMessage (const AccountID& accountId, - const std::string& message) { - if (_dbus) { - _dbus->getCallManager()->incomingMessage(accountId, message); - } + const std::string& message) +{ + if (_dbus) { + _dbus->getCallManager()->incomingMessage (accountId, message); + } } //THREAD=VoIP CALL=Outgoing -void ManagerImpl::peerAnsweredCall (const CallID& id) { +void ManagerImpl::peerAnsweredCall (const CallID& id) +{ - _debug ("Manager: Peer answered call %s", id.c_str()); + _debug ("Manager: Peer answered call %s", id.c_str()); - // The if statement is usefull only if we sent two calls at the same time. - if (isCurrentCall(id)) { - stopTone(); - } + // The if statement is usefull only if we sent two calls at the same time. + if (isCurrentCall (id)) { + stopTone(); + } - if (_dbus) - _dbus->getCallManager()->callStateChanged(id, "CURRENT"); + if (_dbus) + _dbus->getCallManager()->callStateChanged (id, "CURRENT"); - _audiodriver->flushMain(); + _audiodriver->flushMain(); - _audiodriver->flushUrgent(); + _audiodriver->flushUrgent(); } //THREAD=VoIP Call=Outgoing -void ManagerImpl::peerRingingCall (const CallID& id) { +void ManagerImpl::peerRingingCall (const CallID& id) +{ - _debug ("Manager: Peer call %s ringing", id.c_str()); + _debug ("Manager: Peer call %s ringing", id.c_str()); - if (isCurrentCall(id)) { - ringback(); - } + if (isCurrentCall (id)) { + ringback(); + } - if (_dbus) - _dbus->getCallManager()->callStateChanged(id, "RINGING"); + if (_dbus) + _dbus->getCallManager()->callStateChanged (id, "RINGING"); } //THREAD=VoIP Call=Outgoing/Ingoing -void ManagerImpl::peerHungupCall (const CallID& call_id) { - PulseLayer *pulselayer; - AccountID account_id; - bool returnValue; +void ManagerImpl::peerHungupCall (const CallID& call_id) +{ + PulseLayer *pulselayer; + AccountID account_id; + bool returnValue; - _debug ("Manager: Peer hungup call %s", call_id.c_str()); + _debug ("Manager: Peer hungup call %s", call_id.c_str()); - // store the current call id - CallID current_call_id = getCurrentCallId(); + // store the current call id + CallID current_call_id = getCurrentCallId(); - if (participToConference(call_id)) { + if (participToConference (call_id)) { - Conference *conf = getConferenceFromCallID(call_id); + Conference *conf = getConferenceFromCallID (call_id); - if (conf != NULL) { + if (conf != NULL) { - removeParticipant(call_id); - processRemainingParticipant(current_call_id, conf); + removeParticipant (call_id); + processRemainingParticipant (current_call_id, conf); - } - } else { - if (isCurrentCall(call_id)) { - stopTone(); + } + } else { + if (isCurrentCall (call_id)) { + stopTone(); - switchCall(""); - } - } + switchCall (""); + } + } - /* Direct IP to IP call */ - if (getConfigFromCall(call_id) == Call::IPtoIP) { - SIPVoIPLink::instance(AccountNULL)->hangup(call_id); - } + /* Direct IP to IP call */ + if (getConfigFromCall (call_id) == Call::IPtoIP) { + SIPVoIPLink::instance (AccountNULL)->hangup (call_id); + } - else { + else { - account_id = getAccountFromCall(call_id); + account_id = getAccountFromCall (call_id); - returnValue = getAccountLink(account_id)->peerHungup(call_id); - } + returnValue = getAccountLink (account_id)->peerHungup (call_id); + } - /* Broadcast a signal over DBus */ - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "HUNGUP"); + /* Broadcast a signal over DBus */ + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "HUNGUP"); - removeWaitingCall(call_id); + removeWaitingCall (call_id); - removeCallAccount(call_id); + removeCallAccount (call_id); - int nbCalls = getCallList().size(); + int nbCalls = getCallList().size(); - // stop streams + // stop streams - if (nbCalls <= 0) { - _debug ("Manager: Stop audio stream, ther is only %i call(s) remaining", nbCalls); + if (nbCalls <= 0) { + _debug ("Manager: Stop audio stream, ther is only %i call(s) remaining", nbCalls); - AudioLayer* audiolayer = getAudioDriver(); - audiolayer->stopStream(); - } + AudioLayer* audiolayer = getAudioDriver(); + audiolayer->stopStream(); + } - if (_audiodriver->getLayerType() == PULSEAUDIO) { - pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); - } + if (_audiodriver->getLayerType() == PULSEAUDIO) { + pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); + } } //THREAD=VoIP -void ManagerImpl::callBusy (const CallID& id) { - _debug ("Manager: Call %s busy", id.c_str()); +void ManagerImpl::callBusy (const CallID& id) +{ + _debug ("Manager: Call %s busy", id.c_str()); - if (_dbus) - _dbus->getCallManager()->callStateChanged(id, "BUSY"); + if (_dbus) + _dbus->getCallManager()->callStateChanged (id, "BUSY"); - if (isCurrentCall(id)) { - playATone(Tone::TONE_BUSY); - switchCall(""); - } + if (isCurrentCall (id)) { + playATone (Tone::TONE_BUSY); + switchCall (""); + } - removeCallAccount(id); + removeCallAccount (id); - removeWaitingCall(id); + removeWaitingCall (id); } //THREAD=VoIP -void ManagerImpl::callFailure (const CallID& call_id) { - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "FAILURE"); - - if (isCurrentCall(call_id)) { - playATone(Tone::TONE_BUSY); - switchCall(""); - } +void ManagerImpl::callFailure (const CallID& call_id) +{ + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "FAILURE"); + + if (isCurrentCall (call_id)) { + playATone (Tone::TONE_BUSY); + switchCall (""); + } - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - if (participToConference(call_id)) { + if (participToConference (call_id)) { - _debug ("Manager: Call %s participating to a conference failed", call_id.c_str()); + _debug ("Manager: Call %s participating to a conference failed", call_id.c_str()); - Conference *conf = getConferenceFromCallID(call_id); + Conference *conf = getConferenceFromCallID (call_id); - if (conf != NULL) { - // remove this participant - removeParticipant(call_id); + if (conf != NULL) { + // remove this participant + removeParticipant (call_id); - processRemainingParticipant(current_call_id, conf); - } + processRemainingParticipant (current_call_id, conf); + } - } + } - removeCallAccount(call_id); + removeCallAccount (call_id); - removeWaitingCall(call_id); + removeWaitingCall (call_id); } //THREAD=VoIP void ManagerImpl::startVoiceMessageNotification (const AccountID& accountId, - int nb_msg) { - if (_dbus) - _dbus->getCallManager()->voiceMailNotify(accountId, nb_msg); + int nb_msg) +{ + if (_dbus) + _dbus->getCallManager()->voiceMailNotify (accountId, nb_msg); } -void ManagerImpl::connectionStatusNotification () { - - _debug("Manager: connectionStatusNotification"); +void ManagerImpl::connectionStatusNotification () +{ + + _debug ("Manager: connectionStatusNotification"); - if (_dbus != NULL) { - _dbus->getConfigurationManager()->accountsChanged(); - } + if (_dbus != NULL) { + _dbus->getConfigurationManager()->accountsChanged(); + } } /** * Multi Thread */ -bool ManagerImpl::playATone (Tone::TONEID toneId) { +bool ManagerImpl::playATone (Tone::TONEID toneId) +{ - bool hasToPlayTone; - AudioLayer *audiolayer; + bool hasToPlayTone; + AudioLayer *audiolayer; - // _debug ("Manager: Play tone %d", toneId); + // _debug ("Manager: Play tone %d", toneId); - hasToPlayTone = voipPreferences.getPlayTones(); + hasToPlayTone = voipPreferences.getPlayTones(); - if (!hasToPlayTone) - return false; + if (!hasToPlayTone) + return false; - audiolayer = getAudioDriver(); + audiolayer = getAudioDriver(); - if (audiolayer) { + if (audiolayer) { - audiolayer->flushUrgent(); - audiolayer->startStream(); - } + audiolayer->flushUrgent(); + audiolayer->startStream(); + } - if (_telephoneTone != 0) { - _toneMutex.enterMutex(); - _telephoneTone->setCurrentTone(toneId); - _toneMutex.leaveMutex(); - } + if (_telephoneTone != 0) { + _toneMutex.enterMutex(); + _telephoneTone->setCurrentTone (toneId); + _toneMutex.leaveMutex(); + } - return true; + return true; } /** * Multi Thread */ -void ManagerImpl::stopTone () { - bool hasToPlayTone; +void ManagerImpl::stopTone () +{ + bool hasToPlayTone; - hasToPlayTone = voipPreferences.getPlayTones(); + hasToPlayTone = voipPreferences.getPlayTones(); - if (!hasToPlayTone) - return; + if (!hasToPlayTone) + return; - _toneMutex.enterMutex(); + _toneMutex.enterMutex(); - if (_telephoneTone != 0) { - _telephoneTone->setCurrentTone(Tone::TONE_NULL); - } + if (_telephoneTone != 0) { + _telephoneTone->setCurrentTone (Tone::TONE_NULL); + } - _audiofile.stop(); - _toneMutex.leaveMutex(); + _audiofile.stop(); + _toneMutex.leaveMutex(); } /** * Multi Thread */ -bool ManagerImpl::playTone () { - playATone(Tone::TONE_DIALTONE); - return true; +bool ManagerImpl::playTone () +{ + playATone (Tone::TONE_DIALTONE); + return true; } /** * Multi Thread */ -bool ManagerImpl::playToneWithMessage () { - playATone(Tone::TONE_CONGESTION); - return true; +bool ManagerImpl::playToneWithMessage () +{ + playATone (Tone::TONE_CONGESTION); + return true; } /** * Multi Thread */ -void ManagerImpl::congestion () { - playATone(Tone::TONE_CONGESTION); +void ManagerImpl::congestion () +{ + playATone (Tone::TONE_CONGESTION); } /** * Multi Thread */ -void ManagerImpl::ringback () { - playATone(Tone::TONE_RINGTONE); +void ManagerImpl::ringback () +{ + playATone (Tone::TONE_RINGTONE); } /** * Multi Thread */ -void ManagerImpl::ringtone (const AccountID& accountID) { - std::string ringchoice; - AudioLayer *audiolayer; - AudioCodec *codecForTone; - int layer, samplerate; - bool loadFile; +void ManagerImpl::ringtone (const AccountID& accountID) +{ + std::string ringchoice; + AudioLayer *audiolayer; + AudioCodec *codecForTone; + int layer, samplerate; + bool loadFile; - _debug("Manager: Ringtone"); + _debug ("Manager: Ringtone"); - Account *account = getAccount(accountID); + Account *account = getAccount (accountID); - if(!account) { - _warn("Manager: Warning: invalid account in ringtone"); - return; - } + if (!account) { + _warn ("Manager: Warning: invalid account in ringtone"); + return; + } - if (account->getRingtoneEnabled()) { + if (account->getRingtoneEnabled()) { - _debug ("Manager: Tone is enabled"); - //TODO Comment this because it makes the daemon crashes since the main thread - //synchronizes the ringtone thread. + _debug ("Manager: Tone is enabled"); + //TODO Comment this because it makes the daemon crashes since the main thread + //synchronizes the ringtone thread. - ringchoice = account->getRingtonePath(); - //if there is no / inside the path + ringchoice = account->getRingtonePath(); + //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; - } + 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; + } - audiolayer = getAudioDriver(); + audiolayer = getAudioDriver(); - if (!audiolayer) { - _error("Manager: Error: no audio layer in ringtone"); - return; - } + if (!audiolayer) { + _error ("Manager: Error: no audio layer in ringtone"); + return; + } - layer = audiolayer->getLayerType(); + layer = audiolayer->getLayerType(); - samplerate = audiolayer->getSampleRate(); + samplerate = audiolayer->getSampleRate(); - codecForTone = _codecDescriptorMap.getFirstCodecAvailable(); + codecForTone = _codecDescriptorMap.getFirstCodecAvailable(); - _toneMutex.enterMutex(); + _toneMutex.enterMutex(); - loadFile = _audiofile.loadFile(ringchoice, codecForTone, samplerate); + loadFile = _audiofile.loadFile (ringchoice, codecForTone, samplerate); - _toneMutex.leaveMutex(); + _toneMutex.leaveMutex(); - if (loadFile) { + if (loadFile) { - _toneMutex.enterMutex(); - _audiofile.start(); - _toneMutex.leaveMutex(); + _toneMutex.enterMutex(); + _audiofile.start(); + _toneMutex.leaveMutex(); - // start audio if not started AND flush all buffers (main and urgent) - audiolayer->startStream(); + // start audio if not started AND flush all buffers (main and urgent) + audiolayer->startStream(); - } else { - ringback(); - } + } else { + ringback(); + } - } else { - ringback(); - } + } else { + ringback(); + } } AudioLoop* -ManagerImpl::getTelephoneTone () { - // _debug("ManagerImpl::getTelephoneTone()"); - if (_telephoneTone != 0) { - ost::MutexLock m(_toneMutex); - return _telephoneTone->getCurrentTone(); - } else { - return 0; - } +ManagerImpl::getTelephoneTone () +{ + // _debug("ManagerImpl::getTelephoneTone()"); + if (_telephoneTone != 0) { + ost::MutexLock m (_toneMutex); + return _telephoneTone->getCurrentTone(); + } else { + return 0; + } } AudioLoop* -ManagerImpl::getTelephoneFile () { - // _debug("ManagerImpl::getTelephoneFile()"); - ost::MutexLock m(_toneMutex); - - if (_audiofile.isStarted()) { - return &_audiofile; - } else { - return 0; - } +ManagerImpl::getTelephoneFile () +{ + // _debug("ManagerImpl::getTelephoneFile()"); + ost::MutexLock m (_toneMutex); + + if (_audiofile.isStarted()) { + return &_audiofile; + } else { + return 0; + } } -void ManagerImpl::notificationIncomingCall (void) { - AudioLayer *audiolayer; - std::ostringstream frequency; - unsigned int samplerate, nbSampling; +void ManagerImpl::notificationIncomingCall (void) +{ + AudioLayer *audiolayer; + std::ostringstream frequency; + unsigned int samplerate, nbSampling; - audiolayer = getAudioDriver(); + audiolayer = getAudioDriver(); - _debug ("ManagerImpl::notificationIncomingCall"); + _debug ("ManagerImpl::notificationIncomingCall"); - if (audiolayer != 0) { - samplerate = audiolayer->getSampleRate(); - frequency << "440/" << 160; - 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->flushUrgent(); - audiolayer->putUrgent(buf, sizeof(SFLDataFormat) * nbSampling); - } + if (audiolayer != 0) { + samplerate = audiolayer->getSampleRate(); + frequency << "440/" << 160; + 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->flushUrgent(); + audiolayer->putUrgent (buf, sizeof (SFLDataFormat) * nbSampling); + } } /////////////////////////////////////////////////////////////////////////////// @@ -2027,569 +2091,607 @@ void ManagerImpl::notificationIncomingCall (void) { * @return 1: ok -1: error directory */ -int ManagerImpl::createSettingsPath (void) { +int ManagerImpl::createSettingsPath (void) +{ - std::string xdg_config, xdg_env; + std::string xdg_config, xdg_env; - _debug ("XDG_CONFIG_HOME: %s", XDG_CONFIG_HOME); + _debug ("XDG_CONFIG_HOME: %s", XDG_CONFIG_HOME); - xdg_config = std::string(HOMEDIR) + DIR_SEPARATOR_STR + ".config" - + DIR_SEPARATOR_STR + PROGDIR; + xdg_config = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".config" + + DIR_SEPARATOR_STR + PROGDIR; - if (XDG_CONFIG_HOME != NULL) { - xdg_env = std::string(XDG_CONFIG_HOME); - (xdg_env.length() > 0) ? _path = xdg_env : _path = xdg_config; - } else - _path = xdg_config; + if (XDG_CONFIG_HOME != NULL) { + xdg_env = std::string (XDG_CONFIG_HOME); + (xdg_env.length() > 0) ? _path = xdg_env : _path = xdg_config; + } else + _path = xdg_config; - if (mkdir(_path.data(), 0700) != 0) { - // If directory creation failed - if (errno != EEXIST) { - _debug ("Cannot create directory: %s", strerror (errno)); - return -1; - } - } + if (mkdir (_path.data(), 0700) != 0) { + // If directory creation failed + if (errno != EEXIST) { + _debug ("Cannot create directory: %s", strerror (errno)); + return -1; + } + } - // Load user's configuration - _path = _path + DIR_SEPARATOR_STR + PROGNAME + ".yml"; + // Load user's configuration + _path = _path + DIR_SEPARATOR_STR + PROGNAME + ".yml"; - return 1; + return 1; } /** * Initialization: Main Thread */ -void ManagerImpl::initConfigFile (bool load_user_value, std::string alternate) { +void ManagerImpl::initConfigFile (bool load_user_value, std::string alternate) +{ + + _debug ("Manager: Init config file"); + + // Init display name to the username under which + // this sflphone instance is running. + uid_t uid = getuid(); + + struct passwd * user_info = NULL; + user_info = getpwuid (uid); - _debug ("Manager: Init config file"); + std::string path; + // Loads config from ~/.sflphone/sflphoned.yml or so.. - // Init display name to the username under which - // this sflphone instance is running. - uid_t uid = getuid(); + if (createSettingsPath() == 1 && load_user_value) { - struct passwd * user_info = NULL; - user_info = getpwuid(uid); + (alternate == "") ? path = _path : path = alternate; + std::cout << path << std::endl; + _exist = _config.populateFromFile (path); + } - std::string path; - // Loads config from ~/.sflphone/sflphoned.yml or so.. + _debug ("Manager: configuration file path: %s", path.c_str()); - if (createSettingsPath() == 1 && load_user_value) { - (alternate == "") ? path = _path : path = alternate; - std::cout << path << std::endl; - _exist = _config.populateFromFile(path); - } - _debug("Manager: configuration file path: %s", path.c_str()); - + bool fileExist = true; + bool out = false; - bool fileExist = true; - bool out = false; - - if (path.empty()) { - _error("Manager: Error: XDG config file path is empty!"); - fileExist = false; - } + if (path.empty()) { + _error ("Manager: Error: XDG config file path is empty!"); + fileExist = false; + } - std::fstream file; + std::fstream file; - file.open (path.data(), std::fstream::in); + file.open (path.data(), std::fstream::in); - if (!file.is_open()) { + if (!file.is_open()) { - _debug("Manager: File %s not opened, create new one", path.c_str()); - file.open (path.data(), std::fstream::out); - out = true; + _debug ("Manager: File %s not opened, create new one", path.c_str()); + file.open (path.data(), std::fstream::out); + out = true; - if (!file.is_open()) { - _error("Manager: Error: could not create empty configurationfile!"); + if (!file.is_open()) { + _error ("Manager: Error: could not create empty configurationfile!"); fileExist = false; - } - - file.close(); - - fileExist = false; - } - - // get length of file: - file.seekg (0, std::ios::end); - int length = file.tellg(); - - file.seekg (0, std::ios::beg); - - if (length <= 0) { - _debug("Manager: Configuration file length is empty", length); - file.close(); - fileExist = false; // should load config - } - - if(fileExist) { - try { - - // parser = new Conf::YamlParser("sequenceParser.yml"); - parser = new Conf::YamlParser(_path.c_str()); - - parser->serializeEvents(); - - parser->composeEvents(); - - parser->constructNativeData(); - - _setupLoaded = true; - - _debug("Manager: Configuration file parsed successfully"); - } - catch (Conf::YamlParserException &e) { - _error("Manager: %s", e.what()); - } - } + } + + file.close(); + + fileExist = false; + } + + // get length of file: + file.seekg (0, std::ios::end); + int length = file.tellg(); + + file.seekg (0, std::ios::beg); + + if (length <= 0) { + _debug ("Manager: Configuration file length is empty", length); + file.close(); + fileExist = false; // should load config + } + + if (fileExist) { + try { + + // parser = new Conf::YamlParser("sequenceParser.yml"); + parser = new Conf::YamlParser (_path.c_str()); + + parser->serializeEvents(); + + parser->composeEvents(); + + parser->constructNativeData(); + + _setupLoaded = true; + + _debug ("Manager: Configuration file parsed successfully"); + } catch (Conf::YamlParserException &e) { + _error ("Manager: %s", e.what()); + } + } } /** * Initialization: Main Thread */ -void ManagerImpl::initAudioCodec (void) { - _info("Manager: Init audio codecs"); +void ManagerImpl::initAudioCodec (void) +{ + _info ("Manager: Init audio codecs"); - /* Init list of all supported codecs by the application. - * This is a global list. Every account will inherit it. - */ - _codecDescriptorMap.init(); + /* Init list of all supported codecs by the application. + * This is a global list. Every account will inherit it. + */ + _codecDescriptorMap.init(); } /* * TODO Retrieve the active codec list per account */ -std::vector<std::string> ManagerImpl::retrieveActiveCodecs () { +std::vector<std::string> ManagerImpl::retrieveActiveCodecs () +{ - // This property is now set per account basis so we should remove it... - std::string s = ""; - _info("Manager: Retrieve active codecs: %s", s.c_str ()); - return unserialize(s); + // This property is now set per account basis so we should remove it... + std::string s = ""; + _info ("Manager: Retrieve active codecs: %s", s.c_str ()); + return unserialize (s); } -std::vector<std::string> ManagerImpl::unserialize (std::string s) { +std::vector<std::string> ManagerImpl::unserialize (std::string s) +{ - std::vector<std::string> list; - std::string temp; + std::vector<std::string> list; + std::string temp; - while (s.find("/", 0) != std::string::npos) { - size_t pos = s.find("/", 0); - temp = s.substr(0, pos); - s.erase(0, pos + 1); - list.push_back(temp); - } + while (s.find ("/", 0) != std::string::npos) { + size_t pos = s.find ("/", 0); + temp = s.substr (0, pos); + s.erase (0, pos + 1); + list.push_back (temp); + } - return list; + return list; } -std::string ManagerImpl::serialize (std::vector<std::string> v) { +std::string ManagerImpl::serialize (std::vector<std::string> v) +{ - unsigned int i; - std::string res; + unsigned int i; + std::string res; - for (i = 0; i < v.size(); i++) { - res += v[i] + "/"; - } + for (i = 0; i < v.size(); i++) { + res += v[i] + "/"; + } - return res; + return res; } -std::string ManagerImpl::getCurrentCodecName (const CallID& id) { +std::string ManagerImpl::getCurrentCodecName (const CallID& id) +{ - AccountID accountid = getAccountFromCall(id); - VoIPLink* link = getAccountLink(accountid); - Call* call = link->getCall(id); + AccountID accountid = getAccountFromCall (id); + VoIPLink* link = getAccountLink (accountid); + Call* call = link->getCall (id); - if (!call) - return ""; + if (!call) + return ""; - if (call->getState() != Call::Active) - return ""; - else - return link->getCurrentCodecName(); + if (call->getState() != Call::Active) + return ""; + else + return link->getCurrentCodecName(); } /** * Set input audio plugin */ -void ManagerImpl::setInputAudioPlugin (const std::string& audioPlugin) { - int layer = _audiodriver -> getLayerType(); - - if (CHECK_INTERFACE (layer , ALSA)) { - _debug ("Set input audio plugin"); - _audiodriver -> setErrorMessage(-1); - _audiodriver -> openDevice(_audiodriver->getIndexIn(), _audiodriver->getIndexOut(), - _audiodriver->getIndexRing(), _audiodriver -> getSampleRate(), - _audiodriver -> getFrameSize(), SFL_PCM_CAPTURE, audioPlugin); - - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); - } else { - } +void ManagerImpl::setInputAudioPlugin (const std::string& audioPlugin) +{ + int layer = _audiodriver -> getLayerType(); + + if (CHECK_INTERFACE (layer , ALSA)) { + _debug ("Set input audio plugin"); + _audiodriver -> setErrorMessage (-1); + _audiodriver -> openDevice (_audiodriver->getIndexIn(), _audiodriver->getIndexOut(), + _audiodriver->getIndexRing(), _audiodriver -> getSampleRate(), + _audiodriver -> getFrameSize(), SFL_PCM_CAPTURE, audioPlugin); + + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); + } else { + } } /** * Set output audio plugin */ -void ManagerImpl::setOutputAudioPlugin (const std::string& audioPlugin) { +void ManagerImpl::setOutputAudioPlugin (const std::string& audioPlugin) +{ - int res; + int res; - _debug ("Manager: Set output audio plugin"); - _audiodriver -> setErrorMessage(-1); - res = _audiodriver -> openDevice(_audiodriver->getIndexIn(), _audiodriver->getIndexOut(), - _audiodriver->getIndexRing(), _audiodriver -> getSampleRate(), - _audiodriver -> getFrameSize(), SFL_PCM_BOTH, audioPlugin); + _debug ("Manager: Set output audio plugin"); + _audiodriver -> setErrorMessage (-1); + res = _audiodriver -> openDevice (_audiodriver->getIndexIn(), _audiodriver->getIndexOut(), + _audiodriver->getIndexRing(), _audiodriver -> getSampleRate(), + _audiodriver -> getFrameSize(), SFL_PCM_BOTH, audioPlugin); + + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + // set config + if (res) + audioPreference.setPlugin (audioPlugin); - // set config - if (res) - audioPreference.setPlugin(audioPlugin); - //setConig(AUDIO, ALSA_PLUGIN, audioPlugin); + //setConig(AUDIO, ALSA_PLUGIN, audioPlugin); } /** * Get list of supported audio output device */ -std::vector<std::string> ManagerImpl::getAudioOutputDeviceList (void) { - _debug ("Manager: Get audio output device list"); - AlsaLayer *layer; - std::vector<std::string> devices; +std::vector<std::string> ManagerImpl::getAudioOutputDeviceList (void) +{ + _debug ("Manager: Get audio output device list"); + AlsaLayer *layer; + std::vector<std::string> devices; - layer = dynamic_cast<AlsaLayer*> (getAudioDriver()); + layer = dynamic_cast<AlsaLayer*> (getAudioDriver()); - if (layer) - devices = layer -> getSoundCardsInfo(SFL_PCM_PLAYBACK); + if (layer) + devices = layer -> getSoundCardsInfo (SFL_PCM_PLAYBACK); - return devices; + return devices; } /** * Set audio output device */ -void ManagerImpl::setAudioDevice (const int index, int streamType) { - +void ManagerImpl::setAudioDevice (const int index, int streamType) +{ + AlsaLayer *alsalayer = NULL; std::string alsaplugin; _debug ("Manager: Set audio device: %i", index); - _audiodriver -> setErrorMessage(-1); + _audiodriver -> setErrorMessage (-1); - if(!(alsalayer = dynamic_cast<AlsaLayer*> (getAudioDriver()))) { - _warn("Manager: Error: No audio driver"); - return; + if (! (alsalayer = dynamic_cast<AlsaLayer*> (getAudioDriver()))) { + _warn ("Manager: Error: No audio driver"); + return; } - + alsaplugin = alsalayer->getAudioPlugin(); _debug ("Manager: Set ALSA plugin: %s", alsaplugin.c_str()); - switch(streamType) { - case SFL_PCM_PLAYBACK: - _debug("Manager: Set output device"); - _audiodriver->openDevice(_audiodriver->getIndexIn(), index, _audiodriver->getIndexRing(), - _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), - SFL_PCM_PLAYBACK, alsaplugin); - audioPreference.setCardout(index); - break; - case SFL_PCM_CAPTURE: - _debug("Manager: Set input device"); - _audiodriver->openDevice(index, _audiodriver->getIndexOut(), _audiodriver->getIndexRing(), - _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), - SFL_PCM_CAPTURE, alsaplugin); - audioPreference.setCardin(index); - break; - case SFL_PCM_RINGTONE: - _debug("Manager: Set ringtone device"); - _audiodriver->openDevice(_audiodriver->getIndexOut(), _audiodriver->getIndexOut(), index, - _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), - SFL_PCM_RINGTONE, alsaplugin); - audioPreference.setCardring(index); - break; - default: - _warn("Unknown stream type"); + switch (streamType) { + case SFL_PCM_PLAYBACK: + _debug ("Manager: Set output device"); + _audiodriver->openDevice (_audiodriver->getIndexIn(), index, _audiodriver->getIndexRing(), + _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), + SFL_PCM_PLAYBACK, alsaplugin); + audioPreference.setCardout (index); + break; + case SFL_PCM_CAPTURE: + _debug ("Manager: Set input device"); + _audiodriver->openDevice (index, _audiodriver->getIndexOut(), _audiodriver->getIndexRing(), + _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), + SFL_PCM_CAPTURE, alsaplugin); + audioPreference.setCardin (index); + break; + case SFL_PCM_RINGTONE: + _debug ("Manager: Set ringtone device"); + _audiodriver->openDevice (_audiodriver->getIndexOut(), _audiodriver->getIndexOut(), index, + _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), + SFL_PCM_RINGTONE, alsaplugin); + audioPreference.setCardring (index); + break; + default: + _warn ("Unknown stream type"); } if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + notifyErrClient (_audiodriver -> getErrorMessage()); } /** * Get list of supported audio input device */ -std::vector<std::string> ManagerImpl::getAudioInputDeviceList (void) { - AlsaLayer *audiolayer; - std::vector<std::string> devices; +std::vector<std::string> ManagerImpl::getAudioInputDeviceList (void) +{ + AlsaLayer *audiolayer; + std::vector<std::string> devices; - audiolayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); + audiolayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); - if (audiolayer) - devices = audiolayer->getSoundCardsInfo(SFL_PCM_CAPTURE); + if (audiolayer) + devices = audiolayer->getSoundCardsInfo (SFL_PCM_CAPTURE); - return devices; + return devices; } /** * Get string array representing integer indexes of output and input device */ -std::vector<std::string> ManagerImpl::getCurrentAudioDevicesIndex () { - _debug ("Get current audio devices index"); - std::vector<std::string> v; - std::stringstream ssi, sso, ssr; - sso << _audiodriver->getIndexOut(); - v.push_back(sso.str()); - ssi << _audiodriver->getIndexIn(); - v.push_back(ssi.str()); - ssr << _audiodriver->getIndexRing(); - v.push_back(ssr.str()); - return v; -} - -int ManagerImpl::isIax2Enabled (void) { +std::vector<std::string> ManagerImpl::getCurrentAudioDevicesIndex () +{ + _debug ("Get current audio devices index"); + std::vector<std::string> v; + std::stringstream ssi, sso, ssr; + sso << _audiodriver->getIndexOut(); + v.push_back (sso.str()); + ssi << _audiodriver->getIndexIn(); + v.push_back (ssi.str()); + ssr << _audiodriver->getIndexRing(); + v.push_back (ssr.str()); + return v; +} + +int ManagerImpl::isIax2Enabled (void) +{ #ifdef USE_IAX - return true; + return true; #else - return false; + return false; #endif } -int ManagerImpl::isRingtoneEnabled (const AccountID& id) { - Account *account = getAccount(id); +int ManagerImpl::isRingtoneEnabled (const AccountID& id) +{ + Account *account = getAccount (id); - if(!account) { - _warn("Manager: Warning: invalid account in ringtone enabled"); - return 0; - } + if (!account) { + _warn ("Manager: Warning: invalid account in ringtone enabled"); + return 0; + } - return account->getRingtoneEnabled() ? 1 : 0; + return account->getRingtoneEnabled() ? 1 : 0; } -void ManagerImpl::ringtoneEnabled (const AccountID& id) { +void ManagerImpl::ringtoneEnabled (const AccountID& id) +{ - Account *account = getAccount(id); + Account *account = getAccount (id); - if(!account) { - _warn("Manager: Warning: invalid account in ringtone enabled"); - return; - } + if (!account) { + _warn ("Manager: Warning: invalid account in ringtone enabled"); + return; + } + + account->getRingtoneEnabled() ? account->setRingtoneEnabled (false) : account->setRingtoneEnabled (true); - account->getRingtoneEnabled() ? account->setRingtoneEnabled(false) : account->setRingtoneEnabled(true); - } -std::string ManagerImpl::getRingtoneChoice (const AccountID& id) { - - // retreive specified account id - Account *account = getAccount(id); +std::string ManagerImpl::getRingtoneChoice (const AccountID& id) +{ - if(!account) { - _warn("Manager: Warning: Not a valid account ID for ringone choice"); - return std::string(""); - } + // retreive specified account id + Account *account = getAccount (id); - // we need the absolute path - std::string tone_name = account->getRingtonePath(); - std::string tone_path; + if (!account) { + _warn ("Manager: Warning: Not a valid account ID for ringone choice"); + return std::string (""); + } - if (tone_name.find(DIR_SEPARATOR_CH) == std::string::npos) { - // check in ringtone directory ($(PREFIX)/share/sflphone/ringtones) - tone_path = std::string(PROGSHAREDIR) + DIR_SEPARATOR_STR + RINGDIR - + DIR_SEPARATOR_STR + tone_name; - } else { - // the absolute has been saved; do nothing - tone_path = tone_name; - } + // we need the absolute path + std::string tone_name = account->getRingtonePath(); + std::string tone_path; + + if (tone_name.find (DIR_SEPARATOR_CH) == std::string::npos) { + // check in ringtone directory ($(PREFIX)/share/sflphone/ringtones) + tone_path = std::string (PROGSHAREDIR) + DIR_SEPARATOR_STR + RINGDIR + + DIR_SEPARATOR_STR + tone_name; + } else { + // the absolute has been saved; do nothing + tone_path = tone_name; + } - _debug ("Manager: get ringtone path %s", tone_path.c_str()); + _debug ("Manager: get ringtone path %s", tone_path.c_str()); - return tone_path; + return tone_path; } -void ManagerImpl::setRingtoneChoice (const std::string& tone, const AccountID& id) { +void ManagerImpl::setRingtoneChoice (const std::string& tone, const AccountID& id) +{ - _debug("Manager: Set ringtone path %s to account", tone.c_str()); + _debug ("Manager: Set ringtone path %s to account", tone.c_str()); - // retreive specified account id - Account *account = getAccount(id); + // retreive specified account id + Account *account = getAccount (id); - if(!account) { - _warn("Manager: Warning: Not a valid account ID for ringtone choice"); - return; - } + if (!account) { + _warn ("Manager: Warning: Not a valid account ID for ringtone choice"); + return; + } - // we save the absolute path - account->setRingtonePath(tone); + // we save the absolute path + account->setRingtonePath (tone); } -std::string ManagerImpl::getRecordPath (void) { - return audioPreference.getRecordpath(); +std::string ManagerImpl::getRecordPath (void) +{ + return audioPreference.getRecordpath(); } -void ManagerImpl::setRecordPath (const std::string& recPath) { - _debug ("Manager: Set record path %s", recPath.c_str()); - audioPreference.setRecordpath(recPath); +void ManagerImpl::setRecordPath (const std::string& recPath) +{ + _debug ("Manager: Set record path %s", recPath.c_str()); + audioPreference.setRecordpath (recPath); } -bool ManagerImpl::getMd5CredentialHashing (void) { - return preferences.getMd5Hash(); +bool ManagerImpl::getMd5CredentialHashing (void) +{ + return preferences.getMd5Hash(); } -void ManagerImpl::setRecordingCall (const CallID& id) { +void ManagerImpl::setRecordingCall (const CallID& id) +{ - Recordable* rec; - if(!isConference(id)) { - AccountID accountid = getAccountFromCall(id); - rec = (Recordable *) getAccountLink(accountid)->getCall(id); - } - else { - ConferenceMap::iterator it = _conferencemap.find(id); - rec = (Recordable *)it->second; - } + Recordable* rec; + + if (!isConference (id)) { + AccountID accountid = getAccountFromCall (id); + rec = (Recordable *) getAccountLink (accountid)->getCall (id); + } else { + ConferenceMap::iterator it = _conferencemap.find (id); + rec = (Recordable *) it->second; + } - rec->setRecording(); + rec->setRecording(); } -bool ManagerImpl::isRecording (const CallID& id) { +bool ManagerImpl::isRecording (const CallID& id) +{ - AccountID accountid = getAccountFromCall(id); - Recordable* rec = (Recordable*) getAccountLink(accountid)->getCall(id); + AccountID accountid = getAccountFromCall (id); + Recordable* rec = (Recordable*) getAccountLink (accountid)->getCall (id); - return rec->isRecording(); + return rec->isRecording(); } -void ManagerImpl::setHistoryLimit (const int& days) { - preferences.setHistoryLimit(days); +void ManagerImpl::setHistoryLimit (const int& days) +{ + preferences.setHistoryLimit (days); } -int ManagerImpl::getHistoryLimit (void) { - return preferences.getHistoryLimit(); +int ManagerImpl::getHistoryLimit (void) +{ + return preferences.getHistoryLimit(); } -int32_t ManagerImpl::getMailNotify (void) { - return preferences.getNotifyMails(); +int32_t ManagerImpl::getMailNotify (void) +{ + return preferences.getNotifyMails(); } -void ManagerImpl::setMailNotify (void) { - preferences.getNotifyMails() ? preferences.setNotifyMails(true) : preferences.setNotifyMails(false); +void ManagerImpl::setMailNotify (void) +{ + preferences.getNotifyMails() ? preferences.setNotifyMails (true) : preferences.setNotifyMails (false); } -void ManagerImpl::setAudioManager (const int32_t& api) { +void ManagerImpl::setAudioManager (const int32_t& api) +{ - int type; - std::string alsaPlugin; + int type; + std::string alsaPlugin; - _debug ("Setting audio manager "); + _debug ("Setting audio manager "); - if (!_audiodriver) - return; + if (!_audiodriver) + return; - type = _audiodriver->getLayerType(); + type = _audiodriver->getLayerType(); - if (type == api) { - _debug ("Audio manager chosen already in use. No changes made. "); - return; - } + if (type == api) { + _debug ("Audio manager chosen already in use. No changes made. "); + return; + } - preferences.setAudioApi(api); + preferences.setAudioApi (api); - switchAudioManager(); - return; + switchAudioManager(); + return; } -int32_t ManagerImpl::getAudioManager (void) { - return preferences.getAudioApi(); +int32_t ManagerImpl::getAudioManager (void) +{ + return preferences.getAudioApi(); } -void ManagerImpl::notifyErrClient (const int32_t& errCode) { - if (_dbus) { - _debug ("NOTIFY ERR NUMBER %i" , errCode); - _dbus -> getConfigurationManager() -> errorAlert(errCode); - } +void ManagerImpl::notifyErrClient (const int32_t& errCode) +{ + if (_dbus) { + _debug ("NOTIFY ERR NUMBER %i" , errCode); + _dbus -> getConfigurationManager() -> errorAlert (errCode); + } } -int ManagerImpl::getAudioDeviceIndex (const std::string name) { - AlsaLayer *alsalayer; +int ManagerImpl::getAudioDeviceIndex (const std::string name) +{ + AlsaLayer *alsalayer; - _debug ("Get audio device index"); + _debug ("Get audio device index"); - alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); + alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); - if (alsalayer) - return alsalayer -> soundCardGetIndex(name); - else - return 0; + if (alsalayer) + return alsalayer -> soundCardGetIndex (name); + else + return 0; } -std::string ManagerImpl::getCurrentAudioOutputPlugin (void) { - AlsaLayer *alsalayer; +std::string ManagerImpl::getCurrentAudioOutputPlugin (void) +{ + AlsaLayer *alsalayer; - _debug ("Get alsa plugin"); + _debug ("Get alsa plugin"); - alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); + alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); - if (alsalayer) - return alsalayer -> getAudioPlugin(); - else - return audioPreference.getPlugin(); + if (alsalayer) + return alsalayer -> getAudioPlugin(); + else + return audioPreference.getPlugin(); } -std::string ManagerImpl::getEchoCancelState(void) { +std::string ManagerImpl::getEchoCancelState (void) +{ // echo canceller is disabled by default bool isEnabled = false; - if(_audiodriver) { + if (_audiodriver) { isEnabled = _audiodriver->getEchoCancelState(); } - std::string state(""); - if(isEnabled) - state = "enabled"; + std::string state (""); + + if (isEnabled) + state = "enabled"; else - state = "disabled"; + state = "disabled"; return state; } -void ManagerImpl::setEchoCancelState(std::string state) { - _debug("Manager: Set echo suppress state: %s", state.c_str()); +void ManagerImpl::setEchoCancelState (std::string state) +{ + _debug ("Manager: Set echo suppress state: %s", state.c_str()); bool isEnabled = false; - if(state.compare("enabled") == 0) + if (state.compare ("enabled") == 0) isEnabled = true; else isEnabled = false; - if(_audiodriver) { - _audiodriver->setEchoCancelState(isEnabled); + if (_audiodriver) { + _audiodriver->setEchoCancelState (isEnabled); } } -std::string ManagerImpl::getNoiseSuppressState(void) { - +std::string ManagerImpl::getNoiseSuppressState (void) +{ + // noise suppress disabled by default bool isEnabled = false; - if(_audiodriver) { + if (_audiodriver) { isEnabled = _audiodriver->getNoiseSuppressState(); } - std::string state(""); - if(isEnabled) + std::string state (""); + + if (isEnabled) state = "enabled"; else state = "disabled"; @@ -2597,329 +2699,338 @@ std::string ManagerImpl::getNoiseSuppressState(void) { return state; } -void ManagerImpl::setNoiseSuppressState(std::string state) { - _debug("Manager: Set noise suppress state: %s", state.c_str()); +void ManagerImpl::setNoiseSuppressState (std::string state) +{ + _debug ("Manager: Set noise suppress state: %s", state.c_str()); bool isEnabled = false; - if(state.compare("enabled") == 0) - isEnabled = true; + if (state.compare ("enabled") == 0) + isEnabled = true; else - isEnabled = false; + isEnabled = false; - if(_audiodriver) { - _audiodriver->setNoiseSuppressState(isEnabled); + if (_audiodriver) { + _audiodriver->setNoiseSuppressState (isEnabled); } } -int ManagerImpl::app_is_running (std::string process) { - std::ostringstream cmd; +int ManagerImpl::app_is_running (std::string process) +{ + std::ostringstream cmd; - cmd << "ps -C " << process; - return system(cmd.str().c_str()); + cmd << "ps -C " << process; + return system (cmd.str().c_str()); } /** * Initialization: Main Thread */ -bool ManagerImpl::initAudioDriver (void) { - - int error; - - _debugInit ("AudioLayer Creation"); - - if (preferences.getAudioApi() == ALSA) { - _audiodriver = new AlsaLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - } - else if(preferences.getAudioApi() == PULSEAUDIO) { - if (app_is_running("pulseaudio") == 0) { - _audiodriver = new PulseLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - } else { - _audiodriver = new AlsaLayer(this); - preferences.setAudioApi(ALSA); - _audiodriver->setMainBuffer(&_mainBuffer); - } - } else - _debug ("Error - Audio API unknown"); - - if (_audiodriver == 0) { - _debug ("Init audio driver error"); - return false; - } else { - error = getAudioDriver()->getErrorMessage(); - - if (error == -1) { - _debug ("Init audio driver: %i", error); - return false; - } - } +bool ManagerImpl::initAudioDriver (void) +{ + + int error; + + _debugInit ("AudioLayer Creation"); + + if (preferences.getAudioApi() == ALSA) { + _audiodriver = new AlsaLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + } else if (preferences.getAudioApi() == PULSEAUDIO) { + if (app_is_running ("pulseaudio") == 0) { + _audiodriver = new PulseLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + } else { + _audiodriver = new AlsaLayer (this); + preferences.setAudioApi (ALSA); + _audiodriver->setMainBuffer (&_mainBuffer); + } + } else + _debug ("Error - Audio API unknown"); + + if (_audiodriver == 0) { + _debug ("Init audio driver error"); + return false; + } else { + error = getAudioDriver()->getErrorMessage(); + + if (error == -1) { + _debug ("Init audio driver: %i", error); + return false; + } + } - return true; + return true; } /** * Initialization: Main Thread and gui */ -void ManagerImpl::selectAudioDriver (void) { - int layer, numCardIn, numCardOut, numCardRing, sampleRate, frameSize; - std::string alsaPlugin; - AlsaLayer *alsalayer; - - layer = _audiodriver->getLayerType(); - _debug ("Audio layer type: %i" , layer); - - /* Retrieve the global devices info from the user config */ - alsaPlugin = audioPreference.getPlugin(); - numCardIn = audioPreference.getCardin(); - numCardOut = audioPreference.getCardout(); - numCardRing = audioPreference.getCardring(); - - sampleRate = _mainBuffer.getInternalSamplingRate(); - frameSize = audioPreference.getFramesize(); - - /* Only for the ALSA layer, we check the sound card information */ - - if (layer == ALSA) { - alsalayer = dynamic_cast<AlsaLayer*> (getAudioDriver()); - - if (!alsalayer -> soundCardIndexExist(numCardIn, SFL_PCM_CAPTURE)) { - _debug (" Card with index %i doesn't exist or cannot capture. Switch to 0.", numCardIn); - numCardIn = ALSA_DFT_CARD_ID; - audioPreference.setCardin(ALSA_DFT_CARD_ID); - } - - if (!alsalayer -> soundCardIndexExist(numCardOut, SFL_PCM_PLAYBACK)) { - _debug (" Card with index %i doesn't exist or cannot playback. Switch to 0.", numCardOut); - numCardOut = ALSA_DFT_CARD_ID; - audioPreference.setCardout(ALSA_DFT_CARD_ID); - } - - if (!alsalayer->soundCardIndexExist(numCardRing, SFL_PCM_RINGTONE)) { - _debug(" Card with index %i doesn't exist or cannot ringtone. Switch to 0.", numCardRing); - numCardRing = ALSA_DFT_CARD_ID; - audioPreference.setCardring(ALSA_DFT_CARD_ID); - } - } +void ManagerImpl::selectAudioDriver (void) +{ + int layer, numCardIn, numCardOut, numCardRing, sampleRate, frameSize; + std::string alsaPlugin; + AlsaLayer *alsalayer; + + layer = _audiodriver->getLayerType(); + _debug ("Audio layer type: %i" , layer); + + /* Retrieve the global devices info from the user config */ + alsaPlugin = audioPreference.getPlugin(); + numCardIn = audioPreference.getCardin(); + numCardOut = audioPreference.getCardout(); + numCardRing = audioPreference.getCardring(); + + sampleRate = _mainBuffer.getInternalSamplingRate(); + frameSize = audioPreference.getFramesize(); + + /* Only for the ALSA layer, we check the sound card information */ + + if (layer == ALSA) { + alsalayer = dynamic_cast<AlsaLayer*> (getAudioDriver()); + + if (!alsalayer -> soundCardIndexExist (numCardIn, SFL_PCM_CAPTURE)) { + _debug (" Card with index %i doesn't exist or cannot capture. Switch to 0.", numCardIn); + numCardIn = ALSA_DFT_CARD_ID; + audioPreference.setCardin (ALSA_DFT_CARD_ID); + } + + if (!alsalayer -> soundCardIndexExist (numCardOut, SFL_PCM_PLAYBACK)) { + _debug (" Card with index %i doesn't exist or cannot playback. Switch to 0.", numCardOut); + numCardOut = ALSA_DFT_CARD_ID; + audioPreference.setCardout (ALSA_DFT_CARD_ID); + } + + if (!alsalayer->soundCardIndexExist (numCardRing, SFL_PCM_RINGTONE)) { + _debug (" Card with index %i doesn't exist or cannot ringtone. Switch to 0.", numCardRing); + numCardRing = ALSA_DFT_CARD_ID; + audioPreference.setCardring (ALSA_DFT_CARD_ID); + } + } - _audiodriver->setErrorMessage(-1); + _audiodriver->setErrorMessage (-1); - /* Open the audio devices */ - _audiodriver->openDevice(numCardIn, numCardOut, numCardRing, sampleRate, frameSize, - SFL_PCM_BOTH, alsaPlugin); + /* Open the audio devices */ + _audiodriver->openDevice (numCardIn, numCardOut, numCardRing, sampleRate, frameSize, + SFL_PCM_BOTH, alsaPlugin); - /* Notify the error if there is one */ + /* Notify the error if there is one */ - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); } -void ManagerImpl::switchAudioManager (void) { - int type, samplerate, framesize, numCardIn, numCardOut, numCardRing; - std::string alsaPlugin; +void ManagerImpl::switchAudioManager (void) +{ + int type, samplerate, framesize, numCardIn, numCardOut, numCardRing; + std::string alsaPlugin; - _debug ("Manager: Switching audio manager "); + _debug ("Manager: Switching audio manager "); - if (!_audiodriver) - return; + if (!_audiodriver) + return; - type = _audiodriver->getLayerType(); + type = _audiodriver->getLayerType(); - samplerate = _mainBuffer.getInternalSamplingRate(); - framesize = audioPreference.getFramesize(); + samplerate = _mainBuffer.getInternalSamplingRate(); + framesize = audioPreference.getFramesize(); - _debug ("Manager: samplerate: %i, framesize %i", samplerate, framesize); + _debug ("Manager: samplerate: %i, framesize %i", samplerate, framesize); - alsaPlugin = audioPreference.getPlugin(); + alsaPlugin = audioPreference.getPlugin(); - numCardIn = audioPreference.getCardin(); - numCardOut = audioPreference.getCardout(); - numCardRing = audioPreference.getCardring(); + numCardIn = audioPreference.getCardin(); + numCardOut = audioPreference.getCardout(); + numCardRing = audioPreference.getCardring(); - _debug ("Manager: Deleting current layer... "); + _debug ("Manager: Deleting current layer... "); - // ost::MutexLock lock (*getAudioLayerMutex()); - getAudioLayerMutex()->enter(); + // ost::MutexLock lock (*getAudioLayerMutex()); + getAudioLayerMutex()->enter(); - // _audiodriver->closeLayer(); - delete _audiodriver; + // _audiodriver->closeLayer(); + delete _audiodriver; - _audiodriver = NULL; + _audiodriver = NULL; - switch (type) { + switch (type) { - case ALSA: - _debug ("Manager: Creating Pulseaudio layer..."); - _audiodriver = new PulseLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - break; + case ALSA: + _debug ("Manager: Creating Pulseaudio layer..."); + _audiodriver = new PulseLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + break; - case PULSEAUDIO: - _debug ("Manager: Creating ALSA layer..."); - _audiodriver = new AlsaLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - break; + case PULSEAUDIO: + _debug ("Manager: Creating ALSA layer..."); + _audiodriver = new AlsaLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + break; - default: - _warn("Manager: Error: audio layer unknown"); - break; - } + default: + _warn ("Manager: Error: audio layer unknown"); + break; + } - _audiodriver->setErrorMessage(-1); + _audiodriver->setErrorMessage (-1); - _audiodriver->openDevice(numCardIn, numCardOut, numCardRing, samplerate, framesize, - SFL_PCM_BOTH, alsaPlugin); + _audiodriver->openDevice (numCardIn, numCardOut, numCardRing, samplerate, framesize, + SFL_PCM_BOTH, alsaPlugin); - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); - _debug ("Manager: Current device: %i ", type); - _debug ("Manager: Has current call: %i ", hasCurrentCall()); + _debug ("Manager: Current device: %i ", type); + _debug ("Manager: Has current call: %i ", hasCurrentCall()); - if (hasCurrentCall()) - _audiodriver->startStream(); + if (hasCurrentCall()) + _audiodriver->startStream(); - // ost::MutexLock unlock (*getAudioLayerMutex()); - getAudioLayerMutex()->leave(); + // ost::MutexLock unlock (*getAudioLayerMutex()); + getAudioLayerMutex()->leave(); - // need to stop audio streams if there is currently no call - // if ( (type != PULSEAUDIO) && (!hasCurrentCall())) { - // _debug("There is currently a call!!"); - // _audiodriver->stopStream(); + // need to stop audio streams if there is currently no call + // if ( (type != PULSEAUDIO) && (!hasCurrentCall())) { + // _debug("There is currently a call!!"); + // _audiodriver->stopStream(); - // } + // } } -void ManagerImpl::audioSamplingRateChanged (void) { +void ManagerImpl::audioSamplingRateChanged (void) +{ - int type, samplerate, framesize, numCardIn, numCardOut, numCardRing; - std::string alsaPlugin; + int type, samplerate, framesize, numCardIn, numCardOut, numCardRing; + std::string alsaPlugin; - _debug ("Manager: Audio Sampling Rate"); + _debug ("Manager: Audio Sampling Rate"); - if (!_audiodriver) - return; + if (!_audiodriver) + return; - type = _audiodriver->getLayerType(); + type = _audiodriver->getLayerType(); - samplerate = _mainBuffer.getInternalSamplingRate(); - framesize = audioPreference.getFramesize(); + samplerate = _mainBuffer.getInternalSamplingRate(); + framesize = audioPreference.getFramesize(); - _debug ("Mnager: samplerate: %i, framesize %i", samplerate, framesize); + _debug ("Mnager: samplerate: %i, framesize %i", samplerate, framesize); - alsaPlugin = audioPreference.getPlugin(); + alsaPlugin = audioPreference.getPlugin(); - numCardIn = audioPreference.getCardin(); - numCardOut = audioPreference.getCardout(); - numCardRing = audioPreference.getCardring(); + numCardIn = audioPreference.getCardin(); + numCardOut = audioPreference.getCardout(); + numCardRing = audioPreference.getCardring(); - _debug ("Manager: Deleting current layer... "); + _debug ("Manager: Deleting current layer... "); - // ost::MutexLock lock (*getAudioLayerMutex()); - getAudioLayerMutex()->enter(); + // ost::MutexLock lock (*getAudioLayerMutex()); + getAudioLayerMutex()->enter(); - // _audiodriver->closeLayer(); - delete _audiodriver; + // _audiodriver->closeLayer(); + delete _audiodriver; - _audiodriver = NULL; + _audiodriver = NULL; - switch (type) { + switch (type) { - case PULSEAUDIO: - _debug ("Manager: Creating Pulseaudio layer..."); - _audiodriver = new PulseLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - break; + case PULSEAUDIO: + _debug ("Manager: Creating Pulseaudio layer..."); + _audiodriver = new PulseLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + break; - case ALSA: - _debug ("Manager: Creating ALSA layer..."); - _audiodriver = new AlsaLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - break; + case ALSA: + _debug ("Manager: Creating ALSA layer..."); + _audiodriver = new AlsaLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + break; - default: - _warn("Manager: Error: audio layer unknown"); - break; - } + default: + _warn ("Manager: Error: audio layer unknown"); + break; + } - _audiodriver->setErrorMessage(-1); + _audiodriver->setErrorMessage (-1); - _audiodriver->openDevice(numCardIn, numCardOut, numCardRing, samplerate, framesize, - SFL_PCM_BOTH, alsaPlugin); + _audiodriver->openDevice (numCardIn, numCardOut, numCardRing, samplerate, framesize, + SFL_PCM_BOTH, alsaPlugin); - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); - _debug ("Manager: Current device: %i ", type); - _debug ("Manager: Has current call: %i ", hasCurrentCall()); + _debug ("Manager: Current device: %i ", type); + _debug ("Manager: Has current call: %i ", hasCurrentCall()); - if (_audiodriver) { - unsigned int sampleRate = _audiodriver->getSampleRate(); + if (_audiodriver) { + unsigned int sampleRate = _audiodriver->getSampleRate(); - delete _telephoneTone; + delete _telephoneTone; - _debugInit ("Manager: Load telephone tone"); - std::string country = preferences.getZoneToneChoice(); - _telephoneTone = new TelephoneTone(country, sampleRate); + _debugInit ("Manager: Load telephone tone"); + std::string country = preferences.getZoneToneChoice(); + _telephoneTone = new TelephoneTone (country, sampleRate); - delete _dtmfKey; + delete _dtmfKey; - _debugInit ("Manager: Loading DTMF key"); - _dtmfKey = new DTMF(sampleRate); - } + _debugInit ("Manager: Loading DTMF key"); + _dtmfKey = new DTMF (sampleRate); + } - if (hasCurrentCall()) - _audiodriver->startStream(); + if (hasCurrentCall()) + _audiodriver->startStream(); - // ost::MutexLock unlock (*getAudioLayerMutex()); - getAudioLayerMutex()->leave(); + // ost::MutexLock unlock (*getAudioLayerMutex()); + getAudioLayerMutex()->leave(); - // need to stop audio streams if there is currently no call - // if ( (type != PULSEAUDIO) && (!hasCurrentCall())) { - // _debug("There is currently a call!!"); - // _audiodriver->stopStream(); + // need to stop audio streams if there is currently no call + // if ( (type != PULSEAUDIO) && (!hasCurrentCall())) { + // _debug("There is currently a call!!"); + // _audiodriver->stopStream(); - // } + // } } /** * Init the volume for speakers/micro from 0 to 100 value * Initialization: Main Thread */ -void ManagerImpl::initVolume () { - _debugInit ("Initiate Volume"); - setSpkrVolume(audioPreference.getVolumespkr()); - setMicVolume(audioPreference.getVolumemic()); +void ManagerImpl::initVolume () +{ + _debugInit ("Initiate Volume"); + setSpkrVolume (audioPreference.getVolumespkr()); + setMicVolume (audioPreference.getVolumemic()); } -void ManagerImpl::setSpkrVolume (unsigned short spkr_vol) { - PulseLayer *pulselayer = NULL; +void ManagerImpl::setSpkrVolume (unsigned short spkr_vol) +{ + PulseLayer *pulselayer = NULL; - /* Set the manager sound volume */ - _spkr_volume = spkr_vol; + /* Set the manager sound volume */ + _spkr_volume = spkr_vol; - /* Only for PulseAudio */ - pulselayer = dynamic_cast<PulseLayer*> (getAudioDriver()); + /* Only for PulseAudio */ + pulselayer = dynamic_cast<PulseLayer*> (getAudioDriver()); - if (pulselayer) { - if (pulselayer->getLayerType() == PULSEAUDIO) { - if (pulselayer) - pulselayer->setPlaybackVolume(spkr_vol); - } - } + if (pulselayer) { + if (pulselayer->getLayerType() == PULSEAUDIO) { + if (pulselayer) + pulselayer->setPlaybackVolume (spkr_vol); + } + } } -void ManagerImpl::setMicVolume (unsigned short mic_vol) { - _mic_volume = mic_vol; +void ManagerImpl::setMicVolume (unsigned short mic_vol) +{ + _mic_volume = mic_vol; } -int ManagerImpl::getLocalIp2IpPort (void) { - // The SIP port used for default account (IP to IP) calls= - return preferences.getPortNum(); +int ManagerImpl::getLocalIp2IpPort (void) +{ + // The SIP port used for default account (IP to IP) calls= + return preferences.getPortNum(); } @@ -2927,254 +3038,265 @@ int ManagerImpl::getLocalIp2IpPort (void) { /** * Main Thread */ -bool ManagerImpl::getCallStatus (const std::string& sequenceId UNUSED) { - if (!_dbus) { - return false; - } - - ost::MutexLock m(_callAccountMapMutex); - - CallAccountMap::iterator iter = _callAccountMap.begin(); - TokenList tk; - std::string code; - std::string status; - std::string destination; - std::string number; - - while (iter != _callAccountMap.end()) { - Call* call = getAccountLink(iter->second)->getCall(iter->first); - Call::ConnectionState state = call->getConnectionState(); - - if (state != Call::Connected) { - switch (state) { - - case Call::Trying: - code = "110"; - status = "Trying"; - break; - - case Call::Ringing: - code = "111"; - status = "Ringing"; - break; - - case Call::Progressing: - code = "125"; - status = "Progressing"; - break; - - case Call::Disconnected: - code = "125"; - status = "Disconnected"; - break; - - default: - code = ""; - status = ""; - } - } else { - switch (call->getState()) { - - case Call::Active: - - case Call::Conferencing: - code = "112"; - status = "Established"; - break; - - case Call::Hold: - code = "114"; - status = "Held"; - break; - - case Call::Busy: - code = "113"; - status = "Busy"; - break; - - case Call::Refused: - code = "125"; - status = "Refused"; - break; - - case Call::Error: - code = "125"; - status = "Error"; - break; - - case Call::Inactive: - code = "125"; - status = "Inactive"; - break; - } - } - - // No Congestion - // No Wrong Number - // 116 <CSeq> <call-id> <acc> <destination> Busy - destination = call->getPeerName(); - - number = call->getPeerNumber(); - - if (number != "") { - destination.append(" <"); - destination.append(number); - destination.append(">"); - } - - tk.push_back(iter->second); - - tk.push_back(destination); - tk.push_back(status); - tk.clear(); - - iter++; - } - - return true; +bool ManagerImpl::getCallStatus (const std::string& sequenceId UNUSED) +{ + if (!_dbus) { + return false; + } + + ost::MutexLock m (_callAccountMapMutex); + + CallAccountMap::iterator iter = _callAccountMap.begin(); + TokenList tk; + std::string code; + std::string status; + std::string destination; + std::string number; + + while (iter != _callAccountMap.end()) { + Call* call = getAccountLink (iter->second)->getCall (iter->first); + Call::ConnectionState state = call->getConnectionState(); + + if (state != Call::Connected) { + switch (state) { + + case Call::Trying: + code = "110"; + status = "Trying"; + break; + + case Call::Ringing: + code = "111"; + status = "Ringing"; + break; + + case Call::Progressing: + code = "125"; + status = "Progressing"; + break; + + case Call::Disconnected: + code = "125"; + status = "Disconnected"; + break; + + default: + code = ""; + status = ""; + } + } else { + switch (call->getState()) { + + case Call::Active: + + case Call::Conferencing: + code = "112"; + status = "Established"; + break; + + case Call::Hold: + code = "114"; + status = "Held"; + break; + + case Call::Busy: + code = "113"; + status = "Busy"; + break; + + case Call::Refused: + code = "125"; + status = "Refused"; + break; + + case Call::Error: + code = "125"; + status = "Error"; + break; + + case Call::Inactive: + code = "125"; + status = "Inactive"; + break; + } + } + + // No Congestion + // No Wrong Number + // 116 <CSeq> <call-id> <acc> <destination> Busy + destination = call->getPeerName(); + + number = call->getPeerNumber(); + + if (number != "") { + destination.append (" <"); + destination.append (number); + destination.append (">"); + } + + tk.push_back (iter->second); + + tk.push_back (destination); + tk.push_back (status); + tk.clear(); + + iter++; + } + + return true; } //THREAD=Main bool ManagerImpl::getConfig (const std::string& section, - const std::string& name, TokenList& arg) { - return _config.getConfigTreeItemToken(section, name, arg); + const std::string& name, TokenList& arg) +{ + return _config.getConfigTreeItemToken (section, name, arg); } //THREAD=Main // throw an Conf::ConfigTreeItemException if not found int ManagerImpl::getConfigInt (const std::string& section, - const std::string& name) { - try { - return _config.getConfigTreeItemIntValue(section, name); - } catch (Conf::ConfigTreeItemException& e) { - throw e; - } + const std::string& name) +{ + try { + return _config.getConfigTreeItemIntValue (section, name); + } catch (Conf::ConfigTreeItemException& e) { + throw e; + } - return 0; + return 0; } bool ManagerImpl::getConfigBool (const std::string& section, - const std::string& name) { - try { - return (_config.getConfigTreeItemValue(section, name) == TRUE_STR) ? true - : false; - } catch (Conf::ConfigTreeItemException& e) { - throw e; - } + const std::string& name) +{ + try { + return (_config.getConfigTreeItemValue (section, name) == TRUE_STR) ? true + : false; + } catch (Conf::ConfigTreeItemException& e) { + throw e; + } - return false; + return false; } //THREAD=Main std::string ManagerImpl::getConfigString (const std::string& section, - const std::string& name) { - try { - return _config.getConfigTreeItemValue(section, name); - } catch (Conf::ConfigTreeItemException& e) { - throw e; - } + const std::string& name) +{ + try { + return _config.getConfigTreeItemValue (section, name); + } catch (Conf::ConfigTreeItemException& e) { + throw e; + } - return ""; + return ""; } //THREAD=Main bool ManagerImpl::setConfig (const std::string& section, - const std::string& name, const std::string& value) { + const std::string& name, const std::string& value) +{ - return _config.setConfigTreeItem(section, name, value); + return _config.setConfigTreeItem (section, name, value); } //THREAD=Main bool ManagerImpl::setConfig (const std::string& section, - const std::string& name, int value) { - std::ostringstream valueStream; - valueStream << value; - return _config.setConfigTreeItem(section, name, valueStream.str()); + const std::string& name, int value) +{ + std::ostringstream valueStream; + valueStream << value; + return _config.setConfigTreeItem (section, name, valueStream.str()); } -void ManagerImpl::setAccountsOrder (const std::string& order) { - _debug ("Manager: Set accounts order : %s", order.c_str()); - // Set the new config +void ManagerImpl::setAccountsOrder (const std::string& order) +{ + _debug ("Manager: Set accounts order : %s", order.c_str()); + // Set the new config - preferences.setAccountOrder(order); + preferences.setAccountOrder (order); } -std::vector<std::string> ManagerImpl::getAccountList () { +std::vector<std::string> ManagerImpl::getAccountList () +{ + + std::vector<std::string> v; + std::vector<std::string> account_order; + unsigned int i; - std::vector<std::string> v; - std::vector<std::string> account_order; - unsigned int i; + _debug ("Manager: Get account list"); - _debug("Manager: Get account list"); + account_order = loadAccountOrder(); + AccountMap::iterator iter; - account_order = loadAccountOrder(); - AccountMap::iterator iter; + // The IP2IP profile is always available, and first in the list + iter = _accountMap.find (IP2IP_PROFILE); - // The IP2IP profile is always available, and first in the list - iter = _accountMap.find(IP2IP_PROFILE); - if (iter->second != NULL) { - // _debug("PUSHING BACK %s", iter->first.c_str()); - // v.push_back(iter->first.data()); - v.push_back(iter->second->getAccountID()); - } - else { - _error("Manager: could not find IP2IP profile in getAccount list"); - } + if (iter->second != NULL) { + // _debug("PUSHING BACK %s", iter->first.c_str()); + // v.push_back(iter->first.data()); + v.push_back (iter->second->getAccountID()); + } else { + _error ("Manager: could not find IP2IP profile in getAccount list"); + } - // If no order has been set, load the default one - // ie according to the creation date. + // If no order has been set, load the default one + // ie according to the creation date. - if (account_order.size() == 0) { - _debug("Manager: account order is empty"); - iter = _accountMap.begin(); + if (account_order.size() == 0) { + _debug ("Manager: account order is empty"); + iter = _accountMap.begin(); - while (iter != _accountMap.end()) { + while (iter != _accountMap.end()) { - if (iter->second != NULL && iter->first != IP2IP_PROFILE) { - _debug("PUSHING BACK %s", iter->first.c_str()); - // v.push_back(iter->first.data()); - v.push_back(iter->second->getAccountID()); - } + if (iter->second != NULL && iter->first != IP2IP_PROFILE) { + _debug ("PUSHING BACK %s", iter->first.c_str()); + // v.push_back(iter->first.data()); + v.push_back (iter->second->getAccountID()); + } - iter++; - } - } + iter++; + } + } - // Otherelse, load the custom one - // ie according to the saved order - else { - _debug("Manager: Load account list according to preferences"); - for (i = 0; i < account_order.size(); i++) { - // This account has not been loaded, so we ignore it - if ((iter = _accountMap.find(account_order[i])) - != _accountMap.end()) { - // If the account is valid - if (iter->second != NULL && iter->first != IP2IP_PROFILE) { - //_debug("PUSHING BACK %s", iter->first.c_str()); - // v.push_back(iter->first.data()); - v.push_back(iter->second->getAccountID()); - } - } - } - } + // Otherelse, load the custom one + // ie according to the saved order + else { + _debug ("Manager: Load account list according to preferences"); + + for (i = 0; i < account_order.size(); i++) { + // This account has not been loaded, so we ignore it + if ( (iter = _accountMap.find (account_order[i])) + != _accountMap.end()) { + // If the account is valid + if (iter->second != NULL && iter->first != IP2IP_PROFILE) { + //_debug("PUSHING BACK %s", iter->first.c_str()); + // v.push_back(iter->first.data()); + v.push_back (iter->second->getAccountID()); + } + } + } + } - return v; + return v; } std::map<std::string, std::string> ManagerImpl::getAccountDetails ( - const AccountID& accountID) { + const AccountID& accountID) +{ + + _debug ("Manager: get account details %s", accountID.c_str()); + + Account * account; + + if (! (account = _accountMap[accountID])) { + _debug ("Manager: Get account details on a non-existing accountID %s. Returning default", accountID.c_str()); + // return a default map + return defaultAccount.getAccountDetails(); + } else + return account->getAccountDetails(); - _debug("Manager: get account details %s", accountID.c_str()); - - Account * account; - if(!(account = _accountMap[accountID])) { - _debug("Manager: Get account details on a non-existing accountID %s. Returning default", accountID.c_str()); - // return a default map - return defaultAccount.getAccountDetails(); - } - else - return account->getAccountDetails(); - } /* Transform digest to string. @@ -3185,754 +3307,787 @@ std::map<std::string, std::string> ManagerImpl::getAccountDetails ( * NOTE: THE OUTPUT STRING IS NOT NULL TERMINATED! */ -void ManagerImpl::digest2str (const unsigned char digest[], char *output) { - int i; +void ManagerImpl::digest2str (const unsigned char digest[], char *output) +{ + int i; - for (i = 0; i < 16; ++i) { - pj_val_to_hex_digit(digest[i], output); - output += 2; - } + for (i = 0; i < 16; ++i) { + pj_val_to_hex_digit (digest[i], output); + output += 2; + } } std::string ManagerImpl::computeMd5HashFromCredential ( - const std::string& username, const std::string& password, - const std::string& realm) { - pj_md5_context pms; - unsigned char digest[16]; - char ha1[PJSIP_MD5STRLEN]; + const std::string& username, const std::string& password, + const std::string& realm) +{ + pj_md5_context pms; + unsigned char digest[16]; + char ha1[PJSIP_MD5STRLEN]; - pj_str_t usernamePjFormat = pj_str(strdup(username.c_str())); - pj_str_t passwordPjFormat = pj_str(strdup(password.c_str())); - pj_str_t realmPjFormat = pj_str(strdup(realm.c_str())); + pj_str_t usernamePjFormat = pj_str (strdup (username.c_str())); + pj_str_t passwordPjFormat = pj_str (strdup (password.c_str())); + pj_str_t realmPjFormat = pj_str (strdup (realm.c_str())); - /* Compute md5 hash = MD5(username ":" realm ":" password) */ - pj_md5_init(&pms); - MD5_APPEND (&pms, usernamePjFormat.ptr, usernamePjFormat.slen); - MD5_APPEND (&pms, ":", 1); - MD5_APPEND (&pms, realmPjFormat.ptr, realmPjFormat.slen); - MD5_APPEND (&pms, ":", 1); - MD5_APPEND (&pms, passwordPjFormat.ptr, passwordPjFormat.slen); - pj_md5_final(&pms, digest); + /* Compute md5 hash = MD5(username ":" realm ":" password) */ + pj_md5_init (&pms); + MD5_APPEND (&pms, usernamePjFormat.ptr, usernamePjFormat.slen); + MD5_APPEND (&pms, ":", 1); + MD5_APPEND (&pms, realmPjFormat.ptr, realmPjFormat.slen); + MD5_APPEND (&pms, ":", 1); + MD5_APPEND (&pms, passwordPjFormat.ptr, passwordPjFormat.slen); + pj_md5_final (&pms, digest); - digest2str(digest, ha1); + digest2str (digest, ha1); - char ha1_null_terminated[PJSIP_MD5STRLEN + 1]; - memcpy(ha1_null_terminated, ha1, sizeof(char) * PJSIP_MD5STRLEN); - ha1_null_terminated[PJSIP_MD5STRLEN] = '\0'; + char ha1_null_terminated[PJSIP_MD5STRLEN + 1]; + memcpy (ha1_null_terminated, ha1, sizeof (char) * PJSIP_MD5STRLEN); + ha1_null_terminated[PJSIP_MD5STRLEN] = '\0'; - std::string hashedDigest = ha1_null_terminated; - return hashedDigest; + std::string hashedDigest = ha1_null_terminated; + return hashedDigest; } void ManagerImpl::setCredential (const std::string& accountID UNUSED, - const int32_t& index UNUSED, const std::map<std::string UNUSED, std::string>& details UNUSED) { + const int32_t& index UNUSED, const std::map<std::string UNUSED, std::string>& details UNUSED) +{ - _debug("Manager: set credential"); + _debug ("Manager: set credential"); } // method to reduce the if/else mess. // Even better, switch to XML ! void ManagerImpl::setAccountDetails (const std::string& accountID, - const std::map<std::string, std::string>& details) { + const std::map<std::string, std::string>& details) +{ - _debug("Manager: Set account details %s", accountID.c_str()); - - Account* account; - if(!(account = getAccount(accountID))) { - _warn("Manager: Cannot setAccountDetails on a non-existing accountID %s.", accountID.c_str()); - return; - } + _debug ("Manager: Set account details %s", accountID.c_str()); - account->setAccountDetails(details); + Account* account; - saveConfig(); + if (! (account = getAccount (accountID))) { + _warn ("Manager: Cannot setAccountDetails on a non-existing accountID %s.", accountID.c_str()); + return; + } - if (account->isEnabled()) - account->registerVoIPLink(); - else - account->unregisterVoIPLink(); - - // Update account details to the client side - if (_dbus) - _dbus->getConfigurationManager()->accountsChanged(); + account->setAccountDetails (details); -} + saveConfig(); -std::string ManagerImpl::addAccount ( - const std::map<std::string, std::string>& details) { - - /** @todo Deal with both the _accountMap and the Configuration */ - std::string accountType, account_list; - Account* newAccount; - std::stringstream accountID; - AccountID newAccountID; + if (account->isEnabled()) + account->registerVoIPLink(); + else + account->unregisterVoIPLink(); - accountID << "Account:" << time(NULL); - newAccountID = accountID.str(); + // Update account details to the client side + if (_dbus) + _dbus->getConfigurationManager()->accountsChanged(); - // Get the type - accountType = (*details.find(CONFIG_ACCOUNT_TYPE)).second; +} - _debug ("Manager: Adding account %s", newAccountID.c_str()); +std::string ManagerImpl::addAccount ( + const std::map<std::string, std::string>& details) +{ + + /** @todo Deal with both the _accountMap and the Configuration */ + std::string accountType, account_list; + Account* newAccount; + std::stringstream accountID; + AccountID newAccountID; + + accountID << "Account:" << time (NULL); + newAccountID = accountID.str(); + + // Get the type + accountType = (*details.find (CONFIG_ACCOUNT_TYPE)).second; + + _debug ("Manager: Adding account %s", newAccountID.c_str()); + + /** @todo Verify the uniqueness, in case a program adds accounts, two in a row. */ + + if (accountType == "SIP") { + newAccount = AccountCreator::createAccount (AccountCreator::SIP_ACCOUNT, + newAccountID); + newAccount->setVoIPLink(); + } else if (accountType == "IAX") { + newAccount = AccountCreator::createAccount (AccountCreator::IAX_ACCOUNT, + newAccountID); + } else { + _error ("Unknown %s param when calling addAccount(): %s", CONFIG_ACCOUNT_TYPE, accountType.c_str()); + return ""; + } - /** @todo Verify the uniqueness, in case a program adds accounts, two in a row. */ + _accountMap[newAccountID] = newAccount; - if (accountType == "SIP") { - newAccount = AccountCreator::createAccount(AccountCreator::SIP_ACCOUNT, - newAccountID); - newAccount->setVoIPLink(); - } else if (accountType == "IAX") { - newAccount = AccountCreator::createAccount(AccountCreator::IAX_ACCOUNT, - newAccountID); - } else { - _error("Unknown %s param when calling addAccount(): %s", CONFIG_ACCOUNT_TYPE, accountType.c_str()); - return ""; - } + newAccount->setAccountDetails (details); - _accountMap[newAccountID] = newAccount; + // Add the newly created account in the account order list + account_list = preferences.getAccountOrder(); - newAccount->setAccountDetails(details); + if (account_list != "") { + newAccountID += "/"; + // Prepend the new account + account_list.insert (0, newAccountID); - // Add the newly created account in the account order list - account_list = preferences.getAccountOrder(); + preferences.setAccountOrder (account_list); + } else { + newAccountID += "/"; + account_list = newAccountID; + preferences.setAccountOrder (account_list); + } - if (account_list != "") { - newAccountID += "/"; - // Prepend the new account - account_list.insert(0, newAccountID); + _debug ("AccountMap: %s", account_list.c_str()); - preferences.setAccountOrder(account_list); - } - else { - newAccountID += "/"; - account_list = newAccountID; - preferences.setAccountOrder(account_list); - } + newAccount->setVoIPLink(); - _debug("AccountMap: %s", account_list.c_str()); + newAccount->registerVoIPLink(); - newAccount->setVoIPLink(); + saveConfig(); - newAccount->registerVoIPLink(); + if (_dbus) + _dbus->getConfigurationManager()->accountsChanged(); - saveConfig(); + return accountID.str(); +} - if (_dbus) - _dbus->getConfigurationManager()->accountsChanged(); +void ManagerImpl::deleteAllCredential (const AccountID& accountID) +{ - return accountID.str(); -} + _debug ("Manager: delete all credential"); -void ManagerImpl::deleteAllCredential (const AccountID& accountID) { - - _debug("Manager: delete all credential"); + Account *account = getAccount (accountID); - Account *account = getAccount(accountID); + if (!account) + return; - if(!account) - return; - - if(account->getType() != "SIP") - return; + if (account->getType() != "SIP") + return; - SIPAccount *sipaccount = (SIPAccount *)account; + SIPAccount *sipaccount = (SIPAccount *) account; - if (accountID.empty() == false) { - sipaccount->setCredentialCount(0); - } + if (accountID.empty() == false) { + sipaccount->setCredentialCount (0); + } } -void ManagerImpl::removeAccount (const AccountID& accountID) { - // Get it down and dying - Account* remAccount = NULL; - remAccount = getAccount(accountID); +void ManagerImpl::removeAccount (const AccountID& accountID) +{ + // Get it down and dying + Account* remAccount = NULL; + remAccount = getAccount (accountID); - if (remAccount != NULL) { - remAccount->unregisterVoIPLink(); - _accountMap.erase(accountID); - // http://projects.savoirfairelinux.net/issues/show/2355 - // delete remAccount; - } + if (remAccount != NULL) { + remAccount->unregisterVoIPLink(); + _accountMap.erase (accountID); + // http://projects.savoirfairelinux.net/issues/show/2355 + // delete remAccount; + } - _config.removeSection(accountID); + _config.removeSection (accountID); - saveConfig(); + saveConfig(); - _debug ("REMOVE ACCOUNT"); + _debug ("REMOVE ACCOUNT"); - if (_dbus) - _dbus->getConfigurationManager()->accountsChanged(); + if (_dbus) + _dbus->getConfigurationManager()->accountsChanged(); } // ACCOUNT handling bool ManagerImpl::associateCallToAccount (const CallID& callID, - const AccountID& accountID) { - if (getAccountFromCall(callID) == AccountNULL) { // nothing with the same ID - if (accountExists(accountID)) { // account id exist in AccountMap - ost::MutexLock m(_callAccountMapMutex); - _callAccountMap[callID] = accountID; - _debug ("Associate Call %s with Account %s", callID.data(), accountID.data()); - return true; - } else { - return false; - } - } else { - return false; - } + const AccountID& accountID) +{ + if (getAccountFromCall (callID) == AccountNULL) { // nothing with the same ID + if (accountExists (accountID)) { // account id exist in AccountMap + ost::MutexLock m (_callAccountMapMutex); + _callAccountMap[callID] = accountID; + _debug ("Associate Call %s with Account %s", callID.data(), accountID.data()); + return true; + } else { + return false; + } + } else { + return false; + } } -AccountID ManagerImpl::getAccountFromCall (const CallID& callID) { - ost::MutexLock m(_callAccountMapMutex); - CallAccountMap::iterator iter = _callAccountMap.find(callID); +AccountID ManagerImpl::getAccountFromCall (const CallID& callID) +{ + ost::MutexLock m (_callAccountMapMutex); + CallAccountMap::iterator iter = _callAccountMap.find (callID); - if (iter == _callAccountMap.end()) { - return AccountNULL; - } else { - return iter->second; - } + if (iter == _callAccountMap.end()) { + return AccountNULL; + } else { + return iter->second; + } } -bool ManagerImpl::removeCallAccount (const CallID& callID) { - ost::MutexLock m(_callAccountMapMutex); +bool ManagerImpl::removeCallAccount (const CallID& callID) +{ + ost::MutexLock m (_callAccountMapMutex); - if (_callAccountMap.erase(callID)) { - return true; - } - return false; + if (_callAccountMap.erase (callID)) { + return true; + } + + return false; } -CallID ManagerImpl::getNewCallID () { - std::ostringstream random_id("s"); - random_id << (unsigned) rand(); +CallID ManagerImpl::getNewCallID () +{ + std::ostringstream random_id ("s"); + random_id << (unsigned) rand(); - // when it's not found, it return "" - // generate, something like s10000s20000s4394040 + // when it's not found, it return "" + // generate, something like s10000s20000s4394040 - while (getAccountFromCall(random_id.str()) != AccountNULL) { - random_id.clear(); - random_id << "s"; - random_id << (unsigned) rand(); - } + while (getAccountFromCall (random_id.str()) != AccountNULL) { + random_id.clear(); + random_id << "s"; + random_id << (unsigned) rand(); + } - return random_id.str(); + return random_id.str(); } -std::vector<std::string> ManagerImpl::loadAccountOrder (void) { +std::vector<std::string> ManagerImpl::loadAccountOrder (void) +{ - std::string account_list; - std::vector<std::string> account_vect; + std::string account_list; + std::vector<std::string> account_vect; - account_list = preferences.getAccountOrder(); + account_list = preferences.getAccountOrder(); - _debug("Manager: Load sccount order %s", account_list.c_str()); + _debug ("Manager: Load sccount order %s", account_list.c_str()); - return unserialize(account_list); + return unserialize (account_list); } -short ManagerImpl::buildConfiguration () { +short ManagerImpl::buildConfiguration () +{ - _debug ("Manager: Loading account map"); + _debug ("Manager: Loading account map"); - loadIptoipProfile(); + loadIptoipProfile(); - int nbAccount = loadAccountMap(); + int nbAccount = loadAccountMap(); - return nbAccount; + return nbAccount; } -void ManagerImpl::loadIptoipProfile() { +void ManagerImpl::loadIptoipProfile() +{ - _debug ("Manager: Create default \"account\" (used as default UDP transport)"); + _debug ("Manager: Create default \"account\" (used as default UDP transport)"); - // build a default IP2IP account with default parameters - _directIpAccount = AccountCreator::createAccount(AccountCreator::SIP_DIRECT_IP_ACCOUNT, ""); - _accountMap[IP2IP_PROFILE] = _directIpAccount; + // build a default IP2IP account with default parameters + _directIpAccount = AccountCreator::createAccount (AccountCreator::SIP_DIRECT_IP_ACCOUNT, ""); + _accountMap[IP2IP_PROFILE] = _directIpAccount; - if (_directIpAccount == NULL) { - _error("Manager: Failed to create default \"account\""); - return; - } + if (_directIpAccount == NULL) { + _error ("Manager: Failed to create default \"account\""); + return; + } - // If configuration file parsed, load saved preferences - if (_setupLoaded) { + // If configuration file parsed, load saved preferences + if (_setupLoaded) { - _debug("Manager: Loading IP2IP profile preferences from config"); + _debug ("Manager: Loading IP2IP profile preferences from config"); - Conf::SequenceNode *seq = parser->getAccountSequence(); + Conf::SequenceNode *seq = parser->getAccountSequence(); + + Conf::Sequence::iterator iterIP2IP = seq->getSequence()->begin(); + Conf::Key accID ("id"); + + // Iterate over every account maps + while (iterIP2IP != seq->getSequence()->end()) { - Conf::Sequence::iterator iterIP2IP = seq->getSequence()->begin(); - Conf::Key accID("id"); + Conf::MappingNode *map = (Conf::MappingNode *) (*iterIP2IP); - // Iterate over every account maps - while(iterIP2IP != seq->getSequence()->end()) { + // Get the account id + Conf::ScalarNode * val = (Conf::ScalarNode *) (map->getValue (accID)); + Conf::Value accountid = val->getValue(); - Conf::MappingNode *map = (Conf::MappingNode *)(*iterIP2IP); + // if ID is IP2IP, unserialize + if (accountid == "IP2IP") { - // Get the account id - Conf::ScalarNode * val = (Conf::ScalarNode *)(map->getValue(accID)); - Conf::Value accountid = val->getValue(); - - // if ID is IP2IP, unserialize - if(accountid == "IP2IP") { - - try { - _directIpAccount->unserialize(map); - } - catch(SipAccountException &e) { - _error("Manager: %s", e.what()); - } - break; - } + try { + _directIpAccount->unserialize (map); + } catch (SipAccountException &e) { + _error ("Manager: %s", e.what()); + } - iterIP2IP++; + break; + } + + iterIP2IP++; + } } - } - // Force IP2IP settings to be loaded to be loaded - // No registration in the sense of the REGISTER method is performed. - _directIpAccount->registerVoIPLink(); - - // SIPVoIPlink is used as a singleton, it is the first call to instance here - // The SIP library initialization is done in the SIPVoIPLink constructor - // We need the IP2IP settings to be loaded at this time as they are used - // for default sip transport - - // _directIpAccount->setVoIPLink(SIPVoIPLink::instance ("")); - _directIpAccount->setVoIPLink(); + // Force IP2IP settings to be loaded to be loaded + // No registration in the sense of the REGISTER method is performed. + _directIpAccount->registerVoIPLink(); + + // SIPVoIPlink is used as a singleton, it is the first call to instance here + // The SIP library initialization is done in the SIPVoIPLink constructor + // We need the IP2IP settings to be loaded at this time as they are used + // for default sip transport + + // _directIpAccount->setVoIPLink(SIPVoIPLink::instance ("")); + _directIpAccount->setVoIPLink(); } -short ManagerImpl::loadAccountMap() { +short ManagerImpl::loadAccountMap() +{ - _debug("Manager: Load account map"); + _debug ("Manager: Load account map"); - // Conf::YamlParser *parser; - int nbAccount = 0; + // Conf::YamlParser *parser; + int nbAccount = 0; - if(!_setupLoaded) - return 0; + if (!_setupLoaded) + return 0; - // build preferences - preferences.unserialize((Conf::MappingNode *)(parser->getPreferenceSequence())); - voipPreferences.unserialize((Conf::MappingNode *)(parser->getVoipPreferenceSequence())); - addressbookPreference.unserialize((Conf::MappingNode *)(parser->getAddressbookSequence())); - hookPreference.unserialize((Conf::MappingNode *)(parser->getHookSequence())); - audioPreference.unserialize((Conf::MappingNode *)(parser->getAudioSequence())); - shortcutPreferences.unserialize((Conf::MappingNode *)(parser->getShortcutSequence())); + // build preferences + preferences.unserialize ( (Conf::MappingNode *) (parser->getPreferenceSequence())); + voipPreferences.unserialize ( (Conf::MappingNode *) (parser->getVoipPreferenceSequence())); + addressbookPreference.unserialize ( (Conf::MappingNode *) (parser->getAddressbookSequence())); + hookPreference.unserialize ( (Conf::MappingNode *) (parser->getHookSequence())); + audioPreference.unserialize ( (Conf::MappingNode *) (parser->getAudioSequence())); + shortcutPreferences.unserialize ( (Conf::MappingNode *) (parser->getShortcutSequence())); - Conf::SequenceNode *seq = parser->getAccountSequence(); + Conf::SequenceNode *seq = parser->getAccountSequence(); - // Each element in sequence is a new account to create - Conf::Sequence::iterator iterSeq = seq->getSequence()->begin(); - - Conf::Key accTypeKey("type"); - Conf::Key accID("id"); + // Each element in sequence is a new account to create + Conf::Sequence::iterator iterSeq = seq->getSequence()->begin(); - while(iterSeq != seq->getSequence()->end()) { + Conf::Key accTypeKey ("type"); + Conf::Key accID ("id"); - Account *tmpAccount = NULL; - Conf::MappingNode *map = (Conf::MappingNode *)(*iterSeq); - - Conf::ScalarNode * val = (Conf::ScalarNode *)(map->getValue(accTypeKey)); - Conf::Value accountType = val->getValue(); - - val = (Conf::ScalarNode *)(map->getValue(accID)); - Conf::Value accountid = val->getValue(); + while (iterSeq != seq->getSequence()->end()) { - if (accountType == "SIP" && accountid != "IP2IP") { - _debug("Manager: Create SIP account: %s", accountid.c_str()); - tmpAccount = AccountCreator::createAccount(AccountCreator::SIP_ACCOUNT, accountid); - } - else if (accountType == "IAX" && accountid != "IP2IP") { - _debug("Manager: Create IAX account: %s", accountid.c_str()); - tmpAccount = AccountCreator::createAccount(AccountCreator::IAX_ACCOUNT, accountid); - } + Account *tmpAccount = NULL; + Conf::MappingNode *map = (Conf::MappingNode *) (*iterSeq); + + Conf::ScalarNode * val = (Conf::ScalarNode *) (map->getValue (accTypeKey)); + Conf::Value accountType = val->getValue(); + + val = (Conf::ScalarNode *) (map->getValue (accID)); + Conf::Value accountid = val->getValue(); + + if (accountType == "SIP" && accountid != "IP2IP") { + _debug ("Manager: Create SIP account: %s", accountid.c_str()); + tmpAccount = AccountCreator::createAccount (AccountCreator::SIP_ACCOUNT, accountid); + } else if (accountType == "IAX" && accountid != "IP2IP") { + _debug ("Manager: Create IAX account: %s", accountid.c_str()); + tmpAccount = AccountCreator::createAccount (AccountCreator::IAX_ACCOUNT, accountid); + } + + + if (tmpAccount != NULL) { + try { + tmpAccount->unserialize (map); + } catch (SipAccountException &e) { + _error ("Manager: %s", e.what()); + } - if (tmpAccount != NULL) { - - try { - tmpAccount->unserialize(map); - } - catch(SipAccountException &e) { - _error("Manager: %s", e.what()); - } - - _accountMap[accountid] = tmpAccount; - _debug ("Manager: Loading account %s (size %d)", accountid.c_str(), _accountMap.size()); + _accountMap[accountid] = tmpAccount; + _debug ("Manager: Loading account %s (size %d)", accountid.c_str(), _accountMap.size()); - tmpAccount->setVoIPLink(); - nbAccount++; + tmpAccount->setVoIPLink(); + nbAccount++; + } + + iterSeq++; } - - iterSeq++; - } - try { - delete parser; - } - catch (Conf::YamlParserException &e) { - _error("Manager: %s", e.what()); - } + try { + delete parser; + } catch (Conf::YamlParserException &e) { + _error ("Manager: %s", e.what()); + } - parser = NULL; + parser = NULL; - return nbAccount; + return nbAccount; } -void ManagerImpl::unloadAccountMap () { +void ManagerImpl::unloadAccountMap () +{ - AccountMap::iterator iter = _accountMap.begin(); + AccountMap::iterator iter = _accountMap.begin(); - while (iter != _accountMap.end()) { + while (iter != _accountMap.end()) { - _debug ("Unloading account %s", iter->first.c_str()); + _debug ("Unloading account %s", iter->first.c_str()); - delete iter->second; - iter->second = NULL; + delete iter->second; + iter->second = NULL; + + iter++; + } - iter++; - } + _debug ("Manager: Clear account map"); + _accountMap.clear(); + _debug ("Manager: Unload account map"); - _debug("Manager: Clear account map"); - _accountMap.clear(); - _debug("Manager: Unload account map"); - } -bool ManagerImpl::accountExists (const AccountID& accountID) { - AccountMap::iterator iter = _accountMap.find(accountID); +bool ManagerImpl::accountExists (const AccountID& accountID) +{ + AccountMap::iterator iter = _accountMap.find (accountID); - if (iter == _accountMap.end()) { - return false; - } + if (iter == _accountMap.end()) { + return false; + } - return true; + return true; } Account* -ManagerImpl::getAccount (const AccountID& accountID) { - // In our definition, - // this is the "direct ip calls account" - if (accountID == AccountNULL) { - _debug ("Returns the direct IP account"); - return _directIpAccount; - } +ManagerImpl::getAccount (const AccountID& accountID) +{ + // In our definition, + // this is the "direct ip calls account" + if (accountID == AccountNULL) { + _debug ("Returns the direct IP account"); + return _directIpAccount; + } - AccountMap::iterator iter = _accountMap.find(accountID); + AccountMap::iterator iter = _accountMap.find (accountID); - if (iter == _accountMap.end()) { - return NULL; - } + if (iter == _accountMap.end()) { + return NULL; + } - return iter->second; + return iter->second; } AccountID ManagerImpl::getAccountIdFromNameAndServer ( - const std::string& userName, const std::string& server) { + const std::string& userName, const std::string& server) +{ - AccountMap::iterator iter; - SIPAccount *account; + AccountMap::iterator iter; + SIPAccount *account; - _info ("Manager : username = %s , server = %s", userName.c_str(), server.c_str()); - // Try to find the account id from username and server name by full match + _info ("Manager : username = %s , server = %s", userName.c_str(), server.c_str()); + // Try to find the account id from username and server name by full match - for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - account = dynamic_cast<SIPAccount *> (iter->second); + for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + account = dynamic_cast<SIPAccount *> (iter->second); - if (account != NULL) { - if (account->fullMatch(userName, server)) { - _debug ("Manager: Matching account id in request is a fullmatch %s@%s", userName.c_str(), server.c_str()); - return iter->first; - } - } - } + if (account != NULL) { + if (account->fullMatch (userName, server)) { + _debug ("Manager: Matching account id in request is a fullmatch %s@%s", userName.c_str(), server.c_str()); + return iter->first; + } + } + } - // We failed! Then only match the hostname - for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - account = dynamic_cast<SIPAccount *> (iter->second); + // We failed! Then only match the hostname + for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + account = dynamic_cast<SIPAccount *> (iter->second); - if (account != NULL) { - if (account->hostnameMatch(server)) { - _debug ("Manager: Matching account id in request with hostname %s", server.c_str()); - return iter->first; - } - } - } + if (account != NULL) { + if (account->hostnameMatch (server)) { + _debug ("Manager: Matching account id in request with hostname %s", server.c_str()); + return iter->first; + } + } + } - // We failed! Then only match the username - for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - account = dynamic_cast<SIPAccount *> (iter->second); + // We failed! Then only match the username + for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + account = dynamic_cast<SIPAccount *> (iter->second); - if (account != NULL) { - if (account->userMatch(userName)) { - _debug ("Manager: Matching account id in request with username %s", userName.c_str()); - return iter->first; - } - } - } + if (account != NULL) { + if (account->userMatch (userName)) { + _debug ("Manager: Matching account id in request with username %s", userName.c_str()); + return iter->first; + } + } + } - _debug ("Manager: Username %s or server %s doesn't match any account, using IP2IP", userName.c_str(), server.c_str()); + _debug ("Manager: Username %s or server %s doesn't match any account, using IP2IP", userName.c_str(), server.c_str()); - // Failed again! return AccountNULL - return AccountNULL; + // Failed again! return AccountNULL + return AccountNULL; } -std::map<std::string, int32_t> ManagerImpl::getAddressbookSettings () { +std::map<std::string, int32_t> ManagerImpl::getAddressbookSettings () +{ - std::map<std::string, int32_t> settings; + std::map<std::string, int32_t> settings; - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_ENABLE", addressbookPreference.getEnabled() ? 1 : 0)); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_MAX_RESULTS", addressbookPreference.getMaxResults())); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO", addressbookPreference.getPhoto() ? 1 : 0)); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS", addressbookPreference.getBusiness() ? 1 : 0)); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_DISPLAY_PHONE_HOME", addressbookPreference.getHome() ? 1 : 0)); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_DISPLAY_PHONE_MOBILE", addressbookPreference.getMobile() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_ENABLE", addressbookPreference.getEnabled() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_MAX_RESULTS", addressbookPreference.getMaxResults())); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO", addressbookPreference.getPhoto() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS", addressbookPreference.getBusiness() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_PHONE_HOME", addressbookPreference.getHome() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_PHONE_MOBILE", addressbookPreference.getMobile() ? 1 : 0)); - return settings; + return settings; } void ManagerImpl::setAddressbookSettings ( - const std::map<std::string, int32_t>& settings) { + const std::map<std::string, int32_t>& settings) +{ - addressbookPreference.setEnabled((settings.find("ADDRESSBOOK_ENABLE")->second == 1) ? true : false); - addressbookPreference.setMaxResults(settings.find("ADDRESSBOOK_MAX_RESULTS")->second); - addressbookPreference.setPhoto((settings.find("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO")->second == 1) ? true : false); - addressbookPreference.setBusiness((settings.find("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS")->second == 1) ? true : false); - addressbookPreference.setHone((settings.find("ADDRESSBOOK_DISPLAY_PHONE_HOME")->second == 1) ? true : false); - addressbookPreference.setMobile((settings.find("ADDRESSBOOK_DISPLAY_PHONE_MOBILE")->second == 1) ? true : false); + addressbookPreference.setEnabled ( (settings.find ("ADDRESSBOOK_ENABLE")->second == 1) ? true : false); + addressbookPreference.setMaxResults (settings.find ("ADDRESSBOOK_MAX_RESULTS")->second); + addressbookPreference.setPhoto ( (settings.find ("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO")->second == 1) ? true : false); + addressbookPreference.setBusiness ( (settings.find ("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS")->second == 1) ? true : false); + addressbookPreference.setHone ( (settings.find ("ADDRESSBOOK_DISPLAY_PHONE_HOME")->second == 1) ? true : false); + addressbookPreference.setMobile ( (settings.find ("ADDRESSBOOK_DISPLAY_PHONE_MOBILE")->second == 1) ? true : false); - // Write it to the configuration file - saveConfig(); + // Write it to the configuration file + saveConfig(); } -void ManagerImpl::setAddressbookList (const std::vector<std::string>& list) { +void ManagerImpl::setAddressbookList (const std::vector<std::string>& list) +{ - std::string s = serialize(list); - addressbookPreference.setList(s); + std::string s = serialize (list); + addressbookPreference.setList (s); } -std::vector<std::string> ManagerImpl::getAddressbookList (void) { +std::vector<std::string> ManagerImpl::getAddressbookList (void) +{ - std::string s = addressbookPreference.getList(); - return unserialize(s); + std::string s = addressbookPreference.getList(); + return unserialize (s); } -std::map<std::string, std::string> ManagerImpl::getHookSettings () { +std::map<std::string, std::string> ManagerImpl::getHookSettings () +{ - std::map<std::string, std::string> settings; + std::map<std::string, std::string> settings; - - settings.insert(std::pair<std::string, std::string>("URLHOOK_IAX2_ENABLED", hookPreference.getIax2Enabled() ? "true" : "false")); - settings.insert(std::pair<std::string, std::string>("PHONE_NUMBER_HOOK_ADD_PREFIX", hookPreference.getNumberAddPrefix())); - settings.insert(std::pair<std::string, std::string>("PHONE_NUMBER_HOOK_ENABLED", hookPreference.getNumberEnabled() ? "true" : "false")); - settings.insert(std::pair<std::string, std::string>("URLHOOK_SIP_ENABLED", hookPreference.getSipEnabled() ? "true" : "false")); - settings.insert(std::pair<std::string, std::string>("URLHOOK_COMMAND", hookPreference.getUrlCommand())); - settings.insert(std::pair<std::string, std::string>("URLHOOK_SIP_FIELD", hookPreference.getUrlSipField())); - return settings; + settings.insert (std::pair<std::string, std::string> ("URLHOOK_IAX2_ENABLED", hookPreference.getIax2Enabled() ? "true" : "false")); + settings.insert (std::pair<std::string, std::string> ("PHONE_NUMBER_HOOK_ADD_PREFIX", hookPreference.getNumberAddPrefix())); + settings.insert (std::pair<std::string, std::string> ("PHONE_NUMBER_HOOK_ENABLED", hookPreference.getNumberEnabled() ? "true" : "false")); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_SIP_ENABLED", hookPreference.getSipEnabled() ? "true" : "false")); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_COMMAND", hookPreference.getUrlCommand())); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_SIP_FIELD", hookPreference.getUrlSipField())); + + return settings; } -void ManagerImpl::setHookSettings (const std::map<std::string, std::string>& settings) { +void ManagerImpl::setHookSettings (const std::map<std::string, std::string>& settings) +{ - hookPreference.setIax2Enabled((settings.find("URLHOOK_IAX2_ENABLED")->second == "true") ? true : false); - hookPreference.setNumberAddPrefix(settings.find("PHONE_NUMBER_HOOK_ADD_PREFIX")->second); - hookPreference.setNumberEnabled((settings.find("PHONE_NUMBER_HOOK_ENABLED")->second == "true") ? true : false); - hookPreference.setSipEnabled((settings.find("URLHOOK_SIP_ENABLED")->second == "true") ? true : false); - hookPreference.setUrlCommand(settings.find("URLHOOK_COMMAND")->second); - hookPreference.setUrlSipField(settings.find("URLHOOK_SIP_FIELD")->second); + hookPreference.setIax2Enabled ( (settings.find ("URLHOOK_IAX2_ENABLED")->second == "true") ? true : false); + hookPreference.setNumberAddPrefix (settings.find ("PHONE_NUMBER_HOOK_ADD_PREFIX")->second); + hookPreference.setNumberEnabled ( (settings.find ("PHONE_NUMBER_HOOK_ENABLED")->second == "true") ? true : false); + hookPreference.setSipEnabled ( (settings.find ("URLHOOK_SIP_ENABLED")->second == "true") ? true : false); + hookPreference.setUrlCommand (settings.find ("URLHOOK_COMMAND")->second); + hookPreference.setUrlSipField (settings.find ("URLHOOK_SIP_FIELD")->second); - // Write it to the configuration file - saveConfig(); + // Write it to the configuration file + saveConfig(); } void ManagerImpl::check_call_configuration (const CallID& id, - const std::string &to, Call::CallConfiguration *callConfig) { - Call::CallConfiguration config; - - if (to.find(SIP_SCHEME) == 0 || to.find(SIPS_SCHEME) == 0) { - _debug ("Manager: Sip scheme detected (sip: or sips:), sending IP2IP Call"); - config = Call::IPtoIP; - } else { - config = Call::Classic; - } + const std::string &to, Call::CallConfiguration *callConfig) +{ + Call::CallConfiguration config; + + if (to.find (SIP_SCHEME) == 0 || to.find (SIPS_SCHEME) == 0) { + _debug ("Manager: Sip scheme detected (sip: or sips:), sending IP2IP Call"); + config = Call::IPtoIP; + } else { + config = Call::Classic; + } - associateConfigToCall(id, config); + associateConfigToCall (id, config); - *callConfig = config; + *callConfig = config; } bool ManagerImpl::associateConfigToCall (const CallID& callID, - Call::CallConfiguration config) { - - if (getConfigFromCall(callID) == CallConfigNULL) { // nothing with the same ID - _callConfigMap[callID] = config; - _debug ("Manager: Associate call %s with config %i", callID.c_str(), config); - return true; - } else { - return false; - } + Call::CallConfiguration config) +{ + + if (getConfigFromCall (callID) == CallConfigNULL) { // nothing with the same ID + _callConfigMap[callID] = config; + _debug ("Manager: Associate call %s with config %i", callID.c_str(), config); + return true; + } else { + return false; + } } -Call::CallConfiguration ManagerImpl::getConfigFromCall (const CallID& callID) { +Call::CallConfiguration ManagerImpl::getConfigFromCall (const CallID& callID) +{ - CallConfigMap::iterator iter = _callConfigMap.find(callID); + CallConfigMap::iterator iter = _callConfigMap.find (callID); - if (iter == _callConfigMap.end()) { - return (Call::CallConfiguration) CallConfigNULL; - } else { - return iter->second; - } + if (iter == _callConfigMap.end()) { + return (Call::CallConfiguration) CallConfigNULL; + } else { + return iter->second; + } } -bool ManagerImpl::removeCallConfig (const CallID& callID) { +bool ManagerImpl::removeCallConfig (const CallID& callID) +{ - if (_callConfigMap.erase(callID)) { - return true; - } + if (_callConfigMap.erase (callID)) { + return true; + } - return false; + return false; } -std::map<std::string, std::string> ManagerImpl::getCallDetails (const CallID& callID) { +std::map<std::string, std::string> ManagerImpl::getCallDetails (const CallID& callID) +{ - std::map<std::string, std::string> call_details; - AccountID accountid; - Account *account; - VoIPLink *link; - Call *call = NULL; - std::stringstream type; + std::map<std::string, std::string> call_details; + AccountID accountid; + Account *account; + VoIPLink *link; + Call *call = NULL; + std::stringstream type; - // We need here to retrieve the call information attached to the call ID - // To achieve that, we need to get the voip link attached to the call - // But to achieve that, we need to get the account the call was made with + // We need here to retrieve the call information attached to the call ID + // To achieve that, we need to get the voip link attached to the call + // But to achieve that, we need to get the account the call was made with - // So first we fetch the account - accountid = getAccountFromCall(callID); + // So first we fetch the account + accountid = getAccountFromCall (callID); - // Then the VoIP link this account is linked with (IAX2 or SIP) - if ((account = getAccount(accountid)) != 0) { - link = account->getVoIPLink(); + // Then the VoIP link this account is linked with (IAX2 or SIP) + if ( (account = getAccount (accountid)) != 0) { + link = account->getVoIPLink(); - if (link) { - call = link->getCall(callID); - } - } + if (link) { + call = link->getCall (callID); + } + } - if (call) { - type << call->getCallType(); - call_details.insert(std::pair<std::string, std::string>("ACCOUNTID", accountid)); - call_details.insert(std::pair<std::string, std::string>("PEER_NUMBER", call->getPeerNumber())); - call_details.insert(std::pair<std::string, std::string>("PEER_NAME", call->getPeerName())); - call_details.insert(std::pair<std::string, std::string>("DISPLAY_NAME", call->getDisplayName())); - call_details.insert(std::pair<std::string, std::string>("CALL_STATE", call->getStateStr())); - call_details.insert(std::pair<std::string, std::string>("CALL_TYPE", type.str())); - } else { - _error ("Manager: Error: getCallDetails()"); - call_details.insert(std::pair<std::string, std::string>("ACCOUNTID", AccountNULL)); - call_details.insert(std::pair<std::string, std::string>("PEER_NUMBER", "Unknown")); - call_details.insert(std::pair<std::string, std::string>("PEER_NAME", "Unknown")); - call_details.insert(std::pair<std::string, std::string>("CALL_STATE", "UNKNOWN")); - call_details.insert(std::pair<std::string, std::string>("CALL_TYPE", "0")); - } + if (call) { + type << call->getCallType(); + call_details.insert (std::pair<std::string, std::string> ("ACCOUNTID", accountid)); + call_details.insert (std::pair<std::string, std::string> ("PEER_NUMBER", call->getPeerNumber())); + call_details.insert (std::pair<std::string, std::string> ("PEER_NAME", call->getPeerName())); + call_details.insert (std::pair<std::string, std::string> ("DISPLAY_NAME", call->getDisplayName())); + call_details.insert (std::pair<std::string, std::string> ("CALL_STATE", call->getStateStr())); + call_details.insert (std::pair<std::string, std::string> ("CALL_TYPE", type.str())); + } else { + _error ("Manager: Error: getCallDetails()"); + call_details.insert (std::pair<std::string, std::string> ("ACCOUNTID", AccountNULL)); + call_details.insert (std::pair<std::string, std::string> ("PEER_NUMBER", "Unknown")); + call_details.insert (std::pair<std::string, std::string> ("PEER_NAME", "Unknown")); + call_details.insert (std::pair<std::string, std::string> ("CALL_STATE", "UNKNOWN")); + call_details.insert (std::pair<std::string, std::string> ("CALL_TYPE", "0")); + } - return call_details; + return call_details; } -std::map<std::string, std::string> ManagerImpl::send_history_to_client (void) { - return _history->get_history_serialized(); +std::map<std::string, std::string> ManagerImpl::send_history_to_client (void) +{ + return _history->get_history_serialized(); } void ManagerImpl::receive_history_from_client (std::map<std::string, - std::string> history) { + std::string> history) +{ - _history->set_serialized_history(history, preferences.getHistoryLimit());; - _history->save_history(); + _history->set_serialized_history (history, preferences.getHistoryLimit());; + _history->save_history(); } -std::vector<std::string> ManagerImpl::getCallList (void) { - std::vector<std::string> v; +std::vector<std::string> ManagerImpl::getCallList (void) +{ + std::vector<std::string> v; - CallAccountMap::iterator iter = _callAccountMap.begin(); + CallAccountMap::iterator iter = _callAccountMap.begin(); - while (iter != _callAccountMap.end()) { - v.push_back(iter->first.data()); - iter++; - } + while (iter != _callAccountMap.end()) { + v.push_back (iter->first.data()); + iter++; + } - return v; + return v; } std::map<std::string, std::string> ManagerImpl::getConferenceDetails ( - const ConfID& confID) { + const ConfID& confID) +{ - std::map<std::string, std::string> conf_details; - ConferenceMap::iterator iter_conf; + std::map<std::string, std::string> conf_details; + ConferenceMap::iterator iter_conf; - iter_conf = _conferencemap.find(confID); + iter_conf = _conferencemap.find (confID); - Conference* conf = NULL; + Conference* conf = NULL; - if (iter_conf != _conferencemap.end()) { + if (iter_conf != _conferencemap.end()) { - conf = iter_conf->second; - conf_details.insert(std::pair<std::string, std::string>("CONFID", - confID)); - conf_details.insert(std::pair<std::string, std::string>("CONF_STATE", - conf->getStateStr())); - } + conf = iter_conf->second; + conf_details.insert (std::pair<std::string, std::string> ("CONFID", + confID)); + conf_details.insert (std::pair<std::string, std::string> ("CONF_STATE", + conf->getStateStr())); + } - return conf_details; + return conf_details; } -std::vector<std::string> ManagerImpl::getConferenceList (void) { - _debug ("ManagerImpl::getConferenceList"); - std::vector<std::string> v; +std::vector<std::string> ManagerImpl::getConferenceList (void) +{ + _debug ("ManagerImpl::getConferenceList"); + std::vector<std::string> v; - ConferenceMap::iterator iter = _conferencemap.begin(); + ConferenceMap::iterator iter = _conferencemap.begin(); - while (iter != _conferencemap.end()) { - v.push_back(iter->first); - iter++; - } + while (iter != _conferencemap.end()) { + v.push_back (iter->first); + iter++; + } - return v; + return v; } std::vector<std::string> ManagerImpl::getParticipantList ( - const std::string& confID) { + const std::string& confID) +{ - _debug ("ManagerImpl: Get participant list %s", confID.c_str()); - std::vector<std::string> v; + _debug ("ManagerImpl: Get participant list %s", confID.c_str()); + std::vector<std::string> v; - ConferenceMap::iterator iter_conf = _conferencemap.find(confID); - Conference *conf = NULL; + ConferenceMap::iterator iter_conf = _conferencemap.find (confID); + Conference *conf = NULL; - if (iter_conf != _conferencemap.end()) - conf = iter_conf->second; + if (iter_conf != _conferencemap.end()) + conf = iter_conf->second; - if (conf != NULL) { - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + if (conf != NULL) { + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { + while (iter_participant != participants.end()) { - v.push_back(*iter_participant); + v.push_back (*iter_participant); - iter_participant++; - } - } - else { - _warn("Manager: Warning: Did not found conference %s", confID.c_str()); - } + iter_participant++; + } + } else { + _warn ("Manager: Warning: Did not found conference %s", confID.c_str()); + } - return v; + return v; } - + diff --git a/sflphone-common/src/managerimpl_registration.cpp b/sflphone-common/src/managerimpl_registration.cpp old mode 100755 new mode 100644 index 1329aaa68bce3104d60de4bdacf9b26655739c7b..5f9be9bfca93b4f7eb547299b6c4060872ade2e7 --- a/sflphone-common/src/managerimpl_registration.cpp +++ b/sflphone-common/src/managerimpl_registration.cpp @@ -68,8 +68,8 @@ ManagerImpl::registerAccounts() if (iter->second->isEnabled()) { - _debug("Register account %s", iter->first.c_str()); - + _debug ("Register account %s", iter->first.c_str()); + status = iter->second->registerVoIPLink(); if (status != SUCCESS) { @@ -250,10 +250,10 @@ ManagerImpl::sendRegister (const std::string& accountID , const int32_t& enable) // Update the active field Account* acc = getAccount (accountID); - if(enable == 1) - acc->setEnabled(true); + if (enable == 1) + acc->setEnabled (true); else - acc->setEnabled(false); + acc->setEnabled (false); acc->loadConfig(); diff --git a/sflphone-common/src/preferences.cpp b/sflphone-common/src/preferences.cpp index 23566f24d2ef5a6b125898645d89a7acbcd7c5b2..1750246406388bd869405d0e162c1b08f34205c4 100644 --- a/sflphone-common/src/preferences.cpp +++ b/sflphone-common/src/preferences.cpp @@ -33,17 +33,17 @@ #include "global.h" #include "user_cfg.h" -Preferences::Preferences() : _accountOrder("") - , _audioApi(0) - , _historyLimit(30) - , _historyMaxCalls(20) - , _notifyMails(false) - , _zoneToneChoice(DFT_ZONE) // DFT_ZONE - , _registrationExpire(180) - , _portNum(5060) - , _searchBarDisplay(true) - , _zeroConfenable(false) - , _md5Hash(false) +Preferences::Preferences() : _accountOrder ("") + , _audioApi (0) + , _historyLimit (30) + , _historyMaxCalls (20) + , _notifyMails (false) + , _zoneToneChoice (DFT_ZONE) // DFT_ZONE + , _registrationExpire (180) + , _portNum (5060) + , _searchBarDisplay (true) + , _zeroConfenable (false) + , _md5Hash (false) { } @@ -51,89 +51,148 @@ Preferences::Preferences() : _accountOrder("") Preferences::~Preferences() {} -void Preferences::serialize(Conf::YamlEmitter *emiter) +void Preferences::serialize (Conf::YamlEmitter *emiter) { - _debug("Preference: Serialize configuration"); - - Conf::MappingNode preferencemap(NULL); - - Conf::ScalarNode order(_accountOrder); - std::stringstream audiostr; audiostr << _audioApi; - Conf::ScalarNode audioapi(audiostr.str()); - std::stringstream histlimitstr; histlimitstr << _historyLimit; - Conf::ScalarNode historyLimit(histlimitstr.str()); - std::stringstream histmaxstr; histmaxstr << _historyMaxCalls; - Conf::ScalarNode historyMaxCalls(histmaxstr.str()); - Conf::ScalarNode notifyMails(_notifyMails ? "true" : "false"); - Conf::ScalarNode zoneToneChoice(_zoneToneChoice); - std::stringstream expirestr; expirestr << _registrationExpire; - Conf::ScalarNode registrationExpire(expirestr.str()); - std::stringstream portstr; portstr << _portNum; - Conf::ScalarNode portNum(portstr.str()); - Conf::ScalarNode searchBarDisplay(_searchBarDisplay ? "true" : "false"); - Conf::ScalarNode zeroConfenable(_zeroConfenable ? "true" : "false"); - Conf::ScalarNode md5Hash(_md5Hash ? "true" : "false"); - - preferencemap.setKeyValue(orderKey, &order); - preferencemap.setKeyValue(audioApiKey, &audioapi); - preferencemap.setKeyValue(historyLimitKey, &historyLimit); - preferencemap.setKeyValue(historyMaxCallsKey, &historyMaxCalls); - preferencemap.setKeyValue(notifyMailsKey, ¬ifyMails); - preferencemap.setKeyValue(zoneToneChoiceKey, &zoneToneChoice); - preferencemap.setKeyValue(registrationExpireKey, ®istrationExpire); - preferencemap.setKeyValue(portNumKey, &portNum); - preferencemap.setKeyValue(searchBarDisplayKey, &searchBarDisplay); - preferencemap.setKeyValue(zeroConfenableKey, &zeroConfenable); - preferencemap.setKeyValue(md5HashKey, &md5Hash); - - emiter->serializePreference(&preferencemap); + _debug ("Preference: Serialize configuration"); + + Conf::MappingNode preferencemap (NULL); + + Conf::ScalarNode order (_accountOrder); + std::stringstream audiostr; + audiostr << _audioApi; + Conf::ScalarNode audioapi (audiostr.str()); + std::stringstream histlimitstr; + histlimitstr << _historyLimit; + Conf::ScalarNode historyLimit (histlimitstr.str()); + std::stringstream histmaxstr; + histmaxstr << _historyMaxCalls; + Conf::ScalarNode historyMaxCalls (histmaxstr.str()); + Conf::ScalarNode notifyMails (_notifyMails ? "true" : "false"); + Conf::ScalarNode zoneToneChoice (_zoneToneChoice); + std::stringstream expirestr; + expirestr << _registrationExpire; + Conf::ScalarNode registrationExpire (expirestr.str()); + std::stringstream portstr; + portstr << _portNum; + Conf::ScalarNode portNum (portstr.str()); + Conf::ScalarNode searchBarDisplay (_searchBarDisplay ? "true" : "false"); + Conf::ScalarNode zeroConfenable (_zeroConfenable ? "true" : "false"); + Conf::ScalarNode md5Hash (_md5Hash ? "true" : "false"); + + preferencemap.setKeyValue (orderKey, &order); + preferencemap.setKeyValue (audioApiKey, &audioapi); + preferencemap.setKeyValue (historyLimitKey, &historyLimit); + preferencemap.setKeyValue (historyMaxCallsKey, &historyMaxCalls); + preferencemap.setKeyValue (notifyMailsKey, ¬ifyMails); + preferencemap.setKeyValue (zoneToneChoiceKey, &zoneToneChoice); + preferencemap.setKeyValue (registrationExpireKey, ®istrationExpire); + preferencemap.setKeyValue (portNumKey, &portNum); + preferencemap.setKeyValue (searchBarDisplayKey, &searchBarDisplay); + preferencemap.setKeyValue (zeroConfenableKey, &zeroConfenable); + preferencemap.setKeyValue (md5HashKey, &md5Hash); + + emiter->serializePreference (&preferencemap); } -void Preferences::unserialize(Conf::MappingNode *map) +void Preferences::unserialize (Conf::MappingNode *map) { - _debug("Preference: Unserialize configuration"); - - Conf::ScalarNode *val; - - if(!map) - return; - - val = (Conf::ScalarNode *)(map->getValue(orderKey)); - if(val) { _accountOrder = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(audioApiKey)); - if(val) { _audioApi = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(historyLimitKey)); - if(val) { _historyLimit = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(historyMaxCallsKey)); - if(val) { _historyMaxCalls = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(notifyMailsKey)); - if(val) { _notifyMails = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(zoneToneChoiceKey)); - if(val) { _zoneToneChoice = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(registrationExpireKey)); - if(val) { _registrationExpire = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(portNumKey)); - if(val) { _portNum = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(searchBarDisplayKey)); - if(val && !val->getValue().empty()) { _searchBarDisplay = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(zeroConfenableKey)); - if(val && !val->getValue().empty()) { _zeroConfenable = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(md5HashKey)); - if(val && !val->getValue().empty()) { _md5Hash = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - - - + _debug ("Preference: Unserialize configuration"); + + Conf::ScalarNode *val; + + if (!map) + return; + + val = (Conf::ScalarNode *) (map->getValue (orderKey)); + + if (val) { + _accountOrder = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (audioApiKey)); + + if (val) { + _audioApi = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (historyLimitKey)); + + if (val) { + _historyLimit = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (historyMaxCallsKey)); + + if (val) { + _historyMaxCalls = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (notifyMailsKey)); + + if (val) { + _notifyMails = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (zoneToneChoiceKey)); + + if (val) { + _zoneToneChoice = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (registrationExpireKey)); + + if (val) { + _registrationExpire = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (portNumKey)); + + if (val) { + _portNum = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (searchBarDisplayKey)); + + if (val && !val->getValue().empty()) { + _searchBarDisplay = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (zeroConfenableKey)); + + if (val && !val->getValue().empty()) { + _zeroConfenable = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (md5HashKey)); + + if (val && !val->getValue().empty()) { + _md5Hash = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + + } -VoipPreference::VoipPreference() : _playDtmf(true) - , _playTones(true) - , _pulseLength(atoi(DFT_PULSE_LENGTH_STR))// DFT_PULSE_LENGTH_STR - , _sendDtmfAs(0) - , _symmetricRtp(true) - , _zidFile(ZRTP_ZIDFILE)// ZRTP_ZID_FILENAME +VoipPreference::VoipPreference() : _playDtmf (true) + , _playTones (true) + , _pulseLength (atoi (DFT_PULSE_LENGTH_STR)) // DFT_PULSE_LENGTH_STR + , _sendDtmfAs (0) + , _symmetricRtp (true) + , _zidFile (ZRTP_ZIDFILE) // ZRTP_ZID_FILENAME { } @@ -141,302 +200,456 @@ VoipPreference::VoipPreference() : _playDtmf(true) VoipPreference::~VoipPreference() {} -void VoipPreference::serialize(Conf::YamlEmitter *emitter) +void VoipPreference::serialize (Conf::YamlEmitter *emitter) { - _debug("VoipPreference: Serialize configuration"); - - Conf::MappingNode preferencemap(NULL); - - Conf::ScalarNode playDtmf(_playDtmf ? "true" : "false"); - Conf::ScalarNode playTones(_playTones ? "true" : "false"); - std::stringstream pulselengthstr; pulselengthstr << _pulseLength; - Conf::ScalarNode pulseLength(pulselengthstr.str()); - std::stringstream senddtmfstr; senddtmfstr << _sendDtmfAs; - Conf::ScalarNode sendDtmfAs(senddtmfstr.str()); - Conf::ScalarNode symmetricRtp(_symmetricRtp ? "true" : "false"); - Conf::ScalarNode zidFile(_zidFile.c_str()); - - preferencemap.setKeyValue(playDtmfKey, &playDtmf); - preferencemap.setKeyValue(playTonesKey, &playTones); - preferencemap.setKeyValue(pulseLengthKey, &pulseLength); - preferencemap.setKeyValue(sendDtmfAsKey, &sendDtmfAs); - preferencemap.setKeyValue(symmetricRtpKey, &symmetricRtp); - preferencemap.setKeyValue(zidFileKey, &zidFile); - - emitter->serializeVoipPreference(&preferencemap); + _debug ("VoipPreference: Serialize configuration"); + + Conf::MappingNode preferencemap (NULL); + + Conf::ScalarNode playDtmf (_playDtmf ? "true" : "false"); + Conf::ScalarNode playTones (_playTones ? "true" : "false"); + std::stringstream pulselengthstr; + pulselengthstr << _pulseLength; + Conf::ScalarNode pulseLength (pulselengthstr.str()); + std::stringstream senddtmfstr; + senddtmfstr << _sendDtmfAs; + Conf::ScalarNode sendDtmfAs (senddtmfstr.str()); + Conf::ScalarNode symmetricRtp (_symmetricRtp ? "true" : "false"); + Conf::ScalarNode zidFile (_zidFile.c_str()); + + preferencemap.setKeyValue (playDtmfKey, &playDtmf); + preferencemap.setKeyValue (playTonesKey, &playTones); + preferencemap.setKeyValue (pulseLengthKey, &pulseLength); + preferencemap.setKeyValue (sendDtmfAsKey, &sendDtmfAs); + preferencemap.setKeyValue (symmetricRtpKey, &symmetricRtp); + preferencemap.setKeyValue (zidFileKey, &zidFile); + + emitter->serializeVoipPreference (&preferencemap); } -void VoipPreference::unserialize(Conf::MappingNode *map) +void VoipPreference::unserialize (Conf::MappingNode *map) { - _debug("VoipPreference: Unserialize configuration"); - - Conf::ScalarNode *val = NULL; - - if(!map) - return; - - val = (Conf::ScalarNode *)(map->getValue(playDtmfKey)); - if(val && !val->getValue().empty()) { _playDtmf = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(playTonesKey)); - if(val && !val->getValue().empty()) { _playTones = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(pulseLengthKey)); - if(val) { _pulseLength = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(sendDtmfAsKey)); - if(val) { _sendDtmfAs = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(symmetricRtpKey)); - if(val && !val->getValue().empty()) { _symmetricRtp = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(zidFileKey)); - if(val) { _zidFile = val->getValue().c_str(); val = NULL; } - + _debug ("VoipPreference: Unserialize configuration"); + + Conf::ScalarNode *val = NULL; + + if (!map) + return; + + val = (Conf::ScalarNode *) (map->getValue (playDtmfKey)); + + if (val && !val->getValue().empty()) { + _playDtmf = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (playTonesKey)); + + if (val && !val->getValue().empty()) { + _playTones = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (pulseLengthKey)); + + if (val) { + _pulseLength = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (sendDtmfAsKey)); + + if (val) { + _sendDtmfAs = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (symmetricRtpKey)); + + if (val && !val->getValue().empty()) { + _symmetricRtp = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (zidFileKey)); + + if (val) { + _zidFile = val->getValue().c_str(); + val = NULL; + } + } -AddressbookPreference::AddressbookPreference() : _photo(true) - , _enabled(true) - , _list("") - , _maxResults(25) - , _business(true) - , _home(true) - , _mobile(true) +AddressbookPreference::AddressbookPreference() : _photo (true) + , _enabled (true) + , _list ("") + , _maxResults (25) + , _business (true) + , _home (true) + , _mobile (true) { } AddressbookPreference::~AddressbookPreference() {} -void AddressbookPreference::serialize(Conf::YamlEmitter *emitter) +void AddressbookPreference::serialize (Conf::YamlEmitter *emitter) { - _debug("Addressbook: Serialize configuration"); - - Conf::MappingNode preferencemap(NULL); - - Conf::ScalarNode photo(_photo ? "true" : "false"); - Conf::ScalarNode enabled(_enabled ? "true" : "false"); - Conf::ScalarNode list(_list); - std::stringstream maxresultstr; maxresultstr << _maxResults; - Conf::ScalarNode maxResults(maxresultstr.str()); - Conf::ScalarNode business(_business ? "true" : "false"); - Conf::ScalarNode home(_home ? "true" : "false"); - Conf::ScalarNode mobile(_mobile ? "true" : "false"); - - preferencemap.setKeyValue(photoKey, &photo); - preferencemap.setKeyValue(enabledKey, &enabled); - preferencemap.setKeyValue(listKey, &list); - preferencemap.setKeyValue(maxResultsKey, &maxResults); - preferencemap.setKeyValue(businessKey, &business); - preferencemap.setKeyValue(homeKey, &home); - preferencemap.setKeyValue(mobileKey, &mobile); - - emitter->serializeAddressbookPreference(&preferencemap); + _debug ("Addressbook: Serialize configuration"); + + Conf::MappingNode preferencemap (NULL); + + Conf::ScalarNode photo (_photo ? "true" : "false"); + Conf::ScalarNode enabled (_enabled ? "true" : "false"); + Conf::ScalarNode list (_list); + std::stringstream maxresultstr; + maxresultstr << _maxResults; + Conf::ScalarNode maxResults (maxresultstr.str()); + Conf::ScalarNode business (_business ? "true" : "false"); + Conf::ScalarNode home (_home ? "true" : "false"); + Conf::ScalarNode mobile (_mobile ? "true" : "false"); + + preferencemap.setKeyValue (photoKey, &photo); + preferencemap.setKeyValue (enabledKey, &enabled); + preferencemap.setKeyValue (listKey, &list); + preferencemap.setKeyValue (maxResultsKey, &maxResults); + preferencemap.setKeyValue (businessKey, &business); + preferencemap.setKeyValue (homeKey, &home); + preferencemap.setKeyValue (mobileKey, &mobile); + + emitter->serializeAddressbookPreference (&preferencemap); } -void AddressbookPreference::unserialize(Conf::MappingNode *map) +void AddressbookPreference::unserialize (Conf::MappingNode *map) { - _debug("Addressbook: Unserialize configuration"); - - Conf::ScalarNode *val = NULL; - - if(!map) - return; - - val = (Conf::ScalarNode *)(map->getValue(photoKey)); - if(val && !(val->getValue().empty())) { _photo = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(enabledKey)); - if(val && !val->getValue().empty()) { _enabled = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(listKey)); - if(val) { _list = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(maxResultsKey)); - if(val) { _maxResults = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(businessKey)); - if(val && !val->getValue().empty()) { _business = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(homeKey)); - if(val && !val->getValue().empty()) { _home = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(mobileKey)); - if(val && !val->getValue().empty()) { _mobile = (val->getValue() == "true") ? true : false; val = NULL; } - + _debug ("Addressbook: Unserialize configuration"); + + Conf::ScalarNode *val = NULL; + + if (!map) + return; + + val = (Conf::ScalarNode *) (map->getValue (photoKey)); + + if (val && ! (val->getValue().empty())) { + _photo = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (enabledKey)); + + if (val && !val->getValue().empty()) { + _enabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (listKey)); + + if (val) { + _list = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (maxResultsKey)); + + if (val) { + _maxResults = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (businessKey)); + + if (val && !val->getValue().empty()) { + _business = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (homeKey)); + + if (val && !val->getValue().empty()) { + _home = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (mobileKey)); + + if (val && !val->getValue().empty()) { + _mobile = (val->getValue() == "true") ? true : false; + val = NULL; + } + } -HookPreference::HookPreference() : _iax2Enabled(false) - , _numberAddPrefix("") - , _numberEnabled(false) - , _sipEnabled(false) - , _urlCommand("x-www-browser") - , _urlSipField("X-sflphone-url") +HookPreference::HookPreference() : _iax2Enabled (false) + , _numberAddPrefix ("") + , _numberEnabled (false) + , _sipEnabled (false) + , _urlCommand ("x-www-browser") + , _urlSipField ("X-sflphone-url") { } HookPreference::~HookPreference() {} -void HookPreference::serialize(Conf::YamlEmitter *emitter) +void HookPreference::serialize (Conf::YamlEmitter *emitter) { - _debug("Hook: Serialize configuration"); + _debug ("Hook: Serialize configuration"); - Conf::MappingNode preferencemap(NULL); + Conf::MappingNode preferencemap (NULL); - Conf::ScalarNode iax2Enabled(_iax2Enabled ? "true" : "false"); - Conf::ScalarNode numberAddPrefix(_numberAddPrefix); - Conf::ScalarNode numberEnabled(_numberEnabled ? "true" : "false"); - Conf::ScalarNode sipEnabled(_sipEnabled ? "true" : "false"); - Conf::ScalarNode urlCommand(_urlCommand); - Conf::ScalarNode urlSipField(_urlSipField); + Conf::ScalarNode iax2Enabled (_iax2Enabled ? "true" : "false"); + Conf::ScalarNode numberAddPrefix (_numberAddPrefix); + Conf::ScalarNode numberEnabled (_numberEnabled ? "true" : "false"); + Conf::ScalarNode sipEnabled (_sipEnabled ? "true" : "false"); + Conf::ScalarNode urlCommand (_urlCommand); + Conf::ScalarNode urlSipField (_urlSipField); - preferencemap.setKeyValue(iax2EnabledKey, &iax2Enabled); - preferencemap.setKeyValue(numberAddPrefixKey, &numberAddPrefix); - preferencemap.setKeyValue(numberEnabledKey, &numberEnabled); - preferencemap.setKeyValue(sipEnabledKey, &sipEnabled); - preferencemap.setKeyValue(urlCommandKey, &urlCommand); - preferencemap.setKeyValue(urlSipFieldKey, &urlSipField); + preferencemap.setKeyValue (iax2EnabledKey, &iax2Enabled); + preferencemap.setKeyValue (numberAddPrefixKey, &numberAddPrefix); + preferencemap.setKeyValue (numberEnabledKey, &numberEnabled); + preferencemap.setKeyValue (sipEnabledKey, &sipEnabled); + preferencemap.setKeyValue (urlCommandKey, &urlCommand); + preferencemap.setKeyValue (urlSipFieldKey, &urlSipField); - emitter->serializeHooksPreference(&preferencemap); + emitter->serializeHooksPreference (&preferencemap); } -void HookPreference::unserialize(Conf::MappingNode *map) +void HookPreference::unserialize (Conf::MappingNode *map) { - Conf::ScalarNode *val = NULL; - - _debug("Hook: Unserialize preference"); - - if(!map) - return; - - val = (Conf::ScalarNode *)(map->getValue(iax2EnabledKey)); - if(val) { _iax2Enabled = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(numberAddPrefixKey)); - if(val) { _numberAddPrefix = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(numberEnabledKey)); - if(val) { _numberEnabled = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(sipEnabledKey)); - if(val) { _sipEnabled = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(urlCommandKey)); - if(val) { _urlCommand = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(urlSipFieldKey)); - if(val) { _urlSipField = val->getValue(); val = NULL; } - + Conf::ScalarNode *val = NULL; + + _debug ("Hook: Unserialize preference"); + + if (!map) + return; + + val = (Conf::ScalarNode *) (map->getValue (iax2EnabledKey)); + + if (val) { + _iax2Enabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (numberAddPrefixKey)); + + if (val) { + _numberAddPrefix = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (numberEnabledKey)); + + if (val) { + _numberEnabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (sipEnabledKey)); + + if (val) { + _sipEnabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (urlCommandKey)); + + if (val) { + _urlCommand = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (urlSipFieldKey)); + + if (val) { + _urlSipField = val->getValue(); + val = NULL; + } + } -AudioPreference::AudioPreference() : _cardin(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD - , _cardout(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD - , _cardring(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD - , _framesize(atoi(DFT_FRAME_SIZE)) // DFT_FRAME_SIZE - , _plugin("default") // PCM_DEFAULT - , _smplrate(44100) // DFT_SAMPLE_RATE - , _devicePlayback("") - , _deviceRecord("") - , _deviceRingtone("") - , _recordpath("") // DFT_RECORD_PATH - , _volumemic(atoi(DFT_VOL_SPKR_STR)) // DFT_VOL_SPKR_STR - , _volumespkr(atoi(DFT_VOL_MICRO_STR)) // DFT_VOL_MICRO_STR +AudioPreference::AudioPreference() : _cardin (atoi (ALSA_DFT_CARD)) // ALSA_DFT_CARD + , _cardout (atoi (ALSA_DFT_CARD)) // ALSA_DFT_CARD + , _cardring (atoi (ALSA_DFT_CARD)) // ALSA_DFT_CARD + , _framesize (atoi (DFT_FRAME_SIZE)) // DFT_FRAME_SIZE + , _plugin ("default") // PCM_DEFAULT + , _smplrate (44100) // DFT_SAMPLE_RATE + , _devicePlayback ("") + , _deviceRecord ("") + , _deviceRingtone ("") + , _recordpath ("") // DFT_RECORD_PATH + , _volumemic (atoi (DFT_VOL_SPKR_STR)) // DFT_VOL_SPKR_STR + , _volumespkr (atoi (DFT_VOL_MICRO_STR)) // DFT_VOL_MICRO_STR { } AudioPreference::~AudioPreference() {} -void AudioPreference::serialize(Conf::YamlEmitter *emitter) +void AudioPreference::serialize (Conf::YamlEmitter *emitter) { - _debug("AudioPreference: Serialize configuration"); + _debug ("AudioPreference: Serialize configuration"); - Conf::MappingNode preferencemap(NULL); - Conf::MappingNode alsapreferencemap(NULL); - Conf::MappingNode pulsepreferencemap(NULL); + Conf::MappingNode preferencemap (NULL); + Conf::MappingNode alsapreferencemap (NULL); + Conf::MappingNode pulsepreferencemap (NULL); // alsa preference - std::stringstream instr; instr << _cardin; - Conf::ScalarNode cardin(instr.str()); // 0 - std::stringstream outstr; outstr << _cardout; - Conf::ScalarNode cardout(outstr.str()); // 0 - std::stringstream ringstr; ringstr << _cardring; - Conf::ScalarNode cardring(ringstr.str());// 0 - std::stringstream framestr; framestr << _framesize; - Conf::ScalarNode framesize(framestr.str()); // 20 - Conf::ScalarNode plugin(_plugin); // default - std::stringstream ratestr; ratestr << _smplrate; - Conf::ScalarNode smplrate(ratestr.str());// 44100 - - //pulseaudio preference - Conf::ScalarNode devicePlayback(_devicePlayback);//: - Conf::ScalarNode deviceRecord(_deviceRecord); //: - Conf::ScalarNode deviceRingtone(_deviceRingtone); //: - - // general preference - Conf::ScalarNode recordpath(_recordpath); //: /home/msavard/Bureau - std::stringstream micstr; micstr << _volumemic; - Conf::ScalarNode volumemic(micstr.str()); //: 100 - std::stringstream spkrstr; spkrstr << _volumespkr; - Conf::ScalarNode volumespkr(spkrstr.str()); //: 100 - - preferencemap.setKeyValue(recordpathKey, &recordpath); - preferencemap.setKeyValue(volumemicKey, &volumemic); - preferencemap.setKeyValue(volumespkrKey, &volumespkr); - - preferencemap.setKeyValue(alsamapKey, &alsapreferencemap); - alsapreferencemap.setKeyValue(cardinKey, &cardin); - alsapreferencemap.setKeyValue(cardoutKey, &cardout); - alsapreferencemap.setKeyValue(cardringKey, &cardring); - alsapreferencemap.setKeyValue(framesizeKey, &framesize); - alsapreferencemap.setKeyValue(pluginKey, &plugin); - alsapreferencemap.setKeyValue(smplrateKey, &smplrate); - - preferencemap.setKeyValue(pulsemapKey, &pulsepreferencemap); - pulsepreferencemap.setKeyValue(devicePlaybackKey, &devicePlayback); - pulsepreferencemap.setKeyValue(deviceRecordKey, &deviceRecord); - pulsepreferencemap.setKeyValue(deviceRingtoneKey, &deviceRingtone); - - emitter->serializeAudioPreference(&preferencemap); - + std::stringstream instr; + instr << _cardin; + Conf::ScalarNode cardin (instr.str()); // 0 + std::stringstream outstr; + outstr << _cardout; + Conf::ScalarNode cardout (outstr.str()); // 0 + std::stringstream ringstr; + ringstr << _cardring; + Conf::ScalarNode cardring (ringstr.str());// 0 + std::stringstream framestr; + framestr << _framesize; + Conf::ScalarNode framesize (framestr.str()); // 20 + Conf::ScalarNode plugin (_plugin); // default + std::stringstream ratestr; + ratestr << _smplrate; + Conf::ScalarNode smplrate (ratestr.str());// 44100 + + //pulseaudio preference + Conf::ScalarNode devicePlayback (_devicePlayback);//: + Conf::ScalarNode deviceRecord (_deviceRecord); //: + Conf::ScalarNode deviceRingtone (_deviceRingtone); //: + + // general preference + Conf::ScalarNode recordpath (_recordpath); //: /home/msavard/Bureau + std::stringstream micstr; + micstr << _volumemic; + Conf::ScalarNode volumemic (micstr.str()); //: 100 + std::stringstream spkrstr; + spkrstr << _volumespkr; + Conf::ScalarNode volumespkr (spkrstr.str()); //: 100 + + preferencemap.setKeyValue (recordpathKey, &recordpath); + preferencemap.setKeyValue (volumemicKey, &volumemic); + preferencemap.setKeyValue (volumespkrKey, &volumespkr); + + preferencemap.setKeyValue (alsamapKey, &alsapreferencemap); + alsapreferencemap.setKeyValue (cardinKey, &cardin); + alsapreferencemap.setKeyValue (cardoutKey, &cardout); + alsapreferencemap.setKeyValue (cardringKey, &cardring); + alsapreferencemap.setKeyValue (framesizeKey, &framesize); + alsapreferencemap.setKeyValue (pluginKey, &plugin); + alsapreferencemap.setKeyValue (smplrateKey, &smplrate); + + preferencemap.setKeyValue (pulsemapKey, &pulsepreferencemap); + pulsepreferencemap.setKeyValue (devicePlaybackKey, &devicePlayback); + pulsepreferencemap.setKeyValue (deviceRecordKey, &deviceRecord); + pulsepreferencemap.setKeyValue (deviceRingtoneKey, &deviceRingtone); + + emitter->serializeAudioPreference (&preferencemap); + } -void AudioPreference::unserialize(Conf::MappingNode *map) +void AudioPreference::unserialize (Conf::MappingNode *map) { - _debug("AudioPreference: Unserialize configuration"); - - if(!map) - return; - - Conf::ScalarNode *val = NULL; - - val = (Conf::ScalarNode *)(map->getValue(cardinKey)); - if(val) { _cardin = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(cardoutKey)); - if(val) { _cardout = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(cardringKey)); - if(val) { _cardring = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(framesizeKey)); - if(val) { _framesize = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(smplrateKey)); - if(val) { _smplrate = atoi(val->getValue().data()); val = NULL; } - - val = (Conf::ScalarNode *)(map->getValue(devicePlaybackKey)); - if(val) { _devicePlayback = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(deviceRecordKey)); - if(val) { _deviceRecord = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(deviceRingtoneKey)); - if(val) { _deviceRingtone = val->getValue(); val = NULL; } - - val = (Conf::ScalarNode *)(map->getValue(recordpathKey)); - if(val) { _recordpath = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(volumemicKey)); - if(val) { _volumemic = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(volumespkrKey)); - if(val) { _volumespkr = atoi(val->getValue().data()); val = NULL; } + _debug ("AudioPreference: Unserialize configuration"); + + if (!map) + return; + + Conf::ScalarNode *val = NULL; + + val = (Conf::ScalarNode *) (map->getValue (cardinKey)); + + if (val) { + _cardin = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (cardoutKey)); + + if (val) { + _cardout = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (cardringKey)); + + if (val) { + _cardring = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (framesizeKey)); + + if (val) { + _framesize = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (smplrateKey)); + + if (val) { + _smplrate = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (devicePlaybackKey)); + + if (val) { + _devicePlayback = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (deviceRecordKey)); + + if (val) { + _deviceRecord = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (deviceRingtoneKey)); + + if (val) { + _deviceRingtone = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (recordpathKey)); + + if (val) { + _recordpath = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (volumemicKey)); + + if (val) { + _volumemic = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (volumespkrKey)); + + if (val) { + _volumespkr = atoi (val->getValue().data()); + val = NULL; + } } -ShortcutPreferences::ShortcutPreferences() : _hangup("") - , _pickup("") - , _popup("") - , _toggleHold("") - , _togglePickupHangup("") +ShortcutPreferences::ShortcutPreferences() : _hangup ("") + , _pickup ("") + , _popup ("") + , _toggleHold ("") + , _togglePickupHangup ("") { } @@ -447,98 +660,128 @@ ShortcutPreferences::~ShortcutPreferences() {} std::map<std::string, std::string> ShortcutPreferences::getShortcuts() { - std::map<std::string, std::string> shortcutsMap; + std::map<std::string, std::string> shortcutsMap; - shortcutsMap.insert(std::pair<std::string, std::string>(hangupShortKey, _hangup)); - shortcutsMap.insert(std::pair<std::string, std::string>(pickupShortKey, _pickup)); - shortcutsMap.insert(std::pair<std::string, std::string>(popupShortKey, _popup)); - shortcutsMap.insert(std::pair<std::string, std::string>(toggleHoldShortKey, _toggleHold)); - shortcutsMap.insert(std::pair<std::string, std::string>(togglePickupHangupShortKey, _togglePickupHangup)); + shortcutsMap.insert (std::pair<std::string, std::string> (hangupShortKey, _hangup)); + shortcutsMap.insert (std::pair<std::string, std::string> (pickupShortKey, _pickup)); + shortcutsMap.insert (std::pair<std::string, std::string> (popupShortKey, _popup)); + shortcutsMap.insert (std::pair<std::string, std::string> (toggleHoldShortKey, _toggleHold)); + shortcutsMap.insert (std::pair<std::string, std::string> (togglePickupHangupShortKey, _togglePickupHangup)); - return shortcutsMap; + return shortcutsMap; } -void ShortcutPreferences::setShortcuts(std::map<std::string, std::string> map_cpy) +void ShortcutPreferences::setShortcuts (std::map<std::string, std::string> map_cpy) { - // std::map<std::string, int> map_cpy = shortcut; - std::map<std::string, std::string>::iterator it; - - it = map_cpy.find(hangupShortKey); - if (it != map_cpy.end()) { - _hangup = it->second; - } - - it = map_cpy.find(pickupShortKey); - if (it != map_cpy.end()) { - _pickup = it->second; - } - - it = map_cpy.find(popupShortKey); - if (it != map_cpy.end()) { - _popup = it->second; - } - - it = map_cpy.find(toggleHoldShortKey); - if(it != map_cpy.end()) { - _toggleHold = it->second; - } - - it = map_cpy.find(togglePickupHangupShortKey); - if(it != map_cpy.end()) { - _togglePickupHangup = it->second; - } - /* - for (int i = 0; i < (int)shortcutsKeys.size(); i++) { - std::string key = shortcutsKeys.at(i); - it = map_cpy.find(key); - if (it != shortcutsMap.end()) { - Manager::instance().setConfig("Shortcuts", key, it->second); - } - } - */ + // std::map<std::string, int> map_cpy = shortcut; + std::map<std::string, std::string>::iterator it; + + it = map_cpy.find (hangupShortKey); + + if (it != map_cpy.end()) { + _hangup = it->second; + } + + it = map_cpy.find (pickupShortKey); + + if (it != map_cpy.end()) { + _pickup = it->second; + } + + it = map_cpy.find (popupShortKey); + + if (it != map_cpy.end()) { + _popup = it->second; + } + + it = map_cpy.find (toggleHoldShortKey); + + if (it != map_cpy.end()) { + _toggleHold = it->second; + } + + it = map_cpy.find (togglePickupHangupShortKey); + + if (it != map_cpy.end()) { + _togglePickupHangup = it->second; + } + + /* + for (int i = 0; i < (int)shortcutsKeys.size(); i++) { + std::string key = shortcutsKeys.at(i); + it = map_cpy.find(key); + if (it != shortcutsMap.end()) { + Manager::instance().setConfig("Shortcuts", key, it->second); + } + } + */ } -void ShortcutPreferences::serialize(Conf::YamlEmitter *emitter) +void ShortcutPreferences::serialize (Conf::YamlEmitter *emitter) { - _debug("ShortcutPreference: Serialize configuration"); - - Conf::MappingNode preferencemap(NULL); - - Conf::ScalarNode hangup(_hangup); - Conf::ScalarNode pickup(_pickup); - Conf::ScalarNode popup(_popup); - Conf::ScalarNode toggleHold(_toggleHold); - Conf::ScalarNode togglePickupHangup(_togglePickupHangup); - - preferencemap.setKeyValue(hangupShortKey, &hangup); - preferencemap.setKeyValue(pickupShortKey, &pickup); - preferencemap.setKeyValue(popupShortKey, &popup); - preferencemap.setKeyValue(toggleHoldShortKey, &toggleHold); - preferencemap.setKeyValue(togglePickupHangupShortKey, &togglePickupHangup); - - emitter->serializeShortcutPreference(&preferencemap); + _debug ("ShortcutPreference: Serialize configuration"); + + Conf::MappingNode preferencemap (NULL); + + Conf::ScalarNode hangup (_hangup); + Conf::ScalarNode pickup (_pickup); + Conf::ScalarNode popup (_popup); + Conf::ScalarNode toggleHold (_toggleHold); + Conf::ScalarNode togglePickupHangup (_togglePickupHangup); + + preferencemap.setKeyValue (hangupShortKey, &hangup); + preferencemap.setKeyValue (pickupShortKey, &pickup); + preferencemap.setKeyValue (popupShortKey, &popup); + preferencemap.setKeyValue (toggleHoldShortKey, &toggleHold); + preferencemap.setKeyValue (togglePickupHangupShortKey, &togglePickupHangup); + + emitter->serializeShortcutPreference (&preferencemap); } -void ShortcutPreferences::unserialize(Conf::MappingNode *map) +void ShortcutPreferences::unserialize (Conf::MappingNode *map) { - _debug("ShortcutPreference: Unserialize configuration"); - - if(!map) - return; - - Conf::ScalarNode *val = NULL; - - val = (Conf::ScalarNode *)(map->getValue(hangupShortKey)); - if(val) { _hangup = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(pickupShortKey)); - if(val) { _pickup = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(popupShortKey)); - if(val) { _popup = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(toggleHoldShortKey)); - if(val) { _toggleHold = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(togglePickupHangupShortKey)); - if(val) { _togglePickupHangup = val->getValue(); val = NULL; } + _debug ("ShortcutPreference: Unserialize configuration"); + + if (!map) + return; + + Conf::ScalarNode *val = NULL; + + val = (Conf::ScalarNode *) (map->getValue (hangupShortKey)); + + if (val) { + _hangup = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (pickupShortKey)); + + if (val) { + _pickup = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (popupShortKey)); + + if (val) { + _popup = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (toggleHoldShortKey)); + + if (val) { + _toggleHold = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (togglePickupHangupShortKey)); + + if (val) { + _togglePickupHangup = val->getValue(); + val = NULL; + } } diff --git a/sflphone-common/src/sip/Pattern.cpp b/sflphone-common/src/sip/Pattern.cpp index 89e3efb48a884e740383ff294370797ef6a2502a..0923bb09e64ed502075d4f7255b18813633be41d 100644 --- a/sflphone-common/src/sip/Pattern.cpp +++ b/sflphone-common/src/sip/Pattern.cpp @@ -36,7 +36,7 @@ namespace sfl Pattern::Pattern (const std::string& pattern, const std::string& options) : _pattern (pattern), - _re (NULL), + _re (NULL), _ovector (NULL), _ovectorSize (0), _count (0), @@ -194,8 +194,8 @@ std::string Pattern::group (const std::string& groupName) switch (rc) { case PCRE_ERROR_NOSUBSTRING: - - break; + + break; case PCRE_ERROR_NOMEMORY: throw match_error ("Memory exhausted."); @@ -207,14 +207,13 @@ std::string Pattern::group (const std::string& groupName) std::string matchedStr; - if(stringPtr) { + if (stringPtr) { - matchedStr = stringPtr; - pcre_free_substring (stringPtr); - } - else { + matchedStr = stringPtr; + pcre_free_substring (stringPtr); + } else { - matchedStr = ""; + matchedStr = ""; } return matchedStr; @@ -229,7 +228,7 @@ void Pattern::start (const std::string& groupName) const size_t Pattern::start (unsigned int groupNumber) const { - if (groupNumber <= (unsigned int)_count) { + if (groupNumber <= (unsigned int) _count) { return _ovector[ (groupNumber + 1) * 2]; } else { throw std::out_of_range ("Invalid group reference."); @@ -249,7 +248,7 @@ void Pattern::end (const std::string& groupName) const size_t Pattern::end (unsigned int groupNumber) const { - if (groupNumber <= (unsigned int)_count) { + if (groupNumber <= (unsigned int) _count) { return _ovector[ ( (groupNumber + 1) * 2) + 1 ] - 1; } else { throw std::out_of_range ("Invalid group reference."); @@ -280,7 +279,7 @@ bool Pattern::matches (const std::string& subject) throw (match_error) _ovector, _ovectorSize); - + // Matching failed. if (rc < 0) { @@ -304,7 +303,7 @@ bool Pattern::matches (const std::string& subject) throw (match_error) // Matching succeeded. Keep the number of substrings for // subsequent calls to group(). - _count = rc; + _count = rc; return true; } @@ -320,8 +319,8 @@ std::vector<std::string> Pattern::split (void) tokenStart = start(); substringSplitted.push_back (_subject.substr (tokenEnd + 1, tokenStart - tokenEnd - 1)); - // printf("split: %s\n", _subject.substr (tokenEnd + 1, - // tokenStart - tokenEnd - 1).c_str()); + // printf("split: %s\n", _subject.substr (tokenEnd + 1, + // tokenStart - tokenEnd - 1).c_str()); tokenEnd = end(); } diff --git a/sflphone-common/src/sip/SdesNegotiator.cpp b/sflphone-common/src/sip/SdesNegotiator.cpp index 5396755b6be1b948629e6cf6e63111f9756c828e..430bf80f059f934382cfc0f197523daf99c1052a 100644 --- a/sflphone-common/src/sip/SdesNegotiator.cpp +++ b/sflphone-common/src/sip/SdesNegotiator.cpp @@ -65,7 +65,7 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) try { - // used to match white space (which are used as separator) + // used to match white space (which are used as separator) generalSyntaxPattern = new Pattern ("[\x20\x09]+", "g"); tagPattern = new Pattern ("^a=crypto:(?P<tag>[0-9]{1,9})"); @@ -76,12 +76,12 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) "F8_128_HMAC_SHA1_80|" \ "[A-Za-z0-9_]+)"); // srtp-crypto-suite-ext - keyParamsPattern = new Pattern ( - "(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ - "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); + keyParamsPattern = new Pattern ( + "(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ + "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); sessionParamPattern = new Pattern ( "(?P<sessionParam>(kdr\\=[0-9]{1,2}|" \ @@ -96,23 +96,23 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) } catch (compile_error& exception) { throw parse_error ("A compile exception occured on a pattern."); } - + // Take each line from the vector // and parse its content - + std::vector<std::string>::iterator iter; std::vector<CryptoAttribute *> cryptoAttributeVector; - + for (iter = _remoteAttribute.begin(); iter != _remoteAttribute.end(); iter++) { // Split the line into its component // that we will analyze further down. std::vector<std::string> sdesLine; - - *generalSyntaxPattern << (*iter); - + + *generalSyntaxPattern << (*iter); + try { sdesLine = generalSyntaxPattern->split(); @@ -122,54 +122,55 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) } catch (match_error& exception) { throw parse_error ("Error while analyzing the SDES line."); } - + // Check if the attribute starts with a=crypto // and get the tag for this line *tagPattern << sdesLine.at (0); - - std::string tag; - if (tagPattern->matches()) { - try { - // std::cout << "Parsing the tag field"; - tag = tagPattern->group ("tag"); - // std::cout << ": " << tag << std::endl; - } catch (match_error& exception) { - throw parse_error ("Error while parsing the tag field"); - } - } else { - return cryptoAttributeVector; - } + + std::string tag; + + if (tagPattern->matches()) { + try { + // std::cout << "Parsing the tag field"; + tag = tagPattern->group ("tag"); + // std::cout << ": " << tag << std::endl; + } catch (match_error& exception) { + throw parse_error ("Error while parsing the tag field"); + } + } else { + return cryptoAttributeVector; + } // Check if the crypto suite is valid and retreive // its value. *cryptoSuitePattern << sdesLine.at (1); - std::string cryptoSuite; - - if (cryptoSuitePattern->matches()) { - try { - // std::cout << "Parsing the crypto suite field"; - cryptoSuite = cryptoSuitePattern->group ("cryptoSuite"); - // std::cout << ": " << cryptoSuite << std::endl; - } catch (match_error& exception) { - throw parse_error ("Error while parsing the crypto-suite field"); - } - } else { - return cryptoAttributeVector; - } - + std::string cryptoSuite; + + if (cryptoSuitePattern->matches()) { + try { + // std::cout << "Parsing the crypto suite field"; + cryptoSuite = cryptoSuitePattern->group ("cryptoSuite"); + // std::cout << ": " << cryptoSuite << std::endl; + } catch (match_error& exception) { + throw parse_error ("Error while parsing the crypto-suite field"); + } + } else { + return cryptoAttributeVector; + } + // Parse one or more key-params field. *keyParamsPattern << sdesLine.at (2); - std::string srtpKeyInfo; - std::string srtpKeyMethod; - std::string lifetime; - std::string mkiLength; - std::string mkiValue; - + std::string srtpKeyInfo; + std::string srtpKeyMethod; + std::string lifetime; + std::string mkiLength; + std::string mkiValue; + try { - while(keyParamsPattern->matches()) { + while (keyParamsPattern->matches()) { srtpKeyMethod = keyParamsPattern->group ("srtpKeyMethod"); srtpKeyInfo = keyParamsPattern->group ("srtpKeyInfo"); lifetime = keyParamsPattern->group ("lifetime"); @@ -197,11 +198,11 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) } } } */ - - // Add the new CryptoAttribute to the vector - - CryptoAttribute * cryptoAttribute = new CryptoAttribute(tag, cryptoSuite, srtpKeyMethod, srtpKeyInfo, lifetime, mkiValue, mkiLength); - cryptoAttributeVector.push_back(cryptoAttribute); + + // Add the new CryptoAttribute to the vector + + CryptoAttribute * cryptoAttribute = new CryptoAttribute (tag, cryptoSuite, srtpKeyMethod, srtpKeyInfo, lifetime, mkiValue, mkiLength); + cryptoAttributeVector.push_back (cryptoAttribute); } return cryptoAttributeVector; @@ -218,48 +219,48 @@ bool SdesNegotiator::negotiate (void) bool negotiationSuccess = false; try { - + while (!negotiationSuccess && (iter_offer != cryptoAttributeVector.end())) { - /* - std::cout << "Negotiate tag: " + (*iter_offer)->getTag() << std::endl; - std::cout << "Crypto Suite: " + (*iter_offer)->getCryptoSuite() << std::endl; - std::cout << "SRTP Key Method: " + (*iter_offer)->getSrtpKeyMethod() << std::endl; - std::cout << "SRTP Key Info: " + (*iter_offer)->getSrtpKeyInfo() << std::endl; - std::cout << "Lifetime: " + (*iter_offer)->getLifetime() << std::endl; - std::cout << "MKI Value: " + (*iter_offer)->getMkiValue() << std::endl; - std::cout << "MKI Length: " + (*iter_offer)->getMkiLength() << std::endl; - */ + /* + std::cout << "Negotiate tag: " + (*iter_offer)->getTag() << std::endl; + std::cout << "Crypto Suite: " + (*iter_offer)->getCryptoSuite() << std::endl; + std::cout << "SRTP Key Method: " + (*iter_offer)->getSrtpKeyMethod() << std::endl; + std::cout << "SRTP Key Info: " + (*iter_offer)->getSrtpKeyInfo() << std::endl; + std::cout << "Lifetime: " + (*iter_offer)->getLifetime() << std::endl; + std::cout << "MKI Value: " + (*iter_offer)->getMkiValue() << std::endl; + std::cout << "MKI Length: " + (*iter_offer)->getMkiLength() << std::endl; + */ - iter_local = _localCapabilities.begin(); + iter_local = _localCapabilities.begin(); - while(!negotiationSuccess && (iter_local != _localCapabilities.end())) { + while (!negotiationSuccess && (iter_local != _localCapabilities.end())) { - if((*iter_offer)->getCryptoSuite().compare((*iter_local).name)){ + if ( (*iter_offer)->getCryptoSuite().compare ( (*iter_local).name)) { - negotiationSuccess = true; + negotiationSuccess = true; - _cryptoSuite = (*iter_offer)->getCryptoSuite(); - _srtpKeyMethod = (*iter_offer)->getSrtpKeyMethod(); - _srtpKeyInfo = (*iter_offer)->getSrtpKeyInfo(); - _lifetime = (*iter_offer)->getLifetime(); - _mkiValue = (*iter_offer)->getMkiValue(); - _mkiLength = (*iter_offer)->getMkiLength(); - } + _cryptoSuite = (*iter_offer)->getCryptoSuite(); + _srtpKeyMethod = (*iter_offer)->getSrtpKeyMethod(); + _srtpKeyInfo = (*iter_offer)->getSrtpKeyInfo(); + _lifetime = (*iter_offer)->getLifetime(); + _mkiValue = (*iter_offer)->getMkiValue(); + _mkiLength = (*iter_offer)->getMkiLength(); + } - iter_local++; - } + iter_local++; + } + + delete (*iter_offer); + + iter_offer++; + } - delete (*iter_offer); - - iter_offer++; - } - } catch (parse_error& exception) { return false; } catch (match_error& exception) { return false; } - + return negotiationSuccess; } diff --git a/sflphone-common/src/sip/sdp.cpp b/sflphone-common/src/sip/sdp.cpp index d98386916c9f50af296138a35eb7b8d7e0b150a7..65f05626c6149e57b12b80fb63c52b8175b3adeb 100644 --- a/sflphone-common/src/sip/sdp.cpp +++ b/sflphone-common/src/sip/sdp.cpp @@ -63,11 +63,12 @@ Sdp::Sdp (pj_pool_t *pool) Sdp::~Sdp() { - // clean_session_media(); - // clean_local_media_capabilities(); + // clean_session_media(); + // clean_local_media_capabilities(); } -void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) { +void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) +{ pjmedia_sdp_media* med; pjmedia_sdp_rtpmap rtpmap; @@ -85,11 +86,10 @@ void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) med->desc.port = media->get_port(); // in case of sdes, media are tagged as "RTP/SAVP", RTP/AVP elsewhere - if(_srtp_crypto.empty()) { - + if (_srtp_crypto.empty()) { + pj_strdup (_pool, &med->desc.transport, &STR_RTP_AVP); - } - else { + } else { pj_strdup (_pool, &med->desc.transport, &STR_RTP_SAVP); } @@ -114,11 +114,10 @@ void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) rtpmap.enc_name = pj_str ( (char*) codec->getCodecName().c_str()); // G722 require G722/8000 media description even if it is 16000 codec - if(codec->getPayload () == 9) { - rtpmap.clock_rate = 8000; - } - else { - rtpmap.clock_rate = codec->getClockRate(); + if (codec->getPayload () == 9) { + rtpmap.clock_rate = 8000; + } else { + rtpmap.clock_rate = codec->getClockRate(); } // Add the channel number only if different from 1 @@ -152,11 +151,12 @@ void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) *p_med = med; } -int Sdp::create_local_offer (CodecOrder selectedCodecs) { +int Sdp::create_local_offer (CodecOrder selectedCodecs) +{ pj_status_t status; - _info("SDP: Create local offer"); + _info ("SDP: Create local offer"); // Build local media capabilities set_local_media_capabilities (selectedCodecs); @@ -175,8 +175,8 @@ int Sdp::create_local_offer (CodecOrder selectedCodecs) { sdp_add_timing(); sdp_add_media_description(); - if(!_srtp_crypto.empty()) { - sdp_add_sdes_attribute(_srtp_crypto); + if (!_srtp_crypto.empty()) { + sdp_add_sdes_attribute (_srtp_crypto); } //toString (); @@ -190,12 +190,13 @@ int Sdp::create_local_offer (CodecOrder selectedCodecs) { return PJ_SUCCESS; } -int Sdp::create_initial_offer (CodecOrder selectedCodecs) { +int Sdp::create_initial_offer (CodecOrder selectedCodecs) +{ pj_status_t status; pjmedia_sdp_neg_state state; - _info("SDP: Create initial offer"); + _info ("SDP: Create initial offer"); // Build the SDP session descriptor status = create_local_offer (selectedCodecs); @@ -219,16 +220,17 @@ int Sdp::create_initial_offer (CodecOrder selectedCodecs) { return PJ_SUCCESS; } -int Sdp::receiving_initial_offer (pjmedia_sdp_session* remote, CodecOrder selectedCodecs) { +int Sdp::receiving_initial_offer (pjmedia_sdp_session* remote, CodecOrder selectedCodecs) +{ // Create the SDP negociator instance by calling // pjmedia_sdp_neg_create_w_remote_offer with the remote offer, and by providing the local offer ( optional ) pj_status_t status; - if (!remote) { - return !PJ_SUCCESS; - } + if (!remote) { + return !PJ_SUCCESS; + } // Create the SDP negociator instance by calling // pjmedia_sdp_neg_create_w_remote_offer with the remote offer, and by providing the local offer ( optional ) @@ -237,7 +239,7 @@ int Sdp::receiving_initial_offer (pjmedia_sdp_session* remote, CodecOrder select status = create_local_offer (selectedCodecs); if (status != PJ_SUCCESS) { - _error ("SDP: Error: Failed to create initial offer"); + _error ("SDP: Error: Failed to create initial offer"); return status; } @@ -245,14 +247,15 @@ int Sdp::receiving_initial_offer (pjmedia_sdp_session* remote, CodecOrder select this->set_media_transport_info_from_remote_sdp (remote); status = pjmedia_sdp_neg_create_w_remote_offer (_pool, - get_local_sdp_session(), remote, &_negociator); + get_local_sdp_session(), remote, &_negociator); PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); return PJ_SUCCESS; } -pj_status_t Sdp::check_sdp_answer (pjsip_inv_session *inv, pjsip_rx_data *rdata) { +pj_status_t Sdp::check_sdp_answer (pjsip_inv_session *inv, pjsip_rx_data *rdata) +{ static const pj_str_t str_application = { (char*) "application", 11 }; static const pj_str_t str_sdp = { (char*) "sdp", 3 }; @@ -315,12 +318,14 @@ pj_status_t Sdp::check_sdp_answer (pjsip_inv_session *inv, pjsip_rx_data *rdata) return status; } -void Sdp::sdp_add_protocol (void) { +void Sdp::sdp_add_protocol (void) +{ this->_local_offer->origin.version = 0; } -void Sdp::sdp_add_origin (void) { +void Sdp::sdp_add_origin (void) +{ pj_time_val tv; pj_gettimeofday (&tv); @@ -336,13 +341,15 @@ void Sdp::sdp_add_origin (void) { this->_local_offer->origin.addr = pj_str ( (char*) _ip_addr.c_str()); } -void Sdp::sdp_add_session_name (void) { +void Sdp::sdp_add_session_name (void) +{ this->_local_offer->name = STR_SDP_NAME; } -void Sdp::sdp_add_connection_info (void) { +void Sdp::sdp_add_connection_info (void) +{ this->_local_offer->conn->net_type = _local_offer->origin.net_type; this->_local_offer->conn->addr_type = _local_offer->origin.addr_type; @@ -350,7 +357,8 @@ void Sdp::sdp_add_connection_info (void) { } -void Sdp::sdp_add_timing (void) { +void Sdp::sdp_add_timing (void) +{ // RFC 3264: An offer/answer model session description protocol // As the session is created and destroyed through an external signaling mean (SIP), the line @@ -359,7 +367,8 @@ void Sdp::sdp_add_timing (void) { this->_local_offer->time.start = this->_local_offer->time.stop = 0; } -void Sdp::sdp_add_attributes() { +void Sdp::sdp_add_attributes() +{ pjmedia_sdp_attr *a; this->_local_offer->attr_count = 1; @@ -392,37 +401,37 @@ void Sdp::sdp_add_sdes_attribute (std::vector<std::string>& crypto) std::vector<std::string>::iterator iter = crypto.begin(); - while(iter != crypto.end()) { + while (iter != crypto.end()) { // the attribute to add to sdp - pjmedia_sdp_attr *attribute = (pjmedia_sdp_attr*) pj_pool_zalloc(_pool, sizeof(pjmedia_sdp_attr)); + pjmedia_sdp_attr *attribute = (pjmedia_sdp_attr*) pj_pool_zalloc (_pool, sizeof (pjmedia_sdp_attr)); + + attribute->name = pj_strdup3 (_pool, "crypto"); - attribute->name = pj_strdup3(_pool, "crypto"); + // _debug("crypto from sdp: %s", crypto.c_str()); - // _debug("crypto from sdp: %s", crypto.c_str()); - - int len = pj_ansi_snprintf(tempbuf, sizeof(tempbuf), - "%.*s",(int)(*iter).size(), (*iter).c_str()); - - attribute->value.slen = len; - attribute->value.ptr = (char*) pj_pool_alloc (_pool, attribute->value.slen+1); - pj_memcpy (attribute->value.ptr, tempbuf, attribute->value.slen+1); + int len = pj_ansi_snprintf (tempbuf, sizeof (tempbuf), + "%.*s", (int) (*iter).size(), (*iter).c_str()); - // get number of media for this SDP - int media_count = _local_offer->media_count; + attribute->value.slen = len; + attribute->value.ptr = (char*) pj_pool_alloc (_pool, attribute->value.slen+1); + pj_memcpy (attribute->value.ptr, tempbuf, attribute->value.slen+1); - // add crypto attribute to media - for(int i = 0; i < media_count; i++) { + // get number of media for this SDP + int media_count = _local_offer->media_count; - if(pjmedia_sdp_media_add_attr(_local_offer->media[i], attribute) != PJ_SUCCESS) { - // if(pjmedia_sdp_attr_add(&(_local_offer->attr_count), _local_offer->attr, attribute) != PJ_SUCCESS){ - throw sdpException(); - } - } + // add crypto attribute to media + for (int i = 0; i < media_count; i++) { + + if (pjmedia_sdp_media_add_attr (_local_offer->media[i], attribute) != PJ_SUCCESS) { + // if(pjmedia_sdp_attr_add(&(_local_offer->attr_count), _local_offer->attr, attribute) != PJ_SUCCESS){ + throw sdpException(); + } + } - iter++; + iter++; } } @@ -472,39 +481,41 @@ std::string Sdp::media_to_string (void) void Sdp::clean_session_media() { - _info("SDP: Clean session media"); + _info ("SDP: Clean session media"); - if(_session_media.size() > 0) { + if (_session_media.size() > 0) { - std::vector<sdpMedia *>::iterator iter = _session_media.begin(); - sdpMedia *media; + std::vector<sdpMedia *>::iterator iter = _session_media.begin(); + sdpMedia *media; - while(iter != _session_media.end()) { - media = *iter; - delete media; - iter++; - } - _session_media.clear(); - } + while (iter != _session_media.end()) { + media = *iter; + delete media; + iter++; + } + + _session_media.clear(); + } } void Sdp::clean_local_media_capabilities() { - _info("SDP: Clean local media capabilities"); + _info ("SDP: Clean local media capabilities"); - if(_local_media_cap.size() > 0) { + if (_local_media_cap.size() > 0) { - std::vector<sdpMedia *>::iterator iter = _local_media_cap.begin(); - sdpMedia *media; + std::vector<sdpMedia *>::iterator iter = _local_media_cap.begin(); + sdpMedia *media; - while(iter != _local_media_cap.end()) { - media = *iter; - delete media; - iter++; - } - _local_media_cap.clear(); - } + while (iter != _local_media_cap.end()) { + media = *iter; + delete media; + iter++; + } + + _local_media_cap.clear(); + } } void Sdp::set_negotiated_sdp (const pjmedia_sdp_session *sdp) @@ -584,16 +595,15 @@ AudioCodec* Sdp::get_session_media (void) pj_status_t Sdp::start_negociation() { - pj_status_t status; + pj_status_t status; - if (_negociator) { - status = pjmedia_sdp_neg_negotiate(_pool, _negociator, 0); - } - else { - status = !PJ_SUCCESS; - } + if (_negociator) { + status = pjmedia_sdp_neg_negotiate (_pool, _negociator, 0); + } else { + status = !PJ_SUCCESS; + } - return status; + return status; } void Sdp::toString (void) @@ -633,7 +643,8 @@ void Sdp::toString (void) _debug ("LOCAL SDP: \n%s", sdp.str().c_str()); } -void Sdp::set_local_media_capabilities (CodecOrder selectedCodecs) { +void Sdp::set_local_media_capabilities (CodecOrder selectedCodecs) +{ unsigned int i; sdpMedia *audio; @@ -657,11 +668,10 @@ void Sdp::set_local_media_capabilities (CodecOrder selectedCodecs) { if (iter!=codecs_list.end()) { audio->add_codec (iter->second); + } else { + _warn ("SDP: Couldn't find audio codec"); } - else { - _warn ("SDP: Couldn't find audio codec"); - } - } + } _local_media_cap.push_back (audio); } @@ -712,8 +722,8 @@ void Sdp::set_media_transport_info_from_remote_sdp (const pjmedia_sdp_session *r _info ("SDP: Fetching media from sdp"); - if(!remote_sdp) - return; + if (!remote_sdp) + return; pjmedia_sdp_media *r_media; @@ -734,8 +744,8 @@ void Sdp::get_remote_sdp_media_from_offer (const pjmedia_sdp_session* remote_sdp { int count, i; - if(!remote_sdp) - return; + if (!remote_sdp) + return; count = remote_sdp->media_count; *r_media = NULL; @@ -764,31 +774,31 @@ void Sdp::get_remote_sdp_crypto_from_offer (const pjmedia_sdp_session* remote_sd // iterate over all media for (i = 0; i < media_count; ++i) { - // get media - media = remote_sdp->media[i]; + // get media + media = remote_sdp->media[i]; - // get number of attribute for this memdia - attr_count = media->attr_count; + // get number of attribute for this memdia + attr_count = media->attr_count; - // iterate over all attribute for this media - for(j = 0; j < attr_count; j++) { + // iterate over all attribute for this media + for (j = 0; j < attr_count; j++) { - attribute = media->attr[j]; + attribute = media->attr[j]; - // test if this attribute is a crypto - if (pj_stricmp2 (&attribute->name, "crypto") == 0) { + // test if this attribute is a crypto + if (pj_stricmp2 (&attribute->name, "crypto") == 0) { - std::string attr(attribute->value.ptr, attribute->value.slen); + std::string attr (attribute->value.ptr, attribute->value.slen); - // @TODO our parser require the "a=crypto:" to be present - std::string full_attr = "a=crypto:"; - full_attr += attr; + // @TODO our parser require the "a=crypto:" to be present + std::string full_attr = "a=crypto:"; + full_attr += attr; - crypto_offer.push_back(full_attr); - } + crypto_offer.push_back (full_attr); + } - } + } } - + } diff --git a/sflphone-common/src/sip/sdpmedia.cpp b/sflphone-common/src/sip/sdpmedia.cpp index 95955a51db652bc9ebd92c553589e7d82a563a77..3b7c7c39f1fb7d87df70450a6b47c5241cde370f 100644 --- a/sflphone-common/src/sip/sdpmedia.cpp +++ b/sflphone-common/src/sip/sdpmedia.cpp @@ -85,7 +85,7 @@ sdpMedia::sdpMedia (std::string type, int port, std::string dir) sdpMedia::~sdpMedia() { - clear_codec_list(); + clear_codec_list(); } diff --git a/sflphone-common/src/sip/sipaccount.cpp b/sflphone-common/src/sip/sipaccount.cpp old mode 100755 new mode 100644 index 6c30a0d5fd3abece237d4bb8d8932fa1698a0ff6..39e201cdeaba161f48ff2feb89134ca7934f6cb5 --- a/sflphone-common/src/sip/sipaccount.cpp +++ b/sflphone-common/src/sip/sipaccount.cpp @@ -36,57 +36,61 @@ #include <pwd.h> #include <sstream> -Credentials::Credentials() : credentialCount(0) {} +Credentials::Credentials() : credentialCount (0) {} Credentials::~Credentials() {} -void Credentials::setNewCredential(std::string username, std::string password, std::string realm) +void Credentials::setNewCredential (std::string username, std::string password, std::string realm) { - credentialArray[credentialCount].username = username; - credentialArray[credentialCount].password = password; - credentialArray[credentialCount].realm = realm; + credentialArray[credentialCount].username = username; + credentialArray[credentialCount].password = password; + credentialArray[credentialCount].realm = realm; } -CredentialItem *Credentials::getCredential(int index) -{ - if((index >= 0) && (index < credentialCount)) - return &(credentialArray[index]); - else - return NULL; +CredentialItem *Credentials::getCredential (int index) +{ + if ( (index >= 0) && (index < credentialCount)) + return & (credentialArray[index]); + else + return NULL; } -void Credentials::serialize(Conf::YamlEmitter *emitter UNUSED) +void Credentials::serialize (Conf::YamlEmitter *emitter UNUSED) { - + } -void Credentials::unserialize(Conf::MappingNode *map) +void Credentials::unserialize (Conf::MappingNode *map) { - Conf::ScalarNode *val = NULL; + Conf::ScalarNode *val = NULL; - _debug("SipAccount: Unserialize"); + _debug ("SipAccount: Unserialize"); - val = (Conf::ScalarNode *)(map->getValue(credentialCountKey)); - if(val) { credentialCount = atoi(val->getValue().data()); val = NULL; } + val = (Conf::ScalarNode *) (map->getValue (credentialCountKey)); + + if (val) { + credentialCount = atoi (val->getValue().data()); + val = NULL; + } } SIPAccount::SIPAccount (const AccountID& accountID) : Account (accountID, "SIP") - , _routeSet("") + , _routeSet ("") , _regc (NULL) , _bRegister (false) , _registrationExpire ("") - , _interface("default") + , _interface ("default") , _publishedSameasLocal (true) , _publishedIpAddress ("") , _localPort (atoi (DEFAULT_SIP_PORT)) , _publishedPort (atoi (DEFAULT_SIP_PORT)) - , _serviceRoute("") - , _tlsListenerPort (atoi (DEFAULT_SIP_TLS_PORT)) + , _serviceRoute ("") + , _tlsListenerPort (atoi (DEFAULT_SIP_TLS_PORT)) , _transportType (PJSIP_TRANSPORT_UNSPECIFIED) , _transport (NULL) , _resolveOnce (false) @@ -94,40 +98,40 @@ SIPAccount::SIPAccount (const AccountID& accountID) , _realm (DEFAULT_REALM) , _authenticationUsername ("") , _tlsSetting (NULL) - , _dtmfType(OVERRTP) - , _tlsEnable("") - , _tlsPortStr(DEFAULT_SIP_TLS_PORT) - , _tlsCaListFile("") - , _tlsCertificateFile("") - , _tlsPrivateKeyFile("") - , _tlsPassword("") - , _tlsMethod("TLSv1") - , _tlsCiphers("") - , _tlsServerName("") - , _tlsVerifyServer(true) - , _tlsVerifyClient(true) - , _tlsRequireClientCertificate(true) - , _tlsNegotiationTimeoutSec("2") - , _tlsNegotiationTimeoutMsec("0") - , _stunServer(DFT_STUN_SERVER) - , _tlsEnabled(false) - , _stunEnabled(false) - , _srtpEnabled(false) - , _srtpKeyExchange("sdes") - , _srtpFallback(false) - , _zrtpDisplaySas(true) - , _zrtpDisplaySasOnce(false) - , _zrtpHelloHash(true) - , _zrtpNotSuppWarning(true) + , _dtmfType (OVERRTP) + , _tlsEnable ("") + , _tlsPortStr (DEFAULT_SIP_TLS_PORT) + , _tlsCaListFile ("") + , _tlsCertificateFile ("") + , _tlsPrivateKeyFile ("") + , _tlsPassword ("") + , _tlsMethod ("TLSv1") + , _tlsCiphers ("") + , _tlsServerName ("") + , _tlsVerifyServer (true) + , _tlsVerifyClient (true) + , _tlsRequireClientCertificate (true) + , _tlsNegotiationTimeoutSec ("2") + , _tlsNegotiationTimeoutMsec ("0") + , _stunServer (DFT_STUN_SERVER) + , _tlsEnabled (false) + , _stunEnabled (false) + , _srtpEnabled (false) + , _srtpKeyExchange ("sdes") + , _srtpFallback (false) + , _zrtpDisplaySas (true) + , _zrtpDisplaySasOnce (false) + , _zrtpHelloHash (true) + , _zrtpNotSuppWarning (true) { - - _debug("Sip account constructor called"); - + + _debug ("Sip account constructor called"); + _stunServerName.ptr = NULL; _stunServerName.slen = 0; _stunPort = 0; - // IP2IP settings must be loaded before singleton instanciation, cannot call it here... + // IP2IP settings must be loaded before singleton instanciation, cannot call it here... // _link = SIPVoIPLink::instance (""); @@ -139,8 +143,8 @@ SIPAccount::SIPAccount (const AccountID& accountID) SIPAccount::~SIPAccount() { /* One SIP account less connected to the sip voiplink */ - if(_accountID != "default") - dynamic_cast<SIPVoIPLink*> (_link)->decrementClients(); + if (_accountID != "default") + dynamic_cast<SIPVoIPLink*> (_link)->decrementClients(); /* Delete accounts-related information */ _regc = NULL; @@ -148,558 +152,773 @@ SIPAccount::~SIPAccount() free (_tlsSetting); } -void SIPAccount::serialize(Conf::YamlEmitter *emitter) { - - _debug("SipAccount: serialize %s", _accountID.c_str()); - - - Conf::MappingNode accountmap(NULL); - Conf::MappingNode credentialmap(NULL); - Conf::MappingNode srtpmap(NULL); - Conf::MappingNode zrtpmap(NULL); - Conf::MappingNode tlsmap(NULL); - - Conf::ScalarNode id(Account::_accountID); - Conf::ScalarNode username(Account::_username); - Conf::ScalarNode password(Account::_password); - Conf::ScalarNode alias(Account::_alias); - Conf::ScalarNode hostname(Account::_hostname); - Conf::ScalarNode enable(_enabled ? "true" : "false"); - Conf::ScalarNode type(Account::_type); - Conf::ScalarNode expire(_registrationExpire); - Conf::ScalarNode interface(_interface); - std::stringstream portstr; portstr << _localPort; - Conf::ScalarNode port(portstr.str()); - Conf::ScalarNode serviceRoute(_serviceRoute); - - Conf::ScalarNode mailbox("97"); - Conf::ScalarNode publishAddr(_publishedIpAddress); - std::stringstream publicportstr; publicportstr << _publishedPort; - Conf::ScalarNode publishPort(publicportstr.str()); - Conf::ScalarNode sameasLocal(_publishedSameasLocal ? "true" : "false"); - Conf::ScalarNode resolveOnce(_resolveOnce ? "true" : "false"); - Conf::ScalarNode codecs(_codecStr); - Conf::ScalarNode ringtonePath(_ringtonePath); - Conf::ScalarNode ringtoneEnabled(_ringtoneEnabled ? "true" : "false"); - Conf::ScalarNode stunServer(_stunServer); - Conf::ScalarNode stunEnabled(_stunEnabled ? "true" : "false"); - Conf::ScalarNode displayName(_displayName); - Conf::ScalarNode dtmfType(_dtmfType==0 ? "overrtp" : "sipinfo"); - - std::stringstream countstr; countstr << 0; - Conf::ScalarNode count(countstr.str()); - - Conf::ScalarNode srtpenabled(_srtpEnabled ? "true" : "false"); - Conf::ScalarNode keyExchange(_srtpKeyExchange); - Conf::ScalarNode rtpFallback(_srtpFallback ? "true" : "false"); - - Conf::ScalarNode displaySas(_zrtpDisplaySas ? "true" : "false"); - Conf::ScalarNode displaySasOnce(_zrtpDisplaySasOnce ? "true" : "false"); - Conf::ScalarNode helloHashEnabled(_zrtpHelloHash ? "true" : "false"); - Conf::ScalarNode notSuppWarning(_zrtpNotSuppWarning ? "true" : "false"); - - Conf::ScalarNode tlsport(_tlsPortStr); - Conf::ScalarNode certificate(_tlsCertificateFile); - Conf::ScalarNode calist(_tlsCaListFile); - Conf::ScalarNode ciphers(_tlsCiphers); - Conf::ScalarNode tlsenabled(_tlsEnable); - Conf::ScalarNode tlsmethod(_tlsMethod); - Conf::ScalarNode timeout(_tlsNegotiationTimeoutSec); - Conf::ScalarNode tlspassword(_tlsPassword); - Conf::ScalarNode privatekey(_tlsPrivateKeyFile); - Conf::ScalarNode requirecertif(_tlsRequireClientCertificate ? "true" : "false"); - Conf::ScalarNode server(_tlsServerName); - Conf::ScalarNode verifyclient(_tlsVerifyServer ? "true" : "false"); - Conf::ScalarNode verifyserver(_tlsVerifyClient ? "true" : "false"); - - accountmap.setKeyValue(aliasKey, &alias); - accountmap.setKeyValue(typeKey, &type); - accountmap.setKeyValue(idKey, &id); - accountmap.setKeyValue(usernameKey, &username); - accountmap.setKeyValue(passwordKey, &password); - accountmap.setKeyValue(hostnameKey, &hostname); - accountmap.setKeyValue(accountEnableKey, &enable); - accountmap.setKeyValue(mailboxKey, &mailbox); - accountmap.setKeyValue(expireKey, &expire); - accountmap.setKeyValue(interfaceKey, &interface); - accountmap.setKeyValue(portKey, &port); - accountmap.setKeyValue(stunServerKey, &stunServer); - accountmap.setKeyValue(stunEnabledKey, &stunEnabled); - accountmap.setKeyValue(publishAddrKey, &publishAddr); - accountmap.setKeyValue(publishPortKey, &publishPort); - accountmap.setKeyValue(sameasLocalKey, &sameasLocal); - accountmap.setKeyValue(resolveOnceKey, &resolveOnce); - accountmap.setKeyValue(serviceRouteKey, &serviceRoute); - accountmap.setKeyValue(dtmfTypeKey, &dtmfType); - accountmap.setKeyValue(displayNameKey, &displayName); - accountmap.setKeyValue(codecsKey, &codecs); - accountmap.setKeyValue(ringtonePathKey, &ringtonePath); - accountmap.setKeyValue(ringtoneEnabledKey, &ringtoneEnabled); - - accountmap.setKeyValue(srtpKey, &srtpmap); - srtpmap.setKeyValue(srtpEnableKey, &srtpenabled); - srtpmap.setKeyValue(keyExchangeKey, &keyExchange); - srtpmap.setKeyValue(rtpFallbackKey, &rtpFallback); - - accountmap.setKeyValue(zrtpKey, &zrtpmap); - zrtpmap.setKeyValue(displaySasKey, &displaySas); - zrtpmap.setKeyValue(displaySasOnceKey, &displaySasOnce); - zrtpmap.setKeyValue(helloHashEnabledKey, &helloHashEnabled); - zrtpmap.setKeyValue(notSuppWarningKey, ¬SuppWarning); - - accountmap.setKeyValue(credKey, &credentialmap); - credentialmap.setKeyValue(credentialCountKey, &count); - - accountmap.setKeyValue(tlsKey, &tlsmap); - tlsmap.setKeyValue(tlsPortKey, &tlsport); - tlsmap.setKeyValue(certificateKey, &certificate); - tlsmap.setKeyValue(calistKey, &calist); - tlsmap.setKeyValue(ciphersKey, &ciphers); - tlsmap.setKeyValue(tlsEnableKey, &tlsenabled); - tlsmap.setKeyValue(methodKey, &tlsmethod); - tlsmap.setKeyValue(timeoutKey, &timeout); - tlsmap.setKeyValue(tlsPasswordKey, &tlspassword); - tlsmap.setKeyValue(privateKeyKey, &privatekey); - tlsmap.setKeyValue(requireCertifKey, &requirecertif); - tlsmap.setKeyValue(serverKey, &server); - tlsmap.setKeyValue(verifyClientKey, &verifyclient); - tlsmap.setKeyValue(verifyServerKey, &verifyserver); - - try{ - emitter->serializeAccount(&accountmap); - } - catch (Conf::YamlEmitterException &e) { - _error("ConfigTree: %s", e.what()); - } +void SIPAccount::serialize (Conf::YamlEmitter *emitter) +{ + + _debug ("SipAccount: serialize %s", _accountID.c_str()); + + + Conf::MappingNode accountmap (NULL); + Conf::MappingNode credentialmap (NULL); + Conf::MappingNode srtpmap (NULL); + Conf::MappingNode zrtpmap (NULL); + Conf::MappingNode tlsmap (NULL); + + Conf::ScalarNode id (Account::_accountID); + Conf::ScalarNode username (Account::_username); + Conf::ScalarNode password (Account::_password); + Conf::ScalarNode alias (Account::_alias); + Conf::ScalarNode hostname (Account::_hostname); + Conf::ScalarNode enable (_enabled ? "true" : "false"); + Conf::ScalarNode type (Account::_type); + Conf::ScalarNode expire (_registrationExpire); + Conf::ScalarNode interface (_interface); + std::stringstream portstr; + portstr << _localPort; + Conf::ScalarNode port (portstr.str()); + Conf::ScalarNode serviceRoute (_serviceRoute); + + Conf::ScalarNode mailbox ("97"); + Conf::ScalarNode publishAddr (_publishedIpAddress); + std::stringstream publicportstr; + publicportstr << _publishedPort; + Conf::ScalarNode publishPort (publicportstr.str()); + Conf::ScalarNode sameasLocal (_publishedSameasLocal ? "true" : "false"); + Conf::ScalarNode resolveOnce (_resolveOnce ? "true" : "false"); + Conf::ScalarNode codecs (_codecStr); + Conf::ScalarNode ringtonePath (_ringtonePath); + Conf::ScalarNode ringtoneEnabled (_ringtoneEnabled ? "true" : "false"); + Conf::ScalarNode stunServer (_stunServer); + Conf::ScalarNode stunEnabled (_stunEnabled ? "true" : "false"); + Conf::ScalarNode displayName (_displayName); + Conf::ScalarNode dtmfType (_dtmfType==0 ? "overrtp" : "sipinfo"); + + std::stringstream countstr; + countstr << 0; + Conf::ScalarNode count (countstr.str()); + + Conf::ScalarNode srtpenabled (_srtpEnabled ? "true" : "false"); + Conf::ScalarNode keyExchange (_srtpKeyExchange); + Conf::ScalarNode rtpFallback (_srtpFallback ? "true" : "false"); + + Conf::ScalarNode displaySas (_zrtpDisplaySas ? "true" : "false"); + Conf::ScalarNode displaySasOnce (_zrtpDisplaySasOnce ? "true" : "false"); + Conf::ScalarNode helloHashEnabled (_zrtpHelloHash ? "true" : "false"); + Conf::ScalarNode notSuppWarning (_zrtpNotSuppWarning ? "true" : "false"); + + Conf::ScalarNode tlsport (_tlsPortStr); + Conf::ScalarNode certificate (_tlsCertificateFile); + Conf::ScalarNode calist (_tlsCaListFile); + Conf::ScalarNode ciphers (_tlsCiphers); + Conf::ScalarNode tlsenabled (_tlsEnable); + Conf::ScalarNode tlsmethod (_tlsMethod); + Conf::ScalarNode timeout (_tlsNegotiationTimeoutSec); + Conf::ScalarNode tlspassword (_tlsPassword); + Conf::ScalarNode privatekey (_tlsPrivateKeyFile); + Conf::ScalarNode requirecertif (_tlsRequireClientCertificate ? "true" : "false"); + Conf::ScalarNode server (_tlsServerName); + Conf::ScalarNode verifyclient (_tlsVerifyServer ? "true" : "false"); + Conf::ScalarNode verifyserver (_tlsVerifyClient ? "true" : "false"); + + accountmap.setKeyValue (aliasKey, &alias); + accountmap.setKeyValue (typeKey, &type); + accountmap.setKeyValue (idKey, &id); + accountmap.setKeyValue (usernameKey, &username); + accountmap.setKeyValue (passwordKey, &password); + accountmap.setKeyValue (hostnameKey, &hostname); + accountmap.setKeyValue (accountEnableKey, &enable); + accountmap.setKeyValue (mailboxKey, &mailbox); + accountmap.setKeyValue (expireKey, &expire); + accountmap.setKeyValue (interfaceKey, &interface); + accountmap.setKeyValue (portKey, &port); + accountmap.setKeyValue (stunServerKey, &stunServer); + accountmap.setKeyValue (stunEnabledKey, &stunEnabled); + accountmap.setKeyValue (publishAddrKey, &publishAddr); + accountmap.setKeyValue (publishPortKey, &publishPort); + accountmap.setKeyValue (sameasLocalKey, &sameasLocal); + accountmap.setKeyValue (resolveOnceKey, &resolveOnce); + accountmap.setKeyValue (serviceRouteKey, &serviceRoute); + accountmap.setKeyValue (dtmfTypeKey, &dtmfType); + accountmap.setKeyValue (displayNameKey, &displayName); + accountmap.setKeyValue (codecsKey, &codecs); + accountmap.setKeyValue (ringtonePathKey, &ringtonePath); + accountmap.setKeyValue (ringtoneEnabledKey, &ringtoneEnabled); + + accountmap.setKeyValue (srtpKey, &srtpmap); + srtpmap.setKeyValue (srtpEnableKey, &srtpenabled); + srtpmap.setKeyValue (keyExchangeKey, &keyExchange); + srtpmap.setKeyValue (rtpFallbackKey, &rtpFallback); + + accountmap.setKeyValue (zrtpKey, &zrtpmap); + zrtpmap.setKeyValue (displaySasKey, &displaySas); + zrtpmap.setKeyValue (displaySasOnceKey, &displaySasOnce); + zrtpmap.setKeyValue (helloHashEnabledKey, &helloHashEnabled); + zrtpmap.setKeyValue (notSuppWarningKey, ¬SuppWarning); + + accountmap.setKeyValue (credKey, &credentialmap); + credentialmap.setKeyValue (credentialCountKey, &count); + + accountmap.setKeyValue (tlsKey, &tlsmap); + tlsmap.setKeyValue (tlsPortKey, &tlsport); + tlsmap.setKeyValue (certificateKey, &certificate); + tlsmap.setKeyValue (calistKey, &calist); + tlsmap.setKeyValue (ciphersKey, &ciphers); + tlsmap.setKeyValue (tlsEnableKey, &tlsenabled); + tlsmap.setKeyValue (methodKey, &tlsmethod); + tlsmap.setKeyValue (timeoutKey, &timeout); + tlsmap.setKeyValue (tlsPasswordKey, &tlspassword); + tlsmap.setKeyValue (privateKeyKey, &privatekey); + tlsmap.setKeyValue (requireCertifKey, &requirecertif); + tlsmap.setKeyValue (serverKey, &server); + tlsmap.setKeyValue (verifyClientKey, &verifyclient); + tlsmap.setKeyValue (verifyServerKey, &verifyserver); + + try { + emitter->serializeAccount (&accountmap); + } catch (Conf::YamlEmitterException &e) { + _error ("ConfigTree: %s", e.what()); + } } -void SIPAccount::unserialize(Conf::MappingNode *map) +void SIPAccount::unserialize (Conf::MappingNode *map) { - Conf::ScalarNode *val; - Conf::MappingNode *srtpMap; - Conf::MappingNode *tlsMap; - Conf::MappingNode *zrtpMap; - Conf::MappingNode *credMap; - - _debug("SipAccount: Unserialize %s", _accountID.c_str()); - - val = (Conf::ScalarNode *)(map->getValue(aliasKey)); - if(val) { _alias = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(typeKey)); - if(val) { _type = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(idKey)); - if(val) { _accountID = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(usernameKey)); - if(val) { _username = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(passwordKey)); - if(val) { _password = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(hostnameKey)); - if(val) { _hostname = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(accountEnableKey)); - if(val) { _enabled = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); - - val = (Conf::ScalarNode *)(map->getValue(codecsKey)); - if(val) { _codecStr = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(ringtonePathKey)); - if(val) { _ringtonePath = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(ringtoneEnabledKey)); - if(val) { _ringtoneEnabled = (val->getValue() == "true") ? true : false; val = NULL; } - - val = (Conf::ScalarNode *)(map->getValue(expireKey)); - if(val) { _registrationExpire = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(interfaceKey)); - if(val) { _interface = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(portKey)); - if(val) { _localPort = atoi(val->getValue().data()); val = NULL; } - // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); - val = (Conf::ScalarNode *)(map->getValue(publishAddrKey)); - if(val) { _publishedIpAddress = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(publishPortKey)); - if(val) { _publishedPort = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(sameasLocalKey)); - if(val) { _publishedSameasLocal = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(resolveOnceKey)); - if(val) { _resolveOnce = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(dtmfTypeKey)); - if(val) { val = NULL; } - // _dtmfType = atoi(val->getValue(); - val = (Conf::ScalarNode *)(map->getValue(serviceRouteKey)); - if(val) { _serviceRoute = val->getValue(); } - - // stun enabled - val = (Conf::ScalarNode *)(map->getValue(stunEnabledKey)); - if(val) { _stunEnabled = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(stunServerKey)); - if(val) { _stunServer = val->getValue(); val = NULL; } - _stunServerName = pj_str ( (char*) _stunServer.data()); - - credMap = (Conf::MappingNode *)(map->getValue(credKey)); - credentials.unserialize(credMap); - - val = (Conf::ScalarNode *)(map->getValue(displayNameKey)); - if(val) { _displayName = val->getValue(); val = NULL; } - - // get srtp submap - srtpMap = (Conf::MappingNode *)(map->getValue(srtpKey)); - if(!srtpMap) - throw SipAccountException(" did not found srtp map"); - - val = (Conf::ScalarNode *)(srtpMap->getValue(srtpEnableKey)); - if(val) { _srtpEnabled = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(srtpMap->getValue(keyExchangeKey)); - if(val) { _srtpKeyExchange = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(srtpMap->getValue(rtpFallbackKey)); - if(val) { _srtpFallback = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - - // get zrtp submap - zrtpMap = (Conf::MappingNode *)(map->getValue(zrtpKey)); - if(!zrtpMap) - throw SipAccountException(" did not found zrtp map"); - - val = (Conf::ScalarNode *)(zrtpMap->getValue(displaySasKey)); - if(val) { _zrtpDisplaySas = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(zrtpMap->getValue(displaySasOnceKey)); - if(val) { _zrtpDisplaySasOnce = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(zrtpMap->getValue(helloHashEnabledKey)); - if(val) { _zrtpHelloHash = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(zrtpMap->getValue(notSuppWarningKey)); - if(val) { _zrtpNotSuppWarning = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - - // get tls submap - tlsMap = (Conf::MappingNode *)(map->getValue(tlsKey)); - if(!tlsMap) - throw SipAccountException(" did not found tls map"); - - val = (Conf::ScalarNode *)(tlsMap->getValue(tlsEnableKey)); - if(val) { _tlsEnable = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(tlsPortKey)); - if(val) { _tlsPortStr = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(certificateKey)); - if(val) { _tlsCertificateFile = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(calistKey)); - if(val) { _tlsCaListFile = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(ciphersKey)); - if(val) { _tlsCiphers = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(methodKey)); - if(val) { _tlsMethod = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(timeoutKey)); - if(val) _tlsNegotiationTimeoutSec = val->getValue(); - if(val) { _tlsNegotiationTimeoutMsec = val->getValue(); val=NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(tlsPasswordKey)); - if(val) { _tlsPassword = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(privateKeyKey)); - if(val) { _tlsPrivateKeyFile = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(requireCertifKey)); - if(val) { _tlsRequireClientCertificate = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(serverKey)); - if(val) { _tlsServerName = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(verifyClientKey)); - if(val) { _tlsVerifyServer = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(verifyServerKey)); - if(val) { _tlsVerifyClient = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } + Conf::ScalarNode *val; + Conf::MappingNode *srtpMap; + Conf::MappingNode *tlsMap; + Conf::MappingNode *zrtpMap; + Conf::MappingNode *credMap; + + _debug ("SipAccount: Unserialize %s", _accountID.c_str()); + + val = (Conf::ScalarNode *) (map->getValue (aliasKey)); + + if (val) { + _alias = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (typeKey)); + + if (val) { + _type = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (idKey)); + + if (val) { + _accountID = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (usernameKey)); + + if (val) { + _username = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (passwordKey)); + + if (val) { + _password = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (hostnameKey)); + + if (val) { + _hostname = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (accountEnableKey)); + + if (val) { + _enabled = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); + + val = (Conf::ScalarNode *) (map->getValue (codecsKey)); + + if (val) { + _codecStr = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (ringtonePathKey)); + + if (val) { + _ringtonePath = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (ringtoneEnabledKey)); + + if (val) { + _ringtoneEnabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (expireKey)); + + if (val) { + _registrationExpire = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (interfaceKey)); + + if (val) { + _interface = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (portKey)); + + if (val) { + _localPort = atoi (val->getValue().data()); + val = NULL; + } + + // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); + val = (Conf::ScalarNode *) (map->getValue (publishAddrKey)); + + if (val) { + _publishedIpAddress = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (publishPortKey)); + + if (val) { + _publishedPort = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (sameasLocalKey)); + + if (val) { + _publishedSameasLocal = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (resolveOnceKey)); + + if (val) { + _resolveOnce = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (dtmfTypeKey)); + + if (val) { + val = NULL; + } + + // _dtmfType = atoi(val->getValue(); + val = (Conf::ScalarNode *) (map->getValue (serviceRouteKey)); + + if (val) { + _serviceRoute = val->getValue(); + } + + // stun enabled + val = (Conf::ScalarNode *) (map->getValue (stunEnabledKey)); + + if (val) { + _stunEnabled = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (stunServerKey)); + + if (val) { + _stunServer = val->getValue(); + val = NULL; + } + + _stunServerName = pj_str ( (char*) _stunServer.data()); + + credMap = (Conf::MappingNode *) (map->getValue (credKey)); + credentials.unserialize (credMap); + + val = (Conf::ScalarNode *) (map->getValue (displayNameKey)); + + if (val) { + _displayName = val->getValue(); + val = NULL; + } + + // get srtp submap + srtpMap = (Conf::MappingNode *) (map->getValue (srtpKey)); + + if (!srtpMap) + throw SipAccountException (" did not found srtp map"); + + val = (Conf::ScalarNode *) (srtpMap->getValue (srtpEnableKey)); + + if (val) { + _srtpEnabled = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (srtpMap->getValue (keyExchangeKey)); + + if (val) { + _srtpKeyExchange = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (srtpMap->getValue (rtpFallbackKey)); + + if (val) { + _srtpFallback = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + // get zrtp submap + zrtpMap = (Conf::MappingNode *) (map->getValue (zrtpKey)); + + if (!zrtpMap) + throw SipAccountException (" did not found zrtp map"); + + val = (Conf::ScalarNode *) (zrtpMap->getValue (displaySasKey)); + + if (val) { + _zrtpDisplaySas = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (zrtpMap->getValue (displaySasOnceKey)); + + if (val) { + _zrtpDisplaySasOnce = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (zrtpMap->getValue (helloHashEnabledKey)); + + if (val) { + _zrtpHelloHash = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (zrtpMap->getValue (notSuppWarningKey)); + + if (val) { + _zrtpNotSuppWarning = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + // get tls submap + tlsMap = (Conf::MappingNode *) (map->getValue (tlsKey)); + + if (!tlsMap) + throw SipAccountException (" did not found tls map"); + + val = (Conf::ScalarNode *) (tlsMap->getValue (tlsEnableKey)); + + if (val) { + _tlsEnable = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (tlsPortKey)); + + if (val) { + _tlsPortStr = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (certificateKey)); + + if (val) { + _tlsCertificateFile = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (calistKey)); + + if (val) { + _tlsCaListFile = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (ciphersKey)); + + if (val) { + _tlsCiphers = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (methodKey)); + + if (val) { + _tlsMethod = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (timeoutKey)); + + if (val) _tlsNegotiationTimeoutSec = val->getValue(); + + if (val) { + _tlsNegotiationTimeoutMsec = val->getValue(); + val=NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (tlsPasswordKey)); + + if (val) { + _tlsPassword = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (privateKeyKey)); + + if (val) { + _tlsPrivateKeyFile = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (requireCertifKey)); + + if (val) { + _tlsRequireClientCertificate = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (serverKey)); + + if (val) { + _tlsServerName = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (verifyClientKey)); + + if (val) { + _tlsVerifyServer = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (verifyServerKey)); + + if (val) { + _tlsVerifyClient = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } } -void SIPAccount::setAccountDetails(const std::map<std::string, std::string>& details) +void SIPAccount::setAccountDetails (const std::map<std::string, std::string>& details) { - std::map<std::string, std::string> map_cpy; - std::map<std::string, std::string>::iterator iter; - - _debug("SipAccount: set account details %s", _accountID.c_str()); - - // Work on a copy - map_cpy = details; - - std::string alias; - std::string type; - std::string hostname; - std::string username; - std::string password; - std::string mailbox; - std::string accountEnable; - std::string ringtonePath; - std::string ringtoneEnabled; - - // Account setting common to SIP and IAX - find_in_map(CONFIG_ACCOUNT_ALIAS, alias) - find_in_map(CONFIG_ACCOUNT_TYPE, type) - find_in_map(HOSTNAME, hostname) - find_in_map(USERNAME, username) - find_in_map(PASSWORD, password) - find_in_map(CONFIG_ACCOUNT_MAILBOX, mailbox); - find_in_map(CONFIG_ACCOUNT_ENABLE, accountEnable); - find_in_map(CONFIG_RINGTONE_PATH, ringtonePath); - find_in_map(CONFIG_RINGTONE_ENABLED, ringtoneEnabled); - - setAlias(alias); - setType(type); - setUsername(username); - setHostname(hostname); - setPassword(password); - setEnabled((accountEnable == "true")); - setRingtonePath(ringtonePath); - setRingtoneEnabled((ringtoneEnabled == "true")); - - // SIP specific account settings - if(getType() == "SIP") { - - std::string ua_name; - std::string realm; - std::string routeset; - std::string authenticationName; - - std::string resolveOnce; - std::string registrationExpire; - - std::string displayName; - std::string localInterface; - std::string publishedSameasLocal; - std::string localAddress; - std::string publishedAddress; - std::string localPort; - std::string publishedPort; - std::string stunEnable; - std::string stunServer; - std::string dtmfType; - std::string srtpEnable; - std::string srtpRtpFallback; - std::string zrtpDisplaySas; - std::string zrtpDisplaySasOnce; - std::string zrtpNotSuppWarning; - std::string zrtpHelloHash; - std::string srtpKeyExchange; - - std::string tlsListenerPort; - std::string tlsEnable; - std::string tlsCaListFile; - std::string tlsCertificateFile; - std::string tlsPrivateKeyFile; - std::string tlsPassword; - std::string tlsMethod; - std::string tlsCiphers; - std::string tlsServerName; - std::string tlsVerifyServer; - std::string tlsVerifyClient; - std::string tlsRequireClientCertificate; - std::string tlsNegotiationTimeoutSec; - std::string tlsNegotiationTimeoutMsec; - - // general sip settings - find_in_map(DISPLAY_NAME, displayName) - find_in_map(ROUTESET, routeset) - find_in_map(LOCAL_INTERFACE, localInterface) - find_in_map(PUBLISHED_SAMEAS_LOCAL, publishedSameasLocal) - find_in_map(PUBLISHED_ADDRESS, publishedAddress) - find_in_map(LOCAL_PORT, localPort) - find_in_map(PUBLISHED_PORT, publishedPort) - find_in_map(STUN_ENABLE, stunEnable) - find_in_map(STUN_SERVER, stunServer) - find_in_map(ACCOUNT_DTMF_TYPE, dtmfType) - find_in_map(CONFIG_ACCOUNT_RESOLVE_ONCE, resolveOnce) - find_in_map(CONFIG_ACCOUNT_REGISTRATION_EXPIRE, registrationExpire) - - setDisplayName(displayName); - setServiceRoute(routeset); - setLocalInterface(localInterface); - setPublishedSameasLocal((publishedSameasLocal.compare("true") == 0) ? true : false); - setPublishedAddress(publishedAddress); - setLocalPort(atoi(localPort.data())); - setPublishedPort(atoi(publishedPort.data())); - setStunServer(stunServer); - setStunEnabled((stunEnable == "true")); - setResolveOnce((resolveOnce.compare("true")==0) ? true : false); - setRegistrationExpire(registrationExpire); - - // sip credential - find_in_map(REALM, realm) - find_in_map(AUTHENTICATION_USERNAME, authenticationName) - find_in_map(USERAGENT, ua_name) - - setUseragent(ua_name); - - // srtp settings - find_in_map(SRTP_ENABLE, srtpEnable) - find_in_map(SRTP_RTP_FALLBACK, srtpRtpFallback) - find_in_map(ZRTP_DISPLAY_SAS, zrtpDisplaySas) - find_in_map(ZRTP_DISPLAY_SAS_ONCE, zrtpDisplaySasOnce) - find_in_map(ZRTP_NOT_SUPP_WARNING, zrtpNotSuppWarning) - find_in_map(ZRTP_HELLO_HASH, zrtpHelloHash) - find_in_map(SRTP_KEY_EXCHANGE, srtpKeyExchange) - - setSrtpEnable((srtpEnable.compare("true") == 0) ? true : false); - setSrtpFallback((srtpRtpFallback.compare("true") == 0) ? true : false); - setZrtpDisplaySas((zrtpDisplaySas.compare("true") == 0) ? true : false); - setZrtpDiaplaySasOnce((zrtpDisplaySasOnce.compare("true") == 0) ? true : false); - setZrtpNotSuppWarning((zrtpNotSuppWarning.compare("true") == 0) ? true : false); - setZrtpHelloHash((zrtpHelloHash.compare("true") == 0) ? true : false); - // sipaccount->setSrtpKeyExchange((srtpKeyExchange.compare("true") == 0) ? true : false); - setSrtpKeyExchange(srtpKeyExchange); - - // TLS settings - // The TLS listener is unique and globally defined through IP2IP_PROFILE - if(_accountID == IP2IP_PROFILE) { - find_in_map(TLS_LISTENER_PORT, tlsListenerPort) - } - find_in_map(TLS_ENABLE, tlsEnable) - find_in_map(TLS_CA_LIST_FILE, tlsCaListFile) - find_in_map(TLS_CERTIFICATE_FILE, tlsCertificateFile) - find_in_map(TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile) - find_in_map(TLS_PASSWORD, tlsPassword) - find_in_map(TLS_METHOD, tlsMethod) - find_in_map(TLS_CIPHERS, tlsCiphers) - find_in_map(TLS_SERVER_NAME, tlsServerName) - find_in_map(TLS_VERIFY_SERVER, tlsVerifyServer) - find_in_map(TLS_VERIFY_CLIENT, tlsVerifyClient) - find_in_map(TLS_REQUIRE_CLIENT_CERTIFICATE, tlsRequireClientCertificate) - find_in_map(TLS_NEGOTIATION_TIMEOUT_SEC, tlsNegotiationTimeoutSec) - find_in_map(TLS_NEGOTIATION_TIMEOUT_MSEC, tlsNegotiationTimeoutMsec) - - if (_accountID == IP2IP_PROFILE){ - setTlsListenerPort(atoi(tlsListenerPort.data())); - } - setTlsEnable(tlsEnable); - setTlsCaListFile(tlsCaListFile); - setTlsCertificateFile(tlsCertificateFile); - setTlsPrivateKeyFile(tlsPrivateKeyFile); - setTlsPassword(tlsPassword); - setTlsMethod(tlsMethod); - setTlsCiphers(tlsCiphers); - setTlsServerName(tlsServerName); - setTlsVerifyServer(tlsVerifyServer.compare("true") ? true : false); - setTlsVerifyClient(tlsVerifyServer.compare("true") ? true : false); - setTlsRequireClientCertificate(tlsRequireClientCertificate.compare("true") ? true : false); - setTlsNegotiationTimeoutSec(tlsNegotiationTimeoutSec); - setTlsNegotiationTimeoutMsec(tlsNegotiationTimeoutMsec); - - if (!Manager::instance().preferences.getMd5Hash()) { - setPassword(password); - } else { - // Make sure not to re-hash the password field if - // it is already saved as a MD5 Hash. - // TODO: This test is weak. Fix this. - if ((password.compare(getPassword()) != 0)) { - _debug ("SipAccount: Password sent and password from config are different. Re-hashing"); - std::string hash; - - if (authenticationName.empty()) { - hash = Manager::instance().computeMd5HashFromCredential(username, password, realm); - } else { - hash = Manager::instance().computeMd5HashFromCredential(authenticationName, password, realm); - } - - setPassword(hash); - } - } - } + std::map<std::string, std::string> map_cpy; + std::map<std::string, std::string>::iterator iter; + + _debug ("SipAccount: set account details %s", _accountID.c_str()); + + // Work on a copy + map_cpy = details; + + std::string alias; + std::string type; + std::string hostname; + std::string username; + std::string password; + std::string mailbox; + std::string accountEnable; + std::string ringtonePath; + std::string ringtoneEnabled; + + // Account setting common to SIP and IAX + find_in_map (CONFIG_ACCOUNT_ALIAS, alias) + find_in_map (CONFIG_ACCOUNT_TYPE, type) + find_in_map (HOSTNAME, hostname) + find_in_map (USERNAME, username) + find_in_map (PASSWORD, password) + find_in_map (CONFIG_ACCOUNT_MAILBOX, mailbox); + find_in_map (CONFIG_ACCOUNT_ENABLE, accountEnable); + find_in_map (CONFIG_RINGTONE_PATH, ringtonePath); + find_in_map (CONFIG_RINGTONE_ENABLED, ringtoneEnabled); + + setAlias (alias); + setType (type); + setUsername (username); + setHostname (hostname); + setPassword (password); + setEnabled ( (accountEnable == "true")); + setRingtonePath (ringtonePath); + setRingtoneEnabled ( (ringtoneEnabled == "true")); + + // SIP specific account settings + if (getType() == "SIP") { + + std::string ua_name; + std::string realm; + std::string routeset; + std::string authenticationName; + + std::string resolveOnce; + std::string registrationExpire; + + std::string displayName; + std::string localInterface; + std::string publishedSameasLocal; + std::string localAddress; + std::string publishedAddress; + std::string localPort; + std::string publishedPort; + std::string stunEnable; + std::string stunServer; + std::string dtmfType; + std::string srtpEnable; + std::string srtpRtpFallback; + std::string zrtpDisplaySas; + std::string zrtpDisplaySasOnce; + std::string zrtpNotSuppWarning; + std::string zrtpHelloHash; + std::string srtpKeyExchange; + + std::string tlsListenerPort; + std::string tlsEnable; + std::string tlsCaListFile; + std::string tlsCertificateFile; + std::string tlsPrivateKeyFile; + std::string tlsPassword; + std::string tlsMethod; + std::string tlsCiphers; + std::string tlsServerName; + std::string tlsVerifyServer; + std::string tlsVerifyClient; + std::string tlsRequireClientCertificate; + std::string tlsNegotiationTimeoutSec; + std::string tlsNegotiationTimeoutMsec; + + // general sip settings + find_in_map (DISPLAY_NAME, displayName) + find_in_map (ROUTESET, routeset) + find_in_map (LOCAL_INTERFACE, localInterface) + find_in_map (PUBLISHED_SAMEAS_LOCAL, publishedSameasLocal) + find_in_map (PUBLISHED_ADDRESS, publishedAddress) + find_in_map (LOCAL_PORT, localPort) + find_in_map (PUBLISHED_PORT, publishedPort) + find_in_map (STUN_ENABLE, stunEnable) + find_in_map (STUN_SERVER, stunServer) + find_in_map (ACCOUNT_DTMF_TYPE, dtmfType) + find_in_map (CONFIG_ACCOUNT_RESOLVE_ONCE, resolveOnce) + find_in_map (CONFIG_ACCOUNT_REGISTRATION_EXPIRE, registrationExpire) + + setDisplayName (displayName); + setServiceRoute (routeset); + setLocalInterface (localInterface); + setPublishedSameasLocal ( (publishedSameasLocal.compare ("true") == 0) ? true : false); + setPublishedAddress (publishedAddress); + setLocalPort (atoi (localPort.data())); + setPublishedPort (atoi (publishedPort.data())); + setStunServer (stunServer); + setStunEnabled ( (stunEnable == "true")); + setResolveOnce ( (resolveOnce.compare ("true") ==0) ? true : false); + setRegistrationExpire (registrationExpire); + + // sip credential + find_in_map (REALM, realm) + find_in_map (AUTHENTICATION_USERNAME, authenticationName) + find_in_map (USERAGENT, ua_name) + + setUseragent (ua_name); + + // srtp settings + find_in_map (SRTP_ENABLE, srtpEnable) + find_in_map (SRTP_RTP_FALLBACK, srtpRtpFallback) + find_in_map (ZRTP_DISPLAY_SAS, zrtpDisplaySas) + find_in_map (ZRTP_DISPLAY_SAS_ONCE, zrtpDisplaySasOnce) + find_in_map (ZRTP_NOT_SUPP_WARNING, zrtpNotSuppWarning) + find_in_map (ZRTP_HELLO_HASH, zrtpHelloHash) + find_in_map (SRTP_KEY_EXCHANGE, srtpKeyExchange) + + setSrtpEnable ( (srtpEnable.compare ("true") == 0) ? true : false); + setSrtpFallback ( (srtpRtpFallback.compare ("true") == 0) ? true : false); + setZrtpDisplaySas ( (zrtpDisplaySas.compare ("true") == 0) ? true : false); + setZrtpDiaplaySasOnce ( (zrtpDisplaySasOnce.compare ("true") == 0) ? true : false); + setZrtpNotSuppWarning ( (zrtpNotSuppWarning.compare ("true") == 0) ? true : false); + setZrtpHelloHash ( (zrtpHelloHash.compare ("true") == 0) ? true : false); + // sipaccount->setSrtpKeyExchange((srtpKeyExchange.compare("true") == 0) ? true : false); + setSrtpKeyExchange (srtpKeyExchange); + + // TLS settings + // The TLS listener is unique and globally defined through IP2IP_PROFILE + if (_accountID == IP2IP_PROFILE) { + find_in_map (TLS_LISTENER_PORT, tlsListenerPort) + } + + find_in_map (TLS_ENABLE, tlsEnable) + find_in_map (TLS_CA_LIST_FILE, tlsCaListFile) + find_in_map (TLS_CERTIFICATE_FILE, tlsCertificateFile) + find_in_map (TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile) + find_in_map (TLS_PASSWORD, tlsPassword) + find_in_map (TLS_METHOD, tlsMethod) + find_in_map (TLS_CIPHERS, tlsCiphers) + find_in_map (TLS_SERVER_NAME, tlsServerName) + find_in_map (TLS_VERIFY_SERVER, tlsVerifyServer) + find_in_map (TLS_VERIFY_CLIENT, tlsVerifyClient) + find_in_map (TLS_REQUIRE_CLIENT_CERTIFICATE, tlsRequireClientCertificate) + find_in_map (TLS_NEGOTIATION_TIMEOUT_SEC, tlsNegotiationTimeoutSec) + find_in_map (TLS_NEGOTIATION_TIMEOUT_MSEC, tlsNegotiationTimeoutMsec) + + if (_accountID == IP2IP_PROFILE) { + setTlsListenerPort (atoi (tlsListenerPort.data())); + } + + setTlsEnable (tlsEnable); + setTlsCaListFile (tlsCaListFile); + setTlsCertificateFile (tlsCertificateFile); + setTlsPrivateKeyFile (tlsPrivateKeyFile); + setTlsPassword (tlsPassword); + setTlsMethod (tlsMethod); + setTlsCiphers (tlsCiphers); + setTlsServerName (tlsServerName); + setTlsVerifyServer (tlsVerifyServer.compare ("true") ? true : false); + setTlsVerifyClient (tlsVerifyServer.compare ("true") ? true : false); + setTlsRequireClientCertificate (tlsRequireClientCertificate.compare ("true") ? true : false); + setTlsNegotiationTimeoutSec (tlsNegotiationTimeoutSec); + setTlsNegotiationTimeoutMsec (tlsNegotiationTimeoutMsec); + + if (!Manager::instance().preferences.getMd5Hash()) { + setPassword (password); + } else { + // Make sure not to re-hash the password field if + // it is already saved as a MD5 Hash. + // TODO: This test is weak. Fix this. + if ( (password.compare (getPassword()) != 0)) { + _debug ("SipAccount: Password sent and password from config are different. Re-hashing"); + std::string hash; + + if (authenticationName.empty()) { + hash = Manager::instance().computeMd5HashFromCredential (username, password, realm); + } else { + hash = Manager::instance().computeMd5HashFromCredential (authenticationName, password, realm); + } + + setPassword (hash); + } + } + } } std::map<std::string, std::string> SIPAccount::getAccountDetails() { - _debug("SipAccount: get account details %s", _accountID.c_str()); - - std::map<std::string, std::string> a; - - a.insert(std::pair<std::string, std::string>(ACCOUNT_ID, _accountID)); - // The IP profile does not allow to set an alias - (_accountID == IP2IP_PROFILE) ? - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ALIAS, IP2IP_PROFILE)) : - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ALIAS, getAlias())); - - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ENABLE, isEnabled() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_TYPE, getType())); - a.insert(std::pair<std::string, std::string>(HOSTNAME, getHostname())); - a.insert(std::pair<std::string, std::string>(USERNAME, getUsername())); - a.insert(std::pair<std::string, std::string>(PASSWORD, getPassword())); - - a.insert(std::pair<std::string, std::string>(CONFIG_RINGTONE_PATH, getRingtonePath())); - a.insert(std::pair<std::string, std::string>(CONFIG_RINGTONE_ENABLED, getRingtoneEnabled() ? "true" : "false")); - - RegistrationState state = Unregistered; - std::string registrationStateCode; - std::string registrationStateDescription; - - - if (_accountID == IP2IP_PROFILE) { - registrationStateCode = EMPTY_FIELD; - registrationStateDescription = "Direct IP call"; - } else { - state = getRegistrationState(); - int code = getRegistrationStateDetailed().first; - std::stringstream out; out << code; - registrationStateCode = out.str(); - registrationStateDescription = getRegistrationStateDetailed().second; - } - - - (_accountID == IP2IP_PROFILE) ? - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATUS, "READY")) : - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATUS, Manager::instance().mapStateNumberToString(state))); - - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATE_CODE, registrationStateCode)); - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); - - - // Add sip specific details - if(getType() == "SIP") { - - a.insert(std::pair<std::string, std::string>(ROUTESET, getServiceRoute())); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_RESOLVE_ONCE, isResolveOnce() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(REALM, _realm)); - a.insert(std::pair<std::string, std::string>(USERAGENT, getUseragent())); - - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_REGISTRATION_EXPIRE, getRegistrationExpire())); - a.insert(std::pair<std::string, std::string>(LOCAL_INTERFACE, getLocalInterface())); - a.insert(std::pair<std::string, std::string>(PUBLISHED_SAMEAS_LOCAL, getPublishedSameasLocal() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(PUBLISHED_ADDRESS, getPublishedAddress())); - - std::stringstream localport; localport << getLocalPort(); - a.insert(std::pair<std::string, std::string>(LOCAL_PORT, localport.str())); - std::stringstream publishedport; publishedport << getPublishedPort(); - a.insert(std::pair<std::string, std::string>(PUBLISHED_PORT, publishedport.str())); - a.insert(std::pair<std::string, std::string>(STUN_ENABLE, isStunEnabled() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(STUN_SERVER, getStunServer())); - a.insert(std::pair<std::string, std::string>(ACCOUNT_DTMF_TYPE, (getDtmfType() == 0) ? "0" : "1")); - - a.insert(std::pair<std::string, std::string>(SRTP_KEY_EXCHANGE, getSrtpKeyExchange())); - a.insert(std::pair<std::string, std::string>(SRTP_ENABLE, getSrtpEnable() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(SRTP_RTP_FALLBACK, getSrtpFallback() ? "true" : "false")); - - a.insert(std::pair<std::string, std::string>(ZRTP_DISPLAY_SAS, getZrtpDisplaySas() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(ZRTP_DISPLAY_SAS_ONCE, getZrtpDiaplaySasOnce() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(ZRTP_HELLO_HASH, getZrtpHelloHash() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(ZRTP_NOT_SUPP_WARNING, getZrtpNotSuppWarning() ? "true" : "false")); - - // TLS listener is unique and parameters are modified through IP2IP_PROFILE - std::stringstream tlslistenerport; - tlslistenerport << getTlsListenerPort(); - a.insert(std::pair<std::string, std::string>(TLS_LISTENER_PORT, tlslistenerport.str())); - a.insert(std::pair<std::string, std::string>(TLS_ENABLE, getTlsEnable())); - a.insert(std::pair<std::string, std::string>(TLS_CA_LIST_FILE, getTlsCaListFile())); - a.insert(std::pair<std::string, std::string>(TLS_CERTIFICATE_FILE, getTlsCertificateFile())); - a.insert(std::pair<std::string, std::string>(TLS_PRIVATE_KEY_FILE, getTlsPrivateKeyFile())); - a.insert(std::pair<std::string, std::string>(TLS_PASSWORD, getTlsPassword())); - a.insert(std::pair<std::string, std::string>(TLS_METHOD, getTlsMethod())); - a.insert(std::pair<std::string, std::string>(TLS_CIPHERS, getTlsCiphers())); - a.insert(std::pair<std::string, std::string>(TLS_SERVER_NAME, getTlsServerName())); - a.insert(std::pair<std::string, std::string>(TLS_VERIFY_SERVER, getTlsVerifyServer() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(TLS_VERIFY_CLIENT, getTlsVerifyClient() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(TLS_REQUIRE_CLIENT_CERTIFICATE, getTlsRequireClientCertificate() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(TLS_NEGOTIATION_TIMEOUT_SEC, getTlsNegotiationTimeoutSec())); - a.insert(std::pair<std::string, std::string>(TLS_NEGOTIATION_TIMEOUT_MSEC, getTlsNegotiationTimeoutMsec())); - - } - - return a; + _debug ("SipAccount: get account details %s", _accountID.c_str()); + + std::map<std::string, std::string> a; + + a.insert (std::pair<std::string, std::string> (ACCOUNT_ID, _accountID)); + // The IP profile does not allow to set an alias + (_accountID == IP2IP_PROFILE) ? + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, IP2IP_PROFILE)) : + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, getAlias())); + + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ENABLE, isEnabled() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_TYPE, getType())); + a.insert (std::pair<std::string, std::string> (HOSTNAME, getHostname())); + a.insert (std::pair<std::string, std::string> (USERNAME, getUsername())); + a.insert (std::pair<std::string, std::string> (PASSWORD, getPassword())); + + a.insert (std::pair<std::string, std::string> (CONFIG_RINGTONE_PATH, getRingtonePath())); + a.insert (std::pair<std::string, std::string> (CONFIG_RINGTONE_ENABLED, getRingtoneEnabled() ? "true" : "false")); + + RegistrationState state = Unregistered; + std::string registrationStateCode; + std::string registrationStateDescription; + + + if (_accountID == IP2IP_PROFILE) { + registrationStateCode = EMPTY_FIELD; + registrationStateDescription = "Direct IP call"; + } else { + state = getRegistrationState(); + int code = getRegistrationStateDetailed().first; + std::stringstream out; + out << code; + registrationStateCode = out.str(); + registrationStateDescription = getRegistrationStateDetailed().second; + } + + + (_accountID == IP2IP_PROFILE) ? + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATUS, "READY")) : + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATUS, Manager::instance().mapStateNumberToString (state))); + + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_CODE, registrationStateCode)); + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); + + + // Add sip specific details + if (getType() == "SIP") { + + a.insert (std::pair<std::string, std::string> (ROUTESET, getServiceRoute())); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_RESOLVE_ONCE, isResolveOnce() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (REALM, _realm)); + a.insert (std::pair<std::string, std::string> (USERAGENT, getUseragent())); + + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_REGISTRATION_EXPIRE, getRegistrationExpire())); + a.insert (std::pair<std::string, std::string> (LOCAL_INTERFACE, getLocalInterface())); + a.insert (std::pair<std::string, std::string> (PUBLISHED_SAMEAS_LOCAL, getPublishedSameasLocal() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (PUBLISHED_ADDRESS, getPublishedAddress())); + + std::stringstream localport; + localport << getLocalPort(); + a.insert (std::pair<std::string, std::string> (LOCAL_PORT, localport.str())); + std::stringstream publishedport; + publishedport << getPublishedPort(); + a.insert (std::pair<std::string, std::string> (PUBLISHED_PORT, publishedport.str())); + a.insert (std::pair<std::string, std::string> (STUN_ENABLE, isStunEnabled() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (STUN_SERVER, getStunServer())); + a.insert (std::pair<std::string, std::string> (ACCOUNT_DTMF_TYPE, (getDtmfType() == 0) ? "0" : "1")); + + a.insert (std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, getSrtpKeyExchange())); + a.insert (std::pair<std::string, std::string> (SRTP_ENABLE, getSrtpEnable() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (SRTP_RTP_FALLBACK, getSrtpFallback() ? "true" : "false")); + + a.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, getZrtpDisplaySas() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, getZrtpDiaplaySasOnce() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (ZRTP_HELLO_HASH, getZrtpHelloHash() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, getZrtpNotSuppWarning() ? "true" : "false")); + + // TLS listener is unique and parameters are modified through IP2IP_PROFILE + std::stringstream tlslistenerport; + tlslistenerport << getTlsListenerPort(); + a.insert (std::pair<std::string, std::string> (TLS_LISTENER_PORT, tlslistenerport.str())); + a.insert (std::pair<std::string, std::string> (TLS_ENABLE, getTlsEnable())); + a.insert (std::pair<std::string, std::string> (TLS_CA_LIST_FILE, getTlsCaListFile())); + a.insert (std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, getTlsCertificateFile())); + a.insert (std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, getTlsPrivateKeyFile())); + a.insert (std::pair<std::string, std::string> (TLS_PASSWORD, getTlsPassword())); + a.insert (std::pair<std::string, std::string> (TLS_METHOD, getTlsMethod())); + a.insert (std::pair<std::string, std::string> (TLS_CIPHERS, getTlsCiphers())); + a.insert (std::pair<std::string, std::string> (TLS_SERVER_NAME, getTlsServerName())); + a.insert (std::pair<std::string, std::string> (TLS_VERIFY_SERVER, getTlsVerifyServer() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, getTlsVerifyClient() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, getTlsRequireClientCertificate() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, getTlsNegotiationTimeoutSec())); + a.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, getTlsNegotiationTimeoutMsec())); + + } + + return a; } // void SIPAccount::setVoIPLink(VoIPLink *link) { -void SIPAccount::setVoIPLink() { +void SIPAccount::setVoIPLink() +{ _link = SIPVoIPLink::instance (""); dynamic_cast<SIPVoIPLink*> (_link)->incrementClients(); @@ -709,7 +928,7 @@ void SIPAccount::setVoIPLink() { int SIPAccount::initCredential (void) { - _debug("SipAccount: Init credential"); + _debug ("SipAccount: Init credential"); bool md5HashingEnabled = false; int dataType = 0; @@ -750,7 +969,7 @@ int SIPAccount::initCredential (void) // Set the datatype cred_info[0].data_type = dataType; - + // Set the secheme cred_info[0].scheme = pj_str ( (char*) "digest"); @@ -760,8 +979,8 @@ int SIPAccount::initCredential (void) for (i = 0; i < credentials.getCredentialCount(); i++) { std::string username = _username; - std::string password = _password; - std::string realm = _realm; + std::string password = _password; + std::string realm = _realm; cred_info[i].username = pj_str (strdup (username.c_str())); cred_info[i].data = pj_str (strdup (password.c_str())); @@ -816,9 +1035,8 @@ int SIPAccount::registerVoIPLink() if (_stunEnabled) { _transportType = PJSIP_TRANSPORT_START_OTHER; initStunConfiguration (); - } - else { - _stunServerName = pj_str ((char*) _stunServer.data()); + } else { + _stunServerName = pj_str ( (char*) _stunServer.data()); } // In our definition of the @@ -884,10 +1102,10 @@ void SIPAccount::initTlsConfiguration (void) } // TLS listener is unique and should be only modified through IP2IP_PROFILE - + // setTlsListenerPort(atoi(tlsPortStr.c_str())); - setTlsListenerPort(atoi(_tlsPortStr.c_str())); - + setTlsListenerPort (atoi (_tlsPortStr.c_str())); + _tlsSetting = (pjsip_tls_setting *) malloc (sizeof (pjsip_tls_setting)); assert (_tlsSetting); @@ -916,7 +1134,7 @@ void SIPAccount::initStunConfiguration (void) size_t pos; std::string stunServer, serverName, serverPort; - stunServer = _stunServer; + stunServer = _stunServer; // Init STUN socket pos = stunServer.find (':'); @@ -991,9 +1209,9 @@ std::string SIPAccount::getLoginName (void) return username; } -std::string SIPAccount::getTransportMapKey(void) +std::string SIPAccount::getTransportMapKey (void) { - + std::stringstream out; out << getLocalPort(); std::string localPort = out.str(); @@ -1029,7 +1247,7 @@ std::string SIPAccount::getFromUri (void) // Get machine hostname if not provided if (_hostname.empty()) { - hostname = getMachineName(); + hostname = getMachineName(); } @@ -1070,7 +1288,7 @@ std::string SIPAccount::getToUri (const std::string& username) // Check if hostname is already specified if (username.find ("@") == std::string::npos) { // hostname not specified - hostname = _hostname; + hostname = _hostname; } int len = pj_ansi_snprintf (uri, PJSIP_MAX_URL_SIZE, diff --git a/sflphone-common/src/sip/sipcall.cpp b/sflphone-common/src/sip/sipcall.cpp index 78595928dfc0665feba6b6f4b06e8286e2b89910..1317d06071dd0f988d3b4781cead85cc5cc47b28 100644 --- a/sflphone-common/src/sip/sipcall.cpp +++ b/sflphone-common/src/sip/sipcall.cpp @@ -44,14 +44,14 @@ SIPCall::SIPCall (const CallID& id, Call::CallType type, pj_pool_t *pool) : Call , _invSession (NULL) , _local_sdp (0) { - _debug ("SIPCall: Create new call %s", id.c_str()); + _debug ("SIPCall: Create new call %s", id.c_str()); _local_sdp = new Sdp (pool); } SIPCall::~SIPCall() { - _debug ("SIPCall: Delete call"); + _debug ("SIPCall: Delete call"); delete _audiortp; _audiortp = 0; diff --git a/sflphone-common/src/sip/sipvoiplink.cpp b/sflphone-common/src/sip/sipvoiplink.cpp old mode 100755 new mode 100644 index c5df6f3465f60e779ff892ff66c77ab1fff0d520..29de8360b2adac0c6356238ec36606a6ccf4857c --- a/sflphone-common/src/sip/sipvoiplink.cpp +++ b/sflphone-common/src/sip/sipvoiplink.cpp @@ -215,7 +215,7 @@ void call_on_tsx_changed (pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_ void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer); -void on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer); +void on_create_offer (pjsip_inv_session *inv, pjmedia_sdp_session **p_offer); /* * Registration callback @@ -245,7 +245,7 @@ pj_bool_t mod_on_rx_response (pjsip_rx_data *rdata UNUSED) ; * Send an ACK message inside a transaction. PJSIP send automatically, non-2xx ACK response. * ACK for a 2xx response must be send using this method. */ -static void sendAck(pjsip_dialog *dlg, pjsip_rx_data *rdata); +static void sendAck (pjsip_dialog *dlg, pjsip_rx_data *rdata); /* * Transfer callbacks @@ -267,7 +267,7 @@ SIPVoIPLink::SIPVoIPLink (const AccountID& accountID) , _clients (0) { - _debug("SIPVOIPLINK"); + _debug ("SIPVOIPLINK"); // to get random number for RANDOM_PORT srand (time (NULL)); @@ -279,7 +279,7 @@ SIPVoIPLink::SIPVoIPLink (const AccountID& accountID) SIPVoIPLink::~SIPVoIPLink() { - _debug("UserAgent: SIPVoIPLink destructor called"); + _debug ("UserAgent: SIPVoIPLink destructor called"); terminate(); @@ -302,7 +302,7 @@ void SIPVoIPLink::decrementClients (void) if (_clients == 0) { - _debug("UserAgent: No SIP account anymore, terminate SIPVoIPLink"); + _debug ("UserAgent: No SIP account anymore, terminate SIPVoIPLink"); // terminate(); delete SIPVoIPLink::_instance; } @@ -335,7 +335,8 @@ SIPVoIPLink::terminate() if (_evThread) { _debug ("UserAgent: Deleting sip eventThread"); - delete _evThread; _evThread = NULL; + delete _evThread; + _evThread = NULL; } @@ -374,7 +375,7 @@ SIPVoIPLink::terminateSIPCall() void SIPVoIPLink::terminateOneCall (const CallID& id) { - _debug("UserAgent: Terminate call %s", id.c_str()); + _debug ("UserAgent: Terminate call %s", id.c_str()); SIPCall *call = getSIPCall (id); @@ -409,7 +410,8 @@ void get_remote_sdp_from_offer (pjsip_rx_data *rdata, pjmedia_sdp_session** r_sd } -std::string SIPVoIPLink::getInterfaceAddrFromName(std::string ifaceName) { +std::string SIPVoIPLink::getInterfaceAddrFromName (std::string ifaceName) +{ struct ifreq ifr; int fd; @@ -418,23 +420,23 @@ std::string SIPVoIPLink::getInterfaceAddrFromName(std::string ifaceName) { struct sockaddr_in *saddr_in; struct in_addr *addr_in; - if((fd = socket (AF_INET, SOCK_DGRAM,0)) < 0) - _error("UserAgent: Error: could not open socket"); + if ( (fd = socket (AF_INET, SOCK_DGRAM,0)) < 0) + _error ("UserAgent: Error: could not open socket"); memset (&ifr, 0, sizeof (struct ifreq)); strcpy (ifr.ifr_name, ifaceName.c_str()); ifr.ifr_addr.sa_family = AF_INET; - if((err = ioctl(fd, SIOCGIFADDR, &ifr)) < 0) - _debug("UserAgent: Use default interface (0.0.0.0)"); - - saddr_in = (struct sockaddr_in *)&ifr.ifr_addr; - addr_in = &(saddr_in->sin_addr); + if ( (err = ioctl (fd, SIOCGIFADDR, &ifr)) < 0) + _debug ("UserAgent: Use default interface (0.0.0.0)"); + + saddr_in = (struct sockaddr_in *) &ifr.ifr_addr; + addr_in = & (saddr_in->sin_addr); - std::string addr(pj_inet_ntoa(*((pj_in_addr*)addr_in))); + std::string addr (pj_inet_ntoa (* ( (pj_in_addr*) addr_in))); - close(fd); + close (fd); return addr; } @@ -442,19 +444,20 @@ std::string SIPVoIPLink::getInterfaceAddrFromName(std::string ifaceName) { std::string SIPVoIPLink::get_useragent_name (const AccountID& id) { - /* + /* useragent << PROGNAME << "/" << SFLPHONED_VERSION; return useragent.str(); - */ + */ - SIPAccount *account = (SIPAccount *)Manager::instance().getAccount(id); + SIPAccount *account = (SIPAccount *) Manager::instance().getAccount (id); std::ostringstream useragent; useragent << account->getUseragent(); + if (useragent.str() == "sflphone" || useragent.str() == "") - useragent << "/" << SFLPHONED_VERSION; - + useragent << "/" << SFLPHONED_VERSION; + return useragent.str (); } @@ -537,17 +540,17 @@ int SIPVoIPLink::sendRegister (AccountID id) } - // Create SIP transport or get existent SIP transport from internal map + // Create SIP transport or get existent SIP transport from internal map // according to account settings, if the transport could not be created but - // one is already set in account, use this one (most likely this is the - // transport we tried to create) - acquireTransport(account->getAccountID()); + // one is already set in account, use this one (most likely this is the + // transport we tried to create) + acquireTransport (account->getAccountID()); if (account->getAccountTransport()) { - _debug("Acquire transport in account registration: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("Acquire transport in account registration: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } _mutexSIP.enterMutex(); @@ -611,19 +614,19 @@ int SIPVoIPLink::sendRegister (AccountID id) status = pjsip_regc_init (regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, expire_value); - if(!(account->getServiceRoute().empty())) { + if (! (account->getServiceRoute().empty())) { - _error("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); + _error ("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); - pjsip_route_hdr *route_set = pjsip_route_hdr_create(_pool); - pjsip_route_hdr *routing = pjsip_route_hdr_create(_pool); - pjsip_sip_uri *url = pjsip_sip_uri_create(_pool, 0); - routing->name_addr.uri = (pjsip_uri*)url; - pj_strdup2(_pool, &url->host, account->getServiceRoute().c_str()); + pjsip_route_hdr *route_set = pjsip_route_hdr_create (_pool); + pjsip_route_hdr *routing = pjsip_route_hdr_create (_pool); + pjsip_sip_uri *url = pjsip_sip_uri_create (_pool, 0); + routing->name_addr.uri = (pjsip_uri*) url; + pj_strdup2 (_pool, &url->host, account->getServiceRoute().c_str()); - pj_list_push_back(&route_set, pjsip_hdr_clone(_pool, routing)); + pj_list_push_back (&route_set, pjsip_hdr_clone (_pool, routing)); - pjsip_regc_set_route_set(regc, route_set); + pjsip_regc_set_route_set (regc, route_set); } if (status != PJ_SUCCESS) { @@ -649,7 +652,7 @@ int SIPVoIPLink::sendRegister (AccountID id) // pj_list_push_back (&hdr_list, (pjsip_hdr*) routing); pjsip_regc_add_headers (regc, &hdr_list); - + status = pjsip_regc_register (regc, PJ_TRUE, &tdata); if (status != PJ_SUCCESS) { @@ -660,20 +663,20 @@ int SIPVoIPLink::sendRegister (AccountID id) pjsip_tpselector *tp; - init_transport_selector (account->getAccountTransport (), &tp); - + init_transport_selector (account->getAccountTransport (), &tp); + // pjsip_regc_set_transport increments transport ref count by one status = pjsip_regc_set_transport (regc, tp); - if(account->getAccountTransport()) { - // decrease transport's ref count, counter icrementation is - // managed when acquiring transport - pjsip_transport_dec_ref(account->getAccountTransport ()); + if (account->getAccountTransport()) { + // decrease transport's ref count, counter icrementation is + // managed when acquiring transport + pjsip_transport_dec_ref (account->getAccountTransport ()); - _debug("UserAgent: After setting the transport in account registration using transport: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("UserAgent: After setting the transport in account registration using transport: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } if (status != PJ_SUCCESS) { @@ -683,14 +686,14 @@ int SIPVoIPLink::sendRegister (AccountID id) } // Send registration request - // pjsip_regc_send increment the transport ref count by one, + // pjsip_regc_send increment the transport ref count by one, status = pjsip_regc_send (regc, tdata); - if(account->getAccountTransport()) { - // Decrease transport's ref count, since coresponding reference counter decrementation + if (account->getAccountTransport()) { + // Decrease transport's ref count, since coresponding reference counter decrementation // is performed in pjsip_regc_destroy. This function is never called in SFLphone as the // regc data structure is permanently associated to the account at first registration. - pjsip_transport_dec_ref(account->getAccountTransport ()); + pjsip_transport_dec_ref (account->getAccountTransport ()); } if (status != PJ_SUCCESS) { @@ -703,12 +706,12 @@ int SIPVoIPLink::sendRegister (AccountID id) account->setRegistrationInfo (regc); - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("Sent account registration using transport: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("Sent account registration using transport: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } return true; @@ -727,12 +730,12 @@ SIPVoIPLink::sendUnregister (AccountID id) regc = account->getRegistrationInfo(); // If an transport is attached to this account, detach it and decrease reference counter - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("Sent account unregistration using transport: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("Sent account unregistration using transport: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } @@ -749,7 +752,7 @@ SIPVoIPLink::sendUnregister (AccountID id) _debug ("UserAgent: Unable to unregister regc."); return false; } - + status = pjsip_regc_send (regc, tdata); if (status != PJ_SUCCESS) { @@ -774,7 +777,7 @@ SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) pj_status_t status; std::string localAddr, addrSdp; - _debug("UserAgent: New outgoing call %s to %s", id.c_str(), toUrl.c_str()); + _debug ("UserAgent: New outgoing call %s to %s", id.c_str(), toUrl.c_str()); SIPCall* call = new SIPCall (id, Call::Outgoing, _pool); @@ -794,9 +797,9 @@ SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) call->setPeerNumber (toUri); - localAddr = getInterfaceAddrFromName(account->getLocalInterface ()); + localAddr = getInterfaceAddrFromName (account->getLocalInterface ()); - _debug("UserAgent: Local address for call: %s", localAddr.c_str()); + _debug ("UserAgent: Local address for call: %s", localAddr.c_str()); if (localAddr == "0.0.0.0") loadSIPLocalIP (&localAddr); @@ -804,7 +807,7 @@ SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) setCallAudioLocal (call, localAddr); // May use the published address as well - account->isStunEnabled () ? addrSdp = account->getPublishedAddress () : addrSdp = getInterfaceAddrFromName(account->getLocalInterface ()); + account->isStunEnabled () ? addrSdp = account->getPublishedAddress () : addrSdp = getInterfaceAddrFromName (account->getLocalInterface ()); if (addrSdp == "0.0.0.0") loadSIPLocalIP (&addrSdp); @@ -957,7 +960,7 @@ SIPVoIPLink::peerHungup (const CallID& id) pjsip_tx_data *tdata = NULL; SIPCall* call; - _info("UserAgent: Peer hungup"); + _info ("UserAgent: Peer hungup"); call = getSIPCall (id); @@ -1000,12 +1003,12 @@ SIPVoIPLink::peerHungup (const CallID& id) bool SIPVoIPLink::cancel (const CallID& id) { - _info ("UserAgent: Cancel call %s", id.c_str()); + _info ("UserAgent: Cancel call %s", id.c_str()); SIPCall* call = getSIPCall (id); if (!call) { - _warn("UserAgent: Error: Call doesn't exist"); + _warn ("UserAgent: Error: Call doesn't exist"); return false; } @@ -1065,7 +1068,7 @@ int SIPVoIPLink::inv_session_reinvite (SIPCall *call, std::string direction) // Reinvite only if connected // Build the local SDP offer - // TODO Restore Re-Invite + // TODO Restore Re-Invite // status = call->getLocalSDP()->create_initial_offer(); // if (status != PJ_SUCCESS) @@ -1146,7 +1149,7 @@ SIPVoIPLink::transfer (const CallID& id, const std::string& to) account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id)); if (!account) { - _error("UserAgent: Error: Transfer account is null. Returning."); + _error ("UserAgent: Error: Transfer account is null. Returning."); return false; } @@ -1195,9 +1198,9 @@ SIPVoIPLink::transfer (const CallID& id, const std::string& to) } // Put SIP call id in map in order to retrieve call during transfer callback - std::string callidtransfer(call->getInvSession()->dlg->call_id->id.ptr, call->getInvSession()->dlg->call_id->id.slen); - _debug("%s", callidtransfer.c_str()); - transferCallID.insert(std::pair<std::string, CallID>(callidtransfer, call->getCallId())); + std::string callidtransfer (call->getInvSession()->dlg->call_id->id.ptr, call->getInvSession()->dlg->call_id->id.slen); + _debug ("%s", callidtransfer.c_str()); + transferCallID.insert (std::pair<std::string, CallID> (callidtransfer, call->getCallId())); /* Send. */ @@ -1214,8 +1217,8 @@ SIPVoIPLink::transfer (const CallID& id, const std::string& to) bool SIPVoIPLink::transferStep2 (SIPCall* call) { - // TODO is this the best way to proceed? - Manager::instance().peerHungupCall(call->getCallId()); + // TODO is this the best way to proceed? + Manager::instance().peerHungupCall (call->getCallId()); @@ -1229,7 +1232,7 @@ SIPVoIPLink::refuse (const CallID& id) pj_status_t status; pjsip_tx_data *tdata; - _debug("UserAgent: Refuse call %s", id.c_str()); + _debug ("UserAgent: Refuse call %s", id.c_str()); call = getSIPCall (id); @@ -1257,11 +1260,11 @@ SIPVoIPLink::refuse (const CallID& id) call->getInvSession()->mod_data[getModId() ] = NULL; - removeCall(id); + removeCall (id); terminateOneCall (id); - _debug("UserAgent: Refuse call completed"); + _debug ("UserAgent: Refuse call completed"); return true; } @@ -1296,23 +1299,23 @@ SIPVoIPLink::carryingDTMFdigits (const CallID& id, char code) return false; } - AccountID accountID = Manager::instance().getAccountFromCall(id); - SIPAccount *account = static_cast<SIPAccount *>(Manager::instance().getAccount(accountID)); + AccountID accountID = Manager::instance().getAccountFromCall (id); + SIPAccount *account = static_cast<SIPAccount *> (Manager::instance().getAccount (accountID)); - if(!account) { - _error ("UserAgent: Error: Account not found while sending DTMF"); - return false; + if (!account) { + _error ("UserAgent: Error: Account not found while sending DTMF"); + return false; } DtmfType type = account->getDtmfType(); - if(type == OVERRTP) - dtmfOverRtp(call, code); - else if(type == SIPINFO) - dtmfSipInfo(call, code); + if (type == OVERRTP) + dtmfOverRtp (call, code); + else if (type == SIPINFO) + dtmfSipInfo (call, code); else { - _error("UserAgent: Error: Dtmf type does not exist"); - return false; + _error ("UserAgent: Error: Dtmf type does not exist"); + return false; } return true; @@ -1320,69 +1323,69 @@ SIPVoIPLink::carryingDTMFdigits (const CallID& id, char code) bool -SIPVoIPLink::dtmfSipInfo(SIPCall *call, char code) +SIPVoIPLink::dtmfSipInfo (SIPCall *call, char code) { - int duration; - const int body_len = 1000; - char *dtmf_body; - pj_status_t status; - pjsip_tx_data *tdata; - pj_str_t methodName, content; - pjsip_method method; - pjsip_media_type ctype; + int duration; + const int body_len = 1000; + char *dtmf_body; + pj_status_t status; + pjsip_tx_data *tdata; + pj_str_t methodName, content; + pjsip_method method; + pjsip_media_type ctype; - duration = Manager::instance().voipPreferences.getPulseLength(); + duration = Manager::instance().voipPreferences.getPulseLength(); - dtmf_body = new char[body_len]; + dtmf_body = new char[body_len]; - snprintf (dtmf_body, body_len - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration); + snprintf (dtmf_body, body_len - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration); - pj_strdup2 (_pool, &methodName, "INFO"); - pjsip_method_init_np (&method, &methodName); + pj_strdup2 (_pool, &methodName, "INFO"); + pjsip_method_init_np (&method, &methodName); - /* Create request message. */ - status = pjsip_dlg_create_request (call->getInvSession()->dlg, &method, -1, &tdata); + /* Create request message. */ + status = pjsip_dlg_create_request (call->getInvSession()->dlg, &method, -1, &tdata); - if (status != PJ_SUCCESS) { - _debug ("UserAgent: Unable to create INFO request -- %d", status); - return false; - } + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create INFO request -- %d", status); + return false; + } - /* Get MIME type */ - pj_strdup2 (_pool, &ctype.type, "application"); + /* Get MIME type */ + pj_strdup2 (_pool, &ctype.type, "application"); - pj_strdup2 (_pool, &ctype.subtype, "dtmf-relay"); + pj_strdup2 (_pool, &ctype.subtype, "dtmf-relay"); - /* Create "application/dtmf-relay" message body. */ - pj_strdup2 (_pool, &content, dtmf_body); + /* Create "application/dtmf-relay" message body. */ + pj_strdup2 (_pool, &content, dtmf_body); - tdata->msg->body = pjsip_msg_body_create (tdata->pool, &ctype.type, &ctype.subtype, &content); + tdata->msg->body = pjsip_msg_body_create (tdata->pool, &ctype.type, &ctype.subtype, &content); - if (tdata->msg->body == NULL) { - _debug ("UserAgent: Unable to create msg body!"); - pjsip_tx_data_dec_ref (tdata); - return false; - } + if (tdata->msg->body == NULL) { + _debug ("UserAgent: Unable to create msg body!"); + pjsip_tx_data_dec_ref (tdata); + return false; + } - /* Send the request. */ - status = pjsip_dlg_send_request (call->getInvSession()->dlg, tdata, getModId(), NULL); + /* Send the request. */ + status = pjsip_dlg_send_request (call->getInvSession()->dlg, tdata, getModId(), NULL); - if (status != PJ_SUCCESS) { - _debug ("UserAgent: Unable to send MESSAGE request -- %d", status); - return false; - } + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to send MESSAGE request -- %d", status); + return false; + } - return true; + return true; } bool -SIPVoIPLink::dtmfOverRtp(SIPCall* call, char code) +SIPVoIPLink::dtmfOverRtp (SIPCall* call, char code) { - call->getAudioRtp()->sendDtmfDigit(atoi(&code)); + call->getAudioRtp()->sendDtmfDigit (atoi (&code)); - return true; + return true; } @@ -1409,7 +1412,7 @@ SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) AccountID id; - _debug("UserAgent: Start sip call"); + _debug ("UserAgent: Start sip call"); if (call == NULL) return false; @@ -1474,19 +1477,19 @@ SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) status = pjsip_inv_create_uac (dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv); - if(!(account->getServiceRoute().empty())) { + if (! (account->getServiceRoute().empty())) { - _error("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); + _error ("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); - pjsip_route_hdr *route_set = pjsip_route_hdr_create(_pool); - pjsip_route_hdr *routing = pjsip_route_hdr_create(_pool); - pjsip_sip_uri *url = pjsip_sip_uri_create(_pool, 0); - routing->name_addr.uri = (pjsip_uri*)url; - pj_strdup2(_pool, &url->host, account->getServiceRoute().c_str()); + pjsip_route_hdr *route_set = pjsip_route_hdr_create (_pool); + pjsip_route_hdr *routing = pjsip_route_hdr_create (_pool); + pjsip_sip_uri *url = pjsip_sip_uri_create (_pool, 0); + routing->name_addr.uri = (pjsip_uri*) url; + pj_strdup2 (_pool, &url->host, account->getServiceRoute().c_str()); - pj_list_push_back(&route_set, pjsip_hdr_clone(_pool, routing)); + pj_list_push_back (&route_set, pjsip_hdr_clone (_pool, routing)); - pjsip_dlg_set_route_set(dialog, route_set); + pjsip_dlg_set_route_set (dialog, route_set); } @@ -1515,7 +1518,7 @@ SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) // decrement transport's ref count // pjsip_transport_dec_ref(account->getAccountTransport()); - + status = pjsip_inv_send_msg (inv, tdata); if (status != PJ_SUCCESS) { @@ -1523,12 +1526,12 @@ SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) return false; } - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("UserAgent: Sent invite request using transport: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("UserAgent: Sent invite request using transport: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } return true; @@ -1552,10 +1555,10 @@ SIPVoIPLink::SIPCallServerFailure (SIPCall *call) void SIPVoIPLink::SIPCallClosed (SIPCall *call) { - _info("UserAgent: Closing call"); + _info ("UserAgent: Closing call"); if (!call) { - _warn("UserAgent: Error: CAll pointer is NULL\n"); + _warn ("UserAgent: Error: CAll pointer is NULL\n"); return; } @@ -1636,7 +1639,7 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) pjsip_tx_data *tdata; std::string localAddress, addrSdp; - _debug("UserAgent: New IP2IP call %s to %s", id.c_str(), to.c_str()); + _debug ("UserAgent: New IP2IP call %s to %s", id.c_str(), to.c_str()); /* Create the call */ call = new SIPCall (id, Call::Outgoing, _pool); @@ -1651,11 +1654,11 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) if (account == NULL) { _error ("UserAgent: Error: Account %s is null. Returning", IP2IP_PROFILE); - return !PJ_SUCCESS; + return !PJ_SUCCESS; } // Set the local address - localAddress = getInterfaceAddrFromName(account->getLocalInterface ()); + localAddress = getInterfaceAddrFromName (account->getLocalInterface ()); // Set SDP parameters - Set to local addrSdp = localAddress; @@ -1664,14 +1667,14 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) loadSIPLocalIP (&localAddress); } - _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str()); + _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str()); // Local address to appear in SDP if (addrSdp == "0.0.0.0") { - addrSdp = localAddress; + addrSdp = localAddress; } - _debug ("UserAgent: Media Address for IP2IP call: %s", localAddress.c_str()); + _debug ("UserAgent: Media Address for IP2IP call: %s", localAddress.c_str()); // Set local address for RTP media setCallAudioLocal (call, localAddress); @@ -1689,33 +1692,33 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) // Audio Rtp Session must be initialized before creating initial offer in SDP session // since SDES require crypto attribute. try { - call->getAudioRtp()->initAudioRtpConfig (call); - call->getAudioRtp()->initAudioRtpSession (call); + call->getAudioRtp()->initAudioRtpConfig (call); + call->getAudioRtp()->initAudioRtpSession (call); } catch (...) { - _debug ("UserAgent: Unable to create RTP Session in new IP2IP call (%s:%d)", __FILE__, __LINE__); + _debug ("UserAgent: Unable to create RTP Session in new IP2IP call (%s:%d)", __FILE__, __LINE__); } // Init TLS transport if enabled - if(account->isTlsEnabled()) { + if (account->isTlsEnabled()) { - _debug("UserAgent: TLS enabled for IP2IP calls"); - int at = toUri.find("@"); - int trns = toUri.find(";transport"); - std::string remoteAddr = toUri.substr(at+1, trns-at-1); + _debug ("UserAgent: TLS enabled for IP2IP calls"); + int at = toUri.find ("@"); + int trns = toUri.find (";transport"); + std::string remoteAddr = toUri.substr (at+1, trns-at-1); - if(toUri.find("sips:") != 1) { - _debug("UserAgent: Error \"sips\" scheme required for TLS call"); - return false; - } + if (toUri.find ("sips:") != 1) { + _debug ("UserAgent: Error \"sips\" scheme required for TLS call"); + return false; + } - if(createTlsTransport(account->getAccountID(), remoteAddr) != PJ_SUCCESS) - return false; + if (createTlsTransport (account->getAccountID(), remoteAddr) != PJ_SUCCESS) + return false; } // If no transport already set, use the default one created at pjsip initialization if (account->getAccountTransport() == NULL) { - _debug ("UserAgent: No transport for this account, using the default one"); - account->setAccountTransport (_localUDPTransport); + _debug ("UserAgent: No transport for this account, using the default one"); + account->setAccountTransport (_localUDPTransport); } _debug ("UserAgent: Local port %i for IP2IP call", account->getLocalPort()); @@ -1729,94 +1732,94 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) int port = findLocalPortFromUri (toUri, account->getAccountTransport()); std::stringstream ss; - std::string portStr; - ss << port; - ss >> portStr; - - std::string contactUri = account->getContactHeader (address, portStr); - - _debug ("UserAgent: FROM uri: %s, TO uri: %s, CONTACT uri: %s", - fromUri.c_str(), toUri.c_str(), contactUri.c_str()); - - pj_str_t pjFrom; - pj_cstr (&pjFrom, fromUri.c_str()); - - pj_str_t pjTo; - pj_cstr (&pjTo, toUri.c_str()); - - pj_str_t pjContact; - pj_cstr (&pjContact, contactUri.c_str()); - - // Create the dialog (UAC) - // (Parameters are "strduped" inside this function) - status = pjsip_dlg_create_uac (pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog); - PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); - - // Create the invite session for this call - status = pjsip_inv_create_uac (dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv); - PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); - - if(!(account->getServiceRoute().empty())) { - - _error("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); - - pjsip_route_hdr *route_set = pjsip_route_hdr_create(_pool); - pjsip_route_hdr *routing = pjsip_route_hdr_create(_pool); - pjsip_sip_uri *url = pjsip_sip_uri_create(_pool, 0); - routing->name_addr.uri = (pjsip_uri*)url; - pj_strdup2(_pool, &url->host, account->getServiceRoute().c_str()); - - pj_list_push_back(&route_set, pjsip_hdr_clone(_pool, routing)); - - pjsip_dlg_set_route_set(dialog, route_set); - } - - // Set the appropriate transport - pjsip_tpselector *tp; - - init_transport_selector (account->getAccountTransport(), &tp); - - if(!account->getAccountTransport()) { - _error("UserAgent: Error: Transport is NULL in IP2IP call"); - } - - // set_transport methods increment transport's ref_count - status = pjsip_dlg_set_transport (dialog, tp); - - // decrement transport's ref count - // pjsip_transport_dec_ref(account->getAccountTransport()); - - if (status != PJ_SUCCESS) { - _error ("UserAgent: Error: Failed to set the transport for an IP2IP call"); - return status; - } - - // Associate current call in the invite session - inv->mod_data[getModId() ] = call; - - status = pjsip_inv_invite (inv, &tdata); - - PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); - - // Associate current invite session in the call - call->setInvSession (inv); - - status = pjsip_inv_send_msg (inv, tdata); - - if (status != PJ_SUCCESS) { - delete call; - call = 0; - return false; - } - - call->setConnectionState (Call::Progressing); - - call->setState (Call::Active); - addCall (call); - - return true; + std::string portStr; + ss << port; + ss >> portStr; + + std::string contactUri = account->getContactHeader (address, portStr); + + _debug ("UserAgent: FROM uri: %s, TO uri: %s, CONTACT uri: %s", + fromUri.c_str(), toUri.c_str(), contactUri.c_str()); + + pj_str_t pjFrom; + pj_cstr (&pjFrom, fromUri.c_str()); + + pj_str_t pjTo; + pj_cstr (&pjTo, toUri.c_str()); + + pj_str_t pjContact; + pj_cstr (&pjContact, contactUri.c_str()); + + // Create the dialog (UAC) + // (Parameters are "strduped" inside this function) + status = pjsip_dlg_create_uac (pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); + + // Create the invite session for this call + status = pjsip_inv_create_uac (dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); + + if (! (account->getServiceRoute().empty())) { + + _error ("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); + + pjsip_route_hdr *route_set = pjsip_route_hdr_create (_pool); + pjsip_route_hdr *routing = pjsip_route_hdr_create (_pool); + pjsip_sip_uri *url = pjsip_sip_uri_create (_pool, 0); + routing->name_addr.uri = (pjsip_uri*) url; + pj_strdup2 (_pool, &url->host, account->getServiceRoute().c_str()); + + pj_list_push_back (&route_set, pjsip_hdr_clone (_pool, routing)); + + pjsip_dlg_set_route_set (dialog, route_set); + } + + // Set the appropriate transport + pjsip_tpselector *tp; + + init_transport_selector (account->getAccountTransport(), &tp); + + if (!account->getAccountTransport()) { + _error ("UserAgent: Error: Transport is NULL in IP2IP call"); + } + + // set_transport methods increment transport's ref_count + status = pjsip_dlg_set_transport (dialog, tp); + + // decrement transport's ref count + // pjsip_transport_dec_ref(account->getAccountTransport()); + + if (status != PJ_SUCCESS) { + _error ("UserAgent: Error: Failed to set the transport for an IP2IP call"); + return status; + } + + // Associate current call in the invite session + inv->mod_data[getModId() ] = call; + + status = pjsip_inv_invite (inv, &tdata); + + PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); + + // Associate current invite session in the call + call->setInvSession (inv); + + status = pjsip_inv_send_msg (inv, tdata); + + if (status != PJ_SUCCESS) { + delete call; + call = 0; + return false; + } + + call->setConnectionState (Call::Progressing); + + call->setState (Call::Active); + addCall (call); + + return true; } else - return false; + return false; } @@ -1861,10 +1864,11 @@ pj_status_t SIPVoIPLink::enable_dns_srv_resolver (pjsip_endpoint *endpt, pj_dns_ std::vector <std::string> dns_servers; int scount, i; - _debug("UserAgent: Enable DNS SRV resolver"); + _debug ("UserAgent: Enable DNS SRV resolver"); // Create the DNS resolver instance status = pjsip_endpt_create_resolver (endpt, &resv); + if (status != PJ_SUCCESS) { _error ("UserAgent: Error: Creating the DNS resolver instance"); return status; @@ -1882,13 +1886,15 @@ pj_status_t SIPVoIPLink::enable_dns_srv_resolver (pjsip_endpoint *endpt, pj_dns_ } pj_str_t nameservers[scount]; + for (i = 0; i<scount; i++) { - _debug("UserAgent: Server: %s", (char *)dns_servers[i].c_str()); + _debug ("UserAgent: Server: %s", (char *) dns_servers[i].c_str()); nameservers[i] = pj_str ( (char *) dns_servers[i].c_str()); } // Update the name servers for the DNS resolver status = pj_dns_resolver_set_ns (resv, scount, nameservers, NULL); + if (status != PJ_SUCCESS) { _debug ("UserAgent: Error updating the name servers for the DNS resolver"); return status; @@ -1896,6 +1902,7 @@ pj_status_t SIPVoIPLink::enable_dns_srv_resolver (pjsip_endpoint *endpt, pj_dns_ // Set the DNS resolver instance of the SIP resolver engine status = pjsip_endpt_set_resolver (endpt, resv); + if (status != PJ_SUCCESS) { _debug ("UserAgent: Error setting the DNS resolver instance of the SIP resolver engine"); return status; @@ -1957,11 +1964,11 @@ bool SIPVoIPLink::pjsip_init() return false; } - // Initialize default UDP transport according to + // Initialize default UDP transport according to // IP to IP settings (most likely using port 5060) createDefaultSipUdpTransport(); - // Call this method to create TLS listener + // Call this method to create TLS listener createDefaultSipTlsListener(); // Initialize transaction layer @@ -2110,73 +2117,73 @@ pj_status_t SIPVoIPLink::stunServerResolve (AccountID id) -bool SIPVoIPLink::acquireTransport(const AccountID& accountID) { +bool SIPVoIPLink::acquireTransport (const AccountID& accountID) +{ SIPAccount* account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountID)); - if(!account) + if (!account) return false; - // If an account is already bound to this account, decrease its reference - // as it is going to change. If the same transport is selected, reference + // If an account is already bound to this account, decrease its reference + // as it is going to change. If the same transport is selected, reference // counter will be increased - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("pjsip_transport_dec_ref in acquireTransport"); - pjsip_transport_dec_ref(account->getAccountTransport()); + _debug ("pjsip_transport_dec_ref in acquireTransport"); + pjsip_transport_dec_ref (account->getAccountTransport()); } // Try to create a new transport in case the settings for this account // are different than one defined for already created ones // If TLS is enabled, TLS connection is automatically handled when sending account registration - // However, for any other sip transaction, we must create TLS connection - if(createSipTransport(accountID)) { + // However, for any other sip transaction, we must create TLS connection + if (createSipTransport (accountID)) { return true; } // A transport is already created on this port, use it else { - _debug("Could not create a new transport (%s)", account->getTransportMapKey().c_str()); - _debug("Searching transport (%s) in transport map", account->getTransportMapKey().c_str()); + _debug ("Could not create a new transport (%s)", account->getTransportMapKey().c_str()); + _debug ("Searching transport (%s) in transport map", account->getTransportMapKey().c_str()); // Could not create new transport, this transport may already exists SipTransportMap::iterator transport; - transport = _transportMap.find(account->getTransportMapKey()); + transport = _transportMap.find (account->getTransportMapKey()); - if(transport != _transportMap.end()) { + if (transport != _transportMap.end()) { - // Transport already exist, use it for this account - _debug("Found transport (%s) in transport map", account->getTransportMapKey().c_str()); + // Transport already exist, use it for this account + _debug ("Found transport (%s) in transport map", account->getTransportMapKey().c_str()); - pjsip_transport* tr = transport->second; + pjsip_transport* tr = transport->second; - // Set transport to be used for transaction involving this account - account->setAccountTransport(tr); + // Set transport to be used for transaction involving this account + account->setAccountTransport (tr); - // Increment newly associated transport reference counter - // If the account is shutdowning, time is automatically canceled - pjsip_transport_add_ref(tr); + // Increment newly associated transport reference counter + // If the account is shutdowning, time is automatically canceled + pjsip_transport_add_ref (tr); - return true; - } - else { + return true; + } else { - // Transport could not either be created, socket not available - _debug("Did not find transport (%s) in transport map", account->getTransportMapKey().c_str()); + // Transport could not either be created, socket not available + _debug ("Did not find transport (%s) in transport map", account->getTransportMapKey().c_str()); - account->setAccountTransport(_localUDPTransport); + account->setAccountTransport (_localUDPTransport); - std::string localHostName(_localUDPTransport->local_name.host.ptr, _localUDPTransport->local_name.host.slen); + std::string localHostName (_localUDPTransport->local_name.host.ptr, _localUDPTransport->local_name.host.slen); - _debug("Use default one instead (%s:%i)", localHostName.c_str(), _localUDPTransport->local_name.port); + _debug ("Use default one instead (%s:%i)", localHostName.c_str(), _localUDPTransport->local_name.port); - // account->setLocalAddress(localHostName); - account->setLocalPort(_localUDPTransport->local_name.port); + // account->setLocalAddress(localHostName); + account->setLocalPort (_localUDPTransport->local_name.port); - // Transport could not either be created or found in the map, socket not available - return false; - } + // Transport could not either be created or found in the map, socket not available + return false; + } } } @@ -2194,16 +2201,16 @@ bool SIPVoIPLink::createDefaultSipUdpTransport() // Create a UDP listener meant for all accounts for which TLS was not enabled // Cannot acquireTransport since default UDP transport must be created regardless of TLS - errPjsip = createUdpTransport(IP2IP_PROFILE); + errPjsip = createUdpTransport (IP2IP_PROFILE); - if(account && (errPjsip == PJ_SUCCESS)) { + if (account && (errPjsip == PJ_SUCCESS)) { // Store transport in transport map - addTransportToMap(account->getTransportMapKey(), account->getAccountTransport()); + addTransportToMap (account->getTransportMapKey(), account->getAccountTransport()); + + // if account is not NULL, use IP2IP trasport as default one + _localUDPTransport = account->getAccountTransport(); - // if account is not NULL, use IP2IP trasport as default one - _localUDPTransport = account->getAccountTransport(); - } // If the above UDP server // could not be created, then give it another try @@ -2213,12 +2220,12 @@ bool SIPVoIPLink::createDefaultSipUdpTransport() _regPort = RANDOM_SIP_PORT; _debug ("UserAgent: Trying to initialize SIP listener on port %d", _regPort); - // If no AccountID specified, pointer to transport is stored in _localUDPTransport + // If no AccountID specified, pointer to transport is stored in _localUDPTransport errPjsip = createUdpTransport(); if (errPjsip != PJ_SUCCESS) { _debug ("UserAgent: Fail to initialize SIP listener on port %d", _regPort); - return false; + return false; } } @@ -2233,13 +2240,13 @@ void SIPVoIPLink::createDefaultSipTlsListener() SIPAccount * account = NULL; account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (IP2IP_PROFILE)); - if(account->isTlsEnabled()) { - createTlsListener(IP2IP_PROFILE); + if (account->isTlsEnabled()) { + createTlsListener (IP2IP_PROFILE); } } -void SIPVoIPLink::createTlsListener(const AccountID& accountID) +void SIPVoIPLink::createTlsListener (const AccountID& accountID) { pjsip_tpfactory *tls; @@ -2248,7 +2255,7 @@ void SIPVoIPLink::createTlsListener(const AccountID& accountID) pj_status_t status; pj_status_t success; - _debug("Create TLS listener"); + _debug ("Create TLS listener"); /* Grab the tls settings, populated * from configuration file. @@ -2266,7 +2273,7 @@ void SIPVoIPLink::createTlsListener(const AccountID& accountID) pj_sockaddr_in_init (&local_addr, 0, 0); pj_uint16_t localTlsPort = account->getTlsListenerPort(); local_addr.sin_port = pj_htons (localTlsPort); - + pj_str_t pjAddress; pj_cstr (&pjAddress, PJ_INADDR_ANY); success = pj_sockaddr_in_set_str_addr (&local_addr, &pjAddress); @@ -2274,7 +2281,7 @@ void SIPVoIPLink::createTlsListener(const AccountID& accountID) // Init published address for this listener (Local IP address on port 5061) std::string publishedAddress; - loadSIPLocalIP(&publishedAddress); + loadSIPLocalIP (&publishedAddress); pj_bzero (&a_name, sizeof (pjsip_host_port)); pj_cstr (&a_name.host, publishedAddress.c_str()); @@ -2283,28 +2290,27 @@ void SIPVoIPLink::createTlsListener(const AccountID& accountID) /* Get TLS settings. Expected to be filled */ pjsip_tls_setting * tls_setting = account->getTlsSetting(); - + _debug ("UserAgent: TLS transport to be initialized with published address %.*s," " published port %d,\n local address %.*s, local port %d", (int) a_name.host.slen, a_name.host.ptr, (int) a_name.port, pjAddress.slen, pjAddress.ptr, (int) localTlsPort); - + status = pjsip_tls_transport_start (_endpt, tls_setting, &local_addr, &a_name, 1, &tls); if (status != PJ_SUCCESS) { _debug ("UserAgent: Error creating SIP TLS listener (%d)", status); - } - else { + } else { _localTlsListener = tls; } - + // return PJ_SUCCESS; - + } -bool SIPVoIPLink::createSipTransport(AccountID id) +bool SIPVoIPLink::createSipTransport (AccountID id) { SIPAccount* account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); @@ -2316,23 +2322,22 @@ bool SIPVoIPLink::createSipTransport(AccountID id) if (account->isTlsEnabled()) { - if(_localTlsListener == NULL) - createTlsListener(id); + if (_localTlsListener == NULL) + createTlsListener (id); - // Parse remote address to establish connection + // Parse remote address to establish connection std::string remoteSipUri = account->getServerUri(); - int sips = remoteSipUri.find("<sips:") + 6; - int trns = remoteSipUri.find(";transport"); - std::string remoteAddr = remoteSipUri.substr(sips, trns-sips); + int sips = remoteSipUri.find ("<sips:") + 6; + int trns = remoteSipUri.find (";transport"); + std::string remoteAddr = remoteSipUri.substr (sips, trns-sips); // Nothing to do, TLS listener already created at pjsip's startup and TLS connection // is automatically handled in pjsip when sending registration messages. - if(createTlsTransport(id, remoteAddr) != PJ_SUCCESS) - return false; + if (createTlsTransport (id, remoteAddr) != PJ_SUCCESS) + return false; return true; - } - else { + } else { // Launch a new UDP listener/transport, using the published address if (account->isStunEnabled ()) { @@ -2341,45 +2346,44 @@ bool SIPVoIPLink::createSipTransport(AccountID id) if (status != PJ_SUCCESS) { _debug ("Failed to init UDP transport with STUN published address for account %s", id.c_str()); - return false; + return false; } } else { status = createUdpTransport (id); - if (status != PJ_SUCCESS) { + if (status != PJ_SUCCESS) { _debug ("Failed to initialize UDP transport for account %s", id.c_str()); - return false; - } - else { + return false; + } else { - // If transport successfully created, store it in the internal map. - // STUN aware transport are account specific and should not be stored in map. - // TLS transport is ephemeral and is managed by PJSIP, should not be stored either. - addTransportToMap(account->getTransportMapKey(), account->getAccountTransport()); - } - } + // If transport successfully created, store it in the internal map. + // STUN aware transport are account specific and should not be stored in map. + // TLS transport is ephemeral and is managed by PJSIP, should not be stored either. + addTransportToMap (account->getTransportMapKey(), account->getAccountTransport()); + } + } } - return true; + return true; } - -bool SIPVoIPLink::addTransportToMap(std::string key, pjsip_transport* transport) + +bool SIPVoIPLink::addTransportToMap (std::string key, pjsip_transport* transport) { SipTransportMap::iterator iter_transport; - iter_transport = _transportMap.find(key); - + iter_transport = _transportMap.find (key); + // old transport in transport map, erase it - if(iter_transport != _transportMap.end()){ - _transportMap.erase(iter_transport); + if (iter_transport != _transportMap.end()) { + _transportMap.erase (iter_transport); } - _debug("UserAgent: Storing newly created transport in map using key %s", key.c_str()); - _transportMap.insert(pair<std::string, pjsip_transport*>(key, transport)); + _debug ("UserAgent: Storing newly created transport in map using key %s", key.c_str()); + _transportMap.insert (pair<std::string, pjsip_transport*> (key, transport)); return true; @@ -2422,10 +2426,10 @@ int SIPVoIPLink::createUdpTransport (AccountID id) } else { // We are trying to initialize a UDP transport available for all local accounts and direct IP calls - _debug("UserAgent: found account %s in map", account->getAccountID().c_str()); + _debug ("UserAgent: found account %s in map", account->getAccountID().c_str()); if (account->getLocalInterface () != "default") { - listeningAddress = getInterfaceAddrFromName(account->getLocalInterface()); + listeningAddress = getInterfaceAddrFromName (account->getLocalInterface()); } listeningPort = account->getLocalPort (); @@ -2439,13 +2443,12 @@ int SIPVoIPLink::createUdpTransport (AccountID id) // Init bound address to ANY bound_addr.sin_addr.s_addr = pj_htonl (PJ_INADDR_ANY); - loadSIPLocalIP (&listeningAddress); - } - else { + loadSIPLocalIP (&listeningAddress); + } else { - // bind this account to a specific interface - pj_strdup2(_pool, &temporary_address, listeningAddress.c_str()); - bound_addr.sin_addr = pj_inet_addr(&temporary_address); + // bind this account to a specific interface + pj_strdup2 (_pool, &temporary_address, listeningAddress.c_str()); + bound_addr.sin_addr = pj_inet_addr (&temporary_address); } bound_addr.sin_port = pj_htons ( (pj_uint16_t) listeningPort); @@ -2467,13 +2470,14 @@ int SIPVoIPLink::createUdpTransport (AccountID id) // We must specify this here to avoid the IP2IP_PROFILE // to create a transport with name 0.0.0.0 to appear in the via header - if(id == IP2IP_PROFILE) - loadSIPLocalIP (&listeningAddress); + if (id == IP2IP_PROFILE) + loadSIPLocalIP (&listeningAddress); - if(listeningAddress == "" || listeningPort == 0) { - _error("UserAgent: Error invalid address for new udp transport"); - return !PJ_SUCCESS; + if (listeningAddress == "" || listeningPort == 0) { + _error ("UserAgent: Error invalid address for new udp transport"); + return !PJ_SUCCESS; } + //strcpy (tmpIP, listeningAddress.data()); /* Init published name */ pj_bzero (&a_name, sizeof (pjsip_host_port)); @@ -2500,14 +2504,13 @@ int SIPVoIPLink::createUdpTransport (AccountID id) if (account == NULL) { - _debug("UserAgent: Use transport as local UDP server"); + _debug ("UserAgent: Use transport as local UDP server"); _localUDPTransport = transport; - } - else { + } else { - _debug("UserAgent: bind transport to account %s", account->getAccountID().c_str()); - account->setAccountTransport (transport); - } + _debug ("UserAgent: bind transport to account %s", account->getAccountID().c_str()); + account->setAccountTransport (transport); + } } return PJ_SUCCESS; @@ -2575,18 +2578,17 @@ std::string SIPVoIPLink::findLocalAddressFromUri (const std::string& uri, pjsip_ pj_status_t status; /* Init the transport selector */ + //_debug ("Transport ID: %s", transport->obj_name); if (transportType == PJSIP_TRANSPORT_UDP) { status = init_transport_selector (transport, &tp_sel); if (status == PJ_SUCCESS) { status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, tp_sel, &localAddress, &port); + } else { + status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port); } - else { - status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port); - } - } - else { + } else { status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port); } @@ -2595,12 +2597,12 @@ std::string SIPVoIPLink::findLocalAddressFromUri (const std::string& uri, pjsip_ return machineName; } - std::string localaddr(localAddress.ptr, localAddress.slen); + std::string localaddr (localAddress.ptr, localAddress.slen); - if(localaddr == "0.0.0.0") - loadSIPLocalIP (&localaddr); + if (localaddr == "0.0.0.0") + loadSIPLocalIP (&localaddr); - _debug ("SIP: Local address discovered from attached transport: %s", localaddr.c_str()); + _debug ("SIP: Local address discovered from attached transport: %s", localaddr.c_str()); return localaddr; } @@ -2704,26 +2706,26 @@ int SIPVoIPLink::findLocalPortFromUri (const std::string& uri, pjsip_transport * } -pj_status_t SIPVoIPLink::createTlsTransport(const AccountID& accountID, std::string remoteAddr) +pj_status_t SIPVoIPLink::createTlsTransport (const AccountID& accountID, std::string remoteAddr) { pj_status_t success; - _debug("Create TLS transport for account %s\n", accountID.c_str()); + _debug ("Create TLS transport for account %s\n", accountID.c_str()); // Retrieve the account information SIPAccount * account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountID)); - if(!account) { - _debug("UserAgent: Account is NULL when creating TLS connection, returning"); - return !PJ_SUCCESS; + if (!account) { + _debug ("UserAgent: Account is NULL when creating TLS connection, returning"); + return !PJ_SUCCESS; } pj_sockaddr_in rem_addr; pj_str_t remote; - pj_cstr(&remote, remoteAddr.c_str()); + pj_cstr (&remote, remoteAddr.c_str()); - pj_sockaddr_in_init(&rem_addr, &remote, (pj_uint16_t)5061); + pj_sockaddr_in_init (&rem_addr, &remote, (pj_uint16_t) 5061); // Update TLS settings for account registration using the default listeners // Pjsip does not allow to create multiple listener @@ -2732,12 +2734,12 @@ pj_status_t SIPVoIPLink::createTlsTransport(const AccountID& accountID, std::str // Create a new TLS connection from TLS listener pjsip_transport *tls; - success = pjsip_endpt_acquire_transport(_endpt, PJSIP_TRANSPORT_TLS, &rem_addr, sizeof(rem_addr), NULL, &tls); + success = pjsip_endpt_acquire_transport (_endpt, PJSIP_TRANSPORT_TLS, &rem_addr, sizeof (rem_addr), NULL, &tls); - if(success != PJ_SUCCESS) - _debug("UserAgent: Error could not create TLS transport"); - else - account->setAccountTransport(tls); + if (success != PJ_SUCCESS) + _debug ("UserAgent: Error could not create TLS transport"); + else + account->setAccountTransport (tls); return success; } @@ -2832,18 +2834,18 @@ pj_status_t SIPVoIPLink::createAlternateUdpTransport (AccountID id) account->setAccountTransport (transport); - if(transport) { + if (transport) { + + _debug ("UserAgent: Initial ref count: %s %s (refcnt=%i)", transport->obj_name, transport->info, + (int) pj_atomic_get (transport->ref_cnt)); + + pj_sockaddr *addr = (pj_sockaddr*) & (transport->key.rem_addr); - _debug("UserAgent: Initial ref count: %s %s (refcnt=%i)", transport->obj_name, transport->info, - (int)pj_atomic_get(transport->ref_cnt)); + static char str[PJ_INET6_ADDRSTRLEN]; + pj_inet_ntop ( ( (const pj_sockaddr*) addr)->addr.sa_family, pj_sockaddr_get_addr (addr), str, sizeof (str)); - pj_sockaddr *addr = (pj_sockaddr*)&(transport->key.rem_addr); - static char str[PJ_INET6_ADDRSTRLEN]; - pj_inet_ntop(((const pj_sockaddr*)addr)->addr.sa_family, pj_sockaddr_get_addr(addr), str, sizeof(str)); - - - _debug("UserAgent: KEY: %s:%d",str, pj_sockaddr_get_port((const pj_sockaddr*)&(transport->key.rem_addr))); + _debug ("UserAgent: KEY: %s:%d",str, pj_sockaddr_get_port ( (const pj_sockaddr*) & (transport->key.rem_addr))); } @@ -2855,28 +2857,28 @@ pj_status_t SIPVoIPLink::createAlternateUdpTransport (AccountID id) } -void SIPVoIPLink::shutdownSipTransport(const AccountID& accountID) +void SIPVoIPLink::shutdownSipTransport (const AccountID& accountID) { - _debug("UserAgent: Shutdown Sip Transport"); + _debug ("UserAgent: Shutdown Sip Transport"); SIPAccount* account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountID)); - if(!account) + if (!account) return; - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("Transport bound to account, decrease ref count"); + _debug ("Transport bound to account, decrease ref count"); - // decrease reference count added by pjsip_regc_send - // PJSIP's IDLE timer is set if counter reach 0 + // decrease reference count added by pjsip_regc_send + // PJSIP's IDLE timer is set if counter reach 0 // there is still problems when account registration fails, so comment it for now - // status = pjsip_transport_dec_ref(account->getAccountTransport()); + // status = pjsip_transport_dec_ref(account->getAccountTransport()); - // detach transport from this account - account->setAccountTransport(NULL); + // detach transport from this account + account->setAccountTransport (NULL); } @@ -3162,22 +3164,24 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) accId = Manager::instance().getAccountFromCall (call->getCallId()); link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId)); - // Make sure link is valid - assert(link); + // Make sure link is valid + assert (link); switch (inv->cause) { - // The call terminates normally - BYE / CANCEL + // The call terminates normally - BYE / CANCEL case PJSIP_SC_OK: case PJSIP_SC_REQUEST_TERMINATED: link->SIPCallClosed (call); break; case PJSIP_SC_DECLINE: - _debug("UserAgent: Call %s is declined", call->getCallId().c_str()); - if (inv->role == PJSIP_ROLE_UAC) - link->SIPCallServerFailure (call); - break; + _debug ("UserAgent: Call %s is declined", call->getCallId().c_str()); + + if (inv->role == PJSIP_ROLE_UAC) + link->SIPCallServerFailure (call); + + break; case PJSIP_SC_NOT_FOUND: /* peer not found */ case PJSIP_SC_REQUEST_TIMEOUT: /* request timeout */ @@ -3186,13 +3190,13 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) case PJSIP_SC_UNSUPPORTED_MEDIA_TYPE: case PJSIP_SC_UNAUTHORIZED: case PJSIP_SC_FORBIDDEN: - case PJSIP_SC_REQUEST_PENDING: - case PJSIP_SC_ADDRESS_INCOMPLETE: + case PJSIP_SC_REQUEST_PENDING: + case PJSIP_SC_ADDRESS_INCOMPLETE: link->SIPCallServerFailure (call); break; default: - link->SIPCallServerFailure (call); + link->SIPCallServerFailure (call); _error ("UserAgent: Unhandled call state. This is probably a bug."); break; } @@ -3254,90 +3258,92 @@ void call_on_media_update (pjsip_inv_session *inv, pj_status_t status) try { call->getAudioRtp()->updateDestinationIpAddress(); - } - catch(...) { - + } catch (...) { + } // Get the crypto attribute containing srtp's cryptographic context (keys, cipher) CryptoOffer crypto_offer; - call->getLocalSDP()->get_remote_sdp_crypto_from_offer(remote_sdp, crypto_offer); + call->getLocalSDP()->get_remote_sdp_crypto_from_offer (remote_sdp, crypto_offer); bool nego_success = false; - if(!crypto_offer.empty()) { - _debug("UserAgent: Crypto attribute in SDP, init SRTP session"); + if (!crypto_offer.empty()) { + + _debug ("UserAgent: Crypto attribute in SDP, init SRTP session"); + + // init local cryptografic capabilities for negotiation + std::vector<sfl::CryptoSuiteDefinition>localCapabilities; + + for (int i = 0; i < 3; i++) { + localCapabilities.push_back (sfl::CryptoSuites[i]); + } + + sfl::SdesNegotiator sdesnego (localCapabilities, crypto_offer); - // init local cryptografic capabilities for negotiation - std::vector<sfl::CryptoSuiteDefinition>localCapabilities; - for(int i = 0; i < 3; i++) { - localCapabilities.push_back(sfl::CryptoSuites[i]); - } + if (sdesnego.negotiate()) { + _debug ("UserAgent: SDES negociation successfull \n"); + nego_success = true; - sfl::SdesNegotiator sdesnego(localCapabilities, crypto_offer); - - if(sdesnego.negotiate()) { - _debug("UserAgent: SDES negociation successfull \n"); - nego_success = true; + _debug ("UserAgent: Set remote cryptographic context\n"); - _debug("UserAgent: Set remote cryptographic context\n"); try { - call->getAudioRtp()->setRemoteCryptoInfo(sdesnego); - } - catch(...) {} + call->getAudioRtp()->setRemoteCryptoInfo (sdesnego); + } catch (...) {} DBusManager::instance().getCallManager()->secureSdesOn (call->getCallId()); - } - else { - DBusManager::instance().getCallManager()->secureSdesOff (call->getCallId()); - } + } else { + DBusManager::instance().getCallManager()->secureSdesOff (call->getCallId()); + } } // We did not found any crypto context for this media - if(!nego_success && call->getAudioRtp()->getAudioRtpType() == sfl::Sdes) { - + if (!nego_success && call->getAudioRtp()->getAudioRtpType() == sfl::Sdes) { + // We did not found any crypto context for this media // @TODO if SRTPONLY, CallFail - _debug("UserAgent: Did not found any crypto or negociation failed but Sdes enabled"); + _debug ("UserAgent: Did not found any crypto or negociation failed but Sdes enabled"); call->getAudioRtp()->stop(); - call->getAudioRtp()->setSrtpEnabled(false); + call->getAudioRtp()->setSrtpEnabled (false); - // if RTPFALLBACK, change RTP session - AccountID accountID = Manager::instance().getAccountFromCall (call->getCallId()); - SIPAccount *account = (SIPAccount *)Manager::instance().getAccount(accountID); + // if RTPFALLBACK, change RTP session + AccountID accountID = Manager::instance().getAccountFromCall (call->getCallId()); + SIPAccount *account = (SIPAccount *) Manager::instance().getAccount (accountID); - if(account->getSrtpFallback()) - call->getAudioRtp()->initAudioRtpSession(call); + if (account->getSrtpFallback()) + call->getAudioRtp()->initAudioRtpSession (call); } - if(nego_success && call->getAudioRtp()->getAudioRtpType() != sfl::Sdes) { - - // We found a crypto context for this media but Sdes is not + if (nego_success && call->getAudioRtp()->getAudioRtpType() != sfl::Sdes) { + + // We found a crypto context for this media but Sdes is not // enabled for this call, make a try using RTP only... - _debug("UserAgent: SDES not initialized for this call\n"); + _debug ("UserAgent: SDES not initialized for this call\n"); } Sdp *sdpSession = call->getLocalSDP(); - if(!sdpSession) - return; + + if (!sdpSession) + return; AudioCodec *sessionMedia = sdpSession->get_session_media(); - if(!sessionMedia) - return; - AudioCodecType pl = (AudioCodecType)sessionMedia->getPayload(); - AudioCodec* audiocodec = Manager::instance().getCodecDescriptorMap().instantiateCodec(pl); + if (!sessionMedia) + return; + + AudioCodecType pl = (AudioCodecType) sessionMedia->getPayload(); + AudioCodec* audiocodec = Manager::instance().getCodecDescriptorMap().instantiateCodec (pl); - if (audiocodec == NULL) - _error ("UserAgent: No audiocodec found"); + if (audiocodec == NULL) + _error ("UserAgent: No audiocodec found"); try { call->setAudioStart (true); - call->getAudioRtp()->start(audiocodec); + call->getAudioRtp()->start (audiocodec); } catch (exception& rtpException) { _error ("UserAgent: Error: %s", rtpException.what()); } @@ -3350,9 +3356,9 @@ void call_on_forked (pjsip_inv_session *inv UNUSED, pjsip_event *e UNUSED) void call_on_tsx_changed (pjsip_inv_session *inv UNUSED, pjsip_transaction *tsx, pjsip_event *e) { - assert(tsx); + assert (tsx); - _debug("UserAgent: Transaction changed to state %s", transactionStateMap[tsx->state]); + _debug ("UserAgent: Transaction changed to state %s", transactionStateMap[tsx->state]); if (tsx->role==PJSIP_ROLE_UAS && tsx->state==PJSIP_TSX_STATE_TRYING && pjsip_method_cmp (&tsx->method, &pjsip_refer_method) ==0) { @@ -3363,26 +3369,26 @@ void call_on_tsx_changed (pjsip_inv_session *inv UNUSED, pjsip_transaction *tsx, if (e && e->body.rx_msg.rdata) { - _debug("Event"); + _debug ("Event"); pjsip_tx_data* t_data; pjsip_rx_data* r_data = e->body.rx_msg.rdata; if (r_data && r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD) { - _debug("R_data"); + _debug ("R_data"); std::string method_info = "INFO"; std::string method_notify = "NOTIFY"; std::string request = pjsip_rx_data_get_info (r_data); - _debug("UserAgent: %s", request.c_str()); + _debug ("UserAgent: %s", request.c_str()); - if(request.find (method_notify) != (size_t)-1) { + if (request.find (method_notify) != (size_t)-1) { - } - // Must reply 200 OK on SIP INFO request - else if (request.find (method_info) != (size_t)-1) { + } + // Must reply 200 OK on SIP INFO request + else if (request.find (method_info) != (size_t)-1) { pjsip_dlg_create_response (inv->dlg, r_data, PJSIP_SC_OK, NULL, &t_data); @@ -3414,10 +3420,10 @@ void regc_cb (struct pjsip_regc_cbparam *param) DBusManager::instance().getCallManager()->registrationStateChanged (account->getAccountID(), std::string (description->ptr, description->slen), param->code); std::pair<int, std::string> details (param->code, std::string (description->ptr, description->slen)); - - // there a race condition for this ressource when closing the application - if(account) - account->setRegistrationStateDetailed (details); + + // there a race condition for this ressource when closing the application + if (account) + account->setRegistrationStateDetailed (details); } if (param->status == PJ_SUCCESS) { @@ -3444,20 +3450,20 @@ void regc_cb (struct pjsip_regc_cbparam *param) account->setRegistrationState (ErrorAuth); break; - case 423: { // Expiration Interval Too Brief + case 423: { // Expiration Interval Too Brief - int expire_value; - std::istringstream stream (account->getRegistrationExpire()); - stream >> expire_value; + int expire_value; + std::istringstream stream (account->getRegistrationExpire()); + stream >> expire_value; - std::stringstream out; - out << (expire_value * 2); - std::string s = out.str(); + std::stringstream out; + out << (expire_value * 2); + std::string s = out.str(); - account->setRegistrationExpire(s); - account->registerVoIPLink(); - } - break; + account->setRegistrationExpire (s); + account->registerVoIPLink(); + } + break; default: account->setRegistrationState (Error); @@ -3466,11 +3472,11 @@ void regc_cb (struct pjsip_regc_cbparam *param) account->setRegister (false); - // shutdown this transport since useless - // if(account->getAccountTransport() != _localUDPTransport) { + // shutdown this transport since useless + // if(account->getAccountTransport() != _localUDPTransport) { - SIPVoIPLink::instance("")->shutdownSipTransport(account->getAccountID()); - //} + SIPVoIPLink::instance ("")->shutdownSipTransport (account->getAccountID()); + //} } else { // Registration/Unregistration is success @@ -3480,17 +3486,17 @@ void regc_cb (struct pjsip_regc_cbparam *param) account->setRegistrationState (Unregistered); account->setRegister (false); - SIPVoIPLink::instance("")->shutdownSipTransport(account->getAccountID()); + SIPVoIPLink::instance ("")->shutdownSipTransport (account->getAccountID()); - // pjsip_regc_destroy(param->regc); - // account->setRegistrationInfo(NULL); + // pjsip_regc_destroy(param->regc); + // account->setRegistrationInfo(NULL); } } } else { account->setRegistrationState (ErrorAuth); account->setRegister (false); - SIPVoIPLink::instance("")->shutdownSipTransport(account->getAccountID()); + SIPVoIPLink::instance ("")->shutdownSipTransport (account->getAccountID()); } } @@ -3522,14 +3528,14 @@ mod_on_rx_request (pjsip_rx_data *rdata) std::string request; - _info("UserAgent: Transaction REQUEST received using transport: %s %s (refcnt=%d)", - rdata->tp_info.transport->obj_name, - rdata->tp_info.transport->info, - (int)pj_atomic_get(rdata->tp_info.transport->ref_cnt)); + _info ("UserAgent: Transaction REQUEST received using transport: %s %s (refcnt=%d)", + rdata->tp_info.transport->obj_name, + rdata->tp_info.transport->info, + (int) pj_atomic_get (rdata->tp_info.transport->ref_cnt)); // No need to go any further on incoming ACK - if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg(rdata) != NULL) { - _info("UserAgent: received an ACK"); + if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg (rdata) != NULL) { + _info ("UserAgent: received an ACK"); return true; } @@ -3556,24 +3562,26 @@ mod_on_rx_request (pjsip_rx_data *rdata) /* If we can't find any voIP link to handle the incoming call */ if (!link) { - _warn("UserAgent: Error: cannot retrieve the voiplink from the account ID..."); - pj_strdup2 (_pool, &reason, "ERROR: cannot retrieve the voip link from account"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); + _warn ("UserAgent: Error: cannot retrieve the voiplink from the account ID..."); + pj_strdup2 (_pool, &reason, "ERROR: cannot retrieve the voip link from account"); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); return true; return false; } // Parse the display name from "From" header char* from_header = strstr (rdata->msg_info.msg_buf, "From: "); + if (from_header) { std::string temp (from_header); int begin_displayName = temp.find ("\"") + 1; int end_displayName = temp.rfind ("\""); displayName = temp.substr (begin_displayName, end_displayName - begin_displayName); - if(displayName.size() > 25) { - displayName = std::string (""); - } + + if (displayName.size() > 25) { + displayName = std::string (""); + } } else { displayName = std::string (""); } @@ -3594,15 +3602,17 @@ mod_on_rx_request (pjsip_rx_data *rdata) std::string peerNumber (tmp, length); //Remove sip: prefix - size_t found = peerNumber.find("sip:"); + size_t found = peerNumber.find ("sip:"); + if (found!=std::string::npos) - peerNumber.erase(found, found+4); + peerNumber.erase (found, found+4); + + found = peerNumber.find ("@"); - found = peerNumber.find("@"); if (found!=std::string::npos) - peerNumber.erase(found); + peerNumber.erase (found); - _debug("UserAgent: Peer number: %s", peerNumber.c_str()); + _debug ("UserAgent: Peer number: %s", peerNumber.c_str()); // Get the server voicemail notification // Catch the NOTIFY message @@ -3634,8 +3644,8 @@ mod_on_rx_request (pjsip_rx_data *rdata) if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD) { if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { pj_strdup2 (_pool, &reason, "user agent unable to handle this request "); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, - &reason, NULL, NULL); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, + &reason, NULL, NULL); return true; } } @@ -3643,20 +3653,22 @@ mod_on_rx_request (pjsip_rx_data *rdata) account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id)); get_remote_sdp_from_offer (rdata, &r_sdp); - if(account->getActiveCodecs().empty()) { - _warn ("UserAgent: Error: No active codec"); - pj_strdup2 (_pool, &reason, "no active codec"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE , - &reason, NULL, NULL); + + if (account->getActiveCodecs().empty()) { + _warn ("UserAgent: Error: No active codec"); + pj_strdup2 (_pool, &reason, "no active codec"); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE , + &reason, NULL, NULL); return true; } // Verify that we can handle the request status = pjsip_inv_verify_request (rdata, &options, NULL, NULL, _endpt, NULL); + if (status != PJ_SUCCESS) { pj_strdup2 (_pool, &reason, "user agent unable to handle this INVITE"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, - &reason, NULL, NULL); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, + &reason, NULL, NULL); return true; } @@ -3664,12 +3676,12 @@ mod_on_rx_request (pjsip_rx_data *rdata) if (Manager::instance().hookPreference.getSipEnabled()) { - _debug("UserAgent: Set sip url hooks"); + _debug ("UserAgent: Set sip url hooks"); std::string header_value; - header_value = fetch_header_value (rdata->msg_info.msg, - Manager::instance().hookPreference.getUrlSipField()); + header_value = fetch_header_value (rdata->msg_info.msg, + Manager::instance().hookPreference.getUrlSipField()); if (header_value.size () < header_value.max_size()) { if (header_value!="") { @@ -3692,10 +3704,10 @@ mod_on_rx_request (pjsip_rx_data *rdata) // If an error occured at the call creation if (!call) { - _warn("UserAgent: Error: Unable to create an incoming call"); + _warn ("UserAgent: Error: Unable to create an incoming call"); pj_strdup2 (_pool, &reason, "unable to create an incoming call"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); return false; } @@ -3707,17 +3719,17 @@ mod_on_rx_request (pjsip_rx_data *rdata) // May use the published address as well - addrToUse = SIPVoIPLink::instance("")->getInterfaceAddrFromName(account->getLocalInterface ()); + addrToUse = SIPVoIPLink::instance ("")->getInterfaceAddrFromName (account->getLocalInterface ()); account->isStunEnabled () ? addrSdp = account->getPublishedAddress () : addrSdp = addrToUse; // Set the appropriate transport to have the right VIA header link->init_transport_selector (account->getAccountTransport (), &tp); - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("UserAgent: SIP transport for this account: %s %s (refcnt=%i)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("UserAgent: SIP transport for this account: %s %s (refcnt=%i)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } } @@ -3735,7 +3747,7 @@ mod_on_rx_request (pjsip_rx_data *rdata) call->setDisplayName (displayName); call->initRecFileName(); - _debug("UserAgent: DisplayName: %s", displayName.c_str()); + _debug ("UserAgent: DisplayName: %s", displayName.c_str()); // Have to do some stuff with the SDP @@ -3755,22 +3767,25 @@ mod_on_rx_request (pjsip_rx_data *rdata) status = call->getLocalSDP()->receiving_initial_offer (r_sdp, account->getActiveCodecs ()); if (status!=PJ_SUCCESS) { - delete call; call = NULL; - _warn("UserAgent: fail in receiving initial offer"); + delete call; + call = NULL; + _warn ("UserAgent: fail in receiving initial offer"); pj_strdup2 (_pool, &reason, "fail in receiving initial offer"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); return false; } /* Create the local dialog (UAS) */ status = pjsip_dlg_create_uas (pjsip_ua_instance(), rdata, NULL, &dialog); + if (status != PJ_SUCCESS) { - delete call; call = NULL; - _warn("UserAgent: Error: Failed to create uas dialog"); + delete call; + call = NULL; + _warn ("UserAgent: Error: Failed to create uas dialog"); pj_strdup2 (_pool, &reason, "fail to create uas dialog"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); return false; } @@ -3799,18 +3814,20 @@ mod_on_rx_request (pjsip_rx_data *rdata) call->setConnectionState (Call::Ringing); _debug ("UserAgent: Add call to account link"); + if (Manager::instance().incomingCall (call, account_id)) { - // Add this call to the callAccountMap in ManagerImpl - Manager::instance().getAccountLink (account_id)->addCall (call); - } else { - // Fail to notify UI - delete call; call = NULL; - _warn ("UserAgent: Fail to notify UI!"); - pj_strdup2 (_pool, &reason, "fail to notify ui"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); - return false; - } + // Add this call to the callAccountMap in ManagerImpl + Manager::instance().getAccountLink (account_id)->addCall (call); + } else { + // Fail to notify UI + delete call; + call = NULL; + _warn ("UserAgent: Fail to notify UI!"); + pj_strdup2 (_pool, &reason, "fail to notify ui"); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); + return false; + } /* Done */ return true; @@ -3820,42 +3837,42 @@ mod_on_rx_request (pjsip_rx_data *rdata) pj_bool_t mod_on_rx_response (pjsip_rx_data *rdata) { _info ("UserAgent: Transaction response using transport: %s %s (refcnt=%d)", - rdata->tp_info.transport->obj_name, - rdata->tp_info.transport->info, - (int)pj_atomic_get(rdata->tp_info.transport->ref_cnt)); + rdata->tp_info.transport->obj_name, + rdata->tp_info.transport->info, + (int) pj_atomic_get (rdata->tp_info.transport->ref_cnt)); pjsip_dialog *dlg; - dlg = pjsip_rdata_get_dlg( rdata ); - - if(dlg != NULL) { - pjsip_transaction *tsx = pjsip_rdata_get_tsx( rdata ); - if ( tsx != NULL && tsx->method.id == PJSIP_INVITE_METHOD) { - if (tsx->status_code < 200) { - _info("UserAgent: Received provisional response"); - } - else if (tsx->status_code >= 300) { - _warn("UserAgent: Dialog failed"); - // pjsip_dlg_dec_session(dlg); - // ACK for non-2xx final response is sent by transaction. - } - else { - _info("UserAgent: Received 200 OK response"); - sendAck(dlg, rdata); - } - } - } + dlg = pjsip_rdata_get_dlg (rdata); + + if (dlg != NULL) { + pjsip_transaction *tsx = pjsip_rdata_get_tsx (rdata); + + if (tsx != NULL && tsx->method.id == PJSIP_INVITE_METHOD) { + if (tsx->status_code < 200) { + _info ("UserAgent: Received provisional response"); + } else if (tsx->status_code >= 300) { + _warn ("UserAgent: Dialog failed"); + // pjsip_dlg_dec_session(dlg); + // ACK for non-2xx final response is sent by transaction. + } else { + _info ("UserAgent: Received 200 OK response"); + sendAck (dlg, rdata); + } + } + } return PJ_SUCCESS; } -static void sendAck(pjsip_dialog *dlg, pjsip_rx_data *rdata) { +static void sendAck (pjsip_dialog *dlg, pjsip_rx_data *rdata) +{ - pjsip_tx_data *tdata; + pjsip_tx_data *tdata; - // Create ACK request - pjsip_dlg_create_request(dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata); + // Create ACK request + pjsip_dlg_create_request (dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata); - pjsip_dlg_send_request( dlg, tdata,-1, NULL); + pjsip_dlg_send_request (dlg, tdata,-1, NULL); } void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata) @@ -3904,7 +3921,7 @@ void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata) * request. */ ref_by_hdr = (pjsip_hdr*) - pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_ref_by, NULL); + pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_ref_by, NULL); /* Notify callback */ code = PJSIP_SC_ACCEPTED; @@ -4136,7 +4153,7 @@ void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) /* This better be a NOTIFY request */ if (r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD && - request.find(method_notify) != (size_t)-1) { + request.find (method_notify) != (size_t)-1) { /* Check if there's body */ msg = r_data->msg_info.msg; @@ -4169,8 +4186,8 @@ void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) } // Get call coresponding to this transaction - std::string transferID(r_data->msg_info.cid->id.ptr, r_data->msg_info.cid->id.slen); - std::map<std::string, CallID>::iterator it = transferCallID.find(transferID); + std::string transferID (r_data->msg_info.cid->id.ptr, r_data->msg_info.cid->id.slen); + std::map<std::string, CallID>::iterator it = transferCallID.find (transferID); CallID cid = it->second; SIPCall *call = dynamic_cast<SIPCall *> (link->getCall (cid)); @@ -4185,10 +4202,11 @@ void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) cont = !is_last; - _debug("UserAgent: Notification status line: %d", status_line.code); + _debug ("UserAgent: Notification status line: %d", status_line.code); + if (status_line.code/100 == 2) { - _debug ("UserAgent: Received 200 OK on call transfered, stop call!"); + _debug ("UserAgent: Received 200 OK on call transfered, stop call!"); pjsip_tx_data *tdata; status = pjsip_inv_end_session (call->getInvSession(), PJSIP_SC_GONE, NULL, &tdata); @@ -4245,7 +4263,7 @@ void xfer_svr_cb (pjsip_evsub *sub, pjsip_event *event) void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer UNUSED) { - _info("UserAgent: Received SDP offer"); + _info ("UserAgent: Received SDP offer"); #ifdef CAN_REINVITE @@ -4276,44 +4294,44 @@ void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer UNUSE } -void on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer) +void on_create_offer (pjsip_inv_session *inv, pjmedia_sdp_session **p_offer) { - _info("UserAgent: Create new SDP offer"); + _info ("UserAgent: Create new SDP offer"); - /* Retrieve the call information */ - SIPCall * call = NULL; - call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]); + /* Retrieve the call information */ + SIPCall * call = NULL; + call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]); - CallID callid = call->getCallId(); - AccountID accountid = Manager::instance().getAccountFromCall(callid); + CallID callid = call->getCallId(); + AccountID accountid = Manager::instance().getAccountFromCall (callid); - SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(accountid)); + SIPAccount *account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountid)); SIPVoIPLink *link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accountid)); - // Set the local address - std::string localAddress = link->getInterfaceAddrFromName(account->getLocalInterface ()); - // Set SDP parameters - Set to local - std::string addrSdp = localAddress; + // Set the local address + std::string localAddress = link->getInterfaceAddrFromName (account->getLocalInterface ()); + // Set SDP parameters - Set to local + std::string addrSdp = localAddress; - _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str()); + _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str()); - // If local address bound to ANY, reslove it using PJSIP - if (localAddress == "0.0.0.0") { - link->loadSIPLocalIP (&localAddress); - } + // If local address bound to ANY, reslove it using PJSIP + if (localAddress == "0.0.0.0") { + link->loadSIPLocalIP (&localAddress); + } - // Local address to appear in SDP - if (addrSdp == "0.0.0.0") { - addrSdp = localAddress; - } + // Local address to appear in SDP + if (addrSdp == "0.0.0.0") { + addrSdp = localAddress; + } // Set local address for RTP media setCallAudioLocal (call, localAddress); // Building the local SDP offer call->getLocalSDP()->set_ip_address (addrSdp); - call->getLocalSDP()->create_initial_offer( account->getActiveCodecs() ); + call->getLocalSDP()->create_initial_offer (account->getActiveCodecs()); *p_offer = call->getLocalSDP()->get_local_sdp_session(); @@ -4369,7 +4387,7 @@ void handle_incoming_options (pjsip_rx_data *rdata) status = pjsip_endpt_send_response (_endpt, &res_addr, tdata, NULL, NULL); - + if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref (tdata); } @@ -4472,24 +4490,24 @@ std::vector<std::string> SIPVoIPLink::getAllIpInterface (void) } -int get_iface_list(struct ifconf *ifconf) +int get_iface_list (struct ifconf *ifconf) { - int sock, rval; + int sock, rval; - if((sock = socket(AF_INET,SOCK_STREAM,0)) < 0) - _debug("get_iface_list error could not open socket\n"); + if ( (sock = socket (AF_INET,SOCK_STREAM,0)) < 0) + _debug ("get_iface_list error could not open socket\n"); - if((rval = ioctl(sock, SIOCGIFCONF , (char*) ifconf )) < 0 ) - _debug("get_iface_list error ioctl(SIOGIFCONF)\n"); + if ( (rval = ioctl (sock, SIOCGIFCONF , (char*) ifconf)) < 0) + _debug ("get_iface_list error ioctl(SIOGIFCONF)\n"); - close(sock); + close (sock); - return rval; + return rval; } -std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName(void) +std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName (void) { std::vector<std::string> ifaceList; @@ -4497,26 +4515,27 @@ std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName(void) struct ifconf ifconf; int nifaces; - // add the default - ifaceList.push_back(std::string("default")); + // add the default + ifaceList.push_back (std::string ("default")); - memset(&ifconf,0,sizeof(ifconf)); + memset (&ifconf,0,sizeof (ifconf)); ifconf.ifc_buf = (char*) (ifreqs); - ifconf.ifc_len = sizeof(ifreqs); + ifconf.ifc_len = sizeof (ifreqs); - if(get_iface_list(&ifconf) < 0) - _debug("getAllIpInterfaceByName error could not get interface list\n"); + if (get_iface_list (&ifconf) < 0) + _debug ("getAllIpInterfaceByName error could not get interface list\n"); - nifaces = ifconf.ifc_len/sizeof(struct ifreq); + nifaces = ifconf.ifc_len/sizeof (struct ifreq); - _debug("Interfaces (count = %d):\n", nifaces); - for(int i = 0; i < nifaces; i++) { - _debug(" %s ", ifreqs[i].ifr_name); - ifaceList.push_back(std::string (ifreqs[i].ifr_name)); - printf(" %s\n", getInterfaceAddrFromName(std::string (ifreqs[i].ifr_name)).c_str()); + _debug ("Interfaces (count = %d):\n", nifaces); + + for (int i = 0; i < nifaces; i++) { + _debug (" %s ", ifreqs[i].ifr_name); + ifaceList.push_back (std::string (ifreqs[i].ifr_name)); + printf (" %s\n", getInterfaceAddrFromName (std::string (ifreqs[i].ifr_name)).c_str()); } - return ifaceList; + return ifaceList; } diff --git a/sflphone-common/test/accounttest.cpp b/sflphone-common/test/accounttest.cpp index dc905e9a8c040aac9bee05f3edca3a723159fa72..b315c2a4197a3449895a583aa8e80ff69659e74e 100644 --- a/sflphone-common/test/accounttest.cpp +++ b/sflphone-common/test/accounttest.cpp @@ -35,18 +35,19 @@ #include "logger.h" #include "validator.h" -void AccountTest::TestAddRemove(void) { - _debug ("-------------------- AccountTest::TestAddRemove --------------------\n"); +void AccountTest::TestAddRemove (void) +{ + _debug ("-------------------- AccountTest::TestAddRemove --------------------\n"); - std::map<std::string, std::string> details; - details[CONFIG_ACCOUNT_TYPE] = "SIP"; - details[CONFIG_ACCOUNT_ENABLE] = "false"; + std::map<std::string, std::string> details; + details[CONFIG_ACCOUNT_TYPE] = "SIP"; + details[CONFIG_ACCOUNT_ENABLE] = "false"; - std::string accountId = Manager::instance().addAccount(details); - CPPUNIT_ASSERT(Validator::isNotNull(accountId)); - CPPUNIT_ASSERT(Manager::instance().accountExists(accountId)); + std::string accountId = Manager::instance().addAccount (details); + CPPUNIT_ASSERT (Validator::isNotNull (accountId)); + CPPUNIT_ASSERT (Manager::instance().accountExists (accountId)); - Manager::instance().removeAccount(accountId); + Manager::instance().removeAccount (accountId); - CPPUNIT_ASSERT(!Manager::instance().accountExists(accountId)); + CPPUNIT_ASSERT (!Manager::instance().accountExists (accountId)); } diff --git a/sflphone-common/test/audiolayertest.cpp b/sflphone-common/test/audiolayertest.cpp index 7119cae3b1d2ab37629d3bf6b44a490c2b1cb025..b60afe8cd05c3ad1076dad06dc555ea9dd28f2db 100644 --- a/sflphone-common/test/audiolayertest.cpp +++ b/sflphone-common/test/audiolayertest.cpp @@ -38,107 +38,110 @@ using std::cout; using std::endl; -void AudioLayerTest::testAudioLayerConfig() { - _debug ("-------------------- AudioLayerTest::testAudioLayerConfig --------------------\n"); +void AudioLayerTest::testAudioLayerConfig() +{ + _debug ("-------------------- AudioLayerTest::testAudioLayerConfig --------------------\n"); - // int sampling_rate = Manager::instance().audioPreference.getSmplrate(); - // int frame_size = Manager::instance().audioPreference.getFramesize(); + // int sampling_rate = Manager::instance().audioPreference.getSmplrate(); + // int frame_size = Manager::instance().audioPreference.getFramesize(); - // int layer = Manager::instance().getAudioDriver()->getLayerType(); + // int layer = Manager::instance().getAudioDriver()->getLayerType(); - // if (layer != ALSA) - // Manager::instance().switchAudioManager(); + // if (layer != ALSA) + // Manager::instance().switchAudioManager(); - // TODO: Fix tests - //CPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getSampleRate() == sampling_rate); + // TODO: Fix tests + //CPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getSampleRate() == sampling_rate); - //CPPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getFrameSize() == frame_size); + //CPPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getFrameSize() == frame_size); } -void AudioLayerTest::testAudioLayerSwitch() { - _debug ("-------------------- AudioLayerTest::testAudioLayerSwitch --------------------\n"); +void AudioLayerTest::testAudioLayerSwitch() +{ + _debug ("-------------------- AudioLayerTest::testAudioLayerSwitch --------------------\n"); - int previous_layer = Manager::instance().getAudioDriver()->getLayerType(); + int previous_layer = Manager::instance().getAudioDriver()->getLayerType(); - for (int i = 0; i < 2; i++) { - _debug ("iter - %i",i); - Manager::instance().switchAudioManager(); + for (int i = 0; i < 2; i++) { + _debug ("iter - %i",i); + Manager::instance().switchAudioManager(); - if (previous_layer == ALSA) { - CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getLayerType() == PULSEAUDIO); - } else { - CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getLayerType() == ALSA); - } + if (previous_layer == ALSA) { + CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getLayerType() == PULSEAUDIO); + } else { + CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getLayerType() == ALSA); + } - previous_layer = Manager::instance().getAudioDriver()->getLayerType(); + previous_layer = Manager::instance().getAudioDriver()->getLayerType(); - usleep(100000); - } + usleep (100000); + } } -void AudioLayerTest::testPulseConnect() { - _debug ("-------------------- AudioLayerTest::testPulseConnect --------------------\n"); +void AudioLayerTest::testPulseConnect() +{ + _debug ("-------------------- AudioLayerTest::testPulseConnect --------------------\n"); - if (Manager::instance().getAudioDriver()->getLayerType() == ALSA) - return; + if (Manager::instance().getAudioDriver()->getLayerType() == ALSA) + return; - ManagerImpl* manager; - manager = &Manager::instance(); + ManagerImpl* manager; + manager = &Manager::instance(); - _pulselayer = (PulseLayer*) Manager::instance().getAudioDriver(); + _pulselayer = (PulseLayer*) Manager::instance().getAudioDriver(); - CPPUNIT_ASSERT (_pulselayer->getLayerType() == PULSEAUDIO); + CPPUNIT_ASSERT (_pulselayer->getLayerType() == PULSEAUDIO); - std::string alsaPlugin; - int numCardIn, numCardOut, numCardRing, sampleRate, frameSize; + std::string alsaPlugin; + int numCardIn, numCardOut, numCardRing, sampleRate, frameSize; - alsaPlugin = manager->audioPreference.getPlugin(); - numCardIn = manager->audioPreference.getCardin(); - numCardOut = manager->audioPreference.getCardout(); - numCardRing = manager->audioPreference.getCardring(); - sampleRate = manager->audioPreference.getSmplrate(); - frameSize = manager->audioPreference.getFramesize(); + alsaPlugin = manager->audioPreference.getPlugin(); + numCardIn = manager->audioPreference.getCardin(); + numCardOut = manager->audioPreference.getCardout(); + numCardRing = manager->audioPreference.getCardring(); + sampleRate = manager->audioPreference.getSmplrate(); + frameSize = manager->audioPreference.getFramesize(); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() == NULL); - CPPUNIT_ASSERT (_pulselayer->getRecordStream() == NULL); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() == NULL); + CPPUNIT_ASSERT (_pulselayer->getRecordStream() == NULL); - _pulselayer->setErrorMessage(-1); + _pulselayer->setErrorMessage (-1); - try { - CPPUNIT_ASSERT (_pulselayer->openDevice (numCardIn, numCardOut, numCardRing, sampleRate, frameSize, SFL_PCM_BOTH, alsaPlugin) == true); - } catch (...) { - _debug ("Exception occured wile opening device! "); - } + try { + CPPUNIT_ASSERT (_pulselayer->openDevice (numCardIn, numCardOut, numCardRing, sampleRate, frameSize, SFL_PCM_BOTH, alsaPlugin) == true); + } catch (...) { + _debug ("Exception occured wile opening device! "); + } - usleep(100000); + usleep (100000); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() == NULL); - CPPUNIT_ASSERT (_pulselayer->getRecordStream() == NULL); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() == NULL); + CPPUNIT_ASSERT (_pulselayer->getRecordStream() == NULL); - _debug ("-------------------------- \n"); - _pulselayer->startStream(); + _debug ("-------------------------- \n"); + _pulselayer->startStream(); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->pulseStream() != NULL); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->pulseStream() != NULL); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->pulseStream() != NULL); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->pulseStream() != NULL); - // Must return No error "PA_OK" == 1 - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 1); - CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 1); + // Must return No error "PA_OK" == 1 + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 1); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->disconnectStream() == true); - CPPUNIT_ASSERT (_pulselayer->getRecordStream()->disconnectStream() == true); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->disconnectStream() == true); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->disconnectStream() == true); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->connectStream(NULL) == true); - CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream(NULL) == true); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->connectStream (NULL) == true); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream (NULL) == true); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 1); - CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 1); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->connectStream(NULL) == true); - CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream(NULL) == true); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->connectStream (NULL) == true); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream (NULL) == true); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 1); - CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 1); - CPPUNIT_ASSERT (_pulselayer->disconnectAudioStream() == true); + CPPUNIT_ASSERT (_pulselayer->disconnectAudioStream() == true); } diff --git a/sflphone-common/test/configurationtest.cpp b/sflphone-common/test/configurationtest.cpp old mode 100755 new mode 100644 index 57a5e27f2c71b357201dbafefe39fe83839e03d2..85abfe2a197c1acc9e23484489446206c4a63546 --- a/sflphone-common/test/configurationtest.cpp +++ b/sflphone-common/test/configurationtest.cpp @@ -37,248 +37,254 @@ using std::cout; using std::endl; -void ConfigurationTest::testDefaultValueAudio() { - _debug ("-------------------- ConfigurationTest::testDefaultValueAudio() --------------------\n"); - - CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardin() == 0); // ALSA_DFT_CARD); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardout() == 0); // ALSA_DFT_CARD); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getSmplrate() == 44100); // DFT_SAMPLE_RATE); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getFramesize() == 20); // DFT_FRAME_SIZE); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getPlugin() == PCM_DEFAULT); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumespkr() == 100); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumemic() == 100); +void ConfigurationTest::testDefaultValueAudio() +{ + _debug ("-------------------- ConfigurationTest::testDefaultValueAudio() --------------------\n"); + + CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardin() == 0); // ALSA_DFT_CARD); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardout() == 0); // ALSA_DFT_CARD); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getSmplrate() == 44100); // DFT_SAMPLE_RATE); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getFramesize() == 20); // DFT_FRAME_SIZE); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getPlugin() == PCM_DEFAULT); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumespkr() == 100); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumemic() == 100); } -void ConfigurationTest::testDefaultValuePreferences() { - _debug ("-------------------- ConfigurationTest::testDefaultValuePreferences --------------------\n"); +void ConfigurationTest::testDefaultValuePreferences() +{ + _debug ("-------------------- ConfigurationTest::testDefaultValuePreferences --------------------\n"); - CPPUNIT_ASSERT (Manager::instance().preferences.getZoneToneChoice() == DFT_ZONE); + CPPUNIT_ASSERT (Manager::instance().preferences.getZoneToneChoice() == DFT_ZONE); } -void ConfigurationTest::testDefaultValueSignalisation() { - _debug ("-------------------- ConfigurationTest::testDefaultValueSignalisation --------------------\n"); +void ConfigurationTest::testDefaultValueSignalisation() +{ + _debug ("-------------------- ConfigurationTest::testDefaultValueSignalisation --------------------\n"); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getSymmetricRtp() == true); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayDtmf() == true); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayTones() == true); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPulseLength() == 250); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getSendDtmfAs() == 0); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getSymmetricRtp() == true); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayDtmf() == true); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayTones() == true); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPulseLength() == 250); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getSendDtmfAs() == 0); } -void ConfigurationTest::testLoadSIPAccount() { - _debug ("-------------------- ConfigurationTest::testLoadSIPAccount --------------------\n"); - - AccountMap accounts; - Account *current; - std::ostringstream ss; - int nb_account; // Must be 1 - - // Load the account from the user file - nb_account = Manager::instance().loadAccountMap(); - CPPUNIT_ASSERT_EQUAL (1, nb_account); - // Save the account information - accounts = Manager::instance()._accountMap; - - AccountMap::iterator iter = accounts.begin(); - CPPUNIT_ASSERT (Manager::instance().accountExists (iter->first) == true); - - while (iter != accounts.end()) { - current = iter->second; - CPPUNIT_ASSERT (iter->first == current->getAccountID()); - CPPUNIT_ASSERT (0 == current->getVoIPLink()); - iter++; - } +void ConfigurationTest::testLoadSIPAccount() +{ + _debug ("-------------------- ConfigurationTest::testLoadSIPAccount --------------------\n"); + + AccountMap accounts; + Account *current; + std::ostringstream ss; + int nb_account; // Must be 1 + + // Load the account from the user file + nb_account = Manager::instance().loadAccountMap(); + CPPUNIT_ASSERT_EQUAL (1, nb_account); + // Save the account information + accounts = Manager::instance()._accountMap; + + AccountMap::iterator iter = accounts.begin(); + CPPUNIT_ASSERT (Manager::instance().accountExists (iter->first) == true); + + while (iter != accounts.end()) { + current = iter->second; + CPPUNIT_ASSERT (iter->first == current->getAccountID()); + CPPUNIT_ASSERT (0 == current->getVoIPLink()); + iter++; + } } -void ConfigurationTest::testUnloadSIPAccount() { - _debug ("-------------------- ConfigurationTest::testUnloadSIPAccount --------------------\n"); +void ConfigurationTest::testUnloadSIPAccount() +{ + _debug ("-------------------- ConfigurationTest::testUnloadSIPAccount --------------------\n"); - AccountMap accounts; + AccountMap accounts; - // Load the accounts from the user file - Manager::instance().loadAccountMap(); - // Unload the accounts - Manager::instance().unloadAccountMap(); - // Save the account information - accounts = Manager::instance()._accountMap; + // Load the accounts from the user file + Manager::instance().loadAccountMap(); + // Unload the accounts + Manager::instance().unloadAccountMap(); + // Save the account information + accounts = Manager::instance()._accountMap; - AccountMap::iterator iter = accounts.begin(); - CPPUNIT_ASSERT (Manager::instance().accountExists (iter->first) == false); + AccountMap::iterator iter = accounts.begin(); + CPPUNIT_ASSERT (Manager::instance().accountExists (iter->first) == false); - if (iter != accounts.end()) { - CPPUNIT_FAIL ("Unload account map failed\n"); - } + if (iter != accounts.end()) { + CPPUNIT_FAIL ("Unload account map failed\n"); + } } -void ConfigurationTest::testInitVolume() { - _debug ("-------------------- ConfigurationTest::testInitVolume --------------------\n"); +void ConfigurationTest::testInitVolume() +{ + _debug ("-------------------- ConfigurationTest::testInitVolume --------------------\n"); + + Manager::instance().initVolume(); - Manager::instance().initVolume(); - - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumespkr() == Manager::instance().getSpkrVolume()); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumemic() == Manager::instance().getMicVolume()); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumespkr() == Manager::instance().getSpkrVolume()); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumemic() == Manager::instance().getMicVolume()); } -void ConfigurationTest::testInitAudioDriver() { - _debug ("-------------------- ConfigurationTest::testInitAudioDriver --------------------\n"); +void ConfigurationTest::testInitAudioDriver() +{ + _debug ("-------------------- ConfigurationTest::testInitAudioDriver --------------------\n"); - // Load the audio driver - Manager::instance().initAudioDriver(); + // Load the audio driver + Manager::instance().initAudioDriver(); - // Check the creation + // Check the creation - if (Manager::instance().getAudioDriver() == NULL) - CPPUNIT_FAIL ("Error while loading audio layer"); + if (Manager::instance().getAudioDriver() == NULL) + CPPUNIT_FAIL ("Error while loading audio layer"); - // Check if it has been created with the right type - if (Manager::instance().preferences.getAudioApi() == ALSA) - CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), ALSA); - else if (Manager::instance().preferences.getAudioApi() == PULSEAUDIO) - CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), PULSEAUDIO); - else - CPPUNIT_FAIL ("Wrong audio layer type"); + // Check if it has been created with the right type + if (Manager::instance().preferences.getAudioApi() == ALSA) + CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), ALSA); + else if (Manager::instance().preferences.getAudioApi() == PULSEAUDIO) + CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), PULSEAUDIO); + else + CPPUNIT_FAIL ("Wrong audio layer type"); } -void ConfigurationTest::testYamlParser() +void ConfigurationTest::testYamlParser() { - Conf::YamlParser *parser; - try { + Conf::YamlParser *parser; + + try { + + parser = new Conf::YamlParser ("sequence2.yml"); + + parser->serializeEvents(); + + parser->composeEvents(); - parser = new Conf::YamlParser("sequence2.yml"); - - parser->serializeEvents(); + parser->constructNativeData(); - parser->composeEvents(); + delete parser; + parser = NULL; - parser->constructNativeData(); - - delete parser; - parser = NULL; + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } - } - catch (Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } - } void ConfigurationTest::testYamlEmitter() { - Conf::YamlEmitter *emitter; - - Conf::MappingNode accountmap(NULL); - Conf::MappingNode credentialmap(NULL); - Conf::MappingNode srtpmap(NULL); - Conf::MappingNode zrtpmap(NULL); - Conf::MappingNode tlsmap(NULL); - - - Conf::ScalarNode id("Account:1278432417"); - Conf::ScalarNode username("181"); - Conf::ScalarNode password("pass181"); - Conf::ScalarNode alias("sfl-181"); - Conf::ScalarNode hostname("192.168.50.3"); - Conf::ScalarNode enable("true"); - Conf::ScalarNode type("SIP"); - Conf::ScalarNode expire("3600"); - Conf::ScalarNode interface("default"); - Conf::ScalarNode port("5060"); - Conf::ScalarNode mailbox("97"); - Conf::ScalarNode publishAddr("192.168.50.182"); - Conf::ScalarNode publishPort("5060"); - Conf::ScalarNode sameasLocal("true"); - Conf::ScalarNode resolveOnce("false"); - Conf::ScalarNode codecs("0/9/110/111/112/"); - Conf::ScalarNode stunServer("stun.sflphone.org"); - Conf::ScalarNode stunEnabled("false"); - Conf::ScalarNode displayName("Alexandre Savard"); - Conf::ScalarNode dtmfType("sipinfo"); - - Conf::ScalarNode count("0"); - - Conf::ScalarNode srtpenabled("false"); - Conf::ScalarNode keyExchange("sdes"); - Conf::ScalarNode rtpFallback("false"); - - Conf::ScalarNode displaySas("false"); - Conf::ScalarNode displaySasOnce("false"); - Conf::ScalarNode helloHashEnabled("false"); - Conf::ScalarNode notSuppWarning("false"); - - Conf::ScalarNode tlsport(""); - Conf::ScalarNode certificate(""); - Conf::ScalarNode calist(""); - Conf::ScalarNode ciphers(""); - Conf::ScalarNode tlsenabled("false"); - Conf::ScalarNode tlsmethod("TLSV1"); - Conf::ScalarNode timeout("0"); - Conf::ScalarNode tlspassword(""); - Conf::ScalarNode privatekey(""); - Conf::ScalarNode requirecertif("true"); - Conf::ScalarNode server(""); - Conf::ScalarNode verifyclient("true"); - Conf::ScalarNode verifyserver("true"); - - accountmap.setKeyValue(aliasKey, &alias); - accountmap.setKeyValue(typeKey, &type); - accountmap.setKeyValue(idKey, &id); - accountmap.setKeyValue(usernameKey, &username); - accountmap.setKeyValue(passwordKey, &password); - accountmap.setKeyValue(hostnameKey, &hostname); - accountmap.setKeyValue(accountEnableKey, &enable); - accountmap.setKeyValue(mailboxKey, &mailbox); - accountmap.setKeyValue(expireKey, &expire); - accountmap.setKeyValue(interfaceKey, &interface); - accountmap.setKeyValue(portKey, &port); - accountmap.setKeyValue(publishAddrKey, &publishAddr); - accountmap.setKeyValue(publishPortKey, &publishPort); - accountmap.setKeyValue(sameasLocalKey, &sameasLocal); - accountmap.setKeyValue(resolveOnceKey, &resolveOnce); - accountmap.setKeyValue(dtmfTypeKey, &dtmfType); - accountmap.setKeyValue(displayNameKey, &displayName); - - accountmap.setKeyValue(srtpKey, &srtpmap); - srtpmap.setKeyValue(srtpEnableKey, &srtpenabled); - srtpmap.setKeyValue(keyExchangeKey, &keyExchange); - srtpmap.setKeyValue(rtpFallbackKey, &rtpFallback); - - accountmap.setKeyValue(zrtpKey, &zrtpmap); - zrtpmap.setKeyValue(displaySasKey, &displaySas); - zrtpmap.setKeyValue(displaySasOnceKey, &displaySasOnce); - zrtpmap.setKeyValue(helloHashEnabledKey, &helloHashEnabled); - zrtpmap.setKeyValue(notSuppWarningKey, ¬SuppWarning); - - accountmap.setKeyValue(credKey, &credentialmap); - credentialmap.setKeyValue(credentialCountKey, &count); - - accountmap.setKeyValue(tlsKey, &tlsmap); - tlsmap.setKeyValue(tlsPortKey, &tlsport); - tlsmap.setKeyValue(certificateKey, &certificate); - tlsmap.setKeyValue(calistKey, &calist); - tlsmap.setKeyValue(ciphersKey, &ciphers); - tlsmap.setKeyValue(tlsEnableKey, &tlsenabled); - tlsmap.setKeyValue(methodKey, &tlsmethod); - tlsmap.setKeyValue(timeoutKey, &timeout); - tlsmap.setKeyValue(tlsPasswordKey, &tlspassword); - tlsmap.setKeyValue(privateKeyKey, &privatekey); - tlsmap.setKeyValue(requireCertifKey, &requirecertif); - tlsmap.setKeyValue(serverKey, &server); - tlsmap.setKeyValue(verifyClientKey, &verifyclient); - tlsmap.setKeyValue(verifyServerKey, &verifyserver); - - try{ - emitter = new Conf::YamlEmitter("/tmp/sequenceEmiter.txt"); - - emitter->serializeAccount(&accountmap); - emitter->serializeAccount(&accountmap); - emitter->serializeData(); - - delete emitter; - } - catch (Conf::YamlEmitterException &e) { - _error("ConfigTree: %s", e.what()); - } + Conf::YamlEmitter *emitter; + + Conf::MappingNode accountmap (NULL); + Conf::MappingNode credentialmap (NULL); + Conf::MappingNode srtpmap (NULL); + Conf::MappingNode zrtpmap (NULL); + Conf::MappingNode tlsmap (NULL); + + + Conf::ScalarNode id ("Account:1278432417"); + Conf::ScalarNode username ("181"); + Conf::ScalarNode password ("pass181"); + Conf::ScalarNode alias ("sfl-181"); + Conf::ScalarNode hostname ("192.168.50.3"); + Conf::ScalarNode enable ("true"); + Conf::ScalarNode type ("SIP"); + Conf::ScalarNode expire ("3600"); + Conf::ScalarNode interface ("default"); + Conf::ScalarNode port ("5060"); + Conf::ScalarNode mailbox ("97"); + Conf::ScalarNode publishAddr ("192.168.50.182"); + Conf::ScalarNode publishPort ("5060"); + Conf::ScalarNode sameasLocal ("true"); + Conf::ScalarNode resolveOnce ("false"); + Conf::ScalarNode codecs ("0/9/110/111/112/"); + Conf::ScalarNode stunServer ("stun.sflphone.org"); + Conf::ScalarNode stunEnabled ("false"); + Conf::ScalarNode displayName ("Alexandre Savard"); + Conf::ScalarNode dtmfType ("sipinfo"); + + Conf::ScalarNode count ("0"); + + Conf::ScalarNode srtpenabled ("false"); + Conf::ScalarNode keyExchange ("sdes"); + Conf::ScalarNode rtpFallback ("false"); + + Conf::ScalarNode displaySas ("false"); + Conf::ScalarNode displaySasOnce ("false"); + Conf::ScalarNode helloHashEnabled ("false"); + Conf::ScalarNode notSuppWarning ("false"); + + Conf::ScalarNode tlsport (""); + Conf::ScalarNode certificate (""); + Conf::ScalarNode calist (""); + Conf::ScalarNode ciphers (""); + Conf::ScalarNode tlsenabled ("false"); + Conf::ScalarNode tlsmethod ("TLSV1"); + Conf::ScalarNode timeout ("0"); + Conf::ScalarNode tlspassword (""); + Conf::ScalarNode privatekey (""); + Conf::ScalarNode requirecertif ("true"); + Conf::ScalarNode server (""); + Conf::ScalarNode verifyclient ("true"); + Conf::ScalarNode verifyserver ("true"); + + accountmap.setKeyValue (aliasKey, &alias); + accountmap.setKeyValue (typeKey, &type); + accountmap.setKeyValue (idKey, &id); + accountmap.setKeyValue (usernameKey, &username); + accountmap.setKeyValue (passwordKey, &password); + accountmap.setKeyValue (hostnameKey, &hostname); + accountmap.setKeyValue (accountEnableKey, &enable); + accountmap.setKeyValue (mailboxKey, &mailbox); + accountmap.setKeyValue (expireKey, &expire); + accountmap.setKeyValue (interfaceKey, &interface); + accountmap.setKeyValue (portKey, &port); + accountmap.setKeyValue (publishAddrKey, &publishAddr); + accountmap.setKeyValue (publishPortKey, &publishPort); + accountmap.setKeyValue (sameasLocalKey, &sameasLocal); + accountmap.setKeyValue (resolveOnceKey, &resolveOnce); + accountmap.setKeyValue (dtmfTypeKey, &dtmfType); + accountmap.setKeyValue (displayNameKey, &displayName); + + accountmap.setKeyValue (srtpKey, &srtpmap); + srtpmap.setKeyValue (srtpEnableKey, &srtpenabled); + srtpmap.setKeyValue (keyExchangeKey, &keyExchange); + srtpmap.setKeyValue (rtpFallbackKey, &rtpFallback); + + accountmap.setKeyValue (zrtpKey, &zrtpmap); + zrtpmap.setKeyValue (displaySasKey, &displaySas); + zrtpmap.setKeyValue (displaySasOnceKey, &displaySasOnce); + zrtpmap.setKeyValue (helloHashEnabledKey, &helloHashEnabled); + zrtpmap.setKeyValue (notSuppWarningKey, ¬SuppWarning); + + accountmap.setKeyValue (credKey, &credentialmap); + credentialmap.setKeyValue (credentialCountKey, &count); + + accountmap.setKeyValue (tlsKey, &tlsmap); + tlsmap.setKeyValue (tlsPortKey, &tlsport); + tlsmap.setKeyValue (certificateKey, &certificate); + tlsmap.setKeyValue (calistKey, &calist); + tlsmap.setKeyValue (ciphersKey, &ciphers); + tlsmap.setKeyValue (tlsEnableKey, &tlsenabled); + tlsmap.setKeyValue (methodKey, &tlsmethod); + tlsmap.setKeyValue (timeoutKey, &timeout); + tlsmap.setKeyValue (tlsPasswordKey, &tlspassword); + tlsmap.setKeyValue (privateKeyKey, &privatekey); + tlsmap.setKeyValue (requireCertifKey, &requirecertif); + tlsmap.setKeyValue (serverKey, &server); + tlsmap.setKeyValue (verifyClientKey, &verifyclient); + tlsmap.setKeyValue (verifyServerKey, &verifyserver); + + try { + emitter = new Conf::YamlEmitter ("/tmp/sequenceEmiter.txt"); + + emitter->serializeAccount (&accountmap); + emitter->serializeAccount (&accountmap); + emitter->serializeData(); + + delete emitter; + } catch (Conf::YamlEmitterException &e) { + _error ("ConfigTree: %s", e.what()); + } } diff --git a/sflphone-common/test/delaydetectiontest.cpp b/sflphone-common/test/delaydetectiontest.cpp index a0bb79bbc8335c1f783e48caaf0e18cfb41c8cfd..c4bc3e26f7a41a045a14481cd59367a875f22c14 100644 --- a/sflphone-common/test/delaydetectiontest.cpp +++ b/sflphone-common/test/delaydetectiontest.cpp @@ -39,7 +39,7 @@ void DelayDetectionTest::setUp() {} void DelayDetectionTest::tearDown() {} -void DelayDetectionTest::testCrossCorrelation() +void DelayDetectionTest::testCrossCorrelation() { float signal[10] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; float ref[3] = {0.0, 1.0, 2.0}; @@ -47,165 +47,176 @@ void DelayDetectionTest::testCrossCorrelation() float result[10]; float expected[10] = {0.0, 0.89442719, 1.0, 0.95618289, 0.91350028, 0.88543774, 0.86640023, 0.85280287, 0.8426548, 0.83480969}; - CPPUNIT_ASSERT(_delaydetect.correlate(ref, ref, 3) == 5.0); - CPPUNIT_ASSERT(_delaydetect.correlate(signal, signal, 10) == 285.0); - - _delaydetect.crossCorrelate(ref, signal, result, 3, 10); + CPPUNIT_ASSERT (_delaydetect.correlate (ref, ref, 3) == 5.0); + CPPUNIT_ASSERT (_delaydetect.correlate (signal, signal, 10) == 285.0); + + _delaydetect.crossCorrelate (ref, signal, result, 3, 10); float tmp; + for (int i = 0; i < 10; i++) { tmp = result[i]-expected[i]; - if(tmp < 0.0) - CPPUNIT_ASSERT (tmp > -0.001); - else - CPPUNIT_ASSERT(tmp < 0.001); + + if (tmp < 0.0) + CPPUNIT_ASSERT (tmp > -0.001); + else + CPPUNIT_ASSERT (tmp < 0.001); } } void DelayDetectionTest::testCrossCorrelationDelay() { - float signal[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0}; - float ref[3] = {0.0, 1.0, 0.0}; + float signal[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0}; + float ref[3] = {0.0, 1.0, 0.0}; + + float result[10]; - float result[10]; + _delaydetect.crossCorrelate (ref, signal, result, 3, 10); - _delaydetect.crossCorrelate(ref, signal, result, 3, 10); + float expected[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0}; - float expected[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0}; - } void DelayDetectionTest::testFirFilter() { float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03630817, 0.02944626, - 0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722, - -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204, - 0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179, - 0.1160644, 0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299, - 0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834, - -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367, - 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, - 0.05616626, 0.07473655, -0.09870257}; - std::vector<double> ird(decimationCoefs, decimationCoefs + sizeof(decimationCoefs)/sizeof(float)); + 0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722, + -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204, + 0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179, + 0.1160644, 0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299, + 0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834, + -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367, + 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, + 0.05616626, 0.07473655, -0.09870257 + }; + std::vector<double> ird (decimationCoefs, decimationCoefs + sizeof (decimationCoefs) /sizeof (float)); float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113, - 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, - -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563, - 0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507, - -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, - 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034}; - std::vector<double> irb(bandpassCoefs, bandpassCoefs + sizeof(bandpassCoefs)/sizeof(float)); + 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, + -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563, + 0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507, + -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, + 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034 + }; + std::vector<double> irb (bandpassCoefs, bandpassCoefs + sizeof (bandpassCoefs) /sizeof (float)); float impulse[100]; - memset(impulse, 0, sizeof(float)*100); + memset (impulse, 0, sizeof (float) *100); impulse[0] = 1.0; - FirFilter _decimationFilter(ird); - FirFilter _bandpassFilter(irb); + FirFilter _decimationFilter (ird); + FirFilter _bandpassFilter (irb); float impulseresponse[100]; - memset(impulseresponse, 0, sizeof(float)*100); + memset (impulseresponse, 0, sizeof (float) *100); // compute impulse response - for(int i = 0; i < 100; i++) { - impulseresponse[i] = _decimationFilter.getOutputSample(impulse[i]); + for (int i = 0; i < 100; i++) { + impulseresponse[i] = _decimationFilter.getOutputSample (impulse[i]); } float tmp; - int size = sizeof(decimationCoefs)/sizeof(float); - for(int i = 0; i < size; i++) { - tmp = decimationCoefs[i] - impulseresponse[i]; - if(tmp < 0.0) - CPPUNIT_ASSERT (tmp > -0.000001); - else - CPPUNIT_ASSERT(tmp < 0.000001); + int size = sizeof (decimationCoefs) /sizeof (float); + + for (int i = 0; i < size; i++) { + tmp = decimationCoefs[i] - impulseresponse[i]; + + if (tmp < 0.0) + CPPUNIT_ASSERT (tmp > -0.000001); + else + CPPUNIT_ASSERT (tmp < 0.000001); } - for(int i = 0; i < 100; i++) { - impulseresponse[i] = _bandpassFilter.getOutputSample(impulse[i]); + for (int i = 0; i < 100; i++) { + impulseresponse[i] = _bandpassFilter.getOutputSample (impulse[i]); } - size = sizeof(bandpassCoefs)/sizeof(float); - for(int i = 0; i < size; i++) { - tmp = bandpassCoefs[i] - impulseresponse[i]; - if(tmp < 0.0) - CPPUNIT_ASSERT (tmp > -0.000001); - else - CPPUNIT_ASSERT(tmp < 0.000001); + size = sizeof (bandpassCoefs) /sizeof (float); + + for (int i = 0; i < size; i++) { + tmp = bandpassCoefs[i] - impulseresponse[i]; + + if (tmp < 0.0) + CPPUNIT_ASSERT (tmp > -0.000001); + else + CPPUNIT_ASSERT (tmp < 0.000001); } - + } -void DelayDetectionTest::testIntToFloatConversion() { +void DelayDetectionTest::testIntToFloatConversion() +{ + + SFLDataFormat data[32768*2]; + float converted[32768*2]; - SFLDataFormat data[32768*2]; - float converted[32768*2]; + for (int i = -32768; i < 32768; i++) + data[i+32768] = i; - for(int i = -32768; i < 32768; i++) - data[i+32768] = i; - - _delaydetect.convertInt16ToFloat32(data, converted, 32768*2); + _delaydetect.convertInt16ToFloat32 (data, converted, 32768*2); - for(int i = -32768; i < 0; i++) { - CPPUNIT_ASSERT(converted[i+32768] >= -1.0); - CPPUNIT_ASSERT(converted[i+32768] <= 0.0); - } + for (int i = -32768; i < 0; i++) { + CPPUNIT_ASSERT (converted[i+32768] >= -1.0); + CPPUNIT_ASSERT (converted[i+32768] <= 0.0); + } - for(int i = 0; i < 32768; i++) { - CPPUNIT_ASSERT(converted[i+32768] >= 0.0); - CPPUNIT_ASSERT(converted[i+32768] <= 1.0); - } + for (int i = 0; i < 32768; i++) { + CPPUNIT_ASSERT (converted[i+32768] >= 0.0); + CPPUNIT_ASSERT (converted[i+32768] <= 1.0); + } } -void DelayDetectionTest::testDownSamplingData() { +void DelayDetectionTest::testDownSamplingData() +{ + + SFLDataFormat data[32768*2]; + float converted[32768*2]; + float resampled[32768*2]; - SFLDataFormat data[32768*2]; - float converted[32768*2]; - float resampled[32768*2]; + for (int i = -32768; i < 32768; i++) + data[i+32768] = i; - for(int i = -32768; i < 32768; i++) - data[i+32768] = i; + _delaydetect.convertInt16ToFloat32 (data, converted, 32768*2); - _delaydetect.convertInt16ToFloat32(data, converted, 32768*2); + _delaydetect.downsampleData (converted, resampled, 32768*2, 8); - _delaydetect.downsampleData(converted, resampled, 32768*2, 8); + for (int i = 0; i < 32768/8; i++) { + CPPUNIT_ASSERT (resampled[i] >= -1.0); + CPPUNIT_ASSERT (resampled[i] <= 0.0); + } - for(int i = 0; i < 32768/8; i++) { - CPPUNIT_ASSERT(resampled[i] >= -1.0); - CPPUNIT_ASSERT(resampled[i] <= 0.0); - } + for (int i = 32768/8+1; i < 32768/4; i++) { + CPPUNIT_ASSERT (resampled[i] >= 0.0); + CPPUNIT_ASSERT (resampled[i] <= 1.0); + } - for(int i = 32768/8+1; i < 32768/4; i++) { - CPPUNIT_ASSERT(resampled[i] >= 0.0); - CPPUNIT_ASSERT(resampled[i] <= 1.0); - } - } -void DelayDetectionTest::testDelayDetection() { - - int delay = 100; - - SFLDataFormat spkr[WINDOW_SIZE]; - memset(spkr, 0, sizeof(SFLDataFormat)*WINDOW_SIZE); - spkr[0] = 32000; - spkr[1] = 32000; - spkr[2] = 32000; - spkr[3] = 32000; - spkr[4] = 32000; - - SFLDataFormat mic[DELAY_BUFF_SIZE]; - memset(mic, 0, sizeof(SFLDataFormat)*DELAY_BUFF_SIZE); - mic[delay] = 32000; - mic[delay+1] = 32000; - mic[delay+2] = 32000; - mic[delay+3] = 32000; - mic[delay+4] = 32000; - - _delaydetect.putData(spkr, WINDOW_SIZE*sizeof(SFLDataFormat)); - _delaydetect.process(mic, DELAY_BUFF_SIZE*sizeof(SFLDataFormat)); +void DelayDetectionTest::testDelayDetection() +{ + + int delay = 100; + + SFLDataFormat spkr[WINDOW_SIZE]; + memset (spkr, 0, sizeof (SFLDataFormat) *WINDOW_SIZE); + spkr[0] = 32000; + spkr[1] = 32000; + spkr[2] = 32000; + spkr[3] = 32000; + spkr[4] = 32000; + + SFLDataFormat mic[DELAY_BUFF_SIZE]; + memset (mic, 0, sizeof (SFLDataFormat) *DELAY_BUFF_SIZE); + mic[delay] = 32000; + mic[delay+1] = 32000; + mic[delay+2] = 32000; + mic[delay+3] = 32000; + mic[delay+4] = 32000; + + _delaydetect.putData (spkr, WINDOW_SIZE*sizeof (SFLDataFormat)); + _delaydetect.process (mic, DELAY_BUFF_SIZE*sizeof (SFLDataFormat)); } diff --git a/sflphone-common/test/historytest.cpp b/sflphone-common/test/historytest.cpp index 8f0853c6a142b7ece063c455b97fb0369473b74e..f2fe88f4941d357ef1e8551f85f655b9ca977b8d 100644 --- a/sflphone-common/test/historytest.cpp +++ b/sflphone-common/test/historytest.cpp @@ -39,188 +39,198 @@ using std::cout; using std::endl; -void HistoryTest::setUp() { - // Instanciate the cleaner singleton - history = new HistoryManager(); +void HistoryTest::setUp() +{ + // Instanciate the cleaner singleton + history = new HistoryManager(); } -void HistoryTest::test_create_history_path() { - _debug ("-------------------- HistoryTest::test_create_history_path --------------------\n"); +void HistoryTest::test_create_history_path() +{ + _debug ("-------------------- HistoryTest::test_create_history_path --------------------\n"); - int result; - char *cpath; - std::string path; + int result; + char *cpath; + std::string path; - cpath = getenv("XDG_DATA_HOME"); - (cpath != NULL) ? path = std::string(cpath) : path = std::string(HOMEDIR) - + "/.local/share/sflphone/history"; + cpath = getenv ("XDG_DATA_HOME"); + (cpath != NULL) ? path = std::string (cpath) : path = std::string (HOMEDIR) + + "/.local/share/sflphone/history"; - result = history->create_history_path(); - CPPUNIT_ASSERT (result == 0); - CPPUNIT_ASSERT (!history->is_loaded ()); - CPPUNIT_ASSERT (history->_history_path == path); + result = history->create_history_path(); + CPPUNIT_ASSERT (result == 0); + CPPUNIT_ASSERT (!history->is_loaded ()); + CPPUNIT_ASSERT (history->_history_path == path); } -void HistoryTest::test_load_history_from_file() { - _debug ("-------------------- HistoryTest::test_load_history_from_file --------------------\n"); +void HistoryTest::test_load_history_from_file() +{ + _debug ("-------------------- HistoryTest::test_load_history_from_file --------------------\n"); - bool res; - Conf::ConfigTree history_list; + bool res; + Conf::ConfigTree history_list; - history->create_history_path(); - res = history->load_history_from_file(&history_list); + history->create_history_path(); + res = history->load_history_from_file (&history_list); - CPPUNIT_ASSERT (history->is_loaded ()); - CPPUNIT_ASSERT (res == true); + CPPUNIT_ASSERT (history->is_loaded ()); + CPPUNIT_ASSERT (res == true); } -void HistoryTest::test_load_history_items_map() { - _debug ("-------------------- HistoryTest::test_load_history_items_map --------------------\n"); +void HistoryTest::test_load_history_items_map() +{ + _debug ("-------------------- HistoryTest::test_load_history_items_map --------------------\n"); - std::string path; - int nb_items; - Conf::ConfigTree history_list; + std::string path; + int nb_items; + Conf::ConfigTree history_list; - history->set_history_path(HISTORY_SAMPLE); - history->load_history_from_file(&history_list); - nb_items = history->load_history_items_map(&history_list, - HUGE_HISTORY_LIMIT); - CPPUNIT_ASSERT (nb_items == HISTORY_SAMPLE_SIZE); - CPPUNIT_ASSERT (history->get_history_size () == HISTORY_SAMPLE_SIZE); + history->set_history_path (HISTORY_SAMPLE); + history->load_history_from_file (&history_list); + nb_items = history->load_history_items_map (&history_list, + HUGE_HISTORY_LIMIT); + CPPUNIT_ASSERT (nb_items == HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT (history->get_history_size () == HISTORY_SAMPLE_SIZE); } -void HistoryTest::test_save_history_items_map() { - _debug ("-------------------- HistoryTest::test_save_history_items_map --------------------\n"); +void HistoryTest::test_save_history_items_map() +{ + _debug ("-------------------- HistoryTest::test_save_history_items_map --------------------\n"); - std::string path; - int nb_items_loaded, nb_items_saved; - Conf::ConfigTree history_list, history_list2; + std::string path; + int nb_items_loaded, nb_items_saved; + Conf::ConfigTree history_list, history_list2; - history->set_history_path(HISTORY_SAMPLE); - history->load_history_from_file(&history_list); - nb_items_loaded = history->load_history_items_map(&history_list, - HUGE_HISTORY_LIMIT); - nb_items_saved = history->save_history_items_map(&history_list2); - CPPUNIT_ASSERT (nb_items_loaded == nb_items_saved); + history->set_history_path (HISTORY_SAMPLE); + history->load_history_from_file (&history_list); + nb_items_loaded = history->load_history_items_map (&history_list, + HUGE_HISTORY_LIMIT); + nb_items_saved = history->save_history_items_map (&history_list2); + CPPUNIT_ASSERT (nb_items_loaded == nb_items_saved); } -void HistoryTest::test_save_history_to_file() { - _debug ("-------------------- HistoryTest::test_save_history_to_file --------------------\n"); +void HistoryTest::test_save_history_to_file() +{ + _debug ("-------------------- HistoryTest::test_save_history_to_file --------------------\n"); - std::string path; - Conf::ConfigTree history_list, history_list2; - std::map<std::string, std::string> res; - std::map<std::string, std::string>::iterator iter; + std::string path; + Conf::ConfigTree history_list, history_list2; + std::map<std::string, std::string> res; + std::map<std::string, std::string>::iterator iter; - history->set_history_path(HISTORY_SAMPLE); - history->load_history_from_file(&history_list); - history->load_history_items_map(&history_list, HUGE_HISTORY_LIMIT); - history->save_history_items_map(&history_list2); - CPPUNIT_ASSERT (history->save_history_to_file (&history_list2)); + history->set_history_path (HISTORY_SAMPLE); + history->load_history_from_file (&history_list); + history->load_history_items_map (&history_list, HUGE_HISTORY_LIMIT); + history->save_history_items_map (&history_list2); + CPPUNIT_ASSERT (history->save_history_to_file (&history_list2)); } -void HistoryTest::test_get_history_serialized() { - _debug ("-------------------- HistoryTest::test_get_history_serialized --------------------\n"); +void HistoryTest::test_get_history_serialized() +{ + _debug ("-------------------- HistoryTest::test_get_history_serialized --------------------\n"); - std::map<std::string, std::string> res; - std::map<std::string, std::string>::iterator iter; - std::string tmp; + std::map<std::string, std::string> res; + std::map<std::string, std::string>::iterator iter; + std::string tmp; - CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); - res = history->get_history_serialized(); - CPPUNIT_ASSERT (res.size() ==HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); + res = history->get_history_serialized(); + CPPUNIT_ASSERT (res.size() ==HISTORY_SAMPLE_SIZE); - // Warning - If you change the history-sample file, you must change the following lines also so that the tests could work - // The reference here is the file history-sample in this test directory - // The serialized form is: calltype%to%from%callid + // Warning - If you change the history-sample file, you must change the following lines also so that the tests could work + // The reference here is the file history-sample in this test directory + // The serialized form is: calltype%to%from%callid - // Check the first - tmp = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, res ["144562436"])); + // Check the first + tmp = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, res ["144562436"])); - tmp = "2|136|Emmanuel Milou|747638765|Account:1239059899"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, res ["747638685"])); + tmp = "2|136|Emmanuel Milou|747638765|Account:1239059899"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, res ["747638685"])); - // the account ID does not correspond to a loaded account - tmp = "1|5143848557|empty|775354987|empty"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, res ["775354456"])); + // the account ID does not correspond to a loaded account + tmp = "1|5143848557|empty|775354987|empty"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, res ["775354456"])); } -void HistoryTest::test_set_serialized_history() { - _debug ("-------------------- HistoryTest::test_set_serialized_history --------------------\n"); +void HistoryTest::test_set_serialized_history() +{ + _debug ("-------------------- HistoryTest::test_set_serialized_history --------------------\n"); - // We build a map to have an efficient test - std::map<std::string, std::string> map_test; - std::string tmp; - Conf::ConfigTree history_list; + // We build a map to have an efficient test + std::map<std::string, std::string> map_test; + std::string tmp; + Conf::ConfigTree history_list; - map_test["144562436"] = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; - map_test["747638685"] = "2|136|Emmanuel Milou|747638765|Account:1239059899"; - map_test["775354456"] = "1|5143848557|empty|775354987|Account:43789459478"; + map_test["144562436"] = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; + map_test["747638685"] = "2|136|Emmanuel Milou|747638765|Account:1239059899"; + map_test["775354456"] = "1|5143848557|empty|775354987|Account:43789459478"; - CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); - // We use a large history limit to be able to interpret results - CPPUNIT_ASSERT (history->set_serialized_history (map_test, HUGE_HISTORY_LIMIT) == 3); - CPPUNIT_ASSERT (history->get_history_size () == 3); + CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); + // We use a large history limit to be able to interpret results + CPPUNIT_ASSERT (history->set_serialized_history (map_test, HUGE_HISTORY_LIMIT) == 3); + CPPUNIT_ASSERT (history->get_history_size () == 3); - map_test.clear(); - map_test = history->get_history_serialized(); - CPPUNIT_ASSERT (map_test.size() ==3); + map_test.clear(); + map_test = history->get_history_serialized(); + CPPUNIT_ASSERT (map_test.size() ==3); - // Check the first - tmp = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, map_test ["144562436"])); + // Check the first + tmp = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, map_test ["144562436"])); - tmp = "2|136|Emmanuel Milou|747638765|Account:1239059899"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, map_test ["747638685"])); + tmp = "2|136|Emmanuel Milou|747638765|Account:1239059899"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, map_test ["747638685"])); - // the account ID does not correspond to a loaded account - tmp = "1|5143848557|empty|775354987|empty"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, map_test ["775354456"])); + // the account ID does not correspond to a loaded account + tmp = "1|5143848557|empty|775354987|empty"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, map_test ["775354456"])); - history->save_history_items_map(&history_list); - CPPUNIT_ASSERT (history->save_history_to_file (&history_list)); + history->save_history_items_map (&history_list); + CPPUNIT_ASSERT (history->save_history_to_file (&history_list)); } -void HistoryTest::test_set_serialized_history_with_limit() { - _debug ("-------------------- HistoryTest::test_set_serialized_history_with_limit --------------------\n"); - - // We build a map to have an efficient test - std::map<std::string, std::string> map_test; - std::string tmp; - Conf::ConfigTree history_list; - time_t current, day = 86400; // One day in unix timestamp - std::stringstream current_1, current_2, current_3; - - (void) time(¤t); - current_1 << (current - 2 * day) << std::endl; - current_2 << (current - 5 * day) << std::endl; - current_3 << (current - 11 * day) << std::endl; - - map_test[current_1.str()] - = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; - map_test[current_2.str()] - = "2|136|Emmanuel Milou|747638765|Account:1239059899"; - map_test[current_3.str()] - = "1|5143848557|empty|775354987|Account:43789459478"; - - CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); - // We use different value of history limit - // 10 days - the last entry should not be saved - CPPUNIT_ASSERT (history->set_serialized_history (map_test, 10) == 2); - CPPUNIT_ASSERT (history->get_history_size () == 2); - - // 4 days - the two last entries should not be saved - CPPUNIT_ASSERT (history->set_serialized_history (map_test, 4) == 1); - CPPUNIT_ASSERT (history->get_history_size () == 1); - - // 1 day - no entry should not be saved - CPPUNIT_ASSERT (history->set_serialized_history (map_test, 1) == 0); - CPPUNIT_ASSERT (history->get_history_size () == 0); +void HistoryTest::test_set_serialized_history_with_limit() +{ + _debug ("-------------------- HistoryTest::test_set_serialized_history_with_limit --------------------\n"); + + // We build a map to have an efficient test + std::map<std::string, std::string> map_test; + std::string tmp; + Conf::ConfigTree history_list; + time_t current, day = 86400; // One day in unix timestamp + std::stringstream current_1, current_2, current_3; + + (void) time (¤t); + current_1 << (current - 2 * day) << std::endl; + current_2 << (current - 5 * day) << std::endl; + current_3 << (current - 11 * day) << std::endl; + + map_test[current_1.str() ] + = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; + map_test[current_2.str() ] + = "2|136|Emmanuel Milou|747638765|Account:1239059899"; + map_test[current_3.str() ] + = "1|5143848557|empty|775354987|Account:43789459478"; + + CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); + // We use different value of history limit + // 10 days - the last entry should not be saved + CPPUNIT_ASSERT (history->set_serialized_history (map_test, 10) == 2); + CPPUNIT_ASSERT (history->get_history_size () == 2); + + // 4 days - the two last entries should not be saved + CPPUNIT_ASSERT (history->set_serialized_history (map_test, 4) == 1); + CPPUNIT_ASSERT (history->get_history_size () == 1); + + // 1 day - no entry should not be saved + CPPUNIT_ASSERT (history->set_serialized_history (map_test, 1) == 0); + CPPUNIT_ASSERT (history->get_history_size () == 0); } -void HistoryTest::tearDown() { - // Delete the history object - delete history; - history = 0; +void HistoryTest::tearDown() +{ + // Delete the history object + delete history; + history = 0; } diff --git a/sflphone-common/test/hookmanagertest.cpp b/sflphone-common/test/hookmanagertest.cpp index b0d68c936251e69f7200ce772f29af5f40e3d0a2..a0473b525c1c706cd317920d33d255bee687846f 100644 --- a/sflphone-common/test/hookmanagertest.cpp +++ b/sflphone-common/test/hookmanagertest.cpp @@ -47,7 +47,7 @@ void HookManagerTest::setUp() void HookManagerTest::testAddAction () { - _debug ("-------------------- HookManagerTest::testAddAction --------------------\n"); + _debug ("-------------------- HookManagerTest::testAddAction --------------------\n"); int status; @@ -57,7 +57,7 @@ void HookManagerTest::testAddAction () void HookManagerTest::testLargeUrl () { - _debug ("-------------------- HookManagerTest::testLargeUrl --------------------\n"); + _debug ("-------------------- HookManagerTest::testLargeUrl --------------------\n"); std::string url; std::cout << url.max_size() << std::endl; diff --git a/sflphone-common/test/main.cpp b/sflphone-common/test/main.cpp index ada12320f8272f1247ae0f3c6e4b1743ed8da548..0823891c597351b8208f094ddc0247c75e0550ee 100644 --- a/sflphone-common/test/main.cpp +++ b/sflphone-common/test/main.cpp @@ -37,73 +37,74 @@ #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TextTestRunner.h> -int main(int argc, char* argv[]) { - - printf("\nSFLphone Daemon Test Suite, by Savoir-Faire Linux 2004-2010\n\n"); - Logger::setConsoleLog(true); - Logger::setDebugMode(true); - - int argvIndex = 1; - - if (argc > 1) { - if (strcmp("--help", argv[1]) == 0) { - argvIndex++; - - CPPUNIT_NS::Test* suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry("All Tests").makeTest(); - - int testSuiteCount = suite->getChildTestCount(); - printf("Usage: test [OPTIONS] [TEST_SUITE]\n"); - printf("\nOptions:\n"); - printf(" --debug - Debug mode\n"); - printf(" --help - Print help\n"); - printf("\nAvailable test suites:\n"); - for (int i = 0; i < testSuiteCount; i++) { - printf(" - %s\n", suite->getChildTestAt(i)->getName().c_str()); - } - exit(0); - } - else if (strcmp("--debug", argv[1]) == 0) { - argvIndex++; - - Logger::setDebugMode(true); - _info("Debug mode activated"); - } - } - - // Default test suite : all tests - std::string testSuiteName = "All Tests"; - if(argvIndex < argc) - { - testSuiteName = argv[argvIndex]; - argvIndex++; - } - - printf("\n\n=== SFLphone initialization ===\n\n"); - Manager::instance().initConfigFile(true, CONFIG_SAMPLE); - Manager::instance().init(); - - // Get the top level suite from the registry - printf("\n\n=== Test Suite: %s ===\n\n", testSuiteName.c_str()); - CPPUNIT_NS::Test *suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry(testSuiteName).makeTest(); - - if(suite->getChildTestCount() == 0) - { - _error("Invalid test suite name: %s", testSuiteName.c_str()); - exit(-1); - } - - // Adds the test to the list of test to run - CppUnit::TextTestRunner runner; - runner.addTest(suite); - - // Change the default outputter to a compiler error format outputter - runner.setOutputter(new CppUnit::CompilerOutputter(&runner.result(), std::cerr)); - - // Run the tests. - bool wasSucessful = runner.run(); - - Manager::instance().terminate(); - - // Return error code 1 if the one of test failed. - return wasSucessful ? 0 : 1; +int main (int argc, char* argv[]) +{ + + printf ("\nSFLphone Daemon Test Suite, by Savoir-Faire Linux 2004-2010\n\n"); + Logger::setConsoleLog (true); + Logger::setDebugMode (true); + + int argvIndex = 1; + + if (argc > 1) { + if (strcmp ("--help", argv[1]) == 0) { + argvIndex++; + + CPPUNIT_NS::Test* suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry ("All Tests").makeTest(); + + int testSuiteCount = suite->getChildTestCount(); + printf ("Usage: test [OPTIONS] [TEST_SUITE]\n"); + printf ("\nOptions:\n"); + printf (" --debug - Debug mode\n"); + printf (" --help - Print help\n"); + printf ("\nAvailable test suites:\n"); + + for (int i = 0; i < testSuiteCount; i++) { + printf (" - %s\n", suite->getChildTestAt (i)->getName().c_str()); + } + + exit (0); + } else if (strcmp ("--debug", argv[1]) == 0) { + argvIndex++; + + Logger::setDebugMode (true); + _info ("Debug mode activated"); + } + } + + // Default test suite : all tests + std::string testSuiteName = "All Tests"; + + if (argvIndex < argc) { + testSuiteName = argv[argvIndex]; + argvIndex++; + } + + printf ("\n\n=== SFLphone initialization ===\n\n"); + Manager::instance().initConfigFile (true, CONFIG_SAMPLE); + Manager::instance().init(); + + // Get the top level suite from the registry + printf ("\n\n=== Test Suite: %s ===\n\n", testSuiteName.c_str()); + CPPUNIT_NS::Test *suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry (testSuiteName).makeTest(); + + if (suite->getChildTestCount() == 0) { + _error ("Invalid test suite name: %s", testSuiteName.c_str()); + exit (-1); + } + + // Adds the test to the list of test to run + CppUnit::TextTestRunner runner; + runner.addTest (suite); + + // Change the default outputter to a compiler error format outputter + runner.setOutputter (new CppUnit::CompilerOutputter (&runner.result(), std::cerr)); + + // Run the tests. + bool wasSucessful = runner.run(); + + Manager::instance().terminate(); + + // Return error code 1 if the one of test failed. + return wasSucessful ? 0 : 1; } diff --git a/sflphone-common/test/mainbuffertest.cpp b/sflphone-common/test/mainbuffertest.cpp index 8b36a4b776dddfaddbb669ba15ce20815cacc973..6c85862227a45d8e38f00f2e4b1aadbf5a91087b 100644 --- a/sflphone-common/test/mainbuffertest.cpp +++ b/sflphone-common/test/mainbuffertest.cpp @@ -64,7 +64,7 @@ void MainBufferTest::tearDown() void MainBufferTest::testRingBufferCreation() { - _debug ("-------------------- MainBufferTest::testRingBufferCreation --------------------\n"); + _debug ("-------------------- MainBufferTest::testRingBufferCreation --------------------\n"); CallID test_id = "1234"; CallID null_id = "null id"; @@ -111,7 +111,7 @@ void MainBufferTest::testRingBufferCreation() void MainBufferTest::testRingBufferReadPointer() { - _debug ("-------------------- MainBufferTest::testRingBufferReadPointer --------------------\n"); + _debug ("-------------------- MainBufferTest::testRingBufferReadPointer --------------------\n"); CallID call_id = "call id"; CallID read_id = "read id"; @@ -158,7 +158,7 @@ void MainBufferTest::testRingBufferReadPointer() void MainBufferTest::testCallIDSet() { - _debug ("-------------------- MainBufferTest::testCallIDSet --------------------\n"); + _debug ("-------------------- MainBufferTest::testCallIDSet --------------------\n"); CallID test_id = "set id"; CallID false_id = "false set id"; @@ -241,7 +241,7 @@ void MainBufferTest::testCallIDSet() void MainBufferTest::testRingBufferInt() { - _debug ("-------------------- MainBufferTest::testRingBufferInt --------------------\n"); + _debug ("-------------------- MainBufferTest::testRingBufferInt --------------------\n"); // CallID test_id = "test_int"; @@ -357,7 +357,7 @@ void MainBufferTest::testRingBufferInt() void MainBufferTest::testRingBufferNonDefaultID() { - _debug ("-------------------- MainBufferTest::testRingBufferNonDefaultID --------------------\n"); + _debug ("-------------------- MainBufferTest::testRingBufferNonDefaultID --------------------\n"); CallID test_id = "test_int"; @@ -444,7 +444,7 @@ void MainBufferTest::testRingBufferNonDefaultID() void MainBufferTest::testRingBufferFloat() { - _debug ("-------------------- MainBufferTest::testRingBufferFloat --------------------\n"); + _debug ("-------------------- MainBufferTest::testRingBufferFloat --------------------\n"); float testfloat1 = 12.5; float testfloat2 = 13.4; @@ -478,7 +478,7 @@ void MainBufferTest::testRingBufferFloat() void MainBufferTest::testTwoPointer() { - _debug ("-------------------- MainBufferTest::testTwoPointer --------------------\n"); + _debug ("-------------------- MainBufferTest::testTwoPointer --------------------\n"); RingBuffer* input_buffer = _mainbuffer.createRingBuffer (default_id); input_buffer->createReadPointer (default_id); @@ -495,7 +495,7 @@ void MainBufferTest::testTwoPointer() void MainBufferTest::testBindUnbindBuffer() { - _debug ("-------------------- MainBufferTest::testBindUnbindBuffer --------------------\n"); + _debug ("-------------------- MainBufferTest::testBindUnbindBuffer --------------------\n"); CallID test_id1 = "bind unbind 1"; CallID test_id2 = "bind unbind 2"; @@ -894,7 +894,7 @@ void MainBufferTest::testBindUnbindBuffer() void MainBufferTest::testGetPutDataByID() { - _debug ("-------------------- MainBufferTest::testGetPutDataByID --------------------\n"); + _debug ("-------------------- MainBufferTest::testGetPutDataByID --------------------\n"); CallID test_id = "getData putData"; CallID false_id = "false id"; @@ -949,7 +949,7 @@ void MainBufferTest::testGetPutDataByID() void MainBufferTest::testGetPutData() { - _debug ("-------------------- MainBufferTest::testGetPutData --------------------\n"); + _debug ("-------------------- MainBufferTest::testGetPutData --------------------\n"); CallID test_id = "incoming rtp session"; @@ -997,7 +997,7 @@ void MainBufferTest::testGetPutData() void MainBufferTest::testDiscardFlush() { - _debug ("-------------------- MainBufferTest::testDiscardFlush --------------------\n"); + _debug ("-------------------- MainBufferTest::testDiscardFlush --------------------\n"); CallID test_id = "flush discard"; // _mainbuffer.createRingBuffer(test_id); @@ -1039,7 +1039,7 @@ void MainBufferTest::testDiscardFlush() void MainBufferTest::testReadPointerInit() { - _debug ("-------------------- MainBufferTest::testReadPointerInit --------------------\n"); + _debug ("-------------------- MainBufferTest::testReadPointerInit --------------------\n"); CallID test_id = "test read pointer init"; // RingBuffer* test_ring_buffer = _mainbuffer.createRingBuffer(test_id); @@ -1067,7 +1067,7 @@ void MainBufferTest::testReadPointerInit() void MainBufferTest::testRingBufferSeveralPointers() { - _debug ("-------------------- MainBufferTest::testRingBufferSeveralPointers --------------------\n"); + _debug ("-------------------- MainBufferTest::testRingBufferSeveralPointers --------------------\n"); CallID test_id = "test multiple read pointer"; RingBuffer* test_ring_buffer = _mainbuffer.createRingBuffer (test_id); @@ -1180,7 +1180,7 @@ void MainBufferTest::testRingBufferSeveralPointers() void MainBufferTest::testConference() { - _debug ("-------------------- MainBufferTest::testConference --------------------\n"); + _debug ("-------------------- MainBufferTest::testConference --------------------\n"); CallID test_id1 = "participant A"; CallID test_id2 = "participant B"; diff --git a/sflphone-common/test/numbercleanertest.cpp b/sflphone-common/test/numbercleanertest.cpp index c13573e3f9bd9d78d07add7d28ad98f176433ebc..4c9cf71bfc70dccf54d7a0287c59e4099ca2b69f 100644 --- a/sflphone-common/test/numbercleanertest.cpp +++ b/sflphone-common/test/numbercleanertest.cpp @@ -63,70 +63,70 @@ void NumberCleanerTest::setUp() void NumberCleanerTest::test_format_1 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_1 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_1 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_1) == VALID_NUMBER); } void NumberCleanerTest::test_format_2 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_2 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_2 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_2) == VALID_NUMBER); } void NumberCleanerTest::test_format_3 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_3 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_3 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_3) == VALID_NUMBER); } void NumberCleanerTest::test_format_4 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_4 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_4 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_4) == VALID_NUMBER); } void NumberCleanerTest::test_format_5 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_5 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_5 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_5) == VALID_NUMBER); } void NumberCleanerTest::test_format_6 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_6 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_6 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_6) == VALID_NUMBER); } void NumberCleanerTest::test_format_7 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_7 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_7 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_7) == VALID_EXTENSION); } void NumberCleanerTest::test_format_8 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_8 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_8 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_8) == VALID_NUMBER); } void NumberCleanerTest::test_format_9 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_9 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_9 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_9) == VALID_NUMBER); } void NumberCleanerTest::test_format_10 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_10 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_10 --------------------\n"); cleaner->set_phone_number_prefix ("9"); CPPUNIT_ASSERT (cleaner->get_phone_number_prefix () == "9"); @@ -135,7 +135,7 @@ void NumberCleanerTest::test_format_10 (void) void NumberCleanerTest::test_format_11 (void) { - _debug ("-------------------- NumberCleanerTest::test_format_11 --------------------\n"); + _debug ("-------------------- NumberCleanerTest::test_format_11 --------------------\n"); cleaner->set_phone_number_prefix ("9"); CPPUNIT_ASSERT (cleaner->get_phone_number_prefix () == "9"); diff --git a/sflphone-common/test/pluginmanagertest.cpp b/sflphone-common/test/pluginmanagertest.cpp index faa28f2b035931a9da340b16b3406397892efa48..dfe6f268a92d5c64e8b893c57aa788c8e712ac37 100644 --- a/sflphone-common/test/pluginmanagertest.cpp +++ b/sflphone-common/test/pluginmanagertest.cpp @@ -52,14 +52,14 @@ void PluginManagerTest::setUp() void PluginManagerTest::testLoadDynamicLibrary() { - _debug ("-------------------- PluginManagerTest::testLoadDynamicLibrary --------------------\n"); + _debug ("-------------------- PluginManagerTest::testLoadDynamicLibrary --------------------\n"); CPPUNIT_ASSERT (_pm->loadDynamicLibrary (PLUGIN_TEST_NAME) != NULL); } void PluginManagerTest::testUnloadDynamicLibrary() { - _debug ("-------------------- PluginManagerTest::testUnloadDynamicLibrary --------------------\n"); + _debug ("-------------------- PluginManagerTest::testUnloadDynamicLibrary --------------------\n"); library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); CPPUNIT_ASSERT (library != NULL); @@ -68,7 +68,7 @@ void PluginManagerTest::testUnloadDynamicLibrary() void PluginManagerTest::testInstanciatePlugin() { - _debug ("-------------------- PluginManagerTest::testInstanciatePlugin --------------------\n"); + _debug ("-------------------- PluginManagerTest::testInstanciatePlugin --------------------\n"); library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); CPPUNIT_ASSERT (library != NULL); @@ -78,7 +78,7 @@ void PluginManagerTest::testInstanciatePlugin() void PluginManagerTest::testInitPlugin() { - _debug ("-------------------- PluginManagerTest::testInitPlugin --------------------\n"); + _debug ("-------------------- PluginManagerTest::testInitPlugin --------------------\n"); library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); CPPUNIT_ASSERT (library != NULL); @@ -89,7 +89,7 @@ void PluginManagerTest::testInitPlugin() void PluginManagerTest::testRegisterPlugin() { - _debug ("-------------------- PluginManagerTest::testRegisterPlugin --------------------\n"); + _debug ("-------------------- PluginManagerTest::testRegisterPlugin --------------------\n"); library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); CPPUNIT_ASSERT (library != NULL); @@ -101,7 +101,7 @@ void PluginManagerTest::testRegisterPlugin() void PluginManagerTest::testLoadPlugins () { - _debug ("-------------------- PluginManagerTest::testLoadPlugins --------------------\n"); + _debug ("-------------------- PluginManagerTest::testLoadPlugins --------------------\n"); CPPUNIT_ASSERT (_pm->loadPlugins (PLUGIN_TEST_DIR) == 0); CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == true); @@ -109,7 +109,7 @@ void PluginManagerTest::testLoadPlugins () void PluginManagerTest::testUnloadPlugins () { - _debug ("-------------------- PluginManagerTest::testUnloadPlugins --------------------\n"); + _debug ("-------------------- PluginManagerTest::testUnloadPlugins --------------------\n"); CPPUNIT_ASSERT (_pm->loadPlugins (PLUGIN_TEST_DIR) == 0); CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == true); diff --git a/sflphone-common/test/ringtonetest.cpp b/sflphone-common/test/ringtonetest.cpp index 49501d2f576747ba753b75e1035b5855fcb35796..9ddeb96949fd96b5b9c6b5335118be53c0a0f2da 100644 --- a/sflphone-common/test/ringtonetest.cpp +++ b/sflphone-common/test/ringtonetest.cpp @@ -30,18 +30,19 @@ #include "ringtonetest.h" -void RingtoneTest::testLoadWavefile() +void RingtoneTest::testLoadWavefile() { - WavFile *wav = new WavFile(); + WavFile *wav = new WavFile(); - // Test initial values - CPPUNIT_ASSERT(wav->isStarted() == false); - CPPUNIT_ASSERT(wav->getSize() == 0); + // Test initial values + CPPUNIT_ASSERT (wav->isStarted() == false); + CPPUNIT_ASSERT (wav->getSize() == 0); - // Test protection against wrong file name - CPPUNIT_ASSERT(wav->loadFile(std::string("wrongfilename.wav"), NULL, 44100) == false); + // Test protection against wrong file name + CPPUNIT_ASSERT (wav->loadFile (std::string ("wrongfilename.wav"), NULL, 44100) == false); - - delete wav; wav = NULL; + + delete wav; + wav = NULL; } diff --git a/sflphone-common/test/rtptest.cpp b/sflphone-common/test/rtptest.cpp index 366fc1fe23619b18f695228d74db761dfeea64e3..fe8a395ac3ee354896c1a523d916e67b2a432643 100644 --- a/sflphone-common/test/rtptest.cpp +++ b/sflphone-common/test/rtptest.cpp @@ -46,76 +46,80 @@ #include <unistd.h> -void RtpTest::setUp() { +void RtpTest::setUp() +{ - pjsipInit(); + pjsipInit(); - CallID cid = "123456"; + CallID cid = "123456"; - sipcall = new SIPCall(cid, Call::Incoming, _pool); + sipcall = new SIPCall (cid, Call::Incoming, _pool); - sipcall->setLocalIp("127.0.0.1"); - sipcall->setLocalAudioPort(RANDOM_LOCAL_PORT); - sipcall->setLocalExternAudioPort(RANDOM_LOCAL_PORT); + sipcall->setLocalIp ("127.0.0.1"); + sipcall->setLocalAudioPort (RANDOM_LOCAL_PORT); + sipcall->setLocalExternAudioPort (RANDOM_LOCAL_PORT); } -bool RtpTest::pjsipInit() { - // Create memory cache for pool - pj_caching_pool_init(&_cp, &pj_pool_factory_default_policy, 0); +bool RtpTest::pjsipInit() +{ + // Create memory cache for pool + pj_caching_pool_init (&_cp, &pj_pool_factory_default_policy, 0); - // Create memory pool for application. - _pool = pj_pool_create(&_cp.factory, "rtpTest", 4000, 4000, NULL); + // Create memory pool for application. + _pool = pj_pool_create (&_cp.factory, "rtpTest", 4000, 4000, NULL); - if (!_pool) { - _debug ("----- RtpTest: Could not initialize pjsip memory pool ------"); - return PJ_ENOMEM; - } + if (!_pool) { + _debug ("----- RtpTest: Could not initialize pjsip memory pool ------"); + return PJ_ENOMEM; + } - return true; + return true; } -void RtpTest::testRtpInitClose() { - _debug ("-------------------- RtpTest::testRtpInitClose --------------------\n"); +void RtpTest::testRtpInitClose() +{ + _debug ("-------------------- RtpTest::testRtpInitClose --------------------\n"); - audiortp = new AudioRtpFactory(); + audiortp = new AudioRtpFactory(); - try { - _debug ("-------- Open Rtp Session ----------"); - audiortp->initAudioRtpConfig(sipcall); - audiortp->initAudioRtpSession(sipcall); - //AudioCodecType codecType = PAYLOAD_CODEC_ULAW; - //AudioCodec* audioCodec = Manager::instance().getCodecDescriptorMap().instantiateCodec(codecType); - //audiortp->start(audioCodec); + try { + _debug ("-------- Open Rtp Session ----------"); + audiortp->initAudioRtpConfig (sipcall); + audiortp->initAudioRtpSession (sipcall); + //AudioCodecType codecType = PAYLOAD_CODEC_ULAW; + //AudioCodec* audioCodec = Manager::instance().getCodecDescriptorMap().instantiateCodec(codecType); + //audiortp->start(audioCodec); - } catch (...) { - _debug ("!!! Exception occured while Oppenning Rtp !!!"); - CPPUNIT_ASSERT(false); + } catch (...) { + _debug ("!!! Exception occured while Oppenning Rtp !!!"); + CPPUNIT_ASSERT (false); - } + } - CPPUNIT_ASSERT (audiortp != NULL); + CPPUNIT_ASSERT (audiortp != NULL); - sleep(1); + sleep (1); - _debug ("------ RtpTest::testRtpClose() ------"); + _debug ("------ RtpTest::testRtpClose() ------"); - try { - _debug ("------ Close Rtp Session -------"); - audiortp->stop(); + try { + _debug ("------ Close Rtp Session -------"); + audiortp->stop(); - } catch (...) { + } catch (...) { - _debug ("!!! Exception occured while closing Rtp !!!"); - CPPUNIT_ASSERT(false); + _debug ("!!! Exception occured while closing Rtp !!!"); + CPPUNIT_ASSERT (false); - } + } - delete audiortp; + delete audiortp; - audiortp = NULL; + audiortp = NULL; } -void RtpTest::tearDown() { - delete sipcall; - sipcall = NULL; +void RtpTest::tearDown() +{ + delete sipcall; + sipcall = NULL; } diff --git a/sflphone-common/test/sdesnegotiatortest.cpp b/sflphone-common/test/sdesnegotiatortest.cpp index 6a873613f29b59d4fdebf32b15e4c30c9c4724fe..fd1f630fe70d3288f722b3e3fbb92a77f188d2d0 100644 --- a/sflphone-common/test/sdesnegotiatortest.cpp +++ b/sflphone-common/test/sdesnegotiatortest.cpp @@ -51,15 +51,15 @@ using std::endl; void SdesNegotiatorTest::testTagPattern() { - _debug ("-------------------- SdesNegotiatorTest::testTagPattern --------------------\n"); + _debug ("-------------------- SdesNegotiatorTest::testTagPattern --------------------\n"); - std::string subject = "a=crypto:4"; + std::string subject = "a=crypto:4"; - pattern = new sfl::Pattern("^a=crypto:(?P<tag>[0-9]{1,9})"); + pattern = new sfl::Pattern ("^a=crypto:(?P<tag>[0-9]{1,9})"); *pattern << subject; - CPPUNIT_ASSERT(pattern->matches()); - CPPUNIT_ASSERT(pattern->group("tag").compare("4") == 0); + CPPUNIT_ASSERT (pattern->matches()); + CPPUNIT_ASSERT (pattern->group ("tag").compare ("4") == 0); delete pattern; pattern = NULL; @@ -68,18 +68,18 @@ void SdesNegotiatorTest::testTagPattern() void SdesNegotiatorTest::testCryptoSuitePattern() { - _debug ("-------------------- SdesNegotiatorTest::testCryptoSuitePattern --------------------\n"); + _debug ("-------------------- SdesNegotiatorTest::testCryptoSuitePattern --------------------\n"); - std::string subject = "AES_CM_128_HMAC_SHA1_80"; + std::string subject = "AES_CM_128_HMAC_SHA1_80"; - pattern = new sfl::Pattern("(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ - "AES_CM_128_HMAC_SHA1_32|" \ - "F8_128_HMAC_SHA1_80|" \ - "[A-Za-z0-9_]+)"); + pattern = new sfl::Pattern ("(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ + "AES_CM_128_HMAC_SHA1_32|" \ + "F8_128_HMAC_SHA1_80|" \ + "[A-Za-z0-9_]+)"); *pattern << subject; - CPPUNIT_ASSERT(pattern->matches()); - CPPUNIT_ASSERT(pattern->group("cryptoSuite").compare("AES_CM_128_HMAC_SHA1_80") == 0); + CPPUNIT_ASSERT (pattern->matches()); + CPPUNIT_ASSERT (pattern->group ("cryptoSuite").compare ("AES_CM_128_HMAC_SHA1_80") == 0); delete pattern; pattern = NULL; @@ -88,25 +88,25 @@ void SdesNegotiatorTest::testCryptoSuitePattern() void SdesNegotiatorTest::testKeyParamsPattern() { - _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPattern --------------------\n"); + _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPattern --------------------\n"); std::string subject = "inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj|2^20|1:32"; - pattern = new sfl::Pattern("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)\\|" \ - "(2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); + pattern = new sfl::Pattern ("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)\\|" \ + "(2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); *pattern << subject; pattern->matches(); - CPPUNIT_ASSERT(pattern->group("srtpKeyMethod").compare("inline:")); - CPPUNIT_ASSERT(pattern->group("srtpKeyInfo").compare("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") -== 0); - CPPUNIT_ASSERT(pattern->group("lifetime").compare("20")== 0); - CPPUNIT_ASSERT(pattern->group("mkiValue").compare("1")== 0); - CPPUNIT_ASSERT(pattern->group("mkiLength").compare("32")== 0); + CPPUNIT_ASSERT (pattern->group ("srtpKeyMethod").compare ("inline:")); + CPPUNIT_ASSERT (pattern->group ("srtpKeyInfo").compare ("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") + == 0); + CPPUNIT_ASSERT (pattern->group ("lifetime").compare ("20") == 0); + CPPUNIT_ASSERT (pattern->group ("mkiValue").compare ("1") == 0); + CPPUNIT_ASSERT (pattern->group ("mkiLength").compare ("32") == 0); delete pattern; pattern = NULL; @@ -115,21 +115,21 @@ void SdesNegotiatorTest::testKeyParamsPattern() void SdesNegotiatorTest::testKeyParamsPatternWithoutMKI() { - _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPatternWithoutMKI --------------------\n"); + _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPatternWithoutMKI --------------------\n"); std::string subject = "inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj"; - pattern = new sfl::Pattern("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ - "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); + pattern = new sfl::Pattern ("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ + "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); *pattern << subject; pattern->matches(); - CPPUNIT_ASSERT(pattern->group("srtpKeyMethod").compare("inline:")); - CPPUNIT_ASSERT(pattern->group("srtpKeyInfo").compare("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") -== 0); + CPPUNIT_ASSERT (pattern->group ("srtpKeyMethod").compare ("inline:")); + CPPUNIT_ASSERT (pattern->group ("srtpKeyInfo").compare ("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") + == 0); delete pattern; pattern = NULL; @@ -138,26 +138,27 @@ void SdesNegotiatorTest::testKeyParamsPatternWithoutMKI() /** * Make sure that all the fields can be extracted - * properly from the syntax. + * properly from the syntax. */ void SdesNegotiatorTest::testNegotiation() { - _debug ("-------------------- SdesNegotiatorTest::testNegotiation --------------------\n"); + _debug ("-------------------- SdesNegotiatorTest::testNegotiation --------------------\n"); - // Add a new SDES crypto line to be processed. + // Add a new SDES crypto line to be processed. remoteOffer = new std::vector<std::string>(); - remoteOffer->push_back(std::string("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd|2^20|1:32")); - remoteOffer->push_back(std::string("a=crypto:2 AES_CM_128_HMAC_SHA1_32 inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj|2^20|1:32")); - + remoteOffer->push_back (std::string ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd|2^20|1:32")); + remoteOffer->push_back (std::string ("a=crypto:2 AES_CM_128_HMAC_SHA1_32 inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj|2^20|1:32")); + // Register the local capabilities. localCapabilities = new std::vector<sfl::CryptoSuiteDefinition>(); - for(int i = 0; i < 3; i++) { - localCapabilities->push_back(sfl::CryptoSuites[i]); + + for (int i = 0; i < 3; i++) { + localCapabilities->push_back (sfl::CryptoSuites[i]); } - sdesnego = new sfl::SdesNegotiator(*localCapabilities, *remoteOffer); + sdesnego = new sfl::SdesNegotiator (*localCapabilities, *remoteOffer); - CPPUNIT_ASSERT(sdesnego->negotiate()); + CPPUNIT_ASSERT (sdesnego->negotiate()); // CPPUNIT_ASSERT(sdesnego->getKeyInfo().compare("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd|2^20|1:32")==0); delete remoteOffer; @@ -175,24 +176,24 @@ void SdesNegotiatorTest::testNegotiation() */ void SdesNegotiatorTest::testComponent() { - _debug ("-------------------- SdesNegotiatorTest::testComponent --------------------\n"); + _debug ("-------------------- SdesNegotiatorTest::testComponent --------------------\n"); // Register the local capabilities. std::vector<sfl::CryptoSuiteDefinition> * capabilities = new std::vector<sfl::CryptoSuiteDefinition>(); - + //Support all the CryptoSuites - for(int i = 0; i < 3; i++) { - capabilities->push_back(sfl::CryptoSuites[i]); + for (int i = 0; i < 3; i++) { + capabilities->push_back (sfl::CryptoSuites[i]); } - + // Make sure that if a component is missing, negotiate will fail - std::string cryptoLine("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:|2^20|1:32"); + std::string cryptoLine ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:|2^20|1:32"); std::vector<std::string> * cryptoOffer = new std::vector<std::string>(); - cryptoOffer->push_back(cryptoLine); + cryptoOffer->push_back (cryptoLine); - sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator(*capabilities, *cryptoOffer); + sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator (*capabilities, *cryptoOffer); - CPPUNIT_ASSERT(negotiator->negotiate() == false); + CPPUNIT_ASSERT (negotiator->negotiate() == false); } @@ -202,33 +203,36 @@ void SdesNegotiatorTest::testComponent() */ void SdesNegotiatorTest::testMostSimpleCase() { - _debug ("-------------------- SdesNegotiatorTest::testMostSimpleCase --------------------\n"); + _debug ("-------------------- SdesNegotiatorTest::testMostSimpleCase --------------------\n"); // Register the local capabilities. std::vector<sfl::CryptoSuiteDefinition> * capabilities = new std::vector<sfl::CryptoSuiteDefinition>(); //Support all the CryptoSuites - for(int i = 0; i < 3; i++) { - capabilities->push_back(sfl::CryptoSuites[i]); + for (int i = 0; i < 3; i++) { + capabilities->push_back (sfl::CryptoSuites[i]); } // Make sure taht this case works (since it's default for most application) - std::string cryptoLine("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); + std::string cryptoLine ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); std::vector<std::string> * cryptoOffer = new std::vector<std::string>(); - cryptoOffer->push_back(cryptoLine); + cryptoOffer->push_back (cryptoLine); - sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator(*capabilities, *cryptoOffer); + sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator (*capabilities, *cryptoOffer); - CPPUNIT_ASSERT(negotiator->negotiate() == true); + CPPUNIT_ASSERT (negotiator->negotiate() == true); - CPPUNIT_ASSERT(negotiator->getCryptoSuite().compare("AES_CM_128_HMAC_SHA1_80") == 0); - CPPUNIT_ASSERT(negotiator->getKeyMethod().compare("inline") == 0); - CPPUNIT_ASSERT(negotiator->getKeyInfo().compare("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd") == 0); - CPPUNIT_ASSERT(negotiator->getLifeTime().compare("")== 0); - CPPUNIT_ASSERT(negotiator->getMkiValue().compare("")== 0); - CPPUNIT_ASSERT(negotiator->getMkiLength().compare("")== 0); + CPPUNIT_ASSERT (negotiator->getCryptoSuite().compare ("AES_CM_128_HMAC_SHA1_80") == 0); + CPPUNIT_ASSERT (negotiator->getKeyMethod().compare ("inline") == 0); + CPPUNIT_ASSERT (negotiator->getKeyInfo().compare ("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd") == 0); + CPPUNIT_ASSERT (negotiator->getLifeTime().compare ("") == 0); + CPPUNIT_ASSERT (negotiator->getMkiValue().compare ("") == 0); + CPPUNIT_ASSERT (negotiator->getMkiLength().compare ("") == 0); - delete capabilities; capabilities = NULL; - delete cryptoOffer; cryptoOffer = NULL; - delete negotiator; negotiator = NULL; + delete capabilities; + capabilities = NULL; + delete cryptoOffer; + cryptoOffer = NULL; + delete negotiator; + negotiator = NULL; } diff --git a/sflphone-common/test/validator.cpp b/sflphone-common/test/validator.cpp index a12bad1714cebcbda861aa6261f13af8e1851e2f..de6d228e0e867437b4cf701ca4f8460817687484 100644 --- a/sflphone-common/test/validator.cpp +++ b/sflphone-common/test/validator.cpp @@ -30,20 +30,25 @@ #include "validator.h" -bool Validator::isNumber(std::string str) { - unsigned int i = 0; - if (!str.empty() && (str[i] == '-' || str[i] == '+')) - i++; - return string::npos == str.find_first_not_of(".eE0123456789", i); +bool Validator::isNumber (std::string str) +{ + unsigned int i = 0; + + if (!str.empty() && (str[i] == '-' || str[i] == '+')) + i++; + + return string::npos == str.find_first_not_of (".eE0123456789", i); } -bool Validator::isNotNull(std::string str) { - if(!str.empty()) - return true; - else - return false; +bool Validator::isNotNull (std::string str) +{ + if (!str.empty()) + return true; + else + return false; } -bool Validator::isEqual(std::string str1, std::string str2) { - return str1.compare(str2) == 0; +bool Validator::isEqual (std::string str1, std::string str2) +{ + return str1.compare (str2) == 0; }