ITANetAudioStreamingServer.cpp 10.4 KB
Newer Older
Anne's avatar
Anne committed
1 2
#include <ITANetAudioStreamingServer.h>
#include <ITANetAudioServer.h>
3
#include <ITANetAudioMessage.h>
Anne's avatar
Anne committed
4 5

// ITA includes
Anne's avatar
Anne committed
6
#include <ITADataSource.h>
7
#include <ITANetAudioMessage.h>
Anne's avatar
Anne committed
8
#include <ITAException.h>
9
#include <ITAStreamInfo.h>
Anne's avatar
Anne committed
10
#include <ITAClock.h>
Anne's avatar
Anne committed
11 12 13 14 15 16 17

// Vista includes
#include <VistaInterProcComm/Concurrency/VistaThreadLoop.h>
#include <VistaInterProcComm/Connections/VistaConnectionIP.h>
#include <VistaInterProcComm/IPNet/VistaTCPSocket.h>
#include <VistaBase/VistaTimeUtils.h>
#include <VistaInterProcComm/IPNet/VistaIPAddress.h>
18
#include <VistaInterProcComm/Concurrency/VistaPriority.h>
19
#include <VistaBase/VistaStreamUtils.h>
Anne's avatar
Anne committed
20
#include <ITADataLog.h>
Anne's avatar
Anne committed
21 22 23 24 25

// STL
#include <cmath>
#include <cassert>

26 27 28 29 30 31 32
struct ITAServerLog : public ITALogDataBase
{
	inline static std::ostream& outputDesc( std::ostream& os )
	{
		os << "BlockId";
		os << "\t" << "WorldTimeStamp";
		os << "\t" << "ProtocolStatus";
33 34
		os << "\t" << "EstimatedFreeSamples";
		os << "\t" << "TransmittedSamples";
35 36 37 38 39 40 41 42
		os << std::endl;
		return os;
	};

	inline std::ostream& outputData( std::ostream& os ) const
	{
		os << uiBlockId;
		os << "\t" << std::setprecision( 12 ) << dWorldTimeStamp;
43 44 45
		os << "\t" << sProtocolStatus;
		os << "\t" << iEstimatedFreeSamples;
		os << "\t" << iTransmittedSamples;
46 47 48 49 50 51
		os << std::endl;
		return os;
	};

	unsigned int uiBlockId; //!< Block identifier (audio streaming)
	double dWorldTimeStamp;
52 53 54
	std::string sProtocolStatus;
	int iEstimatedFreeSamples;
	int iTransmittedSamples;
Anne's avatar
Anne committed
55 56 57 58
};

class ITABufferedDataLoggerImplServer : public ITABufferedDataLogger < ITAServerLog > {};

59
CITANetAudioStreamingServer::CITANetAudioStreamingServer()
60 61 62 63 64
	: m_pInputStream( NULL )
	, m_iUpdateStrategy( AUTO )
	, m_pConnection( NULL )
	, m_pNetAudioServer( new CITANetAudioServer() )
	, m_dLastTimeStamp( 0 )
65
	, m_iTargetLatencySamples( -1 )
66
	, m_sServerLogBaseName( "ITANetAudioStreamingServer" )
67
{
Anne's avatar
Anne committed
68
	iServerBlockId = 0;
69
	m_iMaxSendBlocks = 40;
70
	m_iEstimatedClientRingBufferFreeSamples = 0;
71

72
	//SetPriority( VistaPriority::VISTA_MID_PRIORITY );
Anne's avatar
Anne committed
73 74
}

75 76 77 78
CITANetAudioStreamingServer::~CITANetAudioStreamingServer()
{
	delete m_pNetAudioServer;
	delete m_pServerLogger;
79 80 81

	vstr::out() << "[ ITANetAudioStreamingServer ] Processing statistics: " << m_swTryReadBlockStats.ToString() << std::endl;
	vstr::out() << "[ ITANetAudioStreamingServer ] Try-read access statistics: " << m_swTryReadAccessStats.ToString() << std::endl;
82 83
}

84
bool CITANetAudioStreamingServer::Start(const std::string& sAddress, int iPort, double dTimeIntervalCientSendStatus)
Anne's avatar
Anne committed
85
{
86
	if( !m_pInputStream )
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
87 88
		ITA_EXCEPT1( MODAL_EXCEPTION, "Can not start server without a valid input stream" );

89
	if( !m_pNetAudioServer->Start( sAddress, iPort ) ) // blocking
90 91
		return false;

92
	m_pConnection = m_pNetAudioServer->GetConnection();
93

94
	m_pMessage = new CITANetAudioMessage( m_pConnection->GetByteorderSwapFlag() );
Jonas Stienen's avatar
Jonas Stienen committed
95 96
	m_pMessage->SetMessageLoggerBaseName( GetServerLogBaseName() + "_Messages" );

97
	m_pMessage->ResetMessage();
98
	m_pMessage->SetConnection( m_pConnection );
99
	while( !m_pMessage->ReadMessage( 0 ) ); //blocking
100

101 102
	assert( m_pMessage->GetMessageType() == CITANetAudioProtocol::NP_CLIENT_OPEN );
	CITANetAudioProtocol::StreamingParameters oClientParams = m_pMessage->ReadStreamingParameters();
103

Anne's avatar
Anne committed
104
	m_oServerParams.iRingBufferSize = oClientParams.iRingBufferSize;
Anne Heimes's avatar
Anne Heimes committed
105
	m_oServerParams.iBlockSize = oClientParams.iBlockSize;
106
	m_iEstimatedClientRingBufferFreeSamples = m_oServerParams.iRingBufferSize;
107

108 109 110 111
	m_sfTempTransmitBuffer.init( m_pInputStream->GetNumberOfChannels(), m_oServerParams.iRingBufferSize, true );

	m_pServerLogger = new ITABufferedDataLoggerImplServer();
	m_pServerLogger->setOutputFile( m_sServerLogBaseName + "_Server.log" );
112
	m_dLastTimeStamp = ITAClock::getDefaultClock()->getTime();
113

114
	if( m_oServerParams == oClientParams )
Anne's avatar
Anne committed
115
	{
116 117 118 119
		m_pMessage->SetMessageType( CITANetAudioProtocol::NP_SERVER_OPEN );
		m_pMessage->WriteDouble( dTimeIntervalCientSendStatus );
		m_pMessage->WriteMessage();

Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
120
#ifdef NET_AUDIO_SHOW_TRAFFIC
121
		vstr::out() << "[ITANetAudioStreamingServer] Server and client parameters matched. Will resume with streaming" << std::endl;
Anne Heimes's avatar
Anne Heimes committed
122
#endif
123 124 125 126

		Run(); // Start thread loop

		return true;
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
127 128 129
	}
	else
	{
130 131 132
		m_pMessage->SetMessageType( CITANetAudioProtocol::NP_SERVER_REFUSED_INVALID_PARAMETERS );
		m_pMessage->WriteMessage();

Anne Heimes's avatar
Anne Heimes committed
133
#ifdef NET_AUDIO_SHOW_TRAFFIC
134
		vstr::out() << "[ITANetAudioStreamingServer] Server and client parameters mismatch detected. Will notify client and stop." << std::endl;
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
135
#endif
136

137 138
		return false;
	}
Anne's avatar
Anne committed
139 140
}

141
bool CITANetAudioStreamingServer::LoopBody()
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
142
{
143 144
	const double dNow = ITAClock::getDefaultClock()->getTime();

Anne's avatar
Anne committed
145
	ITAServerLog oLog;
146
	oLog.dWorldTimeStamp = dNow;
Anne's avatar
Anne committed
147
	oLog.uiBlockId = ++iServerBlockId;
148 149 150 151
	oLog.iTransmittedSamples = 0;
	
	// Sending Samples
	int iEstimatedClientRingBufferTargetLatencyFreeSamples = m_iEstimatedClientRingBufferFreeSamples - ( m_oServerParams.iRingBufferSize - m_iTargetLatencySamples );
152

153
	if (iEstimatedClientRingBufferTargetLatencyFreeSamples >= m_iSendingBlockLength)
Anne's avatar
Anne committed
154 155
	{
		// Send Samples
156
		int iSendBlocks = iEstimatedClientRingBufferTargetLatencyFreeSamples / m_iSendingBlockLength;
157

158
		// Besser wre vermutlich, gleich alle samples zu senden und nicht nur einen Block nach dem anderen
159 160
		if (m_sfTempTransmitBuffer.GetLength() != m_iSendingBlockLength)
			m_sfTempTransmitBuffer.init(m_pInputStream->GetNumberOfChannels(), m_iSendingBlockLength, false);
161 162

		for( int j = 0; j < iSendBlocks; j++ )
163
		{
164
			for( int i = 0; i < int( m_pInputStream->GetNumberOfChannels() ); i++ )
165 166
			{
				ITAStreamInfo oStreamInfo;
167
				oStreamInfo.nSamples = m_iSendingBlockLength;
168 169

				const float* pfData = m_pInputStream->GetBlockPointer( i, &oStreamInfo );
170
				if( pfData != 0 )
171
					m_sfTempTransmitBuffer[i].write(pfData, m_iSendingBlockLength, 0);
172
			}
173

174
			m_pInputStream->IncrementBlockPointer();
175 176 177

			m_pMessage->ResetMessage();
			m_pMessage->SetMessageType( CITANetAudioProtocol::NP_SERVER_SENDING_SAMPLES );
Anne Heimes's avatar
Anne Heimes committed
178
			m_pMessage->WriteSampleFrame( &m_sfTempTransmitBuffer );
179
			m_pMessage->WriteMessage();
180
			m_iEstimatedClientRingBufferFreeSamples -= m_iSendingBlockLength;
Anne Heimes's avatar
Anne Heimes committed
181
		}
182

Anne's avatar
Anne committed
183
#ifdef NET_AUDIO_SHOW_TRAFFIC
184 185
		vstr::out() << "[ITANetAudioStreamingServer] Transmitted " << iSendSamples << " samples for "
			<< m_pInputStream->GetNumberOfChannels() << " channels" << std::endl;
Anne's avatar
Anne committed
186
#endif
187

188 189 190 191
		oLog.iTransmittedSamples = iSendBlocks * m_pInputStream->GetBlocklength();
	}
	
	// Try-read incoming messages from client (e.g. regular status information)
192
	m_pMessage->ResetMessage();
193 194
	m_swTryReadBlockStats.start();
	m_swTryReadAccessStats.start();
195
	if( m_pMessage->ReadMessage( 1 ) )
196
	{
197
		m_swTryReadAccessStats.stop();
198 199
		int iMsgType = m_pMessage->GetMessageType();
		switch( iMsgType )
200
		{
201 202
		case CITANetAudioProtocol::NP_CLIENT_SENDING_RINGBUFFER_FREE_SAMPLES:
		{
203 204
			m_iEstimatedClientRingBufferFreeSamples = m_pMessage->ReadInt();
			m_dLastTimeStamp = dNow;
205 206 207 208
			break;
		}
		case CITANetAudioProtocol::NP_CLIENT_CLOSE:
		{
209 210 211
			// Stop here because answer on client close might be blocking, we don't want that in our statistics
			m_swTryReadBlockStats.stop();

212 213 214 215 216 217 218 219 220 221 222
			m_pMessage->ResetMessage();
			m_pMessage->SetMessageType( CITANetAudioProtocol::NP_SERVER_CLOSE );
			m_pMessage->WriteMessage();

			StopGently( false );
			m_pConnection = NULL;
			Stop();
			break;
		}
		default:
		{
223
			vstr::out() << "[ ITANetAudioStreamingServer ] Unkown protocol type : " << iMsgType << std::endl;
224 225
			break;
		}
226
		}
227 228

		oLog.sProtocolStatus = CITANetAudioProtocol::GetNPMessageID( iMsgType );
229
	}
230 231
	else
	{
232 233 234
		// There is no status message, so we estimate the client-side ring buffer status
		const double dTimeDiff = dNow - m_dLastTimeStamp;
		m_dLastTimeStamp = dNow;
235
		double dEstimatedSamples = dTimeDiff * m_pInputStream->GetSampleRate();
236 237
		m_iEstimatedClientRingBufferFreeSamples += ( int ) dEstimatedSamples;
		oLog.sProtocolStatus = "SERVER_ESTIMATION";
238
	}
239 240 241 242 243
	if( m_swTryReadBlockStats.started() ) // only stop if still running
		m_swTryReadBlockStats.stop();
	
	oLog.iEstimatedFreeSamples = m_iEstimatedClientRingBufferFreeSamples;
	m_pServerLogger->log( oLog );
244

Anne's avatar
Anne committed
245
	return false;
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
246 247
}

248 249
void CITANetAudioStreamingServer::SetInputStream( ITADatasource* pInStream )
{
250
	if( VistaThreadLoop::IsRunning() )
251 252 253
		ITA_EXCEPT1( MODAL_EXCEPTION, "Streaming loop already running, can not change input stream" );

	m_pInputStream = pInStream;
254 255 256
	m_oServerParams.dSampleRate = m_pInputStream->GetSampleRate();
	m_oServerParams.iBlockSize = m_pInputStream->GetBlocklength();
	m_oServerParams.iChannels = m_pInputStream->GetNumberOfChannels();
257 258
}

259
ITADatasource* CITANetAudioStreamingServer::GetInputStream() const
Anne's avatar
Anne committed
260 261 262 263
{
	return m_pInputStream;
}

264
int CITANetAudioStreamingServer::GetNetStreamBlocklength() const
265
{
266
	return m_sfTempTransmitBuffer.GetLength();
267 268
}

269 270 271 272 273 274 275 276 277 278
int CITANetAudioStreamingServer::GetSendingBlockLength() const
{
	return m_iSendingBlockLength;
}

void CITANetAudioStreamingServer::SetSendingBlockLength(const int iSendingBlockLength)
{
	m_iSendingBlockLength = iSendingBlockLength;
}

279
int CITANetAudioStreamingServer::GetNetStreamNumberOfChannels() const
280
{
281
	return m_sfTempTransmitBuffer.channels();
282 283
}

284
void CITANetAudioStreamingServer::SetAutomaticUpdateRate()
285 286 287 288
{
	m_iUpdateStrategy = AUTO;
}

289 290 291 292 293 294 295 296 297
void CITANetAudioStreamingServer::SetTargetLatencySamples( const int iTargetLatency )
{
	// Streaming already set up?
	if( IsClientConnected() && m_iTargetLatencySamples < m_oServerParams.iBlockSize )
		ITA_EXCEPT1( INVALID_PARAMETER, "Target latency has to be at least the block size of the audio streaming at client side." );

	m_iTargetLatencySamples = iTargetLatency;
}

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
void CITANetAudioStreamingServer::SetServerLogBaseName( const std::string& sBaseName )
{
	if( IsClientConnected() )
		ITA_EXCEPT1( MODAL_EXCEPTION, "Streaming and logging already started." );

	assert( !m_sServerLogBaseName.empty() );
	m_sServerLogBaseName = sBaseName;
}

std::string CITANetAudioStreamingServer::GetServerLogBaseName() const
{
	return m_sServerLogBaseName;
}

bool CITANetAudioStreamingServer::IsClientConnected() const
313
{
314
	return m_pNetAudioServer->IsConnected();
315 316
}

317
std::string CITANetAudioStreamingServer::GetNetworkAddress() const
318
{
319
	return m_pNetAudioServer->GetServerAddress();
320 321
}

322
int CITANetAudioStreamingServer::GetNetworkPort() const
323
{
324
	return m_pNetAudioServer->GetNetworkPort();
325 326
}

327
void CITANetAudioStreamingServer::Stop()
Anne's avatar
Anne committed
328
{
329
	m_pNetAudioServer->Stop();
Anne Heimes's avatar
bugfix  
Anne Heimes committed
330
	m_pMessage->ClearConnection();
Anne's avatar
Anne committed
331
}