diff --git a/daemon/src/audio/audiortp/audio_rtp_factory.cpp b/daemon/src/audio/audiortp/audio_rtp_factory.cpp index aaac2ef4feb0028427887d21b9f96f110c4105a7..ee57e4ec085b6a0c15149358ac4a66a248245638 100644 --- a/daemon/src/audio/audiortp/audio_rtp_factory.cpp +++ b/daemon/src/audio/audiortp/audio_rtp_factory.cpp @@ -42,17 +42,17 @@ namespace sfl { -AudioRtpFactory::AudioRtpFactory(SIPCall *ca) : _rtpSession(NULL), remoteContext(NULL), localContext(NULL), ca_(ca) +AudioRtpFactory::AudioRtpFactory(SIPCall *ca) : rtpSession_(NULL), remoteContext_(NULL), localContext_(NULL), ca_(ca) {} AudioRtpFactory::~AudioRtpFactory() { - delete _rtpSession; + delete rtpSession_; } void AudioRtpFactory::initAudioRtpConfig() { - if (_rtpSession != NULL) + if (rtpSession_ != NULL) stop(); std::string accountId(Manager::instance().getAccountFromCall(ca_->getCallId())); @@ -60,150 +60,136 @@ void AudioRtpFactory::initAudioRtpConfig() SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(accountId)); if (account) { - _srtpEnabled = account->getSrtpEnabled(); + srtpEnabled_ = account->getSrtpEnabled(); std::string key(account->getSrtpKeyExchange()); if (key == "sdes") - _keyExchangeProtocol = Sdes; + keyExchangeProtocol_ = Sdes; else if (key == "zrtp") - _keyExchangeProtocol = Zrtp; + keyExchangeProtocol_ = Zrtp; else - _keyExchangeProtocol = Symmetric; + keyExchangeProtocol_ = Symmetric; - _helloHashEnabled = account->getZrtpHelloHash(); + helloHashEnabled_ = account->getZrtpHelloHash(); } else { - _srtpEnabled = false; - _keyExchangeProtocol = Symmetric; - _helloHashEnabled = false; + srtpEnabled_ = false; + keyExchangeProtocol_ = Symmetric; + helloHashEnabled_ = false; } } void AudioRtpFactory::initAudioSymmetricRtpSession() { - ost::MutexLock m(_audioRtpThreadMutex); + ost::MutexLock m(audioRtpThreadMutex_); - if (_srtpEnabled) { + if (srtpEnabled_) { std::string zidFilename(Manager::instance().voipPreferences.getZidFile()); - switch (_keyExchangeProtocol) { + switch (keyExchangeProtocol_) { case Zrtp: - _rtpSession = new AudioZrtpSession(ca_, zidFilename); - - if (_helloHashEnabled) { - // TODO: be careful with that. The hello hash is computed asynchronously. Maybe it's - // not even available at that point. - ca_->getLocalSDP()->setZrtpHash(static_cast<AudioZrtpSession *>(_rtpSession)->getHelloHash()); - } - + rtpSession_ = new AudioZrtpSession(ca_, zidFilename); + // TODO: be careful with that. The hello hash is computed asynchronously. Maybe it's + // not even available at that point. + if (helloHashEnabled_) + ca_->getLocalSDP()->setZrtpHash(static_cast<AudioZrtpSession *>(rtpSession_)->getHelloHash()); break; case Sdes: - _rtpSession = new AudioSrtpSession(ca_); + rtpSession_ = new AudioSrtpSession(ca_); break; default: throw UnsupportedRtpSessionType("Unsupported Rtp Session Exception Type!"); } - } else { - _rtpSession = new AudioSymmetricRtpSession(ca_); - } + } else + rtpSession_ = new AudioSymmetricRtpSession(ca_); } void AudioRtpFactory::start(AudioCodec* audiocodec) { - if (_rtpSession == NULL) { + if (rtpSession_ == NULL) throw AudioRtpFactoryException("AudioRtpFactory: Error: RTP session was null when trying to start audio thread"); - } - if (_rtpSession->getAudioRtpType() == Sdes) { - if (localContext && remoteContext) { - static_cast<AudioSrtpSession *>(_rtpSession)->restoreCryptoContext(localContext, remoteContext); - } - } + if (rtpSession_->getAudioRtpType() == Sdes) + if (localContext_ and remoteContext_) + static_cast<AudioSrtpSession *>(rtpSession_)->restoreCryptoContext(localContext_, remoteContext_); - if (_rtpSession->startRtpThread(audiocodec) != 0) { + if (rtpSession_->startRtpThread(audiocodec) != 0) throw AudioRtpFactoryException("AudioRtpFactory: Error: Failed to start AudioZrtpSession thread"); - } - } -void AudioRtpFactory::stop(void) +void AudioRtpFactory::stop() { - ost::MutexLock mutex(_audioRtpThreadMutex); + ost::MutexLock mutex(audioRtpThreadMutex_); - if (_rtpSession == NULL) + if (rtpSession_ == NULL) return; - if (_rtpSession->getAudioRtpType() == Sdes) { - localContext = static_cast<AudioSrtpSession *>(_rtpSession)->_localCryptoCtx; - remoteContext = static_cast<AudioSrtpSession *>(_rtpSession)->_remoteCryptoCtx; + if (rtpSession_->getAudioRtpType() == Sdes) { + localContext_ = static_cast<AudioSrtpSession*>(rtpSession_)->localCryptoCtx_; + remoteContext_ = static_cast<AudioSrtpSession*>(rtpSession_)->remoteCryptoCtx_; } - delete _rtpSession; - _rtpSession = NULL; + delete rtpSession_; + rtpSession_ = NULL; } int AudioRtpFactory::getSessionMedia() { - if (_rtpSession == NULL) { + if (rtpSession_ == NULL) throw AudioRtpFactoryException("AudioRtpFactory: Error: RTP session was null when trying to get session media type"); - } - return _rtpSession->getCodecPayloadType(); + return rtpSession_->getCodecPayloadType(); } void AudioRtpFactory::updateSessionMedia(AudioCodec *audiocodec) { - if (_rtpSession == NULL) { - throw AudioRtpFactoryException("AudioRtpFactory: Error: _rtpSession was null when trying to update IP address"); - } + if (rtpSession_ == NULL) + throw AudioRtpFactoryException("AudioRtpFactory: Error: rtpSession_ was null when trying to update IP address"); - _rtpSession->updateSessionMedia(audiocodec); + rtpSession_->updateSessionMedia(audiocodec); } -void AudioRtpFactory::updateDestinationIpAddress(void) +void AudioRtpFactory::updateDestinationIpAddress() { - if (_rtpSession) - _rtpSession->updateDestinationIpAddress(); + if (rtpSession_) + rtpSession_->updateDestinationIpAddress(); } sfl::AudioZrtpSession * AudioRtpFactory::getAudioZrtpSession() { - if (_rtpSession->getAudioRtpType() == Zrtp) { - return static_cast<AudioZrtpSession *>(_rtpSession); - } else { - throw AudioRtpFactoryException("RTP: Error: _rtpSession is NULL in getAudioZrtpSession"); - } + if (rtpSession_->getAudioRtpType() == Zrtp) + return static_cast<AudioZrtpSession *>(rtpSession_); + else + throw AudioRtpFactoryException("RTP: Error: rtpSession_ is NULL in getAudioZrtpSession"); } void sfl::AudioRtpFactory::initLocalCryptoInfo() { - if (_rtpSession && _rtpSession->getAudioRtpType() == Sdes) { - static_cast<AudioSrtpSession *>(_rtpSession)->initLocalCryptoInfo(); - - ca_->getLocalSDP()->setLocalSdpCrypto(static_cast<AudioSrtpSession *>(_rtpSession)->getLocalCryptoInfo()); + if (rtpSession_ && rtpSession_->getAudioRtpType() == Sdes) { + static_cast<AudioSrtpSession *>(rtpSession_)->initLocalCryptoInfo(); + ca_->getLocalSDP()->setLocalSdpCrypto(static_cast<AudioSrtpSession *>(rtpSession_)->getLocalCryptoInfo()); } } void AudioRtpFactory::setRemoteCryptoInfo(sfl::SdesNegotiator& nego) { - if (_rtpSession && _rtpSession->getAudioRtpType() == Sdes) { - static_cast<AudioSrtpSession *>(_rtpSession)->setRemoteCryptoInfo(nego); - } else { - throw AudioRtpFactoryException("RTP: Error: _rtpSession is NULL in setRemoteCryptoInfo"); - } + if (rtpSession_ && rtpSession_->getAudioRtpType() == Sdes) + static_cast<AudioSrtpSession *>(rtpSession_)->setRemoteCryptoInfo(nego); + else + throw AudioRtpFactoryException("RTP: Error: rtpSession_ is NULL in setRemoteCryptoInfo"); } void AudioRtpFactory::setDtmfPayloadType(unsigned int payloadType) { - if (_rtpSession) - _rtpSession->setDtmfPayloadType(payloadType); + if (rtpSession_) + rtpSession_->setDtmfPayloadType(payloadType); } void AudioRtpFactory::sendDtmfDigit(int digit) { - _rtpSession->putDtmfEvent(digit); + rtpSession_->putDtmfEvent(digit); } } diff --git a/daemon/src/audio/audiortp/audio_rtp_factory.h b/daemon/src/audio/audiortp/audio_rtp_factory.h index 80adaae98aab9a641bd2a04a284a81a076e23c8e..0e33ae57c7d4f063122a23b60b260ad10a9a1b6a 100644 --- a/daemon/src/audio/audiortp/audio_rtp_factory.h +++ b/daemon/src/audio/audiortp/audio_rtp_factory.h @@ -99,17 +99,17 @@ class AudioRtpFactory { * Update current RTP destination address with one stored in call * @param None */ - void updateDestinationIpAddress(void); + void updateDestinationIpAddress(); - bool isSdesEnabled(void) const { - return _srtpEnabled && _keyExchangeProtocol == sfl::Sdes; + bool isSdesEnabled() const { + return srtpEnabled_ and keyExchangeProtocol_ == sfl::Sdes; } /** * Manually set the srtpEnable option (usefull for RTP fallback) */ void setSrtpEnabled(bool enable) { - _srtpEnabled = enable; + srtpEnabled_ = enable; } /** @@ -138,26 +138,26 @@ class AudioRtpFactory { void sendDtmfDigit(int digit); private: - AudioRtpSession *_rtpSession; - ost::Mutex _audioRtpThreadMutex; + AudioRtpSession *rtpSession_; + ost::Mutex audioRtpThreadMutex_; // Field used when initializinga udio rtp session // May be set manually or from config using initAudioRtpConfig - bool _srtpEnabled; + bool srtpEnabled_; // Field used when initializinga udio rtp session // May be set manually or from config using initAudioRtpConfig - RtpMethod _keyExchangeProtocol; + RtpMethod keyExchangeProtocol_; // Field used when initializinga udio rtp session // May be set manually or from config using initAudioRtpConfig - bool _helloHashEnabled; + bool helloHashEnabled_; /** Remote srtp crypto context to be set into incoming data queue. */ - ost::CryptoContext *remoteContext; + ost::CryptoContext *remoteContext_; /** Local srtp crypto context to be set into outgoing data queue. */ - ost::CryptoContext *localContext; + ost::CryptoContext *localContext_; SIPCall *ca_; }; diff --git a/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp b/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp index 9ed316885fca496c6b86a4ad476d3fe8f7196897..f29196b78801d027d9218f9b3c70ef29cf170a7c 100644 --- a/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp +++ b/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp @@ -38,76 +38,66 @@ namespace sfl { static const SFLDataFormat initFadeinFactor = 32000; -AudioRtpRecord::AudioRtpRecord() : _audioCodec(NULL) - , _hasDynamicPayloadType(false) - , _converter(NULL) - , _codecSampleRate(0) - , _codecFrameSize(0) - , _micAmplFactor(initFadeinFactor) - , _noiseSuppress(NULL) - , _callId("") - , _dtmfPayloadType(101) // same as Asterisk -{ - -} +AudioRtpRecord::AudioRtpRecord() : audioCodec_(NULL) + , hasDynamicPayloadType_(false) + , converter_(NULL) + , codecSampleRate_(0) + , codecFrameSize_(0) + , micAmplFactor_(initFadeinFactor) + , noiseSuppress_(NULL) + , callId_("") + , dtmfPayloadType_(101) // same as Asterisk +{} AudioRtpRecord::~AudioRtpRecord() { - delete _converter; - delete _audioCodec; - delete _noiseSuppress; + delete converter_; + delete audioCodec_; + delete noiseSuppress_; } -AudioRtpRecordHandler::AudioRtpRecordHandler(SIPCall *ca) : _audioRtpRecord(), id_(ca->getCallId()), echoCanceller(ca->getMemoryPool()), gainController(8000, -10.0) -{ - -} +AudioRtpRecordHandler::AudioRtpRecordHandler(SIPCall *ca) : audioRtpRecord_(), id_(ca->getCallId()), echoCanceller(ca->getMemoryPool()), gainController(8000, -10.0) +{} AudioRtpRecordHandler::~AudioRtpRecordHandler() {} void AudioRtpRecordHandler::setRtpMedia(AudioCodec* audioCodec) { - _audioRtpRecord.audioCodecMutex.enter(); + ost::MutexLock lock(audioRtpRecord_.audioCodecMutex_); - delete _audioRtpRecord._audioCodec; + delete audioRtpRecord_.audioCodec_; // Set varios codec info to reduce indirection - _audioRtpRecord._audioCodec = audioCodec; - _audioRtpRecord._codecPayloadType = audioCodec->getPayloadType(); - _audioRtpRecord._codecSampleRate = audioCodec->getClockRate(); - _audioRtpRecord._codecFrameSize = audioCodec->getFrameSize(); - _audioRtpRecord._hasDynamicPayloadType = audioCodec->hasDynamicPayload(); - - _audioRtpRecord.audioCodecMutex.leave(); + audioRtpRecord_.audioCodec_ = audioCodec; + audioRtpRecord_.codecPayloadType_ = audioCodec->getPayloadType(); + audioRtpRecord_.codecSampleRate_ = audioCodec->getClockRate(); + audioRtpRecord_.codecFrameSize_ = audioCodec->getFrameSize(); + audioRtpRecord_.hasDynamicPayloadType_ = audioCodec->hasDynamicPayload(); } void AudioRtpRecordHandler::initBuffers() { // Set sampling rate, main buffer choose the highest one - Manager::instance().audioSamplingRateChanged(_audioRtpRecord._codecSampleRate); + Manager::instance().audioSamplingRateChanged(audioRtpRecord_.codecSampleRate_); // initialize SampleRate converter using AudioLayer's sampling rate // (internal buffers initialized with maximal sampling rate and frame size) - delete _audioRtpRecord._converter; - _audioRtpRecord._converter = new SamplerateConverter(getCodecSampleRate()); + delete audioRtpRecord_.converter_; + audioRtpRecord_.converter_ = new SamplerateConverter(getCodecSampleRate()); } void AudioRtpRecordHandler::initNoiseSuppress() { - _audioRtpRecord.audioProcessMutex.enter(); - - delete _audioRtpRecord._noiseSuppress; - - _audioRtpRecord._noiseSuppress = new NoiseSuppress(getCodecFrameSize(), getCodecSampleRate()); - - _audioRtpRecord.audioProcessMutex.leave(); + ost::MutexLock lock(audioRtpRecord_.audioProcessMutex_); + delete audioRtpRecord_.noiseSuppress_; + audioRtpRecord_.noiseSuppress_ = new NoiseSuppress(getCodecFrameSize(), getCodecSampleRate()); } void AudioRtpRecordHandler::putDtmfEvent(int digit) { - _audioRtpRecord._dtmfQueue.push_back(digit); + audioRtpRecord_.dtmfQueue_.push_back(digit); } #ifdef DUMP_PROCESS_DATA_ENCODE @@ -116,9 +106,9 @@ std::ofstream teststream("test_process_data_encode.raw"); int AudioRtpRecordHandler::processDataEncode(void) { - SFLDataFormat *micData = _audioRtpRecord.decData; - unsigned char *micDataEncoded = _audioRtpRecord.encodedData; - SFLDataFormat *micDataConverted = _audioRtpRecord.resampledData; + SFLDataFormat *micData = audioRtpRecord_.decData_; + unsigned char *micDataEncoded = audioRtpRecord_.encodedData_; + SFLDataFormat *micDataConverted = audioRtpRecord_.resampledData_; int codecSampleRate = getCodecSampleRate(); int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); @@ -129,9 +119,8 @@ int AudioRtpRecordHandler::processDataEncode(void) int samplesToGet = resampleFactor * getCodecFrameSize(); int bytesToGet = samplesToGet * sizeof(SFLDataFormat); - if (Manager::instance().getMainBuffer()->availForGet(id_) < bytesToGet) { + if (Manager::instance().getMainBuffer()->availForGet(id_) < bytesToGet) return 0; - } int bytes = Manager::instance().getMainBuffer()->getData(micData, bytesToGet, id_); @@ -142,7 +131,7 @@ int AudioRtpRecordHandler::processDataEncode(void) int samples = bytesToGet / sizeof(SFLDataFormat); - fadeIn(micData, samples, &_audioRtpRecord._micAmplFactor); + fadeIn(micData, samples, &audioRtpRecord_.micAmplFactor_); if (Manager::instance().getEchoCancelState()) echoCanceller.getData(micData); @@ -155,18 +144,19 @@ int AudioRtpRecordHandler::processDataEncode(void) if (codecSampleRate != mainBufferSampleRate) { out = micDataConverted; - _audioRtpRecord._converter->resample(micData, micDataConverted, codecSampleRate, mainBufferSampleRate, samplesToGet); + audioRtpRecord_.converter_->resample(micData, micDataConverted, codecSampleRate, mainBufferSampleRate, samplesToGet); } if (Manager::instance().audioPreference.getNoiseReduce()) { - _audioRtpRecord.audioProcessMutex.enter(); - _audioRtpRecord._noiseSuppress->process(micData, getCodecFrameSize()); - _audioRtpRecord.audioProcessMutex.leave(); + ost::MutexLock lock(audioRtpRecord_.audioProcessMutex_); + audioRtpRecord_.noiseSuppress_->process(micData, getCodecFrameSize()); } - _audioRtpRecord.audioCodecMutex.enter(); - int compSize = _audioRtpRecord._audioCodec->encode(micDataEncoded, out, getCodecFrameSize()); - _audioRtpRecord.audioCodecMutex.leave(); + int compSize; + { + ost::MutexLock lock(audioRtpRecord_.audioCodecMutex_); + compSize = audioRtpRecord_.audioCodec_->encode(micDataEncoded, out, getCodecFrameSize()); + } return compSize; } @@ -178,19 +168,19 @@ void AudioRtpRecordHandler::processDataDecode(unsigned char *spkrData, unsigned int codecSampleRate = getCodecSampleRate(); - SFLDataFormat *spkrDataDecoded = _audioRtpRecord.decData; - SFLDataFormat *spkrDataConverted = _audioRtpRecord.resampledData; + SFLDataFormat *spkrDataDecoded = audioRtpRecord_.decData_; + SFLDataFormat *spkrDataConverted = audioRtpRecord_.resampledData_; int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); - _audioRtpRecord.audioCodecMutex.enter(); - - // Return the size of data in samples - int inSamples = _audioRtpRecord._audioCodec->decode(spkrDataDecoded , spkrData , size); - - _audioRtpRecord.audioCodecMutex.leave(); + int inSamples; + { + ost::MutexLock lock(audioRtpRecord_.audioCodecMutex_); + // Return the size of data in samples + inSamples = audioRtpRecord_.audioCodec_->decode(spkrDataDecoded , spkrData , size); + } - fadeIn(spkrDataDecoded, inSamples, &_audioRtpRecord._micAmplFactor); + fadeIn(spkrDataDecoded, inSamples, &audioRtpRecord_.micAmplFactor_); // Normalize incomming signal gainController.process(spkrDataDecoded, inSamples); @@ -202,7 +192,7 @@ void AudioRtpRecordHandler::processDataDecode(unsigned char *spkrData, unsigned if (codecSampleRate != mainBufferSampleRate) { // Do sample rate conversion outSamples = ((float) inSamples * ((float) mainBufferSampleRate / (float) codecSampleRate)); - _audioRtpRecord._converter->resample(spkrDataDecoded, spkrDataConverted, codecSampleRate, mainBufferSampleRate, inSamples); + audioRtpRecord_.converter_->resample(spkrDataDecoded, spkrDataConverted, codecSampleRate, mainBufferSampleRate, inSamples); out = spkrDataConverted; } @@ -223,5 +213,4 @@ void AudioRtpRecordHandler::fadeIn(SFLDataFormat *audio, int size, SFLDataFormat *factor /= FADEIN_STEP_SIZE; } - } diff --git a/daemon/src/audio/audiortp/audio_rtp_record_handler.h b/daemon/src/audio/audiortp/audio_rtp_record_handler.h index b249a004b7feba12392f171d07c67fd3a08c8dcf..50f23a5a88cdc55dbf9d3fe48f0f3af6169ee451 100644 --- a/daemon/src/audio/audiortp/audio_rtp_record_handler.h +++ b/daemon/src/audio/audiortp/audio_rtp_record_handler.h @@ -78,24 +78,23 @@ class AudioRtpRecord { AudioRtpRecord(); ~AudioRtpRecord(); - AudioCodec *_audioCodec; - ost::Mutex audioCodecMutex; - int _codecPayloadType; - bool _hasDynamicPayloadType; - SFLDataFormat decData[DEC_BUFFER_SIZE]; - SFLDataFormat resampledData[DEC_BUFFER_SIZE]; - unsigned char encodedData[DEC_BUFFER_SIZE]; - SamplerateConverter *_converter; - int _codecSampleRate; - int _codecFrameSize; - int _converterSamplingRate; - std::list<int> _dtmfQueue; - SFLDataFormat _micAmplFactor; - NoiseSuppress *_noiseSuppress; - ost::Mutex audioProcessMutex; - std::string _callId; - unsigned int _dtmfPayloadType; - + AudioCodec *audioCodec_; + ost::Mutex audioCodecMutex_; + int codecPayloadType_; + bool hasDynamicPayloadType_; + SFLDataFormat decData_[DEC_BUFFER_SIZE]; + SFLDataFormat resampledData_[DEC_BUFFER_SIZE]; + unsigned char encodedData_[DEC_BUFFER_SIZE]; + SamplerateConverter *converter_; + int codecSampleRate_; + int codecFrameSize_; + int converterSamplingRate_; + std::list<int> dtmfQueue_; + SFLDataFormat micAmplFactor_; + NoiseSuppress *noiseSuppress_; + ost::Mutex audioProcessMutex_; + std::string callId_; + unsigned int dtmfPayloadType_; }; @@ -107,45 +106,44 @@ class AudioRtpRecordHandler { /** * Set rtp media for this session */ - void setRtpMedia(AudioCodec* audioCodec); - AudioCodec *getAudioCodec(void) const { - return _audioRtpRecord._audioCodec; + AudioCodec *getAudioCodec() const { + return audioRtpRecord_.audioCodec_; } - int getCodecPayloadType(void) const { - return _audioRtpRecord._codecPayloadType; + int getCodecPayloadType() const { + return audioRtpRecord_.codecPayloadType_; } - int getCodecSampleRate(void) const { - return _audioRtpRecord._codecSampleRate; + int getCodecSampleRate() const { + return audioRtpRecord_.codecSampleRate_; } - int getCodecFrameSize(void) const { - return _audioRtpRecord._codecFrameSize; + int getCodecFrameSize() const { + return audioRtpRecord_.codecFrameSize_; } - bool getHasDynamicPayload(void) const { - return _audioRtpRecord._hasDynamicPayloadType; + bool getHasDynamicPayload() const { + return audioRtpRecord_.hasDynamicPayloadType_; } - int DtmfPending(void) const { - return _audioRtpRecord._dtmfQueue.size() > 0; + int DtmfPending() const { + return audioRtpRecord_.dtmfQueue_.size() > 0; } - const unsigned char *getMicDataEncoded(void) const { - return _audioRtpRecord.encodedData; + const unsigned char *getMicDataEncoded() const { + return audioRtpRecord_.encodedData_; } - void initBuffers(void); + void initBuffers(); - void initNoiseSuppress(void); + void initNoiseSuppress(); /** * Encode audio data from mainbuffer */ - int processDataEncode(void); + int processDataEncode(); /** * Decode audio data received from peer @@ -158,18 +156,18 @@ class AudioRtpRecordHandler { void fadeIn(SFLDataFormat *audio, int size, SFLDataFormat *factor); void setDtmfPayloadType(unsigned int payloadType) { - _audioRtpRecord._dtmfPayloadType = payloadType; + audioRtpRecord_.dtmfPayloadType_ = payloadType; } - unsigned int getDtmfPayloadType(void) const { - return _audioRtpRecord._dtmfPayloadType; + unsigned int getDtmfPayloadType() const { + return audioRtpRecord_.dtmfPayloadType_; } void putDtmfEvent(int digit); protected: - AudioRtpRecord _audioRtpRecord; + AudioRtpRecord audioRtpRecord_; private: diff --git a/daemon/src/audio/audiortp/audio_rtp_session.cpp b/daemon/src/audio/audiortp/audio_rtp_session.cpp index aaf292c938b16effcf3d9ae6f36cc061f8f7b41c..201731872caa08e3ddebd5d3f51043bfa32de183 100644 --- a/daemon/src/audio/audiortp/audio_rtp_session.cpp +++ b/daemon/src/audio/audiortp/audio_rtp_session.cpp @@ -36,6 +36,7 @@ #include "audio_symmetric_rtp_session.h" #include "sip/sdp.h" +#include "sip/sipcall.h" #include "audio/audiolayer.h" #include <ccrtp/rtp.h> #include <ccrtp/oqueue.h> @@ -44,33 +45,33 @@ namespace sfl { AudioRtpSession::AudioRtpSession(SIPCall * sipcall, RtpMethod type, ost::RTPDataQueue *queue, ost::Thread *thread) : AudioRtpRecordHandler(sipcall) - , _ca(sipcall) - , _type(type) - , _timestamp(0) - , _timestampIncrement(0) - , _timestampCount(0) - , _isStarted(false) - , _queue(queue) - , _thread(thread) + , ca_(sipcall) + , type_(type) + , timestamp_(0) + , timestampIncrement_(0) + , timestampCount_(0) + , isStarted_(false) + , queue_(queue) + , thread_(thread) { - assert(_ca); - _queue->setTypeOfService(ost::RTPDataQueue::tosEnhanced); + assert(ca_); + queue_->setTypeOfService(ost::RTPDataQueue::tosEnhanced); } AudioRtpSession::~AudioRtpSession() { - _queue->disableStack(); + queue_->disableStack(); } void AudioRtpSession::updateSessionMedia(AudioCodec *audioCodec) { - int lastSamplingRate = _audioRtpRecord._codecSampleRate; + int lastSamplingRate = audioRtpRecord_.codecSampleRate_; setSessionMedia(audioCodec); - Manager::instance().audioSamplingRateChanged(_audioRtpRecord._codecSampleRate); + Manager::instance().audioSamplingRateChanged(audioRtpRecord_.codecSampleRate_); - if (lastSamplingRate != _audioRtpRecord._codecSampleRate) { + if (lastSamplingRate != audioRtpRecord_.codecSampleRate_) { _debug("AudioRtpSession: Update noise suppressor with sampling rate %d and frame size %d", getCodecSampleRate(), getCodecFrameSize()); initNoiseSuppress(); } @@ -89,65 +90,65 @@ void AudioRtpSession::setSessionMedia(AudioCodec *audioCodec) // G722 requires timestamp to be incremented at 8kHz if (payloadType == g722PayloadType) - _timestampIncrement = g722RtpTimeincrement; + timestampIncrement_ = g722RtpTimeincrement; else - _timestampIncrement = frameSize; + timestampIncrement_ = frameSize; _debug("AudioRptSession: Codec payload: %d", payloadType); _debug("AudioSymmetricRtpSession: Codec sampling rate: %d", smplRate); _debug("AudioSymmetricRtpSession: Codec frame size: %d", frameSize); - _debug("AudioSymmetricRtpSession: RTP timestamp increment: %d", _timestampIncrement); + _debug("AudioSymmetricRtpSession: RTP timestamp increment: %d", timestampIncrement_); if (payloadType == g722PayloadType) { _debug("AudioSymmetricRtpSession: Setting G722 payload format"); - _queue->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) payloadType, g722RtpClockRate)); + queue_->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) payloadType, g722RtpClockRate)); } else { if (dynamic) { _debug("AudioSymmetricRtpSession: Setting dynamic payload format"); - _queue->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) payloadType, smplRate)); + queue_->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) payloadType, smplRate)); } else { _debug("AudioSymmetricRtpSession: Setting static payload format"); - _queue->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) payloadType)); + queue_->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) payloadType)); } } - if (_type != Zrtp) - _ca->setRecordingSmplRate(getCodecSampleRate()); + if (type_ != Zrtp) + ca_->setRecordingSmplRate(getCodecSampleRate()); } void AudioRtpSession::sendDtmfEvent() { ost::RTPPacket::RFC2833Payload payload; - payload.event = _audioRtpRecord._dtmfQueue.front(); + payload.event = audioRtpRecord_.dtmfQueue_.front(); payload.ebit = false; // end of event bit payload.rbit = false; // reserved bit payload.duration = 1; // duration for this event - _audioRtpRecord._dtmfQueue.pop_front(); + audioRtpRecord_.dtmfQueue_.pop_front(); _debug("AudioRtpSession: Send RTP Dtmf (%d)", payload.event); - _timestamp += (_type == Zrtp) ? 160 : _timestampIncrement; + timestamp_ += (type_ == Zrtp) ? 160 : timestampIncrement_; // discard equivalent size of audio processDataEncode(); // change Payload type for DTMF payload - _queue->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) getDtmfPayloadType(), 8000)); + queue_->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) getDtmfPayloadType(), 8000)); - _queue->setMark(true); - _queue->sendImmediate(_timestamp, (const unsigned char *)(&payload), sizeof(payload)); - _queue->setMark(false); + queue_->setMark(true); + queue_->sendImmediate(timestamp_, (const unsigned char *)(&payload), sizeof(payload)); + queue_->setMark(false); // get back the payload to audio - _queue->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) getCodecPayloadType())); + queue_->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) getCodecPayloadType())); } void AudioRtpSession::receiveSpeakerData() { - const ost::AppDataUnit* adu = _queue->getData(_queue->getFirstTimestamp()); + const ost::AppDataUnit* adu = queue_->getData(queue_->getFirstTimestamp()); if (!adu) return; @@ -173,57 +174,57 @@ void AudioRtpSession::sendMicData() return; // Increment timestamp for outgoing packet - _timestamp += _timestampIncrement; + timestamp_ += timestampIncrement_; - if (_type == Zrtp) - _queue->putData(_timestamp, getMicDataEncoded(), compSize); + if (type_ == Zrtp) + queue_->putData(timestamp_, getMicDataEncoded(), compSize); // putData put the data on RTP queue, sendImmediate bypass this queue - _queue->sendImmediate(_timestamp, getMicDataEncoded(), compSize); + queue_->sendImmediate(timestamp_, getMicDataEncoded(), compSize); } -void AudioRtpSession::setSessionTimeouts(void) +void AudioRtpSession::setSessionTimeouts() { _debug("AudioRtpSession: Set session scheduling timeout (%d) and expireTimeout (%d)", sfl::schedulingTimeout, sfl::expireTimeout); - _queue->setSchedulingTimeout(sfl::schedulingTimeout); - _queue->setExpireTimeout(sfl::expireTimeout); + queue_->setSchedulingTimeout(sfl::schedulingTimeout); + queue_->setExpireTimeout(sfl::expireTimeout); } -void AudioRtpSession::setDestinationIpAddress(void) +void AudioRtpSession::setDestinationIpAddress() { _info("AudioRtpSession: Setting IP address for the RTP session"); // Store remote ip in case we would need to forget current destination - _remote_ip = ost::InetHostAddress(_ca->getLocalSDP()->getRemoteIP().c_str()); + remote_ip_ = ost::InetHostAddress(ca_->getLocalSDP()->getRemoteIP().c_str()); - if (!_remote_ip) { + if (!remote_ip_) { _warn("AudioRtpSession: Target IP address (%s) is not correct!", - _ca->getLocalSDP()->getRemoteIP().data()); + ca_->getLocalSDP()->getRemoteIP().data()); return; } // Store remote port in case we would need to forget current destination - _remote_port = (unsigned short) _ca->getLocalSDP()->getRemoteAudioPort(); + remote_port_ = (unsigned short) ca_->getLocalSDP()->getRemoteAudioPort(); _info("AudioRtpSession: New remote address for session: %s:%d", - _ca->getLocalSDP()->getRemoteIP().data(), _remote_port); + ca_->getLocalSDP()->getRemoteIP().data(), remote_port_); - if (!_queue->addDestination(_remote_ip, _remote_port)) { + if (!queue_->addDestination(remote_ip_, remote_port_)) { _warn("AudioRtpSession: Can't add new destination to session!"); return; } } -void AudioRtpSession::updateDestinationIpAddress(void) +void AudioRtpSession::updateDestinationIpAddress() { _debug("AudioRtpSession: Update destination ip address"); // Destination address are stored in a list in ccrtp // This method remove the current destination entry - if (!_queue->forgetDestination(_remote_ip, _remote_port, _remote_port+1)) + if (!queue_->forgetDestination(remote_ip_, remote_port_, remote_port_ + 1)) _debug("AudioRtpSession: Did not remove previous destination"); // new destination is stored in call @@ -234,21 +235,21 @@ void AudioRtpSession::updateDestinationIpAddress(void) int AudioRtpSession::startRtpThread(AudioCodec* audiocodec) { - if (_isStarted) + if (isStarted_) return 0; _debug("AudioSymmetricRtpSession: Starting main thread"); - _isStarted = true; + isStarted_ = true; setSessionTimeouts(); setSessionMedia(audiocodec); initBuffers(); initNoiseSuppress(); - _queue->enableStack(); - int ret = _thread->start(); + queue_->enableStack(); + int ret = thread_->start(); - if (_type == Zrtp) + if (type_ == Zrtp) return ret; AudioSymmetricRtpSession *self = dynamic_cast<AudioSymmetricRtpSession*>(this); diff --git a/daemon/src/audio/audiortp/audio_rtp_session.h b/daemon/src/audio/audiortp/audio_rtp_session.h index 64ebd2cbd7da276150c7f1e8698b8903743f0862..35733fa49141217f89e5e208d9f49b217ae7504f 100644 --- a/daemon/src/audio/audiortp/audio_rtp_session.h +++ b/daemon/src/audio/audiortp/audio_rtp_session.h @@ -63,7 +63,7 @@ class AudioRtpSession : public AudioRtpRecordHandler { virtual ~AudioRtpSession(); RtpMethod getAudioRtpType() { - return _type; + return type_; } void updateSessionMedia(AudioCodec *audioCodec); @@ -72,7 +72,7 @@ class AudioRtpSession : public AudioRtpRecordHandler { /** * Used mostly when receiving a reinvite */ - void updateDestinationIpAddress(void); + void updateDestinationIpAddress(); protected: @@ -91,9 +91,9 @@ class AudioRtpSession : public AudioRtpRecordHandler { */ void sendMicData(); - SIPCall *_ca; + SIPCall *ca_; - RtpMethod _type; + RtpMethod type_; private: @@ -105,13 +105,12 @@ class AudioRtpSession : public AudioRtpRecordHandler { /** * Set RTP Sockets send/receive timeouts */ - void setSessionTimeouts(void); + void setSessionTimeouts(); /** * Retreive destination address for this session. Stored in CALL */ - void setDestinationIpAddress(void); - + void setDestinationIpAddress(); /** * Receive data from peer @@ -121,35 +120,34 @@ class AudioRtpSession : public AudioRtpRecordHandler { // Main destination address for this rtp session. // Stored in case or reINVITE, which may require to forget // this destination and update a new one. - ost::InetHostAddress _remote_ip; + ost::InetHostAddress remote_ip_; // Main destination port for this rtp session. // Stored in case reINVITE, which may require to forget // this destination and update a new one - unsigned short _remote_port; + unsigned short remote_port_; /** * Timestamp for this session */ - int _timestamp; + int timestamp_; /** * Timestamp incrementation value based on codec period length (framesize) * except for G722 which require a 8 kHz incrementation. */ - int _timestampIncrement; + int timestampIncrement_; /** * Timestamp reset frequency specified in number of packet sent */ - short _timestampCount; - + short timestampCount_; - bool _isStarted; + bool isStarted_; - ost::RTPDataQueue *_queue; + ost::RTPDataQueue *queue_; - ost::Thread *_thread; + ost::Thread *thread_; }; } diff --git a/daemon/src/audio/audiortp/audio_srtp_session.cpp b/daemon/src/audio/audiortp/audio_srtp_session.cpp index 01e9173411f8392735db8256ac85000ae4f4d822..fee63e9bc5250b44e6bf480480ba5312f4163d11 100644 --- a/daemon/src/audio/audiortp/audio_srtp_session.cpp +++ b/daemon/src/audio/audiortp/audio_srtp_session.cpp @@ -46,17 +46,17 @@ namespace sfl { AudioSrtpSession::AudioSrtpSession(SIPCall * sipcall) : AudioSymmetricRtpSession(sipcall), - _remoteCryptoCtx(NULL), - _localCryptoCtx(NULL), - _localCryptoSuite(0), - _remoteCryptoSuite(0), - _localMasterKeyLength(0), - _localMasterSaltLength(0), - _remoteMasterKeyLength(0), - _remoteMasterSaltLength(0), - _remoteOfferIsSet(false) + remoteCryptoCtx_(NULL), + localCryptoCtx_(NULL), + localCryptoSuite_(0), + remoteCryptoSuite_(0), + localMasterKeyLength_(0), + localMasterSaltLength_(0), + remoteMasterKeyLength_(0), + remoteMasterSaltLength_(0), + remoteOfferIsSet_(false) { - this->_type = Sdes; + type_ = Sdes; } AudioSrtpSession::~AudioSrtpSession() @@ -74,10 +74,9 @@ void AudioSrtpSession::initLocalCryptoInfo() initializeLocalCryptoContext(); // Set local crypto context in ccrtp - _localCryptoCtx->deriveSrtpKeys(0); - - setOutQueueCryptoContext(_localCryptoCtx); + localCryptoCtx_->deriveSrtpKeys(0); + setOutQueueCryptoContext(localCryptoCtx_); } std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() @@ -91,7 +90,7 @@ std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() // cryptographic context tagged 1, 2, 3... std::string tag = "1"; - std::string crypto_suite = sfl::CryptoSuites[_localCryptoSuite].name; + std::string crypto_suite = sfl::CryptoSuites[localCryptoSuite_].name; // srtp keys formated as the following as the following // inline:keyParameters|keylifetime|MasterKeyIdentifier @@ -112,18 +111,16 @@ std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() return crypto_vector; } - void AudioSrtpSession::setRemoteCryptoInfo(sfl::SdesNegotiator& nego) { - if (!_remoteOfferIsSet) { - + if (not remoteOfferIsSet_) { _debug("%s", nego.getKeyInfo().c_str()); // Use second crypto suite if key length is 32 bit, default is 80; if (nego.getAuthTagLength() == "32") { - _localCryptoSuite = 1; - _remoteCryptoSuite = 1; + localCryptoSuite_ = 1; + remoteCryptoSuite_ = 1; } // decode keys @@ -131,85 +128,76 @@ void AudioSrtpSession::setRemoteCryptoInfo(sfl::SdesNegotiator& nego) // init crypto content in Srtp session initializeRemoteCryptoContext(); - setInQueueCryptoContext(_remoteCryptoCtx); + setInQueueCryptoContext(remoteCryptoCtx_); // initLocalCryptoInfo(); - _remoteOfferIsSet = true; + remoteOfferIsSet_ = true; } - } - void AudioSrtpSession::initializeLocalMasterKey(void) { _debug("AudioSrtp: Init local master key"); // @TODO key may have different length depending on cipher suite - _localMasterKeyLength = sfl::CryptoSuites[_localCryptoSuite].masterKeyLength / 8; + localMasterKeyLength_ = sfl::CryptoSuites[localCryptoSuite_].masterKeyLength / 8; - _debug("AudioSrtp: Local master key length %d", _localMasterKeyLength); + _debug("AudioSrtp: Local master key length %d", localMasterKeyLength_); // Allocate memory for key - unsigned char *random_key = new unsigned char[_localMasterKeyLength]; + unsigned char *random_key = new unsigned char[localMasterKeyLength_]; // Generate ryptographically strong pseudo-random bytes int err; - if ((err = RAND_bytes(random_key, _localMasterKeyLength)) != 1) + if ((err = RAND_bytes(random_key, localMasterKeyLength_)) != 1) _debug("Error occured while generating cryptographically strong pseudo-random key"); - memcpy(_localMasterKey, random_key, _localMasterKeyLength); - + memcpy(localMasterKey_, random_key, localMasterKeyLength_); } - void AudioSrtpSession::initializeLocalMasterSalt(void) { - // @TODO key may have different length depending on cipher suite - _localMasterSaltLength = sfl::CryptoSuites[_localCryptoSuite].masterSaltLength / 8; + localMasterSaltLength_ = sfl::CryptoSuites[localCryptoSuite_].masterSaltLength / 8; // Allocate memory for key - unsigned char *random_key = new unsigned char[_localMasterSaltLength]; + unsigned char *random_key = new unsigned char[localMasterSaltLength_]; - _debug("AudioSrtp: Local master salt length %d", _localMasterSaltLength); + _debug("AudioSrtp: Local master salt length %d", localMasterSaltLength_); // Generate ryptographically strong pseudo-random bytes int err; - if ((err = RAND_bytes(random_key, _localMasterSaltLength)) != 1) + if ((err = RAND_bytes(random_key, localMasterSaltLength_)) != 1) _debug("Error occured while generating cryptographically strong pseudo-random key"); - memcpy(_localMasterSalt, random_key, _localMasterSaltLength); - - + memcpy(localMasterSalt_, random_key, localMasterSaltLength_); } - std::string AudioSrtpSession::getBase64ConcatenatedKeys() { _debug("AudioSrtp: Get base64 concatenated keys"); // compute concatenated master and salt length - int concatLength = _localMasterKeyLength + _localMasterSaltLength; + int concatLength = localMasterKeyLength_ + localMasterSaltLength_; uint8 concatKeys[concatLength]; _debug("AudioSrtp: Concatenated length %d", 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 return encodeBase64((unsigned char*) concatKeys, concatLength); } - void AudioSrtpSession::unBase64ConcatenatedKeys(std::string base64keys) { - _remoteMasterKeyLength = sfl::CryptoSuites[_remoteCryptoSuite].masterKeyLength / 8; - _remoteMasterSaltLength = sfl::CryptoSuites[_remoteCryptoSuite].masterSaltLength / 8; + remoteMasterKeyLength_ = sfl::CryptoSuites[remoteCryptoSuite_].masterKeyLength / 8; + remoteMasterSaltLength_ = sfl::CryptoSuites[remoteCryptoSuite_].masterSaltLength / 8; // pointer to binary data char *dataptr = (char*) base64keys.data(); @@ -218,33 +206,32 @@ void AudioSrtpSession::unBase64ConcatenatedKeys(std::string base64keys) char *output = decodeBase64((unsigned char*) dataptr, strlen(dataptr)); // 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_); delete[] output; } - void AudioSrtpSession::initializeRemoteCryptoContext(void) { _debug("AudioSrtp: Initialize remote crypto context"); - CryptoSuiteDefinition crypto = sfl::CryptoSuites[_remoteCryptoSuite]; + CryptoSuiteDefinition crypto = sfl::CryptoSuites[remoteCryptoSuite_]; - if (_remoteCryptoCtx) { - delete _remoteCryptoCtx; - _remoteCryptoCtx = NULL; + if (remoteCryptoCtx_) { + delete remoteCryptoCtx_; + remoteCryptoCtx_ = NULL; } - _remoteCryptoCtx = new ost::CryptoContext(0x0, + remoteCryptoCtx_ = new ost::CryptoContext(0x0, 0, // roc, 0L, // keydr, SrtpEncryptionAESCM, // encryption algo SrtpAuthenticationSha1Hmac, // authtication algo - _remoteMasterKey, - _remoteMasterKeyLength, - _remoteMasterSalt, - _remoteMasterSaltLength, + remoteMasterKey_, + remoteMasterKeyLength_, + remoteMasterSalt_, + remoteMasterSaltLength_, crypto.encryptionKeyLength / 8, crypto.srtpAuthKeyLength / 8, crypto.masterSaltLength / 8, // session salt len @@ -256,27 +243,26 @@ void AudioSrtpSession::initializeLocalCryptoContext(void) { _debug("AudioSrtp: Initialize local crypto context"); - CryptoSuiteDefinition crypto = sfl::CryptoSuites[_localCryptoSuite]; + CryptoSuiteDefinition crypto = sfl::CryptoSuites[localCryptoSuite_]; - if (_localCryptoCtx) { - delete _localCryptoCtx; - _localCryptoCtx = NULL; + if (localCryptoCtx_) { + delete localCryptoCtx_; + localCryptoCtx_ = NULL; } - _localCryptoCtx = new ost::CryptoContext(OutgoingDataQueue::getLocalSSRC(), + localCryptoCtx_ = new ost::CryptoContext(OutgoingDataQueue::getLocalSSRC(), 0, // roc, 0L, // keydr, SrtpEncryptionAESCM, // encryption algo SrtpAuthenticationSha1Hmac, // authtication algo - _localMasterKey, - _localMasterKeyLength, - _localMasterSalt, - _localMasterSaltLength, + localMasterKey_, + localMasterKeyLength_, + localMasterSalt_, + localMasterSaltLength_, crypto.encryptionKeyLength / 8, crypto.srtpAuthKeyLength / 8, crypto.masterSaltLength / 8, // session salt len crypto.srtpAuthTagLength / 8); - } void AudioSrtpSession::restoreCryptoContext(ost::CryptoContext *localContext, ost::CryptoContext *remoteContext) @@ -336,5 +322,4 @@ char* AudioSrtpSession::decodeBase64(unsigned char *input, int length) return buffer; } - } diff --git a/daemon/src/audio/audiortp/audio_srtp_session.h b/daemon/src/audio/audiortp/audio_srtp_session.h index b4df5643550cde80866d7c1a7b1a4f0894cf4462..28d822caa4c226e5d464fb0bbe5842675bff425c 100644 --- a/daemon/src/audio/audiortp/audio_srtp_session.h +++ b/daemon/src/audio/audiortp/audio_srtp_session.h @@ -81,7 +81,7 @@ class AudioSrtpSession : public AudioSymmetricRtpSession { * method must be called befor setRemoteCryptoInfo in case of an * outgoing call or after in case of an outgoing call. */ - std::vector<std::string> getLocalCryptoInfo(void); + std::vector<std::string> getLocalCryptoInfo(); /** * Set remote crypto header from incoming sdp offer @@ -93,7 +93,7 @@ class AudioSrtpSession : public AudioSymmetricRtpSession { * this method must be called before sending first Invite request * with SDP offer. */ - void initLocalCryptoInfo(void); + void initLocalCryptoInfo(); /** * Restore the cryptographic context. most likely useful to restore @@ -103,10 +103,10 @@ class AudioSrtpSession : public AudioSymmetricRtpSession { /** Remote srtp crypto context to be set into incoming data queue. */ - ost::CryptoContext* _remoteCryptoCtx; + ost::CryptoContext* remoteCryptoCtx_; /** Local srtp crypto context to be set into outgoing data queue. */ - ost::CryptoContext* _localCryptoCtx; + ost::CryptoContext* localCryptoCtx_; private: @@ -114,25 +114,25 @@ class AudioSrtpSession : public AudioSymmetricRtpSession { * Init local master key according to current crypto context * as defined in SdesNegotiator.h */ - void initializeLocalMasterKey(void); + void initializeLocalMasterKey(); /** * Init local master salt according to current crypto context * as defined in SdesNegotiator.h */ - void initializeLocalMasterSalt(void); + void initializeLocalMasterSalt(); /** * Init remote crypto context in audio srtp session. This method * must be called after unBase64ConcatenatedKeys. */ - void initializeRemoteCryptoContext(void); + void initializeRemoteCryptoContext(); /** * Init local crypto context in audio srtp session. Make sure remote * crypto context is set before calling this method for incoming calls. */ - void initializeLocalCryptoContext(void); + void initializeLocalCryptoContext(); /** * Used to generate local keys to be included in SDP offer/answer. @@ -155,33 +155,33 @@ class AudioSrtpSession : public AudioSymmetricRtpSession { char* decodeBase64(unsigned char *input, int length); /** Default local crypto suite is AES_CM_128_HMAC_SHA1_80*/ - int _localCryptoSuite; + int localCryptoSuite_; /** Remote crypto suite is initialized at AES_CM_128_HMAC_SHA1_80*/ - int _remoteCryptoSuite; + int remoteCryptoSuite_; - uint8 _localMasterKey[16]; + uint8 localMasterKey_[16]; /** local master key length in byte */ - int _localMasterKeyLength; + int localMasterKeyLength_; - uint8 _localMasterSalt[14]; + uint8 localMasterSalt_[14]; /** local master salt length in byte */ - int _localMasterSaltLength; + int localMasterSaltLength_; - uint8 _remoteMasterKey[16]; + uint8 remoteMasterKey_[16]; /** remote master key length in byte */ - int _remoteMasterKeyLength; + int remoteMasterKeyLength_; - uint8 _remoteMasterSalt[14]; + uint8 remoteMasterSalt_[14]; /** remote master salt length in byte */ - int _remoteMasterSaltLength; + int remoteMasterSaltLength_; /** Used to make sure remote crypto context not initialized wice. */ - bool _remoteOfferIsSet; + bool remoteOfferIsSet_; }; } diff --git a/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp index 1d5f57a262b39d7b9bdf48df92111fbad9182489..71ad81f6ea1fee8e434018105181d606f9691f16 100644 --- a/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp +++ b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp @@ -36,6 +36,7 @@ #include "audio_symmetric_rtp_session.h" #include "audio_rtp_record_handler.h" #include "sip/sdp.h" +#include "sip/sipcall.h" #include "audio/audiolayer.h" namespace sfl { @@ -43,30 +44,20 @@ namespace sfl { AudioSymmetricRtpSession::AudioSymmetricRtpSession(SIPCall * sipcall) : ost::SymmetricRTPSession(ost::InetHostAddress(sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort()) , AudioRtpSession(sipcall, Symmetric, this, this) - , _rtpThread(new AudioRtpThread(this)) + , rtpThread_(new AudioRtpThread(this)) { - _info("AudioSymmetricRtpSession: Setting new RTP session with destination %s:%d", _ca->getLocalIp().c_str(), _ca->getLocalAudioPort()); - - _audioRtpRecord._callId = _ca->getCallId(); + _info("AudioSymmetricRtpSession: Setting new RTP session with destination %s:%d", ca_->getLocalIp().c_str(), ca_->getLocalAudioPort()); + audioRtpRecord_.callId_ = ca_->getCallId(); } AudioSymmetricRtpSession::~AudioSymmetricRtpSession() { - _info("AudioSymmetricRtpSession: Delete AudioSymmetricRtpSession instance"); - - _rtpThread->running = false; - delete _rtpThread; + rtpThread_->running = false; + delete rtpThread_; } AudioSymmetricRtpSession::AudioRtpThread::AudioRtpThread(AudioSymmetricRtpSession *session) : running(true), rtpSession(session) -{ - _debug("AudioSymmetricRtpSession: Create new rtp thread"); -} - -AudioSymmetricRtpSession::AudioRtpThread::~AudioRtpThread() -{ - _debug("AudioSymmetricRtpSession: Delete rtp thread"); -} +{} void AudioSymmetricRtpSession::AudioRtpThread::run() { @@ -77,7 +68,6 @@ void AudioSymmetricRtpSession::AudioRtpThread::run() _debug("AudioRtpThread: Entering Audio rtp thread main loop"); while (running) { - // Send session if (rtpSession->DtmfPending()) rtpSession->sendDtmfEvent(); diff --git a/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h index 8eee8ab6defb3669d1312cb876b4f0f90a1c825d..26fdcf5f46418895dd116b39e78633027d297297 100644 --- a/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h +++ b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h @@ -34,25 +34,19 @@ #ifndef __AUDIO_SYMMETRIC_RTP_SESSION_H__ #define __AUDIO_SYMMETRIC_RTP_SESSION_H__ -#include <iostream> #include <exception> -#include <list> #include <cassert> #include <cstddef> -#include "global.h" - #include "audio_rtp_session.h" -#include "audio_rtp_record_handler.h" -#include "sip/sipcall.h" -#include "audio/codecs/audiocodec.h" using std::ptrdiff_t; #include <ccrtp/rtp.h> #include <ccrtp/iqueue.h> #include <cc++/numbers.h> // ost::Time -#include <fstream> +class SIPCall; + namespace sfl { class AudioSymmetricRtpSession : public ost::TimerPort, public ost::SymmetricRTPSession, public AudioRtpSession { @@ -69,9 +63,9 @@ class AudioSymmetricRtpSession : public ost::TimerPort, public ost::SymmetricRTP return AudioRtpSession::onRTPPacketRecv(pkt); } - int startSymmetricRtpThread(void) { - assert(_rtpThread); - return _rtpThread->start(); + int startSymmetricRtpThread() { + assert(rtpThread_); + return rtpThread_->start(); } private: @@ -79,23 +73,25 @@ class AudioSymmetricRtpSession : public ost::TimerPort, public ost::SymmetricRTP class AudioRtpThread : public ost::Thread, public ost::TimerPort { public: AudioRtpThread(AudioSymmetricRtpSession *session); - ~AudioRtpThread(); + ~AudioRtpThread(){} virtual void run(); bool running; private: + AudioRtpThread(const AudioRtpThread &); + AudioRtpThread& operator=(const AudioRtpThread &); + AudioSymmetricRtpSession *rtpSession; }; SpeexEchoCancel echoCanceller; protected: - AudioRtpThread *_rtpThread; + AudioRtpThread *rtpThread_; public: - friend class AudioRtpThread; }; diff --git a/daemon/src/audio/audiortp/audio_zrtp_session.cpp b/daemon/src/audio/audiortp/audio_zrtp_session.cpp index a09d8256c83edf4323fcc453bc3cb0fb3a665f76..6dbc9751c95cf6fb2053851fb28aa652e65c441d 100644 --- a/daemon/src/audio/audiortp/audio_zrtp_session.cpp +++ b/daemon/src/audio/audiortp/audio_zrtp_session.cpp @@ -56,28 +56,25 @@ AudioZrtpSession::AudioZrtpSession(SIPCall * sipcall, const std::string& zidFile 0, ost::MembershipBookkeeping::defaultMembersHashSize, ost::defaultApplication()), - _zidFilename(zidFilename) + zidFilename_(zidFilename) { _debug("AudioZrtpSession initialized"); initializeZid(); setCancel(cancelDefault); - _info("AudioZrtpSession: Setting new RTP session with destination %s:%d", _ca->getLocalIp().c_str(), _ca->getLocalAudioPort()); + _info("AudioZrtpSession: Setting new RTP session with destination %s:%d", ca_->getLocalIp().c_str(), ca_->getLocalAudioPort()); } AudioZrtpSession::~AudioZrtpSession() { - _debug("AudioZrtpSession: Delete AudioSymmetricRtpSession instance"); - try { terminate(); } catch (...) { - _debug("AudioZrtpSession: Thread destructor didn't terminate correctly"); throw; } - Manager::instance().getMainBuffer()->unBindAll(_ca->getCallId()); + Manager::instance().getMainBuffer()->unBindAll(ca_->getCallId()); } void AudioZrtpSession::final() @@ -85,23 +82,21 @@ void AudioZrtpSession::final() delete this; } -void AudioZrtpSession::initializeZid(void) +void AudioZrtpSession::initializeZid() { - - if (_zidFilename.empty()) { + if (zidFilename_.empty()) throw ZrtpZidException("zid filename empty"); - } std::string zidCompleteFilename; // xdg_config = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".cache/sflphone"; - std::string xdg_config = std::string(HOMEDIR) + DIR_SEPARATOR_STR + ".cache" + DIR_SEPARATOR_STR + PACKAGE + "/" + _zidFilename; + std::string xdg_config = std::string(HOMEDIR) + DIR_SEPARATOR_STR + ".cache" + DIR_SEPARATOR_STR + PACKAGE + "/" + zidFilename_; _debug(" xdg_config %s", xdg_config.c_str()); if (XDG_CACHE_HOME != NULL) { - std::string xdg_env = std::string(XDG_CACHE_HOME) + _zidFilename; + std::string xdg_env = std::string(XDG_CACHE_HOME) + zidFilename_; _debug(" xdg_env %s", xdg_env.c_str()); (xdg_env.length() > 0) ? zidCompleteFilename = xdg_env : zidCompleteFilename = xdg_config; } else @@ -111,40 +106,32 @@ void AudioZrtpSession::initializeZid(void) if (initialize(zidCompleteFilename.c_str()) >= 0) { _debug("Register callbacks"); setEnableZrtp(true); - setUserCallback(new ZrtpSessionCallback(_ca)); + setUserCallback(new ZrtpSessionCallback(ca_)); return; } _debug("Initialization from ZID file failed. Trying to remove..."); - if (remove(zidCompleteFilename.c_str()) !=0) { - _debug("Failed to remove zid file: %m"); + if (remove(zidCompleteFilename.c_str()) != 0) throw ZrtpZidException("zid file deletion failed"); - } - if (initialize(zidCompleteFilename.c_str()) < 0) { - _debug("ZRTP initialization failed"); + if (initialize(zidCompleteFilename.c_str()) < 0) throw ZrtpZidException("zid initialization failed"); - } return; } void AudioZrtpSession::run() { - // Set recording sampling rate - _ca->setRecordingSmplRate(getCodecSampleRate()); - - _debug("AudioZrtpSession: Entering mainloop for call %s",_ca->getCallId().c_str()); + ca_->setRecordingSmplRate(getCodecSampleRate()); + _debug("AudioZrtpSession: Entering mainloop for call %s", ca_->getCallId().c_str()); uint32 timeout = 0; while (isActive()) { - - if (timeout < 1000) { // !(timeout/1000) + if (timeout < 1000) timeout = getSchedulingTimeout(); - } // Send session if (DtmfPending()) @@ -171,19 +158,16 @@ void AudioZrtpSession::run() if (isPendingData(timeout/1000)) { setCancel(cancelDeferred); - if (isActive()) { // take in only if active + if (isActive()) takeInDataPacket(); - } setCancel(cancelImmediate); } - timeout = 0; } - } - _debug("AudioZrtpSession: Left main loop for call %s", _ca->getCallId().c_str()); + _debug("AudioZrtpSession: Left main loop for call %s", ca_->getCallId().c_str()); } } diff --git a/daemon/src/audio/audiortp/audio_zrtp_session.h b/daemon/src/audio/audiortp/audio_zrtp_session.h index 920d10b3d2ea2303d41ea460bfebdc2298dc78d9..3a19a5e3fd148e2e9090965a0b058bb56296407f 100644 --- a/daemon/src/audio/audiortp/audio_zrtp_session.h +++ b/daemon/src/audio/audiortp/audio_zrtp_session.h @@ -48,7 +48,7 @@ namespace sfl { class ZrtpZidException: public std::runtime_error { public: - ZrtpZidException(const std::string& str="") : + ZrtpZidException(const std::string& str = "") : std::runtime_error("ZRTP ZID initialization failed." + str) {} }; @@ -56,7 +56,6 @@ class ZrtpZidException: public std::runtime_error { class AudioZrtpSession : public AudioRtpSession, protected ost::Thread, public ost::TRTPSessionBase<ost::SymmetricRTPChannel, ost::SymmetricRTPChannel, ost::ZrtpQueue> { public: AudioZrtpSession(SIPCall * sipcall, const std::string& zidFilename); - ~AudioZrtpSession(); virtual void final(); @@ -69,10 +68,8 @@ class AudioZrtpSession : public AudioRtpSession, protected ost::Thread, public o } private: - - void initializeZid(void); - - std::string _zidFilename; + void initializeZid(); + std::string zidFilename_; }; } diff --git a/daemon/src/audio/dcblocker.cpp b/daemon/src/audio/dcblocker.cpp index 7578347ff548e5622074982d959e98f3c0b004a1..3aa1169a36fa0ffbf0fe7f48df336a8ee6408643 100644 --- a/daemon/src/audio/dcblocker.cpp +++ b/daemon/src/audio/dcblocker.cpp @@ -30,27 +30,24 @@ #include "dcblocker.h" -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::process(SFLDataFormat *out, SFLDataFormat *in, int samples) { - for (int i = 0; i < samples; i++) { - _x = in[i]; + for (int i = 0; i < samples; ++i) { + x_ = in[i]; - _y = (SFLDataFormat)((float) _x - (float) _xm1 + 0.9999 * (float) _y); - _xm1 = _x; - _ym1 = _y; + y_ = (SFLDataFormat) ((float) x_ - (float) xm1_ + 0.9999 * (float) y_); + xm1_ = x_; + ym1_ = y_; - out[i] = _y; + out[i] = y_; } } + diff --git a/daemon/src/audio/dcblocker.h b/daemon/src/audio/dcblocker.h index 56bd15f56aa6a14cc9062badc2671ea3ccf041ff..6dbb073ea50330eef90b3308d20a99b1e2c4f524 100644 --- a/daemon/src/audio/dcblocker.h +++ b/daemon/src/audio/dcblocker.h @@ -34,20 +34,13 @@ #include "global.h" class DcBlocker { - public: - - DcBlocker(); - - ~DcBlocker(); - - void reset(void); - + void reset(); void process(SFLDataFormat *out, SFLDataFormat *in, int samples); private: - SFLDataFormat _y, _x, _xm1, _ym1; + SFLDataFormat y_, x_, xm1_, ym1_; }; #endif diff --git a/daemon/src/audio/delaydetection.cpp b/daemon/src/audio/delaydetection.cpp index 1b6bdb9c8050b1c2398e7b418400d815cedcff4e..23837e0e61604293121a11a50a8973eb3cf6a427 100644 --- a/daemon/src/audio/delaydetection.cpp +++ b/daemon/src/audio/delaydetection.cpp @@ -35,8 +35,9 @@ #include <string.h> #include <samplerate.h> +namespace { // decimation filter coefficient -float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03630817, 0.02944626, +const 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, @@ -50,78 +51,75 @@ std::vector<double> ird(decimationCoefs, decimationCoefs + sizeof(decimationCoef // decimation filter coefficient -float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113, +const 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)); +std::vector<double> irb(bandpassCoefs, bandpassCoefs + sizeof(bandpassCoefs) / sizeof(float)); +} // end anonymous namespace -FirFilter::FirFilter(std::vector<double> ir) : _length(ir.size()), - _impulseResponse(ir), - _count(0) +FirFilter::FirFilter(const std::vector<double> &ir) : length_(ir.size()), + impulseResponse_(ir), + counter_(0) { - memset(_taps, 0, sizeof(double) *MAXFILTERSIZE); + memset(taps_, 0, sizeof(double) * MAXFILTERSIZE); } -FirFilter::~FirFilter() {} - float FirFilter::getOutputSample(float inputSample) { - _taps[_count] = inputSample; + taps_[counter_] = inputSample; double result = 0.0; - int index = _count; + int index = counter_; - for (int i = 0; i < _length; i++) { - result = result + _impulseResponse[i] * _taps[index--]; + for (int i = 0; i < length_; ++i) { + result = result + impulseResponse_[i] * taps_[index--]; if (index < 0) - index = _length-1; + index = length_ - 1; } - _count++; + counter_++; - if (_count >= _length) - _count = 0; + if (counter_ >= length_) + counter_ = 0; return result; } -void FirFilter::reset(void) +void FirFilter::reset() { - 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; + 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); } void DelayDetection::putData(SFLDataFormat *inputData, int nbSamples) { // Machine may already got a spkr and is waiting for mic or computing correlation - if (_nbSpkrSampleStored == WINDOW_SIZE) + if (nbSpkrSampleStored_ == WINDOW_SIZE) return; - if ((_nbSpkrSampleStored + nbSamples) > WINDOW_SIZE) - nbSamples = WINDOW_SIZE - _nbSpkrSampleStored; - + if ((nbSpkrSampleStored_ + nbSamples) > WINDOW_SIZE) + nbSamples = WINDOW_SIZE - nbSpkrSampleStored_; if (nbSamples) { @@ -129,67 +127,58 @@ void DelayDetection::putData(SFLDataFormat *inputData, int nbSamples) float down[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)); + memcpy(spkrReference_ + nbSpkrSampleStored_, tmp, nbSamples * sizeof(float)); - _nbSpkrSampleStored += nbSamples; + downsampleData(tmp, down, nbSamples, downsamplingFactor_); + bandpassFilter(down, nbSamples / downsamplingFactor_); + memcpy(spkrReferenceDown_+ (nbSpkrSampleStored_ / downsamplingFactor_), down, (nbSamples / downsamplingFactor_) * sizeof(float)); + nbSpkrSampleStored_ += nbSamples; } // Update the state - _internalState = WaitForMic; - + internalState_ = WaitForMic; } void DelayDetection::process(SFLDataFormat *inputData, int nbSamples) { - if (_internalState != WaitForMic) + if (internalState_ != WaitForMic) return; - 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]; convertInt16ToFloat32(inputData, tmp, nbSamples); - memcpy(_capturedData+_nbMicSampleStored, tmp, nbSamples); - - downsampleData(tmp, down, nbSamples, _downsamplingFactor); + memcpy(capturedData_ + nbMicSampleStored_, tmp, nbSamples); - memcpy(_captureDataDown+ (_nbMicSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor) *sizeof(float)); + downsampleData(tmp, down, nbSamples, downsamplingFactor_); - _nbMicSampleStored += nbSamples; + memcpy(captureDataDown_ + (nbMicSampleStored_ / downsamplingFactor_), down, (nbSamples / downsamplingFactor_) * sizeof(float)); + nbMicSampleStored_ += nbSamples; } - if (_nbMicSampleStored == DELAY_BUFF_SIZE) - _internalState = ComputeCorrelation; + if (nbMicSampleStored_ == DELAY_BUFF_SIZE) + internalState_ = ComputeCorrelation; else return; - _debug("_spkrDownSize: %d, _micDownSize: %d", _spkrDownSize, _micDownSize); - crossCorrelate(_spkrReferenceDown, _captureDataDown, _correlationResult, _micDownSize, _spkrDownSize); + crossCorrelate(spkrReferenceDown_, captureDataDown_, correlationResult_, micDownSize_, spkrDownSize_); - int maxIndex = getMaxIndex(_correlationResult, _spkrDownSize); - - _debug("MaxIndex: %d", maxIndex); + int maxIndex = getMaxIndex(correlationResult_, spkrDownSize_); } void DelayDetection::crossCorrelate(float *ref, float *seg, float *res, int refSize, int segSize) { - - _debug("CrossCorrelate"); - // Output has same size as the int rsize = refSize; int ssize = segSize; - int tmpsize = segSize-refSize+1; + int tmpsize = segSize - refSize + 1; // perform autocorrelation on reference signal float acref = correlate(ref, ref, rsize); @@ -215,13 +204,13 @@ void DelayDetection::crossCorrelate(float *ref, float *seg, float *res, int refS while (rsize) { acseg = correlate(seg, seg, rsize); - res[ssize-1] = correlate(ref+i, seg, rsize); - r = sqrt(acref*acseg); + res[ssize - 1] = correlate(ref + i, seg, rsize); + r = sqrt(acref * acseg); if (r < 0.0001) - res[ssize-1] = 0.0; + res[ssize - 1] = 0.0; else - res[ssize-1] = res[ssize-1] / r; + res[ssize - 1] = res[ssize-1] / r; --rsize; --ssize; @@ -231,13 +220,12 @@ void DelayDetection::crossCorrelate(float *ref, float *seg, float *res, int refS double DelayDetection::correlate(float *sig1, float *sig2, short size) { - short s = size; double ac = 0.0; while (s--) - ac += sig1[s]*sig2[s]; + ac += sig1[s] * sig2[s]; return ac; } @@ -245,8 +233,7 @@ double DelayDetection::correlate(float *sig1, float *sig2, short size) void DelayDetection::convertInt16ToFloat32(SFLDataFormat *input, float *output, int nbSamples) { - -#define S2F_FACTOR .000030517578125f; + static const float S2F_FACTOR = .000030517578125f; int len = nbSamples; while (len) { @@ -258,10 +245,8 @@ void DelayDetection::convertInt16ToFloat32(SFLDataFormat *input, float *output, void DelayDetection::downsampleData(float *input, float *output, int nbSamples, int factor) { - - int _src_err; - - SRC_STATE *_src_state = src_new(SRC_LINEAR, 1, &_src_err); + int src_err; + SRC_STATE *src_state = src_new(SRC_LINEAR, 1, &src_err); double downfactor = 1.0 / (double) factor; @@ -274,21 +259,20 @@ void DelayDetection::downsampleData(float *input, float *output, int nbSamples, 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) { - 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) { - float max = 0.0; int k = 0; diff --git a/daemon/src/audio/delaydetection.h b/daemon/src/audio/delaydetection.h index dd2adde18a44142cee51a1abe280e14cde8519d0..caa99db8551fc3ad9cb9d57bd2fa5eea6cffcf56 100644 --- a/daemon/src/audio/delaydetection.h +++ b/daemon/src/audio/delaydetection.h @@ -42,61 +42,42 @@ #define MAX_DELAY 150 // Size of internal buffers in samples -#define DELAY_BUFF_SIZE MAX_DELAY*8000/1000 +#define DELAY_BUFF_SIZE MAX_DELAY * 8000 / 1000 #define MAXFILTERSIZE 100 - - class FirFilter { public: - - /** - * Constructor for this class - */ - FirFilter(std::vector<double> ir); - - /** - * SDestructor for this class - */ - ~FirFilter(); - + FirFilter(const std::vector<double> &ir); /** * Perform filtering on one sample */ float getOutputSample(float inputSample); - void reset(void); - + void reset(); private: /** * Length of the filter */ - int _length; + int length_; /** * Coefficient of the filter */ - std::vector<double> _impulseResponse; + std::vector<double> impulseResponse_; /** * Circular buffer */ - double _taps[MAXFILTERSIZE]; - - /** - * Counter - */ - int _count; - + double taps_[MAXFILTERSIZE]; + int counter_; }; class DelayDetection { - public: DelayDetection(); @@ -134,47 +115,47 @@ class DelayDetection { int getMaxIndex(float *data, int size); - State _internalState; + State internalState_; - FirFilter _decimationFilter; + FirFilter decimationFilter_; - FirFilter _bandpassFilter; + FirFilter bandpassFilter_; /** * Segment size in samples for correlation */ - short _segmentSize; + short segmentSize_; - int _downsamplingFactor; + int downsamplingFactor_; /** * Resulting correlation size (s + w -1) */ - short _correlationSize; + short correlationSize_; - float _spkrReference[WINDOW_SIZE*2]; + float spkrReference_[WINDOW_SIZE*2]; - float _capturedData[DELAY_BUFF_SIZE*2]; + float capturedData_[DELAY_BUFF_SIZE*2]; - float _spkrReferenceDown[WINDOW_SIZE*2]; + float spkrReferenceDown_[WINDOW_SIZE*2]; - float _captureDataDown[DELAY_BUFF_SIZE*2]; + float captureDataDown_[DELAY_BUFF_SIZE*2]; - float _spkrReferenceFilter[WINDOW_SIZE*2]; + float spkrReferenceFilter_[WINDOW_SIZE*2]; - float _captureDataFilter[DELAY_BUFF_SIZE*2]; + float captureDataFilter_[DELAY_BUFF_SIZE*2]; - float _correlationResult[DELAY_BUFF_SIZE*2]; + float correlationResult_[DELAY_BUFF_SIZE*2]; - int _remainingIndex; + int remainingIndex_; - int _spkrDownSize; + int spkrDownSize_; - int _micDownSize; + int micDownSize_; - int _nbMicSampleStored; + int nbMicSampleStored_; - int _nbSpkrSampleStored; + int nbSpkrSampleStored_; public: diff --git a/daemon/src/audio/gaincontrol.cpp b/daemon/src/audio/gaincontrol.cpp index 5955d52cba2058f50f63789074bfb5aca824b8c8..f9df37193a72ffc41cb0524f08b53b0a29506fcf 100644 --- a/daemon/src/audio/gaincontrol.cpp +++ b/daemon/src/audio/gaincontrol.cpp @@ -1,7 +1,6 @@ -#include <math.h> -#include <limits.h> +#include <cmath> +#include <climits> #include <fstream> -#include <iostream> #include "global.h" #include "gaincontrol.h" @@ -14,34 +13,18 @@ #define SFL_GAIN_LOGe10 2.30258509299404568402 -// #define DUMP_GAIN_CONTROL_SIGNAL - -GainControl::GainControl(double sr, double target) : averager(sr, SFL_GAIN_ATTACK_TIME, SFL_GAIN_RELEASE_TIME) - , limiter(SFL_GAIN_LIMITER_RATIO, SFL_GAIN_LIMITER_THRESHOLD) - , targetLeveldB(target) - , targetLevelLinear(0.0) - , currentGain(1.0) - , previousGain(0.0) - , maxIncreaseStep(0.0) - , maxDecreaseStep(0.0) +GainControl::GainControl(double sr, double target) : averager_(sr, SFL_GAIN_ATTACK_TIME, SFL_GAIN_RELEASE_TIME) + , limiter_(SFL_GAIN_LIMITER_RATIO, SFL_GAIN_LIMITER_THRESHOLD) + , targetLeveldB_(target) + , targetLevelLinear_(exp(targetLeveldB_ * 0.05 * SFL_GAIN_LOGe10)) + , currentGain_(1.0) + , previousGain_(0.0) + , maxIncreaseStep_(exp(0.11513 * 12. * 160 / 8000)) // Computed on 12 frames (240 ms) + , maxDecreaseStep_(exp(-0.11513 * 40. * 160 / 8000))// Computed on 40 frames (800 ms) { - targetLevelLinear = exp(targetLeveldB * 0.05 * SFL_GAIN_LOGe10); - - maxIncreaseStep = exp(0.11513 * 12. * 160 / 8000); // Computed on 12 frames (240 ms) - maxDecreaseStep = exp(-0.11513 * 40. * 160 / 8000); // Computed on 40 frames (800 ms) - - _debug("GainControl: Target gain %f dB (%f linear)", targetLeveldB, targetLevelLinear); - + _debug("GainControl: Target gain %f dB (%f linear)", targetLeveldB_, targetLevelLinear_); } -GainControl::~GainControl() {} - -#ifdef DUMP_GAIN_CONTROL_SIGNAL -std::fstream tmpRms("gaintestrms.raw", std::fstream::out); -std::fstream tmpIn("gaintestin.raw", std::fstream::out); -std::fstream tmpOut("gaintestout.raw", std::fstream::out); -#endif - void GainControl::process(SFLDataFormat *buf, int samples) { double rms, rmsAvgLevel, in, out, diffRms, maxRms; @@ -52,82 +35,56 @@ void GainControl::process(SFLDataFormat *buf, int samples) // linear conversion in = (double)buf[i] / (double)SHRT_MAX; - out = currentGain * in; - - rms = detector.getRms(out); - rmsAvgLevel = sqrt(averager.getAverage(rms)); + out = currentGain_ * in; -#ifdef DUMP_GAIN_CONTROL_SIGNAL - tmpRms.write(reinterpret_cast<char *>(&rmsAvgLevel), sizeof(double)); - tmpIn.write(reinterpret_cast<char *>(&in), sizeof(double)); -#endif + rms = out * out; + rmsAvgLevel = sqrt(averager_.getAverage(rms)); - if (rmsAvgLevel > maxRms) { + if (rmsAvgLevel > maxRms) maxRms = rmsAvgLevel; - } - - out = limiter.limit(out); -#ifdef DUMP_GAIN_CONTROL_SIGNAL - tmpOut.write(reinterpret_cast<char *>(&out), sizeof(double)); -#endif + out = limiter_.limit(out); buf[i] = (short)(out * (double)SHRT_MAX); } - diffRms = maxRms - targetLevelLinear; - - if ((diffRms > 0.0) && (maxRms > 0.1)) { - currentGain *= maxDecreaseStep; - } else if ((diffRms <= 0.0) && (maxRms > 0.1)) { - currentGain *= maxIncreaseStep; - } else if (maxRms <= 0.1) { - currentGain = 1.0; - } + diffRms = maxRms - targetLevelLinear_; - currentGain = 0.5 * (currentGain + previousGain); + if ((diffRms > 0.0) && (maxRms > 0.1)) + currentGain_ *= maxDecreaseStep_; + else if ((diffRms <= 0.0) && (maxRms > 0.1)) + currentGain_ *= maxIncreaseStep_; + else if (maxRms <= 0.1) + currentGain_ = 1.0; - previousGain = currentGain; + currentGain_ = 0.5 * (currentGain_ + previousGain_); - // _debug("GainControl: current gain: %f, target gain: %f, rmsAvgLevel %f, target level %f", - // currentGain, gainTargetLevel, rmsAvgLevel, targetLevelLinear); -} - -GainControl::RmsDetection::RmsDetection() {} - -double GainControl::RmsDetection::getRms(double in) -{ - return in * in; + previousGain_ = currentGain_; } GainControl::DetectionAverage::DetectionAverage(double sr, double ta, double tr) : - g_a(0.0), teta_a(ta), g_r(0.0), teta_r(tr), samplingRate(sr), previous_y(0.0) + g_a_(0.0), teta_a_(ta), g_r_(0.0), teta_r_(tr), samplingRate_(sr), previous_y_(0.0) { - g_a = exp(-1.0 / (samplingRate * (teta_a / 1000.0))); - g_r = exp(-1.0 / (samplingRate * (teta_r / 1000.0))); + g_a_ = exp(-1.0 / (samplingRate_ * (teta_a_ / 1000.0))); + g_r_ = exp(-1.0 / (samplingRate_ * (teta_r_ / 1000.0))); } double GainControl::DetectionAverage::getAverage(double in) { - if (in > previous_y) { - previous_y = ((1.0 - g_a) * in) + (g_a * previous_y); - } else { - previous_y = ((1.0 - g_r) * in) + (g_r * previous_y); - } - - return previous_y; + if (in > previous_y_) + previous_y_ = ((1.0 - g_a_) * in) + (g_a_ * previous_y_); + else + previous_y_ = ((1.0 - g_r_) * in) + (g_r_ * previous_y_); + return previous_y_; } -GainControl::Limiter::Limiter(double r, double thresh) : ratio(r), threshold(thresh) -{ -} +GainControl::Limiter::Limiter(double r, double thresh) : ratio_(r), threshold_(thresh) +{} double GainControl::Limiter::limit(double in) { - double out; - - out = (in > threshold ? (ratio * (in - threshold)) + threshold : - in < -threshold ? (ratio * (in + threshold)) - threshold : in); + double out = (in > threshold_ ? (ratio_ * (in - threshold_)) + threshold_ : + in < -threshold_ ? (ratio_ * (in + threshold_)) - threshold_ : in); return out; } diff --git a/daemon/src/audio/gaincontrol.h b/daemon/src/audio/gaincontrol.h index d0455368a8ac6406377387f93cf0e8e6e2b2ee33..e8f0ecd685103c14d4232805d7f17b2cf79ebec7 100644 --- a/daemon/src/audio/gaincontrol.h +++ b/daemon/src/audio/gaincontrol.h @@ -3,8 +3,6 @@ #include "global.h" -#define SFL_GAIN_BUFFER_LENGTH 160 - class GainControl { public: @@ -15,11 +13,6 @@ class GainControl { */ GainControl(double, double); - /** - * Destructor for this class - */ - ~GainControl(void); - /** * Apply addaptive gain factor on input signal * /param Input audio buffer @@ -28,25 +21,6 @@ class GainControl { void process(SFLDataFormat *, int samples); private: - - /** - * Rms detector - */ - class RmsDetection { - public: - /** - * Constructor for this class - */ - RmsDetection(void); - - /** - * Get rms value - * /param Audio sample - */ - double getRms(double); - - }; - class DetectionAverage { public: /** @@ -66,32 +40,32 @@ class GainControl { /** * Average factor for attack */ - double g_a; + double g_a_; /** * Attack ramp time (in ms) */ - double teta_a; + double teta_a_; /** * Average factor for release */ - double g_r; + double g_r_; /** * Release ramp time (in ms) */ - double teta_r; + double teta_r_; /** * Samplig rate */ - double samplingRate; + double samplingRate_; /** * Previous gain (first order memory) */ - double previous_y; + double previous_y_; }; class Limiter { @@ -109,54 +83,49 @@ class GainControl { double limit(double); private: - double ratio; - double threshold; + double ratio_; + double threshold_; }; - /** - * Current audio level detection - */ - RmsDetection detector; - /** * First order mean filter */ - DetectionAverage averager; + DetectionAverage averager_; /** * Post processing compression */ - Limiter limiter; + Limiter limiter_; /** * Target audio level in dB */ - double targetLeveldB; + double targetLeveldB_; /** * Target audio level in linear scale */ - double targetLevelLinear; + double targetLevelLinear_; /** * Current gain */ - double currentGain; + double currentGain_; /** * Previou gain for smoothing */ - double previousGain; + double previousGain_; /** * Maximum incrementation stop of current gain */ - double maxIncreaseStep; + double maxIncreaseStep_; /** * Maximum decrease step */ - double maxDecreaseStep; + double maxDecreaseStep_; }; diff --git a/daemon/src/audio/pulseaudio/audiostream.cpp b/daemon/src/audio/pulseaudio/audiostream.cpp index 316e2a92e82c6ad5d578ad353a80e6f97fb7b99f..530784d291d90f1d3d32c837e0aa7fe867d5ce9a 100644 --- a/daemon/src/audio/pulseaudio/audiostream.cpp +++ b/daemon/src/audio/pulseaudio/audiostream.cpp @@ -32,7 +32,7 @@ #include "pulselayer.h" AudioStream::AudioStream(pa_context *c, pa_threaded_mainloop *m, const char *desc, int type, int smplrate, std::string *deviceName) - : _mainloop(m) + : mainloop_(m) { static const pa_channel_map channel_map = { 1, @@ -48,9 +48,9 @@ AudioStream::AudioStream(pa_context *c, pa_threaded_mainloop *m, const char *des assert(pa_sample_spec_valid(&sample_spec)); assert(pa_channel_map_valid(&channel_map)); - _audiostream = pa_stream_new(c, desc, &sample_spec, &channel_map); + audiostream_ = pa_stream_new(c, desc, &sample_spec, &channel_map); - if (!_audiostream) { + if (!audiostream_) { _error("Pulse: %s: pa_stream_new() failed : %s" , desc, pa_strerror(pa_context_errno(c))); throw std::runtime_error("Pulse : could not create stream\n"); } @@ -64,33 +64,33 @@ AudioStream::AudioStream(pa_context *c, pa_threaded_mainloop *m, const char *des const char *name = deviceName ? deviceName->c_str() : NULL; - pa_threaded_mainloop_lock(_mainloop); + pa_threaded_mainloop_lock(mainloop_); if (type == PLAYBACK_STREAM || type == RINGTONE_STREAM) - pa_stream_connect_playback(_audiostream , name, &attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); + pa_stream_connect_playback(audiostream_, name, &attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); else if (type == CAPTURE_STREAM) - pa_stream_connect_record(_audiostream, name, &attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); + pa_stream_connect_record(audiostream_, name, &attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); - pa_threaded_mainloop_unlock(_mainloop); + pa_threaded_mainloop_unlock(mainloop_); - pa_stream_set_state_callback(_audiostream , stream_state_callback, NULL); + pa_stream_set_state_callback(audiostream_, stream_state_callback, NULL); } AudioStream::~AudioStream() { - pa_threaded_mainloop_lock(_mainloop); + pa_threaded_mainloop_lock(mainloop_); - pa_stream_disconnect(_audiostream); + pa_stream_disconnect(audiostream_); // make sure we don't get any further callback - pa_stream_set_state_callback(_audiostream, NULL, NULL); - pa_stream_set_write_callback(_audiostream, NULL, NULL); - pa_stream_set_underflow_callback(_audiostream, NULL, NULL); - pa_stream_set_overflow_callback(_audiostream, NULL, NULL); + pa_stream_set_state_callback(audiostream_, NULL, NULL); + pa_stream_set_write_callback(audiostream_, NULL, NULL); + pa_stream_set_underflow_callback(audiostream_, NULL, NULL); + pa_stream_set_overflow_callback(audiostream_, NULL, NULL); - pa_stream_unref(_audiostream); + pa_stream_unref(audiostream_); - pa_threaded_mainloop_unlock(_mainloop); + pa_threaded_mainloop_unlock(mainloop_); } void @@ -99,7 +99,6 @@ AudioStream::stream_state_callback(pa_stream* s, void* user_data UNUSED) char str[PA_SAMPLE_SPEC_SNPRINT_MAX]; switch (pa_stream_get_state(s)) { - case PA_STREAM_CREATING: _info("Pulse: Stream is creating..."); break; @@ -129,10 +128,10 @@ AudioStream::stream_state_callback(pa_stream* s, void* user_data UNUSED) } } -bool AudioStream::isReady(void) +bool AudioStream::isReady() { - if (!_audiostream) + if (!audiostream_) return false; - return pa_stream_get_state(_audiostream) == PA_STREAM_READY; + return pa_stream_get_state(audiostream_) == PA_STREAM_READY; } diff --git a/daemon/src/audio/pulseaudio/audiostream.h b/daemon/src/audio/pulseaudio/audiostream.h index bacfc6f9baac6c67c15468235d2365c6657e815f..7e67db5fc305f6d83b2d47511bc8a2fd4ed353c2 100644 --- a/daemon/src/audio/pulseaudio/audiostream.h +++ b/daemon/src/audio/pulseaudio/audiostream.h @@ -63,10 +63,10 @@ class AudioStream { * @return pa_stream* The stream */ pa_stream* pulseStream() { - return _audiostream; + return audiostream_; } - bool isReady(void); + bool isReady(); private: @@ -84,12 +84,12 @@ class AudioStream { /** * The pulse audio object */ - pa_stream* _audiostream; + pa_stream* audiostream_; /** * A pointer to the opaque threaded main loop object */ - pa_threaded_mainloop * _mainloop; + pa_threaded_mainloop * mainloop_; }; #endif // _AUDIO_STREAM_H diff --git a/daemon/src/audio/pulseaudio/pulselayer.cpp b/daemon/src/audio/pulseaudio/pulselayer.cpp index db5d35008f2194623c0e702503d31504f099e9b3..bbfb3fbbe0d374ee164ba9840152a24dca518701 100644 --- a/daemon/src/audio/pulseaudio/pulselayer.cpp +++ b/daemon/src/audio/pulseaudio/pulselayer.cpp @@ -231,7 +231,7 @@ PulseLayer::PulseLayer() isStarted_ = true; } -PulseLayer::~PulseLayer(void) +PulseLayer::~PulseLayer() { disconnectAudioStream(); @@ -287,13 +287,13 @@ void PulseLayer::context_state_callback(pa_context* c, void* user_data) } -void PulseLayer::updateSinkList(void) +void PulseLayer::updateSinkList() { getSinkList()->clear(); pa_context_get_sink_info_list(context_, sink_input_info_callback, this); } -void PulseLayer::updateSourceList(void) +void PulseLayer::updateSourceList() { getSourceList()->clear(); pa_context_get_source_info_list(context_, source_input_info_callback, this); @@ -345,7 +345,7 @@ void PulseLayer::createStreams(pa_context* c) } -void PulseLayer::disconnectAudioStream(void) +void PulseLayer::disconnectAudioStream() { if (playback_) { if (playback_->pulseStream()) { @@ -384,7 +384,7 @@ void PulseLayer::disconnectAudioStream(void) } } -void PulseLayer::startStream(void) +void PulseLayer::startStream() { // Create Streams if (!playback_ or !record_) @@ -398,7 +398,7 @@ void PulseLayer::startStream(void) void -PulseLayer::stopStream(void) +PulseLayer::stopStream() { pa_threaded_mainloop_lock(mainloop_); @@ -413,7 +413,7 @@ PulseLayer::stopStream(void) disconnectAudioStream(); } -void PulseLayer::writeToSpeaker(void) +void PulseLayer::writeToSpeaker() { if (!playback_ or !playback_->isReady()) return; @@ -505,7 +505,7 @@ void PulseLayer::writeToSpeaker(void) pa_stream_write(s, data, inBytes, NULL, 0, PA_SEEK_RELATIVE); } -void PulseLayer::readFromMic(void) +void PulseLayer::readFromMic() { if (!record_ or !record_->isReady()) return; @@ -545,7 +545,7 @@ void PulseLayer::readFromMic(void) } -void PulseLayer::ringtoneToSpeaker(void) +void PulseLayer::ringtoneToSpeaker() { if (!ringtone_ or !ringtone_->isReady()) return; diff --git a/daemon/src/audio/pulseaudio/pulselayer.h b/daemon/src/audio/pulseaudio/pulselayer.h index 7e078bde878eb6bd84ac898099391aae2fd32619..a57fe30a390d23a08f67dca8bc28ec2f83521f3e 100644 --- a/daemon/src/audio/pulseaudio/pulselayer.h +++ b/daemon/src/audio/pulseaudio/pulselayer.h @@ -44,35 +44,35 @@ class AudioStream; class PulseLayer : public AudioLayer { public: PulseLayer(); - ~PulseLayer(void); + ~PulseLayer(); - std::list<std::string>* getSinkList(void) { + std::list<std::string>* getSinkList() { return &sinkList_; } - std::list<std::string>* getSourceList(void) { + std::list<std::string>* getSourceList() { return &sourceList_; } /** * Write data from the ring buffer to the harware and read data from the hardware */ - void readFromMic(void); - void writeToSpeaker(void); - void ringtoneToSpeaker(void); + void readFromMic(); + void writeToSpeaker(); + void ringtoneToSpeaker(); - void updateSinkList(void); + void updateSinkList(); - void updateSourceList(void); + void updateSourceList(); bool inSinkList(const std::string &deviceName) const; bool inSourceList(const std::string &deviceName) const; - void startStream(void); + void startStream(); - void stopStream(void); + void stopStream(); static void context_state_callback(pa_context* c, void* user_data); @@ -92,7 +92,7 @@ class PulseLayer : public AudioLayer { /** * Close the connection with the local pulseaudio server */ - void disconnectAudioStream(void); + void disconnectAudioStream(); /** PulseAudio context and asynchronous loop */ pa_context* context_; diff --git a/daemon/src/audio/recordable.cpp b/daemon/src/audio/recordable.cpp index ca4813cede78d2f1365669ecfc1877bce1645776..4b9ea8f41bdeeb2ad900ad5e1a5d291813faccd6 100644 --- a/daemon/src/audio/recordable.cpp +++ b/daemon/src/audio/recordable.cpp @@ -32,21 +32,15 @@ Recordable::Recordable() : recorder(&recAudio, Manager::instance().getMainBuffer()) { - _debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Recordable Constructor -=-=-=-=-=-=-=-=-=--=-=-=-"); recAudio.setRecordingOption(AudioRecord::FILE_WAV, 8000, Manager::instance().audioPreference.getRecordpath()); } - Recordable::~Recordable() { - _debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Recordable Destructor -=-=-=-=-=-=-=-=-=-=-=-=-=-"); - - if (recAudio.isOpenFile()) { + if (recAudio.isOpenFile()) recAudio.closeFile(); - } } - void Recordable::initRecFileName(std::string filename) { recAudio.initFileName(filename); @@ -66,5 +60,3 @@ int Recordable::getRecordingSmplRate() const { return recAudio.getSndSamplingRate(); } - - diff --git a/daemon/src/audio/recordable.h b/daemon/src/audio/recordable.h index efbb411e54b99f49bf20a26c21aaaf86f12fc958..3e900a2f479dbc0dfb868b62befa7c656b720c2e 100644 --- a/daemon/src/audio/recordable.h +++ b/daemon/src/audio/recordable.h @@ -57,7 +57,7 @@ class Recordable { /** * Stop recording */ - void stopRecording(void) { + void stopRecording() { recAudio.stopRecording(); } @@ -69,7 +69,7 @@ class Recordable { /** * Return the file path for this recording */ - std::string getFileName(void); + std::string getFileName(); /** * Set recording sampling rate. @@ -79,7 +79,7 @@ class Recordable { /** * Return the recording sampling rate */ - int getRecordingSmplRate(void) const; + int getRecordingSmplRate() const; /** * Virtual method to be implemented in order to the main diff --git a/daemon/src/audio/sound/audiofile.cpp b/daemon/src/audio/sound/audiofile.cpp index dcf6d911422d30f844479cbb0036151b95e0d8f9..11c9172a8417760692572746c6db173a64dcff48 100644 --- a/daemon/src/audio/sound/audiofile.cpp +++ b/daemon/src/audio/sound/audiofile.cpp @@ -44,7 +44,7 @@ #include "manager.h" RawFile::RawFile(const std::string& name, sfl::AudioCodec* codec, unsigned int sampleRate) - : audioCodec(codec) + : audioCodec_(codec) { filepath_ = name; @@ -66,9 +66,9 @@ RawFile::RawFile(const std::string& name, sfl::AudioCodec* codec, unsigned int s file.read(fileBuffer,length); file.close(); - unsigned int frameSize = audioCodec->getFrameSize(); - unsigned int bitrate = audioCodec->getBitRate() * 1000 / 8; - unsigned int audioRate = audioCodec->getClockRate(); + unsigned int frameSize = audioCodec_->getFrameSize(); + unsigned int bitrate = audioCodec_->getBitRate() * 1000 / 8; + unsigned int audioRate = audioCodec_->getClockRate(); unsigned int encFrameSize = frameSize * bitrate / audioRate; unsigned int decodedSize = length * (frameSize / encFrameSize); @@ -78,7 +78,7 @@ RawFile::RawFile(const std::string& name, sfl::AudioCodec* codec, unsigned int s size_ = decodedSize; while (length >= encFrameSize) { - bufpos += audioCodec->decode(bufpos, filepos, encFrameSize); + bufpos += audioCodec_->decode(bufpos, filepos, encFrameSize); filepos += encFrameSize; length -= encFrameSize; } diff --git a/daemon/src/audio/sound/audiofile.h b/daemon/src/audio/sound/audiofile.h index 1a6d2ff182a5b3c45bb31ec53d3d6a28e8223a9f..27cd35672b0342182d93aeac1b61da18b86577c6 100644 --- a/daemon/src/audio/sound/audiofile.h +++ b/daemon/src/audio/sound/audiofile.h @@ -35,8 +35,6 @@ #define __AUDIOFILE_H__ #include <stdexcept> -#include <fstream> - #include "audio/audioloop.h" namespace sfl { @@ -45,7 +43,7 @@ class AudioCodec; class AudioFileException : public std::runtime_error { public: - AudioFileException(const std::string& str="") : + AudioFileException(const std::string& str = "") : std::runtime_error("AudioFile: AudioFileException occured: " + str) {} }; @@ -54,7 +52,7 @@ class AudioFileException : public std::runtime_error { */ class AudioFile : public AudioLoop { public: - std::string getFilePath(void) const { + std::string getFilePath() const { return filepath_; } @@ -63,13 +61,6 @@ class AudioFile : public AudioLoop { std::string filepath_; }; - - -/** - * @file audiofile.h - * @brief A class to manage sound files - */ - class RawFile : public AudioFile { public: /** @@ -78,24 +69,21 @@ class RawFile : public AudioFile { RawFile(const std::string& name, sfl::AudioCodec* codec, unsigned int sampleRate = 8000); private: - // Copy Constructor + // noncopyable RawFile(const RawFile& rh); - - // Assignment Operator - const RawFile& operator= (const RawFile& rh); + RawFile& operator= (const RawFile& rh); /** Your preferred codec */ - sfl::AudioCodec* audioCodec; + sfl::AudioCodec* audioCodec_; }; class WaveFile : public AudioFile { - public: /** * Load a sound file in memory - * @param filename The absolute path to the file - * @param sampleRate The sample rate to read it - */ + * @param filename The absolute path to the file + * @param sampleRate The sample rate to read it + */ WaveFile(const std::string&, unsigned int); }; diff --git a/daemon/src/audio/sound/dtmf.cpp b/daemon/src/audio/sound/dtmf.cpp index 015eaa6a48c40fc885a26fbf9c635d012bfcbc44..914e616efcec7c2ade4e7c500b860069931ef576 100644 --- a/daemon/src/audio/sound/dtmf.cpp +++ b/daemon/src/audio/sound/dtmf.cpp @@ -35,54 +35,47 @@ #include "dtmf.h" DTMF::DTMF(unsigned int sampleRate) - : currentTone(0), newTone(0), dtmfgenerator(sampleRate) -{ -} + : currentTone_(0), newTone_(0), dtmfgenerator_(sampleRate) +{} -DTMF::~DTMF(void) +void DTMF::startTone(char code) { + newTone_ = code; } -void -DTMF::startTone(char code) -{ - newTone = code; -} - -bool -DTMF::generateDTMF(SFLDataFormat* buffer, size_t n) +bool DTMF::generateDTMF(SFLDataFormat* buffer, size_t n) { if (!buffer) return false; try { - if (currentTone != 0) { + if (currentTone_ != 0) { // Currently generating a DTMF tone - if (currentTone == newTone) { + if (currentTone_ == newTone_) { // Continue generating the same tone - dtmfgenerator.getNextSamples(buffer, n); + dtmfgenerator_.getNextSamples(buffer, n); return true; - } else if (newTone != 0) { + } else if (newTone_ != 0) { // New tone requested - dtmfgenerator.getSamples(buffer, n, newTone); - currentTone = newTone; + dtmfgenerator_.getSamples(buffer, n, newTone_); + currentTone_ = newTone_; return true; } else { // Stop requested - currentTone = newTone; + currentTone_ = newTone_; return false; } } else { // Not generating any DTMF tone - if (newTone) { + if (newTone_) { // Requested to generate a DTMF tone - dtmfgenerator.getSamples(buffer, n, newTone); - currentTone = newTone; + dtmfgenerator_.getSamples(buffer, n, newTone_); + currentTone_ = newTone_; return true; } - - return false; + else + return false; } - } catch (DTMFException e) { + } catch (const DTMFException &e) { // invalid key return false; } diff --git a/daemon/src/audio/sound/dtmf.h b/daemon/src/audio/sound/dtmf.h index 2be2c49f1cad12e0837ca234e6b1385f0dcb74dd..90b17715b82eaee2cc7c0fd636497e7543f78c47 100644 --- a/daemon/src/audio/sound/dtmf.h +++ b/daemon/src/audio/sound/dtmf.h @@ -50,11 +50,6 @@ class DTMF { */ DTMF(unsigned int sampleRate); - /** - * Destructor - */ - ~DTMF(void); - /** * Start the done for th given dtmf * @param code The DTMF code @@ -68,10 +63,11 @@ class DTMF { */ bool generateDTMF(SFLDataFormat* buffer, size_t n); - char currentTone; - char newTone; + private: + char currentTone_; + char newTone_; - DTMFGenerator dtmfgenerator; + DTMFGenerator dtmfgenerator_; }; #endif // __KEY_DTMF_H_ diff --git a/daemon/src/audio/sound/tone.h b/daemon/src/audio/sound/tone.h index 5d82b2c465d0b5b3435d0b65e6d6e027e2494a2a..be9c6c0cbe270308fb924cf45c4d3ceabac2755f 100644 --- a/daemon/src/audio/sound/tone.h +++ b/daemon/src/audio/sound/tone.h @@ -71,7 +71,7 @@ class Tone : public AudioLoop { /** * */ - void fillWavetable(void); + void fillWavetable(); /** * diff --git a/daemon/src/audio/sound/tonelist.cpp b/daemon/src/audio/sound/tonelist.cpp index b529c2452e760945d4c4d13b2b0dd409a5602017..4878db4db427d7d8ea3d27abb4e6c641d3386957 100644 --- a/daemon/src/audio/sound/tonelist.cpp +++ b/daemon/src/audio/sound/tonelist.cpp @@ -88,54 +88,47 @@ static const char *toneZone[TelephoneTone::ZID_COUNTRIES][Tone::TONE_NULL] = { TelephoneTone::COUNTRYID TelephoneTone::getCountryId(const std::string& countryName) { - if (countryName == "North America") return ZID_NORTH_AMERICA; - - if (countryName == "France") return ZID_FRANCE; - - if (countryName == "Australia") return ZID_AUSTRALIA; - - if (countryName == "United Kingdom") return ZID_UNITED_KINGDOM; - - if (countryName == "Spain") return ZID_SPAIN; - - if (countryName == "Italy") return ZID_ITALY; - - if (countryName == "Japan") return ZID_JAPAN; - - return ZID_NORTH_AMERICA; // default + if (countryName == "North America") return ZID_NORTH_AMERICA; + else if (countryName == "France") return ZID_FRANCE; + else if (countryName == "Australia") return ZID_AUSTRALIA; + else if (countryName == "United Kingdom") return ZID_UNITED_KINGDOM; + else if (countryName == "Spain") return ZID_SPAIN; + else if (countryName == "Italy") return ZID_ITALY; + else if (countryName == "Japan") return ZID_JAPAN; + else return ZID_NORTH_AMERICA; // default } TelephoneTone::TelephoneTone(const std::string& countryName, unsigned int sampleRate) : - _currentTone(Tone::TONE_NULL) + currentTone_(Tone::TONE_NULL) { TelephoneTone::COUNTRYID countryId = getCountryId(countryName); - _tone[Tone::TONE_DIALTONE] = new Tone(toneZone[countryId][Tone::TONE_DIALTONE], sampleRate); - _tone[Tone::TONE_BUSY] = new Tone(toneZone[countryId][Tone::TONE_BUSY], sampleRate); - _tone[Tone::TONE_RINGTONE] = new Tone(toneZone[countryId][Tone::TONE_RINGTONE], sampleRate); - _tone[Tone::TONE_CONGESTION] = new Tone(toneZone[countryId][Tone::TONE_CONGESTION], sampleRate); + tone_[Tone::TONE_DIALTONE] = new Tone(toneZone[countryId][Tone::TONE_DIALTONE], sampleRate); + tone_[Tone::TONE_BUSY] = new Tone(toneZone[countryId][Tone::TONE_BUSY], sampleRate); + tone_[Tone::TONE_RINGTONE] = new Tone(toneZone[countryId][Tone::TONE_RINGTONE], sampleRate); + tone_[Tone::TONE_CONGESTION] = new Tone(toneZone[countryId][Tone::TONE_CONGESTION], sampleRate); } TelephoneTone::~TelephoneTone() { for (size_t i=0; i < Tone::TONE_NULL; i++) - delete _tone[i]; + delete tone_[i]; } void TelephoneTone::setCurrentTone(Tone::TONEID toneId) { - if (toneId != Tone::TONE_NULL && _currentTone != toneId) - _tone[toneId]->reset(); + if (toneId != Tone::TONE_NULL && currentTone_ != toneId) + tone_[toneId]->reset(); - _currentTone = toneId; + currentTone_ = toneId; } Tone* TelephoneTone::getCurrentTone() { - if (_currentTone == Tone::TONE_NULL) + if (currentTone_ == Tone::TONE_NULL) return NULL; - return _tone[_currentTone]; + return tone_[currentTone_]; } diff --git a/daemon/src/audio/sound/tonelist.h b/daemon/src/audio/sound/tonelist.h index 8df0c4cc02f7f37e7ed7ee8a985e6fe12368a2ec..5c43b6ab52b196009f637e496291c96f36606368 100644 --- a/daemon/src/audio/sound/tonelist.h +++ b/daemon/src/audio/sound/tonelist.h @@ -39,7 +39,6 @@ class TelephoneTone { public: - /** Countries */ enum COUNTRYID { ZID_NORTH_AMERICA = 0, @@ -61,14 +60,13 @@ class TelephoneTone { private: // Copy Constructor TelephoneTone(const TelephoneTone& rh); - // Assignment Operator TelephoneTone& operator= (const TelephoneTone& rh); static COUNTRYID getCountryId(const std::string& countryName); - Tone* _tone[Tone::TONE_NULL]; - Tone::TONEID _currentTone; + Tone* tone_[Tone::TONE_NULL]; + Tone::TONEID currentTone_; }; #endif diff --git a/daemon/src/config/yamlnode.h b/daemon/src/config/yamlnode.h index 5d2ae0a16ceaf44d9a5cd8f1e72edb0300a0a4f9..a183ebe04dbb9863b882e3fa2234fcb1101a38c0 100644 --- a/daemon/src/config/yamlnode.h +++ b/daemon/src/config/yamlnode.h @@ -38,7 +38,6 @@ namespace Conf { - class YamlNode; typedef std::list<YamlNode *> Sequence; @@ -47,87 +46,67 @@ typedef std::map<std::string, YamlNode *> Mapping; enum NodeType { DOCUMENT, SCALAR, MAPPING, SEQUENCE }; class YamlNode { - public: YamlNode(NodeType t, YamlNode *top=NULL) : type(t), topNode(top) {} - virtual ~YamlNode(void) {} + virtual ~YamlNode() {} - NodeType getType(void) { + NodeType getType() { return type; } - YamlNode *getTopNode(void) { + YamlNode *getTopNode() { return topNode; } - virtual void deleteChildNodes(void) = 0; + virtual void deleteChildNodes() = 0; private: - NodeType type; - YamlNode *topNode; - }; class YamlDocument : YamlNode { - public: - YamlDocument(YamlNode* top=NULL) : YamlNode(DOCUMENT, top) {} - ~YamlDocument() {} - void addNode(YamlNode *node); - YamlNode *popNode(void); + YamlNode *popNode(); - Sequence *getSequence(void) { + Sequence *getSequence() { return &doc; } - virtual void deleteChildNodes(void); + virtual void deleteChildNodes(); private: - Sequence doc; - }; class SequenceNode : public YamlNode { - public: - SequenceNode(YamlNode *top) : YamlNode(SEQUENCE, top) {} - ~SequenceNode() {} - Sequence *getSequence() { return &seq; } void addNode(YamlNode *node); - virtual void deleteChildNodes(void); + virtual void deleteChildNodes(); private: - Sequence seq; - }; class MappingNode : public YamlNode { - public: - MappingNode(YamlNode *top) : YamlNode(MAPPING, top) {} - ~MappingNode() {} - Mapping *getMapping() { return ↦ } @@ -147,26 +126,18 @@ class MappingNode : public YamlNode { void getValue(const std::string &key, int *i); void getValue(const std::string &key, std::string *s); - virtual void deleteChildNodes(void); + virtual void deleteChildNodes(); private: - Mapping map; - std::string tmpKey; - }; - class ScalarNode : public YamlNode { - public: - ScalarNode(std::string s="", YamlNode *top=NULL) : YamlNode(SCALAR, top), str(s) {} ScalarNode(bool b, YamlNode *top=NULL) : YamlNode(SCALAR, top), str(b ? "true" : "false") {} - ~ScalarNode() {} - const std::string &getValue() { return str; } @@ -175,17 +146,13 @@ class ScalarNode : public YamlNode { str = s; } - virtual void deleteChildNodes(void) {} + virtual void deleteChildNodes() {} private: - std::string str; - }; - } - - #endif + diff --git a/daemon/src/config/yamlparser.cpp b/daemon/src/config/yamlparser.cpp index 008c8919c9ed3284e4a586aab845a468b06d9062..166abd1b94577f8ae9307b36645411cb1d0ac2ee 100644 --- a/daemon/src/config/yamlparser.cpp +++ b/daemon/src/config/yamlparser.cpp @@ -77,14 +77,13 @@ YamlParser::~YamlParser() } } -void YamlParser::serializeEvents() throw(YamlParserException) +void YamlParser::serializeEvents() { bool done = false; yaml_event_t event, copiedEvent; try { - - while (!done) { + while (not done) { if (!yaml_parser_parse(&parser, &event)) throw YamlParserException("Error while parsing"); @@ -99,30 +98,27 @@ void YamlParser::serializeEvents() throw(YamlParserException) yaml_event_delete(&event); } - } catch (YamlParserException &e) { + } catch (const YamlParserException &e) { throw; } } -void YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) throw(YamlParserException) +void YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) { - switch (event_from->type) { case YAML_STREAM_START_EVENT: { if (yaml_stream_start_event_initialize(event_to, - event_from->data.stream_start.encoding) == 0) { + event_from->data.stream_start.encoding) == 0) throw YamlParserException("Error stream start event"); - } break; } case YAML_STREAM_END_EVENT: { - if (yaml_stream_end_event_initialize(event_to) == 0) { + if (yaml_stream_end_event_initialize(event_to) == 0) throw YamlParserException("Error stream end event"); - } break; } @@ -132,26 +128,23 @@ void YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) thr 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) == 0) { + event_from->data.document_start.implicit) == 0) throw YamlParserException("Error document start event"); - } break; } case YAML_DOCUMENT_END_EVENT: { if (yaml_document_end_event_initialize(event_to, - event_from->data.document_end.implicit) == 0) { + event_from->data.document_end.implicit) == 0) throw YamlParserException("Error document end event"); - } break; } case YAML_ALIAS_EVENT: { if (yaml_alias_event_initialize(event_to, - event_from->data.alias.anchor) == 0) { + event_from->data.alias.anchor) == 0) throw YamlParserException("Error alias event initialize"); - } break; } @@ -163,9 +156,8 @@ void YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) thr event_from->data.scalar.length, event_from->data.scalar.plain_implicit, event_from->data.scalar.quoted_implicit, - event_from->data.scalar.style) == 0) { + event_from->data.scalar.style) == 0) throw YamlParserException("Error scalar event initialize"); - } break; } @@ -174,16 +166,14 @@ void YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) thr event_from->data.sequence_start.anchor, event_from->data.sequence_start.tag, event_from->data.sequence_start.implicit, - event_from->data.sequence_start.style) == 0) { + event_from->data.sequence_start.style) == 0) throw YamlParserException("Error sequence start event"); - } break; } case YAML_SEQUENCE_END_EVENT: { - if (yaml_sequence_end_event_initialize(event_to) == 0) { + if (yaml_sequence_end_event_initialize(event_to) == 0) throw YamlParserException("Error sequence end event"); - } break; } @@ -192,16 +182,13 @@ void YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) thr event_from->data.mapping_start.anchor, event_from->data.mapping_start.tag, event_from->data.mapping_start.implicit, - event_from->data.mapping_start.style) == 0) { + event_from->data.mapping_start.style) == 0) throw YamlParserException("Error mapping start event"); - } - break; } case YAML_MAPPING_END_EVENT: { - if (yaml_mapping_end_event_initialize(event_to) == 0) { + if (yaml_mapping_end_event_initialize(event_to) == 0) throw YamlParserException("Error mapping end event"); - } break; } @@ -211,7 +198,7 @@ void YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) thr } -YamlDocument *YamlParser::composeEvents() throw(YamlParserException) +YamlDocument *YamlParser::composeEvents() { try { if (eventNumber == 0) @@ -223,7 +210,7 @@ YamlDocument *YamlParser::composeEvents() throw(YamlParserException) eventIndex = 0; processStream(); - } catch (YamlParserException &e) { + } catch (const YamlParserException &e) { throw; } @@ -231,7 +218,7 @@ YamlDocument *YamlParser::composeEvents() throw(YamlParserException) return doc; } -void YamlParser::processStream() throw(YamlParserException) +void YamlParser::processStream() { try { while ((eventIndex < eventNumber) && (events[eventIndex].type != YAML_STREAM_END_EVENT)) { @@ -244,12 +231,12 @@ void YamlParser::processStream() throw(YamlParserException) if (events[eventIndex].type != YAML_STREAM_END_EVENT) throw YamlParserException("Did not found end of stream"); - } catch (YamlParserException &e) { + } catch (const YamlParserException &e) { throw; } } -void YamlParser::processDocument() throw(YamlParserException) +void YamlParser::processDocument() { try { @@ -280,13 +267,13 @@ void YamlParser::processDocument() throw(YamlParserException) if (events[eventIndex].type != YAML_DOCUMENT_END_EVENT) throw YamlParserException("Did not found end of document"); - } catch (YamlParserException &e) { + } catch (const YamlParserException &e) { throw; } } -void YamlParser::processScalar(YamlNode *topNode) throw(YamlParserException) +void YamlParser::processScalar(YamlNode *topNode) { try { @@ -308,17 +295,15 @@ void YamlParser::processScalar(YamlNode *topNode) throw(YamlParserException) default: break; } - } catch (YamlParserException &e) { + } catch (const YamlParserException &e) { throw; } } -void YamlParser::processSequence(YamlNode *topNode) throw(YamlParserException) +void YamlParser::processSequence(YamlNode *topNode) { - try { - if (!topNode) throw YamlParserException("No container for sequence"); @@ -362,13 +347,13 @@ void YamlParser::processSequence(YamlNode *topNode) throw(YamlParserException) if (events[eventIndex].type != YAML_SEQUENCE_END_EVENT) throw YamlParserException("Did not found end of sequence"); - } catch (YamlParserException &e) { + } catch (const YamlParserException &e) { throw; } } -void YamlParser::processMapping(YamlNode *topNode) throw(YamlParserException) +void YamlParser::processMapping(YamlNode *topNode) { try { @@ -422,14 +407,13 @@ void YamlParser::processMapping(YamlNode *topNode) throw(YamlParserException) if (events[eventIndex].type != YAML_MAPPING_END_EVENT) throw YamlParserException("Did not found end of mapping"); - } catch (YamlParserException &e) { + } catch (const YamlParserException &e) { throw; } } -void YamlParser::constructNativeData() throw(YamlParserException) +void YamlParser::constructNativeData() { - try { Sequence *seq; @@ -462,7 +446,7 @@ void YamlParser::constructNativeData() throw(YamlParserException) iter++; } - } catch (YamlParserException &e) { + } catch (const YamlParserException &e) { throw; } diff --git a/daemon/src/config/yamlparser.h b/daemon/src/config/yamlparser.h index ca8e64622c2914e53d47994bbefbd8a5fbbf205b..43b54f466b0647c8166afc05b893c4522d59d431 100644 --- a/daemon/src/config/yamlparser.h +++ b/daemon/src/config/yamlparser.h @@ -59,37 +59,37 @@ class YamlParser { ~YamlParser(); - void serializeEvents() throw(YamlParserException); + void serializeEvents(); - YamlDocument *composeEvents() throw(YamlParserException); + YamlDocument *composeEvents(); - void constructNativeData() throw(YamlParserException); + void constructNativeData(); - SequenceNode *getAccountSequence(void) { + SequenceNode *getAccountSequence() { return accountSequence; }; - MappingNode *getPreferenceNode(void) { + MappingNode *getPreferenceNode() { return preferenceNode; } - MappingNode *getAddressbookNode(void) { + MappingNode *getAddressbookNode() { return addressbookNode; } - MappingNode *getAudioNode(void) { + MappingNode *getAudioNode() { return audioNode; } - MappingNode *getHookNode(void) { + MappingNode *getHookNode() { return hooksNode; } - MappingNode *getVoipPreferenceNode(void) { + MappingNode *getVoipPreferenceNode() { return voiplinkNode; } - MappingNode *getShortcutNode(void) { + MappingNode *getShortcutNode() { return shortcutNode; } @@ -98,17 +98,17 @@ class YamlParser { /** * Copy yaml parser event in event_to according to their type. */ - void copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) throw(YamlParserException); + void copyEvent(yaml_event_t *event_to, yaml_event_t *event_from); - void processStream(void) throw(YamlParserException); + void processStream(); - void processDocument(void) throw(YamlParserException); + void processDocument(); - void processScalar(YamlNode *topNode) throw(YamlParserException); + void processScalar(YamlNode *topNode); - void processSequence(YamlNode *topNode) throw(YamlParserException); + void processSequence(YamlNode *topNode); - void processMapping(YamlNode *topNode) throw(YamlParserException); + void processMapping(YamlNode *topNode); void mainNativeDataMapping(MappingNode *map); diff --git a/daemon/src/dbus/callmanager.cpp b/daemon/src/dbus/callmanager.cpp index a8b449caadcb53a0cc8e927d5509d7929ee59cfc..aea7355ef46bcdb0f67122be16cb87e6bbd10e8d 100644 --- a/daemon/src/dbus/callmanager.cpp +++ b/daemon/src/dbus/callmanager.cpp @@ -202,7 +202,7 @@ CallManager::getConferenceDetails(const std::string& callID) } std::vector< std::string > -CallManager::getConferenceList(void) +CallManager::getConferenceList() { return Manager::instance().getConferenceList(); } @@ -245,14 +245,14 @@ CallManager::getCurrentAudioCodecName(const std::string& callID) } -std::map< std::string, std::string > +std::map<std::string, std::string> CallManager::getCallDetails(const std::string& callID) { return Manager::instance().getCallDetails(callID); } -std::vector< std::string > -CallManager::getCallList(void) +std::vector<std::string> +CallManager::getCallList() { return Manager::instance().getCallList(); } @@ -301,7 +301,7 @@ CallManager::getAudioZrtpSession(const std::string& callID) throw CallManagerException("Call id " + callID + " is not valid"); } - sfl::AudioZrtpSession * zSession = call->getAudioRtp()->getAudioZrtpSession(); + sfl::AudioZrtpSession * zSession = call->getAudioRtp().getAudioZrtpSession(); if (!zSession) throw CallManagerException("Failed to get AudioZrtpSession"); diff --git a/daemon/src/dbus/callmanager.h b/daemon/src/dbus/callmanager.h index e1650ecf96bff0c643d31464c701a809e88b97b3..e0592f32b4ec5f5a9134e9238c6a85c1c370f6e5 100644 --- a/daemon/src/dbus/callmanager.h +++ b/daemon/src/dbus/callmanager.h @@ -85,7 +85,7 @@ class CallManager void transfer(const std::string& callID, const std::string& to); void attendedTransfer(const std::string& transferID, const std::string& targetID); std::map< std::string, std::string > getCallDetails(const std::string& callID); - std::vector< std::string > getCallList(void); + std::vector< std::string > getCallList(); std::string getCurrentCallID(); /* Conference related methods */ @@ -98,7 +98,7 @@ class CallManager void hangUpConference(const std::string& confID); void holdConference(const std::string& confID); void unholdConference(const std::string& confID); - std::vector< std::string > getConferenceList(void); + std::vector< std::string > getConferenceList(); std::vector< std::string > getParticipantList(const std::string& confID); std::map< std::string, std::string > getConferenceDetails(const std::string& callID); diff --git a/daemon/src/dbus/configurationmanager.cpp b/daemon/src/dbus/configurationmanager.cpp index 88806dd6a1ac3371b0af8093e77148346e4a48fa..4abab73d4d1076e3b5473050ae47cd271b95eb56 100644 --- a/daemon/src/dbus/configurationmanager.cpp +++ b/daemon/src/dbus/configurationmanager.cpp @@ -53,7 +53,7 @@ ConfigurationManager::ConfigurationManager(DBus::Connection& connection) : shortcutsKeys.push_back("toggle_hold"); } -std::map<std::string, std::string> ConfigurationManager::getIp2IpDetails(void) +std::map<std::string, std::string> ConfigurationManager::getIp2IpDetails() { std::map<std::string, std::string> ip2ipAccountDetails; SIPAccount *sipaccount = static_cast<SIPAccount *>(Manager::instance().getAccount(IP2IP_PROFILE)); @@ -161,7 +161,7 @@ std::vector<std::string> ConfigurationManager::getAccountList() * 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<int32_t > ConfigurationManager::getAudioCodecList(void) +std::vector<int32_t > ConfigurationManager::getAudioCodecList() { std::vector<int32_t> list(Manager::instance().audioCodecFactory.getAudioCodecList()); @@ -171,7 +171,7 @@ std::vector<int32_t > ConfigurationManager::getAudioCodecList(void) return list; } -std::vector<std::string> ConfigurationManager::getSupportedTlsMethod(void) +std::vector<std::string> ConfigurationManager::getSupportedTlsMethod() { std::vector<std::string> method; method.push_back("Default"); @@ -265,14 +265,14 @@ int32_t ConfigurationManager::getAudioDeviceIndex(const std::string& name) return Manager::instance().getAudioDeviceIndex(name); } -std::string ConfigurationManager::getCurrentAudioOutputPlugin(void) +std::string ConfigurationManager::getCurrentAudioOutputPlugin() { _debug("ConfigurationManager: Get audio plugin %s", Manager::instance().getCurrentAudioOutputPlugin().c_str()); return Manager::instance().getCurrentAudioOutputPlugin(); } -std::string ConfigurationManager::getNoiseSuppressState(void) +std::string ConfigurationManager::getNoiseSuppressState() { return Manager::instance().getNoiseSuppressState(); } @@ -282,7 +282,7 @@ void ConfigurationManager::setNoiseSuppressState(const std::string& state) Manager::instance().setNoiseSuppressState(state); } -std::string ConfigurationManager::getEchoCancelState(void) +std::string ConfigurationManager::getEchoCancelState() { return Manager::instance().getEchoCancelState() ? "enabled" : "disabled"; } @@ -292,7 +292,7 @@ void ConfigurationManager::setEchoCancelState(const std::string& state) Manager::instance().setEchoCancelState(state); } -int ConfigurationManager::getEchoCancelTailLength(void) +int ConfigurationManager::getEchoCancelTailLength() { return Manager::instance().getEchoCancelTailLength(); } @@ -302,7 +302,7 @@ void ConfigurationManager::setEchoCancelTailLength(const int32_t& length) Manager::instance().setEchoCancelTailLength(length); } -int ConfigurationManager::getEchoCancelDelay(void) +int ConfigurationManager::getEchoCancelDelay() { return Manager::instance().getEchoCancelDelay(); } @@ -312,12 +312,12 @@ void ConfigurationManager::setEchoCancelDelay(const int32_t& delay) Manager::instance().setEchoCancelDelay(delay); } -int32_t ConfigurationManager::isIax2Enabled(void) +int32_t ConfigurationManager::isIax2Enabled() { return HAVE_IAX; } -std::string ConfigurationManager::getRecordPath(void) +std::string ConfigurationManager::getRecordPath() { return Manager::instance().getRecordPath(); } @@ -327,7 +327,7 @@ void ConfigurationManager::setRecordPath(const std::string& recPath) Manager::instance().setRecordPath(recPath); } -bool ConfigurationManager::getIsAlwaysRecording(void) +bool ConfigurationManager::getIsAlwaysRecording() { return Manager::instance().getIsAlwaysRecording(); } @@ -337,7 +337,7 @@ void ConfigurationManager::setIsAlwaysRecording(const bool& rec) Manager::instance().setIsAlwaysRecording(rec); } -int32_t ConfigurationManager::getHistoryLimit(void) +int32_t ConfigurationManager::getHistoryLimit() { return Manager::instance().getHistoryLimit(); } @@ -352,22 +352,22 @@ void ConfigurationManager::setAudioManager(const std::string& api) Manager::instance().setAudioManager(api); } -std::string ConfigurationManager::getAudioManager(void) +std::string ConfigurationManager::getAudioManager() { return Manager::instance().getAudioManager(); } -void ConfigurationManager::setMailNotify(void) +void ConfigurationManager::setMailNotify() { Manager::instance().setMailNotify(); } -int32_t ConfigurationManager::getMailNotify(void) +int32_t ConfigurationManager::getMailNotify() { return Manager::instance().getMailNotify(); } -std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings(void) +std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings() { return Manager::instance().getAddressbookSettings(); } @@ -377,7 +377,7 @@ void ConfigurationManager::setAddressbookSettings(const std::map<std::string, in Manager::instance().setAddressbookSettings(settings); } -std::vector<std::string> ConfigurationManager::getAddressbookList(void) +std::vector<std::string> ConfigurationManager::getAddressbookList() { return Manager::instance().getAddressbookList(); } @@ -388,7 +388,7 @@ void ConfigurationManager::setAddressbookList( Manager::instance().setAddressbookList(list); } -std::map<std::string, std::string> ConfigurationManager::getHookSettings(void) +std::map<std::string, std::string> ConfigurationManager::getHookSettings() { return Manager::instance().getHookSettings(); } @@ -404,7 +404,7 @@ void ConfigurationManager::setAccountsOrder(const std::string& order) Manager::instance().setAccountsOrder(order); } -std::vector<std::string> ConfigurationManager::getHistory(void) +std::vector<std::string> ConfigurationManager::getHistory() { return Manager::instance().getHistorySerialized(); } @@ -420,12 +420,12 @@ std::string ConfigurationManager::getAddrFromInterfaceName( return SIPVoIPLink::getInterfaceAddrFromName(interface); } -std::vector<std::string> ConfigurationManager::getAllIpInterface(void) +std::vector<std::string> ConfigurationManager::getAllIpInterface() { return SIPVoIPLink::getAllIpInterface(); } -std::vector<std::string> ConfigurationManager::getAllIpInterfaceByName(void) +std::vector<std::string> ConfigurationManager::getAllIpInterfaceByName() { return SIPVoIPLink::getAllIpInterfaceByName(); } diff --git a/daemon/src/dbus/configurationmanager.h b/daemon/src/dbus/configurationmanager.h index d8574e4f788ab6399e24e17df21e2e64e83b7678..f1516b0ad1f828bf0eec760ee2d2c41f5db5625b 100644 --- a/daemon/src/dbus/configurationmanager.h +++ b/daemon/src/dbus/configurationmanager.h @@ -70,10 +70,10 @@ class ConfigurationManager std::vector< std::string > getAccountList(); void sendRegister(const std::string& accoundID , const int32_t& expire); - std::map< std::string, std::string > getTlsSettingsDefault(void); + std::map< std::string, std::string > getTlsSettingsDefault(); - std::vector< int32_t > getAudioCodecList(void); - std::vector< std::string > getSupportedTlsMethod(void); + std::vector< int32_t > getAudioCodecList(); + std::vector< std::string > getSupportedTlsMethod(); std::vector< std::string > getAudioCodecDetails(const int32_t& payload); std::vector< int32_t > getActiveAudioCodecList(const std::string& accountID); void setActiveAudioCodecList(const std::vector< std::string >& list, const std::string& accountID); @@ -87,60 +87,60 @@ class ConfigurationManager std::vector< std::string > getAudioInputDeviceList(); std::vector< std::string > getCurrentAudioDevicesIndex(); int32_t getAudioDeviceIndex(const std::string& name); - std::string getCurrentAudioOutputPlugin(void); - std::string getNoiseSuppressState(void); + std::string getCurrentAudioOutputPlugin(); + std::string getNoiseSuppressState(); void setNoiseSuppressState(const std::string& state); - std::string getEchoCancelState(void); + std::string getEchoCancelState(); void setEchoCancelState(const std::string& state); void setEchoCancelTailLength(const int32_t& length); - int getEchoCancelTailLength(void); + int getEchoCancelTailLength(); void setEchoCancelDelay(const int32_t& length); - int getEchoCancelDelay(void); + int getEchoCancelDelay(); - std::string getAudioManager(void); + std::string getAudioManager(); void setAudioManager(const std::string& api); - int32_t isIax2Enabled(void); - std::string getRecordPath(void); + int32_t isIax2Enabled(); + std::string getRecordPath(); void setRecordPath(const std::string& recPath); - bool getIsAlwaysRecording(void); + bool getIsAlwaysRecording(); void setIsAlwaysRecording(const bool& rec); void setHistoryLimit(const int32_t& days); - int32_t getHistoryLimit(void); + int32_t getHistoryLimit(); - int32_t getMailNotify(void); - void setMailNotify(void); + int32_t getMailNotify(); + void setMailNotify(); - std::map<std::string, int32_t> getAddressbookSettings(void); + std::map<std::string, int32_t> getAddressbookSettings(); void setAddressbookSettings(const std::map<std::string, int32_t>& settings); - std::vector< std::string > getAddressbookList(void); + std::vector< std::string > getAddressbookList(); void setAddressbookList(const std::vector< std::string >& list); void setAccountsOrder(const std::string& order); - std::map<std::string, std::string> getHookSettings(void); + std::map<std::string, std::string> getHookSettings(); void setHookSettings(const std::map<std::string, std::string>& settings); - std::vector<std::string> getHistory(void); + std::vector<std::string> getHistory(); void setHistory(const std::vector<std::string> &entries); - std::map<std::string, std::string> getTlsSettings(void); + std::map<std::string, std::string> getTlsSettings(); void setTlsSettings(const std::map< std::string, std::string >& details); - std::map< std::string, std::string > getIp2IpDetails(void); + std::map< std::string, std::string > getIp2IpDetails(); std::vector< std::map< std::string, std::string > > getCredentials(const std::string& accountID); void setCredentials(const std::string& accountID, const std::vector< std::map< std::string, std::string > >& details); std::string getAddrFromInterfaceName(const std::string& interface); - std::vector<std::string> getAllIpInterface(void); - std::vector<std::string> getAllIpInterfaceByName(void); + std::vector<std::string> getAllIpInterface(); + std::vector<std::string> getAllIpInterfaceByName(); std::map< std::string, std::string > getShortcuts(); void setShortcuts(const std::map< std::string, std::string >& shortcutsMap); }; - #endif//CONFIGURATIONMANAGER_H + diff --git a/daemon/src/dbus/instance.h b/daemon/src/dbus/instance.h index cc64ef7a391f805fb64474d35d2bd8472b097ab9..31c82d29e96652267ef03eb6680baf43ac22797a 100644 --- a/daemon/src/dbus/instance.h +++ b/daemon/src/dbus/instance.h @@ -58,7 +58,7 @@ class Instance void Register(const int32_t& pid, const std::string& name); void Unregister(const int32_t& pid); - int32_t getRegistrationCount(void); + int32_t getRegistrationCount(); }; diff --git a/daemon/src/fileutils.cpp b/daemon/src/fileutils.cpp index 29d1149bed5bd69042cb22535196884365f79e0d..60279ec6393284627c650804b739a785ac15c0c7 100644 --- a/daemon/src/fileutils.cpp +++ b/daemon/src/fileutils.cpp @@ -38,7 +38,7 @@ void set_program_dir(char *program_path) program_dir = dirname(program_path); } -const char *get_program_dir(void) +const char *get_program_dir() { return program_dir; } diff --git a/daemon/src/history/historyitem.cpp b/daemon/src/history/historyitem.cpp index 1221c82fa42c54a27150f7d2e8ae91822e292a7b..130094aaa810a84cb6ca657670f8894b24d77f7d 100644 --- a/daemon/src/history/historyitem.cpp +++ b/daemon/src/history/historyitem.cpp @@ -38,18 +38,17 @@ #define ITEM_SEPARATOR "|" HistoryItem::HistoryItem(std::string timestamp_start, CallType call_type, std::string timestamp_stop, std::string name, std::string number, std::string id, std::string account_id, std::string recording, std::string confID, std::string timeAdded) - : _timestamp_start(timestamp_start), - _timestamp_stop(timestamp_stop), - _call_type(call_type), - _name(name), - _number(number), - _id(id), - _account_id(account_id), - _recording_file(recording), - _confID(confID), - _timeAdded(timeAdded) -{ -} + : timestamp_start_(timestamp_start), + timestamp_stop_(timestamp_stop), + call_type_(call_type), + name_(name), + number_(number), + id_(id), + account_id_(account_id), + recording_file_(recording), + confID_(confID), + timeAdded_(timeAdded) +{} HistoryItem::HistoryItem(std::string serialized_form) @@ -63,38 +62,37 @@ HistoryItem::HistoryItem(std::string serialized_form) switch (indice) { case 0: // The call type - _call_type = (CallType) atoi(tmp.c_str()); + call_type_ = (CallType) atoi(tmp.c_str()); break; case 1: // The number field - _number = tmp; + number_ = tmp; break; case 2: // The name field - _name = tmp; - - if (_name == "empty") - _name = ""; + name_ = tmp; + if (name_ == "empty") + name_ = ""; break; case 3: // The start timestamp - _timestamp_start = tmp; + timestamp_start_ = tmp; break; case 4: // The end timestamp - _timestamp_stop = tmp; + timestamp_stop_ = tmp; break; case 5: // The ID - _id = tmp; + id_ = tmp; break; case 6: // The account ID - _account_id = tmp; + account_id_ = tmp; break; case 7: // The recorded file name - _recording_file = tmp; + recording_file_ = tmp; break; case 8: // The conference ID - _confID = tmp; + confID_ = tmp; break; case 9: // The time - _timeAdded = tmp; + timeAdded_ = tmp; break; default: // error _error("Unserialized form %d not recognized\n", indice); @@ -105,11 +103,6 @@ HistoryItem::HistoryItem(std::string serialized_form) } } -HistoryItem::~HistoryItem() -{ - // TODO -} - bool HistoryItem::save(Conf::ConfigTree **history) { std::stringstream section; @@ -118,53 +111,39 @@ bool HistoryItem::save(Conf::ConfigTree **history) // The section is : "[" + timestamp = "]" section << rand(); std::string sectionstr = section.str(); - call_type << _call_type; - - /* - _error("-- Unserialized type: %s", call_type.str().c_str()); - _error("-- Unserialized time start: %s", _timestamp_start.c_str()); - _error("-- Unserialized time stop: %s", _timestamp_stop.c_str()); - _error("-- Unserialized number: %s", _number.c_str()); - _error("-- Unserialized id: %s", _id.c_str()); - _error("-- Unserialized account: %s", _account_id.c_str()); - _error("-- Unserialized name: %s", _name.c_str()); - _error("-- Unserialized record file: %s", _recording_file.c_str()); - _error("-- Unserialized conference id:%s", _confID.c_str()); - _error("-- Unserialized time added: %s", _timeAdded.c_str()); - */ + call_type << call_type_; return (*history)->setConfigTreeItem(sectionstr, "type", call_type.str()) - && (*history)->setConfigTreeItem(sectionstr, "timestamp_start", _timestamp_start) - && (*history)->setConfigTreeItem(sectionstr, "timestamp_stop", _timestamp_stop) - && (*history)->setConfigTreeItem(sectionstr, "number", _number) - && (*history)->setConfigTreeItem(sectionstr, "id", _id) - && (*history)->setConfigTreeItem(sectionstr, "accountid", _account_id) - && (*history)->setConfigTreeItem(sectionstr, "name", _name) - && (*history)->setConfigTreeItem(sectionstr, "recordfile", _recording_file) - && (*history)->setConfigTreeItem(sectionstr, "confid", _confID) - && (*history)->setConfigTreeItem(sectionstr, "timeadded", _timeAdded); + && (*history)->setConfigTreeItem(sectionstr, "timestamp_start", timestamp_start_) + && (*history)->setConfigTreeItem(sectionstr, "timestamp_stop", timestamp_stop_) + && (*history)->setConfigTreeItem(sectionstr, "number", number_) + && (*history)->setConfigTreeItem(sectionstr, "id", id_) + && (*history)->setConfigTreeItem(sectionstr, "accountid", account_id_) + && (*history)->setConfigTreeItem(sectionstr, "name", name_) + && (*history)->setConfigTreeItem(sectionstr, "recordfile", recording_file_) + && (*history)->setConfigTreeItem(sectionstr, "confid", confID_) + && (*history)->setConfigTreeItem(sectionstr, "timeadded", timeAdded_); } -std::string HistoryItem::serialize(void) +std::string HistoryItem::serialize() { - std::stringstream res; - // Replace empty string with a valid standard string value - std::string name(_name); + std::string name(name_); - if (name == "") + if (name.empty()) name = "empty"; // For the account ID, check also if the accountID corresponds to an existing account // ie the account may have been removed - std::string accountID(_account_id); + std::string accountID(account_id_); - if (_account_id == "" || not valid_account(_account_id)) + if (account_id_.empty() or not valid_account(account_id_)) accountID = "empty"; + std::stringstream res; // Serialize it - res << _call_type << ITEM_SEPARATOR << _number << ITEM_SEPARATOR << name << ITEM_SEPARATOR << _timestamp_start << ITEM_SEPARATOR << _timestamp_stop - << ITEM_SEPARATOR << _id << ITEM_SEPARATOR << accountID << ITEM_SEPARATOR << _recording_file << ITEM_SEPARATOR << _confID << ITEM_SEPARATOR << _timeAdded; + res << call_type_ << ITEM_SEPARATOR << number_ << ITEM_SEPARATOR << name << ITEM_SEPARATOR << timestamp_start_ << ITEM_SEPARATOR << timestamp_stop_ + << ITEM_SEPARATOR << id_ << ITEM_SEPARATOR << accountID << ITEM_SEPARATOR << recording_file_ << ITEM_SEPARATOR << confID_ << ITEM_SEPARATOR << timeAdded_; return res.str(); } diff --git a/daemon/src/history/historyitem.h b/daemon/src/history/historyitem.h index d4788fe8ed18979baa0abdfc3dfabeb923772fe9..83b136db8c17a94b2ec5a8f77797f0a0496a09b3 100644 --- a/daemon/src/history/historyitem.h +++ b/daemon/src/history/historyitem.h @@ -30,12 +30,11 @@ * as that of the covered work. */ -#ifndef _HISTORY_ITEM -#define _HISTORY_ITEM +#ifndef HISTORY_ITEM_H_ +#define HISTORY_ITEM_H_ #include <string> #include <config/config.h> -#include <iostream> typedef enum CallType { CALL_MISSED, @@ -43,7 +42,6 @@ typedef enum CallType { CALL_OUTGOING } CallType; - class HistoryItem { public: @@ -69,21 +67,15 @@ class HistoryItem { */ HistoryItem(std::string=""); - /* - * Destructor - */ - ~HistoryItem(); - std::string get_timestamp() const { - return _timestamp_start; + return timestamp_start_; } bool save(Conf::ConfigTree **history); - std::string serialize(void); + std::string serialize(); private: - /* * @return true if the account ID corresponds to a loaded account */ @@ -92,45 +84,45 @@ class HistoryItem { /* * Timestamp representing the date of the call */ - std::string _timestamp_start; - std::string _timestamp_stop; + std::string timestamp_start_; + std::string timestamp_stop_; /* * Represents the type of call * Has be either CALL_MISSED, CALL_INCOMING or CALL_OUTGOING */ - CallType _call_type; + CallType call_type_; /* * The information about the callee/caller, depending on the type of call. */ - std::string _name; - std::string _number; + std::string name_; + std::string number_; /** * The identifier fo this item */ - std::string _id; + std::string id_; /* * The account the call was made with */ - std::string _account_id; + std::string account_id_; /** * Wether or not a recording exist for this call */ - std::string _recording_file; + std::string recording_file_; /** * The conference ID for this call (if any) */ - std::string _confID; + std::string confID_; /** * Time added to conference */ - std::string _timeAdded; + std::string timeAdded_; }; diff --git a/daemon/src/history/historymanager.cpp b/daemon/src/history/historymanager.cpp index e82d8d1f92e2a262e96fc3d34a6a7ccdbf6bbd44..8989f3dc4f5d47c7c23d45525c128f2a3f1f345e 100644 --- a/daemon/src/history/historymanager.cpp +++ b/daemon/src/history/historymanager.cpp @@ -48,91 +48,71 @@ static void free_history(HistoryItemMap &history_items) } // end anonymous namespace HistoryManager::HistoryManager() - : _history_loaded(false), - _history_path("") + : history_loaded_(false), + history_path_("") { } HistoryManager::~HistoryManager() { - free_history(_history_items); + free_history(history_items_); } int HistoryManager::load_history(int limit, std::string path) { Conf::ConfigTree history_list; - - _debug("HistoryManager: Load history"); - create_history_path(path); load_history_from_file(&history_list); return load_history_items_map(&history_list, limit); } -bool HistoryManager::save_history(void) +bool HistoryManager::save_history() { Conf::ConfigTree history_list; - - _debug("HistoryManager: Save history"); - save_history_items_map(&history_list); return save_history_to_file(&history_list); } bool HistoryManager::load_history_from_file(Conf::ConfigTree *history_list) { - _debug("HistoryManager: Load history from file %s", _history_path.c_str()); + _debug("HistoryManager: Load history from file %s", history_path_.c_str()); - int exist = history_list->populateFromFile(_history_path.c_str()); - _history_loaded = (exist == 2) ? false : true; + int exist = history_list->populateFromFile(history_path_.c_str()); + history_loaded_ = (exist == 2) ? false : true; - return _history_loaded; + return history_loaded_; } int HistoryManager::load_history_items_map(Conf::ConfigTree *history_list, int limit) { - - short nb_items = 0; - Conf::TokenList sections; - HistoryItem *item; - Conf::TokenList::iterator iter; - std::string number, name, callID, accountID, timestamp_start, timestamp_stop, recording_file, confID, time_added; - CallType type; - int history_limit; - time_t current_timestamp; - - _debug("HistoryManager: Load history items"); + using std::string; // We want to save only the items recent enough (ie compared to CONFIG_HISTORY_LIMIT) // Get the current timestamp - (void) time(¤t_timestamp); - history_limit = get_unix_timestamp_equivalent(limit); - - sections = history_list->getSections(); - iter = sections.begin(); - - while (iter != sections.end()) { - - type = (CallType) getConfigInt(*iter, "type", history_list); - timestamp_start = getConfigString(*iter, "timestamp_start", history_list); - timestamp_stop = getConfigString(*iter, "timestamp_stop", history_list); - name = getConfigString(*iter, "name", history_list); - number = getConfigString(*iter, "number", history_list); - callID = getConfigString(*iter, "id", history_list); - accountID = getConfigString(*iter, "accountid", history_list); - recording_file = getConfigString(*iter, "recordfile", history_list); - confID = getConfigString(*iter, "confid", history_list); - time_added = getConfigString(*iter, "timeadded", history_list); + time_t current_timestamp; + time(¤t_timestamp); + int history_limit = get_unix_timestamp_equivalent(limit); + + Conf::TokenList sections(history_list->getSections()); + int nb_items = 0; + for (Conf::TokenList::iterator iter = sections.begin(); iter != sections.end(); ++iter) { + CallType type = (CallType) getConfigInt(*iter, "type", history_list); + string timestamp_start = getConfigString(*iter, "timestamp_start", history_list); + string timestamp_stop = getConfigString(*iter, "timestamp_stop", history_list); + string name = getConfigString(*iter, "name", history_list); + string number = getConfigString(*iter, "number", history_list); + string callID = getConfigString(*iter, "id", history_list); + string accountID = getConfigString(*iter, "accountid", history_list); + string recording_file = getConfigString(*iter, "recordfile", history_list); + string confID = getConfigString(*iter, "confid", history_list); + string time_added = getConfigString(*iter, "timeadded", history_list); // Make a check on the start timestamp to know it is loadable according to CONFIG_HISTORY_LIMIT - if (atoi(timestamp_start.c_str()) >= ((int) current_timestamp - history_limit)) { - item = new HistoryItem(timestamp_start, type, timestamp_stop, name, number, callID, accountID, recording_file, confID, time_added); + HistoryItem *item = new HistoryItem(timestamp_start, type, timestamp_stop, name, number, callID, accountID, recording_file, confID, time_added); add_new_history_entry(item); - nb_items ++; + ++nb_items; } - - iter ++; } return nb_items; @@ -141,32 +121,22 @@ int HistoryManager::load_history_items_map(Conf::ConfigTree *history_list, int l bool HistoryManager::save_history_to_file(Conf::ConfigTree *history_list) { - _debug("HistoryManager: Saving history in XDG directory: %s", _history_path.data()); - return history_list->saveConfigTree(_history_path.data()); + _debug("HistoryManager: Saving history in XDG directory: %s", history_path_.c_str()); + return history_list->saveConfigTree(history_path_.data()); } int HistoryManager::save_history_items_map(Conf::ConfigTree *history_list) { - HistoryItemMap::iterator iter; - HistoryItem *item; int items_saved = 0; - - _debug("HistoryManager: Save history items map"); - - iter = _history_items.begin(); - - while (iter != _history_items.end()) { - item = *iter; + for (HistoryItemMap::iterator iter = history_items_.begin(); iter != history_items_.end(); ++iter) { + HistoryItem *item = *iter; if (item) { if (item->save(&history_list)) - items_saved ++; - } else { + ++items_saved; + } else _debug("can't save NULL history item\n"); - } - - iter ++; } return items_saved; @@ -175,7 +145,7 @@ int HistoryManager::save_history_items_map(Conf::ConfigTree *history_list) void HistoryManager::add_new_history_entry(HistoryItem *new_item) { // Add it in the map - _history_items.push_back(new_item); + history_items_.push_back(new_item); } int HistoryManager::create_history_path(std::string path) @@ -185,8 +155,7 @@ int HistoryManager::create_history_path(std::string path) xdg_data = std::string(HOMEDIR) + DIR_SEPARATOR_STR + ".local/share/sflphone"; - if (path == "") { - + if (path.empty()) { // If the environment variable is set (not null and not empty), we'll use it to save the history // Else we 'll the standard one, ie: XDG_DATA_HOME = $HOMEDIR/.local/share/sflphone if (XDG_DATA_HOME != NULL) { @@ -205,11 +174,10 @@ int HistoryManager::create_history_path(std::string path) } // Load user's history - _history_path = userdata + DIR_SEPARATOR_STR + "history"; + history_path_ = userdata + DIR_SEPARATOR_STR + "history"; } else set_history_path(path); - return 0; } @@ -219,7 +187,7 @@ HistoryManager::getConfigInt(const std::string& section, const std::string& name { try { return history_list->getConfigTreeItemIntValue(section, name); - } catch (Conf::ConfigTreeItemException& e) { + } catch (const Conf::ConfigTreeItemException& e) { throw e; } @@ -231,21 +199,21 @@ HistoryManager::getConfigString(const std::string& section, const std::string& n { try { return history_list->getConfigTreeItemValue(section, name); - } catch (Conf::ConfigTreeItemException& e) { + } catch (const Conf::ConfigTreeItemException& e) { throw e; } return ""; } -std::vector<std::string> HistoryManager::get_history_serialized(void) +std::vector<std::string> HistoryManager::get_history_serialized() { std::vector<std::string> serialized; HistoryItemMap::iterator iter; _debug("HistoryManager: Get history serialized"); - for (iter = _history_items.begin(); iter != _history_items.end(); ++iter) { + for (iter = history_items_.begin(); iter != history_items_.end(); ++iter) { HistoryItem *current = *iter; if (current) @@ -258,40 +226,31 @@ std::vector<std::string> HistoryManager::get_history_serialized(void) int HistoryManager::set_serialized_history(std::vector<std::string> history, int limit) { - std::vector<std::string>::iterator iter; - HistoryItem *new_item; - int items_added = 0; int history_limit; time_t current_timestamp; _debug("HistoryManager: Set serialized history"); // Clear the existing history - free_history(_history_items); + free_history(history_items_); // We want to save only the items recent enough (ie compared to CONFIG_HISTORY_LIMIT) // Get the current timestamp - (void) time(¤t_timestamp); + time(¤t_timestamp); history_limit = get_unix_timestamp_equivalent(limit); - for (iter = history.begin() ; iter != history.end() ; iter ++) { - new_item = new HistoryItem(*iter); - - if (new_item == NULL) { - _error("HistoryManager: Error: Could not create history item"); - } - + int items_added = 0; + for (std::vector<std::string>::iterator iter = history.begin() ; iter != history.end() ; ++iter) { + HistoryItem *new_item = new HistoryItem(*iter); int item_timestamp = atoi(new_item->get_timestamp().c_str()); if (item_timestamp >= ((int) current_timestamp - history_limit)) { add_new_history_entry(new_item); - items_added ++; - } else { + ++items_added; + } else delete new_item; - } } return items_added; } - diff --git a/daemon/src/history/historymanager.h b/daemon/src/history/historymanager.h index 578cd5e26df057ef163a40712ef08e8a7c3a1670..a27ae247a4b7935b7ee97402956a3c28a2aacf40 100644 --- a/daemon/src/history/historymanager.h +++ b/daemon/src/history/historymanager.h @@ -63,7 +63,7 @@ class HistoryManager { /** *@return bool True if the history has been successfully saved in the file */ - bool save_history(void); + bool save_history(); /* * Load the history from a file to the dedicated data structure @@ -88,22 +88,22 @@ class HistoryManager { /** *@return bool True if the history file has been successfully read */ - bool is_loaded(void) const { - return _history_loaded; + bool is_loaded() const { + return history_loaded_; } void set_history_path(const std::string &filename) { - _history_path = filename; + history_path_ = filename; } /* *@return int The number of items found in the history file */ - int get_history_size(void) const { - return _history_items.size(); + int get_history_size() const { + return history_items_.size(); } - std::vector<std::string> get_history_serialized(void); + std::vector<std::string> get_history_serialized(); int set_serialized_history(std::vector<std::string> history, int limit); @@ -129,18 +129,18 @@ class HistoryManager { /* * Map containing the history items */ - HistoryItemMap _history_items; + HistoryItemMap history_items_; /* * History has been loaded */ - bool _history_loaded; + bool history_loaded_; /* * The path to the history file */ - std::string _history_path; + std::string history_path_; friend class HistoryTest; }; diff --git a/daemon/src/iax/iaxaccount.cpp b/daemon/src/iax/iaxaccount.cpp index 778d56723e21e854cc825a3a3a9654cce2a61f21..a30705662ae02888796bfa9ec85552b7fa363ed9 100644 --- a/daemon/src/iax/iaxaccount.cpp +++ b/daemon/src/iax/iaxaccount.cpp @@ -84,7 +84,7 @@ void IAXAccount::serialize(Conf::YamlEmitter *emitter) try { emitter->serializeAccount(&accountmap); - } catch (Conf::YamlEmitterException &e) { + } catch (const Conf::YamlEmitterException &e) { _error("ConfigTree: %s", e.what()); } } diff --git a/daemon/src/iax/iaxaccount.h b/daemon/src/iax/iaxaccount.h index dc866888e665052be2d666cd7d6d42b52036fa13..60b9a1acee27eb704046dc45685460177534d457 100644 --- a/daemon/src/iax/iaxaccount.h +++ b/daemon/src/iax/iaxaccount.h @@ -40,7 +40,6 @@ class IAXAccount : public Account { public: IAXAccount(const std::string& accountID); - ~IAXAccount(); virtual void serialize(Conf::YamlEmitter *emitter); @@ -51,30 +50,21 @@ class IAXAccount : public Account { std::map<std::string, std::string> getAccountDetails() const; - /** - * Actually useless, since config loading is done in init() - */ + // Actually useless, since config loading is done in init() void loadConfig(); - /** - * Register an account - */ + // Register an account void registerVoIPLink(); - /** - * Unregister an account - */ + // Unregister an account void unregisterVoIPLink(); - std::string getPassword(void) const { + std::string getPassword() const { return password_; } private: - - /** - * Account login information: password - */ + // Account login information: password std::string password_; }; diff --git a/daemon/src/iax/iaxcall.cpp b/daemon/src/iax/iaxcall.cpp index 79088235b758d14547cd719b640bd760b2b3d376..afa6622310fc35875838c3120d9d7751019dd4ca 100644 --- a/daemon/src/iax/iaxcall.cpp +++ b/daemon/src/iax/iaxcall.cpp @@ -37,27 +37,29 @@ namespace { int codecToASTFormat(int c) { - if (c == PAYLOAD_CODEC_ULAW) return AST_FORMAT_ULAW; - - if (c == PAYLOAD_CODEC_GSM) return AST_FORMAT_GSM; - - if (c == PAYLOAD_CODEC_ALAW) return AST_FORMAT_ALAW; - - if (c == PAYLOAD_CODEC_ILBC_20) return AST_FORMAT_ILBC; - - if (c == PAYLOAD_CODEC_SPEEX_8000) return AST_FORMAT_SPEEX; - - _error("Codec %d not supported!", c); - return 0; + switch (c) { + case PAYLOAD_CODEC_ULAW: + return AST_FORMAT_ULAW; + case PAYLOAD_CODEC_GSM: + return AST_FORMAT_GSM; + case PAYLOAD_CODEC_ALAW: + return AST_FORMAT_ALAW; + case PAYLOAD_CODEC_ILBC_20: + return AST_FORMAT_ILBC; + case PAYLOAD_CODEC_SPEEX_8000: + return AST_FORMAT_SPEEX; + + default: + _error("Codec %d not supported!", c); + return 0; + } } } IAXCall::IAXCall(const std::string& id, Call::CallType type) : Call(id, type), session(NULL) -{ -} +{} -int -IAXCall::getSupportedFormat(const std::string &accountID) const +int IAXCall::getSupportedFormat(const std::string &accountID) const { Account *account = Manager::instance().getAccount(accountID); @@ -94,18 +96,21 @@ int IAXCall::getFirstMatchingFormat(int needles, const std::string &accountID) c return 0; } -int IAXCall::getAudioCodec(void) +int IAXCall::getAudioCodec() const { - if (format == AST_FORMAT_ULAW) return PAYLOAD_CODEC_ULAW; - - if (format == AST_FORMAT_GSM) return PAYLOAD_CODEC_GSM; - - if (format == AST_FORMAT_ALAW) return PAYLOAD_CODEC_ALAW; - - if (format == AST_FORMAT_ILBC) return PAYLOAD_CODEC_ILBC_20; - - if (format == AST_FORMAT_SPEEX) return PAYLOAD_CODEC_SPEEX_8000; - - _error("IAX: Format %d not supported!", format); - return -1; + switch (format) { + case AST_FORMAT_ULAW: + return PAYLOAD_CODEC_ULAW; + case AST_FORMAT_GSM: + return PAYLOAD_CODEC_GSM; + case AST_FORMAT_ALAW: + return PAYLOAD_CODEC_ALAW; + case AST_FORMAT_ILBC: + return PAYLOAD_CODEC_ILBC_20; + case AST_FORMAT_SPEEX: + return PAYLOAD_CODEC_SPEEX_8000; + default: + _error("IAX: Format %d not supported!", format); + return -1; + } } diff --git a/daemon/src/iax/iaxcall.h b/daemon/src/iax/iaxcall.h index fe404da08f6aedaba33ac30a959d8712d777f5ef..e81c3bb70ebe0a98167ee35c8211388b8eec93c5 100644 --- a/daemon/src/iax/iaxcall.h +++ b/daemon/src/iax/iaxcall.h @@ -32,7 +32,6 @@ #define IAXCALL_H #include "call.h" -#include "audio/codecs/audiocodecfactory.h" /** * @file: iaxcall.h @@ -69,7 +68,7 @@ class IAXCall : public Call { */ int getFirstMatchingFormat(int needles, const std::string &accountID) const; - int getAudioCodec(void); + int getAudioCodec() const; int format; iax_session* session; diff --git a/daemon/src/iax/iaxvoiplink.cpp b/daemon/src/iax/iaxvoiplink.cpp index f89e3301dc40f18036ec7e29cf225569dd4f0882..2ee740e936fe35044738d70e58e701f3312c9254 100644 --- a/daemon/src/iax/iaxvoiplink.cpp +++ b/daemon/src/iax/iaxvoiplink.cpp @@ -136,7 +136,7 @@ IAXVoIPLink::getEvent() } void -IAXVoIPLink::sendAudioFromMic(void) +IAXVoIPLink::sendAudioFromMic() { for (CallMap::const_iterator iter = callMap_.begin(); iter != callMap_.end() ; ++iter) { IAXCall *currentCall = dynamic_cast<IAXCall*>(iter->second); @@ -396,7 +396,8 @@ IAXVoIPLink::carryingDTMFdigits(const std::string& id, char code) void IAXVoIPLink::sendTextMessage(sfl::InstantMessaging *module, - const std::string& callID, const std::string& message, + const std::string& callID, + const std::string& message, const std::string& /*from*/) { IAXCall* call = getIAXCall(callID); @@ -439,7 +440,7 @@ IAXVoIPLink::iaxOutgoingInvite(IAXCall* call) IAXCall* -IAXVoIPLink::iaxFindCallBySession(struct iax_session* session) +IAXVoIPLink::iaxFindCallBySession(iax_session* session) { ost::MutexLock m(callMapMutex_); @@ -537,8 +538,7 @@ IAXVoIPLink::iaxHandleCallEvent(iax_event* event, IAXCall* call) /* Handle audio event, VOICE packet received */ -void -IAXVoIPLink::iaxHandleVoiceEvent(iax_event* event, IAXCall* call) +void IAXVoIPLink::iaxHandleVoiceEvent(iax_event* event, IAXCall* call) { // Skip this empty packet. if (!event->datalen) @@ -580,8 +580,7 @@ IAXVoIPLink::iaxHandleVoiceEvent(iax_event* event, IAXCall* call) /** * Handle the registration process */ -void -IAXVoIPLink::iaxHandleRegReply(iax_event* event) +void IAXVoIPLink::iaxHandleRegReply(iax_event* event) { IAXAccount *account = dynamic_cast<IAXAccount *>(Manager::instance().getAccount(accountID_)); @@ -598,8 +597,7 @@ IAXVoIPLink::iaxHandleRegReply(iax_event* event) nextRefreshStamp_ = time(NULL) + (event->ies.refresh ? event->ies.refresh : 60); } -void -IAXVoIPLink::iaxHandlePrecallEvent(iax_event* event) +void IAXVoIPLink::iaxHandlePrecallEvent(iax_event* event) { IAXCall *call; std::string id; diff --git a/daemon/src/iax/iaxvoiplink.h b/daemon/src/iax/iaxvoiplink.h index 17f21058bf17fbf0bbca05a1153be77dca990bdb..1b29e2199e0bd486c7dfb8064aafda7f1590f92a 100644 --- a/daemon/src/iax/iaxvoiplink.h +++ b/daemon/src/iax/iaxvoiplink.h @@ -59,31 +59,23 @@ class IAXAccount; class IAXVoIPLink : public VoIPLink { public: - /** - * Constructor - * @param accountID The account containing the voip link - */ IAXVoIPLink(const std::string& accountID); - - /** - * Destructor - */ ~IAXVoIPLink(); /** * Listen to events sent by the call manager ( asterisk, etc .. ) */ - void getEvent(void); + void getEvent(); /** * Init the voip link */ - virtual void init(void); + virtual void init(); /** * Terminate a voip link by clearing the call list */ - virtual void terminate(void); + virtual void terminate(); /** * Send out registration @@ -236,7 +228,7 @@ class IAXVoIPLink : public VoIPLink { /** * Work out the audio data from Microphone to IAX2 channel */ - void sendAudioFromMic(void); + void sendAudioFromMic(); /** * Send an outgoing call invite to iax diff --git a/daemon/src/im/instant_messaging.cpp b/daemon/src/im/instant_messaging.cpp index a8403cfb046cd1a09d45170f5818c88dbffdc403..1e30e9c1b56ae4a30c56fd8624f2a64cf6a63b33 100644 --- a/daemon/src/im/instant_messaging.cpp +++ b/daemon/src/im/instant_messaging.cpp @@ -49,14 +49,7 @@ static void XMLCALL startElementCallback(void *userData, const char *name, const } static void XMLCALL endElementCallback(void * /*userData*/, const char * /*name*/) -{ -} - - -InstantMessaging::InstantMessaging() {} - - -InstantMessaging::~InstantMessaging() {} +{} bool InstantMessaging::saveMessage(const std::string& message, const std::string& author, const std::string& id, int mode) { diff --git a/daemon/src/im/instant_messaging.h b/daemon/src/im/instant_messaging.h index 347293788a798765bdacb20fbcccedc7ca0bc8f0..17018b56ca0a03eef17d1620de1c4e51eb8b4267 100644 --- a/daemon/src/im/instant_messaging.h +++ b/daemon/src/im/instant_messaging.h @@ -67,27 +67,15 @@ class InstantMessageException : public std::runtime_error { }; class InstantMessaging { - public: - typedef std::map <std::string, std::string> UriEntry; typedef std::list <UriEntry> UriList; - /* - * Class constructor - */ - InstantMessaging(); - - /* - * Class destructor - */ - ~InstantMessaging(); - /** * Return the maximum number if character for a single SIP MESSAGE. * Longer messages should be splitted in several smaller messages using split_message */ - size_t getMessageMaximumSize(void) { + static size_t getMessageMaximumSize() { return MAXIMUM_MESSAGE_LENGTH; } @@ -161,11 +149,6 @@ class InstantMessaging { * @return A string containing the actual message */ std::string findTextMessage(std::string& text); - - private: - - InstantMessaging(const InstantMessaging&); //No Copy Constructor - InstantMessaging& operator= (const InstantMessaging&); //No Assignment Operator }; } #endif // __INSTANT_MESSAGING_H_ diff --git a/daemon/src/managerimpl.h b/daemon/src/managerimpl.h index eda4145baf501fe05235d67dab86ecdb3f500725..fd17a44d6e9dc65bf105a7e0435877a320994c00 100644 --- a/daemon/src/managerimpl.h +++ b/daemon/src/managerimpl.h @@ -730,13 +730,13 @@ class ManagerImpl { * Get the desktop mail notification level * @return int The mail notification level */ - int32_t getMailNotify(void) const; + int32_t getMailNotify() const; /** * Get the list of the active codecs * @return std::vector< ::std::string > The list of active codecs */ - std::vector<std::string> getActiveCodecList(void) const; + std::vector<std::string> getActiveCodecList() const; /** * Retrieve in the configuration tree the value of a parameter in a specific section diff --git a/daemon/src/sip/sdes_negotiator.cpp b/daemon/src/sip/sdes_negotiator.cpp index 0bb8e8d587868d0f1ab806ad79c3cfcb91ff06aa..213a676532d274b21b64cdc93801b3f7c24f05d6 100644 --- a/daemon/src/sip/sdes_negotiator.cpp +++ b/daemon/src/sip/sdes_negotiator.cpp @@ -41,13 +41,11 @@ using namespace sfl; SdesNegotiator::SdesNegotiator(const std::vector<CryptoSuiteDefinition>& localCapabilites, const std::vector<std::string>& remoteAttribute) : - _remoteAttribute(remoteAttribute), - _localCapabilities(localCapabilites) -{ - -} + remoteAttribute_(remoteAttribute), + localCapabilities_(localCapabilites) +{} -std::vector<CryptoAttribute *> SdesNegotiator::parse(void) +std::vector<CryptoAttribute *> SdesNegotiator::parse() { // The patterns below try to follow // the ABNF grammar rules described in @@ -62,7 +60,6 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse(void) * keyParamsPattern; try { - // used to match white space (which are used as separator) generalSyntaxPattern = new Pattern("[\x20\x09]+", "g"); @@ -81,19 +78,7 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse(void) "(?P<mkiValue>[0-9]+)\\:" \ "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); - /* - sessionParamPattern = new Pattern ( - "(?P<sessionParam>(kdr\\=[0-9]{1,2}|" \ - "UNENCRYPTED_SRTP|" \ - "UNENCRYPTED_SRTCP|" \ - "UNAUTHENTICATED_SRTP|" \ - "FEC_ORDER=(?P<fecOrder>FEC_SRTP|SRTP_FEC)|" \ - "FEC_KEY=(?P<fecKey>" + keyParamsPattern->getPattern() + ")|" \ - "WSH=(?P<wsh>[0-9]{1,2})|" \ - "(?<!\\-)[[:graph:]]+))*", "g"); // srtp-session-extension - */ - - } catch (compile_error& exception) { + } catch (const compile_error& exception) { throw parse_error("A compile exception occured on a pattern."); } @@ -102,10 +87,10 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse(void) // and parse its content - std::vector<std::string>::iterator iter; std::vector<CryptoAttribute *> cryptoAttributeVector; - for (iter = _remoteAttribute.begin(); iter != _remoteAttribute.end(); iter++) { + for (std::vector<std::string>::iterator iter = remoteAttribute_.begin(); + iter != remoteAttribute_.end(); ++iter) { // Split the line into its component // that we will analyze further down. @@ -116,14 +101,12 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse(void) try { sdesLine = generalSyntaxPattern->split(); - if (sdesLine.size() < 3) { + if (sdesLine.size() < 3) throw parse_error("Missing components in SDES line"); - } - } catch (match_error& exception) { + } catch (const 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); @@ -133,12 +116,11 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse(void) if (tagPattern->matches()) { try { tag = tagPattern->group("tag"); - } catch (match_error& exception) { + } catch (const match_error& exception) { throw parse_error("Error while parsing the tag field"); } - } else { + } else return cryptoAttributeVector; - } // Check if the crypto suite is valid and retreive // its value. @@ -149,12 +131,11 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse(void) if (cryptoSuitePattern->matches()) { try { cryptoSuite = cryptoSuitePattern->group("cryptoSuite"); - } catch (match_error& exception) { + } catch (const match_error& exception) { throw parse_error("Error while parsing the crypto-suite field"); } - } else { + } else return cryptoAttributeVector; - } // Parse one or more key-params field. *keyParamsPattern << sdesLine.at(2); @@ -173,28 +154,10 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse(void) mkiValue = keyParamsPattern->group("mkiValue"); mkiLength = keyParamsPattern->group("mkiLength"); } - } catch (match_error& exception) { + } catch (const match_error& exception) { throw parse_error("Error while parsing the key-params field"); } - /** - * Parse the optional session-param fields - * @TODO Implement this ! - */ - /* - if (sdesLine.size() == 3) continue; - - int i; - for (i = 3; i < sdesLine.size(); i++) { - sessionParamPattern << sdesLine.at(i); - while (sessionpParamPattern.matches()) { - - } catch (match_error& exception) { - throw parse_error("Error while parsing the crypto-suite field"); - } - } - } */ - // Add the new CryptoAttribute to the vector CryptoAttribute * cryptoAttribute = new CryptoAttribute(tag, cryptoSuite, srtpKeyMethod, srtpKeyInfo, lifetime, mkiValue, mkiLength); @@ -204,71 +167,40 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse(void) return cryptoAttributeVector; } -bool SdesNegotiator::negotiate(void) +bool SdesNegotiator::negotiate() { std::vector<CryptoAttribute *> cryptoAttributeVector = parse(); std::vector<CryptoAttribute *>::iterator iter_offer = cryptoAttributeVector.begin(); - std::vector<CryptoSuiteDefinition>::iterator iter_local = _localCapabilities.begin(); + std::vector<CryptoSuiteDefinition>::iterator iter_local = localCapabilities_.begin(); bool negotiationSuccess = false; try { - while (!negotiationSuccess && (iter_offer != cryptoAttributeVector.end())) { + iter_local = localCapabilities_.begin(); - /* - 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(); - - while (!negotiationSuccess && (iter_local != _localCapabilities.end())) { + while (!negotiationSuccess && (iter_local != localCapabilities_.end())) { if ((*iter_offer)->getCryptoSuite().compare((*iter_local).name)) { - negotiationSuccess = true; - _cryptoSuite = (*iter_offer)->getCryptoSuite(); - _srtpKeyMethod = (*iter_offer)->getSrtpKeyMethod(); - _srtpKeyInfo = (*iter_offer)->getSrtpKeyInfo(); - // TODO why does there return empty strings - // _lifetime = (*iter_offer)->getLifetime(); - // _mkiValue = (*iter_offer)->getMkiValue(); - // _mkiLength = (*iter_offer)->getMkiLength(); - - _authTagLength = _cryptoSuite.substr(_cryptoSuite.size()-2, 2); - - /* - std::cout << "Negotiate tag: " + (*iter_offer)->getTag() << std::endl; - std::cout << "Crypto Suite: " + _cryptoSuite << std::endl; - std::cout << "SRTP Key Method: " + _srtpKeyMethod << std::endl; - std::cout << "SRTP Key Info: " + _srtpKeyInfo << std::endl; - std::cout << "Lifetime: " + _lifetime << std::endl; - std::cout << "MKI Value: " + _mkiValue << std::endl; - std::cout << "MKI Length: " + _mkiLength << std::endl; - std::cout << "Auth tag length: " + _authTagLength << std::endl; - */ + cryptoSuite_ = (*iter_offer)->getCryptoSuite(); + srtpKeyMethod_ = (*iter_offer)->getSrtpKeyMethod(); + srtpKeyInfo_ = (*iter_offer)->getSrtpKeyInfo(); + authTagLength_ = cryptoSuite_.substr(cryptoSuite_.size()-2, 2); } iter_local++; } - delete(*iter_offer); - iter_offer++; } - } catch (parse_error& exception) { + } catch (const parse_error& exception) { return false; - } catch (match_error& exception) { + } catch (const match_error& exception) { return false; } diff --git a/daemon/src/sip/sdes_negotiator.h b/daemon/src/sip/sdes_negotiator.h index 6c63961e40df8b001ca4b0b6059d65d7915d1817..42d2b66c96aae4c207db996c37073f17682dbea0 100644 --- a/daemon/src/sip/sdes_negotiator.h +++ b/daemon/src/sip/sdes_negotiator.h @@ -152,57 +152,56 @@ class SdesNegotiator { public: SdesNegotiator(const std::vector<CryptoSuiteDefinition>& localCapabilites, const std::vector<std::string>& remoteAttribute); - ~SdesNegotiator() {}; - bool negotiate(void); + bool negotiate(); /** * Return crypto suite after negotiation */ - std::string getCryptoSuite(void) const { - return _cryptoSuite; + std::string getCryptoSuite() const { + return cryptoSuite_; } /** * Return key method after negotiation (most likely inline:) */ - std::string getKeyMethod(void) const { - return _srtpKeyMethod; + std::string getKeyMethod() const { + return srtpKeyMethod_; } /** * Return crypto suite after negotiation */ - std::string getKeyInfo(void) const { - return _srtpKeyInfo; + std::string getKeyInfo() const { + return srtpKeyInfo_; } /** * Return key lifetime after negotiation */ - std::string getLifeTime(void) const { - return _lifetime; + std::string getLifeTime() const { + return lifetime_; } /** * Return mki value after negotiation */ - std::string getMkiValue(void) const { - return _mkiValue; + std::string getMkiValue() const { + return mkiValue_; } /** * Return mki length after negotiation */ - std::string getMkiLength(void) const { - return _mkiLength; + std::string getMkiLength() const { + return mkiLength_; } /** * Authentication tag lenth */ - std::string getAuthTagLength(void) const { - return _authTagLength; + std::string getAuthTagLength() const { + return authTagLength_; } @@ -212,46 +211,46 @@ class SdesNegotiator { * Multiple crypto lines can be sent, and the * prefered method is then chosen from that list. */ - std::vector<std::string> _remoteAttribute; + std::vector<std::string> remoteAttribute_; - std::vector<CryptoSuiteDefinition> _localCapabilities; + std::vector<CryptoSuiteDefinition> localCapabilities_; /** * Selected crypto suite after negotiation */ - std::string _cryptoSuite; + std::string cryptoSuite_; /** * Selected key method after negotiation (most likely inline:) */ - std::string _srtpKeyMethod; + std::string srtpKeyMethod_; /** * Selected crypto suite after negotiation */ - std::string _srtpKeyInfo; + std::string srtpKeyInfo_; /** * Selected key lifetime after negotiation */ - std::string _lifetime; + std::string lifetime_; /** * Selected mki value after negotiation */ - std::string _mkiValue; + std::string mkiValue_; /** * Selected mki length after negotiation */ - std::string _mkiLength; + std::string mkiLength_; /** * Authenticvation tag length in byte */ - std::string _authTagLength; + std::string authTagLength_; - std::vector<CryptoAttribute *> parse(void); + std::vector<CryptoAttribute *> parse(); }; } #endif // __SDES_NEGOTIATOR_H__ diff --git a/daemon/src/sip/sdp.cpp b/daemon/src/sip/sdp.cpp index 89aaca09b3d0a143004020ff3753db03d06c4309..3ada56f849d44b54a8109fc76c091cdff16fdccd 100644 --- a/daemon/src/sip/sdp.cpp +++ b/daemon/src/sip/sdp.cpp @@ -113,7 +113,7 @@ void Sdp::setActiveRemoteSdpSession(const pjmedia_sdp_session *sdp) _error("Sdp: Error: Could not found dtmf event from remote sdp"); } -std::string Sdp::getCodecName(void) const +std::string Sdp::getCodecName() const { try { sfl::AudioCodec *codec = getSessionMedia(); @@ -123,7 +123,7 @@ std::string Sdp::getCodecName(void) const } } -sfl::AudioCodec* Sdp::getSessionMedia(void) const +sfl::AudioCodec* Sdp::getSessionMedia() const { if (sessionAudioMedia_.size() < 1) throw SdpException("No codec description for this media"); diff --git a/daemon/src/sip/sdp.h b/daemon/src/sip/sdp.h index 0bc8d8530b0300c793b35abac587ae4b8aa2f1a7..c6a9f78ca4cfea893d1df8cb71f10ff7fd316d53 100644 --- a/daemon/src/sip/sdp.h +++ b/daemon/src/sip/sdp.h @@ -74,7 +74,7 @@ class Sdp { /** * Accessor for the internal memory pool */ - pj_pool_t *getMemoryPool(void) const { + pj_pool_t *getMemoryPool() const { return memPool_; } @@ -83,7 +83,7 @@ class Sdp { * * @return The structure that describes a SDP session */ - pjmedia_sdp_session *getLocalSdpSession(void) { + pjmedia_sdp_session *getLocalSdpSession() { return localSession_; } @@ -92,7 +92,7 @@ class Sdp { * * @return The structure that describe the SDP session */ - pjmedia_sdp_session *getRemoteSdpSession(void) { + pjmedia_sdp_session *getRemoteSdpSession() { return remoteSession_; } @@ -108,7 +108,7 @@ class Sdp { * * @return pjmedia_sdp_session The negotiated offer */ - pjmedia_sdp_session* getActiveLocalSdpSession(void) { + pjmedia_sdp_session* getActiveLocalSdpSession() { return activeLocalSession_; } @@ -124,7 +124,7 @@ class Sdp { * * @return pjmedia_sdp_session The negotiated offer */ - pjmedia_sdp_session* getActiveRemoteSdpSession(void) { + pjmedia_sdp_session* getActiveRemoteSdpSession() { return activeRemoteSession_; } @@ -132,13 +132,13 @@ class Sdp { /** * Return whether or not the media have been determined for this sdp session */ - bool hasSessionMedia(void) const; + bool hasSessionMedia() const; /** * Return the codec of the first media after negotiation * @throw SdpException */ - sfl::AudioCodec* getSessionMedia(void) const; + sfl::AudioCodec* getSessionMedia() const; /* * On building an invite outside a dialog, build the local offer and create the @@ -158,17 +158,17 @@ class Sdp { /** * Start the sdp negotiation. */ - void startNegotiation(void); + void startNegotiation(); /** * Remove all media in the session media vector. */ - void cleanSessionMedia(void); + void cleanSessionMedia(); /** * Remove all media in local media capability vector */ - void cleanLocalMediaCapabilities(void); + void cleanLocalMediaCapabilities(); /* * Write accessor. Set the local IP address that will be used in the sdp session @@ -180,7 +180,7 @@ class Sdp { /* * Read accessor. Get the local IP address */ - std::string getLocalIP(void) const { + std::string getLocalIP() const { return localIpAddr_; } @@ -194,7 +194,7 @@ class Sdp { /** * @return The published audio port */ - int getLocalPublishedAudioPort(void) const { + int getLocalPublishedAudioPort() const { return localAudioPort_; } @@ -271,7 +271,7 @@ class Sdp { void setMediaTransportInfoFromRemoteSdp(); - std::string getCodecName(void) const; + std::string getCodecName() const; void receivingAnswerAfterInitialOffer(const pjmedia_sdp_session* remote); @@ -354,9 +354,9 @@ class Sdp { */ unsigned int telephoneEventPayload_; - Sdp(const Sdp&); //No Copy Constructor - - Sdp& operator= (const Sdp&); //No Assignment Operator + // noncopyable + Sdp(const Sdp&); + Sdp& operator=(const Sdp&); /* * Build the sdp media section diff --git a/daemon/src/sip/sipaccount.cpp b/daemon/src/sip/sipaccount.cpp index e210faf8e1239c3a01e5ee73ce1e458fb88df202..0f9cfcce665b9efcefc114948dfbf4e7be11f095 100644 --- a/daemon/src/sip/sipaccount.cpp +++ b/daemon/src/sip/sipaccount.cpp @@ -582,7 +582,7 @@ pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum(const std::string& method) return PJSIP_SSL_UNSPECIFIED_METHOD; } -void SIPAccount::initTlsConfiguration(void) +void SIPAccount::initTlsConfiguration() { // TLS listener is unique and should be only modified through IP2IP_PROFILE tlsListenerPort_ = tlsPort_; @@ -605,7 +605,7 @@ void SIPAccount::initTlsConfiguration(void) tlsSetting_.timeout.msec = atol(tlsNegotiationTimeoutMsec_.c_str()); } -void SIPAccount::initStunConfiguration(void) +void SIPAccount::initStunConfiguration() { size_t pos; std::string stunServer, serverName, serverPort; @@ -654,13 +654,13 @@ bool SIPAccount::hostnameMatch(const std::string& hostname) const return hostname == hostname_; } -std::string SIPAccount::getLoginName(void) +std::string SIPAccount::getLoginName() { struct passwd * user_info = getpwuid(getuid()); return user_info ? user_info->pw_name : ""; } -std::string SIPAccount::getFromUri(void) const +std::string SIPAccount::getFromUri() const { std::string scheme; std::string transport; @@ -709,7 +709,7 @@ std::string SIPAccount::getToUri(const std::string& username) const return "<" + scheme + username + (hostname.empty() ? "" : "@") + hostname + transport + ">"; } -std::string SIPAccount::getServerUri(void) const +std::string SIPAccount::getServerUri() const { std::string scheme; std::string transport; @@ -843,7 +843,7 @@ void SIPAccount::setCredentials(const std::vector<std::map<std::string, std::str } } -const std::vector<std::map<std::string, std::string> > &SIPAccount::getCredentials(void) +const std::vector<std::map<std::string, std::string> > &SIPAccount::getCredentials() { return credentials_; } @@ -858,7 +858,7 @@ std::string SIPAccount::getUserAgentName() const return result; } -std::map<std::string, std::string> SIPAccount::getIp2IpDetails(void) const +std::map<std::string, std::string> SIPAccount::getIp2IpDetails() const { assert(accountID_ == IP2IP_PROFILE); std::map<std::string, std::string> ip2ipAccountDetails; diff --git a/daemon/src/sip/sipaccount.h b/daemon/src/sip/sipaccount.h index 03b93a87aa45cef32402a7cfe997b3345f438d85..5ca66094f5a7783f9caece76dbf8a13eed3d58fc 100644 --- a/daemon/src/sip/sipaccount.h +++ b/daemon/src/sip/sipaccount.h @@ -125,8 +125,8 @@ class SIPAccount : public Account { virtual void setAccountDetails(std::map<std::string, std::string> details); virtual std::map<std::string, std::string> getAccountDetails() const; - std::map<std::string, std::string> getIp2IpDetails(void) const; - std::map<std::string, std::string> getTlsSettings(void) const; + std::map<std::string, std::string> getIp2IpDetails() const; + std::map<std::string, std::string> getTlsSettings() const; void setTlsSettings(const std::map<std::string, std::string>& details); /** @@ -154,12 +154,12 @@ class SIPAccount : public Account { * @param none * @return int The number of credentials set for this account. */ - unsigned getCredentialCount(void) const { + unsigned getCredentialCount() const { return credentials_.size(); } void setCredentials(const std::vector<std::map<std::string, std::string> >& details); - const std::vector<std::map<std::string, std::string> > &getCredentials(void); + const std::vector<std::map<std::string, std::string> > &getCredentials(); /** * A client sendings a REGISTER request MAY suggest an expiration @@ -168,7 +168,7 @@ class SIPAccount : public Account { * * @return the expiration value. */ - unsigned getRegistrationExpire(void) const { + unsigned getRegistrationExpire() const { if (registrationExpire_ == 0) return PJSIP_REGC_EXPIRATION_NOT_SPECIFIED; @@ -178,7 +178,7 @@ class SIPAccount : public Account { /** * Doubles the Expiration Interval of Contact Addresses. */ - void doubleRegistrationExpire(void) { + void doubleRegistrationExpire() { registrationExpire_ *= 2; if (registrationExpire_ < 0) @@ -204,7 +204,7 @@ class SIPAccount : public Account { * @param void * @return pjsip_regc* A pointer to the registration structure */ - pjsip_regc* getRegistrationInfo(void) const { + pjsip_regc* getRegistrationInfo() const { return regc_; } @@ -223,7 +223,7 @@ class SIPAccount : public Account { * file, that can be used directly by PJSIP to initialize * TLS transport. */ - const pjsip_tls_setting * getTlsSetting(void) const { + const pjsip_tls_setting * getTlsSetting() const { return &tlsSetting_; } @@ -232,14 +232,14 @@ class SIPAccount : public Account { * file, that can be used directly by PJSIP to initialize * an alternate UDP transport. */ - std::string getStunServer(void) const { + std::string getStunServer() const { return stunServer_; } void setStunServer(const std::string &srv) { stunServer_ = srv; } - pj_str_t getStunServerName(void) const { + pj_str_t getStunServerName() const { return stunServerName_; } @@ -248,7 +248,7 @@ class SIPAccount : public Account { * file, that can be used directly by PJSIP to initialize * an alternate UDP transport. */ - pj_uint16_t getStunPort(void) const { + pj_uint16_t getStunPort() const { return stunPort_; } void setStunPort(pj_uint16_t port) { @@ -259,7 +259,7 @@ class SIPAccount : public Account { * @return bool Tells if current transport for that * account is set to TLS. */ - bool isTlsEnabled(void) const { + bool isTlsEnabled() const { return transportType_ == PJSIP_TRANSPORT_TLS; } @@ -267,7 +267,7 @@ class SIPAccount : public Account { * @return bool Tells if current transport for that * account is set to OTHER. */ - bool isStunEnabled(void) const { + bool isStunEnabled() const { return stunEnabled_; } @@ -280,7 +280,7 @@ class SIPAccount : public Account { * of the host on which the UA is running, since these are not logical * names." */ - std::string getFromUri(void) const; + std::string getFromUri() const; /* * This method adds the correct scheme, hostname and append @@ -300,7 +300,7 @@ class SIPAccount : public Account { * @return pj_str_t "server" uri based on @param hostPort * @param hostPort A string formatted as : "hostname:port" */ - std::string getServerUri(void) const; + std::string getServerUri() const; /** * @param port Optional port. Otherwise set to the port defined for that account. @@ -312,7 +312,7 @@ class SIPAccount : public Account { /** * Get the local interface name on which this account is bound. */ - std::string getLocalInterface(void) const { + std::string getLocalInterface() const { return interface_; } @@ -330,7 +330,7 @@ class SIPAccount : public Account { * actually using. * @return pj_uint16 The port used for that account */ - pj_uint16_t getLocalPort(void) const { + pj_uint16_t getLocalPort() const { return (pj_uint16_t) localPort_; } @@ -347,7 +347,7 @@ class SIPAccount : public Account { * for the chosen SIP transport. * @return pj_uint16 The port used for that account */ - pj_uint16_t getPublishedPort(void) const { + pj_uint16_t getPublishedPort() const { return (pj_uint16_t) publishedPort_; } @@ -364,7 +364,7 @@ class SIPAccount : public Account { * Get the local port for TLS listener. * @return pj_uint16 The port used for that account */ - pj_uint16_t getTlsListenerPort(void) const { + pj_uint16_t getTlsListenerPort() const { return tlsListenerPort_; } @@ -374,7 +374,7 @@ class SIPAccount : public Account { * will be used. * @return std::string The public IPV4 address formatted in the standard dot notation. */ - std::string getPublishedAddress(void) const { + std::string getPublishedAddress() const { return publishedIpAddress_; } @@ -387,27 +387,27 @@ class SIPAccount : public Account { publishedIpAddress_ = publishedIpAddress; } - std::string getServiceRoute(void) const { + std::string getServiceRoute() const { return serviceRoute_; } - DtmfType getDtmfType(void) const { + DtmfType getDtmfType() const { return dtmfType_; } - bool getSrtpEnabled(void) const { + bool getSrtpEnabled() const { return srtpEnabled_; } - std::string getSrtpKeyExchange(void) const { + std::string getSrtpKeyExchange() const { return srtpKeyExchange_; } - bool getSrtpFallback(void) const { + bool getSrtpFallback() const { return srtpFallback_; } - bool getZrtpHelloHash(void) const { + bool getZrtpHelloHash() const { return zrtpHelloHash_; } @@ -427,12 +427,12 @@ class SIPAccount : public Account { * Initializes tls settings from configuration file. * */ - void initTlsConfiguration(void); + void initTlsConfiguration(); /* * Initializes STUN config from the config file */ - void initStunConfiguration(void); + void initStunConfiguration(); /** * If username is not provided, as it happens for Direct ip calls, @@ -440,7 +440,7 @@ class SIPAccount : public Account { * running this program. * @return std::string The login name under which SFLPhone is running. */ - static std::string getLoginName(void); + static std::string getLoginName(); // The pjsip client registration information pjsip_regc *regc_; diff --git a/daemon/src/sip/sipcall.cpp b/daemon/src/sip/sipcall.cpp index 6c2f87cf24b0e5b0aaedaec9fb3c528d4638dbcc..dd31f3bdc387e2db9490d1602a5fc0defc73a56e 100644 --- a/daemon/src/sip/sipcall.cpp +++ b/daemon/src/sip/sipcall.cpp @@ -35,10 +35,15 @@ #include "audio/audiortp/audio_rtp_factory.h" #include "sdp.h" +namespace { + static const int INITIAL_SIZE = 16384; + static const int INCREMENT_SIZE = INITIAL_SIZE; +} + SIPCall::SIPCall(const std::string& id, Call::CallType type, pj_caching_pool *caching_pool) : Call(id, type) , inv(NULL) - , _audiortp(this) - , pool_(pj_pool_create(&caching_pool->factory, id.c_str(), 16384, 16384, NULL)) + , audiortp_(this) + , pool_(pj_pool_create(&caching_pool->factory, id.c_str(), INITIAL_SIZE, INCREMENT_SIZE, NULL)) , local_sdp_(new Sdp(pool_)) { } diff --git a/daemon/src/sip/sipcall.h b/daemon/src/sip/sipcall.h index 5f20bbf478643f2579788745a182000104323a7a..7213957f02ab2dd3d24c09f054ed171d2611844a 100644 --- a/daemon/src/sip/sipcall.h +++ b/daemon/src/sip/sipcall.h @@ -64,21 +64,21 @@ class SIPCall : public Call { /** * Return the local SDP session */ - Sdp* getLocalSDP(void) { + Sdp* getLocalSDP() { return local_sdp_; } /** * Returns a pointer to the AudioRtp object */ - sfl::AudioRtpFactory * getAudioRtp(void) { - return &_audiortp; + sfl::AudioRtpFactory & getAudioRtp() { + return audiortp_; } /** * Return the local memory pool for this call */ - pj_pool_t *getMemoryPool(void) { + pj_pool_t *getMemoryPool() { return pool_; } @@ -98,7 +98,7 @@ class SIPCall : public Call { /** * Audio Rtp Session factory */ - sfl::AudioRtpFactory _audiortp; + sfl::AudioRtpFactory audiortp_; /** * The pool to allocate memory, released once call hang up diff --git a/daemon/src/sip/sipvoiplink.cpp b/daemon/src/sip/sipvoiplink.cpp index a37bc8fcb894264c503d8e95dbf5a15b895d4100..1cc6855cb34b70fe17ddf28b52e89cf3fabdc5f0 100644 --- a/daemon/src/sip/sipvoiplink.cpp +++ b/daemon/src/sip/sipvoiplink.cpp @@ -76,7 +76,7 @@ using namespace sfl; namespace { -static pjsip_transport *_localUDPTransport = NULL; /** The default transport (5060) */ +static pjsip_transport *localUDPTransport_ = NULL; /** The default transport (5060) */ /** A map to retreive SFLphone internal call id * Given a SIP call ID (usefull for transaction sucha as transfer)*/ @@ -96,10 +96,10 @@ void setCallMediaLocal(SIPCall* call, const std::string &localIP); */ std::string fetchHeaderValue(pjsip_msg *msg, std::string field); -static pj_caching_pool pool_cache, *_cp = &pool_cache; -static pj_pool_t *_pool; -static pjsip_endpoint *_endpt; -static pjsip_module _mod_ua; +static pj_caching_pool pool_cache, *cp_ = &pool_cache; +static pj_pool_t *pool_; +static pjsip_endpoint *endpt_; +static pjsip_module mod_ua_; static pj_thread_t *thread; static void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status UNUSED); @@ -108,7 +108,7 @@ static void sdp_create_offer_cb(pjsip_inv_session *inv, pjmedia_sdp_session **p_ static void invite_session_state_changed_cb(pjsip_inv_session *inv, pjsip_event *e); static void outgoing_request_forked_cb(pjsip_inv_session *inv, pjsip_event *e); static void transaction_state_changed_cb(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e); -static void registration_cb(struct pjsip_regc_cbparam *param); +static void registration_cb(pjsip_regc_cbparam *param); static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata); static pj_bool_t transaction_response_cb(pjsip_rx_data *rdata UNUSED) ; @@ -180,32 +180,32 @@ SIPVoIPLink::SIPVoIPLink() : evThread_(new EventThread(this)) pj_log_set_level(6); // From 0 (min) to 6 (max) TRY(pjnath_init()); - pj_caching_pool_init(_cp, &pj_pool_factory_default_policy, 0); - _pool = pj_pool_create(&_cp->factory, "sflphone", 4000, 4000, NULL); + pj_caching_pool_init(cp_, &pj_pool_factory_default_policy, 0); + pool_ = pj_pool_create(&cp_->factory, "sflphone", 4000, 4000, NULL); - if (!_pool) + if (!pool_) throw VoipLinkException("UserAgent: Could not initialize memory pool"); - TRY(pjsip_endpt_create(&_cp->factory, pj_gethostname()->ptr, &_endpt)); + TRY(pjsip_endpt_create(&cp_->factory, pj_gethostname()->ptr, &endpt_)); if (loadSIPLocalIP().empty()) throw VoipLinkException("UserAgent: Unable to determine network capabilities"); - TRY(pjsip_tsx_layer_init_module(_endpt)); - TRY(pjsip_ua_init_module(_endpt, NULL)); - TRY(pjsip_replaces_init_module(_endpt)); // See the Replaces specification in RFC 3891 - TRY(pjsip_100rel_init_module(_endpt)); + TRY(pjsip_tsx_layer_init_module(endpt_)); + TRY(pjsip_ua_init_module(endpt_, NULL)); + TRY(pjsip_replaces_init_module(endpt_)); // See the Replaces specification in RFC 3891 + TRY(pjsip_100rel_init_module(endpt_)); // Initialize and register sflphone module - _mod_ua.name = pj_str((char*) PACKAGE); - _mod_ua.id = -1; - _mod_ua.priority = PJSIP_MOD_PRIORITY_APPLICATION; - _mod_ua.on_rx_request = &transaction_request_cb; - _mod_ua.on_rx_response = &transaction_response_cb; - TRY(pjsip_endpt_register_module(_endpt, &_mod_ua)); + mod_ua_.name = pj_str((char*) PACKAGE); + mod_ua_.id = -1; + mod_ua_.priority = PJSIP_MOD_PRIORITY_APPLICATION; + mod_ua_.on_rx_request = &transaction_request_cb; + mod_ua_.on_rx_response = &transaction_response_cb; + TRY(pjsip_endpt_register_module(endpt_, &mod_ua_)); - TRY(pjsip_evsub_init_module(_endpt)); - TRY(pjsip_xfer_init_module(_endpt)); + TRY(pjsip_evsub_init_module(endpt_)); + TRY(pjsip_xfer_init_module(endpt_)); static const pjsip_inv_callback inv_cb = { invite_session_state_changed_cb, @@ -217,20 +217,20 @@ SIPVoIPLink::SIPVoIPLink() : evThread_(new EventThread(this)) NULL, NULL, }; - TRY(pjsip_inv_usage_init(_endpt, &inv_cb)); + TRY(pjsip_inv_usage_init(endpt_, &inv_cb)); static const pj_str_t allowed[] = { { (char*) "INFO", 4}, { (char*) "REGISTER", 8}, { (char*) "OPTIONS", 7}, { (char*) "MESSAGE", 7 } }; // //{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6} - pjsip_endpt_add_capability(_endpt, &_mod_ua, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE(allowed), allowed); + pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE(allowed), allowed); static const pj_str_t text_plain = { (char*) "text/plain", 10 }; - pjsip_endpt_add_capability(_endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &text_plain); + pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ACCEPT, NULL, 1, &text_plain); static const pj_str_t accepted = { (char*) "application/sdp", 15 }; - pjsip_endpt_add_capability(_endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &accepted); + pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ACCEPT, NULL, 1, &accepted); _debug("UserAgent: pjsip version %s for %s initialized", pj_get_version(), PJ_OS_NAME); - TRY(pjsip_replaces_init_module(_endpt)); + TRY(pjsip_replaces_init_module(endpt_)); evThread_->start(); } @@ -242,11 +242,11 @@ SIPVoIPLink::~SIPVoIPLink() pj_thread_destroy(thread); const pj_time_val tv = {0, 10}; - pjsip_endpt_handle_events(_endpt, &tv); - pjsip_endpt_destroy(_endpt); + pjsip_endpt_handle_events(endpt_, &tv); + pjsip_endpt_destroy(endpt_); - pj_pool_release(_pool); - pj_caching_pool_destroy(_cp); + pj_pool_release(pool_); + pj_caching_pool_destroy(cp_); pj_shutdown(); } @@ -275,7 +275,7 @@ SIPVoIPLink::getEvent() pj_thread_register(NULL, desc, &thread); static const pj_time_val timeout = {0, 10}; - pjsip_endpt_handle_events(_endpt, &timeout); + pjsip_endpt_handle_events(endpt_, &timeout); } void SIPVoIPLink::sendRegister(Account *a) @@ -288,7 +288,7 @@ void SIPVoIPLink::sendRegister(Account *a) pjsip_regc *regc = account->getRegistrationInfo(); - if (pjsip_regc_create(_endpt, (void *) account, ®istration_cb, ®c) != PJ_SUCCESS) + if (pjsip_regc_create(endpt_, (void *) account, ®istration_cb, ®c) != PJ_SUCCESS) throw VoipLinkException("UserAgent: Unable to create regc structure."); std::string srvUri(account->getServerUri()); @@ -306,7 +306,7 @@ void SIPVoIPLink::sendRegister(Account *a) throw VoipLinkException("Unable to initialize account registration structure"); if (!account->getServiceRoute().empty()) - pjsip_regc_set_route_set(regc, createRouteSet(account->getServiceRoute(), _pool)); + pjsip_regc_set_route_set(regc, createRouteSet(account->getServiceRoute(), pool_)); pjsip_regc_set_credentials(regc, account->getCredentialCount(), account->getCredInfo()); @@ -317,7 +317,7 @@ void SIPVoIPLink::sendRegister(Account *a) pj_str_t pJuseragent = pj_str((char*)useragent.c_str()); const pj_str_t STR_USER_AGENT = { (char*) "User-Agent", 10 }; - pjsip_generic_string_hdr *h = pjsip_generic_string_hdr_create(_pool, &STR_USER_AGENT, &pJuseragent); + pjsip_generic_string_hdr *h = pjsip_generic_string_hdr_create(pool_, &STR_USER_AGENT, &pJuseragent); pj_list_push_back(&hdr_list, (pjsip_hdr*) h); pjsip_regc_add_headers(regc, &hdr_list); @@ -327,7 +327,7 @@ void SIPVoIPLink::sendRegister(Account *a) if (pjsip_regc_register(regc, PJ_TRUE, &tdata) != PJ_SUCCESS) throw VoipLinkException("Unable to initialize transaction data for account registration"); - if (pjsip_regc_set_transport(regc, initTransportSelector(account->transport_, _pool)) != PJ_SUCCESS) + if (pjsip_regc_set_transport(regc, initTransportSelector(account->transport_, pool_)) != PJ_SUCCESS) throw VoipLinkException("Unable to set transport"); // decrease transport's ref count, counter incrementation is managed when acquiring transport @@ -378,7 +378,7 @@ Call *SIPVoIPLink::newOutgoingCall(const std::string& id, const std::string& toU if (account == NULL) // TODO: We should investigate how we could get rid of this error and create a IP2IP call instead throw VoipLinkException("Could not get account for this call"); - SIPCall* call = new SIPCall(id, Call::Outgoing, _cp); + SIPCall* call = new SIPCall(id, Call::Outgoing, cp_); // If toUri is not a well formated sip URI, use account information to process it std::string toUri; @@ -416,10 +416,10 @@ Call *SIPVoIPLink::newOutgoingCall(const std::string& id, const std::string& toU } try { - call->getAudioRtp()->initAudioRtpConfig(); - call->getAudioRtp()->initAudioSymmetricRtpSession(); - call->getAudioRtp()->initLocalCryptoInfo(); - call->getAudioRtp()->start(static_cast<sfl::AudioCodec *>(audiocodec)); + call->getAudioRtp().initAudioRtpConfig(); + call->getAudioRtp().initAudioSymmetricRtpSession(); + call->getAudioRtp().initLocalCryptoInfo(); + call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec)); } catch (...) { delete call; throw VoipLinkException("Could not start rtp session for early media"); @@ -490,10 +490,10 @@ SIPVoIPLink::hangup(const std::string& id) return; // Make sure user data is NULL in callbacks - inv->mod_data[_mod_ua.id] = NULL; + inv->mod_data[mod_ua_.id] = NULL; if (Manager::instance().isCurrentCall(id)) - call->getAudioRtp()->stop(); + call->getAudioRtp().stop(); removeCall(id); } @@ -513,10 +513,10 @@ SIPVoIPLink::peerHungup(const std::string& id) return; // Make sure user data is NULL in callbacks - call->inv->mod_data[_mod_ua.id ] = NULL; + call->inv->mod_data[mod_ua_.id ] = NULL; if (Manager::instance().isCurrentCall(id)) - call->getAudioRtp()->stop(); + call->getAudioRtp().stop(); removeCall(id); } @@ -526,7 +526,7 @@ SIPVoIPLink::onhold(const std::string& id) { SIPCall *call = getSIPCall(id); call->setState(Call::Hold); - call->getAudioRtp()->stop(); + call->getAudioRtp().stop(); Sdp *sdpSession = call->getLocalSDP(); @@ -563,10 +563,9 @@ SIPVoIPLink::offhold(const std::string& id) if (audiocodec == NULL) throw VoipLinkException("Could not instantiate codec"); - call->getAudioRtp()->initAudioRtpConfig(); - call->getAudioRtp()->initAudioSymmetricRtpSession(); - call->getAudioRtp()->start(static_cast<sfl::AudioCodec *>(audiocodec)); - + call->getAudioRtp().initAudioRtpConfig(); + call->getAudioRtp().initAudioSymmetricRtpSession(); + call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec)); } catch (const SdpException &e) { _error("UserAgent: Exception: %s", e.what()); } catch (...) { @@ -619,7 +618,7 @@ SIPVoIPLink::transferCommon(SIPCall *call, pj_str_t *dst) * because after this function, we can no find the cooresponding * voiplink from the call any more. But the voiplink is useful! */ - pjsip_evsub_set_mod_data(sub, _mod_ua.id, this); + pjsip_evsub_set_mod_data(sub, mod_ua_.id, this); /* * Create REFER request. @@ -697,7 +696,7 @@ SIPVoIPLink::refuse(const std::string& id) if (!call->isIncoming() or call->getConnectionState() == Call::Connected) return; - call->getAudioRtp()->stop(); + call->getAudioRtp().stop(); pjsip_tx_data *tdata; @@ -708,7 +707,7 @@ SIPVoIPLink::refuse(const std::string& id) return; // Make sure the pointer is NULL in callbacks - call->inv->mod_data[_mod_ua.id] = NULL; + call->inv->mod_data[mod_ua_.id] = NULL; removeCall(id); } @@ -736,7 +735,7 @@ void SIPVoIPLink::dtmfSend(SIPCall *call, char code, DtmfType dtmf) { if (dtmf == OVERRTP) { - call->getAudioRtp()->sendDtmfDigit(code - '0'); + call->getAudioRtp().sendDtmfDigit(code - '0'); return; } @@ -765,7 +764,7 @@ SIPVoIPLink::dtmfSend(SIPCall *call, char code, DtmfType dtmf) if (tdata->msg->body == NULL) pjsip_tx_data_dec_ref(tdata); else - pjsip_dlg_send_request(call->inv->dlg, tdata, _mod_ua.id, NULL); + pjsip_dlg_send_request(call->inv->dlg, tdata, mod_ua_.id, NULL); } bool @@ -804,7 +803,7 @@ SIPVoIPLink::SIPStartCall(SIPCall *call) pjsip_auth_clt_set_credentials(&dialog->auth_sess, account->getCredentialCount(), account->getCredInfo()); - call->inv->mod_data[_mod_ua.id] = call; + call->inv->mod_data[mod_ua_.id] = call; pjsip_tx_data *tdata; @@ -840,7 +839,7 @@ SIPVoIPLink::SIPCallClosed(SIPCall *call) std::string id(call->getCallId()); if (Manager::instance().isCurrentCall(id)) - call->getAudioRtp()->stop(); + call->getAudioRtp().stop(); Manager::instance().peerHungupCall(id); removeCall(id); @@ -875,7 +874,7 @@ bool SIPVoIPLink::SIPNewIpToIpCall(const std::string& id, const std::string& to) if (!account) return false; - SIPCall *call = new SIPCall(id, Call::Outgoing, _cp); + SIPCall *call = new SIPCall(id, Call::Outgoing, cp_); call->setCallConfiguration(Call::IPtoIP); call->initRecFileName(to); @@ -893,10 +892,10 @@ bool SIPVoIPLink::SIPNewIpToIpCall(const std::string& id, const std::string& to) // Audio Rtp Session must be initialized before creating initial offer in SDP session // since SDES require crypto attribute. - call->getAudioRtp()->initAudioRtpConfig(); - call->getAudioRtp()->initAudioSymmetricRtpSession(); - call->getAudioRtp()->initLocalCryptoInfo(); - call->getAudioRtp()->start(static_cast<sfl::AudioCodec *>(audiocodec)); + call->getAudioRtp().initAudioRtpConfig(); + call->getAudioRtp().initAudioSymmetricRtpSession(); + call->getAudioRtp().initLocalCryptoInfo(); + call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec)); // Building the local SDP offer call->getLocalSDP()->setLocalIP(localAddress); @@ -950,7 +949,7 @@ static pj_bool_t stun_sock_on_rx_data_cb(pj_stun_sock *stun_sock UNUSED, void *p pj_status_t SIPVoIPLink::stunServerResolve(SIPAccount *account) { pj_stun_config stunCfg; - pj_stun_config_init(&stunCfg, &_cp->factory, 0, pjsip_endpt_get_ioqueue(_endpt), pjsip_endpt_get_timer_heap(_endpt)); + pj_stun_config_init(&stunCfg, &cp_->factory, 0, pjsip_endpt_get_ioqueue(endpt_), pjsip_endpt_get_timer_heap(endpt_)); static const pj_stun_sock_cb stun_sock_cb = { stun_sock_on_rx_data_cb, @@ -989,7 +988,7 @@ void SIPVoIPLink::createDefaultSipUdpTransport() createUdpTransport(account); assert(account->transport_); - _localUDPTransport = account->transport_; + localUDPTransport_ = account->transport_; } void SIPVoIPLink::createTlsListener(SIPAccount *account, pjsip_tpfactory **listener) @@ -1007,7 +1006,7 @@ void SIPVoIPLink::createTlsListener(SIPAccount *account, pjsip_tpfactory **liste local_addr.sin_port }; - pjsip_tls_transport_start(_endpt, account->getTlsSetting(), &local_addr, &a_name, 1, listener); + pjsip_tls_transport_start(endpt_, account->getTlsSetting(), &local_addr, &a_name, 1, listener); } @@ -1024,7 +1023,8 @@ void SIPVoIPLink::createTlsTransport(SIPAccount *account, std::string remoteAddr if (localTlsListener == NULL) createTlsListener(account, &localTlsListener); - pjsip_endpt_acquire_transport(_endpt, PJSIP_TRANSPORT_TLS, &rem_addr, sizeof(rem_addr), NULL, &account->transport_); + pjsip_endpt_acquire_transport(endpt_, PJSIP_TRANSPORT_TLS, &rem_addr, + sizeof rem_addr, NULL, &account->transport_); } @@ -1051,8 +1051,8 @@ void SIPVoIPLink::createSipTransport(SIPAccount *account) if (account->transport_) pjsip_transport_add_ref(account->transport_); else { - account->transport_ = _localUDPTransport; - account->setLocalPort(_localUDPTransport->local_name.port); + account->transport_ = localUDPTransport_; + account->setLocalPort(localUDPTransport_->local_name.port); } } } @@ -1092,8 +1092,8 @@ void SIPVoIPLink::createUdpTransport(SIPAccount *account) listeningPort }; - pjsip_udp_transport_start(_endpt, &bound_addr, &a_name, 1, &account->transport_); - pjsip_tpmgr_dump_transports(pjsip_endpt_get_tpmgr(_endpt)); // dump debug information to stdout + pjsip_udp_transport_start(endpt_, &bound_addr, &a_name, 1, &account->transport_); + pjsip_tpmgr_dump_transports(pjsip_endpt_get_tpmgr(endpt_)); // dump debug information to stdout if (account->transport_) transportMap_[account->getLocalPort()] = account->transport_; @@ -1137,7 +1137,7 @@ void SIPVoIPLink::createStunTransport(SIPAccount *account) // Query the mapped IP address and port on the 'outside' of the NAT pj_sockaddr_in pub_addr; - if (pjstun_get_mapped_addr(&_cp->factory, 1, &sock, &stunServer, stunPort, &stunServer, stunPort, &pub_addr) != PJ_SUCCESS) { + if (pjstun_get_mapped_addr(&cp_->factory, 1, &sock, &stunServer, stunPort, &stunServer, stunPort, &pub_addr) != PJ_SUCCESS) { _error("Can't contact STUN server"); pj_sock_close(sock); return; @@ -1153,9 +1153,10 @@ void SIPVoIPLink::createStunTransport(SIPAccount *account) account->setPublishedAddress(listeningAddress); account->setPublishedPort(a_name.port); - pjsip_udp_transport_attach2(_endpt, PJSIP_TRANSPORT_UDP, sock, &a_name, 1, &account->transport_); + pjsip_udp_transport_attach2(endpt_, PJSIP_TRANSPORT_UDP, sock, &a_name, 1, + &account->transport_); - pjsip_tpmgr_dump_transports(pjsip_endpt_get_tpmgr(_endpt)); + pjsip_tpmgr_dump_transports(pjsip_endpt_get_tpmgr(endpt_)); } @@ -1174,7 +1175,7 @@ void SIPVoIPLink::findLocalAddressFromUri(const std::string& uri, pjsip_transpor ss << DEFAULT_SIP_PORT; port = ss.str(); - pjsip_uri *genericUri = pjsip_parse_uri(_pool, (char*)uri.data(), uri.size(), 0); + pjsip_uri *genericUri = pjsip_parse_uri(pool_, (char*)uri.data(), uri.size(), 0); const pj_str_t *pjMachineName = pj_gethostname(); addr = std::string(pjMachineName->ptr, pjMachineName->slen); @@ -1196,25 +1197,25 @@ void SIPVoIPLink::findLocalAddressFromUri(const std::string& uri, pjsip_transpor port = ss.str(); } else { if (transport == NULL) - transport = _localUDPTransport; + transport = localUDPTransport_; transportType = PJSIP_TRANSPORT_UDP; } - pjsip_tpmgr *tpmgr = pjsip_endpt_get_tpmgr(_endpt); + pjsip_tpmgr *tpmgr = pjsip_endpt_get_tpmgr(endpt_); if (!tpmgr) return; pjsip_tpselector *tp_sel = NULL; - if (transportType == PJSIP_TRANSPORT_UDP && transport) - tp_sel = initTransportSelector(transport, _pool); + if (transportType == PJSIP_TRANSPORT_UDP and transport) + tp_sel = initTransportSelector(transport, pool_); pj_str_t localAddress; int i_port; - if (pjsip_tpmgr_find_local_addr(tpmgr, _pool, transportType, tp_sel, &localAddress, &i_port) != PJ_SUCCESS) + if (pjsip_tpmgr_find_local_addr(tpmgr, pool_, transportType, tp_sel, &localAddress, &i_port) != PJ_SUCCESS) return; addr = std::string(localAddress.ptr, localAddress.slen); @@ -1276,7 +1277,7 @@ int SIPSessionReinvite(SIPCall *call) void invite_session_state_changed_cb(pjsip_inv_session *inv, pjsip_event *e) { - SIPCall *call = reinterpret_cast<SIPCall*>(inv->mod_data[_mod_ua.id]); + SIPCall *call = reinterpret_cast<SIPCall*>(inv->mod_data[mod_ua_.id]); if (call == NULL) return; @@ -1332,7 +1333,7 @@ void invite_session_state_changed_cb(pjsip_inv_session *inv, pjsip_event *e) void sdp_request_offer_cb(pjsip_inv_session *inv, const pjmedia_sdp_session *offer) { - SIPCall *call = (SIPCall*) inv->mod_data[_mod_ua.id ]; + SIPCall *call = (SIPCall*) inv->mod_data[mod_ua_.id ]; if (!call) return; @@ -1348,7 +1349,7 @@ void sdp_request_offer_cb(pjsip_inv_session *inv, const pjmedia_sdp_session *off static void sdp_create_offer_cb(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer) { - SIPCall *call = reinterpret_cast<SIPCall*>(inv->mod_data[_mod_ua.id]); + SIPCall *call = reinterpret_cast<SIPCall*>(inv->mod_data[mod_ua_.id]); std::string accountid(Manager::instance().getAccountFromCall(call->getCallId())); SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(accountid)); @@ -1376,7 +1377,7 @@ void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status) const pjmedia_sdp_session *remote_sdp; const pjmedia_sdp_session *local_sdp; - SIPCall *call = reinterpret_cast<SIPCall *>(inv->mod_data[_mod_ua.id]); + SIPCall *call = reinterpret_cast<SIPCall *>(inv->mod_data[mod_ua_.id]); if (call == NULL) { _debug("UserAgent: Call declined by peer, SDP negotiation stopped"); @@ -1419,8 +1420,8 @@ void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status) // Update internal field for sdpSession->setMediaTransportInfoFromRemoteSdp(); - call->getAudioRtp()->updateDestinationIpAddress(); - call->getAudioRtp()->setDtmfPayloadType(sdpSession->getTelephoneEventType()); + call->getAudioRtp().updateDestinationIpAddress(); + call->getAudioRtp().setDtmfPayloadType(sdpSession->getTelephoneEventType()); // Get the crypto attribute containing srtp's cryptographic context (keys, cipher) CryptoOffer crypto_offer; @@ -1441,7 +1442,7 @@ void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status) nego_success = true; try { - call->getAudioRtp()->setRemoteCryptoInfo(sdesnego); + call->getAudioRtp().setRemoteCryptoInfo(sdesnego); } catch (...) {} Manager::instance().getDbusManager()->getCallManager()->secureSdesOn(call->getCallId()); @@ -1452,14 +1453,14 @@ void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status) // We did not found any crypto context for this media, RTP fallback - if (!nego_success && call->getAudioRtp()->isSdesEnabled()) { - call->getAudioRtp()->stop(); - call->getAudioRtp()->setSrtpEnabled(false); + if (!nego_success && call->getAudioRtp().isSdesEnabled()) { + call->getAudioRtp().stop(); + call->getAudioRtp().setSrtpEnabled(false); std::string accountID = Manager::instance().getAccountFromCall(call->getCallId()); if (((SIPAccount *) Manager::instance().getAccount(accountID))->getSrtpFallback()) - call->getAudioRtp()->initAudioSymmetricRtpSession(); + call->getAudioRtp().initAudioSymmetricRtpSession(); } if (!sdpSession) @@ -1477,9 +1478,9 @@ void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status) int pl = sessionMedia->getPayloadType(); - if (pl != call->getAudioRtp()->getSessionMedia()) { + if (pl != call->getAudioRtp().getSessionMedia()) { sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(pl); - call->getAudioRtp()->updateSessionMedia(static_cast<sfl::AudioCodec *>(audiocodec)); + call->getAudioRtp().updateSessionMedia(static_cast<sfl::AudioCodec *>(audiocodec)); } } catch (const SdpException &e) { _error("UserAgent: Exception: %s", e.what()); @@ -1533,7 +1534,7 @@ void transaction_state_changed_cb(pjsip_inv_session *inv UNUSED, pjsip_transacti std::string formatedMessage = (char*) r_data->msg_info.msg->body->data; // Try to determine who is the recipient of the message - SIPCall *call = reinterpret_cast<SIPCall *>(inv->mod_data[_mod_ua.id]); + SIPCall *call = reinterpret_cast<SIPCall *>(inv->mod_data[mod_ua_.id]); if (!call) return; @@ -1644,7 +1645,7 @@ static void handleIncomingOptions(pjsip_rx_data *rdata) { pjsip_tx_data *tdata; - if (pjsip_endpt_create_response(_endpt, rdata, PJSIP_SC_OK, NULL, &tdata) != PJ_SUCCESS) + if (pjsip_endpt_create_response(endpt_, rdata, PJSIP_SC_OK, NULL, &tdata) != PJ_SUCCESS) return; #define ADD_HDR(hdr) do { \ @@ -1652,7 +1653,7 @@ static void handleIncomingOptions(pjsip_rx_data *rdata) if (cap_hdr) \ pjsip_msg_add_hdr (tdata->msg, (pjsip_hdr*) pjsip_hdr_clone (tdata->pool, cap_hdr)); \ } while(0) -#define ADD_CAP(cap) ADD_HDR(pjsip_endpt_get_capability(_endpt, cap, NULL)); +#define ADD_CAP(cap) ADD_HDR(pjsip_endpt_get_capability(endpt_, cap, NULL)); ADD_CAP(PJSIP_H_ALLOW); ADD_CAP(PJSIP_H_ACCEPT); @@ -1662,7 +1663,7 @@ static void handleIncomingOptions(pjsip_rx_data *rdata) pjsip_response_addr res_addr; pjsip_get_response_addr(tdata->pool, rdata, &res_addr); - if (pjsip_endpt_send_response(_endpt, &res_addr, tdata, NULL, NULL) != PJ_SUCCESS) + if (pjsip_endpt_send_response(endpt_, &res_addr, tdata, NULL, NULL) != PJ_SUCCESS) pjsip_tx_data_dec_ref(tdata); } @@ -1693,14 +1694,14 @@ static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata) Manager::instance().startVoiceMessageNotification(account_id, voicemail); } - pjsip_endpt_respond_stateless(_endpt, rdata, PJSIP_SC_OK, NULL, NULL, NULL); + pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_OK, NULL, NULL, NULL); return true; } else if (method->id == PJSIP_OPTIONS_METHOD) { handleIncomingOptions(rdata); return true; } else if (method->id != PJSIP_INVITE_METHOD && method->id != PJSIP_ACK_METHOD) { - pjsip_endpt_respond_stateless(_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); + pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); return true; } @@ -1713,15 +1714,17 @@ static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata) r_sdp = NULL; if (account->getActiveCodecs().empty()) { - pjsip_endpt_respond_stateless(_endpt, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL, NULL); + pjsip_endpt_respond_stateless(endpt_, rdata, + PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL, + NULL); return false; } // Verify that we can handle the request unsigned options = 0; - if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, _endpt, NULL) != PJ_SUCCESS) { - pjsip_endpt_respond_stateless(_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); + if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, endpt_, NULL) != PJ_SUCCESS) { + pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); return true; } @@ -1730,7 +1733,7 @@ static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata) UrlHook::runAction(Manager::instance().hookPreference.getUrlCommand(), header_value); } - SIPCall* call = new SIPCall(Manager::instance().getNewCallID(), Call::Incoming, _cp); + SIPCall* call = new SIPCall(Manager::instance().getNewCallID(), Call::Incoming, cp_); Manager::instance().associateCallToAccount(call->getCallId(), account_id); // May use the published address as well @@ -1761,8 +1764,8 @@ static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata) call->getLocalSDP()->setLocalIP(addrSdp); - call->getAudioRtp()->initAudioRtpConfig(); - call->getAudioRtp()->initAudioSymmetricRtpSession(); + call->getAudioRtp().initAudioRtpConfig(); + call->getAudioRtp().initAudioSymmetricRtpSession(); if (rdata->msg_info.msg->body) { char sdpbuffer[1000]; @@ -1787,8 +1790,8 @@ static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata) sfl::SdesNegotiator sdesnego(localCapabilities, crypto_offer); if (sdesnego.negotiate()) { - call->getAudioRtp()->setRemoteCryptoInfo(sdesnego); - call->getAudioRtp()->initLocalCryptoInfo(); + call->getAudioRtp().setRemoteCryptoInfo(sdesnego); + call->getAudioRtp().initLocalCryptoInfo(); } } } @@ -1796,22 +1799,21 @@ static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata) call->getLocalSDP()->receiveOffer(r_sdp, account->getActiveCodecs()); sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(PAYLOAD_CODEC_ULAW); - call->getAudioRtp()->start(static_cast<sfl::AudioCodec *>(audiocodec)); + call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec)); pjsip_dialog* dialog; if (pjsip_dlg_create_uas(pjsip_ua_instance(), rdata, NULL, &dialog) != PJ_SUCCESS) { delete call; - pjsip_endpt_respond_stateless(_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL, NULL); + pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL, NULL); return false; - } pjsip_inv_create_uas(dialog, rdata, call->getLocalSDP()->getLocalSdpSession(), 0, &call->inv); PJ_ASSERT_RETURN(pjsip_dlg_set_transport(dialog, tp) == PJ_SUCCESS, 1); - call->inv->mod_data[_mod_ua.id] = call; + call->inv->mod_data[mod_ua_.id] = call; // Check whether Replaces header is present in the request and process accordingly. pjsip_dialog *replaced_dlg; @@ -1819,7 +1821,7 @@ static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata) if (pjsip_replaces_verify_request(rdata, &replaced_dlg, PJ_FALSE, &response) != PJ_SUCCESS) { _error("Something wrong with Replaces request."); - pjsip_endpt_respond_stateless(_endpt, rdata, 500 /* internal server error */, NULL, NULL, NULL); + pjsip_endpt_respond_stateless(endpt_, rdata, 500 /* internal server error */, NULL, NULL, NULL); } // Check if call has been transfered @@ -1859,7 +1861,7 @@ static pj_bool_t transaction_response_cb(pjsip_rx_data *rdata) pjsip_transaction *tsx = pjsip_rdata_get_tsx(rdata); - if (!tsx || tsx->method.id != PJSIP_INVITE_METHOD) + if (!tsx or tsx->method.id != PJSIP_INVITE_METHOD) return PJ_SUCCESS; if (tsx->status_code / 100 == 2) { @@ -1877,7 +1879,7 @@ static pj_bool_t transaction_response_cb(pjsip_rx_data *rdata) void onCallTransfered(pjsip_inv_session *inv, pjsip_rx_data *rdata) { - SIPCall *currentCall = reinterpret_cast<SIPCall *>(inv->mod_data[_mod_ua.id]); + SIPCall *currentCall = reinterpret_cast<SIPCall *>(inv->mod_data[mod_ua_.id]); if (currentCall == NULL) return; @@ -1903,12 +1905,12 @@ void transfer_client_cb(pjsip_evsub *sub, pjsip_event *event) break; case PJSIP_EVSUB_STATE_TERMINATED: - pjsip_evsub_set_mod_data(sub, _mod_ua.id, NULL); + pjsip_evsub_set_mod_data(sub, mod_ua_.id, NULL); break; case PJSIP_EVSUB_STATE_ACTIVE: { - SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *>(pjsip_evsub_get_mod_data(sub, _mod_ua.id)); + SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *>(pjsip_evsub_get_mod_data(sub, mod_ua_.id)); if (!link or !event) return; @@ -1950,7 +1952,7 @@ void transfer_client_cb(pjsip_evsub *sub, pjsip_event *event) pjsip_inv_send_msg(call->inv, tdata); Manager::instance().hangupCall(call->getCallId()); - pjsip_evsub_set_mod_data(sub, _mod_ua.id, NULL); + pjsip_evsub_set_mod_data(sub, mod_ua_.id, NULL); } break; @@ -1997,7 +1999,7 @@ std::string fetchHeaderValue(pjsip_msg *msg, std::string field) } // end anonymous namespace -std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName(void) +std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName() { static ifreq ifreqs[20]; ifconf ifconf; @@ -2042,7 +2044,7 @@ std::string SIPVoIPLink::getInterfaceAddrFromName(const std::string &ifaceName) return inet_ntoa(saddr_in->sin_addr); } -std::vector<std::string> SIPVoIPLink::getAllIpInterface(void) +std::vector<std::string> SIPVoIPLink::getAllIpInterface() { pj_sockaddr addrList[16]; unsigned addrCnt = PJ_ARRAY_SIZE(addrList); diff --git a/daemon/src/sip/sipvoiplink.h b/daemon/src/sip/sipvoiplink.h index f11b182bc7d37ca219fb041335f22fe7d739b45d..cf5fdfb613c8eb1cd98e14209caf0f17165b2c62 100644 --- a/daemon/src/sip/sipvoiplink.h +++ b/daemon/src/sip/sipvoiplink.h @@ -32,8 +32,8 @@ * as that of the covered work. */ -#ifndef SIPVOIPLINK_H -#define SIPVOIPLINK_H +#ifndef SIPVOIPLINK_H_ +#define SIPVOIPLINK_H_ #include <map> @@ -66,10 +66,6 @@ class SIPAccount; class SIPVoIPLink : public VoIPLink { public: - - /** - * Destructor - */ ~SIPVoIPLink(); /** @@ -81,17 +77,17 @@ class SIPVoIPLink : public VoIPLink { /** * Try to initiate the pjsip engine/thread and set config */ - virtual void init(void); + virtual void init(); /** * Shut the library and clean up */ - virtual void terminate(void); + virtual void terminate(); /** * Event listener. Each event send by the call manager is received and handled from here */ - virtual void getEvent(void); + virtual void getEvent(); /** * Build and send SIP registration request @@ -226,7 +222,7 @@ class SIPVoIPLink : public VoIPLink { * of IPV4 address available on all of the interfaces on * the system. */ - static std::vector<std::string> getAllIpInterface(void); + static std::vector<std::string> getAllIpInterface(); /** * List all the interfaces on the system and return @@ -236,7 +232,7 @@ class SIPVoIPLink : public VoIPLink { * of interface name available on all of the interfaces on * the system. */ - static std::vector<std::string> getAllIpInterfaceByName(void); + static std::vector<std::string> getAllIpInterfaceByName(); /** * List all the interfaces on the system and return @@ -353,5 +349,4 @@ class SIPVoIPLink : public VoIPLink { friend class SIPTest; }; - -#endif +#endif // SIPVOIPLINK_H_ diff --git a/daemon/test/historytest.cpp b/daemon/test/historytest.cpp index 670bcc58b9747f7c6e1665dd7d903fec08869858..529237360ef6117d73c7b4f574a47b9724fc2f81 100644 --- a/daemon/test/historytest.cpp +++ b/daemon/test/historytest.cpp @@ -58,7 +58,7 @@ void HistoryTest::test_create_history_path() result = history->create_history_path(path); CPPUNIT_ASSERT(result == 0); CPPUNIT_ASSERT(!history->is_loaded()); - CPPUNIT_ASSERT(history->_history_path == path); + CPPUNIT_ASSERT(history->history_path_ == path); } void HistoryTest::test_load_history_from_file()