ovpCBoxAlgorithmMatlabFilter.cpp 20.8 KB
Newer Older
Jussi Lindgren's avatar
Jussi Lindgren committed
1 2 3 4 5
#if defined TARGET_HAS_ThirdPartyMatlab

#include "ovpCBoxAlgorithmMatlabFilter.h"


Jozef Legeny's avatar
Jozef Legeny committed
6
#include <system/Memory.h>
Jussi Lindgren's avatar
Jussi Lindgren committed
7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <stdio.h>
#include <sstream>
#include <mex.h>
#include <engine.h>
#include <string>

#if defined TARGET_OS_Windows
	#include <windows.h>
#endif

Jussi Lindgren's avatar
Jussi Lindgren committed
18 19
#include <fs/Files.h>

Jussi Lindgren's avatar
Jussi Lindgren committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#define MATLAB_BUFFER 2048
#define m_pMatlabEngine ((Engine*)m_pMatlabEngineHandle)
#define m_pMatlabStimulation ((mxArray*)m_pMatlabStimulationHandle)
#define m_pMatlabMatrix ((mxArray*)m_pMatlabMatrixHandle)
#define m_pMatlabBCIContext ((mxArray*)m_pMatlabBCIContextHandle)

using namespace std;

using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBE::Plugins;

using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::Tools;

#define boolean OpenViBE::boolean

Jussi Lindgren's avatar
Jussi Lindgren committed
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
// Sanitizes a path so that it only has / or \ characters and has a / or \ in the end.
// @fixme should move to plugins-FS possibly
void CBoxAlgorithmMatlabFilter::sanitizePath(OpenViBE::CString &sPathToModify) const {

	std::string l_oTmpPath(sPathToModify);
	// Append / to end of path if its not there already
	if(l_oTmpPath.length()>0) 
	{
		char l_cLastChar = l_oTmpPath.at(l_oTmpPath.length()-1);
		if(l_cLastChar != '\\' && l_cLastChar != '/')
		{
			l_oTmpPath = l_oTmpPath + "/";
		}
	}

#if defined TARGET_OS_Windows
	// Convert '/' to '\'
	for (size_t i=0; i < l_oTmpPath.length(); i++) {
		if(l_oTmpPath[i] == '/') 
		{
			l_oTmpPath[i] = '\\';
		}
	}
#endif
	sPathToModify = OpenViBE::CString(l_oTmpPath.c_str());
}

Jussi Lindgren's avatar
Jussi Lindgren committed
64 65
boolean CBoxAlgorithmMatlabFilter::OpenMatlabEngineSafely(void)
{
Jussi Lindgren's avatar
Jussi Lindgren committed
66
	this->getLogManager() << LogLevel_Trace << "Trying to open the Matlab engine\n";
Jussi Lindgren's avatar
Jussi Lindgren committed
67 68
#if defined TARGET_OS_Linux
	m_pMatlabEngineHandle=::engOpen(m_sMatlabPath.toASCIIString());
Jussi Lindgren's avatar
Jussi Lindgren committed
69 70 71 72 73 74
	if(!m_pMatlabEngine) 
	{
		this->getLogManager() << LogLevel_Error << "Could not open the Matlab engine.\n" << 
			"The configured path to the matlab executable was expanded as '" << m_sMatlabPath << "'.\n";
		return false;
	}
Jussi Lindgren's avatar
Jussi Lindgren committed
75 76 77 78 79 80 81
#elif defined TARGET_OS_Windows
	__try
	{
		m_pMatlabEngineHandle=::engOpen(NULL);
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
Jussi Lindgren's avatar
Jussi Lindgren committed
82
		this->getLogManager() << LogLevel_Error << "First call to the MATLAB engine failed.\n"
Jussi Lindgren's avatar
Jussi Lindgren committed
83
			<< "\tTo use this box you must have MATLAB (32 bits version) installed on your computer.\n";
Jussi Lindgren's avatar
Jussi Lindgren committed
84
		m_pMatlabEngineHandle = NULL;
Jussi Lindgren's avatar
Jussi Lindgren committed
85 86 87
	}
	if(!m_pMatlabEngine)
	{
Jussi Lindgren's avatar
Jussi Lindgren committed
88 89
		this->getLogManager() << LogLevel_Error << "Could not open the Matlab engine.\n" << 
			"The configured path to the matlab bin directory was expanded as '" << m_sMatlabPath << "'.\n";
Jussi Lindgren's avatar
Jussi Lindgren committed
90 91
		return false;
	}
Jussi Lindgren's avatar
Jussi Lindgren committed
92 93 94 95
#else
	this->getLogManager() << LogLevel_Error << "Only Linux and Windows are supported\n";
	return false;
#endif
Jussi Lindgren's avatar
Jussi Lindgren committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
	return true;
}

boolean CBoxAlgorithmMatlabFilter::initialize(void)
{
	
	m_pStimulationDecoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationStreamDecoder));
	m_pStimulationEncoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationStreamEncoder));
	m_pStreamedMatrixDecoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixStreamDecoder));
	m_pStreamedMatrixEncoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixStreamEncoder));

	m_pStimulationDecoder->initialize();
	m_pStimulationEncoder->initialize();
 	m_pStreamedMatrixDecoder->initialize();
	m_pStreamedMatrixEncoder->initialize();

	op_pStimulationSet.initialize(m_pStimulationDecoder->getOutputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_OutputParameterId_StimulationSet));
	ip_pStimulationSet.initialize(m_pStimulationEncoder->getInputParameter(OVP_GD_Algorithm_StimulationStreamEncoder_InputParameterId_StimulationSet));
	op_pMatrix.initialize(m_pStreamedMatrixDecoder->getOutputParameter(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputParameterId_Matrix));
	ip_pMatrix.initialize(m_pStreamedMatrixEncoder->getInputParameter(OVP_GD_Algorithm_StreamedMatrixStreamEncoder_InputParameterId_Matrix));

	m_ui64LatestStimulationChunkEndTime=0;

	getStaticBoxContext().getSettingValue(0, m_sMatlabPath);

#if defined TARGET_OS_Windows
Jussi Lindgren's avatar
Jussi Lindgren committed
122 123 124 125 126 127
	if(!FS::Files::directoryExists(m_sMatlabPath) && FS::Files::fileExists(m_sMatlabPath)) 
	{
		// The path might be pointing to the executable, try to extract the directory
		char l_sParentPath[MAX_PATH];
		FS::Files::getParentPath(m_sMatlabPath, l_sParentPath);
		m_sMatlabPath = OpenViBE::CString(l_sParentPath);
Jussi Lindgren's avatar
Jussi Lindgren committed
128
	}
Jussi Lindgren's avatar
Jussi Lindgren committed
129 130 131 132 133 134

	sanitizePath(m_sMatlabPath);

	this->getLogManager() << LogLevel_Trace << "Interpreting Matlab path as '" << m_sMatlabPath << "'\n";

	if(!FS::Files::directoryExists(m_sMatlabPath)) 
Jussi Lindgren's avatar
Jussi Lindgren committed
135
	{
Jussi Lindgren's avatar
Jussi Lindgren committed
136 137
		this->getLogManager() << LogLevel_Error << "Configured Matlab path'" << m_sMatlabPath << "' does not seem to be a directory\n";
		return false;
Jussi Lindgren's avatar
Jussi Lindgren committed
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 178 179 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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
	}

	char * l_sPath = getenv("PATH");
	if(l_sPath == NULL)
	{
		this->getLogManager() << LogLevel_Error << "Could not access the environment variable PATH to add Matlab.\n";
		return false;
	}
	string l_sStrPath = string(l_sPath);
	size_t l_pFound = l_sStrPath.find((const char *)m_sMatlabPath);
	if( l_pFound == string::npos )
	{
		CString l_sCommandForPathModification = l_sPath + CString(";") + m_sMatlabPath;
		if(_putenv_s("PATH",l_sCommandForPathModification) != 0)
		{
			this->getLogManager() << LogLevel_Error << "Failed to modify the environment PATH with the Matlab path.\n";
			return false;
		}
		this->getLogManager() << LogLevel_Trace << "Matlab Path added to Windows PATH environment variable.\n";
	}
#endif

	if(!OpenMatlabEngineSafely()) return false;
	
	CString l_sSettingValue;
	getStaticBoxContext().getSettingValue(1, l_sSettingValue); // working directory
	l_sSettingValue=CString("cd ")+l_sSettingValue;
	::engEvalString(m_pMatlabEngine, l_sSettingValue.toASCIIString());

	getStaticBoxContext().getSettingValue(2,m_sInitializeFunction);
	getStaticBoxContext().getSettingValue(3,m_sProcessFunction);

	m_pMatlabStimulationHandle=NULL;
	m_pMatlabMatrixHandle=NULL;
	m_pMatlabBCIContextHandle=::mxCreateDoubleMatrix(2,1,mxREAL);


	return true;
}

boolean CBoxAlgorithmMatlabFilter::CloseMatlabEngineSafely(void)
{
	if(m_pMatlabEngine == NULL)
	{
		return true;
	}
	this->getLogManager() << LogLevel_Trace << "Trying to close Matlab engine\n";
#if defined TARGET_OS_Windows
	__try
	{
#endif
		if(m_pMatlabMatrix)
		{
			::mxDestroyArray(m_pMatlabMatrix);
		}

		::mxDestroyArray(m_pMatlabBCIContext);

		if(m_pMatlabEngine)
		{
			if(::engClose(m_pMatlabEngine)!=0)
			{
				this->getLogManager() << LogLevel_ImportantWarning << "Could not close Matlab engine.\n";
			}
		}
#if defined TARGET_OS_Windows
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		this->getLogManager() << LogLevel_Error << "Closing MATLAB engine failed.\n"
			<< "\tTo use this box you must have MATLAB (32 bits version) installed on your computer.\n";

		return false;
	}
#endif

	return true;
}

boolean CBoxAlgorithmMatlabFilter::uninitialize(void)
{
	CloseMatlabEngineSafely();

	ip_pMatrix.uninitialize();
	op_pMatrix.uninitialize();
	ip_pStimulationSet.uninitialize();
	op_pStimulationSet.uninitialize();

	m_pStreamedMatrixEncoder->uninitialize();
	m_pStreamedMatrixDecoder->uninitialize();
	m_pStimulationEncoder->uninitialize();
	m_pStimulationDecoder->uninitialize();

	this->getAlgorithmManager().releaseAlgorithm(*m_pStreamedMatrixEncoder);
	this->getAlgorithmManager().releaseAlgorithm(*m_pStreamedMatrixDecoder);
	this->getAlgorithmManager().releaseAlgorithm(*m_pStimulationEncoder);
	this->getAlgorithmManager().releaseAlgorithm(*m_pStimulationDecoder);

	return true;
}

boolean CBoxAlgorithmMatlabFilter::processInput(uint32 ui32InputIndex)
{
	if(!m_pMatlabEngine)
	{
		return true;
	}

	getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();

	return true;
}

boolean CBoxAlgorithmMatlabFilter::process(void)
{
	IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();
	
	TParameterHandler < IMemoryBuffer* > op_pMemoryBuffer(m_pStreamedMatrixEncoder->getOutputParameter(OVP_GD_Algorithm_StimulationStreamEncoder_OutputParameterId_EncodedMemoryBuffer));
	TParameterHandler < IMemoryBuffer* > op_pMemoryBufferStimulation(m_pStimulationEncoder->getOutputParameter(OVP_GD_Algorithm_StimulationStreamEncoder_OutputParameterId_EncodedMemoryBuffer));
	op_pMemoryBufferStimulation=l_rDynamicBoxContext.getOutputChunk(1);
	
	// We decode and save the received stimulations.
	for(uint32 i=0; i<l_rDynamicBoxContext.getInputChunkCount(1); i++)
	{
		TParameterHandler < const IMemoryBuffer* > ip_pMemoryBuffer(m_pStimulationDecoder->getInputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_InputParameterId_MemoryBufferToDecode));
		ip_pMemoryBuffer=l_rDynamicBoxContext.getInputChunk(1, i);
		m_pStimulationDecoder->process();
		if(m_pStimulationDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedHeader))
		{
		}
		if(m_pStimulationDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedBuffer))
		{
			for(uint32 j=0; j<op_pStimulationSet->getStimulationCount(); j++)
			{
				m_oPendingStimulationSet.appendStimulation(
					op_pStimulationSet->getStimulationIdentifier(j),
					op_pStimulationSet->getStimulationDate(j),
					op_pStimulationSet->getStimulationDuration(j));
				if (op_pStimulationSet->getStimulationDate(j)<l_rDynamicBoxContext.getInputChunkStartTime(1, i))
				{
					this->getLogManager() << LogLevel_Error << "Stimulation Date before beginning of the buffer, stimulation may be skipped\n";
				}
			}
		}
		if(m_pStimulationDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedEnd))
		{
		}
		m_ui64LatestStimulationChunkEndTime=l_rDynamicBoxContext.getInputChunkEndTime(1, i);
		l_rDynamicBoxContext.markInputAsDeprecated(1, i);
	}

	// We now decode the stream matrix
	for(uint32 i=0; i<l_rDynamicBoxContext.getInputChunkCount(0); i++)
	{
		uint64 l_ui64StartTime=l_rDynamicBoxContext.getInputChunkStartTime(0, i);
		uint64 l_ui64EndTime=l_rDynamicBoxContext.getInputChunkEndTime(0, i);

		((float64*)::mxGetPr(m_pMatlabBCIContext))[0] = (l_ui64StartTime >> 16) / 65536.0;
		((float64*)::mxGetPr(m_pMatlabBCIContext))[1] = (l_ui64EndTime >> 16) / 65536.0;

		if(l_ui64EndTime<=m_ui64LatestStimulationChunkEndTime)
		{
			TParameterHandler < const IMemoryBuffer* > ip_pMemoryBuffer(m_pStreamedMatrixDecoder->getInputParameter(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_InputParameterId_MemoryBufferToDecode));
			ip_pMemoryBuffer=l_rDynamicBoxContext.getInputChunk(0, i);
			m_pStreamedMatrixDecoder->process();
			// we received the header
			if(m_pStreamedMatrixDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputTriggerId_ReceivedHeader))
			{
				//we analyse the header
				if(op_pMatrix->getDimensionCount()!=2)
				{
					this->getLogManager() << LogLevel_ImportantWarning << "Streamed matrix dimension count is not 2\n";
				}
				else
				{
					m_pMatlabMatrixHandle=::mxCreateDoubleMatrix(
						op_pMatrix->getDimensionSize(1),
						op_pMatrix->getDimensionSize(0),
						mxREAL);
					if(!m_pMatlabMatrix)
					{
						this->getLogManager() << LogLevel_ImportantWarning << "Could not create Matlab matrix\n";
					}
					
					char l_pMatlabBuffer[MATLAB_BUFFER+1];
					l_pMatlabBuffer[MATLAB_BUFFER]='\0';
					std::stringstream l_sMatlabBuffer;
					::engOutputBuffer(m_pMatlabEngine, l_pMatlabBuffer,MATLAB_BUFFER);
					
					::engPutVariable(m_pMatlabEngine, "bci_context", m_pMatlabBCIContext);
					::engPutVariable(m_pMatlabEngine, "matrix_in", m_pMatlabMatrix);
					if(::engEvalString(m_pMatlabEngine, CString("matrix_out = ") + m_sInitializeFunction + CString("(bci_context, matrix_in);"))!=0)
					{
						l_sMatlabBuffer<<l_pMatlabBuffer;
						this->getLogManager()<< LogLevel_Error << "Matlab Error: "<<l_sMatlabBuffer.str().c_str()<<"\n";
						return false;
					}

					l_sMatlabBuffer<<l_pMatlabBuffer;

					// if the MatlabBuffer is not empty, we have to print it in the openvibe console
					// We have to check if it's error, warning, or simple info messages
					if(l_sMatlabBuffer.str().size()>0)
					{
						size_t l_oErrorIndex=l_sMatlabBuffer.str().find("??? ");
						size_t l_oWarningIndex=l_sMatlabBuffer.str().find("Warning: ");
						if(l_oWarningIndex > 0 && l_oErrorIndex > 0)
						{
							this->getLogManager()<<LogLevel_Info<<l_sMatlabBuffer.str().substr(0,(l_oWarningIndex<l_oErrorIndex)?l_oWarningIndex:l_oErrorIndex).c_str()<<"\n";
						
						}
						if(l_oWarningIndex!=std::string::npos)
						{
							this->getLogManager()<<LogLevel_Warning<<l_sMatlabBuffer.str().substr(l_oWarningIndex,l_oErrorIndex).c_str()<<"\n";
						}
						if(l_oErrorIndex!=std::string::npos)
						{
							this->getLogManager()<<LogLevel_Error<<l_sMatlabBuffer.str().substr(l_oErrorIndex).c_str()<<"\n";
						}
						
					}
					if(this->getLogManager().isActive(LogLevel_Debug))
					{
						::engOutputBuffer(m_pMatlabEngine, l_pMatlabBuffer, MATLAB_BUFFER);
						::engEvalString(m_pMatlabEngine, "result");
						l_sMatlabBuffer.clear();
						l_sMatlabBuffer<<l_pMatlabBuffer;
						this->getLogManager() << LogLevel_Debug << l_sMatlabBuffer.str().c_str()<<"\n";
					}
					
					// now we check the result of the initialization
					::mxArray* l_pMatlabMatrixOut=::engGetVariable(m_pMatlabEngine, "matrix_out");
					if(l_pMatlabMatrixOut)
					{
						if(!::mxIsDouble(l_pMatlabMatrixOut))
						{
							this->getLogManager() << LogLevel_Warning << "Expected double matrix output from " << m_sInitializeFunction << "\n";
						}
						else
						{
							// we send a header on the stream matrix output:
							ip_pMatrix->setDimensionCount(2);
							ip_pMatrix->setDimensionSize(0, ::mxGetDimensions(l_pMatlabMatrixOut)[1]);
							ip_pMatrix->setDimensionSize(1, ::mxGetDimensions(l_pMatlabMatrixOut)[0]);

							op_pMemoryBuffer=l_rDynamicBoxContext.getOutputChunk(0);
							m_pStreamedMatrixEncoder->process(OVP_GD_Algorithm_StreamedMatrixStreamEncoder_InputTriggerId_EncodeHeader);
							l_rDynamicBoxContext.markOutputAsReadyToSend(0, l_ui64StartTime, l_ui64EndTime);
						}
						::mxDestroyArray(l_pMatlabMatrixOut);
					}
				}

				// we send a header on the stimulation output:
				m_pStimulationEncoder->process(OVP_GD_Algorithm_StimulationStreamEncoder_InputTriggerId_EncodeHeader);
				l_rDynamicBoxContext.markOutputAsReadyToSend(1, l_ui64StartTime,l_ui64EndTime );
			}
			// we received a buffer
			if(m_pStreamedMatrixDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputTriggerId_ReceivedBuffer))
			{
				// we copy the actual pending stimulation in l_oStimulationSet
				CStimulationSet l_oStimulationSet;
				for(uint64 j=0; j<m_oPendingStimulationSet.getStimulationCount(); )
				{
					if(m_oPendingStimulationSet.getStimulationDate(j)<l_ui64StartTime)
					{
						m_oPendingStimulationSet.removeStimulation(j);
					}
					else
					{
						if(m_oPendingStimulationSet.getStimulationDate(j)<=l_ui64EndTime)
						{
							l_oStimulationSet.appendStimulation(
								m_oPendingStimulationSet.getStimulationIdentifier(j),
								m_oPendingStimulationSet.getStimulationDate(j),
								m_oPendingStimulationSet.getStimulationDuration(j));
						}
						j++;
					}
				}

				// we copy the stimulation into the corresponding matlab matrix
				m_pMatlabStimulationHandle=::mxCreateDoubleMatrix(::mwSize(l_oStimulationSet.getStimulationCount()), 3, mxREAL);
				float64* l_pMatlabStimulationBuffer=(float64*)::mxGetPr(m_pMatlabStimulation);
Jussi Lindgren's avatar
Jussi Lindgren committed
422 423
				uint64 l_ui64StimulationCount=l_oStimulationSet.getStimulationCount();
				for(uint64 j=0; j<l_ui64StimulationCount; j++)
Jussi Lindgren's avatar
Jussi Lindgren committed
424
				{
Jussi Lindgren's avatar
Jussi Lindgren committed
425 426 427
					l_pMatlabStimulationBuffer[j+0*l_ui64StimulationCount]=(float64)l_oStimulationSet.getStimulationIdentifier(j);
					l_pMatlabStimulationBuffer[j+1*l_ui64StimulationCount]=((l_oStimulationSet.getStimulationDate(j)-l_ui64StartTime) >> 16) / 65536.0;
					l_pMatlabStimulationBuffer[j+2*l_ui64StimulationCount]=( l_oStimulationSet.getStimulationDuration(j) >> 16) / 65536.0;
Jussi Lindgren's avatar
Jussi Lindgren committed
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 457 458 459 460 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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
				}

				// we copy the data
				System::Memory::copy(::mxGetPr(m_pMatlabMatrix), op_pMatrix->getBuffer(), op_pMatrix->getBufferElementCount()*sizeof(float64));

				// the call to the matlab engine
				::engPutVariable(m_pMatlabEngine, "bci_context", m_pMatlabBCIContext);
				::engPutVariable(m_pMatlabEngine, "stimulation_in", m_pMatlabStimulation);
				::engPutVariable(m_pMatlabEngine, "matrix_in", m_pMatlabMatrix);
				
				// the buffer for the console
				char l_pMatlabBuffer[MATLAB_BUFFER+1];
				l_pMatlabBuffer[MATLAB_BUFFER]='\0';
				std::stringstream l_sMatlabBuffer;
				::engOutputBuffer(m_pMatlabEngine, l_pMatlabBuffer,MATLAB_BUFFER);

				if(::engEvalString(m_pMatlabEngine, CString("[matrix_out,stimulation_out] = ") + m_sProcessFunction + CString("(bci_context, matrix_in, stimulation_in);"))!=0)
				{
					l_sMatlabBuffer<<l_pMatlabBuffer;
					this->getLogManager()<< LogLevel_Error << "Matlab Error: "<<l_sMatlabBuffer.str().c_str()<<"\n";
					return false;
				}
				l_sMatlabBuffer<<l_pMatlabBuffer;
				if(l_sMatlabBuffer.str().size()>0)
				{
					size_t l_oErrorIndex=l_sMatlabBuffer.str().find("??? ");
					size_t l_oWarningIndex=l_sMatlabBuffer.str().find("Warning: ");
					if(l_oErrorIndex!=0 && l_oWarningIndex!=0)
					{
						this->getLogManager()<<LogLevel_Info<<l_sMatlabBuffer.str().substr(0,(l_oWarningIndex<l_oErrorIndex)?l_oWarningIndex:l_oErrorIndex).c_str()<<"\n";
					}
					if(l_oWarningIndex!=std::string::npos)
					{
						this->getLogManager()<<LogLevel_Warning<<l_sMatlabBuffer.str().substr(l_oWarningIndex,l_oErrorIndex).c_str()<<"\n";
					}
					if(l_oErrorIndex!=std::string::npos)
					{
						this->getLogManager()<<LogLevel_Error<<l_sMatlabBuffer.str().substr(l_oErrorIndex).c_str()<<"\n";
					}
				}
				if(this->getLogManager().isActive(LogLevel_Debug))
				{
					::engOutputBuffer(m_pMatlabEngine, l_pMatlabBuffer, MATLAB_BUFFER);
					::engEvalString(m_pMatlabEngine, "result");
					l_sMatlabBuffer.clear();
					l_sMatlabBuffer<<l_pMatlabBuffer;
					this->getLogManager() << LogLevel_Debug << l_sMatlabBuffer.str().c_str()<<"\n";
				}
				::mxDestroyArray(m_pMatlabStimulation);

				// reading matrix_out from matlab
				::mxArray* l_pMatlabMatrixOut=::engGetVariable(m_pMatlabEngine, "matrix_out");
				if(l_pMatlabMatrixOut)
				{
					if(!::mxIsDouble(l_pMatlabMatrixOut))
					{
						this->getLogManager() << LogLevel_Warning << "Expected double matrix output from " << m_sProcessFunction << "\n";
					}
					else
					{
						System::Memory::copy(ip_pMatrix->getBuffer(), ::mxGetPr(l_pMatlabMatrixOut), ip_pMatrix->getBufferElementCount()*sizeof(float64));
 
						op_pMemoryBuffer=l_rDynamicBoxContext.getOutputChunk(0);
						m_pStreamedMatrixEncoder->process(OVP_GD_Algorithm_StreamedMatrixStreamEncoder_InputTriggerId_EncodeBuffer);
						l_rDynamicBoxContext.markOutputAsReadyToSend(0, l_ui64StartTime, l_ui64EndTime);
					}
					::mxDestroyArray(l_pMatlabMatrixOut);
				}

				// reading stimulation_out from matlab
				::mxArray* l_pMatlabStimulationOut=::engGetVariable(m_pMatlabEngine, "stimulation_out");
				if(l_pMatlabStimulationOut)
				{
					if(!::mxIsDouble(l_pMatlabStimulationOut))
					{
						this->getLogManager() << LogLevel_Warning << "Expected double matrix output from " << m_sProcessFunction << "\n";
					}
					else
					{
						if (::mxGetDimensions(l_pMatlabStimulationOut)[1] != 3)
						{
							this->getLogManager() << LogLevel_Warning << "Output Stimulation matrix must be of size (nb_stim x 3) after " << m_sProcessFunction << "\n";
						}
						else
						{
							ip_pStimulationSet->setStimulationCount(0);
							uint32 l_ui32StimulationCount=::mxGetDimensions(l_pMatlabStimulationOut)[0];
							float64* l_pStim=::mxGetPr(l_pMatlabMatrixOut);
							for(uint32 j=0; j<l_ui32StimulationCount; j++)
							{
								// we decode a stimulation from the matlab stimulation matrix
								ip_pStimulationSet->appendStimulation(
Jussi Lindgren's avatar
Jussi Lindgren committed
520
									(uint64)l_pStim[j+0*l_ui32StimulationCount],
Jussi Lindgren's avatar
Jussi Lindgren committed
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
									l_ui64StartTime + ((int64)(l_pStim[j+1*l_ui32StimulationCount] * 65536.0)<<16),
									l_ui64StartTime + ((int64)(l_pStim[j+2*l_ui32StimulationCount] * 65536.0)<<16));
							}
							m_pStimulationEncoder->process(OVP_GD_Algorithm_StimulationStreamEncoder_InputTriggerId_EncodeBuffer);
							l_rDynamicBoxContext.markOutputAsReadyToSend(1, l_ui64StartTime, l_ui64EndTime);
						}
					}
				}


			}
			// We received the End
			if(m_pStreamedMatrixDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputTriggerId_ReceivedEnd))
			{
				// we send the End signal to the stream matrix output
				m_pStreamedMatrixEncoder->process(OVP_GD_Algorithm_StreamedMatrixStreamEncoder_InputTriggerId_EncodeEnd);
				// and to the stimulation output:
				m_pStimulationEncoder->process(OVP_GD_Algorithm_StimulationStreamEncoder_InputTriggerId_EncodeEnd);
			}
			// The stream matrix chunk i has been process 
			l_rDynamicBoxContext.markInputAsDeprecated(0, i);
		}
	}

	return true;
}

#endif // TARGET_HAS_ThirdPartyMatlab