ovasCAcquisitionServer.cpp 38.6 KB
Newer Older
Jozef Legeny's avatar
Jozef Legeny committed
1 2 3
#include "ovasCAcquisitionServer.h"
#include "ovasIAcquisitionServerPlugin.h"

Jozef Legeny's avatar
Jozef Legeny committed
4
#include <toolkit/ovtk_all.h>
Jozef Legeny's avatar
Jozef Legeny committed
5
#include <openvibe/ovITimeArithmetics.h>
Jozef Legeny's avatar
Jozef Legeny committed
6 7 8

#include <ovp_global_defines.h>

9 10
#include <system/ovCMemory.h>
#include <system/ovCTime.h>
Jozef Legeny's avatar
Jozef Legeny committed
11 12 13 14 15 16 17 18 19 20 21 22

#include <fstream>
#include <sstream>

#include <string>
#include <algorithm>
#include <functional>
#include <cctype>
#include <cstring>

#include <cassert>

23
#include <mutex>
Jozef Legeny's avatar
Jozef Legeny committed
24

25
#include <iostream>
Jozef Legeny's avatar
Jozef Legeny committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

#define boolean OpenViBE::boolean

namespace
{
	// because std::tolower has multiple signatures,
	// it can not be easily used in std::transform
	// this workaround is taken from http://www.gcek.net/ref/books/sw/cpp/ticppv2/
	template <class charT>
	charT to_lower(charT c)
	{
		return std::tolower(c);
	}
};

using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBEAcquisitionServer;
using namespace std;

namespace OpenViBEAcquisitionServer
{
	class CDriverContext : public OpenViBEAcquisitionServer::IDriverContext
	{
	public:

		CDriverContext(const OpenViBE::Kernel::IKernelContext& rKernelContext, OpenViBEAcquisitionServer::CAcquisitionServer& rAcquisitionServer)
			:m_rKernelContext(rKernelContext)
			,m_rAcquisitionServer(rAcquisitionServer)
		{
		}

		virtual ILogManager& getLogManager(void) const
		{
			return m_rKernelContext.getLogManager();
		}

		virtual IConfigurationManager& getConfigurationManager(void) const
		{
			return m_rKernelContext.getConfigurationManager();
		}

		virtual boolean isConnected(void) const
		{
			return m_rAcquisitionServer.isConnected();
		}

		virtual boolean isStarted(void) const
		{
			return m_rAcquisitionServer.isStarted();
		}

		virtual boolean isImpedanceCheckRequested(void) const
		{
			return m_rAcquisitionServer.isImpedanceCheckRequested();
		}

83 84 85 86 87
		virtual boolean isChannelSelectionRequested(void) const
		{
			return m_rAcquisitionServer.isChannelSelectionRequested();
		}

Jozef Legeny's avatar
Jozef Legeny committed
88 89
		virtual int64 getDriftSampleCount(void) const
		{
90
			return m_rAcquisitionServer.m_oDriftCorrection.getDriftSampleCount();
Jozef Legeny's avatar
Jozef Legeny committed
91 92 93 94
		}

		virtual boolean correctDriftSampleCount(int64 i64SampleCount)
		{
95 96 97 98 99
			return m_rAcquisitionServer.m_oDriftCorrection.correctDrift(i64SampleCount, 
				m_rAcquisitionServer.m_ui64SampleCount,
				m_rAcquisitionServer.m_vPendingBuffer,
				m_rAcquisitionServer.m_oPendingStimulationSet,
				m_rAcquisitionServer.m_vSwapBuffer);
Jozef Legeny's avatar
Jozef Legeny committed
100 101 102 103
		}

		virtual int64 getDriftToleranceSampleCount(void) const
		{
104
			return m_rAcquisitionServer.m_oDriftCorrection.getDriftToleranceSampleCount();
Jozef Legeny's avatar
Jozef Legeny committed
105 106 107 108
		}

		virtual int64 getSuggestedDriftCorrectionSampleCount(void) const
		{
109
			return m_rAcquisitionServer.m_oDriftCorrection.getSuggestedDriftCorrectionSampleCount();
Jozef Legeny's avatar
Jozef Legeny committed
110 111 112 113
		}

		virtual boolean setInnerLatencySampleCount(int64 i64SampleCount)
		{
114
			return m_rAcquisitionServer.m_oDriftCorrection.setInnerLatencySampleCount(i64SampleCount);
Jozef Legeny's avatar
Jozef Legeny committed
115 116 117 118
		}

		virtual int64 getInnerLatencySampleCount(void) const
		{
119
			return m_rAcquisitionServer.m_oDriftCorrection.getInnerLatencySampleCount();
Jozef Legeny's avatar
Jozef Legeny committed
120 121 122 123 124 125 126
		}

		virtual boolean updateImpedance(const uint32 ui32ChannelIndex, const float64 f64Impedance)
		{
			return m_rAcquisitionServer.updateImpedance(ui32ChannelIndex, f64Impedance);
		}

127 128 129 130 131
		virtual uint64 getStartTime(void) const
		{
			return m_rAcquisitionServer.m_ui64StartTime;
		}

Jozef Legeny's avatar
Jozef Legeny committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
	protected:

		const IKernelContext& m_rKernelContext;
		CAcquisitionServer& m_rAcquisitionServer;
	};

	class CConnectionServerHandlerThread
	{
	public:
		CConnectionServerHandlerThread(CAcquisitionServer& rAcquisitionServer, Socket::IConnectionServer& rConnectionServer)
			:m_rAcquisitionServer(rAcquisitionServer)
			,m_rConnectionServer(rConnectionServer)
		{
		}

		void operator()(void)
		{
			Socket::IConnection* l_pConnection=NULL;
			do
			{
				l_pConnection=m_rConnectionServer.accept();
				m_rAcquisitionServer.acceptNewConnection(l_pConnection);
			}
			while(l_pConnection && m_rAcquisitionServer.isConnected());
		}

		CAcquisitionServer& m_rAcquisitionServer;
		Socket::IConnectionServer& m_rConnectionServer;
	};

	class CConnectionClientHandlerThread
	{
	public:
		CConnectionClientHandlerThread(CAcquisitionServer& rAcquisitionServer, Socket::IConnection& rConnection)
			:m_rAcquisitionServer(rAcquisitionServer)
			,m_rConnection(rConnection)
		{
		}

		void operator()(void)
		{
			do
			{
				CMemoryBuffer* l_pMemoryBuffer=NULL;

				{
178 179
					DoubleLock lock(&m_oPendingBufferProtectionMutex, &m_oPendingBufferExecutionMutex);

Jozef Legeny's avatar
Jozef Legeny committed
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
					if(m_vPendingBuffer.size())
					{
						l_pMemoryBuffer=m_vPendingBuffer.front();
						m_vPendingBuffer.pop_front();
					}
				}

				if(l_pMemoryBuffer)
				{
					uint64 l_ui64MemoryBufferSize=l_pMemoryBuffer->getSize();
					m_rConnection.sendBufferBlocking(&l_ui64MemoryBufferSize, sizeof(l_ui64MemoryBufferSize));
					m_rConnection.sendBufferBlocking(l_pMemoryBuffer->getDirectPointer(), (uint32)l_pMemoryBuffer->getSize());
					delete l_pMemoryBuffer;
				}
				else
				{
					System::Time::sleep((uint32)m_rAcquisitionServer.m_ui64StartedDriverSleepDuration);
				}
			}
			while(m_rConnection.isConnected());

			while(m_vPendingBuffer.size())
			{
				delete m_vPendingBuffer.front();
				m_vPendingBuffer.pop_front();
			}
		}

		void scheduleBuffer(const IMemoryBuffer& rMemoryBuffer)
		{
			CMemoryBuffer* l_pMemoryBuffer=new CMemoryBuffer(rMemoryBuffer);
211 212 213

			DoubleLock lock(&m_oPendingBufferProtectionMutex, &m_oPendingBufferExecutionMutex);

Jozef Legeny's avatar
Jozef Legeny committed
214 215 216 217 218 219 220
			m_vPendingBuffer.push_back(l_pMemoryBuffer);
		}

		CAcquisitionServer& m_rAcquisitionServer;
		Socket::IConnection& m_rConnection;

		std::deque < CMemoryBuffer* > m_vPendingBuffer;
221 222 223 224

		// See class DoubleLock
		std::mutex m_oPendingBufferProtectionMutex;
		std::mutex m_oPendingBufferExecutionMutex;
Jozef Legeny's avatar
Jozef Legeny committed
225 226 227 228 229 230 231 232 233 234 235 236
	};

	static void start_connection_client_handler_thread(CConnectionClientHandlerThread* pThread)
	{
		(*pThread)();
	}
}

//___________________________________________________________________//
//                                                                   //

CAcquisitionServer::CAcquisitionServer(const IKernelContext& rKernelContext)
237
	:m_pConnectionServerHandlerStdThread(NULL)
Jozef Legeny's avatar
Jozef Legeny committed
238 239 240 241 242 243 244 245 246
	,m_rKernelContext(rKernelContext)
	,m_pDriverContext(NULL)
	,m_pDriver(NULL)
	,m_pStreamEncoder(NULL)
	,m_pConnectionServer(NULL)
	,m_eNaNReplacementPolicy(NaNReplacementPolicy_LastCorrectValue)
	,m_bReplacementInProgress(false)
	,m_bInitialized(false)
	,m_bStarted(false)
247
	,m_ui64StartTime(0)
Jussi Lindgren's avatar
Jussi Lindgren committed
248
	,m_ui64LastDeliveryTime(0)
249
	,m_oDriftCorrection(rKernelContext)
Jozef Legeny's avatar
Jozef Legeny committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263
{
	m_pDriverContext=new CDriverContext(rKernelContext, *this);

	m_pStreamEncoder=&m_rKernelContext.getAlgorithmManager().getAlgorithm(m_rKernelContext.getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_MasterAcquisitionStreamEncoder));
	// m_pStreamEncoder=&m_rKernelContext.getAlgorithmManager().getAlgorithm(m_rKernelContext.getAlgorithmManager().createAlgorithm(OVP_ClassId_GD_Algorithm_MasterAcquisitionStreamEncoderCSV));
	m_pStreamEncoder->initialize();

	ip_ui64SubjectIdentifier.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_SubjectIdentifier));
	ip_ui64SubjectAge.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_SubjectAge));
	ip_ui64SubjectGender.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_SubjectGender));
	ip_pSignalMatrix.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_SignalMatrix));
	ip_ui64SignalSamplingRate.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_SignalSamplingRate));
	ip_pStimulationSet.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_StimulationSet));
	ip_ui64BufferDuration.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_BufferDuration));
264
	ip_pChannelUnits.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_ChannelUnits));
Jozef Legeny's avatar
Jozef Legeny committed
265 266
	op_pEncodedMemoryBuffer.initialize(m_pStreamEncoder->getOutputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_OutputParameterId_EncodedMemoryBuffer));

267 268 269
	ip_bEncodeChannelLocalisationData.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_EncodeChannelLocalisationData));
	ip_bEncodeChannelUnitData.initialize(m_pStreamEncoder->getInputParameter(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputParameterId_EncodeChannelUnitData));

Jozef Legeny's avatar
Jozef Legeny committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
	CString l_sNaNReplacementPolicy=m_rKernelContext.getConfigurationManager().expand("${AcquisitionServer_NaNReplacementPolicy}");
	if(l_sNaNReplacementPolicy==CString("Disabled"))
	{
		this->setNaNReplacementPolicy(NaNReplacementPolicy_Disabled);
	}
	else if(l_sNaNReplacementPolicy==CString("Zero"))
	{
		this->setNaNReplacementPolicy(NaNReplacementPolicy_Zero);
	}
	else
	{
		this->setNaNReplacementPolicy(NaNReplacementPolicy_LastCorrectValue);
	}

	this->setOversamplingFactor(m_rKernelContext.getConfigurationManager().expandAsUInteger("${AcquisitionServer_OverSamplingFactor}", 1));
	this->setImpedanceCheckRequest(m_rKernelContext.getConfigurationManager().expandAsBoolean("${AcquisitionServer_CheckImpedance}", false));
286
	this->setChannelSelectionRequest(m_rKernelContext.getConfigurationManager().expandAsBoolean("${AcquisitionServer_ChannelSelection}", false));
Jozef Legeny's avatar
Jozef Legeny committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319

	m_ui64StartedDriverSleepDuration=m_rKernelContext.getConfigurationManager().expandAsUInteger("${AcquisitionServer_StartedDriverSleepDuration}", 2);
	m_ui64StoppedDriverSleepDuration=m_rKernelContext.getConfigurationManager().expandAsUInteger("${AcquisitionServer_StoppedDriverSleepDuration}", 100);
	m_ui64DriverTimeoutDuration=m_rKernelContext.getConfigurationManager().expandAsUInteger("${AcquisitionServer_DriverTimeoutDuration}", 5000);

	for(std::vector<IAcquisitionServerPlugin*>::iterator itp = m_vPlugins.begin(); itp != m_vPlugins.end(); ++itp)
	{
		(*itp)->createHook();
	}
}

CAcquisitionServer::~CAcquisitionServer(void)
{
	if(m_bStarted)
	{
		m_pDriver->stop();
		// m_pDriverContext->onStop(*m_pDriver->getHeader());
		m_bStarted=false;
	}

	if(m_bInitialized)
	{
		m_pDriver->uninitialize();
		// m_pDriverContext->onUninitialize(*m_pDriver->getHeader());
		m_bInitialized=false;
	}

	if(m_pConnectionServer)
	{
		m_pConnectionServer->release();
		m_pConnectionServer=NULL;
	}

320 321 322 323 324 325 326 327
	/* -- should already be empty after call to stop -- */
	/*
    list < pair < Socket::IConnection*, SConnectionInfo > >::iterator itConnection=m_vConnection.begin();
    while(itConnection!=m_vConnection.end())
    {
	itConnection->first->release();
	itConnection=m_vConnection.erase(itConnection);
    }
Jozef Legeny's avatar
Jozef Legeny committed
328 329 330 331 332 333 334 335 336 337
*/

	ip_ui64SubjectIdentifier.uninitialize();
	ip_ui64SubjectAge.uninitialize();
	ip_ui64SubjectGender.uninitialize();
	ip_pSignalMatrix.uninitialize();
	ip_ui64SignalSamplingRate.uninitialize();
	ip_pStimulationSet.uninitialize();
	ip_ui64BufferDuration.uninitialize();
	op_pEncodedMemoryBuffer.uninitialize();
338 339 340 341
	ip_pChannelUnits.uninitialize();

	ip_bEncodeChannelLocalisationData.uninitialize();
	ip_bEncodeChannelUnitData.uninitialize();
Jozef Legeny's avatar
Jozef Legeny committed
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

	m_pStreamEncoder->uninitialize();
	m_rKernelContext.getAlgorithmManager().releaseAlgorithm(*m_pStreamEncoder);
	m_pStreamEncoder=NULL;

	delete m_pDriverContext;
	m_pDriverContext=NULL;
}

IDriverContext& CAcquisitionServer::getDriverContext(void)
{
	return *m_pDriverContext;
}

uint32 CAcquisitionServer::getClientCount(void)
{
	return uint32(m_vConnection.size());
}


float64 CAcquisitionServer::getImpedance(const uint32 ui32ChannelIndex)
{
	if(ui32ChannelIndex < m_vImpedance.size())
	{
		return m_vImpedance[ui32ChannelIndex];
	}
	return OVAS_Impedance_Unknown;
}

//___________________________________________________________________//
//                                                                   //

boolean CAcquisitionServer::loop(void)
{
	// m_rKernelContext.getLogManager() << LogLevel_Debug << "idleCB\n";

	list < pair < Socket::IConnection*, SConnectionInfo > >::iterator itConnection;

	// Searches for new connection(s)
	if(m_pConnectionServer)
	{
383
		DoubleLock lock(&m_oPendingConnectionProtectionMutex, &m_oPendingConnectionExecutionMutex);
Jozef Legeny's avatar
Jozef Legeny committed
384 385 386 387 388 389 390 391 392 393 394 395

		for(itConnection=m_vPendingConnection.begin(); itConnection!=m_vPendingConnection.end(); itConnection++)
		{
			m_rKernelContext.getLogManager() << LogLevel_Info << "Received new connection...\n";

			Socket::IConnection* l_pConnection=itConnection->first;
			if(this->isStarted())
			{
				// When a new connection is found and the
				// acq server is started, send the header

				// Computes inner data to skip
396
				int64 l_i64SignedTheoreticalSampleCountToSkip=0;
397
				if(m_oDriftCorrection.isActive())
Jozef Legeny's avatar
Jozef Legeny committed
398
				{
399
					l_i64SignedTheoreticalSampleCountToSkip=((int64(itConnection->second.m_ui64ConnectionTime-m_ui64StartTime)*m_ui32SamplingFrequency)>>32)-m_ui64SampleCount+m_vPendingBuffer.size();
Jozef Legeny's avatar
Jozef Legeny committed
400 401 402
				}
				else
				{
403
					l_i64SignedTheoreticalSampleCountToSkip=((int64(itConnection->second.m_ui64ConnectionTime-m_ui64LastDeliveryTime)*m_ui32SamplingFrequency)>>32)+m_vPendingBuffer.size();
Jozef Legeny's avatar
Jozef Legeny committed
404 405
				}

406
				uint64 l_ui64TheoreticalSampleCountToSkip=(l_i64SignedTheoreticalSampleCountToSkip<0?0:uint64(l_i64SignedTheoreticalSampleCountToSkip));
Jozef Legeny's avatar
Jozef Legeny committed
407

408
				m_rKernelContext.getLogManager() << LogLevel_Trace << "Sample count offset at connection : " << l_ui64TheoreticalSampleCountToSkip << "\n";
Jozef Legeny's avatar
Jozef Legeny committed
409 410 411

				SConnectionInfo l_oInfo;
				l_oInfo.m_ui64ConnectionTime=itConnection->second.m_ui64ConnectionTime;
412 413
				l_oInfo.m_ui64StimulationTimeOffset=ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, l_ui64TheoreticalSampleCountToSkip+m_ui64SampleCount-m_vPendingBuffer.size());
				l_oInfo.m_ui64SignalSampleCountToSkip=l_ui64TheoreticalSampleCountToSkip;
Jozef Legeny's avatar
Jozef Legeny committed
414
				l_oInfo.m_pConnectionClientHandlerThread=new CConnectionClientHandlerThread(*this, *l_pConnection);
415
				l_oInfo.m_pConnectionClientHandlerStdThread=new std::thread(std::bind(&start_connection_client_handler_thread, l_oInfo.m_pConnectionClientHandlerThread));
416 417
				l_oInfo.m_bChannelLocalisationSent = false;
				l_oInfo.m_bChannelUnitsSent = false;
418
				//applyPriority(l_oInfo.m_pConnectionClientHandlerStdThread,15);
Jozef Legeny's avatar
Jozef Legeny committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

				m_vConnection.push_back(pair < Socket::IConnection*, SConnectionInfo >(l_pConnection, l_oInfo));

#if DEBUG_STREAM
				m_rKernelContext.getLogManager() << LogLevel_Debug << "Creating header\n";
#endif

				op_pEncodedMemoryBuffer->setSize(0, true);
				m_pStreamEncoder->process(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputTriggerId_EncodeHeader);

#if 0
				uint64 l_ui64MemoryBufferSize=op_pEncodedMemoryBuffer->getSize();
				l_pConnection->sendBufferBlocking(&l_ui64MemoryBufferSize, sizeof(l_ui64MemoryBufferSize));
				l_pConnection->sendBufferBlocking(op_pEncodedMemoryBuffer->getDirectPointer(), (uint32)op_pEncodedMemoryBuffer->getSize());
#else
				l_oInfo.m_pConnectionClientHandlerThread->scheduleBuffer(*op_pEncodedMemoryBuffer);
#endif
			}
			else
			{
				// When a new connection is found and the
				// acq server is _not_ started, drop the
				// connection

				m_rKernelContext.getLogManager() << LogLevel_Warning << "Dropping connection - acquisition is not started\n";
				l_pConnection->release();
			}
		}
		m_vPendingConnection.clear();
	}

	// Cleans disconnected client(s)
	for(itConnection=m_vConnection.begin(); itConnection!=m_vConnection.end(); )
	{
		Socket::IConnection* l_pConnection=itConnection->first;
		if(!l_pConnection->isConnected())
		{
			l_pConnection->release();
457
			if(itConnection->second.m_pConnectionClientHandlerStdThread)
Jozef Legeny's avatar
Jozef Legeny committed
458
			{
459 460
				itConnection->second.m_pConnectionClientHandlerStdThread->join();
				delete itConnection->second.m_pConnectionClientHandlerStdThread;
Jozef Legeny's avatar
Jozef Legeny committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
				delete itConnection->second.m_pConnectionClientHandlerThread;
			}
			itConnection=m_vConnection.erase(itConnection);
			m_rKernelContext.getLogManager() << LogLevel_Info << "Closed connection...\n";
		}
		else
		{
			itConnection++;
		}
	}

	// Handles driver's main loop
	if(m_pDriver)
	{
		boolean l_bResult;
		boolean l_bTimeout;
		if(this->isStarted())
		{
			l_bResult=true;
			l_bTimeout=false;
			m_bGotData=false;
			uint32 l_ui32StartTime=System::Time::getTime();
			while(l_bResult && !m_bGotData && !l_bTimeout)
			{
				// Calls driver's loop
				l_bResult=m_pDriver->loop();
				if(!m_bGotData)
				{
					System::Time::sleep((uint32)m_ui64StartedDriverSleepDuration);
					l_bTimeout=(System::Time::getTime()>l_ui32StartTime+m_ui64DriverTimeoutDuration);
				}
			}
			if(l_bTimeout)
			{
				m_rKernelContext.getLogManager() << LogLevel_ImportantWarning << "After " << m_ui64DriverTimeoutDuration << " milliseconds, did not receive anything from the driver - Timed out\n";
				return false;
			}
498
			if(m_bGotData && m_oDriftCorrection.getDriftCorrectionPolicy() == DriftCorrectionPolicy_Forced)
Jozef Legeny's avatar
Jozef Legeny committed
499
			{
500 501
				m_oDriftCorrection.correctDrift(m_oDriftCorrection.getSuggestedDriftCorrectionSampleCount(),
					m_ui64SampleCount, m_vPendingBuffer, m_oPendingStimulationSet, m_vSwapBuffer);
Jozef Legeny's avatar
Jozef Legeny committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
			}
		}
		else
		{
			// Calls driver's loop
			l_bResult=m_pDriver->loop();
			System::Time::sleep((uint32)m_ui64StoppedDriverSleepDuration);
		}

		// Calls driver's loop
		if(!l_bResult)
		{
			m_rKernelContext.getLogManager() << LogLevel_ImportantWarning << "Something bad happened in the loop callback, stopping the acquisition\n";
			return false;
		}
	}

	// Eventually builds up buffer and
	// sends data to connected client(s)
	while(m_vPendingBuffer.size() >= m_ui32SampleCountPerSentBlock*2)
	{
523 524 525
		const int64 p = m_ui64SampleCount-m_vPendingBuffer.size();
		if (p < 0)
			m_rKernelContext.getLogManager() << LogLevel_Error << "Signed number used for bit operations:" << p << " (case A)\n";
Jozef Legeny's avatar
Jozef Legeny committed
526

527 528 529 530
		const uint64 l_ui64BufferStartSamples = m_ui64SampleCount-m_vPendingBuffer.size();
		const uint64 l_ui64BufferEndSamples   = m_ui64SampleCount-m_vPendingBuffer.size()+m_ui32SampleCountPerSentBlock;
		const uint64 l_ui64BufferStartTime    = ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, l_ui64BufferStartSamples);
		const uint64 l_ui64BufferEndTime      = ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, l_ui64BufferEndSamples);
nfoy's avatar
nfoy committed
531
		const uint64 l_ui64SampleTime         = ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, m_ui64SampleCount);
532 533 534 535

		// Pass the stimuli and buffer to all plugins; note that they may modify them
		for(std::vector<IAcquisitionServerPlugin*>::iterator itp = m_vPlugins.begin(); itp != m_vPlugins.end(); ++itp)
		{
nfoy's avatar
nfoy committed
536
			(*itp)->loopHook(m_vPendingBuffer, m_oPendingStimulationSet, l_ui64BufferStartTime, l_ui64BufferEndTime, l_ui64SampleTime);
537 538 539
		}

		// Handle connections
Jozef Legeny's avatar
Jozef Legeny committed
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
		for(itConnection=m_vConnection.begin(); itConnection!=m_vConnection.end(); itConnection++)
		{
			// Socket::IConnection* l_pConnection=itConnection->first;
			SConnectionInfo& l_rInfo=itConnection->second;

			if(l_rInfo.m_ui64SignalSampleCountToSkip<m_ui32SampleCountPerSentBlock)
			{
#if DEBUG_STREAM
				m_rKernelContext.getLogManager() << LogLevel_Debug << "Creating buffer for connection " << uint64(l_pConnection) << "\n";
#endif

				// Signal buffer
				for(uint32 j=0; j<m_ui32ChannelCount; j++)
				{
					for(uint32 i=0; i<m_ui32SampleCountPerSentBlock; i++)
					{
						ip_pSignalMatrix->getBuffer()[j*m_ui32SampleCountPerSentBlock+i]=m_vPendingBuffer[(int)(i+l_rInfo.m_ui64SignalSampleCountToSkip)][j];
					}
				}

560 561
				//				int l = l_oStimulationSet.getStimulationCount();

562
				const int64 p = l_ui64BufferStartSamples+l_rInfo.m_ui64SignalSampleCountToSkip;
Jozef Legeny's avatar
Jozef Legeny committed
563
				if (p < 0)
564
					m_rKernelContext.getLogManager() << LogLevel_Error << "Signed number used for bit operations:" << p << " (case B)\n";
Jozef Legeny's avatar
Jozef Legeny committed
565

566 567
				const uint64 l_ui64ConnBlockStartTime = ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, l_ui64BufferStartSamples + l_rInfo.m_ui64SignalSampleCountToSkip);
				const uint64 l_ui64ConnBlockEndTime   = ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, l_ui64BufferEndSamples   + l_rInfo.m_ui64SignalSampleCountToSkip);
Jozef Legeny's avatar
Jozef Legeny committed
568

569 570 571 572
				//m_rKernelContext.getLogManager() << LogLevel_Info << "start: " << time64(start) << "end: " << time64(end) << "\n";

				// Stimulation buffer
				CStimulationSet l_oStimulationSet;
Jozef Legeny's avatar
Jozef Legeny committed
573

574
				// Take the stimuli range valid for the connection
Jozef Legeny's avatar
Jozef Legeny committed
575
				OpenViBEToolkit::Tools::StimulationSet::appendRange(
576 577
							l_oStimulationSet,
							m_oPendingStimulationSet,
578
							l_ui64ConnBlockStartTime,l_ui64ConnBlockEndTime);
Jozef Legeny's avatar
Jozef Legeny committed
579 580 581

				OpenViBEToolkit::Tools::StimulationSet::copy(*ip_pStimulationSet, l_oStimulationSet, -int64(l_rInfo.m_ui64StimulationTimeOffset));

582 583 584 585 586 587 588
				// Send a chunk of channel units? Note that we'll always send the units header.
				if(!l_rInfo.m_bChannelUnitsSent)
				{
					// If default values in channel units, don't bother sending unit data chunk
					ip_bEncodeChannelUnitData = m_pHeaderCopy->isChannelUnitSet();
					// std::cout << "Set " <<  ip_pChannelUnits->getBufferElementCount()  << "\n";
				}
Jozef Legeny's avatar
Jozef Legeny committed
589 590 591 592

				op_pEncodedMemoryBuffer->setSize(0, true);
				m_pStreamEncoder->process(OVP_GD_Algorithm_MasterAcquisitionStreamEncoder_InputTriggerId_EncodeBuffer);

593 594 595 596 597 598 599
				if(!l_rInfo.m_bChannelUnitsSent)
				{
					// Do not send again
					l_rInfo.m_bChannelUnitsSent = true;
					ip_bEncodeChannelUnitData = false;
				}

Jozef Legeny's avatar
Jozef Legeny committed
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
#if 0
				uint64 l_ui64MemoryBufferSize=op_pEncodedMemoryBuffer->getSize();
				l_pConnection->sendBufferBlocking(&l_ui64MemoryBufferSize, sizeof(l_ui64MemoryBufferSize));
				l_pConnection->sendBufferBlocking(op_pEncodedMemoryBuffer->getDirectPointer(), (uint32)op_pEncodedMemoryBuffer->getSize());
#else
				l_rInfo.m_pConnectionClientHandlerThread->scheduleBuffer(*op_pEncodedMemoryBuffer);
#endif
			}
			else
			{
				l_rInfo.m_ui64SignalSampleCountToSkip-=m_ui32SampleCountPerSentBlock;
			}
		}

		// Clears pending stimulations
		OpenViBEToolkit::Tools::StimulationSet::removeRange(
616
					m_oPendingStimulationSet,
617 618
					l_ui64BufferStartTime,
					l_ui64BufferEndTime
619
					);
Jozef Legeny's avatar
Jozef Legeny committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

		// Clears pending signal
		m_vPendingBuffer.erase(m_vPendingBuffer.begin(), m_vPendingBuffer.begin()+m_ui32SampleCountPerSentBlock);
	}

	return true;
}

//___________________________________________________________________//
//                                                                   //

boolean CAcquisitionServer::connect(IDriver& rDriver, IHeader& rHeaderCopy, uint32 ui32SamplingCountPerSentBlock, uint32 ui32ConnectionPort)
{
	m_rKernelContext.getLogManager() << LogLevel_Debug << "connect\n";

635

Jozef Legeny's avatar
Jozef Legeny committed
636
	m_pDriver=&rDriver;
637
	m_pHeaderCopy=&rHeaderCopy;
Jozef Legeny's avatar
Jozef Legeny committed
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
	m_ui32SampleCountPerSentBlock=ui32SamplingCountPerSentBlock;

	m_rKernelContext.getLogManager() << LogLevel_Info << "Connecting to device [" << CString(m_pDriver->getName()) << "]...\n";

	// Initializes driver
	if(!m_pDriver->initialize(m_ui32SampleCountPerSentBlock, *this))
	{
		m_rKernelContext.getLogManager() << LogLevel_Error << "Connection failed...\n";
		return false;
	}

	// m_pDriverContext->onInitialize(*m_pDriver->getHeader());

	m_rKernelContext.getLogManager() << LogLevel_Info << "Connection succeeded !\n";

	const IHeader& l_rHeader=*rDriver.getHeader();
654
	IHeader::copy(rHeaderCopy, l_rHeader);
Jozef Legeny's avatar
Jozef Legeny committed
655

656 657 658
	m_ui32ChannelCount=rHeaderCopy.getChannelCount();
	m_ui32SamplingFrequency=(uint32)(rHeaderCopy.getSamplingFrequency()*m_ui64OverSamplingFactor);

659 660 661 662 663 664 665
	m_vSelectedChannels.clear();
	if (m_bIsChannelSelectionRequested)
	{
		for (OpenViBE::uint32 i=0,l=0;i<m_ui32ChannelCount;++i) {
			const std::string name = rHeaderCopy.getChannelName(i);
			if (name!="") {
				m_vSelectedChannels.push_back(i);
666 667 668 669 670 671 672 673 674
				rHeaderCopy.setChannelName(l,name.c_str());

				uint32 l_ui32Unit = 0, l_ui32Factor = 0;
				if(rHeaderCopy.isChannelUnitSet())
				{
					rHeaderCopy.getChannelUnits(i, l_ui32Unit, l_ui32Factor); // no need to check, will be defaults on failure
					rHeaderCopy.setChannelUnits(l, l_ui32Unit, l_ui32Factor);
				}
				l++;
675 676 677 678 679 680 681 682 683 684
			}
		}
		rHeaderCopy.setChannelCount(m_vSelectedChannels.size());
		m_ui32ChannelCount = rHeaderCopy.getChannelCount();

	} else {

		for (OpenViBE::uint32 i=0;i<m_ui32ChannelCount;++i)
			m_vSelectedChannels.push_back(i);
	}
685 686 687 688 689 690 691
	
	// These are passed to plugins
	m_vSelectedChannelNames.clear();
	for(uint32 i=0;i<rHeaderCopy.getChannelCount();i++) 
	{
		m_vSelectedChannelNames.push_back(CString(rHeaderCopy.getChannelName(i)));
	}
Jozef Legeny's avatar
Jozef Legeny committed
692 693 694

	if(m_ui32ChannelCount==0)
	{
695 696 697 698 699
		std::stringstream ss;
		ss << "Driver claimed to have " << uint32(0) << " channel";
		if (isChannelSelectionRequested())
			ss << "(check whether the property `Select only named channel' is set).\n";
		m_rKernelContext.getLogManager() << LogLevel_Error << ss.str().c_str();
Jozef Legeny's avatar
Jozef Legeny committed
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
		return false;
	}

	if(m_ui32SamplingFrequency==0)
	{
		m_rKernelContext.getLogManager() << LogLevel_Error << "Driver claimed to have a sample frequency of " << uint32(0) << "\n";
		return false;
	}

	m_vImpedance.resize(m_ui32ChannelCount, OVAS_Impedance_NotAvailable);
	m_vSwapBuffer.resize(m_ui32ChannelCount);

	m_pConnectionServer=Socket::createConnectionServer();
	if(m_pConnectionServer->listen(ui32ConnectionPort))
	{
		m_bInitialized=true;

		m_rKernelContext.getLogManager() << LogLevel_Trace << "NaN value correction is set to ";
		switch(m_eNaNReplacementPolicy)
		{
			default:
			case NaNReplacementPolicy_LastCorrectValue: m_rKernelContext.getLogManager() << CString("LastCorrectValue") << "\n"; break;
			case NaNReplacementPolicy_Zero:             m_rKernelContext.getLogManager() << CString("Zero") << "\n"; break;
			case NaNReplacementPolicy_Disabled:         m_rKernelContext.getLogManager() << CString("Disabled") << "\n"; break;
		};

		m_rKernelContext.getLogManager() << LogLevel_Trace << "Oversampling factor set to " << m_ui64OverSamplingFactor << "\n";
		m_rKernelContext.getLogManager() << LogLevel_Trace << "Sampling frequency set to " << m_ui32SamplingFrequency << "Hz\n";
		m_rKernelContext.getLogManager() << LogLevel_Trace << "Started driver sleeping duration is " << m_ui64StartedDriverSleepDuration << " milliseconds\n";
		m_rKernelContext.getLogManager() << LogLevel_Trace << "Stopped driver sleeping duration is " << m_ui64StoppedDriverSleepDuration << " milliseconds\n";
		m_rKernelContext.getLogManager() << LogLevel_Trace << "Driver timeout duration set to " << m_ui64DriverTimeoutDuration << " milliseconds\n";

		ip_ui64BufferDuration=ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, m_ui32SampleCountPerSentBlock);

734 735 736
		ip_ui64SubjectIdentifier=rHeaderCopy.getExperimentIdentifier();
		ip_ui64SubjectAge=rHeaderCopy.getSubjectAge();
		ip_ui64SubjectGender=rHeaderCopy.getSubjectGender();
Jozef Legeny's avatar
Jozef Legeny committed
737 738 739 740 741 742 743 744 745 746 747 748

		ip_ui64SignalSamplingRate=m_ui32SamplingFrequency;
		ip_pSignalMatrix->setDimensionCount(2);
		ip_pSignalMatrix->setDimensionSize(0, m_ui32ChannelCount);
		ip_pSignalMatrix->setDimensionSize(1, m_ui32SampleCountPerSentBlock);

		m_rKernelContext.getLogManager() << LogLevel_Trace << "Sampling rate     : " << m_ui32SamplingFrequency << "\n";
		m_rKernelContext.getLogManager() << LogLevel_Trace << "Samples per block : " << m_ui32SampleCountPerSentBlock << "\n";
		m_rKernelContext.getLogManager() << LogLevel_Trace << "Channel count     : " << m_ui32ChannelCount << "\n";

		for(uint32 i=0; i<m_ui32ChannelCount; i++)
		{
749
			const std::string l_sChannelName=rHeaderCopy.getChannelName(i);
Jozef Legeny's avatar
Jozef Legeny committed
750 751 752 753 754 755 756 757 758 759 760 761 762
			if(l_sChannelName!="")
			{
				ip_pSignalMatrix->setDimensionLabel(0, i, l_sChannelName.c_str());
			}
			else
			{
				std::stringstream ss;
				ss << "Channel " << i+1;
				ip_pSignalMatrix->setDimensionLabel(0, i, ss.str().c_str());
			}
			m_rKernelContext.getLogManager() << LogLevel_Trace << "Channel name      : " << CString(ip_pSignalMatrix->getDimensionLabel(0, i)) << "\n";
		}

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
		// Construct channel units stream header & matrix
		// Note: Channel units, although part of IHeader, will be sent as a matrix chunk during loop() once - if at all - to each client
		if(m_pHeaderCopy->isChannelUnitSet())
		{
			ip_pChannelUnits->setDimensionCount(2);
			ip_pChannelUnits->setDimensionSize(0, m_ui32ChannelCount);
			ip_pChannelUnits->setDimensionSize(1,2);                    // Units, Factor
			for(uint32 c=0;c<m_ui32ChannelCount;c++)
			{
				ip_pChannelUnits->setDimensionLabel(0, c, m_pHeaderCopy->getChannelName(c));
				if(m_pHeaderCopy->isChannelUnitSet())
				{
					uint32 l_ui32Unit = 0, l_ui32Factor = 0;
				
					m_pHeaderCopy->getChannelUnits(c, l_ui32Unit, l_ui32Factor); // no need to check, will be defaults on failure

					ip_pChannelUnits->getBuffer()[c*2+0] = static_cast<float64>(l_ui32Unit);
					ip_pChannelUnits->getBuffer()[c*2+1] = static_cast<float64>(l_ui32Factor);

					m_rKernelContext.getLogManager() << LogLevel_Trace << "Channel Unit      : " << l_ui32Unit << ", factor=" << OVTK_DECODE_FACTOR(l_ui32Factor) << "\n";
				}
			}
			ip_pChannelUnits->setDimensionLabel(1, 0, "Unit");
			ip_pChannelUnits->setDimensionLabel(1, 1, "Factor");
		}
		else
		{
			// Driver did not set units. Convention: send empty header matrix in this case.
			ip_pChannelUnits->setDimensionCount(2);
			ip_pChannelUnits->setDimensionSize(0,0);
			ip_pChannelUnits->setDimensionSize(0,0);
			m_rKernelContext.getLogManager() << LogLevel_Trace << "Driver did not set units, sending empty channel units matrix\n";
		}

		// @TODO Channel localisation
		{
			ip_bEncodeChannelLocalisationData = false; // never at the moment

		}

		// @TODO Gain is ignored
Jozef Legeny's avatar
Jozef Legeny committed
804 805 806 807 808 809 810
	}
	else
	{
		m_rKernelContext.getLogManager() << LogLevel_Error << "Could not listen on TCP port (firewall problem ?)\n";
		return false;
	}

811 812
	m_pConnectionServerHandlerStdThread=new std::thread(CConnectionServerHandlerThread(*this, *m_pConnectionServer));
	//applyPriority(m_pConnectionServerHandlerStdThread,15);
Jozef Legeny's avatar
Jozef Legeny committed
813 814 815 816 817 818 819 820 821 822

	return true;
}

boolean CAcquisitionServer::start(void)
{
	m_rKernelContext.getLogManager() << LogLevel_Debug << "buttonStartPressedCB\n";

	m_rKernelContext.getLogManager() << LogLevel_Info << "Starting the acquisition...\n";

823 824 825 826 827 828
	m_vPendingBuffer.clear();
	m_oPendingStimulationSet.clear();

	m_ui64SampleCount=0;
	m_ui64LastSampleCount=0;

Jozef Legeny's avatar
Jozef Legeny committed
829 830 831 832 833 834 835 836
	// Starts driver
	if(!m_pDriver->start())
	{
		m_rKernelContext.getLogManager() << LogLevel_Error << "Starting failed !\n";
		return false;
	}
	// m_pDriverContext->onStart(*m_pDriver->getHeader());

837 838
	m_ui64StartTime = System::Time::zgetTime();
	m_ui64LastDeliveryTime = m_ui64StartTime;
Jozef Legeny's avatar
Jozef Legeny committed
839

840 841
	m_oDriftCorrection.start(m_ui32SamplingFrequency, m_ui64StartTime);

Jozef Legeny's avatar
Jozef Legeny committed
842 843
	for(std::vector<IAcquisitionServerPlugin*>::iterator itp = m_vPlugins.begin(); itp != m_vPlugins.end(); ++itp)
	{
844
		(*itp)->startHook(m_vSelectedChannelNames, m_ui32SamplingFrequency, m_ui32ChannelCount, m_ui32SampleCountPerSentBlock);
Jozef Legeny's avatar
Jozef Legeny committed
845 846
	}

847 848
	m_rKernelContext.getLogManager() << LogLevel_Info << "Now acquiring...\n";

Jozef Legeny's avatar
Jozef Legeny committed
849 850 851 852 853 854 855 856 857 858
	m_bStarted=true;
	return true;
}

boolean CAcquisitionServer::stop(void)
{
	m_rKernelContext.getLogManager() << LogLevel_Debug << "buttonStopPressedCB\n";

	m_rKernelContext.getLogManager() << LogLevel_Info << "Stopping the acquisition.\n";

859 860
	m_oDriftCorrection.printStats();
	m_oDriftCorrection.stop();
Jozef Legeny's avatar
Jozef Legeny committed
861 862 863 864 865 866 867 868 869

	// Stops driver
	m_pDriver->stop();
	// m_pDriverContext->onStop(*m_pDriver->getHeader());

	list < pair < Socket::IConnection*, SConnectionInfo > >::iterator itConnection=m_vConnection.begin();
	while(itConnection!=m_vConnection.end())
	{
		itConnection->first->close();
870
		if(itConnection->second.m_pConnectionClientHandlerStdThread)
Jozef Legeny's avatar
Jozef Legeny committed
871
		{
872 873
			itConnection->second.m_pConnectionClientHandlerStdThread->join();
			delete itConnection->second.m_pConnectionClientHandlerStdThread;
Jozef Legeny's avatar
Jozef Legeny committed
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
			delete itConnection->second.m_pConnectionClientHandlerThread;
		}
		itConnection->first->release();

		itConnection=m_vConnection.erase(itConnection);
	}

	for(std::vector<IAcquisitionServerPlugin*>::iterator itp = m_vPlugins.begin(); itp != m_vPlugins.end(); ++itp)
	{
		(*itp)->stopHook();
	}


	m_bStarted=false;


	return true;
}

boolean CAcquisitionServer::disconnect(void)
{
	m_rKernelContext.getLogManager() << LogLevel_Info << "Disconnecting.\n";

	if(m_bInitialized)
	{
		m_pDriver->uninitialize();
		// m_pDriverContext->onUninitialize(*m_pDriver->getHeader());
	}

	m_vImpedance.clear();

	if(m_pConnectionServer)
	{
		m_pConnectionServer->close();
		m_pConnectionServer->release();
		m_pConnectionServer=NULL;
	}

	m_bInitialized=false;

	// Thread joining must be done after
	// switching m_bInitialized to false
916
	if(m_pConnectionServerHandlerStdThread)
Jozef Legeny's avatar
Jozef Legeny committed
917
	{
918 919 920
		m_pConnectionServerHandlerStdThread->join();
		delete m_pConnectionServerHandlerStdThread;
		m_pConnectionServerHandlerStdThread=NULL;
Jozef Legeny's avatar
Jozef Legeny committed
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
	}

	return true;
}

//___________________________________________________________________//
//                                                                   //

void CAcquisitionServer::setSamples(const float32* pSample)
{
	if (pSample==NULL) m_rKernelContext.getLogManager() << LogLevel_Warning << "Null data detected\n";
	this->setSamples(pSample, m_ui32SampleCountPerSentBlock);
}

void CAcquisitionServer::setSamples(const float32* pSample, const uint32 ui32SampleCount)
{
	if(m_bStarted)
	{
		for(uint32 i=0; i<ui32SampleCount; i++)
		{
			if(!m_bReplacementInProgress)
			{
				// otherwise NaN are propagating
				m_vOverSamplingSwapBuffer=m_vSwapBuffer;
			}
			for(uint32 k=0; k<m_ui64OverSamplingFactor; k++)
			{
948 949 950 951
				const float32 alpha=float32(k+1)/m_ui64OverSamplingFactor;

				bool l_bHadNaN = false;

Jozef Legeny's avatar
Jozef Legeny committed
952 953
				for(uint32 j=0; j<m_ui32ChannelCount; j++)
				{
954 955
					const uint32 l_ui32Channel = m_vSelectedChannels[j];

Jozef Legeny's avatar
Jozef Legeny committed
956
#ifdef TARGET_OS_Windows
957
					if(_isnan(pSample[l_ui32Channel*ui32SampleCount+i]) || !_finite(pSample[l_ui32Channel*ui32SampleCount+i])) // NaN or infinite values
Jozef Legeny's avatar
Jozef Legeny committed
958
#else
959
					if(std::isnan(pSample[l_ui32Channel*ui32SampleCount+i]) || !finite(pSample[l_ui32Channel*ui32SampleCount+i])) // NaN or infinite values
Jozef Legeny's avatar
Jozef Legeny committed
960 961
#endif
					{
962
						l_bHadNaN = true;
Jozef Legeny's avatar
Jozef Legeny committed
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980

						switch(m_eNaNReplacementPolicy)
						{
							case NaNReplacementPolicy_Disabled:
								m_vSwapBuffer[j] = std::numeric_limits<float>::quiet_NaN();
								break;
							case NaNReplacementPolicy_Zero:
								m_vSwapBuffer[j] = 0;
								break;
							case NaNReplacementPolicy_LastCorrectValue:
								// we simply don't update the value
								break;
							default:
								break;
						}
					}
					else
					{
981 982 983 984 985
						m_vSwapBuffer[j]=alpha*pSample[l_ui32Channel*ui32SampleCount+i]+(1-alpha)*m_vOverSamplingSwapBuffer[j];
					}
				}
		
				const uint64 l_ui64CurrentSampleIndex = m_ui64SampleCount + i*m_ui64OverSamplingFactor + k;		// j is not included here as all channels have the equal sample time
Jozef Legeny's avatar
Jozef Legeny committed
986

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
				if(l_bHadNaN)
				{
					// When a NaN is encountered at time t1 on any channel, OVTK_GDF_Incorrect stimulus is sent. When a first good sample is encountered 
					// after the last bad sample t2, OVTK_GDF_Correct stimulus is sent, i.e. specifying a range of bad data : [t1,t2]. The stimuli are global 
					// and not specific to channels.

					if(!m_bReplacementInProgress)
					{
						const uint64 l_ui64IncorrectBlockStarts = ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, l_ui64CurrentSampleIndex);

						m_oPendingStimulationSet.appendStimulation(OVTK_GDF_Incorrect, l_ui64IncorrectBlockStarts, 0);
						m_bReplacementInProgress = true;
					}
				} 
				else 
				{
					if(m_bReplacementInProgress)
					{
						// @note -1 is used here because the incorrect-correct range is inclusive, [a,b]. So when sample is good at b+1, we set the end point at b.
						const uint64 l_ui64IncorrectBlockStops = ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, l_ui64CurrentSampleIndex - 1);

						m_oPendingStimulationSet.appendStimulation(OVTK_GDF_Correct, l_ui64IncorrectBlockStops, 0);
						m_bReplacementInProgress = false;
Jozef Legeny's avatar
Jozef Legeny committed
1010 1011
					}
				}
1012

Jozef Legeny's avatar
Jozef Legeny committed
1013 1014 1015
				m_vPendingBuffer.push_back(m_vSwapBuffer);
			}
		}
1016

Jozef Legeny's avatar
Jozef Legeny committed
1017 1018 1019
		m_ui64LastSampleCount=m_ui64SampleCount;
		m_ui64SampleCount+=ui32SampleCount*m_ui64OverSamplingFactor;

1020
		m_oDriftCorrection.estimateDrift(ui32SampleCount*m_ui64OverSamplingFactor);
Jozef Legeny's avatar
Jozef Legeny committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

		m_ui64LastDeliveryTime=System::Time::zgetTime();
		m_bGotData=true;
	}
	else
	{
		m_rKernelContext.getLogManager() << LogLevel_Warning << "The acquisition is not started\n";
	}
}

void CAcquisitionServer::setStimulationSet(const IStimulationSet& rStimulationSet)
{
	if(m_bStarted)
	{
		uint64 l_ui64StimulationTime = ITimeArithmetics::sampleCountToTime(m_ui32SamplingFrequency, m_ui64LastSampleCount);
		OpenViBEToolkit::Tools::StimulationSet::append(m_oPendingStimulationSet, rStimulationSet, l_ui64StimulationTime);
	}
	else
	{
		m_rKernelContext.getLogManager() << LogLevel_Warning << "The acquisition is not started\n";
	}
}


boolean CAcquisitionServer::updateImpedance(const uint32 ui32ChannelIndex, const float64 f64Impedance)
{
1047 1048 1049 1050 1051 1052
	for (OpenViBE::uint32 i=0;i<m_vSelectedChannels.size();++i)
		if (ui32ChannelIndex==m_vSelectedChannels[i]) {
			m_vImpedance[i] = f64Impedance;
			return true;
		}
	return false;
Jozef Legeny's avatar
Jozef Legeny committed
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
}

// ____________________________________________________________________________
//

ENaNReplacementPolicy CAcquisitionServer::getNaNReplacementPolicy(void)
{
	return m_eNaNReplacementPolicy;
}

CString CAcquisitionServer::getNaNReplacementPolicyStr(void)
{
	switch (m_eNaNReplacementPolicy)
	{
		case NaNReplacementPolicy_Disabled:
			return CString("Disabled");
		case NaNReplacementPolicy_LastCorrectValue:
			return CString("LastCorrectValue");
		case NaNReplacementPolicy_Zero:
			return CString("Zero");
		default :
			return CString("N/A");
	}
}

uint64 CAcquisitionServer::getOversamplingFactor(void)
{
	return m_ui64OverSamplingFactor;
}

boolean CAcquisitionServer::setNaNReplacementPolicy(ENaNReplacementPolicy eNaNReplacementPolicy)
{
	m_eNaNReplacementPolicy=eNaNReplacementPolicy;
	return true;
}


boolean CAcquisitionServer::isImpedanceCheckRequested(void)
{
1092 1093 1094 1095 1096
	if (m_pDriver)
	{
		return m_pDriver->getHeader()->isImpedanceCheckRequested();
	}
	return false;
Jozef Legeny's avatar
Jozef Legeny committed
1097 1098
}

1099 1100 1101 1102 1103
boolean CAcquisitionServer::isChannelSelectionRequested(void)
{
	return m_bIsChannelSelectionRequested;
}

Jozef Legeny's avatar
Jozef Legeny committed
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
boolean CAcquisitionServer::setOversamplingFactor(uint64 ui64OversamplingFactor)
{
	m_ui64OverSamplingFactor=ui64OversamplingFactor;
	if(m_ui64OverSamplingFactor<1) m_ui64OverSamplingFactor=1;
	if(m_ui64OverSamplingFactor>16) m_ui64OverSamplingFactor=16;
	return true;
}

boolean CAcquisitionServer::setImpedanceCheckRequest(boolean bActive)
{
	m_bIsImpedanceCheckRequested=bActive;
	return true;
}

1118 1119 1120 1121 1122 1123
boolean CAcquisitionServer::setChannelSelectionRequest(const boolean bActive)
{
	m_bIsChannelSelectionRequested=bActive;
	return true;
}

Jozef Legeny's avatar
Jozef Legeny committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
// ____________________________________________________________________________
//

boolean CAcquisitionServer::acceptNewConnection(Socket::IConnection* pConnection)
{
	if(!pConnection)
	{
		return false;
	}

	uint64 l_ui64Time=System::Time::zgetTime();

1136
	DoubleLock lock(&m_oPendingConnectionProtectionMutex, &m_oPendingConnectionExecutionMutex);
Jozef Legeny's avatar
Jozef Legeny committed
1137 1138 1139 1140 1141 1142

	SConnectionInfo l_oInfo;
	l_oInfo.m_ui64ConnectionTime=l_ui64Time;
	l_oInfo.m_ui64StimulationTimeOffset=0; // not used
	l_oInfo.m_ui64SignalSampleCountToSkip=0; // not used
	l_oInfo.m_pConnectionClientHandlerThread=NULL; // not used
1143
	l_oInfo.m_pConnectionClientHandlerStdThread=NULL; // not used
1144 1145 1146
	l_oInfo.m_bChannelLocalisationSent = false;
	l_oInfo.m_bChannelUnitsSent = false;

Jozef Legeny's avatar
Jozef Legeny committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
	m_vPendingConnection.push_back(pair < Socket::IConnection*, SConnectionInfo > (pConnection, l_oInfo));

	for(std::vector<IAcquisitionServerPlugin*>::iterator itp = m_vPlugins.begin(); itp != m_vPlugins.end(); ++itp)
	{
		(*itp)->acceptNewConnectionHook();
	}

	return true;
}