From 31997016b985c4a441011e8e3249b2b3d02ccf84 Mon Sep 17 00:00:00 2001
From: yanmorin <yanmorin>
Date: Fri, 28 Oct 2005 18:57:51 +0000
Subject: [PATCH] Try to remove unlock from deamon But it is unstable

---
 src/audio/audiolayer.cpp          | 14 ++++--
 src/audio/audiortp.cpp            |  6 +--
 src/gui/server/requestmanager.cpp |  7 ++-
 src/gui/server/tcpstreampool.cpp  |  3 +-
 src/managerimpl.cpp               | 81 ++++++++++++++++++-------------
 src/managerimpl.h                 | 11 +----
 src/sipcall.h                     |  3 +-
 src/sipvoiplink.cpp               | 34 +++++++------
 src/sipvoiplink.h                 |  9 +---
 src/voIPLink.h                    |  5 +-
 10 files changed, 90 insertions(+), 83 deletions(-)

diff --git a/src/audio/audiolayer.cpp b/src/audio/audiolayer.cpp
index bee238e64c..18ca6f32c6 100644
--- a/src/audio/audiolayer.cpp
+++ b/src/audio/audiolayer.cpp
@@ -111,11 +111,15 @@ void
 AudioLayer::stopStream(void) 
 {
   ost::MutexLock guard(_mutex);
-  if (_stream && !_stream->isStopped()) {
-     _stream->stop();
-    _mainSndRingBuffer.flush();
-    _urgentRingBuffer.flush();
-    _micRingBuffer.flush();
+  try {
+    if (_stream && !_stream->isStopped()) {
+      _stream->stop();
+      _mainSndRingBuffer.flush();
+      _urgentRingBuffer.flush();
+      _micRingBuffer.flush();
+    }
+  } catch (...) {
+    _debug("Portaudio error: error when stoping audiolayer stream\n");
   }
 }
 
diff --git a/src/audio/audiortp.cpp b/src/audio/audiortp.cpp
index 2ef3feea29..3395ae8d9e 100644
--- a/src/audio/audiortp.cpp
+++ b/src/audio/audiortp.cpp
@@ -83,7 +83,7 @@ AudioRtpRTX::AudioRtpRTX (SipCall *sipcall, AudioLayer* driver, bool sym) : _cod
   _debug("AudioRtpRTX ctor : Local IP:port %s:%d\tsymmetric:%d\n", local_ip.getHostname(), _ca->getLocalAudioPort(), _sym);
 
   if (!_sym) {
-    _sessionRecv = new ost::RTPSession(local_ip, _ca->getRemoteSdpAudioPort());
+    _sessionRecv = new ost::RTPSession(local_ip, _ca->getLocalAudioPort());
     _sessionSend = new ost::RTPSession(local_ip, _ca->getLocalAudioPort());
     _session = NULL;
   } else {
@@ -133,9 +133,7 @@ AudioRtpRTX::initAudioRtpSession (void)
   }
 
   if (!_sym) {
-    std::string localipConfig = _ca->getLocalIp();
-    ost::InetHostAddress local_ip(localipConfig.c_str());
-    if ( !_sessionRecv->addDestination(local_ip, (unsigned short) _ca->getLocalAudioPort()) ) {
+    if ( !_sessionRecv->addDestination(remote_ip, (unsigned short) _ca->getRemoteSdpAudioPort()) ) {
       _debug("RTX recv: could not connect to port %d\n",  _ca->getLocalAudioPort());
       return;
     }
diff --git a/src/gui/server/requestmanager.cpp b/src/gui/server/requestmanager.cpp
index 6511c88cfa..436906d9fa 100644
--- a/src/gui/server/requestmanager.cpp
+++ b/src/gui/server/requestmanager.cpp
@@ -38,6 +38,7 @@ RequestManager::~RequestManager()
 int 
 RequestManager::exec() 
 {
+  _debug("Request manager waiting TCP session\n");
   try {
     _stop = false;
     while(std::cin.good() && !_stop) {
@@ -55,6 +56,7 @@ RequestManager::exec()
       Request *request;
 
       _quit = false;
+      _debug("Initiate a new TCP Session... \n");
       _sessionIO->init();
 
       // std::cin.good() is only there to close the server when
@@ -72,16 +74,19 @@ RequestManager::exec()
       } // end streaming
 
       { // session mutex block
+        _debug("Closing TCP Session... \n");
         _sessionMutex.enterMutex(); 
         delete _sessionIO; _sessionIO = NULL;
         _sessionMutex.leaveMutex();
+        _debug("TCP Session has closed\n");
       }
 
     } // end while
- 
+
   } catch(ost::Socket *e) {
     std::cerr << "Exception: " << e->getErrorString() << std::endl;
   }
+  _debug("Request manager has closed\n");
   return 0;
 }
 
diff --git a/src/gui/server/tcpstreampool.cpp b/src/gui/server/tcpstreampool.cpp
index 785f95c2b7..172443c87e 100644
--- a/src/gui/server/tcpstreampool.cpp
+++ b/src/gui/server/tcpstreampool.cpp
@@ -26,6 +26,7 @@ TCPStreamPool::~TCPStreamPool()
   terminate();
   std::string output;
   while (good() && _outputPool.pop(output, WAITING_TIME))  {
+    //_debug("sending last message...\n");
     *this << output << std::endl;
   }
 }
@@ -46,7 +47,7 @@ TCPStreamPool::run() {
       // security check, since we are inside a loop
       if (testCancel() || !good()) {break;}
     }
-    if (_outputPool.pop(output, WAITING_TIME)) {
+    if (good() && _outputPool.pop(output, WAITING_TIME)) {
       //_debug("TCPStreamPool send %s\n", output.c_str());
       *this << output << std::endl;
     }
diff --git a/src/managerimpl.cpp b/src/managerimpl.cpp
index 369cc73879..84f6917c34 100644
--- a/src/managerimpl.cpp
+++ b/src/managerimpl.cpp
@@ -61,12 +61,8 @@
 
 ManagerImpl::ManagerImpl (void)
 {
-  // initialize random generator  
-  srand (time(NULL));
-  
   // Init private variables 
   _error = new Error();
-  _tone = new ToneGenerator();	
 
   _hasZeroconf = false;
 #ifdef USE_ZEROCONF
@@ -74,14 +70,14 @@ ManagerImpl::ManagerImpl (void)
   _DNSService = new DNSService();
 #endif
 
-  _nCodecs = 0;
-  _currentCallId = 0;
-  _startTime = 0;
-  _endTime = 0;
+  // setup
   _path = ""; 
   _exist = 0;
   _setupLoaded = false;
   _gui = NULL;
+
+  // SOUND:
+  _codecMap = CodecDescriptorMap().getMap();
   _audiodriverPA = NULL;
 
   // Initialize after by init() -> initVolume()
@@ -89,41 +85,47 @@ ManagerImpl::ManagerImpl (void)
   _mic_volume  = 0; 
   _mic_volume_before_mute = 0;
 
+  _tone = new ToneGenerator();	
   _toneType = ZT_TONE_NULL;
 
+  // Call
+  _currentCallId = 0;
   _nbIncomingWaitingCall=0;
-
-  _codecMap = CodecDescriptorMap().getMap();
-
   _registerState = UNREGISTERED;
+  _hasTriedToRegister = false;
+  // initialize random generator for call id
+  srand (time(NULL));
 }
 
 // never call if we use only the singleton...
 ManagerImpl::~ManagerImpl (void) 
 {
   terminate();
+  delete _tone;  _tone = NULL;
+
 #ifdef USE_ZEROCONF
   delete _DNSService; _DNSService = NULL;
 #endif
 
-  delete _tone;  _tone = NULL;
   delete _error; _error = NULL;
 
-  _debug("%s stop correctly\n", PROGNAME);
+  _debug("%s stop correctly.\n", PROGNAME);
 }
 
 void 
 ManagerImpl::init() 
 {
-  _debugInit("Volume Initialisation");
   initVolume();
 
   if (_exist == 0) {
     _debug("Cannot create config file in your home directory\n");
-  } 
+  }
+
+  _debugInit("Load Telephone Tone");
+  std::string country = getConfigString(PREFERENCES, ZONE_TONE);
+  _telephoneTone = new TelephoneTone(country);
 
   try {
-    _debugInit("Audio Driver Selection");
     selectAudioDriver();
   }
   catch (const portaudio::PaException &e)
@@ -142,11 +144,10 @@ ManagerImpl::init()
       throw e;
     }
   catch (...)
-    { 
+    {
       displayError("An unknown exception occured.");
       throw;
     }
-  _debugInit("Audio Codec Initialization");
   initAudioCodec();
 
   _debugInit("Adding new VoIP Link");
@@ -155,17 +156,14 @@ ManagerImpl::init()
 
   // initRegisterVoIP was here, but we doing it after the gui loaded... 
   // the stun detection is long, so it's a better idea to do it after getEvents
-
   initZeroconf();
-
-  std::string country = getConfigString(PREFERENCES, ZONE_TONE);
-  _telephoneTone = new TelephoneTone(country);
 }
 
 void ManagerImpl::terminate()
 {
-  delete _telephoneTone; _telephoneTone = 0;
+  saveConfig();
 
+  _debug("Removing VoIP Links...\n");
   for(VoIPLinkVector::iterator pos = _voIPLinkVector.begin();
       pos != _voIPLinkVector.end();
       pos++) {
@@ -174,6 +172,7 @@ void ManagerImpl::terminate()
   }
   _voIPLinkVector.clear();
 
+  _debug("Removing calls\n");
   _mutex.enterMutex();
   for(CallVector::iterator pos = _callVector.begin();
       pos != _callVector.end();
@@ -185,7 +184,11 @@ void ManagerImpl::terminate()
 
   unloadAudioCodec();
 
+  _debug("Unload Audio Driver\n");
   delete _audiodriverPA; _audiodriverPA = NULL;
+
+  _debug("Unload Telephone Tone\n");
+  delete _telephoneTone; _telephoneTone = 0;
 }
 
 void
@@ -447,6 +450,7 @@ ManagerImpl::refuseCall (CALLID id)
 bool
 ManagerImpl::saveConfig (void)
 {
+  _debug("Saving Configuration...\n");
   setConfig(AUDIO, VOLUME_SPKR, getSpkrVolume());
   setConfig(AUDIO, VOLUME_MICRO, getMicVolume());
 
@@ -460,6 +464,7 @@ ManagerImpl::saveConfig (void)
 void 
 ManagerImpl::initRegisterVoIPLink() 
 {
+  _debug("Initiate VoIP Link Registration\n");
   if (_hasTriedToRegister == false) {
    _voIPLinkVector.at(DFT_VOIP_LINK)->init(); // we call here, because it's long...
    if (_voIPLinkVector.at(DFT_VOIP_LINK)->checkNetwork()) {
@@ -481,6 +486,7 @@ ManagerImpl::initRegisterVoIPLink()
 int 
 ManagerImpl::registerVoIPLink (void)
 {
+  _debug("Register VoIP Link\n");
   int returnValue = 0;
   // Cyrille always want to register to receive call | 2005-10-24 10:50
   //if ( !useStun() ) {
@@ -503,6 +509,7 @@ ManagerImpl::registerVoIPLink (void)
 int 
 ManagerImpl::unregisterVoIPLink (void)
 {
+  _debug("Unregister VoIP Link\n");
 	if (_voIPLinkVector.at(DFT_VOIP_LINK)->setUnregister() == 0) {
 		return 1;
 	} else {
@@ -572,7 +579,6 @@ ManagerImpl::playDtmf(char code)
     }
 
     AudioLayer *audiolayer = getAudioDriver();
-    _toneMutex.enterMutex();
 
     // Put buffer to urgentRingBuffer 
     // put the size in bytes...
@@ -593,7 +599,6 @@ ManagerImpl::playDtmf(char code)
     } else {
       audiolayer->sleep(pulselen); // in milliseconds
     }
-    _toneMutex.leaveMutex();
     delete[] buf_ctrl_vol; buf_ctrl_vol = 0;
     returnValue = true;
   }
@@ -858,10 +863,9 @@ ManagerImpl::stopVoiceMessageNotification (void)
  */
 bool 
 ManagerImpl::playATone(Tone::TONEID toneId) {
-  ost::MutexLock m(_toneMutex); 
-  //_toneType = tone;
-  //_tone->toneHandle(_toneType, getConfigString(PREFERENCES, ZONE_TONE));
+  _toneMutex.enterMutex();
   _telephoneTone->setCurrentTone(toneId);
+  _toneMutex.leaveMutex();
   getAudioDriver()->startStream();
   return true;
 }
@@ -871,6 +875,10 @@ ManagerImpl::playATone(Tone::TONEID toneId) {
  */
 void 
 ManagerImpl::stopTone() {
+  _debug("TONE: stop tone/stream...\n");
+  getAudioDriver()->stopStream();
+
+  _debug("TONE: stop tone...\n");
   _toneMutex.enterMutex();
   _telephoneTone->setCurrentTone(Tone::TONE_NULL);
   // for ringing tone..
@@ -879,7 +887,7 @@ ManagerImpl::stopTone() {
     _tone->stopTone();
   }
   _toneMutex.leaveMutex();
-  getAudioDriver()->stopStream();
+  _debug("TONE: tone stopped\n");
 }
 
 /**
@@ -888,6 +896,7 @@ ManagerImpl::stopTone() {
 bool
 ManagerImpl::playTone()
 {
+  _debug("TONE: play dialtone...\n");
   return playATone(Tone::TONE_DIALTONE);
 }
 
@@ -939,6 +948,7 @@ Tone *
 ManagerImpl::getTelephoneTone()
 {
   if(_telephoneTone) {
+    ost::MutexLock m(_toneMutex);
     return _telephoneTone->getCurrentTone();
   }
   else {
@@ -953,14 +963,14 @@ ManagerImpl::getTelephoneTone()
 void
 ManagerImpl::ringtone() 
 {
-  _toneMutex.enterMutex(); 
-  _toneType = ZT_TONE_FILE;
   std::string ringchoice = getConfigString(AUDIO, RING_CHOICE);
   // if there is no / inside the path
   if ( ringchoice.find(DIR_SEPARATOR_CH) == std::string::npos ) {
     // check inside global share directory
     ringchoice = std::string(PROGSHAREDIR) + DIR_SEPARATOR_STR + RINGDIR + DIR_SEPARATOR_STR + ringchoice; 
   }
+  _toneMutex.enterMutex(); 
+  _toneType = ZT_TONE_FILE;
   int play = _tone->playRingtone(ringchoice.c_str());
   _toneMutex.leaveMutex();
   if (play!=1) {
@@ -1134,6 +1144,7 @@ ManagerImpl::initConfigFile (void)
 void
 ManagerImpl::initAudioCodec (void)
 {
+  _debugInit("Load Audio Codecs");
   // TODO: need to be more dynamic...
   _codecDescVector.push_back(new CodecDescriptor(getConfigString(AUDIO, CODEC1)));
   _codecDescVector.push_back(new CodecDescriptor(getConfigString(AUDIO, CODEC2)));
@@ -1146,6 +1157,7 @@ ManagerImpl::initAudioCodec (void)
 void 
 ManagerImpl::unloadAudioCodec()
 {
+  _debug("Unload Audio Codecs\n");
   CodecDescriptorVector::iterator iter = _codecDescVector.begin();
   while(iter!=_codecDescVector.end()) {
     delete *iter; *iter = NULL;
@@ -1163,10 +1175,10 @@ ManagerImpl::selectAudioDriver (void)
 {
 #if defined(AUDIO_PORTAUDIO)
   try {
-    _debugInit("  AudioLayer Creation");
+    _debugInit("AudioLayer Creation");
     _audiodriverPA = new AudioLayer();
     int noDevice = getConfigInt(AUDIO, DRIVER_NAME);
-    _debugInit("  AudioLayer Device Count");
+    _debugInit(" AudioLayer Device Count");
     int nbDevice = portaudio::System::instance().deviceCount();
     if (nbDevice == 0) {
       throw std::runtime_error("Portaudio detect no sound card.");
@@ -1175,7 +1187,7 @@ ManagerImpl::selectAudioDriver (void)
       _setupLoaded = false;
       noDevice = 0;
     }
-    _debugInit("  AudioLayer Opening Device");
+    _debugInit(" AudioLayer Opening Device");
     _audiodriverPA->openDevice(noDevice);
   } catch(...) {
     throw;
@@ -1210,6 +1222,7 @@ ManagerImpl::initZeroconf(void)
 void
 ManagerImpl::initVolume()
 {
+  _debugInit("Initiate Volume\n");
   setSpkrVolume(getConfigInt(AUDIO, VOLUME_SPKR));
   setMicVolume(getConfigInt(AUDIO, VOLUME_MICRO));
 }
diff --git a/src/managerimpl.h b/src/managerimpl.h
index dd903e726d..7cab468ecb 100644
--- a/src/managerimpl.h
+++ b/src/managerimpl.h
@@ -370,20 +370,13 @@ private:
   // Current callid 
 	CALLID _currentCallId;
 
-	/*
-	 * For the call timer
-	 */
-	unsigned int _startTime;
-	unsigned int _endTime;
-
-	/* Path of the ConfigFile 
+	/**
+   * Path of the ConfigFile 
 	 */
 	std::string 	_path;
 	int _exist;
   int _setupLoaded;
 
-	unsigned int _nCodecs;
-
   // To handle volume control
   short _spkr_volume;
   short _mic_volume;
diff --git a/src/sipcall.h b/src/sipcall.h
index f8d9904219..87f2e6fd84 100644
--- a/src/sipcall.h
+++ b/src/sipcall.h
@@ -60,7 +60,7 @@ public:
 	 * Use to answer to an incoming call 
 	 */
 	void  	answeredCall_without_hold (eXosip_event_t *);
-	
+
 	int  	ringingCall			(eXosip_event_t *);
 	int  	receivedAck			(eXosip_event_t *);
 
@@ -144,6 +144,7 @@ private:
   int  	_remote_sdp_audio_port;
   int 	_local_sendrecv;           /* _SENDRECV, _SENDONLY, _RECVONLY */
   int 	_remote_sendrecv;          /* _SENDRECV, _SENDONLY, _RECVONLY */
+
   std::string _localIp;
   std::string _name;   // set by incoming call
   std::string _number; // set by incoming call
diff --git a/src/sipvoiplink.cpp b/src/sipvoiplink.cpp
index 44a399b7cd..d68d0b5deb 100644
--- a/src/sipvoiplink.cpp
+++ b/src/sipvoiplink.cpp
@@ -39,7 +39,7 @@
 #define VOICE_MSG			"Voice-Message"
 #define LENGTH_VOICE_MSG	15
 
-SipVoIPLink::SipVoIPLink()
+SipVoIPLink::SipVoIPLink() : VoIPLink()
 {
   // default _audioRTP object initialization
   _evThread = new EventThread(this);
@@ -70,27 +70,24 @@ bool
 SipVoIPLink::checkNetwork (void) 
 {
   // Set IP address
-  return getLocalIp();
+  return getSipLocalIp();
 }
 
 int
 SipVoIPLink::init (void)
 {
   std::string tmp;
-  int i;
-
   tmp = std::string(PROGNAME) + "/" + std::string(SFLPHONED_VERSION);
 	
-  i = eXosip_init ();
-  _started = true;
-
-  if (i != 0) {
+  if (0 != eXosip_init()) {
     _debug("Could not initialize eXosip\n");
     exit (0);
   }
-	
+  _started = true;
+
   srand (time(NULL));
   //should be NULL or INADDR_ANY for the second parameter?
+  int i;
   i = eXosip_listen_addr(IPPROTO_UDP, NULL, DEFAULT_SIP_PORT, AF_INET, 0);
   if (i != 0) {
     i = eXosip_listen_addr(IPPROTO_UDP, NULL, RANDOM_SIP_PORT, AF_INET, 0);
@@ -114,7 +111,7 @@ SipVoIPLink::init (void)
     eXosip_set_user_agent(tmp.data());
   }
 
-  _debug("Thread: start event thread\n");
+  _debug("SIP VoIP Link: listen to SIP Events\n");
   _evThread->start();
   return 1;
 }
@@ -792,6 +789,7 @@ SipVoIPLink::getEvent (void)
     case REQ_TIMEOUT:
     case TEMP_UNAVAILABLE:
     case ADDR_INCOMPLETE:
+    case NOT_ACCEPTABLE_HERE: // 488
       // Display error on the screen phone
       //Manager::instance().displayError(event->response->reason_phrase);
       Manager::instance().displayErrorText(id, event->response->reason_phrase);
@@ -1255,19 +1253,22 @@ SipVoIPLink::behindNat (void)
 
 /**
  * Get the local Ip by eXosip 
+ * only if the local ip address is to his default value: 127.0.0.1
  * setLocalIpAdress
  * @return false if not found
  */
 bool
-SipVoIPLink::getLocalIp (void) 
+SipVoIPLink::getSipLocalIp (void) 
 {
   bool returnValue = true;
-  char* myIPAddress = new char[65];
-  if (eXosip_guess_localip (AF_INET, myIPAddress, 64) == -1) {
-    returnValue = false;
+  if (getLocalIpAddress() == "127.0.0.1") {
+    char* myIPAddress = new char[65];
+    if (eXosip_guess_localip (AF_INET, myIPAddress, 64) == -1) {
+      returnValue = false;
+    }
+    setLocalIpAddress(std::string(myIPAddress));
+    delete [] myIPAddress; myIPAddress = NULL;
   }
-  setLocalIpAddress(std::string(myIPAddress));
-  delete [] myIPAddress; myIPAddress = NULL;
   return returnValue;
 }
 
@@ -1489,3 +1490,4 @@ SipVoIPLink::findCallIdInitial (eXosip_event_t *e)
   }
   return 0;
 }
+
diff --git a/src/sipvoiplink.h b/src/sipvoiplink.h
index 0046f95e60..8aa704519d 100644
--- a/src/sipvoiplink.h
+++ b/src/sipvoiplink.h
@@ -93,6 +93,7 @@ public:
 	 */
 	int	getLocalPort (void);
 	void setLocalPort (int);
+  bool getSipLocalIp (void);
 
 	/*
 	 * Add a new SipCall at the end of the SipCallVector with identifiant 'id'
@@ -129,14 +130,6 @@ private:
 	 */
 	int behindNat (void);
 
-	/*
-   * To Store the local IP address, and allow to know if the network is 
-	 * available.
-	 *
-	 * Return false if an error occured and true if no error
-	 */	 
-	bool getLocalIp (void);
-
 	/*
 	 * Return -1 if an error occured and 0 if no error
 	 */
diff --git a/src/voIPLink.h b/src/voIPLink.h
index 03b3360136..6621669515 100644
--- a/src/voIPLink.h
+++ b/src/voIPLink.h
@@ -64,10 +64,7 @@ public:
 	void setHostName (const std::string& hostname);
 	std::string getHostName (void);
 	void setLocalIpAddress (const std::string& ipAdress);
-	std::string getLocalIpAddress (void);
-
-	
-protected:
+  std::string getLocalIpAddress (void);
 
 private:
 	void initConstructor(void);
-- 
GitLab