ITANetAudioStreamingServer.cpp 10.9 KB
Newer Older
Anne's avatar
Anne committed
1
#include <ITANetAudioStreamingServer.h>
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
2 3 4

#include "ITANetAudioServer.h"
#include "ITANetAudioMessage.h"
Anne's avatar
Anne committed
5 6

// ITA includes
Anne's avatar
Anne committed
7
#include <ITADataSource.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
	: m_pInputStream( NULL )
	, m_pConnection( NULL )
	, m_pNetAudioServer( new CITANetAudioServer() )
	, m_dLastTimeStamp( 0 )
64
	, m_iTargetLatencySamples( -1 )
65
	, m_sServerLogBaseName( "ITANetAudioStreamingServer" )
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
66 67 68 69
	, m_bExportLogs( false )
	, m_iMaxSendBlocks( 40 )
	, m_iServerBlockId( 0 )
	, m_iEstimatedClientRingBufferFreeSamples( 0 )
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
70
	, m_iClientRingBufferSize( 0 )
71
{
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
72
	// Careful with this:
73
	//SetPriority( VistaPriority::VISTA_MID_PRIORITY );
Anne's avatar
Anne committed
74 75
}

76 77 78
CITANetAudioStreamingServer::~CITANetAudioStreamingServer()
{
	delete m_pNetAudioServer;
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
79 80 81

	if( m_bExportLogs == false )
		m_pServerLogger->setOutputFile( "" ); // disables export
82
	delete m_pServerLogger;
83 84 85

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

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

93
	if( !m_pNetAudioServer->Start( sAddress, iPort ) ) // blocking
94 95
		return false;

96
	m_pConnection = m_pNetAudioServer->GetConnection();
97

98
	m_pMessage = new CITANetAudioMessage( m_pConnection->GetByteorderSwapFlag() );
Jonas Stienen's avatar
Jonas Stienen committed
99 100
	m_pMessage->SetMessageLoggerBaseName( GetServerLogBaseName() + "_Messages" );

101
	m_pMessage->ResetMessage();
102
	m_pMessage->SetConnection( m_pConnection );
103
	while( !m_pMessage->ReadMessage( 0 ) ); //blocking
104

105 106
	assert( m_pMessage->GetMessageType() == CITANetAudioProtocol::NP_CLIENT_OPEN );
	CITANetAudioProtocol::StreamingParameters oClientParams = m_pMessage->ReadStreamingParameters();
107

Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
108 109 110 111 112
	CITANetAudioProtocol::StreamingParameters oServerParams;
	oServerParams.iRingBufferSize = oClientParams.iRingBufferSize;
	oServerParams.iBlockSize = m_pInputStream->GetBlocklength();
	oServerParams.dSampleRate = m_pInputStream->GetSampleRate();
	oServerParams.iChannels = m_pInputStream->GetNumberOfChannels();
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
113

Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
114 115 116
	m_iEstimatedClientRingBufferFreeSamples = oServerParams.iRingBufferSize;
	m_iClientRingBufferSize = oClientParams.iRingBufferSize;
	m_iSendingBlockLength = oServerParams.iBlockSize;
117

Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
118
	m_sfTempTransmitBuffer.init( m_pInputStream->GetNumberOfChannels(), oServerParams.iRingBufferSize, true );
119 120 121

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

Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
124
	if( oServerParams == oClientParams )
Anne's avatar
Anne committed
125
	{
126 127 128 129
		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
130
#ifdef NET_AUDIO_SHOW_TRAFFIC
131
		vstr::out() << "[ITANetAudioStreamingServer] Server and client parameters matched. Will resume with streaming" << std::endl;
Anne Heimes's avatar
Anne Heimes committed
132
#endif
133 134 135 136

		Run(); // Start thread loop

		return true;
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
137 138 139
	}
	else
	{
140 141 142
		m_pMessage->SetMessageType( CITANetAudioProtocol::NP_SERVER_REFUSED_INVALID_PARAMETERS );
		m_pMessage->WriteMessage();

Anne Heimes's avatar
Anne Heimes committed
143
#ifdef NET_AUDIO_SHOW_TRAFFIC
144
		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
145
#endif
146

147 148
		return false;
	}
Anne's avatar
Anne committed
149 150
}

151
bool CITANetAudioStreamingServer::LoopBody()
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
152
{
153 154
	const double dNow = ITAClock::getDefaultClock()->getTime();

Anne's avatar
Anne committed
155
	ITAServerLog oLog;
156
	oLog.dWorldTimeStamp = dNow;
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
157
	oLog.uiBlockId = ++m_iServerBlockId;
158 159 160
	oLog.iTransmittedSamples = 0;
	
	// Sending Samples
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
161
	int iEstimatedClientRingBufferTargetLatencyFreeSamples = m_iEstimatedClientRingBufferFreeSamples - ( m_iClientRingBufferSize - m_iTargetLatencySamples );
162

163
	if (iEstimatedClientRingBufferTargetLatencyFreeSamples >= m_iSendingBlockLength)
Anne's avatar
Anne committed
164 165
	{
		// Send Samples
166
		int iSendBlocks = iEstimatedClientRingBufferTargetLatencyFreeSamples / m_iSendingBlockLength;
167

168
		// Besser wre vermutlich, gleich alle samples zu senden und nicht nur einen Block nach dem anderen
169 170
		if (m_sfTempTransmitBuffer.GetLength() != m_iSendingBlockLength)
			m_sfTempTransmitBuffer.init(m_pInputStream->GetNumberOfChannels(), m_iSendingBlockLength, false);
171 172

		for( int j = 0; j < iSendBlocks; j++ )
173
		{
174
			for( int i = 0; i < int( m_pInputStream->GetNumberOfChannels() ); i++ )
175 176
			{
				ITAStreamInfo oStreamInfo;
177
				oStreamInfo.nSamples = m_iSendingBlockLength;
178 179

				const float* pfData = m_pInputStream->GetBlockPointer( i, &oStreamInfo );
180
				if( pfData != 0 )
181
					m_sfTempTransmitBuffer[i].write(pfData, m_iSendingBlockLength, 0);
182
			}
183

184
			m_pInputStream->IncrementBlockPointer();
185 186 187

			m_pMessage->ResetMessage();
			m_pMessage->SetMessageType( CITANetAudioProtocol::NP_SERVER_SENDING_SAMPLES );
Anne Heimes's avatar
Anne Heimes committed
188
			m_pMessage->WriteSampleFrame( &m_sfTempTransmitBuffer );
189
			m_pMessage->WriteMessage();
190
			m_iEstimatedClientRingBufferFreeSamples -= m_iSendingBlockLength;
Anne Heimes's avatar
Anne Heimes committed
191
		}
192

Anne's avatar
Anne committed
193
#ifdef NET_AUDIO_SHOW_TRAFFIC
194 195
		vstr::out() << "[ITANetAudioStreamingServer] Transmitted " << iSendSamples << " samples for "
			<< m_pInputStream->GetNumberOfChannels() << " channels" << std::endl;
Anne's avatar
Anne committed
196
#endif
197

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

222 223 224 225 226 227 228 229 230 231 232
			m_pMessage->ResetMessage();
			m_pMessage->SetMessageType( CITANetAudioProtocol::NP_SERVER_CLOSE );
			m_pMessage->WriteMessage();

			StopGently( false );
			m_pConnection = NULL;
			Stop();
			break;
		}
		default:
		{
233
			vstr::out() << "[ ITANetAudioStreamingServer ] Unkown protocol type : " << iMsgType << std::endl;
234 235
			break;
		}
236
		}
237 238

		oLog.sProtocolStatus = CITANetAudioProtocol::GetNPMessageID( iMsgType );
239
	}
240 241
	else
	{
242 243 244
		// There is no status message, so we estimate the client-side ring buffer status
		const double dTimeDiff = dNow - m_dLastTimeStamp;
		m_dLastTimeStamp = dNow;
245
		double dEstimatedSamples = dTimeDiff * m_pInputStream->GetSampleRate();
246 247
		m_iEstimatedClientRingBufferFreeSamples += ( int ) dEstimatedSamples;
		oLog.sProtocolStatus = "SERVER_ESTIMATION";
248
	}
249 250 251 252 253
	if( m_swTryReadBlockStats.started() ) // only stop if still running
		m_swTryReadBlockStats.stop();
	
	oLog.iEstimatedFreeSamples = m_iEstimatedClientRingBufferFreeSamples;
	m_pServerLogger->log( oLog );
254

Anne's avatar
Anne committed
255
	return false;
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
256 257
}

258 259
void CITANetAudioStreamingServer::SetInputStream( ITADatasource* pInStream )
{
260
	if( VistaThreadLoop::IsRunning() )
261 262 263 264 265
		ITA_EXCEPT1( MODAL_EXCEPTION, "Streaming loop already running, can not change input stream" );

	m_pInputStream = pInStream;
}

266
ITADatasource* CITANetAudioStreamingServer::GetInputStream() const
Anne's avatar
Anne committed
267 268 269 270
{
	return m_pInputStream;
}

271
int CITANetAudioStreamingServer::GetNetStreamBlocklength() const
272
{
273
	return m_sfTempTransmitBuffer.GetLength();
274 275
}

276 277 278 279 280 281 282 283 284 285
int CITANetAudioStreamingServer::GetSendingBlockLength() const
{
	return m_iSendingBlockLength;
}

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

286
int CITANetAudioStreamingServer::GetNetStreamNumberOfChannels() const
287
{
288
	return m_sfTempTransmitBuffer.channels();
289 290
}

Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
291 292 293 294 295 296
void CITANetAudioStreamingServer::SetLoggingExportEnabled( bool bEnabled )
{
	m_bExportLogs = bEnabled;
}

bool CITANetAudioStreamingServer::GetLoggingExportEnabled() const
297
{
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
298
	return m_bExportLogs;
299 300
}

301 302 303
void CITANetAudioStreamingServer::SetTargetLatencySamples( const int iTargetLatency )
{
	// Streaming already set up?
Dipl.-Ing. Jonas Stienen's avatar
Dipl.-Ing. Jonas Stienen committed
304 305 306 307 308 309
	if( IsClientConnected() )
		ITA_EXCEPT1( MODAL_EXCEPTION, "Server not connected, client ring buffer unkown" );

	if( m_pInputStream )
		if( m_iTargetLatencySamples < m_pInputStream->GetBlocklength() )
			ITA_EXCEPT1( INVALID_PARAMETER, "Target latency has to be at least the block size of the audio streaming at client side." );
310 311 312 313

	m_iTargetLatencySamples = iTargetLatency;
}

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
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
329
{
330
	return m_pNetAudioServer->IsConnected();
331 332
}

333
std::string CITANetAudioStreamingServer::GetNetworkAddress() const
334
{
335
	return m_pNetAudioServer->GetServerAddress();
336 337
}

338
int CITANetAudioStreamingServer::GetNetworkPort() const
339
{
340
	return m_pNetAudioServer->GetNetworkPort();
341 342
}

343
void CITANetAudioStreamingServer::Stop()
Anne's avatar
Anne committed
344
{
345
	m_pNetAudioServer->Stop();
Anne Heimes's avatar
bugfix  
Anne Heimes committed
346
	m_pMessage->ClearConnection();
Anne's avatar
Anne committed
347
}