예제 #1
0
void XnSensorsManager::ReleaseSensor(XnServerSensorInvoker* pInvoker)
{
	XnAutoCSLocker locker(m_hLock);
	ReferencedSensor* pSensor;
	XnStatus nRetVal = m_sensors.Get(pInvoker->GetDevicePath(), pSensor);
	if (nRetVal != XN_STATUS_OK)
	{
		xnLogError(XN_MASK_SENSOR_SERVER, "Trying to release a sensor that is not in the map!");
		return;
	}

	--pSensor->nRefCount;
	xnLogVerbose(XN_MASK_SENSOR_SERVER, "Sensor '%s' now has %u sessions", pInvoker->GetDevicePath(), pSensor->nRefCount);

	if (pSensor->nRefCount == 0)
	{
		// store current time. Then, in CleanUp() if timeout passed, sensor will be closed
		xnOSGetTimeStamp(&pSensor->nNoClientsTime);

		// do some clean-up (so that next client will behave as if it started the server)

		// This is a bit ugly, but we need to manually set back to default DEVICE properties
		// (we know there aren't any streams and clients, but the Device module always remains)
		nRetVal = pSensor->pInvoker->SetIntProperty(XN_MODULE_NAME_DEVICE, XN_MODULE_PROPERTY_FRAME_SYNC, (XnUInt64)FALSE);
		if (nRetVal != XN_STATUS_OK)
		{
			xnLogError(XN_MASK_SENSOR_SERVER, "Failed resetting FrameSync: %s", xnGetStatusString(nRetVal));
		}

		nRetVal = pSensor->pInvoker->ConfigureModuleFromGlobalFile(XN_MODULE_NAME_DEVICE);
		if (nRetVal != XN_STATUS_OK)
		{
			xnLogError(XN_MASK_SENSOR_SERVER, "Failed configuring device from global config file: %s", xnGetStatusString(nRetVal));
		}
	}
}
예제 #2
0
void LinkMsgEncoder::EncodeData(const void* pSourceData, XnUInt32 nSize)
{
	XnUInt16 nPacketRemainingSpace = 0; //Remaining space in current packet in each iteration
	XnUInt16 nPacketBytesToCopy = 0; //Number of bytes to copy to current packet in each iteration
	XnUInt32 nBytesLeftToCopy = nSize; //Total number of bytes left to copy
	const XnUInt8* pCurrData = reinterpret_cast<const XnUInt8*>(pSourceData); //Current source data pointer
	while (nBytesLeftToCopy > 0)
	{
		if (m_pCurrPacket->GetSize() == m_nMaxPacketSize)
		{
			//Current packet is full. Move to next packet (this also advances m_pCurrPacket).
			m_pCurrPacketBuffer += m_nMaxPacketSize;
			if (m_pCurrPacketBuffer >= m_pOutputBuffer + m_nBufferSize)
			{
				xnLogError(XN_MASK_LINK, "Msg encoder buffer overrun :( Was about to write to position %u, but buffer size is only %u",
					(m_pCurrPacketBuffer - m_pOutputBuffer), m_nBufferSize);
				XN_ASSERT(FALSE);
				return;
			}
			//Advance packet ID
			m_packetHeader.SetPacketID(m_packetHeader.GetPacketID() + 1);
			/*Copy prepared packet header into destination packet. This also sets m_pCurrPacket->m_nSize to minimum
			  and m_pCurrPacket->m_nFragmentation to XN_LINK_FRAG_MIDDLE.*/
			xnOSMemCopy(m_pCurrPacket, &m_packetHeader, sizeof(m_packetHeader));
			//Increase encoded size for packet header
			m_nEncodedSize += sizeof(m_packetHeader);
		}
		//Calculate remaining space in current packet
		nPacketRemainingSpace = m_nMaxPacketSize - m_pCurrPacket->GetSize();
		//Calculate how many bytes we're copying to the current packet
		nPacketBytesToCopy = static_cast<XnUInt16>(XN_MIN(nPacketRemainingSpace, nBytesLeftToCopy));
		
		/************ Copy data to current packet ********************/
		xnOSMemCopy(m_pCurrPacketBuffer + m_pCurrPacket->GetSize(), 
		            pCurrData,
					nPacketBytesToCopy);
		/*************************************************************/

		//Advance current source data pointer
		pCurrData += nPacketBytesToCopy;
		//Increase encoded size for packet data
		m_nEncodedSize += nPacketBytesToCopy;
		//Increase size of current packet
		m_pCurrPacket->SetSize(m_pCurrPacket->GetSize() + nPacketBytesToCopy);
		//Decrease number of bytes we have left to copy
		nBytesLeftToCopy -= nPacketBytesToCopy;
	}
}
예제 #3
0
XnStatus XnDeviceBase::AddSupportedStream(const XnChar* StreamType)
{
	// make sure stream doesn't exist yet
	XnStringsHash::Iterator it = m_SupportedStreams.end();
	if (XN_STATUS_OK == m_SupportedStreams.Find(StreamType, it))
	{
		xnLogError(XN_MASK_DEVICE, "A stream with the name %s already exists!", StreamType);
		return XN_STATUS_STREAM_ALREADY_EXISTS;
	}

	// add it to the list
	XnStatus nRetVal = m_SupportedStreams.Set(StreamType, NULL);
	XN_IS_STATUS_OK(nRetVal);

	return XN_STATUS_OK;
}
예제 #4
0
XnStatus UserSelector::UpdateUserTrackingProgress(XnUserID nUserId, XnInt64 newSubState)
{
    // update by getting the current state, making sure it is ok and then change the relevant
    // sub state
    UserSelectionState* pState;
    XnStatus nRetVal = m_hUsersState.Get(nUserId , pState);
    if(nRetVal != XN_STATUS_OK)
    {
        return nRetVal;
    }
    if(pState == NULL || pState->m_eState != XN_SELECTION_SELECTED)
    {
        xnLogError("SAMPLE","User %d should have been in an unselected state but was instead in %d state.\n", nUserId, pState->m_eState);
        return XN_STATUS_ERROR; // this should be only called when a user is selected!
    }
    return UpdateUserSelectionState(nUserId, pState->m_eState, newSubState);
}
예제 #5
0
XnStatus PS1200Device::Init(const XnChar* strConnString, XnTransportType transportType)
{
	XnStatus nRetVal = XN_STATUS_OK;

	if (transportType != XN_TRANSPORT_TYPE_USB)
	{
		xnLogError(XN_MASK_LINK, "Transport type not supported: %d", transportType);
		XN_ASSERT(FALSE);
		return XN_STATUS_BAD_PARAM;
	}

	nRetVal = PrimeClient::Init(strConnString, XN_TRANSPORT_TYPE_USB);
	XN_IS_STATUS_OK_LOG_ERROR("Init EE Device", nRetVal);

	m_bInitialized = TRUE;
	return XN_STATUS_OK;	
}
예제 #6
0
XnStatus XnDeviceBase::AddModule(XnDeviceModuleHolder* pModuleHolder)
{
    XnDeviceModule* pModule = pModuleHolder->GetModule();

    // make sure module doesn't exist yet
    if (m_Modules.Find(pModule->GetName()) != m_Modules.End())
    {
        xnLogError(XN_MASK_DEVICE, "A module with the name %s already exists!", pModule->GetName());
        return XN_STATUS_ERROR;
    }

    // add it to the list
    XnStatus nRetVal = m_Modules.Set(pModule->GetName(), pModuleHolder);
    XN_IS_STATUS_OK(nRetVal);

    return XN_STATUS_OK;
}
void XnFrameBufferManager::MarkWriteBufferAsStable(XnUInt64 nTimestamp, XnUInt32* pnFrameID)
{
	xnOSEnterCriticalSection(&m_hLock);

	// lock buffer pool (for rollback option)
	m_pBufferPool->Lock();

	XnBuffer* pPrevStable = m_pStableBuffer;

	// release previous stable
	if (m_pStableBuffer != NULL)
	{
		m_pBufferPool->DecRef(m_pStableBuffer);
	}

	// mark working as stable
	m_nStableFrameID++;
	m_nStableTimestamp = nTimestamp;
	*pnFrameID = m_nStableFrameID;

	m_pStableBuffer = m_pWorkingBuffer; // no need to add ref, working buffer will be replaced in a moment

	// take a new working buffer
	XnStatus nRetVal = m_pBufferPool->GetBuffer(&m_pWorkingBuffer);
	if (nRetVal != XN_STATUS_OK)
	{
		xnLogError(XN_MASK_DDK, "Failed to get new working buffer!");
		// we'll return back to our old working one
		m_pWorkingBuffer->Reset();

		m_pStableBuffer = pPrevStable;
		m_pBufferPool->AddRef(m_pStableBuffer);
		m_pBufferPool->Unlock();
		return;
	}

	m_pBufferPool->Unlock();
	xnOSLeaveCriticalSection(&m_hLock);

	// reset new working
	m_pWorkingBuffer->Reset();

	// notify stream that new data is available
	m_NewFrameEvent.Raise(this, m_nStableTimestamp);
}
예제 #8
0
void XnFrameBufferManager::MarkWriteBufferAsStable(XnUInt32* pnFrameID)
{
    xnOSEnterCriticalSection(&m_hLock);

    OniFrame* pStableBuffer = m_pWorkingBuffer;
    pStableBuffer->dataSize = m_writeBuffer.GetSize();

    // lock buffer pool (for rollback option)
    m_pBufferPool->Lock();

    // mark working as stable
    m_nStableFrameID++;
    *pnFrameID = m_nStableFrameID;
    pStableBuffer->frameIndex = m_nStableFrameID;

    // take a new working buffer
    m_pWorkingBuffer = m_pBufferPool->Acquire();
    if (m_pWorkingBuffer == NULL)
    {
        xnLogError(XN_MASK_DDK, "Failed to get new working buffer!");

        // we'll return back to our old working one
        m_pWorkingBuffer = pStableBuffer;
        m_pWorkingBuffer->dataSize = 0;

        m_pBufferPool->Unlock();

        XN_ASSERT(FALSE);
        return;
    }

    m_writeBuffer.SetExternalBuffer((XnUChar*)m_pWorkingBuffer->data, m_pBufferPool->GetFrameSize());

    m_pBufferPool->Unlock();
    xnOSLeaveCriticalSection(&m_hLock);

    // reset new working
    m_pWorkingBuffer->dataSize = 0;

    // notify stream that new data is available
    NewFrameEventArgs args;
    args.pFrame = pStableBuffer;
    m_NewFrameEvent.Raise(args);
}
예제 #9
0
XnStatus LinkOniMapStream::SetVideoMode(OniVideoMode* pVideoMode)
{
	XnStatus nRetVal = XN_STATUS_OK;

	OniVideoMode current;
	GetVideoMode(&current);

	if (!xnOSMemCmp(&current, pVideoMode, sizeof(OniVideoMode)))
	{
		// nothing to do here
		return (ONI_STATUS_OK);
	}

	// now look for the first mode that matches
	const xnl::Array<XnFwStreamVideoMode>& supportedModes = m_pInputStream->GetSupportedVideoModes();
	XnInt32 selectedIndex = -1;
	for (XnUInt32 i = 0; i < supportedModes.GetSize(); ++i)
	{
		if (pVideoMode->resolutionX == (int)supportedModes[i].m_nXRes &&
			pVideoMode->resolutionY == (int)supportedModes[i].m_nYRes &&
			pVideoMode->fps         == (int)supportedModes[i].m_nFPS)
		{
			selectedIndex = i;
			break;
		}
	}

	if (selectedIndex == -1)
	{
		xnLogError(XN_MASK_LINK, "Tried to set unsupported mode: %ux%u@%u fps", 
			pVideoMode->resolutionX, pVideoMode->resolutionY, pVideoMode->fps);
		XN_ASSERT(FALSE);
		return XN_STATUS_BAD_PARAM;
	}

	nRetVal = m_pInputStream->SetVideoMode(supportedModes[selectedIndex]);
	XN_IS_STATUS_OK_LOG_ERROR("Set video mode", nRetVal);

	nRetVal = m_pInputStream->SetOutputFormat(pVideoMode->pixelFormat);
	XN_IS_STATUS_OK_LOG_ERROR("Set output format", nRetVal);

	return XN_STATUS_OK;
}
예제 #10
0
XnStatus UserSelector::UpdateUserTracking(XnUserID nUserId, XnBool bTracked, XnInt64 newSubState)
{
    // update by checking the current state is ok and then update it based on the success and the
    // sub state.
    UserSelectionState* pState;
    XnStatus nRetVal = m_hUsersState.Get(nUserId,pState);
    if(nRetVal!=XN_STATUS_OK)
    {
        return nRetVal;
    }
    if(pState == NULL || pState->m_eState != XN_SELECTION_SELECTED)
    {
        xnLogError("SAMPLE","User %d should have been in an unselected state but was instead in %d state.\n", nUserId, pState->m_eState);
        return XN_STATUS_ERROR; // this should be only called when a user is selected!
    }
    XnSelectionState newState = bTracked ? XN_SELECTION_TRACKING : XN_SELECTION_FAILED;

    return UpdateUserSelectionState(nUserId, newState, newSubState);
}
예제 #11
0
XN_C_API XnStatus xnOSLockSemaphore(XN_SEMAPHORE_HANDLE hSemaphore, XnUInt32 nMilliseconds)
{
	XN_RET_IF_NULL(hSemaphore, XN_STATUS_OS_INVALID_SEMAPHORE);
	DWORD nRetVal = WaitForSingleObject(hSemaphore, nMilliseconds);

	switch (nRetVal)
	{
		case WAIT_OBJECT_0:
			break;
		case WAIT_TIMEOUT:
			return XN_STATUS_OS_SEMAPHORE_TIMEOUT;
		default:
			xnLogError(XN_MASK_OS, "Failed to wait for semaphore. Last error was %u.", GetLastError());
			XN_ASSERT(FALSE);
			return XN_STATUS_OS_SEMAPHORE_LOCK_FAILED;
	}
	
	return XN_STATUS_OK;
}
예제 #12
0
XN_C_API XnStatus XN_C_DECL xnOSCreateNamedEventEx(XN_EVENT_HANDLE* pEventHandle, const XnChar* cpEventName, XnBool bManualReset, XnBool bAllowOtherUsers)
{
	// Local function variables
	XnStatus nRetVal = XN_STATUS_OK;

	// Validate the input/output pointers (to make sure none of them is NULL)
	XN_VALIDATE_OUTPUT_PTR(pEventHandle);

	XnChar strEventOSName[MAX_PATH];
	XnChar* pEventOSName = NULL;
	SECURITY_ATTRIBUTES* pSecurityAttributes = NULL;

	if (cpEventName != NULL)
	{
		nRetVal = XnWin32CreateKernelObjectName(strEventOSName, MAX_PATH, cpEventName, bAllowOtherUsers);
		if (nRetVal != XN_STATUS_OK)
		{
			return XN_STATUS_OS_EVENT_CREATION_FAILED;
		}

		pEventOSName = strEventOSName;

		nRetVal = XnWin32GetSecurityAttributes(bAllowOtherUsers, &pSecurityAttributes);
		if (nRetVal != XN_STATUS_OK)
		{
			return XN_STATUS_OS_MUTEX_CREATION_FAILED;
		}
	}

	// Create a named event via the OS
	*pEventHandle = CreateEvent(pSecurityAttributes, bManualReset, FALSE, pEventOSName);

	// Make sure it succeeded (return value is not null)
	if (*pEventHandle == NULL)
	{
		xnLogError(XN_MASK_OS, "CreateEvent() failed with error %u", GetLastError());
		return XN_STATUS_OS_EVENT_CREATION_FAILED;
	}

	// All is good...
	return (XN_STATUS_OK);
}
예제 #13
0
XnVideoStream::Mode XnVideoStream::MediaTypeToMode(const CMediaType& mediaType)
{
	Mode result = {0};

	if (*mediaType.Type() != MEDIATYPE_Video)   // we only output video
	{                                                  
		xnLogError(XN_MASK_FILTER, "bad type");
		return result;
	}

	// Check for the subtypes we support
	const GUID *SubType = mediaType.Subtype();

	if (SubType && *SubType != GUID_NULL) 
	{
		if (*SubType == MEDIASUBTYPE_RGB24)
		{
			result.Format = XN_PIXEL_FORMAT_RGB24;
		}
		else if (*SubType == MEDIASUBTYPE_MJPG)
		{
			result.Format = XN_PIXEL_FORMAT_MJPEG;
		}
		else
		{
			xnLogVerbose(XN_MASK_FILTER, "bad subtype");
			return result;
		}
	}

	// Get the format area of the media type
	VIDEOINFO *pvi = (VIDEOINFO*)mediaType.Format();
	if (pvi == NULL)
	{
		return result;
	}

	result.OutputMode.nFPS = (XnUInt32)(10000000ULL / pvi->AvgTimePerFrame);
	result.OutputMode.nXRes = pvi->bmiHeader.biWidth;
	result.OutputMode.nYRes = pvi->bmiHeader.biHeight;
	return result;
}
예제 #14
0
XnStatus XnDeviceBase::WaitForPrimaryStream(XN_EVENT_HANDLE hNewDataEvent, XnStreamDataSet* pSet)
{
	XnStatus nRetVal = XN_STATUS_OK;

	XnWaitForPrimaryData WaitData;
	WaitData.pThis = this;
	WaitData.pSet = pSet;
	nRetVal = xnOSWaitForCondition(hNewDataEvent, XN_DEVICE_READ_FRAME_TIMEOUT, &XnDeviceBase::HasPrimaryStreamAdvancedCallback, &WaitData);
	if (nRetVal == XN_STATUS_OS_EVENT_TIMEOUT)
	{
		xnLogError(XN_MASK_DDK, "Not responding - primary stream did not advance!");
		return (XN_STATUS_IO_DEVICE_NOT_RESPONDING);
	}
	else
	{
		XN_IS_STATUS_OK(nRetVal);
	}

	return (XN_STATUS_OK);
}
XnStatus SocketInConnection::Connect()
{
	XnStatus nRetVal = XN_STATUS_OK;
	Disconnect(); // In case we're already connected
	nRetVal = xnOSCreateThread(&ReadThreadProc, this, &m_hReadThread);
	XN_IS_STATUS_OK_LOG_ERROR("Create input socket read thread", nRetVal);
	xnLogVerbose(XN_MASK_LINK, "Waiting for connection on socket %u...", m_nPort);
	nRetVal = xnOSWaitEvent(m_hConnectEvent, CONNECT_TIMEOUT);
	XN_IS_STATUS_OK_LOG_ERROR("Wait for input socket to connect", nRetVal);
	if (m_nConnectionStatus != XN_STATUS_OK)
	{
		xnLogError(XN_MASK_LINK, "Failed to connect to socket %u: %s", m_nPort, xnGetStatusString(m_nConnectionStatus));
		XN_ASSERT(FALSE);
		return m_nConnectionStatus;
	}
	xnLogVerbose(XN_MASK_LINK, "Socket %u connected.", m_nPort);
	nRetVal = xnOSSetThreadPriority(m_hReadThread, XN_PRIORITY_CRITICAL);
	XN_IS_STATUS_OK_LOG_ERROR("Set read thread priority", nRetVal);
	return XN_STATUS_OK;
}
예제 #16
0
XnStatus LinkContInputStream::UpdateData()
{
	xnl::AutoCSLocker csLock(m_hCriticalSection);
	if (!m_bInitialized)
	{
		xnLogError(XN_MASK_INPUT_STREAM, "Attempted to update data from stream %u which is not initialized", m_nStreamID);
		XN_ASSERT(FALSE);
		return XN_STATUS_NOT_INIT;
	}

	if (m_bNewDataAvailable)
	{
		//Copy working buffer to user buffer
		xnOSMemCopy(m_pUserBuffer, m_pWorkingBuffer, m_nUserBufferMaxSize);
		m_nUserBufferCurrentSize = m_nWorkingBufferCurrentSize;
		m_bNewDataAvailable = FALSE;
	}

	return XN_STATUS_OK;
}
예제 #17
0
XnPixelFormat XnSensorImageGenerator::GetPixelFormat()
{
	XnUInt64 nValue;
	m_pSensor->GetProperty(m_strModule, XN_STREAM_PROPERTY_OUTPUT_FORMAT, &nValue);

	switch (nValue)
	{
	case XN_OUTPUT_FORMAT_RGB24:
		return XN_PIXEL_FORMAT_RGB24;
	case XN_OUTPUT_FORMAT_YUV422:
		return XN_PIXEL_FORMAT_YUV422;
	case XN_OUTPUT_FORMAT_GRAYSCALE8:
		return XN_PIXEL_FORMAT_GRAYSCALE_8_BIT;
	case XN_OUTPUT_FORMAT_JPEG:
		return XN_PIXEL_FORMAT_MJPEG;
	default:
		xnLogError(XN_MASK_DEVICE_SENSOR, "Unknown output format: %d", nValue);
		return (XnPixelFormat)-1;
	}
}
예제 #18
0
XN_C_API XnStatus xnOSCreateNamedEvent(XN_EVENT_HANDLE* pEventHandle, const XnChar* cpEventName, XnBool bManualReset)
{
	// Local function variables
	XnStatus nRetVal = XN_STATUS_OK;

	// Validate the input/output pointers (to make sure none of them is NULL)
	XN_VALIDATE_OUTPUT_PTR(pEventHandle);

	// Create a named event via the OS
	*pEventHandle = CreateEvent(NULL, bManualReset, FALSE, cpEventName);

	// Make sure it succeeded (return value is not null)
	if (*pEventHandle == NULL)
	{
		xnLogError(XN_MASK_OS, "CreateEvent() failed with error %u", GetLastError());
		return XN_STATUS_OS_EVENT_CREATION_FAILED;
	}

	// All is good...
	return (XN_STATUS_OK);
}
예제 #19
0
XnStatus XnSensor::SetErrorState(XnStatus errorState)
{
	XnStatus nRetVal = XN_STATUS_OK;
	
	if (errorState != GetErrorState())
	{
		if (errorState == XN_STATUS_OK)
		{
			xnLogInfo(XN_MASK_DEVICE_SENSOR, "Device is back to normal state.");
		}
		else
		{
			xnLogError(XN_MASK_DEVICE_SENSOR, "Device has entered error mode: %s", xnGetStatusString(errorState));
		}

		nRetVal = m_ErrorState.UnsafeUpdateValue((XnUInt64)errorState);
		XN_IS_STATUS_OK(nRetVal);
	}
	
	return (XN_STATUS_OK);
}
예제 #20
0
XnBool XnDeviceBase::IsStream(XnDeviceModule* pModule)
{
	XnProperty* pProperty;
	XnStatus nRetVal = pModule->GetProperty(XN_STREAM_PROPERTY_IS_STREAM, &pProperty);
	if (nRetVal != XN_STATUS_OK)
		return FALSE;

	if (pProperty->GetType() != XN_PROPERTY_TYPE_INTEGER)
		return FALSE;

	XnIntProperty* pIntProperty = (XnIntProperty*)pProperty;

	XnUInt64 nValue;
	nRetVal = pIntProperty->GetValue(&nValue);
	if (nRetVal != XN_STATUS_OK)
	{
		xnLogError(XN_MASK_DDK, "Failed getting the value of the IsStream property: %s", xnGetStatusString(nRetVal));
		return FALSE;
	}

	return (XnBool)nValue;
}
예제 #21
0
XnStatus xnXmlReadQuery(const TiXmlElement* pQueryElem, XnNodeQuery* pQuery)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// vendor
	const TiXmlElement* pVendor = pQueryElem->FirstChildElement("Vendor");
	if (pVendor != NULL)
	{
		xnNodeQuerySetVendor(pQuery, pVendor->GetText());
	}

	// name
	const TiXmlElement* pName = pQueryElem->FirstChildElement("Name");
	if (pName != NULL)
	{
		xnNodeQuerySetName(pQuery, pName->GetText());
	}

	// Min version
	const TiXmlElement* pMinVersion = pQueryElem->FirstChildElement("MinVersion");
	if (pMinVersion != NULL)
	{
		XnVersion minVersion;
		nRetVal = xnReadVersionFromXml(pMinVersion, &minVersion);
		XN_IS_STATUS_OK(nRetVal);

		xnNodeQuerySetMinVersion(pQuery, &minVersion);
	}

	// Max version
	const TiXmlElement* pMaxVersion = pQueryElem->FirstChildElement("MaxVersion");
	if (pMaxVersion != NULL)
	{
		XnVersion maxVersion;
		nRetVal = xnReadVersionFromXml(pMaxVersion, &maxVersion);
		XN_IS_STATUS_OK(nRetVal);

		xnNodeQuerySetMaxVersion(pQuery, &maxVersion);
	}

	// Capabilities
	const TiXmlElement* pCapabilities = pQueryElem->FirstChildElement("Capabilities");
	if (pCapabilities != NULL)
	{
		const TiXmlElement* pCap = pCapabilities->FirstChildElement("Capability");
		while (pCap != NULL)
		{
			xnNodeQueryAddSupportedCapability(pQuery, pCap->GetText());
			pCap = pCap->NextSiblingElement("Capability");
		}
	}

	// Map Output Modes
	const TiXmlElement* pOutputModes = pQueryElem->FirstChildElement("MapOutputModes");
	if (pOutputModes != NULL)
	{
		const TiXmlElement* pMode = pOutputModes->FirstChildElement("MapOutputMode");
		while (pMode != NULL)
		{
			XnMapOutputMode Mode;
			nRetVal = xnXmlReadMapOutputMode(pMode, &Mode);
			XN_IS_STATUS_OK(nRetVal);

			xnNodeQueryAddSupportedMapOutputMode(pQuery, &Mode);

			pMode = pMode->NextSiblingElement("MapOutputMode");
		}
	}

	// Min User Position
	const TiXmlElement* pMinUserPositions = pQueryElem->FirstChildElement("MinUserPositions");
	if (pMinUserPositions != NULL)
	{
		XnInt nMinUserPositions;
		nRetVal = xnXmlReadTextAsInt(pMinUserPositions, &nMinUserPositions);
		XN_IS_STATUS_OK(nRetVal);

		xnNodeQuerySetSupportedMinUserPositions(pQuery, nMinUserPositions);
	}

	// Existing Node Only
	XnBool bExistingOnly = FALSE;
	const TiXmlElement* pExistingOnly = pQueryElem->FirstChildElement("ExistingNodeOnly");
	if (pExistingOnly != NULL)
	{
		xnNodeQuerySetExistingNodeOnly(pQuery, TRUE);
		bExistingOnly = TRUE;
	}

	// Non Existing Node Only
	const TiXmlElement* pNonExistingOnly = pQueryElem->FirstChildElement("NonExistingNodeOnly");
	if (pNonExistingOnly != NULL)
	{
		if (bExistingOnly)
		{
			xnLogError(XN_MASK_OPEN_NI, "Cannot specify both <ExistingNodeOnly> and <NonExistingNodeOnly> in query");
			XN_ASSERT(FALSE);
			return XN_STATUS_INVALID_OPERATION;
		}
		xnNodeQuerySetNonExistingNodeOnly(pQuery, TRUE);
	}

	// Needed Nodes
	const TiXmlElement* pNeededNodes = pQueryElem->FirstChildElement("NeededNodes");
	if (pNeededNodes != NULL)
	{
		const TiXmlElement* pNode = pNeededNodes->FirstChildElement("Node");
		while (pNode != NULL)
		{
			xnNodeQueryAddNeededNode(pQuery, pNode->GetText());

			pNode = pNode->NextSiblingElement("Node");
		}
	}

	// Creation info
	const TiXmlElement* pCreationInfo = pQueryElem->FirstChildElement("CreationInfo");
	if (pCreationInfo != NULL)
	{
		xnNodeQuerySetCreationInfo(pQuery, pCreationInfo->GetText());
	}

	return (XN_STATUS_OK);
}
예제 #22
0
HRESULT XnVideoStream::FillBuffer(IMediaSample *pms)
{
	XN_METHOD_START;

	XN_METHOD_CHECK_POINTER(pms);

	if (!m_imageGen.IsGenerating())
	{
		XN_METHOD_RETURN(E_UNEXPECTED);
	}

	VIDEOINFOHEADER* videoInfo = (VIDEOINFOHEADER*)m_mt.Format();
	bool bUpsideDown = videoInfo->bmiHeader.biHeight > 0;

	if (m_bFlipVertically)
	{
		bUpsideDown = !bUpsideDown;
	}

	BYTE *pData;
	long lDataLen;

	pms->GetPointer(&pData);
	lDataLen = pms->GetSize();

	{
		CAutoLock cAutoLock(m_pFilter->pStateLock());

		XnStatus nRetVal = XN_STATUS_OK;

		// ignore timeouts
		for(;;)
		{
			nRetVal = m_imageGen.WaitAndUpdateData();
			if (nRetVal != XN_STATUS_WAIT_DATA_TIMEOUT)
			{
				break;
			}
			else
			{
				xnDumpFileWriteString(m_Dump, "\tTimeout during FillBuffer\n");
			}
		}

		if (nRetVal != XN_STATUS_OK) XN_METHOD_RETURN(E_UNEXPECTED);
	}

	xn::ImageMetaData imageMD;
	m_imageGen.GetMetaData(imageMD);

	if (imageMD.PixelFormat() == XN_PIXEL_FORMAT_RGB24)
	{
		const XnRGB24Pixel* pImage = imageMD.RGB24Data();
		if (bUpsideDown)
		{
			// convert from left-to-right top-to-bottom RGB to left-to-right bottom-to-top BGR
			pImage += imageMD.XRes() * imageMD.YRes() - 1;

			for (XnUInt32 y = 0; y < imageMD.YRes(); ++y)
			{
				for (XnUInt32 x = 0; x < imageMD.XRes(); ++x, pImage -=1, pData += 3)
				{
					// translate RGB to BGR
					pData[0] = pImage->nBlue;
					pData[1] = pImage->nGreen;
					pData[2] = pImage->nRed;
				}
			}
		}
		else
		{
			for (XnUInt32 y = 0; y < imageMD.YRes(); ++y)
			{
				for (XnUInt32 x = 0; x < imageMD.XRes(); ++x, pImage += 1, pData += 3)
				{
					// translate RGB to BGR
					pData[0] = pImage->nBlue;
					pData[1] = pImage->nGreen;
					pData[2] = pImage->nRed;
				}
			}
		}
	}
	else if (imageMD.PixelFormat() == XN_PIXEL_FORMAT_MJPEG)
	{
		memcpy(pData, imageMD.Data(), imageMD.DataSize());
		pms->SetActualDataLength(imageMD.DataSize());
	}
	else
	{
		xnLogError(XN_MASK_FILTER, "Unsupported pixel format!");
		XN_METHOD_RETURN(E_UNEXPECTED);
	}

	// The current time is the sample's start
//		CRefTime rtStart = m_rtSampleTime;

	// Increment to find the finish time
//		m_rtSampleTime += (LONG)m_iRepeatTime;

//		pms->SetTime((REFERENCE_TIME *) &rtStart,(REFERENCE_TIME *) &m_rtSampleTime);

	pms->SetSyncPoint(TRUE);

	xnFPSMarkFrame(&m_FPS);

	XN_METHOD_RETURN(NOERROR);
}
예제 #23
0
XnStatus PrimeClient::RunPresetFile(const XnChar* strFileName)
{
	XnStatus nRetVal = XN_STATUS_OK;

	xnLogVerbose(XN_MASK_PRIME_CLIENT, "Executing preset file '%s'...", strFileName);

	// Check that file exists
	XnBool bFileExists;
	nRetVal = xnOSDoesFileExist(strFileName, &bFileExists);
	XN_IS_STATUS_OK(nRetVal);

	if (!bFileExists)
	{
		xnLogError(XN_MASK_PRIME_CLIENT, "File '%s' does not exist", strFileName);
		return XN_STATUS_OS_FILE_NOT_FOUND;
	}

	FILE* pFile = fopen(strFileName, "r");
	XN_ASSERT(pFile != NULL);

	XnChar strLine[1024];

	// read header
	if (NULL == fgets(strLine, sizeof(strLine), pFile))
	{
		xnLogError(XN_MASK_PRIME_CLIENT, "File '%s' is empty - no header", strFileName);
		return XN_STATUS_ERROR;
	}

	XnUInt32 nAddress;
	XnUInt32 nValue;
	XnUInt8 nBitOffset;
	XnUInt8 nBitWidth;

	for (;;)
	{
		// read a line
		if (NULL == fgets(strLine, sizeof(strLine), pFile))
		{
			// end of file reached
			break;
		}

		// skip empty lines
		if (xnOSStrCmp(strLine, "\n") == 0 || xnOSStrCmp(strLine, "\r\n") == 0)
		{
			continue;
		}

		// block name
		XnChar* pToken = strtok(strLine, ",");
		CHECK_TOKEN(pToken, strLine, pFile);

		// reg name
		pToken = strtok(NULL, ",");
		CHECK_TOKEN(pToken, strLine, pFile);

		// Address
		pToken = strtok(NULL, ",");
		CHECK_TOKEN(pToken, strLine, pFile);
		sscanf(pToken, "0x%x", &nAddress);

		// field name
		pToken = strtok(NULL, ",");
		CHECK_TOKEN(pToken, strLine, pFile);

		// bit offset
		pToken = strtok(NULL, ",");
		CHECK_TOKEN(pToken, strLine, pFile);
		nBitOffset = (XnUInt8)atoi(pToken);

		// bit width
		pToken = strtok(NULL, ",");
		CHECK_TOKEN(pToken, strLine, pFile);
		nBitWidth = (XnUInt8)atoi(pToken);

		// value
		pToken = strtok(NULL, ",");
		CHECK_TOKEN(pToken, strLine, pFile);
		sscanf(pToken, "0x%x", &nValue);

		// execute
		nRetVal = WriteAHB(nAddress, nValue, nBitOffset, nBitWidth);
		if (nRetVal != XN_STATUS_OK)
		{
			fclose(pFile);
			return nRetVal;
		}
	}

	fclose(pFile);

	xnLogInfo(XN_MASK_PRIME_CLIENT, "Preset file '%s' was executed", strFileName);

	return (XN_STATUS_OK);
}
예제 #24
0
XnStatus XnSensorClient::CreateIOStreamImpl(const XnChar *strConnectionString, XnIOStream *&pStream)
{
	XnStatus nRetVal = XN_STATUS_OK;

	nRetVal = xnOSCreateSocket(XN_OS_TCP_SOCKET, XN_SENSOR_SERVER_IP_ADDRESS, XN_SENSOR_SERVER_PORT, &m_hSocket);
	XN_IS_STATUS_OK(nRetVal);

	// connect to server
	XnUInt64 nStart;
	xnOSGetTimeStamp(&nStart);

	nRetVal = XN_STATUS_OS_NETWORK_TIMEOUT;
	for (XnUInt32 nRetries = 0; (nRetries < XN_SENSOR_CLIENT_CONNECT_RETRIES) && (nRetVal != XN_STATUS_OK); nRetries++)
	{
		nRetVal = xnOSConnectSocket(m_hSocket, XN_SENSOR_CLIENT_WAIT_FOR_SERVER);
	}

	if (nRetVal == XN_STATUS_OS_NETWORK_TIMEOUT)
	{
		xnLogError(XN_MASK_SENSOR_CLIENT, "Got timeout waiting for server");
		return nRetVal;
	}
	else if (nRetVal != XN_STATUS_OK)
	{
		xnLogError(XN_MASK_SENSOR_CLIENT, "Got an error trying to connect to server socket: %s", xnGetStatusString(nRetVal));
		return nRetVal;
	}

	XnIONetworkStream *pNetworkStream = XN_NEW(XnIONetworkStream, m_hSocket);
	if (pNetworkStream == NULL)
	{
		xnOSCloseSocket(m_hSocket);
		return XN_STATUS_ALLOC_FAILED;
	}
	pNetworkStream->SetReadTimeout(XN_SENSOR_CLIENT_READ_TIMEOUT);
	pStream = pNetworkStream;

	// create outgoing data packer (incoming is created by base class)
	m_pOutgoingPacker = XN_NEW(XnDataPacker, pNetworkStream, XN_SENSOR_SERVER_CONFIG_PACKER_SIZE);
	if (m_pOutgoingPacker == NULL)
	{
		XN_DELETE(pNetworkStream);
		xnOSCloseSocket(m_hSocket);
		return XN_STATUS_ALLOC_FAILED;
	}

	nRetVal = m_pOutgoingPacker->Init();
	if (nRetVal != XN_STATUS_OK)
	{
		XN_DELETE(pNetworkStream);
		XN_DELETE(m_pOutgoingPacker);
		xnOSCloseSocket(m_hSocket);
		return nRetVal;
	}

	// send server a request to open the sensor
	nRetVal = m_pOutgoingPacker->WriteCustomData(XN_SENSOR_SERVER_MESSAGE_OPEN_SENSOR, strConnectionString, strlen(strConnectionString) + 1);
	if (nRetVal != XN_STATUS_OK)
	{
		XN_DELETE(pNetworkStream);
		XN_DELETE(m_pOutgoingPacker);
		xnOSCloseSocket(m_hSocket);
		return nRetVal;
	}

	return (XN_STATUS_OK);
}
예제 #25
0
OniStatus Context::deviceOpen(const char* uri, const char* mode, OniDeviceHandle* pDevice)
{
	oni::implementation::Device* pMyDevice = NULL;

	const char* deviceURI = uri;
	if (xnOSStrLen(m_overrideDevice) > 0)
		deviceURI = m_overrideDevice;

	xnLogVerbose(XN_MASK_ONI_CONTEXT, "Trying to open device by URI '%s'", deviceURI == NULL ? "(NULL)" : deviceURI);

	m_cs.Lock();

	if (deviceURI == NULL)
	{
		// Default
		if (m_devices.Size() == 0)
		{
			m_errorLogger.Append("DeviceOpen using default: no devices found");
			xnLogError(XN_MASK_ONI_CONTEXT, "Can't open default device - none found");
			m_cs.Unlock();
			return ONI_STATUS_ERROR;
		}

		pMyDevice = *m_devices.Begin();
	}
	else
	{
		for (xnl::List<Device*>::Iterator iter = m_devices.Begin(); iter != m_devices.End(); ++iter)
		{
			if (xnOSStrCmp((*iter)->getInfo()->uri, deviceURI) == 0)
			{
				pMyDevice = *iter;
			}
		}
	}

	if (pMyDevice == NULL)
	{
		for (xnl::List<DeviceDriver*>::Iterator iter = m_deviceDrivers.Begin(); iter != m_deviceDrivers.End() && pMyDevice == NULL; ++iter)
		{
			if ((*iter)->tryDevice(deviceURI))
			{
				for (xnl::List<Device*>::Iterator iter = m_devices.Begin(); iter != m_devices.End(); ++iter)
				{
					if (xnOSStrCmp((*iter)->getInfo()->uri, deviceURI) == 0)
					{
						pMyDevice = *iter;
						break;
					}
				}
			}
			else
			{
//					printf("Not yet\n");
			}
		}
	}

	m_cs.Unlock();

	if (pMyDevice == NULL)
	{
		xnLogError(XN_MASK_ONI_CONTEXT, "Couldn't open device '%s'", uri);
		m_errorLogger.Append("DeviceOpen: Couldn't open device '%s'", uri);
		return ONI_STATUS_NO_DEVICE;
	}

	_OniDevice* pDeviceHandle = XN_NEW(_OniDevice);
	if (pDeviceHandle == NULL)
	{
		m_errorLogger.Append("Couldn't allocate memory for DeviceHandle");
		return ONI_STATUS_ERROR;
	}
	*pDevice = pDeviceHandle;
	pDeviceHandle->pDevice = pMyDevice;

	return pMyDevice->open(mode);
}
예제 #26
0
HRESULT XnVideoStream::GetStreamCapability(int iIndex, CMediaType& mediaType, VIDEO_STREAM_CONFIG_CAPS& vscc)
{
	// check bounds
	if(iIndex < 0 || iIndex >= int(m_aSupportedModes.GetSize()))
	{
		xnLogVerbose(XN_MASK_FILTER, "GetStreamCapability() - Index %d is out of bounds!", iIndex);
		return S_FALSE;
	}

	VIDEOINFO *pvi = (VIDEOINFO*)mediaType.AllocFormatBuffer(sizeof(VIDEOINFO));
	if(NULL == pvi)
		return(E_OUTOFMEMORY);

	ZeroMemory(pvi, sizeof(VIDEOINFO));

	int xRes = m_aSupportedModes[iIndex].OutputMode.nXRes;
	int yRes = m_aSupportedModes[iIndex].OutputMode.nYRes;

	XnUInt64 nFrameTime = 10000000 / m_aSupportedModes[iIndex].OutputMode.nFPS;

	if (m_aSupportedModes[iIndex].Format == XN_PIXEL_FORMAT_RGB24)
	{
		pvi->bmiHeader.biCompression = BI_RGB;
	}
	else if (m_aSupportedModes[iIndex].Format == XN_PIXEL_FORMAT_MJPEG)
	{
		pvi->bmiHeader.biCompression = 'GPJM';
	}
	else
	{
		xnLogError(XN_MASK_FILTER, "Unknown format type!");
		return E_UNEXPECTED;
	}

	pvi->bmiHeader.biBitCount	= 24;
	pvi->bmiHeader.biSize       = sizeof(BITMAPINFOHEADER);
	pvi->bmiHeader.biWidth      = xRes;
	pvi->bmiHeader.biHeight     = yRes;
	pvi->bmiHeader.biPlanes     = 1;
	pvi->bmiHeader.biSizeImage  = GetBitmapSize(&pvi->bmiHeader);
	pvi->bmiHeader.biClrImportant = 0;

	SetRectEmpty(&(pvi->rcSource)); // we want the whole image area rendered.
	SetRectEmpty(&(pvi->rcTarget)); // no particular destination rectangle

	pvi->dwBitRate = 
		GetBitmapSize(&pvi->bmiHeader) * // bytes per frame
		m_aSupportedModes[iIndex].OutputMode.nFPS * // frames per second
		8; // bits per byte

	pvi->dwBitErrorRate = 0; // assume no errors
	pvi->AvgTimePerFrame = nFrameTime;

	mediaType.SetType(&MEDIATYPE_Video);
	mediaType.SetFormatType(&FORMAT_VideoInfo);
	mediaType.SetTemporalCompression(FALSE);

	// Work out the GUID for the subtype from the header info.
	const GUID SubTypeGUID = GetBitmapSubtype(&pvi->bmiHeader);
	mediaType.SetSubtype(&SubTypeGUID);
	mediaType.SetSampleSize(pvi->bmiHeader.biSizeImage);

	vscc.guid = FORMAT_VideoInfo;
	vscc.VideoStandard = AnalogVideo_None;
	vscc.InputSize.cx = xRes;
	vscc.InputSize.cy = yRes;
	vscc.MinCroppingSize.cx = xRes;
	vscc.MinCroppingSize.cy = yRes;
	vscc.MaxCroppingSize.cx = xRes;
	vscc.MaxCroppingSize.cy = yRes;
	vscc.CropGranularityX = 1;
	vscc.CropGranularityY = 1;
	vscc.CropAlignX = 1;
	vscc.CropAlignY = 1;

	vscc.MinOutputSize.cx = xRes;
	vscc.MinOutputSize.cy = yRes;
	vscc.MaxOutputSize.cx = xRes;
	vscc.MaxOutputSize.cy = yRes;
	vscc.OutputGranularityX = 1;
	vscc.OutputGranularityY = 1;
	vscc.StretchTapsX = 0;
	vscc.StretchTapsY = 0;
	vscc.ShrinkTapsX = 0;
	vscc.ShrinkTapsY = 0;
	// Frame interval is in 100 nanosecond units
	vscc.MinFrameInterval = nFrameTime;
	vscc.MaxFrameInterval = nFrameTime;
	vscc.MinBitsPerSecond = 
		mediaType.GetSampleSize() * // bytes in frame
		m_aSupportedModes[iIndex].OutputMode.nFPS * // frames per second
		8; // bits per byte
	vscc.MaxBitsPerSecond = vscc.MinBitsPerSecond;

	return S_OK;
}
예제 #27
0
XnStatus XnSensorClient::InitImpl(const XnDeviceConfig* pDeviceConfig)
{
	XnStatus nRetVal = XN_STATUS_OK;
	XN_MUTEX_HANDLE hServerRunningMutex = NULL;
	XnOSEvent serverRunningEvent;

	nRetVal = serverRunningEvent.Open(XN_SENSOR_SERVER_RUNNING_EVENT_NAME);
	if (nRetVal != XN_STATUS_OK)
	{
		nRetVal = serverRunningEvent.Create(XN_SENSOR_SERVER_RUNNING_EVENT_NAME, TRUE);
		if (nRetVal != XN_STATUS_OK)
		{
			xnLogError(XN_MASK_SENSOR_CLIENT, "Failed to create server running event: %s", xnGetStatusString(nRetVal));
			return nRetVal;
		}
	}
	
	nRetVal = xnOSCreateNamedMutex(&hServerRunningMutex, XN_SENSOR_SERVER_RUNNING_MUTEX_NAME);
	XN_IS_STATUS_OK(nRetVal);
	
	nRetVal = xnOSLockMutex(hServerRunningMutex, XN_SENSOR_SERVER_RUNNING_MUTEX_TIMEOUT);
	if (nRetVal != XN_STATUS_OK)
	{
		xnOSCloseMutex(&hServerRunningMutex);
		return nRetVal;
	}

	XnBool bServerRunning = (serverRunningEvent.Wait(1) == XN_STATUS_OK);
	nRetVal = xnOSUnLockMutex(hServerRunningMutex);
	xnOSCloseMutex(&hServerRunningMutex);
	XN_IS_STATUS_OK(nRetVal);

	if (!bServerRunning)
	{
		nRetVal = StartServerProcess();
		if (nRetVal != XN_STATUS_OK)
		{
			xnLogError(XN_MASK_SENSOR_CLIENT, "Failed to start server process: %s", xnGetStatusString(nRetVal));
			return nRetVal;
		}
	}

	nRetVal = serverRunningEvent.Wait(XN_SENSOR_CLIENT_WAIT_FOR_SERVER);
	if (nRetVal != XN_STATUS_OK)
	{
		xnLogError(XN_MASK_SENSOR_CLIENT, "Failed to wait for server to start: %s", xnGetStatusString(nRetVal));
		return nRetVal;
	}

	// init network
	nRetVal = xnOSInitNetwork();
	XN_IS_STATUS_OK(nRetVal);

	nRetVal = xnOSCreateCriticalSection(&m_hLock);
	XN_IS_STATUS_OK(nRetVal);

	// now init
	nRetVal = XnStreamReaderDevice::InitImpl(pDeviceConfig);
	if (nRetVal != XN_STATUS_OK)
	{
		xnOSCloseCriticalSection(&m_hLock);
		return nRetVal;
	}

	m_bConnected = TRUE;

	nRetVal = xnOSCreateEvent(&m_hReplyEvent, FALSE);
	if (nRetVal != XN_STATUS_OK)
	{
		xnOSCloseCriticalSection(&m_hLock);
		return nRetVal;
	}

	nRetVal = xnOSCreateThread(ListenThread, this, &m_hListenThread);
	if (nRetVal != XN_STATUS_OK)
	{
		xnOSCloseEvent(&m_hReplyEvent);
		xnOSCloseCriticalSection(&m_hLock);
		return nRetVal;
	}
	
	return (XN_STATUS_OK);
}
예제 #28
0
XN_C_API XnStatus xnOSConnectSocket(XN_SOCKET_HANDLE Socket, XnUInt32 nMillisecsTimeout)
{
	// Local function variables
	XnInt32 nRetVal = 0;
	sockaddr SocketAddress;
	fd_set fdWriteHandles;
	fd_set fdExceptHandles;
	struct timeval selectTimeOut;
	struct timeval* pTimeout = xnOSMillisecsToTimeVal(nMillisecsTimeout, &selectTimeOut);

	// Validate the input/output pointers (to make sure none of them is NULL)
	XN_VALIDATE_INPUT_PTR(Socket);

	// Make sure the actual socket handle isn't NULL
	XN_RET_IF_INVALID(Socket->Socket, XN_STATUS_OS_INVALID_SOCKET);

	// Connect to the socket and make sure it succeeded
	if (sizeof(SocketAddress) != sizeof(Socket->SocketAddress))
	{
		return(XN_STATUS_OS_NETWORK_SOCKET_CONNECT_FAILED);
	}

	xnOSMemCopy(&SocketAddress, &Socket->SocketAddress, sizeof(SocketAddress));
	
	// Make the socket non-blocking temporarily
	int nFlags = fcntl(Socket->Socket, F_GETFL, 0);
	int nNonBlockFlags = nFlags | O_NONBLOCK;
	if (-1 == fcntl(Socket->Socket, F_SETFL, nNonBlockFlags))
	{
		XN_LOG_ERROR_RETURN(XN_STATUS_OS_NETWORK_SOCKET_CONNECT_FAILED, XN_MASK_OS, "fcntl() failed with error %d", errno);
	}

	//This is a non-blocking connect() call - it doesn't do anything until we call select()
	nRetVal = connect(Socket->Socket, &SocketAddress, sizeof(SocketAddress));
	if (nRetVal	== -1 && errno != EINPROGRESS)
	{
		xnLogError(XN_MASK_OS, "connect() failed with error %d", errno);
		return(XN_STATUS_OS_NETWORK_SOCKET_CONNECT_FAILED);
	}

	FD_ZERO(&fdWriteHandles);
	FD_SET(Socket->Socket, &fdWriteHandles);
	FD_ZERO(&fdExceptHandles);
	FD_SET(Socket->Socket, &fdExceptHandles);
	nRetVal = select(Socket->Socket + 1, NULL, &fdWriteHandles, &fdExceptHandles, pTimeout);

	//Make the socket blocking again before we check select()'s success
	fcntl(Socket->Socket, F_SETFL, nFlags);

	if (nRetVal == 0)
	{
		return (XN_STATUS_OS_NETWORK_TIMEOUT);
	}
	else if (nRetVal == -1)
	{
		XN_LOG_ERROR_RETURN(XN_STATUS_OS_NETWORK_SOCKET_ACCEPT_FAILED, XN_MASK_OS, "select() returned error: %d", errno);
	}
	else
	{
		// select returned due to socket state change. Check if an error occurred or everything is OK.
		if (FD_ISSET(Socket->Socket, &fdExceptHandles))
		{
			XnUInt32 nLastError = 0;
			XnUInt32 nLastErrorSize = sizeof(nLastError);
			getsockopt(Socket->Socket, SOL_SOCKET, SO_ERROR, &nLastError, &nLastErrorSize);
			XN_LOG_ERROR_RETURN(XN_STATUS_OS_NETWORK_SOCKET_CONNECT_FAILED, XN_MASK_OS, "Connect failed with error: %u", nLastError);
		}
		// else, it means it's in the writable state, which means connect succeeded.
		XN_ASSERT(FD_ISSET(Socket->Socket, &fdWriteHandles));
	}

	// All is good...
	return (XN_STATUS_OK);
}
예제 #29
0
XN_C_API XnStatus xnOSConnectSocket(XN_SOCKET_HANDLE Socket, XnUInt32 nMillisecsTimeout)
{
	// Local function variables
	XnInt32 nRetVal = 0;
	sockaddr SocketAddress;
	fd_set fdWriteHandles;
	fd_set fdExceptHandles;
	struct timeval selectTimeOut;
	struct timeval* pTimeout = xnOSMillisecsToTimeVal(nMillisecsTimeout, &selectTimeOut);

	// Validate the input/output pointers (to make sure none of them is NULL)
	XN_VALIDATE_INPUT_PTR(Socket);

	// Make sure the actual socket handle isn't NULL
	XN_RET_IF_NULL(Socket->Socket, XN_STATUS_OS_INVALID_SOCKET);

	// Connect to the socket and make sure it succeeded
	xnOSMemCopy(&SocketAddress, &Socket->SocketAddress, sizeof(SocketAddress));

	// if timeout is XN_SOCKET_DEFAULT_TIMEOUT, leave the socket as a blocking one
	if (nMillisecsTimeout != XN_SOCKET_DEFAULT_TIMEOUT)
	{
		// Make the socket non-blocking temporarily
		u_long nNonBlockingSocket = 1;
		if (ioctlsocket(Socket->Socket, FIONBIO, &nNonBlockingSocket) != 0)
		{
			XN_LOG_ERROR_RETURN(XN_STATUS_OS_NETWORK_SOCKET_CONNECT_FAILED, XN_MASK_OS, "ioctlsocket() failed with error %d", WSAGetLastError());
		}
	}

	nRetVal = connect(Socket->Socket, &SocketAddress, sizeof(SocketAddress));
	if ((nRetVal == SOCKET_ERROR) && (WSAGetLastError() != WSAEWOULDBLOCK))
	{
		xnLogError(XN_MASK_OS, "connect() failed with winsock error %d", WSAGetLastError());
		return(XN_STATUS_OS_NETWORK_SOCKET_CONNECT_FAILED);
	}

	if (nMillisecsTimeout != XN_SOCKET_DEFAULT_TIMEOUT)
	{
		XN_PRAGMA_START_DISABLED_WARNING_SECTION(XN_CONDITION_IS_CONST_WARNING_ID);
		FD_ZERO(&fdWriteHandles);
		FD_SET(Socket->Socket, &fdWriteHandles);
		FD_ZERO(&fdExceptHandles);
		FD_SET(Socket->Socket, &fdExceptHandles);
		XN_PRAGMA_STOP_DISABLED_WARNING_SECTION;

		nRetVal = select(1 /* ignored */, NULL, &fdWriteHandles, &fdExceptHandles, pTimeout);

		// in any case, make the socket blocking again before we check select()'s success
		u_long nBlockingSocket = 0;
		ioctlsocket(Socket->Socket, FIONBIO, &nBlockingSocket);

		if (nRetVal == 0)
		{
			return (XN_STATUS_OS_NETWORK_TIMEOUT);
		}
		else if (nRetVal == SOCKET_ERROR)
		{
			XN_LOG_ERROR_RETURN(XN_STATUS_OS_NETWORK_SOCKET_CONNECT_FAILED, XN_MASK_OS, "select() returned WinSock error: %d", WSAGetLastError());
		}
		else
		{
			// select returned due to socket state change. Check if an error occurred or everything is OK.
			if (FD_ISSET(Socket->Socket, &fdExceptHandles))
			{
				XnUInt32 nLastError = 0;
				XnInt32 nLastErrorSize = sizeof(nLastError);
				getsockopt(Socket->Socket, SOL_SOCKET, SO_ERROR, (char*)&nLastError, &nLastErrorSize);
				XN_LOG_ERROR_RETURN(XN_STATUS_OS_NETWORK_SOCKET_CONNECT_FAILED, XN_MASK_OS, "Connect failed with error: %u", nLastError);
			}
			// else, it means it's in the writable state, which means connect succeeded.
			XN_ASSERT(FD_ISSET(Socket->Socket, &fdWriteHandles));
		}
	}

	// All is good...
	return (XN_STATUS_OK);
}
예제 #30
0
XnStatus Context::loadLibraries(const char* directoryName)
{
	XnStatus nRetVal;

	// Get a file list of Xiron devices

	XnInt32 nFileCount = 0;
	typedef XnChar FileName[XN_FILE_MAX_PATH];
	FileName* acsFileList = NULL;

#if (ONI_PLATFORM != ONI_PLATFORM_ANDROID_ARM)
	XnChar cpSearchString[XN_FILE_MAX_PATH] = "";

	xnLogVerbose(XN_MASK_ONI_CONTEXT, "Looking for drivers in drivers repository '%s'", directoryName);

	// Build the search pattern string
	XN_VALIDATE_STR_APPEND(cpSearchString, directoryName, XN_FILE_MAX_PATH, nRetVal);
	XN_VALIDATE_STR_APPEND(cpSearchString, XN_FILE_DIR_SEP, XN_FILE_MAX_PATH, nRetVal);
	XN_VALIDATE_STR_APPEND(cpSearchString, XN_SHARED_LIBRARY_PREFIX, XN_FILE_MAX_PATH, nRetVal);
	XN_VALIDATE_STR_APPEND(cpSearchString, XN_FILE_ALL_WILDCARD, XN_FILE_MAX_PATH, nRetVal);
	XN_VALIDATE_STR_APPEND(cpSearchString, XN_SHARED_LIBRARY_POSTFIX, XN_FILE_MAX_PATH, nRetVal);

	nRetVal = xnOSCountFiles(cpSearchString, &nFileCount);
	if (nRetVal != XN_STATUS_OK || nFileCount == 0)
	{
		xnLogError(XN_MASK_ONI_CONTEXT, "Found no drivers matching '%s'", cpSearchString);
		m_errorLogger.Append("Found no files matching '%s'", cpSearchString);
		return XN_STATUS_NO_MODULES_FOUND;
	}

	acsFileList = XN_NEW_ARR(FileName, nFileCount);
	nRetVal = xnOSGetFileList(cpSearchString, NULL, acsFileList, nFileCount, &nFileCount);
#else
	// Android
	nFileCount = 3;
	acsFileList = XN_NEW_ARR(FileName, nFileCount);
	strcpy(acsFileList[0], "libPS1080.so");
	strcpy(acsFileList[1], "libOniFile.so");
	strcpy(acsFileList[2], "libPSLink.so");
#endif

	// Save directory
	XnChar workingDir[XN_FILE_MAX_PATH];
	xnOSGetCurrentDir(workingDir, XN_FILE_MAX_PATH);
	// Change directory
	xnOSSetCurrentDir(directoryName);

	for (int i = 0; i < nFileCount; ++i)
	{
		DeviceDriver* pDeviceDriver = XN_NEW(DeviceDriver, acsFileList[i], m_frameManager, m_errorLogger);
		if (pDeviceDriver == NULL || !pDeviceDriver->isValid())
		{
			xnLogVerbose(XN_MASK_ONI_CONTEXT, "Couldn't use file '%s' as a device driver", acsFileList[i]);
			m_errorLogger.Append("Couldn't understand file '%s' as a device driver", acsFileList[i]);
			XN_DELETE(pDeviceDriver);
			continue;
		}
		OniCallbackHandle dummy;
		pDeviceDriver->registerDeviceConnectedCallback(deviceDriver_DeviceConnected, this, dummy);
		pDeviceDriver->registerDeviceDisconnectedCallback(deviceDriver_DeviceDisconnected, this, dummy);
		pDeviceDriver->registerDeviceStateChangedCallback(deviceDriver_DeviceStateChanged, this, dummy);
		if (!pDeviceDriver->initialize())
		{
			xnLogVerbose(XN_MASK_ONI_CONTEXT, "Couldn't use file '%s' as a device driver", acsFileList[i]);
			m_errorLogger.Append("Couldn't initialize device driver from file '%s'", acsFileList[i]);
			XN_DELETE(pDeviceDriver);
			continue;
		}
		m_cs.Lock();
		m_deviceDrivers.AddLast(pDeviceDriver);
		m_cs.Unlock();
	}

	// Return to directory
	xnOSSetCurrentDir(workingDir);

	if (m_deviceDrivers.Size() == 0)
	{
		xnLogError(XN_MASK_ONI_CONTEXT, "Found no valid drivers");
		m_errorLogger.Append("Found no valid drivers in '%s'", directoryName);
		return XN_STATUS_NO_MODULES_FOUND;
	}

	XN_DELETE_ARR(acsFileList);

	return XN_STATUS_OK;
}