From b39a205e2060030265f621fc57236f3a39c43cbb Mon Sep 17 00:00:00 2001
From: yanmorin <yanmorin>
Date: Fri, 4 Nov 2005 22:22:09 +0000
Subject: [PATCH] Remove debug message Add changes to project files Fix a
 nonat-nonat bug (reinvite)

---
 AUTHORS                          |   1 +
 CHANGES                          |   9 +-
 DEPS                             |   2 +
 src/audio/audiolayer.cpp         |  56 +++---
 src/audio/audiolayer.h           |  19 +-
 src/audio/audiortp.cpp           | 318 ++++++++++++++++---------------
 src/audio/ringbuffer.cpp         |   2 -
 src/audio/tonegenerator.cpp      |   5 +-
 src/global.h                     |  16 +-
 src/gui/server/tcpsessionio.cpp  |   4 -
 src/gui/server/tcpstreampool.cpp |   7 -
 src/managerimpl.cpp              |  74 ++++---
 src/sipcall.cpp                  |  56 +++---
 src/sipvoiplink.cpp              |  81 ++++----
 src/zeroconf/DNSService.cpp      |   9 +-
 15 files changed, 331 insertions(+), 328 deletions(-)

diff --git a/AUTHORS b/AUTHORS
index 301f9be8ac..3e3ab1355d 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -16,6 +16,7 @@ Yan Morin
 (yan dot morin at savoifairelinux dot com)
 	- zeroconf integration
 	- sflphoned deamon
+	- add and improve sip core feature
 	- tests and debugging
 
 
diff --git a/CHANGES b/CHANGES
index e1644f7854..6f1eb920e7 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,4 +1,11 @@
-SFLphoned/SFLphone (0.5) / 2005-10-17
+SFLphoned/SFLphone (0.6)  / 2005-11-04
+	* improve sip protocol
+	* can now receive text message
+	* accept reinvite call
+	* cleaning headers
+	* improving bash launcher script
+
+SFLphoned/SFLphone (0.5a) / 2005-10-17
 	* sflphoned
 	* bug fixes
 	* sflphone-qt
diff --git a/DEPS b/DEPS
index 3308b72d8e..94e54d0478 100644
--- a/DEPS
+++ b/DEPS
@@ -4,3 +4,5 @@ ccRTP 1.3.5: http://sourceforge.net/projects/cplusplus/
 libosip 2.2.1: http://savannah.gnu.org/projects/osip/
 libeXosip2-1.9.1-pre17: http://www.antisip.com/download/
 mDNSResponder87: http://developer.apple.com/darwin/projects/bonjour/
+
+See tools/config.sh
diff --git a/src/audio/audiolayer.cpp b/src/audio/audiolayer.cpp
index 933043f903..f24cb1ef58 100644
--- a/src/audio/audiolayer.cpp
+++ b/src/audio/audiolayer.cpp
@@ -2,17 +2,17 @@
  *  Copyright (C) 2005 Savoir-Faire Linux inc.
  *  Author: Yan Morin <yan.morin@savoirfairelinux.com>
  *  Author: Jerome Oufella <jerome.oufella@savoirfairelinux.com> 
- *                                                                              
+ *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *                                                                              
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *                                                                              
+ *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
@@ -41,7 +41,11 @@ AudioLayer::AudioLayer()
 // Destructor
 AudioLayer::~AudioLayer (void) 
 {
-  portaudio::System::terminate();
+  try {
+    portaudio::System::terminate();
+  } catch (const portaudio::PaException &e) {
+    _debug("Catch an exception when portaudio tried to terminate\n");
+  }
   closeStream();
 }
 
@@ -55,23 +59,12 @@ AudioLayer::closeStream (void)
   }
 }
 
-void
-AudioLayer::listDevices()
-{
-  ost::MutexLock guard(_mutex);
-  portaudio::System::DeviceIterator pos =  portaudio::System::instance().devicesBegin();
-  while(pos != portaudio::System::instance().devicesEnd()) {
-    _debug("AudioLayer: Device (%d) %s\n", pos->index(), pos->name());
-    pos++;
-  }
-
-}
-
 void
 AudioLayer::openDevice (int index) 
 {
   closeStream();
 
+  try {
   // Set up the parameters required to open a (Callback)Stream:
   portaudio::DirectionSpecificStreamParameters 
     outParams(portaudio::System::instance().deviceByIndex(index), 
@@ -84,7 +77,6 @@ AudioLayer::openDevice (int index)
 	     2, portaudio::INT16, true, 
 	     portaudio::System::instance().deviceByIndex(index).defaultLowInputLatency(), 
 	     NULL);
-
 	
   // we could put paFramesPerBufferUnspecified instead of FRAME_PER_BUFFER to be variable
   portaudio::StreamParameters const params(inParams, outParams, 
@@ -95,32 +87,46 @@ AudioLayer::openDevice (int index)
   _stream = new portaudio::MemFunCallbackStream<AudioLayer>(params, 
 							    *this, 
 							    &AudioLayer::audioCallback);
+  } catch(...) {
+    throw;
+  }
 }
 
 void
 AudioLayer::startStream(void) 
 {
-  ost::MutexLock guard(_mutex);
-  if (_stream && !_stream->isActive()) {
-    _debug("starting stream...\n");
-    _stream->start();
+  try {
+    ost::MutexLock guard(_mutex);
+    if (_stream && !_stream->isActive()) {
+      //_debug("Starting sound stream\n");
+        _stream->start();
+    }
+  } catch (const portaudio::PaException &e) {
+    _debugException("Portaudio error: error on starting audiolayer stream");
+    throw;
+  } catch(...) {
+    _debugException("stream start error");
+    throw;
   }
 }
 	
 void
 AudioLayer::stopStream(void) 
 {
-  ost::MutexLock guard(_mutex);
   try {
+    ost::MutexLock guard(_mutex);
     if (_stream && !_stream->isStopped()) {
-      _debug("stopping stream...\n");
       _stream->stop();
       _mainSndRingBuffer.flush();
       _urgentRingBuffer.flush();
       _micRingBuffer.flush();
     }
-  } catch (...) {
-    _debug("Portaudio error: error when stoping audiolayer stream\n");
+  } catch (const portaudio::PaException &e) {
+    _debugException("Portaudio error: error on stoping audiolayer stream");
+    throw;
+  } catch(...) {
+    _debugException("stream stop error");
+    throw;
   }
 }
 
diff --git a/src/audio/audiolayer.h b/src/audio/audiolayer.h
index b444ed8370..8ba2d34370 100644
--- a/src/audio/audiolayer.h
+++ b/src/audio/audiolayer.h
@@ -40,16 +40,15 @@ class RingBuffer;
 
 class AudioLayer {
 public:
-	AudioLayer();
-	~AudioLayer (void);
-
-	void listDevices();
-	void	openDevice 		(int);
-	void 	startStream		(void);
-	void 	stopStream		(void);
-	void    sleep			(int);
-	bool    isStreamActive	        (void);
-	bool    isStreamStopped	        (void);
+  AudioLayer();
+  ~AudioLayer(void);
+
+  void openDevice(int);
+  void startStream(void);
+  void stopStream(void);
+  void sleep(int);
+  bool isStreamActive(void);
+  bool isStreamStopped(void);
 
   void flushMain();
   int putMain(void* buffer, int toCopy);
diff --git a/src/audio/audiortp.cpp b/src/audio/audiortp.cpp
index bba9342fb7..992342192f 100644
--- a/src/audio/audiortp.cpp
+++ b/src/audio/audiortp.cpp
@@ -37,12 +37,13 @@
 ////////////////////////////////////////////////////////////////////////////////
 // AudioRtp                                                          
 ////////////////////////////////////////////////////////////////////////////////
-AudioRtp::AudioRtp () {
-	_RTXThread = 0;
+AudioRtp::AudioRtp ()
+{
+  _RTXThread = 0;
 }
 
 AudioRtp::~AudioRtp (void) {
-	delete _RTXThread; _RTXThread = 0;
+  delete _RTXThread; _RTXThread = 0;
 }
 
 int 
@@ -51,7 +52,7 @@ AudioRtp::createNewSession (SipCall *ca) {
 
   // something should stop the thread before...
   if ( _RTXThread != 0 ) { 
-    _debug("AudioRTP error: try to create a new audio rtp thread...\n");
+    _debug("Try to create a new audio rtp thread...\n");
     return -1; 
   }
 
@@ -59,14 +60,13 @@ AudioRtp::createNewSession (SipCall *ca) {
   _symmetric = Manager::instance().getConfigInt(SIGNALISATION,SYMMETRIC) ? true : false;
   _RTXThread = new AudioRtpRTX (ca, Manager::instance().getAudioDriver(), _symmetric);
 
-  _debug("AudioRtp::createNewSession: starting RTX thread\n");
   try {
     if (_RTXThread->start() != 0) {
-//    if (_RTXThread->start() != 0) {
       return -1;
     }
   } catch(...) {
-    _debug("exception on start?");
+    _debugException("AudioRTP try to start a thread");
+    throw;
   }
   return 0;
 }
@@ -74,10 +74,15 @@ AudioRtp::createNewSession (SipCall *ca) {
 	
 void
 AudioRtp::closeRtpSession () {
+  ost::MutexLock m(_threadMutex);
   // This will make RTP threads finish.
-  _debug("waiting start signal...\n");
-  _debug("receive start signal...");
-  delete _RTXThread; _RTXThread = 0;
+  // _debug("Stopping AudioRTP\n");
+  try {
+    delete _RTXThread; _RTXThread = 0;
+  } catch(...) {
+    _debugException("Exception when stopping audiortp\n");
+    throw;
+  }
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -113,7 +118,7 @@ AudioRtpRTX::~AudioRtpRTX () {
   try {
     this->terminate();
   } catch(...) {
-    _debug("audiortprtx dtor catches an exception\n");
+    _debugException("AudioRTP Thread destructor didn't terminate correctly");
     throw;
   }
   //_debug("terminate audiortprtx ended...\n");
@@ -133,58 +138,52 @@ void
 AudioRtpRTX::initAudioRtpSession (void) 
 {
   try {
-  //_debug("Init audio RTP session\n");
-  ost::InetHostAddress remote_ip(_ca->getRemoteSdpAudioIp());
-  if (!remote_ip) {
-    _debug("RTP: Target IP address [%s] is not correct!\n", _ca->getRemoteSdpAudioIp());
-    return;
-  }
-
-  // Initialization
-  if (!_sym) {
-    _sessionRecv->setSchedulingTimeout (10000);
-    _sessionRecv->setExpireTimeout(1000000);
-
-    _sessionSend->setSchedulingTimeout(10000);
-    _sessionSend->setExpireTimeout(1000000);
-  } else {
-    _session->setSchedulingTimeout(10000);
-    _session->setExpireTimeout(1000000);
-  }
-
-  if (!_sym) {
-    if ( !_sessionRecv->addDestination(remote_ip, (unsigned short) _ca->getRemoteSdpAudioPort()) ) {
-      _debug("RTX recv: could not connect to port %d\n",  _ca->getLocalAudioPort());
+    //_debug("Init audio RTP session\n");
+    ost::InetHostAddress remote_ip(_ca->getRemoteSdpAudioIp());
+    if (!remote_ip) {
+      _debug("AudioRTP Thread Error: Target IP address [%s] is not correct!\n", _ca->getRemoteSdpAudioIp());
       return;
     }
-    if (!_sessionSend->addDestination (remote_ip, (unsigned short) _ca->getRemoteSdpAudioPort())) {
-      _debug("RTX send: could not connect to port %d\n",  _ca->getRemoteSdpAudioPort());
-      return;
+
+    // Initialization
+    if (!_sym) {
+      _sessionRecv->setSchedulingTimeout (10000);
+      _sessionRecv->setExpireTimeout(1000000);
+
+      _sessionSend->setSchedulingTimeout(10000);
+      _sessionSend->setExpireTimeout(1000000);
+    } else {
+      _session->setSchedulingTimeout(10000);
+      _session->setExpireTimeout(1000000);
     }
-    _debug("RTP(Send): Added sessionSend destination %s:%d\n", remote_ip.getHostname(), (unsigned short) _ca->getRemoteSdpAudioPort());
 
-    //setPayloadFormat(StaticPayloadFormat(sptPCMU));
-    //_debug("Payload Format: %d\n", _ca->payload);
-    _sessionRecv->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) _ca->payload));
-    _sessionSend->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) _ca->payload));
+    if (!_sym) {
+      if ( !_sessionRecv->addDestination(remote_ip, (unsigned short) _ca->getRemoteSdpAudioPort()) ) {
+        _debug("AudioRTP Thread Error: could not connect to port %d\n",  _ca->getLocalAudioPort());
+        return;
+      }
+      if (!_sessionSend->addDestination (remote_ip, (unsigned short) _ca->getRemoteSdpAudioPort())) {
+        _debug("AudioRTP Thread Error: could not connect to port %d\n",  _ca->getRemoteSdpAudioPort());
+        return;
+      }
+      //_debug("AudioRTP Thread: Added sessionSend destination %s:%d\n", remote_ip.getHostname(), (unsigned short) _ca->getRemoteSdpAudioPort());
 
-    _sessionSend->setMark(true);
-    //setCancel(cancelImmediate);
-  } else {
+      _sessionRecv->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) _ca->payload));
+      _sessionSend->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) _ca->payload));
 
-    _debug("RTP(Send): Added session destination %s:%d\n", 
-        remote_ip.getHostname(), (unsigned short) _ca->getRemoteSdpAudioPort());
+      _sessionSend->setMark(true);
+    } else {
 
-    if (!_session->addDestination (remote_ip, (unsigned short) _ca->getRemoteSdpAudioPort())) {
-      return;
-    }
+      //_debug("AudioRTP Thread: Added session destination %s:%d\n", remote_ip.getHostname(), (unsigned short) _ca->getRemoteSdpAudioPort());
 
-    _session->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) _ca->payload));
-    //setCancel(cancelImmediate);
-  }
-  _debug("== AudioRtpRTX::initAudioRtpSession end == \n");
+      if (!_session->addDestination (remote_ip, (unsigned short) _ca->getRemoteSdpAudioPort())) {
+        return;
+      }
+
+      _session->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) _ca->payload));
+    }
   } catch(...) {
-    _debug("initAudioRtpSession catch an exception\n");
+    _debugException("AudioRTP initialisation failed");
     throw;
   }
 }
@@ -192,108 +191,115 @@ AudioRtpRTX::initAudioRtpSession (void)
 void
 AudioRtpRTX::sendSessionFromMic (unsigned char* data_to_send, int16* data_from_mic_stereo, int16* data_from_mic_mono, int timestamp)
 {
-  int availBytesFromMic = Manager::instance().getAudioDriver()->canGetMic();
-  int maxBytesToGet = RTP_FRAMES2SEND * 2 * 2; // * channels * int16/byte
-  int bytesAvail;
-
-  // take the lower
-  if (availBytesFromMic < maxBytesToGet) {
-    bytesAvail = availBytesFromMic;
-  } else {
-    bytesAvail = maxBytesToGet;
-  }
-
-  // Get bytes from micRingBuffer to data_from_mic
-  Manager::instance().getAudioDriver()->getMic(data_from_mic_stereo, bytesAvail);
-  // control volume and stereo->mono
-  // the j is in int16 RTP_FRAMES2SEND
-  // data_from_mic_mono = 0 to RTP_FRAME2SEND [in int16]
-  for (int j = 0, k=0; j < bytesAvail/4; j++) {
-    k = j<<1;
-    data_from_mic_mono[j] = (int16)(0.5f*(data_from_mic_stereo[k] + data_from_mic_stereo[k+1]));
-  }
-  if ( bytesAvail != maxBytesToGet ) {
-    // fill end with 0...
-    //_debug("Padding mic: %d bytes\n", (maxBytesToGet-bytesAvail)/2);
-    bzero(data_from_mic_mono + (bytesAvail/4), (maxBytesToGet-bytesAvail)/2);
-  }
-
-  if ( _ca != NULL ) {
-    // Encode acquired audio sample
-    AudioCodec* ac = _ca->getAudioCodec();
-    if ( ac != NULL ) {
-      // for the mono: range = 0 to RTP_FRAME2SEND * sizeof(int16)
-      // codecEncode(char *dest, int16* src, size in bytes of the src)
-      int compSize = ac->codecEncode (data_to_send, data_from_mic_mono, RTP_FRAMES2SEND*2);
-      // encode divise by two
-      // Send encoded audio sample over the network
-      //fprintf(stderr, "m");
-      if (!_sym) {
-        _sessionSend->putData(timestamp, data_to_send, compSize);
-      } else {
-        _session->putData(timestamp, data_to_send, compSize);
+  try {
+    int availBytesFromMic = Manager::instance().getAudioDriver()->canGetMic();
+    int maxBytesToGet = RTP_FRAMES2SEND * 2 * 2; // * channels * int16/byte
+    int bytesAvail;
+  
+    // take the lower
+    if (availBytesFromMic < maxBytesToGet) {
+      bytesAvail = availBytesFromMic;
+    } else {
+      bytesAvail = maxBytesToGet;
+    }
+  
+    // Get bytes from micRingBuffer to data_from_mic
+    Manager::instance().getAudioDriver()->getMic(data_from_mic_stereo, bytesAvail);
+    // control volume and stereo->mono
+    // the j is in int16 RTP_FRAMES2SEND
+    // data_from_mic_mono = 0 to RTP_FRAME2SEND [in int16]
+    for (int j = 0, k=0; j < bytesAvail/4; j++) {
+      k = j<<1;
+      data_from_mic_mono[j] = (int16)(0.5f*(data_from_mic_stereo[k] + data_from_mic_stereo[k+1]));
+    }
+    if ( bytesAvail != maxBytesToGet ) {
+      // fill end with 0...
+      bzero(data_from_mic_mono + (bytesAvail/4), (maxBytesToGet-bytesAvail)/2);
+    }
+  
+    if ( _ca != NULL ) {
+      // Encode acquired audio sample
+      AudioCodec* ac = _ca->getAudioCodec();
+      if ( ac != NULL ) {
+        // for the mono: range = 0 to RTP_FRAME2SEND * sizeof(int16)
+        // codecEncode(char *dest, int16* src, size in bytes of the src)
+        int compSize = ac->codecEncode (data_to_send, data_from_mic_mono, RTP_FRAMES2SEND*2);
+        // encode divise by two
+        // Send encoded audio sample over the network
+        if (!_sym) {
+          _sessionSend->putData(timestamp, data_to_send, compSize);
+        } else {
+          _session->putData(timestamp, data_to_send, compSize);
+        }
+      } else { 
+        _debug("Exception: No AudioCodec for the mic\n"); 
       }
-    } else { 
-      _debug("No AudioCodec for the mic\n"); 
     }
+  } catch(...) {
+    _debugException("AudioRTP sending failed");
+    throw;
   }
 }
 
 void
 AudioRtpRTX::receiveSessionForSpkr (int16* data_for_speakers_stereo, int16* data_for_speakers_recv, int& countTime)
 {
-  const ost::AppDataUnit* adu = NULL;
-  // Get audio data stream
-
-  if (!_sym) {
-    adu = _sessionRecv->getData(_sessionRecv->getFirstTimestamp());
-  } else {
-    adu = _session->getData(_session->getFirstTimestamp());
-  }
-  if (adu == NULL) {
-    return;
-  }
-
-  int payload = adu->getType();
-  unsigned char* data  = (unsigned char*)adu->getData();
-  unsigned int size    = adu->getSize();
-
-	// Decode data with relevant codec
-	int expandedSize = 0;
-	AudioCodec* ac = _codecBuilder.alloc(payload, "");
-  if (ac != NULL) {
-    // codecDecode(int16 *dest, char* src, size in bytes of the src)
-    // decode multiply by two
-    // size shall be RTP_FRAME2SEND or lower
-    expandedSize = ac->codecDecode(data_for_speakers_recv, data, size);
-  }
-  ac = NULL;
-
-  // control volume for speakers and mono->stereo
-  // expandedSize is in bytes for data_for_speakers_recv
-  // data_for_speakers_recv are in int16
-  for (int j = 0, k=0; j < expandedSize/2; j++) {
-    k = j<<1; // fast multiply by two
-    data_for_speakers_stereo[k] = data_for_speakers_stereo[k+1] = data_for_speakers_recv[j];
+  try {
+    const ost::AppDataUnit* adu = NULL;
+    // Get audio data stream
+  
+    if (!_sym) {
+      adu = _sessionRecv->getData(_sessionRecv->getFirstTimestamp());
+    } else {
+      adu = _session->getData(_session->getFirstTimestamp());
+    }
+    if (adu == NULL) {
+      return;
+    }
+  
+    int payload = adu->getType();
+    unsigned char* data  = (unsigned char*)adu->getData();
+    unsigned int size    = adu->getSize();
+  
+    // Decode data with relevant codec
+    int expandedSize = 0;
+    AudioCodec* ac = _codecBuilder.alloc(payload, "");
+    if (ac != NULL) {
+      // codecDecode(int16 *dest, char* src, size in bytes of the src)
+      // decode multiply by two
+      // size shall be RTP_FRAME2SEND or lower
+      expandedSize = ac->codecDecode(data_for_speakers_recv, data, size);
+    }
+    ac = NULL;
+  
+    // control volume for speakers and mono->stereo
+    // expandedSize is in bytes for data_for_speakers_recv
+    // data_for_speakers_recv are in int16
+    for (int j = 0, k=0; j < expandedSize/2; j++) {
+      k = j<<1; // fast multiply by two
+      data_for_speakers_stereo[k] = data_for_speakers_stereo[k+1] = data_for_speakers_recv[j];
+    }
+  
+    // If the current call is the call which is answered
+    // Set decoded data to sound device
+    // expandedSize is in mono/bytes, since we double in stereo, we send two time more
+    Manager::instance().getAudioDriver()->putMain(data_for_speakers_stereo, expandedSize*2);
+    //Manager::instance().getAudioDriver()->startStream();
+ 
+    // Notify (with a beep) an incoming call when there is already a call 
+    countTime += time->getSecond();
+    if (Manager::instance().incomingCallWaiting() > 0) {
+      countTime = countTime % 500; // more often...
+      if (countTime == 0) {
+        Manager::instance().notificationIncomingCall();
+      }
+    }
+  
+    delete adu; adu = NULL;
+  } catch(...) {
+    _debugException("AudioRTP receiving failed");
+    throw;
   }
-
-  // If the current call is the call which is answered
-  // Set decoded data to sound device
-  // expandedSize is in mono/bytes, since we double in stereo, we send two time more
-  //fprintf(stderr, "r");
-  Manager::instance().getAudioDriver()->putMain(data_for_speakers_stereo, expandedSize*2);
-  Manager::instance().getAudioDriver()->startStream();
-
-	// Notify (with a beep) an incoming call when there is already a call 
-	countTime += time->getSecond();
-	if (Manager::instance().incomingCallWaiting() > 0) {
-		countTime = countTime % 500; // more often...
-		if (countTime == 0) {
-			Manager::instance().notificationIncomingCall();
-		}
-	}
-
-	delete adu; adu = NULL;
 }
 
 void
@@ -310,33 +316,33 @@ AudioRtpRTX::run () {
   int16 *data_for_speakers_stereo = new int16[RTP_FRAMES2SEND*2];
 
   try {
-    _debug("Audio RtpRTX is running\n");
+    //_debug("AudioRTP Thread is running\n");
 
     // Init the session
     initAudioRtpSession();
-    _start.post();
 
     // flush stream:
     AudioLayer *audiolayer = Manager::instance().getAudioDriver();
 
     // start running the packet queue scheduler.
-    _debug("Thread: start session of AudioRtpRTX\n");
+    //_debug("AudioRTP Thread started\n");
     if (!_sym) {
       _sessionRecv->startRunning();
       _sessionSend->startRunning();
     } else {
       _session->startRunning();
-      _debug("Session is now: %d active?\n", _session->isActive());
+      //_debug("Session is now: %d active\n", _session->isActive());
     }
-  
+
     int timestamp = 0; // for mic
     int countTime = 0; // for receive
     // TODO: get frameSize from user config 
     int frameSize = 20; // 20ms frames
     TimerPort::setTimer(frameSize);
-  
+
     audiolayer->flushMic();
     audiolayer->startStream();
+    _start.post();
     while (!testCancel()) {
       ////////////////////////////
       // Send session
@@ -356,10 +362,12 @@ AudioRtpRTX::run () {
     //_debug("stop stream for audiortp loop\n");
     audiolayer->stopStream();
   } catch(std::exception &e) {
-    _debug("AudioRTP Thread, run function, has caught an exception here: %s\n", e.what());
+    _start.post();
+    _debug("AudioRTP Thread, run: %s\n", e.what());
     throw;
   } catch(...) {
-    _debug("AudioRTP Thread, run function, has caught an unknown exception here\n");
+    _start.post();
+    _debugException("AudioRTP Thread, run()");
     throw;
   }
   delete [] data_for_speakers_stereo; data_for_speakers_stereo = 0;
diff --git a/src/audio/ringbuffer.cpp b/src/audio/ringbuffer.cpp
index 68893aad3c..fe8f49b9b1 100644
--- a/src/audio/ringbuffer.cpp
+++ b/src/audio/ringbuffer.cpp
@@ -143,8 +143,6 @@ RingBuffer::Get(void *buffer, int toCopy, unsigned short volume) {
       }
       // bcopy(src, dest, len)
       bcopy (mBuffer + mStart, dest, block);
-      //fprintf(stderr, "has %d get %d\t", len, block);
-      //_debug("get %d chars at address %ld, mBufferSize=%d, toCopy=%d\n", block, mBuffer+mStart, mBufferSize, toCopy);
       dest += block;
       mStart = (mStart + block) % mBufferSize;
       toCopy -= block;
diff --git a/src/audio/tonegenerator.cpp b/src/audio/tonegenerator.cpp
index 4b3b4057b9..22c6458004 100644
--- a/src/audio/tonegenerator.cpp
+++ b/src/audio/tonegenerator.cpp
@@ -47,7 +47,7 @@ ToneThread::~ToneThread (void) {
   try {
     terminate();
   } catch (...) {
-    _debug("ToneThread: try to terminate, but catch an exception...\n");
+    _debugException("ToneThread: didn't terminate correctly");
   }
   delete[] buf_ctrl_vol; buf_ctrl_vol=NULL;
 }
@@ -79,7 +79,6 @@ ToneThread::run (void) {
   // int16 are the buf_ctrl_vol 
   //  unsigned char are the sample_ptr inside ringbuffer
   int size_in_char = _size * 2 * (sizeof(int16)/sizeof(unsigned char));
-  //_debug(" size : %d\t size_in_char : %d\n", _size, size_in_char);
 
  	while (!testCancel()) {
     manager.getAudioDriver()->putMain(buf_ctrl_vol, size_in_char);
@@ -331,8 +330,6 @@ ToneGenerator::toneHandle (unsigned int idr, const std::string& zone) {
 
 void
 ToneGenerator::stopTone() {
-  //_currentTone = ZT_TONE_NULL;
-
   //_debug("Thread: delete tonethread\n");
   delete tonethread; tonethread = NULL;
   // we end the last thread
diff --git a/src/global.h b/src/global.h
index 22b59e440c..9ec66d35e5 100644
--- a/src/global.h
+++ b/src/global.h
@@ -27,22 +27,20 @@
 typedef float float32;
 typedef short int16;
 
-#define DEBUG
-#define DEBUG_LEVEL 
+//#define DEBUG
 
 #ifdef DEBUG
-	#define _debug(...)	fprintf(stderr, "[sflphoned] " __VA_ARGS__)
+	#define _debug(...)          fprintf(stderr, "[sflphoned] " __VA_ARGS__)
+  #define _debugException(...) fprintf(stderr, "[sflphoned-exception] " __VA_ARGS__ "\n")
+	#define _debugInit(...)      fprintf(stderr, "[sflphoned-init] " __VA_ARGS__ "\n")
 #else
 	#define _debug(...)
-#endif
-#ifdef DEBUG_LEVEL
-	#define _debugInit(...)	fprintf(stderr, "[sflphoned-init] " __VA_ARGS__ "\n")
-#else
+  #define _debugException(...)
 	#define _debugInit(...)
 #endif
 
-#define SFLPHONED_VERSION "0.5"
-#define SFLPHONED_VERSIONNUM 0x000500
+#define SFLPHONED_VERSION "0.6"
+#define SFLPHONED_VERSIONNUM 0x000600
 
 #define PROGNAME         "sflphoned"
 #define PROGNAME_GLOBAL  "sflphone"
diff --git a/src/gui/server/tcpsessionio.cpp b/src/gui/server/tcpsessionio.cpp
index 8d7559e9cf..dbf0563a89 100644
--- a/src/gui/server/tcpsessionio.cpp
+++ b/src/gui/server/tcpsessionio.cpp
@@ -17,7 +17,6 @@
  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  */
 #include "tcpsessionio.h"
-#include <cstdio>
 
 const int TCPSessionIO::PORT = 3999;
 const char * const TCPSessionIO::IP = "127.0.0.1";
@@ -38,11 +37,8 @@ TCPSessionIO::TCPSessionIO() : SessionIO()
 
 TCPSessionIO::~TCPSessionIO()
 {
-  fprintf(stderr, "TCPSessionIO: delete clientStream\n");
   delete _clientStream; _clientStream = NULL;
-  fprintf(stderr, "TCPSessionIO: delete serverSocket\n");
   delete _serverSocket; _serverSocket = NULL;
-  fprintf(stderr, "TCPSessionIO: end\n");
 }
 
 bool
diff --git a/src/gui/server/tcpstreampool.cpp b/src/gui/server/tcpstreampool.cpp
index 89670835f3..7afd51e131 100644
--- a/src/gui/server/tcpstreampool.cpp
+++ b/src/gui/server/tcpstreampool.cpp
@@ -17,15 +17,12 @@
  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  */
 #include "tcpstreampool.h"
-#include "../../global.h"
 
 #define WAITING_TIME 2UL
 
 TCPStreamPool::~TCPStreamPool() 
 {
-  _debug("TCPStreamPool terminate\n");
   terminate();
-  _debug("terminate done\n");
 }
 
 void 
@@ -61,8 +58,6 @@ void
 TCPStreamPool::sendLast() {
   std::string output;
   while (good() && _outputPool.pop(output, WAITING_TIME))  {
-    _debug("TCPStreamPool send last %s\n", output.c_str());
-    //_debug("sending last message...\n");
     *this << output << std::endl;
   }
 }
@@ -72,5 +67,3 @@ TCPStreamPool::receive(std::string& request)
 {
   return _inputPool.pop(request, WAITING_TIME);
 }
-
-
diff --git a/src/managerimpl.cpp b/src/managerimpl.cpp
index 52e9839ef0..4e6615e667 100644
--- a/src/managerimpl.cpp
+++ b/src/managerimpl.cpp
@@ -101,8 +101,6 @@ ManagerImpl::~ManagerImpl (void)
   delete _DNSService; _DNSService = NULL;
 #endif
 
-  //delete _error; _error = NULL;
-
   _debug("%s stop correctly.\n", PROGNAME);
 }
 
@@ -203,7 +201,7 @@ ManagerImpl::pushBackNewCall (CALLID id, enum CallType type)
 Call*
 ManagerImpl::getCall (CALLID id)
 {
-  _debug("%10d: Getting call\n", id);
+  //_debug("%10d: Getting call\n", id);
   Call* call = NULL;
   unsigned int size = _callVector.size();
   for (unsigned int i = 0; i < size; i++) {
@@ -223,7 +221,7 @@ ManagerImpl::getCall (CALLID id)
 void
 ManagerImpl::deleteCall (CALLID id)
 {
-  _debug("%10d: Deleting call\n", id);
+  //_debug("%10d: Deleting call\n", id);
   CallVector::iterator iter = _callVector.begin();
   while(iter!=_callVector.end()) {
     Call *call = *iter;
@@ -243,7 +241,7 @@ ManagerImpl::deleteCall (CALLID id)
 void
 ManagerImpl::setCurrentCallId(CALLID id)
 {
-  _debug("%10d: Setting current callid, old one was: %d\n", id, _currentCallId);
+  //_debug("%10d: Setting current callid, old one was: %d\n", id, _currentCallId);
   _currentCallId = id;
 }
 
@@ -251,7 +249,7 @@ void
 ManagerImpl::removeCallFromCurrent(CALLID id)
 {
   if ( _currentCallId == id ) {
-  _debug("%10d: Setting current callid, old one was: %d\n", 0, _currentCallId);
+    //_debug("%10d: Setting current callid, old one was: %d\n", 0, _currentCallId);
     _currentCallId = 0;
   }
 }
@@ -265,8 +263,9 @@ ManagerImpl::removeCallFromCurrent(CALLID id)
  */
 int 
 ManagerImpl::outgoingCall (const std::string& to)
-{	
+{
   CALLID id = generateNewCallId();
+  _debug("%10d: Outgoing Call\n", id);
   Call *call = pushBackNewCall(id, Outgoing);
   ost::MutexLock m(_mutex);
   call->setState(Call::Progressing);
@@ -287,22 +286,21 @@ ManagerImpl::hangupCall (CALLID id)
 {
   _debug("%10d: Hangup Call\n", id);
   ost::MutexLock m(_mutex);
-  if (id == _currentCallId || _currentCallId == 0) {
-    stopTone(); // stop tone, like a 700 error: number not found Not Found
-  }
   Call* call = getCall(id);
   if (call == NULL) {
+    stopTone();
     return -1;
   }
   int result = -1;
   if (call->getState() != Call::Error) { 
     result = call->hangup();
+  } else {
+    stopTone();
   }
   deleteCall(id);
   // current call id or no line selected
   if (id == _currentCallId || _currentCallId == 0) {
     removeCallFromCurrent(id);
-    stopTone(); // stop tone, like a 700 error: number not found Not Found
   }
   return result;
 }
@@ -394,7 +392,11 @@ ManagerImpl::offHoldCall (CALLID id)
   int returnValue = call->offHold();
   // start audio if it's ok
   if (returnValue != -1) {
-    getAudioDriver()->startStream();
+    try {
+      getAudioDriver()->startStream();
+    } catch(...) {
+      _debugException("Off hold could not start audio stream");
+    }
   }
   return returnValue;
 }
@@ -483,7 +485,7 @@ bool
 ManagerImpl::initRegisterVoIPLink() 
 {
   int returnValue = true;
-  _debug("Initiate VoIP Link Registration\n");
+  _debugInit("Initiate VoIP Link Registration\n");
   if (_hasTriedToRegister == false) {
     if ( _voIPLinkVector.at(DFT_VOIP_LINK)->init() ) { 
       // we call here, because it's long...
@@ -603,14 +605,15 @@ ManagerImpl::playDtmf(char code)
     int nbInt16InChar = sizeof(int16)/sizeof(char);
     audiolayer->putUrgent(buf_ctrl_vol, size * CHANNELS * nbInt16InChar);
 
-    // We activate the stream if it's not active yet.
-    if (!audiolayer->isStreamActive()) {
-      audiolayer->startStream();
-      //TODO: Is this really what we want?
-      //audiolayer->sleep(pulselen);
-      //audiolayer->stopStream();
-    } else {
-      audiolayer->sleep(pulselen); // in milliseconds
+    try {
+      // We activate the stream if it's not active yet.
+      if (!audiolayer->isStreamActive()) {
+        audiolayer->startStream();
+      } else {
+        audiolayer->sleep(pulselen); // in milliseconds
+      }
+    } catch(...) {
+      _debugException("Portaudio exception when playing a dtmf");
     }
     delete[] buf_ctrl_vol; buf_ctrl_vol = 0;
     returnValue = true;
@@ -635,14 +638,14 @@ void
 ManagerImpl::incWaitingCall() {
   ost::MutexLock m(_incomingCallMutex);
   _nbIncomingWaitingCall++;
-  _debug("incWaitingCall: %d\n", _nbIncomingWaitingCall);
+  //_debug("incWaitingCall: %d\n", _nbIncomingWaitingCall);
 }
 
 void
 ManagerImpl::decWaitingCall() {
   ost::MutexLock m(_incomingCallMutex);
   _nbIncomingWaitingCall--;
-  _debug("decWaitingCall: %d\n", _nbIncomingWaitingCall);
+  //_debug("decWaitingCall: %d\n", _nbIncomingWaitingCall);
 }
 
 
@@ -968,7 +971,11 @@ ManagerImpl::playATone(Tone::TONEID toneId) {
   _telephoneTone->setCurrentTone(toneId);
   _toneMutex.leaveMutex();
 
-  getAudioDriver()->startStream();
+  try {
+    getAudioDriver()->startStream();
+  } catch(...) {
+    _debugException("Off hold could not start audio stream");
+  }
   return true;
 }
 
@@ -977,7 +984,11 @@ ManagerImpl::playATone(Tone::TONEID toneId) {
  */
 void 
 ManagerImpl::stopTone() {
-  getAudioDriver()->stopStream();
+  try {
+    getAudioDriver()->stopStream();
+  } catch(...) {
+    _debugException("Stop tone and stop stream");
+  }
 
   _toneMutex.enterMutex();
   _telephoneTone->setCurrentTone(Tone::TONE_NULL);
@@ -1033,7 +1044,11 @@ ManagerImpl::ringtone()
     _toneMutex.enterMutex(); 
     _audiofile.start();
     _toneMutex.leaveMutex(); 
-    getAudioDriver()->startStream();
+    try {
+      getAudioDriver()->startStream();
+    } catch(...) {
+      _debugException("Audio file couldn't start audio stream");
+    }
   } else {
     ringback();
   }
@@ -1104,15 +1119,14 @@ ManagerImpl::getStunInfo (StunAddress4& stunSvrAddr)
   if (ok) {
     closesocket(fd3);
     closesocket(fd4);
-    _debug("Got port pair at %d\n", mappedAddr.port);
     _firewallPort = mappedAddr.port;
     // Convert ipv4 address to host byte ordering
     in.s_addr = ntohl (mappedAddr.addr);
     addr = inet_ntoa(in);
     _firewallAddr = std::string(addr);
-    _debug("address firewall = %s\n",_firewallAddr.data());
+    _debug("STUN Firewall: [%s:%d]\n", _firewallAddr.data(), _firewallPort);
   } else {
-    _debug("Opened a stun socket pair FAILED\n");
+    _debug("Opening a stun socket pair failed\n");
   }
 }
 
@@ -1263,7 +1277,7 @@ ManagerImpl::selectAudioDriver (void)
     if (nbDevice == 0) {
       throw std::runtime_error("Portaudio detect no sound card.");
     } else if (noDevice >= nbDevice) {
-      _debug("Portaudio auto-select device #0 because device #%d is not found\n", noDevice);
+      _debug(" Portaudio auto-select device #0 because device #%d is not found\n", noDevice);
       _setupLoaded = false;
       noDevice = 0;
     }
diff --git a/src/sipcall.cpp b/src/sipcall.cpp
index c4c8aea721..5909e4d429 100644
--- a/src/sipcall.cpp
+++ b/src/sipcall.cpp
@@ -163,7 +163,7 @@ SipCall::newIncomingCall (eXosip_event_t *event) {
   if (event->response != NULL) {
     _status_code = event->response->status_code;
     snprintf (_reason_phrase, 49, "%s", event->response->reason_phrase);
-    _debug("  Status: %d %s\n", _status_code, _reason_phrase);
+    _debug("            Status: %d %s\n", _status_code, _reason_phrase);
   }
 
   strcpy(_remote_uri, "");
@@ -192,9 +192,9 @@ SipCall::newIncomingCall (eXosip_event_t *event) {
       osip_from_free(from);
     }
   }
-  _debug("  Name: %s\n", _name.c_str());
-  _debug("  Number: %s\n", _number.c_str());
-  _debug("  Remote URI: %s\n", _remote_uri);
+  _debug("            Name: %s\n", _name.c_str());
+  _debug("            Number: %s\n", _number.c_str());
+  _debug("            Remote URI: %s\n", _remote_uri);
 
   /* negotiate payloads */
   sdp_message_t *remote_sdp = NULL;
@@ -218,7 +218,7 @@ SipCall::newIncomingCall (eXosip_event_t *event) {
   eXosip_unlock();
   if (conn != NULL && conn->c_addr != NULL) {
       snprintf (_remote_sdp_audio_ip, 49, "%s", conn->c_addr);
-      _debug("  Remote Audio IP: %s\n", _remote_sdp_audio_ip);
+      _debug("            Remote Audio IP: %s\n", _remote_sdp_audio_ip);
   }
 
   // Remote Media Port
@@ -236,7 +236,7 @@ SipCall::newIncomingCall (eXosip_event_t *event) {
     return -1;
   }
   _remote_sdp_audio_port = atoi(remote_med->m_port);
-  _debug("  Remote Audio Port: %d\n", _remote_sdp_audio_port);
+  _debug("            Remote Audio Port: %d\n", _remote_sdp_audio_port);
 
   // Remote Payload
   char *tmp = NULL;
@@ -253,7 +253,7 @@ SipCall::newIncomingCall (eXosip_event_t *event) {
   }
   if (tmp != NULL) {
     payload = atoi (tmp);
-    _debug("  Payload: %d\n", payload);
+    _debug("            Payload: %d\n", payload);
     setAudioCodec(_cdv->at(0)->alloc(payload, "")); // codec builder for the mic
   } else {
     _debug("< Sending 415 Unsupported media type\n");
@@ -284,16 +284,16 @@ SipCall::newIncomingCall (eXosip_event_t *event) {
         /* search if stream is sendonly or recvonly */
         _remote_sendrecv = sdp_analyse_attribute (remote_sdp, remote_med);
         _local_sendrecv =  sdp_analyse_attribute (local_sdp, local_med);
-        _debug("  Remote SendRecv: %d\n", _remote_sendrecv);
-        _debug("  Local  SendRecv: %d\n", _local_sendrecv);
+        _debug("            Remote SendRecv: %d\n", _remote_sendrecv);
+        _debug("            Local  SendRecv: %d\n", _local_sendrecv);
         if (_local_sendrecv == _SENDRECV) {
           if (_remote_sendrecv == _SENDONLY)      { _local_sendrecv = _RECVONLY; }
           else if (_remote_sendrecv == _RECVONLY) { _local_sendrecv = _SENDONLY; }
         }
-        _debug("  Final Local SendRecv: %d\n", _local_sendrecv);
+        _debug("            Final Local SendRecv: %d\n", _local_sendrecv);
         sdp_message_free (local_sdp);
       }
-      _debug("  < Sending answer 183\n");
+      _debug("< Sending answer 183\n");
       if (0 != eXosip_call_send_answer (_tid, 183, answer)) {
         _debug("SipCall::newIncomingCall: cannot send 183 progress?\n");
       }
@@ -323,7 +323,7 @@ SipCall::newReinviteCall (eXosip_event_t *event) {
   if (event->response != NULL) {
     _status_code = event->response->status_code;
     snprintf (_reason_phrase, 49, "%s", event->response->reason_phrase);
-    _debug("  Status: %d %s\n", _status_code, _reason_phrase);
+    _debug("            Status: %d %s\n", _status_code, _reason_phrase);
   }
 
   strcpy(_remote_uri, "");
@@ -352,9 +352,9 @@ SipCall::newReinviteCall (eXosip_event_t *event) {
       osip_from_free(from);
     }
   }
-  _debug("  Name: %s\n", _name.c_str());
-  _debug("  Number: %s\n", _number.c_str());
-  _debug("  Remote URI: %s\n", _remote_uri);
+  _debug("            Name: %s\n", _name.c_str());
+  _debug("            Number: %s\n", _number.c_str());
+  _debug("            Remote URI: %s\n", _remote_uri);
 
   /* negotiate payloads */
   sdp_message_t *remote_sdp = NULL;
@@ -379,7 +379,7 @@ SipCall::newReinviteCall (eXosip_event_t *event) {
   eXosip_unlock();
   if (conn != NULL && conn->c_addr != NULL) {
       snprintf (_remote_sdp_audio_ip, 49, "%s", conn->c_addr);
-      _debug("  Remote Audio IP: %s\n", _remote_sdp_audio_ip);
+      _debug("            Remote Audio IP: %s\n", _remote_sdp_audio_ip);
   }
 
   // Remote Media Port
@@ -397,7 +397,7 @@ SipCall::newReinviteCall (eXosip_event_t *event) {
     return 0;
   }
   _remote_sdp_audio_port = atoi(remote_med->m_port);
-  _debug("  Remote Audio Port: %d\n", _remote_sdp_audio_port);
+  _debug("            Remote Audio Port: %d\n", _remote_sdp_audio_port);
 
   // Remote Payload
   char *tmp = NULL;
@@ -414,7 +414,7 @@ SipCall::newReinviteCall (eXosip_event_t *event) {
   }
   if (tmp != NULL) {
     payload = atoi (tmp);
-    _debug("  Payload: %d\n", payload);
+    _debug("            Payload: %d\n", payload);
     setAudioCodec(_cdv->at(0)->alloc(payload, "")); // codec builder for the mic
   } else {
     _debug("< Sending 415 Unsupported media type\n");
@@ -445,13 +445,13 @@ SipCall::newReinviteCall (eXosip_event_t *event) {
         /* search if stream is sendonly or recvonly */
         _remote_sendrecv = sdp_analyse_attribute (remote_sdp, remote_med);
         _local_sendrecv =  sdp_analyse_attribute (local_sdp, local_med);
-        _debug("  Remote SendRecv: %d\n", _remote_sendrecv);
-        _debug("  Local  SendRecv: %d\n", _local_sendrecv);
+        _debug("            Remote SendRecv: %d\n", _remote_sendrecv);
+        _debug("            Local  SendRecv: %d\n", _local_sendrecv);
         if (_local_sendrecv == _SENDRECV) {
           if (_remote_sendrecv == _SENDONLY)      { _local_sendrecv = _RECVONLY; }
           else if (_remote_sendrecv == _RECVONLY) { _local_sendrecv = _SENDONLY; }
         }
-        _debug("  Final Local SendRecv: %d\n", _local_sendrecv);
+        _debug("            Final Local SendRecv: %d\n", _local_sendrecv);
         sdp_message_free (local_sdp);
       }
       _debug("< Sending answer 200\n");
@@ -528,8 +528,8 @@ SipCall::answeredCall(eXosip_event_t *event) {
         osip_free (tmp);
     }
   }
-  _debug("  Status: %d %s\n", _status_code, _reason_phrase);
-  _debug("  From URI: %s\n", _remote_uri);
+  _debug("            Status: %d %s\n", _status_code, _reason_phrase);
+  _debug("            From URI: %s\n", _remote_uri);
 
   eXosip_lock ();
   {
@@ -606,7 +606,7 @@ SipCall::answeredCall_without_hold (eXosip_event_t *event)
         _remote_sdp_audio_port = atoi (remote_med->m_port);
       }
       eXosip_unlock();
-      _debug("  Remote Audio: %s:%d\n", _remote_sdp_audio_ip, _remote_sdp_audio_port);
+      _debug("            Remote Audio: %s:%d\n", _remote_sdp_audio_ip, _remote_sdp_audio_port);
 
       if (_remote_sdp_audio_port > 0 && _remote_sdp_audio_ip[0] != '\0' && 
         remote_med != NULL) {
@@ -618,7 +618,7 @@ SipCall::answeredCall_without_hold (eXosip_event_t *event)
         setAudioCodec(_cdv->at(0)->alloc(payload, ""));
       }
     }
-    _debug("  Remote Payload: %d\n", payload);
+    _debug("            Remote Payload: %d\n", payload);
 
     if (local_sdp == NULL) {
       _debug("SipCall::answeredCall_without_hold: SDP body was probably in the ACK (TODO)\n");
@@ -632,7 +632,7 @@ SipCall::answeredCall_without_hold (eXosip_event_t *event)
       if (local_med != NULL && local_med->m_port != NULL) {
         audio_port = atoi (local_med->m_port);
       }
-      _debug("  Local Audio port: %d\n", audio_port);
+      _debug("            Local Audio port: %d\n", audio_port);
 
       if (tmp != NULL && audio_port > 0
           && _remote_sdp_audio_port > 0
@@ -648,8 +648,8 @@ SipCall::answeredCall_without_hold (eXosip_event_t *event)
               _local_sendrecv = _SENDONLY;
         }
       }
-      _debug("  Remote Sendrecv: %d\n", _remote_sendrecv);
-      _debug("  Local Sendrecv: %d\n", _local_sendrecv);
+      _debug("            Remote Sendrecv: %d\n", _remote_sendrecv);
+      _debug("            Local Sendrecv: %d\n", _local_sendrecv);
     }
     sdp_message_free (local_sdp);
     sdp_message_free (remote_sdp);
diff --git a/src/sipvoiplink.cpp b/src/sipvoiplink.cpp
index ea3b8a647c..14bfc14ba6 100644
--- a/src/sipvoiplink.cpp
+++ b/src/sipvoiplink.cpp
@@ -256,7 +256,6 @@ SipVoIPLink::setUnregister (void)
     eXosip_lock();
 
     if (_reg_id > 0) {
-      _debug("UNREGISTER\n");
       i = eXosip_register_build_register (_reg_id, 0, &reg);
     }
     eXosip_unlock();
@@ -264,20 +263,16 @@ SipVoIPLink::setUnregister (void)
       return -1;
     }
 
-    if (setAuthentication() == -1) {
-      _debug("No authentication\n");
-      return -1;
-    }
-
     eXosip_lock();
+    _debug("< Sending REGISTER (expire=0)\n");
     i = eXosip_register_send_register (_reg_id, reg);
     if (i == -2) {
-      _debug("(unregister) Cannot build registration, check the setup\n"); 
+      _debug("  Cannot build registration (unregister), check the setup\n"); 
       eXosip_unlock();
       return -1;
     }
     if (i == -1) {
-      _debug("(unregister) Registration Failed\n");
+      _debug("  Registration (unregister) Failed\n");
     }
     eXosip_unlock();
     _reg_id = -1;
@@ -314,8 +309,8 @@ SipVoIPLink::outgoingInvite (CALLID id, const std::string& to_url)
     }
   }
 		
-  _debug("From: %s\n", from.data());
-  _debug("To: %s\n", to.data());
+  _debug("            From: %s\n", from.data());
+  _debug("            To: %s\n", to.data());
 
   if (manager.getConfigString(SIGNALISATION, PROXY).empty()) {
     // If no SIP proxy setting for direct call with only IP address
@@ -361,7 +356,7 @@ SipVoIPLink::answer (CALLID id)
 
   _debug("%10d: Answer call [cid = %d, did = %d]\n", id, getSipCall(id)->getCid(), getSipCall(id)->getDid());
   port = getSipCall(id)->getLocalAudioPort();
-  _debug("Local audio port: %d\n", port);
+  _debug("            Local audio port: %d\n", port);
 
   osip_message_t *answerMessage = NULL;
   SipCall* ca = getSipCall(id);
@@ -393,7 +388,7 @@ SipVoIPLink::answer (CALLID id)
   eXosip_unlock();
 
   // Incoming call is answered, start the sound channel.
-  _debug("Starting AudioRTP\n");
+  _debug("          Starting AudioRTP\n");
   if (_audiortp.createNewSession (getSipCall(id)) < 0) {
     _debug("FATAL: Unable to start sound (%s:%d)\n", __FILE__, __LINE__);
     i = -1;
@@ -411,7 +406,7 @@ SipVoIPLink::hangup (CALLID id)
   int i = 0;
   SipCall* sipcall = getSipCall(id);
   if (sipcall == NULL) { return -1; }
-  _debug("Hang up call [id = %d, cid = %d, did = %d]\n", 
+  _debug("%10d: Hang up call [cid = %d, did = %d]\n", 
     id, sipcall->getCid(), sipcall->getDid());	
   // Release SIP stack.
   eXosip_lock();
@@ -419,7 +414,6 @@ SipVoIPLink::hangup (CALLID id)
   eXosip_unlock();
 
   // Release RTP channels
-  _debug("Stopping AudioRTP\n");
   if (id == Manager::instance().getCurrentCallId()) {
     _audiortp.closeRtpSession();
   }
@@ -433,7 +427,7 @@ SipVoIPLink::cancel (CALLID id)
 {
   int i = 0;
   SipCall* sipcall = getSipCall(id);
-  _debug("Cancel call [id = %d, cid = %d]\n", id, sipcall->getCid());
+  _debug("%10d: Cancel call [cid = %d]\n", id, sipcall->getCid());
   // Release SIP stack.
   eXosip_lock();
   i = eXosip_call_terminate (sipcall->getCid(), -1);
@@ -502,7 +496,6 @@ SipVoIPLink::onhold (CALLID id)
   }
   
   // Send request
-  _debug("Stopping AudioRTP\n");
   _audiortp.closeRtpSession();
 
   eXosip_lock ();
@@ -573,7 +566,7 @@ SipVoIPLink::offhold (CALLID id)
   eXosip_unlock ();
 
   // Enable audio
-  _debug("Starting AudioRTP\n");
+  _debug("          Starting AudioRTP\n");
   if (_audiortp.createNewSession (getSipCall(id)) < 0) {
     _debug("FATAL: Unable to start sound (%s:%d)\n", __FILE__, __LINE__);
     i = -1;
@@ -665,24 +658,24 @@ SipVoIPLink::getEvent (void)
     // Generate id
     id = Manager::instance().generateNewCallId();
     Manager::instance().pushBackNewCall(id, Incoming);
-    _debug("  ID: %d [cid = %d, did = %d]\n",id, event->cid, event->did);
+    _debug("%10d: [cid = %d, did = %d]\n", id, event->cid, event->did);
 
     // Associate an audio port with a call
     sipcall = getSipCall(id);
     sipcall->setLocalAudioPort(_localPort);
     sipcall->setLocalIp(getLocalIpAddress());
-    _debug("  Local listening port: %d\n", _localPort);
-    _debug("  Local listening IP: %s\n", getLocalIpAddress().c_str());
+    _debug("            Local listening port: %d\n", _localPort);
+    _debug("            Local listening IP: %s\n", getLocalIpAddress().c_str());
 
     if (sipcall->newIncomingCall(event) == 0 ) {
       if (Manager::instance().incomingCall(id, sipcall->getName(), sipcall->getNumber()) == -1) {
-        Manager::instance().displayError("  Incoming Call Failed");
+        Manager::instance().displayError("            Incoming Call Failed");
         deleteSipCall(id);
       }
     } else {
       Manager::instance().peerHungupCall(id);
       deleteSipCall(id);
-      Manager::instance().displayError("  Incoming Call Failed");
+      Manager::instance().displayError("            Incoming Call Failed");
     }
     break;
 
@@ -695,10 +688,10 @@ SipVoIPLink::getEvent (void)
     if (id != 0) {
       sipcall = getSipCall(id);
       if (sipcall != 0) {
-        _debug("  Info [id = %d, cid = %d, did = %d], localport=%d\n", id, event->cid, event->did,sipcall->getLocalAudioPort());
+        _debug("%10d: Receive Reinvite [cid = %d, did = %d], localport=%d\n", id, event->cid, event->did,sipcall->getLocalAudioPort());
 
         if ( id == Manager::instance().getCurrentCallId() ) {
-          _debug("Stopping AudioRTP\n");
+          Manager::instance().stopTone();
           _audiortp.closeRtpSession();
         }
         sipcall->newReinviteCall(event);
@@ -718,7 +711,7 @@ SipVoIPLink::getEvent (void)
 
   case EXOSIP_CALL_RINGING: // 9 peer call is ringing
     id = findCallIdInitial(event);
-    _debug("> Receive Call Ringing [id = %d, cid = %d, did = %d]\n", id, event->cid, event->did);
+    _debug("%10d: Receive Call Ringing [cid = %d, did = %d]\n", id, event->cid, event->did);
     if (id != 0) {
       getSipCall(id)->ringingCall(event);
       Manager::instance().peerRingingCall(id);
@@ -734,7 +727,7 @@ SipVoIPLink::getEvent (void)
     if ( id != 0) {
       sipcall = getSipCall(id);
       if ( sipcall != 0 ) {
-        _debug("> Receive Call Answer [id = %d, cid = %d, did = %d], localport=%d\n", id, event->cid, event->did, sipcall->getLocalAudioPort());
+        _debug("%10d: Receive Call Answer [cid = %d, did = %d], localport=%d\n", id, event->cid, event->did, sipcall->getLocalAudioPort());
 
         // Answer
         if (Manager::instance().callCanBeAnswered(id)) {
@@ -745,9 +738,9 @@ SipVoIPLink::getEvent (void)
   
             if(!Manager::instance().callIsOnHold(id) && Manager::instance().getCurrentCallId()==id) {
               // Outgoing call is answered, start the sound channel.
-              _debug("Starting AudioRTP\n");
+              _debug("            Starting AudioRTP\n");
               if (_audiortp.createNewSession(sipcall) < 0) {
-                _debug("FATAL: Unable to start sound (%s:%d)\n", 
+                _debug("            FATAL: Unable to start sound (%s:%d)\n", 
                 __FILE__, __LINE__);
                 returnValue = -1;
               }
@@ -755,7 +748,7 @@ SipVoIPLink::getEvent (void)
           }
         } else {
           // Answer to on/off hold to send ACK
-          _debug("Answering call\n");
+          _debug("            Answering call\n");
           sipcall->answeredCall(event);
         }
       }
@@ -769,7 +762,7 @@ SipVoIPLink::getEvent (void)
 
   case EXOSIP_CALL_ACK: // 15
     id = findCallId(event);
-    _debug("> Receive ACK [id = %d, cid = %d, did = %d]\n", id, event->cid, event->did);
+    _debug("%10d: Receive ACK [cid = %d, did = %d]\n", id, event->cid, event->did);
     if (id != 0 ) {
       sipcall = getSipCall(id);
       if(sipcall != 0 ) { 
@@ -777,8 +770,10 @@ SipVoIPLink::getEvent (void)
         if (sipcall->isReinvite()) {
           sipcall->endReinvite();
           if(!Manager::instance().callIsOnHold(id) && Manager::instance().getCurrentCallId()==id) {
-            _debug("Starting AudioRTP\n");
+            _debug("            Starting AudioRTP\n");
             _audiortp.createNewSession(sipcall);
+          } else {
+            _debug("            Didn't start RTP because it's on hold or it's not the current call id\n");
           }
         }
       }
@@ -790,11 +785,10 @@ SipVoIPLink::getEvent (void)
     // The peer-user closed the phone call(we received BYE).
   case EXOSIP_CALL_CLOSED: // 25
     id = findCallId(event);
-    _debug("> BYE [id = %d, cid = %d, did = %d]\n", id, event->cid, event->did);	
+    _debug("%10d: Receive BYE [cid = %d, did = %d]\n", id, event->cid, event->did);	
     if (id != 0) {
       if (Manager::instance().callCanBeClosed(id)) {
          sipcall = getSipCall(id);
-         _debug("Stopping AudioRTP\n");
          _audiortp.closeRtpSession();
       }
       Manager::instance().peerHungupCall(id);
@@ -809,17 +803,11 @@ SipVoIPLink::getEvent (void)
       id = findCallId(event);
       if (id!=0) {
         // not supposed to be execute on a current call...
-        _debug("send a call failure...");
         Manager::instance().callFailure(id);
         deleteSipCall(id);
       }
 
     }
-    //id = findCallId(event);
-    //if (id!=0) {
-    //Manager::instance().peerHungupCall(id);
-    //deleteSipCall(id);
-    //}
     break;
   case EXOSIP_CALL_REQUESTFAILURE:
     id = findCallId(event);
@@ -944,7 +932,7 @@ SipVoIPLink::getEvent (void)
       // Get the message body
       ii = osip_message_get_body(event->request, 0, &body);
       if (ii != 0) {
-        _debug("Cannot get body in a new EXOSIP_MESSAGE_NEW event\n");
+        _debug("  Cannot get body in a new EXOSIP_MESSAGE_NEW event\n");
         returnValue = -1;
         break;
       }
@@ -1019,11 +1007,9 @@ SipVoIPLink::getEvent (void)
     break;
 
   default:
-    //Manager::instance().displayErrorText(event->type, "getEvent:default");
     returnValue = -1;
     break;
   }
-  //_debug(" : end event : %d / %d\n", event->type, returnValue);
   eXosip_event_free(event);
 
   return returnValue;
@@ -1113,7 +1099,6 @@ SipVoIPLink::endSipCalls()
       eXosip_unlock();
 
       // Release RTP channels
-      _debug("Stopping AudioRTP\n");
       _audiortp.closeRtpSession();
       delete *iter; *iter = NULL;
     }
@@ -1453,12 +1438,12 @@ SipVoIPLink::startCall (CALLID id, const std::string& from, const std::string& t
   if (!Manager::instance().useStun()) {
     // Set random port for outgoing call if no firewall
     setLocalPort(RANDOM_LOCAL_PORT);
-    _debug("  Setting local port to random: %d\n",_localPort);
+    _debug("            Setting local port to random: %d\n",_localPort);
   } else {
     // If use Stun server
     if (behindNat() != 0) {
       setLocalPort(Manager::instance().getFirewallPort());
-      _debug("  Setting local port to firewall port: %d\n", _localPort);	
+      _debug("            Setting local port to firewall port: %d\n", _localPort);	
     } else {
       return -1;
     }
@@ -1529,10 +1514,10 @@ SipVoIPLink::startCall (CALLID id, const std::string& from, const std::string& t
   }
   
   // this is the cid (call id from exosip)
-  _debug("< INVITE (%d)\n", id);
+  _debug("%10d: Receive INVITE\n", id);
   int cid = eXosip_call_send_initial_invite (invite);
-  _debug("  Local IP:port: %s:%d\n", getLocalIpAddress().c_str(), getLocalPort());
-  _debug("  Payload:       %s\n", media_audio);
+  _debug("            Local IP:port: %s:%d\n", getLocalIpAddress().c_str(), getLocalPort());
+  _debug("            Payload:       %s\n", media_audio);
 
   // Keep the cid in case of cancelling
   sipcall->setCid(cid);
diff --git a/src/zeroconf/DNSService.cpp b/src/zeroconf/DNSService.cpp
index 03f1a0d96e..f70e79efa6 100644
--- a/src/zeroconf/DNSService.cpp
+++ b/src/zeroconf/DNSService.cpp
@@ -24,7 +24,6 @@
 #include "DNSService.h"
 #include "DNSServiceTXTRecord.h"
 #include "DNSQueryThread.h"
-#include "../global.h" // for _debug()
 
 #include <cc++/thread.h>
 
@@ -200,10 +199,10 @@ DNSServiceAddServicesCallback(DNSServiceRef,
       std::string tempService;
       tempService = std::string(serviceName) + "." + std::string(replyType) + std::string(replyDomain);
       if (flags&kDNSServiceFlagsAdd) {
-        _debug("DNSServiceAddServicesCallback call addService\n");
+//        _debug("DNSServiceAddServicesCallback call addService\n");
         service->addService(tempService);
       } else {
-        _debug("DNSServiceAddServicesCallback call removeService\n");
+//        _debug("DNSServiceAddServicesCallback call removeService\n");
         service->removeService(tempService);
       }
     }
@@ -228,10 +227,10 @@ DNSServiceQueryRecordCallback(
 {
   if (errorCode==kDNSServiceErr_NoError) {
     if (flags&kDNSServiceFlagsAdd) {
-      _debug("DNSServiceQueryRecordCallback call addTXTRecord\n");
+//      _debug("DNSServiceQueryRecordCallback call addTXTRecord\n");
       ((DNSService *)context)->addTXTRecord(fullname, rdlen, rdata);
     } else {
-      _debug("DNSServiceQueryRecordCallback call removeService\n");
+//      _debug("DNSServiceQueryRecordCallback call removeService\n");
       ((DNSService *)context)->removeService(fullname);
     }
   }
-- 
GitLab