void QQmlNetwork::handelError(QString err)
{
    setErrorString(err);
}
Example #2
0
void QLocalSocket::connectToServer(const QString &name, OpenMode openMode)
{
    Q_D(QLocalSocket);
    if (state() == ConnectedState || state() == ConnectingState) {
        setErrorString(tr("Trying to connect while connection is in progress"));
        emit error(QLocalSocket::OperationError);
        return;
    }

    d->error = QLocalSocket::UnknownSocketError;
    d->errorString = QString();
    d->state = ConnectingState;
    emit stateChanged(d->state);
    if (name.isEmpty()) {
        d->error = QLocalSocket::ServerNotFoundError;
        setErrorString(QLocalSocket::tr("%1: Invalid name").arg(QLatin1String("QLocalSocket::connectToServer")));
        d->state = UnconnectedState;
        emit error(d->error);
        emit stateChanged(d->state);
        return;
    }

    QString pipePath = QLatin1String("\\\\.\\pipe\\");
    if (name.startsWith(pipePath))
        d->fullServerName = name;
    else
        d->fullServerName = pipePath + name;
    // Try to open a named pipe
    HANDLE localSocket;
    forever {
        DWORD permissions = (openMode & QIODevice::ReadOnly) ? GENERIC_READ : 0;
        permissions |= (openMode & QIODevice::WriteOnly) ? GENERIC_WRITE : 0;
        localSocket = CreateFile((const wchar_t *)d->fullServerName.utf16(),   // pipe name
                                 permissions,
                                 0,              // no sharing
                                 NULL,           // default security attributes
                                 OPEN_EXISTING,  // opens existing pipe
                                 FILE_FLAG_OVERLAPPED,
                                 NULL);          // no template file

        if (localSocket != INVALID_HANDLE_VALUE)
            break;
        DWORD error = GetLastError();
        // It is really an error only if it is not ERROR_PIPE_BUSY
        if (ERROR_PIPE_BUSY != error) {
            break;
        }

        // All pipe instances are busy, so wait until connected or up to 5 seconds.
        if (!WaitNamedPipe((const wchar_t *)d->fullServerName.utf16(), 5000))
            break;
    }

    if (localSocket == INVALID_HANDLE_VALUE) {
        d->setErrorString(QLatin1String("QLocalSocket::connectToServer"));
        d->fullServerName = QString();
        return;
    }

    // we have a valid handle
    d->serverName = name;
    if (setSocketDescriptor((qintptr)localSocket, ConnectedState, openMode)) {
        d->handle = localSocket;
        emit connected();
    }
}
bool QTarDecode::decodeData(const std::vector<char> &data)
{
    setErrorString("Unknown error");
    if(data.size()<1024)
        return false;
    unsigned int offset=0;
    while(offset<data.size())
    {
        //load the file name from ascii, from 0+offset with size of 100
        std::string fileName(data.data()+offset,100);
        while(!fileName.empty() && fileName.at(fileName.size()-1)==0x00)
            fileName.resize(fileName.size()-1);
        //load the file type
        std::string fileType(data.data()+156+offset,1);
        while(!fileName.empty() && fileType.at(fileType.size()-1)==0x00)
            fileType.resize(fileType.size()-1);
        //load the ustar string
        std::string ustar(data.data()+257+offset,5);
        while(!fileName.empty() && ustar.at(ustar.size()-1)==0x00)
            ustar.resize(ustar.size()-1);
        //load the ustar version
        std::string ustarVersion(data.data()+263+offset,2);
        while(!fileName.empty() && ustarVersion.at(ustarVersion.size()-1)==0x00)
            ustarVersion.resize(ustarVersion.size()-1);
        bool ok=false;
        //load the file size from ascii, from 124+offset with size of 12
        uint64_t finalSize=0;
        std::string sizeString(data.data()+124+offset,12);
        if(sizeString.at(sizeString.size()-1)==0x00)
        {
            //the size is in octal base
            sizeString.resize(sizeString.size()-1);
            finalSize=octaltouint64(sizeString,&ok);
        }
        else
            finalSize=stringtouint64(sizeString,&ok);
        //if the size conversion to qulonglong have failed, then qui with error
        if(ok==false)
        {
            //it's the end of the archive, no more verification
            break;
        }
        //if check if the ustar not found
        if(ustar!="ustar")
        {
            setErrorString("\"ustar\" string not found at "+std::to_string(257+offset)+", content: \""+ustar+"\"");
            return false;
        }
        if(ustarVersion!="00")
        {
            setErrorString("ustar version string is wrong, content:\""+ustarVersion+"\"");
            return false;
        }
        //check if the file have the good size for load the data
        if((offset+512+finalSize)>data.size())
        {
            setErrorString("The tar file seem be too short");
            return false;
        }
        if(fileType=="0") //this code manage only the file, then only the file is returned
        {
            std::vector<char> newdata;
            newdata.resize(finalSize);
            memcpy(newdata.data(),data.data()+512+offset,finalSize);
            fileList.push_back(fileName);
            dataList.push_back(newdata);
        }
        //calculate the offset for the next header
        bool retenu=((finalSize%512)!=0);
        //go to the next header
        offset+=512+(finalSize/512+retenu)*512;
    }
    if(fileList.size()>0)
    {
        std::string baseDirToTest=fileList.at(0);
        std::size_t found = baseDirToTest.find_last_of("/");
        if(found!=std::string::npos && found>=baseDirToTest.size())
            baseDirToTest.resize(baseDirToTest.size()-(baseDirToTest.size()-found));
        bool isFoundForAllEntries=true;
        for (unsigned int i = 0; i < fileList.size(); ++i)
            if(!stringStartWith(fileList.at(i),baseDirToTest))
                isFoundForAllEntries=false;
        if(isFoundForAllEntries)
            for (unsigned int i = 0; i < fileList.size(); ++i)
                fileList[i].erase(0,baseDirToTest.size());
    }
    return true;
}
bool MIPAudioTrackOutput::open(int sampRate, int channels, MIPTime interval, MIPTime arrayTime)
{
	if (m_pTrack != 0)
	{
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_CLIENTALREADYOPEN);
		return false;
	}
	
	if (arrayTime.getValue() < 2.0) // Should be at least two since one second will be filled in 
	{                               // in the close function
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_ARRAYTIMETOOSMALL);
		return false;
	}

	if (!(channels == 1 || channels == 2))
	{
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_INVALIDCHANNELS);
		return false;
	}
	
	m_pTrack = new android::AudioTrack();
	if (m_pTrack->set(android::AudioSystem::DEFAULT, sampRate, android::AudioSystem::PCM_16_BIT,
	                  channels, 0, 0, StaticAudioTrackCallback, this, 0) != 0)
	{
		delete m_pTrack;
		m_pTrack = 0;
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_CANTOPENCLIENT);
		return false;
	}
	
	// TODO: check sampling rate somehow?

	if (channels != m_pTrack->channelCount())
	{
		delete m_pTrack;
		m_pTrack = 0;
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_CANTGETCHANNELS);
		return false;
	}

	m_sampRate = sampRate;
	m_channels = channels;

//	m_blockFrames = m_pTrack->frameCount() / 2; // TODO: better way to obtain notificationFrames?
	m_blockFrames = m_pTrack->frameCount();

	size_t frames = (size_t)(interval.getValue()*(real_t)m_sampRate+0.5);

	if (frames < m_blockFrames)
	{
		delete m_pTrack;
		m_pTrack = 0;

		char str[256];
		real_t minInterval = ((real_t)m_blockFrames)/((real_t)m_sampRate);

		MIP_SNPRINTF(str, 255, "%f", (double)minInterval);

		setErrorString(std::string(MIPAUDIOTRACKOUTPUT_ERRSTR_INTERVALTOOSMALL) + std::string(str));
		return false;
	}

	m_blockLength = m_blockFrames * m_channels;
	m_blockTime = MIPTime((real_t)m_blockFrames/(real_t)m_sampRate);
	m_frameArrayLength = ((size_t)((arrayTime.getValue() * ((real_t)m_sampRate)) + 0.5));
	m_intervalLength = ((((size_t)((interval.getValue()*(real_t)m_sampRate)+0.5))/m_blockLength)+1)*m_blockLength;
	m_interval = MIPTime((real_t)m_intervalLength/(real_t)m_sampRate);

	if (m_intervalLength > m_frameArrayLength/4)
	{
		delete m_pTrack;
		m_pTrack = 0;
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_ARRAYTIMETOOSMALL);
		return false;
	}

	// make sure a fixed number of blocks fit in the frame array
	size_t numBlocks = m_frameArrayLength / m_blockLength + 1;
	m_frameArrayLength = numBlocks * m_blockLength * m_channels;
	
	m_pFrameArray = new uint16_t[m_frameArrayLength];
	
	for (size_t i = 0 ; i < m_frameArrayLength ; i++)
		m_pFrameArray[i] = 0;
	
	m_currentPos = 0;
	m_nextPos = m_intervalLength;
	m_distTime = m_interval;

	m_pTrack->start();

	return true;
}
Example #5
0
/*!
    Sets the error condition to be \a errorCode. The human-readable
    message is set with \a errorString.

    Calling setError() does not emit the error(QNetworkReply::NetworkError)
    signal.

    \sa error(), errorString()
*/
void QNetworkReply::setError(NetworkError errorCode, const QString &errorString)
{
    Q_D(QNetworkReply);
    d->errorCode = errorCode;
    setErrorString(errorString); // in QIODevice
}
Example #6
0
	DataPin* Block::createDataPin(char* name, uint8 dir, uint32 bufsz,
		uint32 bufco, int32 queuesz)
	{
		DataPin* dp = NULL;
		char tmp[4096];
		int32 ret = 0;

		dp = new DataPin();
		if (!dp)
			return NULL;

		ret = dp->init(this,		  // pointer to this block
		 name,  		// pin's name
		 dir,   		// direction (one of INPUT or OUTPUT)
		 bufsz, 		// preferred buffer size
		 bufco, 		// preferred buffers count
		 queuesz		// pin's input queue size (no. of elements)
		);
		if (ret == FAILURE) {
			delete dp; return NULL;
		}

		switch (dir) {
		case Pin::DIR_INPUT:
			ret = _idp.pput(dp->getName(), (char *) dp);
			if (ret != SUCCESS) {
				snprintf(tmp, sizeof(tmp),
					"Cannot add input pin \"%s\" to pins table (ret = %d)",
					name, ret);
				setErrorString(tmp);

				// free resources
				delete dp;

				// fail
				return NULL;
			}
			break;
		case Pin::DIR_OUTPUT:
			ret = _odp.pput(dp->getName(), (char *) dp);
			if (ret != SUCCESS) {
				snprintf(tmp, sizeof(tmp),
					"Cannot add output pin \"%s\" to pins table (ret = %d)",
					name, ret);
				setErrorString(tmp);

				// free resources 
				delete dp;

				// fail
				return NULL;
			}
			break;
		case Pin::DIR_IO:
			setErrorString("Data pin cannot be bidirectional");

			// free resources
			delete dp;

			// fail 
			return NULL;
		}

		// ok
		return dp;
	}
bool MIPAudioTrackOutput::push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg)
{
	if (!(pMsg->getMessageType() == MIPMESSAGE_TYPE_AUDIO_RAW && 
		pMsg->getMessageSubtype() == MIPRAWAUDIOMESSAGE_TYPE_S16))
	{
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_BADMESSAGE);
		return false;
	}
	
	if (m_pTrack == 0)
	{
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_CLIENTNOTOPEN);
		return false;
	}
	
	MIPAudioMessage *audioMessage = (MIPAudioMessage *)pMsg;
	
	if (audioMessage->getSamplingRate() != m_sampRate)
	{
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_INCOMPATIBLESAMPLINGRATE);
		return false;
	}
	if (audioMessage->getNumberOfChannels() != m_channels)
	{
		setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_INCOMPATIBLECHANNELS);
		return false;
	}
	
	size_t num = audioMessage->getNumberOfFrames() * m_channels;
	size_t offset = 0;

	MIPRaw16bitAudioMessage *audioMessage16bit = (MIPRaw16bitAudioMessage *)pMsg;
	const uint16_t *frames = audioMessage16bit->getFrames();

	m_frameMutex.Lock();
	while (num > 0)
	{
		size_t maxAmount = m_frameArrayLength - m_nextPos;
		size_t amount = (num > maxAmount)?maxAmount:num;
		
		if (m_nextPos <= m_currentPos && m_nextPos + amount > m_currentPos)
		{
			//std::cerr << "Strange error" << std::endl;
			m_nextPos = m_currentPos + m_blockLength;
		}
		
		if (amount != 0)
		{
			size_t i;
			uint16_t *pDest = m_pFrameArray + m_nextPos;
			const uint16_t *pSrc = frames + offset;
			
			memcpy(pDest, pSrc, amount*sizeof(uint16_t));
		}
		
		if (amount != num)
		{
			m_nextPos = 0;
//			std::cerr << "Cycling next pos" << std::endl;
		}
		else
			m_nextPos += amount;
		
		offset += amount;
		num -= amount;
	}
	
	m_distTime += MIPTime(((real_t)audioMessage->getNumberOfFrames())/((real_t)m_sampRate));
	m_frameMutex.Unlock();

	return true;
}
Example #8
0
bool MIPSILKEncoder::init(int samplingRate, MIPTime interval, int targetBitrate, int encoderSamplingRate)
{
	if (m_init)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_ALREADYINIT);
		return false;
	}

	if (!(samplingRate == 8000 || samplingRate == 12000 || samplingRate == 16000 || samplingRate == 24000 ||
              samplingRate == 32000 || samplingRate == 44100 || samplingRate == 48000 ))
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDINPUTSAMPLINGRATE);
		return false;
	}

	if (!(encoderSamplingRate == 8000 || encoderSamplingRate == 12000 || encoderSamplingRate == 16000 ||
	      encoderSamplingRate == 24000 ))
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDENCODERSAMPLINGRATE);
		return false;
	}

	if (targetBitrate < 0)
		targetBitrate = 0;

	/*
	if (targetBitrate < 5000 || targetBitrate > 100000)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDBITRATE);
		return false;
	}
	*/

	int intervalMs = (int)(interval.getValue()*1000.0 + 0.5);

	if (!(intervalMs == 20 || intervalMs == 40 || intervalMs == 60 || intervalMs == 80 || intervalMs == 100 ))
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDINTERVAL);
		return false;
	}

	int frameSize = (samplingRate*intervalMs)/1000;
	int frameSize2 = (int)((double)samplingRate * interval.getValue() + 0.5);

	if (frameSize2 != frameSize)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INVALIDINTERVAL);
		return false;
	}

	int32_t encSize = 0;
	int status = SKP_Silk_SDK_Get_Encoder_Size(&encSize);

	if (status != 0)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_CANTGETENCODERSIZE);
		return false;
	}

	m_pState = new uint8_t[encSize];
	m_pEncoderControlStruct = new SKP_SILK_SDK_EncControlStruct;

	SKP_SILK_SDK_EncControlStruct *pCtrl = (SKP_SILK_SDK_EncControlStruct *)m_pEncoderControlStruct;

	status = SKP_Silk_SDK_InitEncoder(m_pState, pCtrl);
	if (status != 0)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_CANTINITENCODER);
		delete [] m_pState;
		delete pCtrl;
		return false;
	}

	pCtrl->API_sampleRate = samplingRate;
	pCtrl->maxInternalSampleRate = encoderSamplingRate;
	pCtrl->packetSize = frameSize;
	pCtrl->bitRate = targetBitrate;
	pCtrl->packetLossPercentage = 0;
	pCtrl->complexity = 2;
	pCtrl->useInBandFEC = 0;
	pCtrl->useDTX = 0; // TODO: when this is 1, output size can be 0!

	m_inputSamplingRate = samplingRate;
	m_maxInternalSamplingRate = samplingRate;
	m_frameSize = frameSize;
	m_targetBitrate = targetBitrate;

	m_prevIteration = -1;
	m_msgIt = m_messages.begin();
	
	m_init = true;
	
	return true;
}
qint64 OgreNetworkReply::writeData(const char * data, qint64 maxSize)
{
    setErrorString("Unable to write to an Ogre network request.");
    return -1;
}
Example #10
0
bool MmffParameters::read(const std::string &fileName)
{
    // delete old parameters data
    if(d){
        d->deref();
        d = 0;
    }

    // try to load cached parameters
    MmffPlugin *mmffPlugin = static_cast<MmffPlugin *>(chemkit::PluginManager::instance()->plugin("mmff"));
    if(mmffPlugin){
        d = mmffPlugin->parameters(QString::fromStdString(fileName));

        if(d){
            d->ref();
            return true;
        }
    }

    // create new parameters data if we don't have a cached one
    if(!d){
        d = new MmffParametersData;
    }

    QFile file(QString::fromStdString(fileName));
    if(!file.open(QFile::ReadOnly)){
        setErrorString(file.errorString());
        return false;
    }

    m_fileName = fileName;

    // section in file
    enum Section {
        BondStrech,
        EmpiricalBondStrech,
        AngleBend,
        StrechBend,
        DefaultStrechBend,
        OutOfPlaneBending,
        Torsion,
        VanDerWaals,
        Charge,
        PartialCharge,
        End
    };

    // first section is bond strech parameters
    int section = BondStrech;

    while(!file.atEnd()){
        QString line = file.readLine();

        // lines that start with '$' indicate a new section
        if(line.startsWith("$")){
            section++;

            if(section == End){
                break;
            }
        }

        // lines starting with '#' are comments
        else if(line.startsWith("#")){
            continue;
        }

        // read data from line
        else{
            QStringList data = line.split(" ", QString::SkipEmptyParts);
            if(data.isEmpty() || data.size() < 2){
                continue;
            }

            if(section == BondStrech){
                int bondType = data.value(0).toInt();
                int typeA = data.value(1).toInt();
                int typeB = data.value(2).toInt();

                int index = calculateBondStrechIndex(bondType, typeA, typeB);

                MmffBondStrechParameters *parameters = new MmffBondStrechParameters;
                parameters->kb = data.value(3).toDouble();
                parameters->r0 = data.value(4).toDouble();

                d->bondStrechParameters[index] = parameters;
            }
            else if(section == EmpiricalBondStrech){
            }
            else if(section == AngleBend){
                int angleType = data.value(0).toInt();
                int typeA = data.value(1).toInt();
                int typeB = data.value(2).toInt();
                int typeC = data.value(3).toInt();

                int index = calculateAngleBendIndex(angleType, typeA, typeB, typeC);

                MmffAngleBendParameters *parameters = new MmffAngleBendParameters;
                parameters->ka = data.value(4).toDouble();
                parameters->theta0 = data.value(5).toDouble();

                d->angleBendParameters[index] = parameters;
            }
            else if(section == StrechBend){
                int strechBendType = data.value(0).toInt();
                int typeA = data.value(1).toInt();
                int typeB = data.value(2).toInt();
                int typeC = data.value(3).toInt();

                int index = calculateStrechBendIndex(strechBendType, typeA, typeB, typeC);

                MmffStrechBendParameters *parameters = new MmffStrechBendParameters;
                parameters->kba_ijk = data.value(4).toDouble();
                parameters->kba_kji = data.value(5).toDouble();

                d->strechBendParameters[index] = parameters;
            }
            else if(section == DefaultStrechBend){
                MmffDefaultStrechBendParameters *parameters = new MmffDefaultStrechBendParameters;
                parameters->rowA = data.value(0).toInt();
                parameters->rowB = data.value(1).toInt();
                parameters->rowC = data.value(2).toInt();
                parameters->parameters.kba_ijk = data.value(3).toDouble();
                parameters->parameters.kba_kji = data.value(4).toDouble();
                d->defaultStrechBendParameters.append(parameters);
            }
            else if(section == OutOfPlaneBending){
                int typeA = data.value(0).toInt();
                int typeB = data.value(1).toInt();
                int typeC = data.value(2).toInt();
                int typeD = data.value(3).toInt();

                int index = calculateOutOfPlaneBendingIndex(typeA, typeB, typeC, typeD);

                MmffOutOfPlaneBendingParameters *parameters = new MmffOutOfPlaneBendingParameters;
                parameters->koop = data.value(4).toDouble();

                d->outOfPlaneBendingParameters[index] = parameters;
            }
            else if(section == Torsion){
                int torsionType = data.value(0).toInt();
                int typeA = data.value(1).toInt();
                int typeB = data.value(2).toInt();
                int typeC = data.value(3).toInt();
                int typeD = data.value(4).toInt();

                int index = calculateTorsionIndex(torsionType, typeA, typeB, typeC, typeD);

                MmffTorsionParameters *parameters = new MmffTorsionParameters;
                parameters->V1 = data.value(5).toDouble();
                parameters->V2 = data.value(6).toDouble();
                parameters->V3 = data.value(7).toDouble();

                d->torsionParameters[index] = parameters;
            }
            else if(section == VanDerWaals){
                int type = data.value(0).toInt();
                if(type > MaxAtomType)
                    continue;

                MmffVanDerWaalsParameters *parameters = new MmffVanDerWaalsParameters;
                parameters->alpha = data.value(1).toDouble();
                parameters->N = data.value(2).toDouble();
                parameters->A = data.value(3).toDouble();
                parameters->G = data.value(4).toDouble();
                parameters->DA = data.value(5).at(0).toAscii();

                d->vanDerWaalsParameters[type] = parameters;
            }
            else if(section == Charge){
                MmffChargeParameters *parameters = new MmffChargeParameters;
                parameters->bondType = data.value(0).toInt();
                parameters->typeA = data.value(1).toInt();
                parameters->typeB = data.value(2).toInt();
                parameters->bci = data.value(3).toDouble();
                d->chargeParameters.append(parameters);
            }
            else if(section == PartialCharge){
                int type = data.value(1).toInt();
                if(type > MaxAtomType)
                    continue;

                MmffPartialChargeParameters *parameters = new MmffPartialChargeParameters;
                parameters->pbci = data.value(2).toDouble();
                parameters->fcadj = data.value(3).toDouble();

                d->partialChargeParameters[type] = parameters;
            }
        }
    }

    // store parameters in the cache
    if(mmffPlugin){
        mmffPlugin->storeParameters(QString::fromStdString(fileName), d);
    }

    return true;
}
Example #11
0
bool MIPSILKEncoder::push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg)
{
	if (!m_init)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_NOTINIT);
		return false;
	}

	if (iteration != m_prevIteration)
	{
		m_prevIteration = iteration;
		clearMessages();
	}

	if (!(pMsg->getMessageType() == MIPMESSAGE_TYPE_AUDIO_RAW && pMsg->getMessageSubtype() == MIPRAWAUDIOMESSAGE_TYPE_S16 ) )
	{
		setErrorString(MIPSILKENCODER_ERRSTR_BADMESSAGE);
		return false;
	}

	MIPRaw16bitAudioMessage *pAudioMsg = (MIPRaw16bitAudioMessage *)pMsg;

	if (pAudioMsg->getNumberOfChannels() != 1)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_NOTMONO);
		return false;
	}

	if (pAudioMsg->getSamplingRate() != m_inputSamplingRate)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INCOMPATIBLESAMPLINGRATE);
		return false;
	}

	if (pAudioMsg->getNumberOfFrames() != m_frameSize)
	{
		setErrorString(MIPSILKENCODER_ERRSTR_INCOMPATIBLEFRAMESIZE);
		return false;
	}

	const int16_t *pFrames = (const int16_t *)pAudioMsg->getFrames();
	int16_t outSize = m_frameSize*2;
	uint8_t *pOutData = new uint8_t[outSize]; // the input size should be more than adequate

	SKP_SILK_SDK_EncControlStruct *pCtrl = (SKP_SILK_SDK_EncControlStruct *)m_pEncoderControlStruct;

	int status = SKP_Silk_SDK_Encode(m_pState, pCtrl, pFrames, m_frameSize, pOutData, &outSize);
	if (status != 0)
	{
		char str[1024];
		sprintf(str, "Error using SILK encoder (error code %d)", status);
		delete [] pOutData;
		setErrorString(str);
		return false;
	}

	if (outSize == 0)
		std::cerr << "WARNING: MIPSILKEncoder::push -> outSize = 0!" << std::endl;

	// The number of frames is related to the interval by the input sampling rate
	MIPEncodedAudioMessage *pNewMsg = new MIPEncodedAudioMessage(MIPENCODEDAUDIOMESSAGE_TYPE_SILK, m_inputSamplingRate, 1, m_frameSize, pOutData, outSize, true);

	pNewMsg->copyMediaInfoFrom(*pAudioMsg); // copy time and sourceID
	m_messages.push_back(pNewMsg);
		
	m_msgIt = m_messages.begin();

	return true;
}
/*!
    \internal
    Reads and decompresses data from the underlying device.
*/
qint64 QtIOCompressor::readData(char *data, qint64 maxSize)
{
    Q_D(QtIOCompressor);

    if (d->state == QtIOCompressorPrivate::EndOfStream)
        return 0;

    if (d->state == QtIOCompressorPrivate::Error)
        return -1;

    // We are ging to try to fill the data buffer
    d->zlibStream.next_out = reinterpret_cast<ZlibByte *>(data);
    d->zlibStream.avail_out = maxSize;

    int status;
    do {
        // Read data if if the input buffer is empty. There could be data in the buffer
        // from a previous readData call.
        if (d->zlibStream.avail_in == 0) {
            qint64 bytesAvalible = d->device->read(reinterpret_cast<char *>(d->buffer), d->bufferSize);
            d->zlibStream.next_in = d->buffer;
            d->zlibStream.avail_in = bytesAvalible;

            if (bytesAvalible == -1) {
                d->state = QtIOCompressorPrivate::Error;
                setErrorString(QT_TRANSLATE_NOOP("QtIOCompressor", "Error reading data from underlying device: ") + d->device->errorString());
                return -1;
            }

            if (d->state != QtIOCompressorPrivate::InStream) {
                // If we are not in a stream and get 0 bytes, we are probably trying to read from an empty device.
                if(bytesAvalible == 0)
                    return 0;
                else if (bytesAvalible > 0)
                    d->state = QtIOCompressorPrivate::InStream;
            }
        }

        // Decompress.
        status = inflate(&d->zlibStream, Z_SYNC_FLUSH);
        switch (status) {
            case Z_NEED_DICT:
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                d->state = QtIOCompressorPrivate::Error;
                d->setZlibError(QT_TRANSLATE_NOOP("QtIOCompressor", "Internal zlib error when decompressing: "), status);
                return -1;
            case Z_BUF_ERROR: // No more input and zlib can not privide more output - Not an error, we can try to read again when we have more input.
                return 0;
            break;
        }
    // Loop util data buffer is full or we reach the end of the input stream.
    } while (d->zlibStream.avail_out != 0 && status != Z_STREAM_END);

    if (status == Z_STREAM_END) {
        d->state = QtIOCompressorPrivate::EndOfStream;

        // Unget any data left in the read buffer.
        for (int i = d->zlibStream.avail_in;  i >= 0; --i)
            d->device->ungetChar(*reinterpret_cast<char *>(d->zlibStream.next_in + i));
    }

    const ZlibSize outputSize = maxSize - d->zlibStream.avail_out;
    return outputSize;
}
/*!
    Opens the QtIOCompressor in \a mode. Only ReadOnly and WriteOnly is supported.
    This functon will return false if you try to open in other modes.

    If the underlying device is not opened, this function will open it in a suitable mode. If this happens
    the device will also be closed when close() is called.

    If the underlying device is already opened, its openmode must be compatable with \a mode.

    Returns true on success, false on error.

    \sa close()
*/
bool QtIOCompressor::open(OpenMode mode)
{
    Q_D(QtIOCompressor);
    if (isOpen()) {
        qWarning("QtIOCompressor::open: device already open");
        return false;
    }

    // Check for correct mode: ReadOnly xor WriteOnly
    const bool read = (bool)(mode & ReadOnly);
    const bool write = (bool)(mode & WriteOnly);
    const bool both = (read && write);
    const bool neither = !(read || write);
    if (both || neither) {
        qWarning("QtIOCompressor::open: QtIOCompressor can only be opened in the ReadOnly or WriteOnly modes");
        return false;
    }

    // If the underlying device is open, check that is it opened in a compatible mode.
    if (d->device->isOpen()) {
        d->manageDevice = false;
        const OpenMode deviceMode = d->device->openMode();
        if (read && !(deviceMode & ReadOnly)) {
            qWarning("QtIOCompressor::open: underlying device must be open in one of the ReadOnly or WriteOnly modes");
            return false;
        } else if (write && !(deviceMode & WriteOnly)) {
            qWarning("QtIOCompressor::open: underlying device must be open in one of the ReadOnly or WriteOnly modes");
            return false;
        }

    // If the underlying device is closed, open it.
    } else {
        d->manageDevice = true;
        if (d->device->open(mode) == false) {
            setErrorString(QT_TRANSLATE_NOOP("QtIOCompressor", "Error opening underlying device: ") + d->device->errorString());
            return false;
        }
    }

    // Initialize zlib for deflating or inflating.

    // The second argument to inflate/deflateInit2 is the windowBits parameter,
    // which also controls what kind of compression stream headers to use.
    // The default value for this is 15. Passing a value greater than 15
    // enables gzip headers and then subtracts 16 form the windowBits value.
    // (So passing 31 gives gzip headers and 15 windowBits). Passing a negative
    // value selects no headers hand then negates the windowBits argument.
    int windowBits;
    switch (d->streamFormat) {
    case QtIOCompressor::GzipFormat:
        windowBits = 31;
        break;
    case QtIOCompressor::RawZipFormat:
        windowBits = -15;
        break;
    default:
        windowBits = 15;
    }

    int status;
    if (read) {
        d->state = QtIOCompressorPrivate::NotReadFirstByte;
        d->zlibStream.avail_in = 0;
        d->zlibStream.next_in = 0;
        if (d->streamFormat == QtIOCompressor::ZlibFormat) {
            status = inflateInit(&d->zlibStream);
        } else {
            if (checkGzipSupport(zlibVersion()) == false) {
                setErrorString(QT_TRANSLATE_NOOP("QtIOCompressor::open", "The gzip format not supported in this version of zlib."));
                return false;
            }

            status = inflateInit2(&d->zlibStream, windowBits);
        }
    } else {
        d->state = QtIOCompressorPrivate::NoBytesWritten;
        if (d->streamFormat == QtIOCompressor::ZlibFormat)
            status = deflateInit(&d->zlibStream, d->compressionLevel);
        else
            status = deflateInit2(&d->zlibStream, d->compressionLevel, Z_DEFLATED, windowBits, 8, Z_DEFAULT_STRATEGY);
    }

    // Handle error.
    if (status != Z_OK) {
        d->setZlibError(QT_TRANSLATE_NOOP("QtIOCompressor::open", "Internal zlib error: "), status);
        return false;
    }
    return QIODevice::open(mode);
}
bool MIPSamplingRateConverter::push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg)
{
	if (!m_init)
	{
		setErrorString(MIPSAMPLINGRATECONVERTER_ERRSTR_NOTINIT);
		return false;
	}
	
	if (!(pMsg->getMessageType() == MIPMESSAGE_TYPE_AUDIO_RAW && 
		( (pMsg->getMessageSubtype() == MIPRAWAUDIOMESSAGE_TYPE_FLOAT && m_floatSamples) ||
		  (pMsg->getMessageSubtype() == MIPRAWAUDIOMESSAGE_TYPE_S16 && !m_floatSamples) ) ) ) 
	{
		setErrorString(MIPSAMPLINGRATECONVERTER_ERRSTR_BADMESSAGETYPE);
		return false;
	}

	MIPAudioMessage *pAudioMsg = (MIPAudioMessage *)pMsg;
	
	if (pAudioMsg->getNumberOfChannels() != 1 && m_outChannels != pAudioMsg->getNumberOfChannels() && m_outChannels != 1)
	{
		setErrorString(MIPSAMPLINGRATECONVERTER_ERRSTR_CANTHANDLECHANNELS);
		return false;
	}
	
	int numInChannels = pAudioMsg->getNumberOfChannels();
	int numInFrames = pAudioMsg->getNumberOfFrames();
	real_t frameTime = (((real_t)numInFrames)/((real_t)pAudioMsg->getSamplingRate()));
	int numNewFrames = (int)((frameTime * ((real_t)m_outRate))+0.5);
	int numNewSamples = numNewFrames * m_outChannels;
	MIPAudioMessage *pNewMsg = 0;
	
	if (m_floatSamples)
	{
		MIPRawFloatAudioMessage *pFloatAudioMsg = (MIPRawFloatAudioMessage *)pMsg;
		const float *oldFrames = pFloatAudioMsg->getFrames();
		float *newFrames = new float [numNewSamples];
	
		if (!MIPResample<float,float>(oldFrames, numInFrames, numInChannels, newFrames, numNewFrames, m_outChannels))
		{
			setErrorString(MIPSAMPLINGRATECONVERTER_ERRSTR_CANTRESAMPLE);
			return false;
		}
		
		pNewMsg = new MIPRawFloatAudioMessage(m_outRate, m_outChannels, numNewFrames, newFrames, true);
		pNewMsg->copyMediaInfoFrom(*pAudioMsg); // copy time info and source ID
	}
	else // 16 bit signed
	{
		MIPRaw16bitAudioMessage *pIntAudioMsg = (MIPRaw16bitAudioMessage *)pMsg;
		const uint16_t *oldFrames = pIntAudioMsg->getFrames();
		uint16_t *newFrames = new uint16_t [numNewSamples];
	
		if (!MIPResample<int16_t,int32_t>((const int16_t *)oldFrames, numInFrames, numInChannels, (int16_t *)newFrames, numNewFrames, m_outChannels))
		{
			setErrorString(MIPSAMPLINGRATECONVERTER_ERRSTR_CANTRESAMPLE);
			return false;
		}
		
		pNewMsg = new MIPRaw16bitAudioMessage(m_outRate, m_outChannels, numNewFrames, true, MIPRaw16bitAudioMessage::Native, newFrames, true);
		pNewMsg->copyMediaInfoFrom(*pAudioMsg); // copy time info and source ID
	}
	
	if (m_prevIteration != iteration)
	{
		clearMessages();
		m_prevIteration = iteration;
	}
	
	m_messages.push_back(pNewMsg);
	m_msgIt = m_messages.begin();
	
	return true;
}
Example #15
0
/*!
 * \internal
 */
qint64 WebSocket::doWriteFrames(const QByteArray &data, bool isBinary)
{
	const WebSocketProtocol::OpCode firstOpCode = isBinary ? WebSocketProtocol::OC_BINARY : WebSocketProtocol::OC_TEXT;

	int numFrames = data.size() / FRAME_SIZE_IN_BYTES;
	QByteArray tmpData(data);
	tmpData.detach();
	char *payload = tmpData.data();
	quint64 sizeLeft = static_cast<quint64>(data.size()) % FRAME_SIZE_IN_BYTES;
	if (sizeLeft)
	{
		++numFrames;
	}
	if (numFrames == 0)     //catch the case where the payload is zero bytes; in that case, we still need to send a frame
	{
		numFrames = 1;
	}
	quint64 currentPosition = 0;
	qint64 bytesWritten = 0;
	qint64 payloadWritten = 0;
	quint64 bytesLeft = data.size();

	for (int i = 0; i < numFrames; ++i)
	{
		quint32 maskingKey = 0;
		if (m_mustMask)
		{
			maskingKey = generateMaskingKey();
		}

		bool isLastFrame = (i == (numFrames - 1));
		bool isFirstFrame = (i == 0);

		quint64 size = qMin(bytesLeft, FRAME_SIZE_IN_BYTES);
		WebSocketProtocol::OpCode opcode = isFirstFrame ? firstOpCode : WebSocketProtocol::OC_CONTINUE;

		//write header
		bytesWritten += m_pSocket->write(getFrameHeader(opcode, size, maskingKey, isLastFrame));

		//write payload
		if (size > 0)
		{
			char *currentData = payload + currentPosition;
			if (m_mustMask)
			{
				WebSocketProtocol::mask(currentData, size, maskingKey);
			}
			qint64 written = m_pSocket->write(currentData, static_cast<qint64>(size));
			if (written > 0)
			{
				bytesWritten += written;
				payloadWritten += written;
			}
			else
			{
				setErrorString("WebSocket::doWriteFrames: Error writing bytes to socket: " + m_pSocket->errorString());
				qDebug() << errorString();
				m_pSocket->flush();
				Q_EMIT error(QAbstractSocket::NetworkError);
				break;
			}
		}
		currentPosition += size;
		bytesLeft -= size;
	}
	if (payloadWritten != data.size())
	{
		setErrorString("Bytes written " + QString::number(payloadWritten) + " != " + QString::number(data.size()));
		qDebug() << errorString();
		Q_EMIT error(QAbstractSocket::NetworkError);
	}
	return payloadWritten;
}
Example #16
0
void DhQIODevice::DvhsetErrorString(const QString& x1) {
  return setErrorString(x1);
}
Example #17
0
/*!
	\internal
 */
void WebSocket::processHandshake(QTcpSocket *pSocket)
{
	if (pSocket == 0)
	{
		return;
	}

	bool ok = false;
	QString errorDescription;

	const QString regExpStatusLine("^(HTTP/1.1)\\s([0-9]+)\\s(.*)");
	const QRegExp regExp(regExpStatusLine);
	QString statusLine = readLine(pSocket);
	QString httpProtocol;
	int httpStatusCode;
	QString httpStatusMessage;
	if (regExp.indexIn(statusLine) != -1)
	{
		QStringList tokens = regExp.capturedTexts();
		tokens.removeFirst();	//remove the search string
		if (tokens.length() == 3)
		{
			httpProtocol = tokens[0];
			httpStatusCode = tokens[1].toInt();
			httpStatusMessage = tokens[2].trimmed();
			ok = true;
		}
	}
	if (!ok)
	{
		errorDescription = "WebSocket::processHandshake: Invalid statusline in response: " + statusLine;
	}
	else
	{
		QString headerLine = readLine(pSocket);
		QMap<QString, QString> headers;
		while (!headerLine.isEmpty())
		{
			QStringList headerField = headerLine.split(QString(": "), QString::SkipEmptyParts);
			headers.insertMulti(headerField[0], headerField[1]);
			headerLine = readLine(pSocket);
		}

		QString acceptKey = headers.value("Sec-WebSocket-Accept", "");
		QString upgrade = headers.value("Upgrade", "");
		QString connection = headers.value("Connection", "");
		QString extensions = headers.value("Sec-WebSocket-Extensions", "");
		QString protocol = headers.value("Sec-WebSocket-Protocol", "");
		QString version = headers.value("Sec-WebSocket-Version", "");

		if (httpStatusCode == 101)	//HTTP/1.1 101 Switching Protocols
		{
			//TODO: do not check the httpStatusText right now
			ok = !(acceptKey.isEmpty() ||
				   (httpProtocol.toLower() != "http/1.1") ||
				   (upgrade.toLower() != "websocket") ||
				   (connection.toLower() != "upgrade"));
			if (ok)
			{
				QString accept = calculateAcceptKey(m_key);
				ok = (accept == acceptKey);
				if (!ok)
				{
					errorDescription = "WebSocket::processHandshake: Accept-Key received from server " + acceptKey + " does not match the client key " + accept;
				}
			}
			else
			{
				errorDescription = "WebSocket::processHandshake: Invalid statusline in response: " + statusLine;
			}
		}
		else if (httpStatusCode == 400)	//HTTP/1.1 400 Bad Request
		{
			if (!version.isEmpty())
			{
				QStringList versions = version.split(", ", QString::SkipEmptyParts);
				if (!versions.contains("13"))
				{
					//if needed to switch protocol version, then we are finished here
					//because we cannot handle other protocols than the RFC one (v13)
					errorDescription = "WebSocket::processHandshake: Server requests a version that we don't support: " + versions.join(", ");
					ok = false;
				}
				else
				{
					//we tried v13, but something different went wrong
					errorDescription = "WebSocket::processHandshake: Unknown error condition encountered. Aborting connection.";
					ok = false;
				}
			}
		}
		else
		{
			errorDescription = "WebSocket::processHandshake: Unhandled http status code " + QString::number(httpStatusCode);
			ok = false;
		}

		if (!ok)
		{
			qDebug() << errorDescription;
			setErrorString(errorDescription);
			Q_EMIT error(QAbstractSocket::ConnectionRefusedError);
		}
		else
		{
			//handshake succeeded
			setSocketState(QAbstractSocket::ConnectedState);
			Q_EMIT connected();
		}
	}
}
bool MIPAudioDistanceFade::push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg)
{
	if (!m_init)
	{
		setErrorString(MIPAUDIODISTANCEFADE_ERRSTR_NOTINIT);
		return false;
	}

	if (iteration != m_curIteration)
	{
		std::list<MIPRawFloatAudioMessage *>::iterator it;

		for (it = m_messages.begin() ; it != m_messages.end() ; it++)
			delete (*it);
		m_messages.clear();

		m_msgIt = m_messages.begin();

		m_curIteration = iteration;
	}
	
	expirePositionalInfo();

	if (!(pMsg->getMessageType() == MIPMESSAGE_TYPE_AUDIO_RAW && pMsg->getMessageSubtype() == MIPRAWAUDIOMESSAGE_TYPE_FLOAT))
	{
		setErrorString(MIPAUDIODISTANCEFADE_ERRSTR_BADMESSAGE);
		return false;
	}

	
	MIPRawFloatAudioMessage *pFloatMsg = (MIPRawFloatAudioMessage *)pMsg;
	uint64_t sourceID = pFloatMsg->getSourceID();
	real_t azimuth, elevation, distance;

	if (!getPositionalInfo(sourceID, &azimuth, &elevation, &distance))
	{
		// No source with this ID found, ignore it
		return true;
	}
	
	if (distance > m_cutOffDistance)
	{
		// Source is too far away, ignore it
		return true;
	}

	int numSamples = pFloatMsg->getNumberOfFrames()*pFloatMsg->getNumberOfChannels();
	const float *pOldSamples = pFloatMsg->getFrames();
	float *pNewSamples = new float[numSamples];
	float scaleFactor = (float)(1.0/(1.0+distance));

	for (int i = 0 ; i < numSamples ; i++)
		pNewSamples[i] = pOldSamples[i]*scaleFactor;

	MIPRawFloatAudioMessage *pNewMsg = new MIPRawFloatAudioMessage(pFloatMsg->getSamplingRate(), pFloatMsg->getNumberOfChannels(), pFloatMsg->getNumberOfFrames(), pNewSamples, true);
	pNewMsg->copyMediaInfoFrom(*pFloatMsg);

	m_messages.push_back(pNewMsg);
	m_msgIt = m_messages.begin();
	
	return true;
}
Example #19
0
/*!
    \internal
*/
bool QSystemSemaphorePrivate::modifySemaphore(int count)
{
#ifndef QT_POSIX_IPC
    if (-1 == handle())
        return false;

    struct sembuf operation;
    operation.sem_num = 0;
    operation.sem_op = count;
    operation.sem_flg = SEM_UNDO;

    register int res;
    EINTR_LOOP(res, semop(semaphore, &operation, 1));
    if (-1 == res) {
        // If the semaphore was removed be nice and create it and then modifySemaphore again
        if (errno == EINVAL || errno == EIDRM) {
            semaphore = -1;
            cleanHandle();
            handle();
            return modifySemaphore(count);
        }
        setErrorString(QLatin1String("QSystemSemaphore::modifySemaphore"));
#ifdef QSYSTEMSEMAPHORE_DEBUG
        qDebug() << QLatin1String("QSystemSemaphore::modify failed") << count << semctl(semaphore, 0, GETVAL) << errno << EIDRM << EINVAL;
#endif
        return false;
    }
#else
    if (!handle())
        return false;

    if (count > 0) {
        int cnt = count;
        do {
            if (sem_post(semaphore) == -1) {
                setErrorString(QLatin1String("QSystemSemaphore::modifySemaphore (sem_post)"));
#ifdef QSYSTEMSEMAPHORE_DEBUG
                qDebug() << QLatin1String("QSystemSemaphore::modify sem_post failed") << count << errno;
#endif
                // rollback changes to preserve the SysV semaphore behavior
                for ( ; cnt < count; ++cnt) {
                    register int res;
                    EINTR_LOOP(res, sem_wait(semaphore));
                }
                return false;
            }
            --cnt;
        } while (cnt > 0);
    } else {
        register int res;
        EINTR_LOOP(res, sem_wait(semaphore));
        if (res == -1) {
            // If the semaphore was removed be nice and create it and then modifySemaphore again
            if (errno == EINVAL || errno == EIDRM) {
                semaphore = SEM_FAILED;
                return modifySemaphore(count);
            }
            setErrorString(QLatin1String("QSystemSemaphore::modifySemaphore (sem_wait)"));
#ifdef QSYSTEMSEMAPHORE_DEBUG
            qDebug() << QLatin1String("QSystemSemaphore::modify sem_wait failed") << count << errno;
#endif
            return false;
        }
    }
#endif // QT_POSIX_IPC

    return true;
}
Example #20
0
bool MIPOSSInputOutput::push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg)
{
	if (m_device == -1)
	{
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_NOTOPENED);
		return false;
	}
	
	if ((m_accessMode == ReadOnly || m_accessMode == ReadWrite) && 
	    pMsg->getMessageType() == MIPMESSAGE_TYPE_SYSTEM && 
	    pMsg->getMessageSubtype() == MIPSYSTEMMESSAGE_TYPE_WAITTIME)
	{
		m_inputFrameMutex.Lock();
		m_sigWait.clearSignalBuffers();
		bool gotFrame = m_gotLastInput;
		m_inputFrameMutex.Unlock();
		
		if (gotFrame) // already got the current frame in the buffer, wait for new one
			m_sigWait.waitForSignal();

		m_inputFrameMutex.Lock();
		memcpy(m_pMsgBuffer, m_pLastInputCopy, m_blockLength*sizeof(uint16_t));
		m_gotLastInput = true;
		m_pMsg->setTime(m_sampleInstant);
		m_inputFrameMutex.Unlock();
		
		m_gotMsg = false;
	}
	else if ((m_accessMode == WriteOnly || m_accessMode == ReadWrite) && 
	         pMsg->getMessageType() == MIPMESSAGE_TYPE_AUDIO_RAW &&
		 pMsg->getMessageSubtype() == m_audioSubtype)
	{
		// Write block

		if (!m_pOutputThread->IsRunning())
		{
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_OUTPUTTHREADNOTRUNNING);
			return false;
		}
	
		MIPRaw16bitAudioMessage *audioMessage = (MIPRaw16bitAudioMessage *)pMsg;
	
		if (audioMessage->getSamplingRate() != m_sampRate)
		{
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_INCOMPATIBLESAMPLINGRATE);
			return false;
		}
		if (audioMessage->getNumberOfChannels() != m_channels)
		{
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_INCOMPATIBLECHANNELS);
			return false;
		}

		size_t num = audioMessage->getNumberOfFrames() * m_channels;
		size_t offset = 0;
		const uint16_t *frames = audioMessage->getFrames();

		m_outputFrameMutex.Lock();
		//std::cerr << "Adding at position " << m_nextOutputPos << std::endl;
		while (num > 0)
		{
			size_t maxAmount = m_bufferLength - m_nextOutputPos;
			size_t amount = (num > maxAmount)?maxAmount:num;
		
			if (m_nextOutputPos <= m_curOutputPos && m_nextOutputPos + amount > m_curOutputPos)
			{
//				std::cerr << "Strange error" << std::endl;
				m_nextOutputPos = m_curOutputPos + m_blockLength;
			}
		
			if (amount != 0)
				memcpy(m_pOutputBuffer + m_nextOutputPos, frames + offset, amount*sizeof(uint16_t));

			if (amount != num)
			{
				m_nextOutputPos = 0;
//				std::cerr << "Cycling next output pos" << std::endl;
			}
			else
				m_nextOutputPos += amount;
		
			offset += amount;
			num -= amount;
		}
		m_outputDistTime += MIPTime(((real_t)audioMessage->getNumberOfFrames())/((real_t)m_sampRate));
		m_outputFrameMutex.Unlock();
	}
	else
	{
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_BADMESSAGE);
		return false;
	}
	return true;
}
Example #21
0
bool MIPAudioTrackOutput::pull(const MIPComponentChain &chain, int64_t iteration, MIPMessage **pMsg)
{
	setErrorString(MIPAUDIOTRACKOUTPUT_ERRSTR_PULLNOTIMPLEMENTED);
	return false;
}
Example #22
0
bool MIPOSSInputOutput::open(int sampRate, int channels, MIPTime interval, AccessMode accessMode, 
                             const MIPOSSInputOutputParams *pParams)
{
	if (m_device != -1)
	{
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_ALREADYOPENED);
		return false;
	}
	
	if (!(channels == 1 || channels == 2))
	{
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_UNSUPPORTEDCHANNELS);
		return false;
	}

	MIPOSSInputOutputParams defaultParams;
	const MIPOSSInputOutputParams *pIOParams;

	if (pParams)
		pIOParams = pParams;
	else
		pIOParams = &defaultParams;

	std::string devName = pIOParams->getDeviceName();
	
	if (accessMode == ReadOnly)
		m_device = ::open(devName.c_str(),O_RDONLY|O_NONBLOCK);
	else if (accessMode == WriteOnly)
		m_device = ::open(devName.c_str(),O_WRONLY|O_NONBLOCK);
	else
		m_device = ::open(devName.c_str(),O_RDWR|O_NONBLOCK);
	
	if (m_device < 0)
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTOPENDEVICE);
		return false;
	}

	// Now that we've opened the file, we can set the blocking
	// mode again
	int flags = fcntl(m_device,F_GETFL);
	if (flags < 0)
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTGETFLAGS);
		return false;
	}
	flags &= ~O_NONBLOCK; // disable non-blocking flags
	if (fcntl(m_device,F_SETFL,flags) < 0)
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTSETFLAGS);
		return false;
	}

	int val;
	
	real_t bytesPerSecond = 2.0*(real_t)sampRate; // 16 bit samples

	if (channels == 2)
		bytesPerSecond *= 2.0;

	real_t ossBufTime = pIOParams->getOSSBufferSize().getValue();
	uint16_t ossFragments = pIOParams->getOSSFragments();
	
	
	if (ossBufTime < 0.001)
		ossBufTime = 0.001;
	if (ossBufTime > 1.000)
		ossBufTime = 1.000;

	if (ossFragments < 2)
		ossFragments = 2;
	if (ossFragments > 256)
		ossFragments = 256;
		
	// get amount of bytes in requested milliseconds
	
	real_t numBytes = ossBufTime*bytesPerSecond;
	int shiftNum = (int)(log(numBytes)/log(2)+0.5);
	
	if (shiftNum > 16)
		shiftNum = 16;
	else if (shiftNum < 8)
		shiftNum = 8;

	// set internal dma block size and number of fragments: this should
	// correspond to something like 42 milliseconds
	val = shiftNum | ((uint32_t)ossFragments<<16);
	if (ioctl(m_device,SNDCTL_DSP_SETFRAGMENT,&val) < 0)
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTSETFRAGMENTS);
		return false;
	}

	if (accessMode == ReadWrite)
	{
		// check if full duplex is supported
		val = 0;
		if (ioctl(m_device,SNDCTL_DSP_GETCAPS,&val) < 0)
		{
			::close(m_device); 
			m_device = -1;
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTGETCAPABILITIES);
			return false;
		}
		if (!(val&DSP_CAP_DUPLEX))
		{
			::close(m_device); 
			m_device = -1;
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_NOFULLDUPLEX);
			return false;
		}
	}

	// check the supported sample encodings

	val = 0;
	if (ioctl(m_device,SNDCTL_DSP_GETFMTS,&val) < 0)
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTGETSUPPORTEDENCODINGS);
		return false;
	}

	if (val&AFMT_S16_LE)
	{
		m_audioSubtype = MIPRAWAUDIOMESSAGE_TYPE_S16LE;
		m_isSigned = true;
	
		val = AFMT_S16_LE;
		if (ioctl(m_device,SNDCTL_DSP_SETFMT,&val) < 0)
		{
			::close(m_device); 
			m_device = -1;
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTSETENCODING);
			return false;
		}
	}
	else if (val&AFMT_U16_LE)
	{
		m_audioSubtype = MIPRAWAUDIOMESSAGE_TYPE_U16LE;
		m_isSigned = false;
	
		val = AFMT_U16_LE;
		if (ioctl(m_device,SNDCTL_DSP_SETFMT,&val) < 0)
		{
			::close(m_device); 
			m_device = -1;
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTSETENCODING);
			return false;
		}
	}
	else
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_NOSUPPORTEDENCODING);
		return false;
	}

	// set to stereo if required
	val = channels;
	if (ioctl(m_device,SNDCTL_DSP_CHANNELS,&val) < 0)
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTSETCHANNELS);
		return false;
	}

	if (val != channels)
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTSETCHANNELS);
		return false;
	}
	
	// set sampling rate
	bool exactRate = pIOParams->useExactRate();
	int realSamplingRate = sampRate;
	if (ioctl(m_device,SNDCTL_DSP_SPEED,&realSamplingRate) < 0)
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTSETSAMPLINGRATE);
		return false;
	}

	if (exactRate && realSamplingRate != sampRate)
	{
		::close(m_device); 
		m_device = -1;

		char rateStr[256];
		
		MIP_SNPRINTF(rateStr, 255, "%d",realSamplingRate);
		setErrorString(std::string(MIPOSSINPUTOUTPUT_ERRSTR_CANTSETEXACTRATE)+std::string(rateStr));
		return false;
	}

	m_sampRate = realSamplingRate;

	// prepare buffers

	MIPTime bufferTime = pIOParams->getBufferTime();
	
	m_bufferLength = ((size_t)(bufferTime.getValue() * ((real_t)m_sampRate) + 0.5)) * channels;
	m_blockFrames = (size_t)(interval.getValue()*((real_t)m_sampRate) + 0.5);
	m_blockLength = m_blockFrames * channels;

	if (m_blockLength > m_bufferLength/4)
	{
		::close(m_device); 
		m_device = -1;
		setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_BUFFERTOOSMALL);
		return false;
	}

	size_t num = (size_t)(((real_t)m_bufferLength)/((real_t)m_blockLength)+0.5);
	
	m_bufferLength = m_blockLength * num;
	
	m_pInputBuffer = 0;
	m_pLastInputCopy = 0;
	m_pMsgBuffer = 0;
	m_pMsg = 0;
	m_pOutputBuffer = 0;
	m_pInputThread = 0;
	m_pOutputThread = 0;
	
	m_accessMode = accessMode;
	m_channels = channels;

	m_curOutputPos = 0;
	m_nextOutputPos = m_blockLength;
	m_outputDistTime = interval;
	m_blockTime = interval;

	uint16_t initVal;

	if (!m_isSigned)
	{
#ifndef MIPCONFIG_BIGENDIAN
		initVal = 0x8000;
#else
		initVal = 0x0080;
#endif // MIPCONFIG_BIGENDIAN
	}
	else
		initVal = 0;
	
	if (accessMode == ReadOnly || accessMode == ReadWrite)
	{
		if (!m_sigWait.init())
		{
			::close(m_device);
			m_device = -1;
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTINITSIGWAIT);
			return false;
		}
		
		m_pInputBuffer = new uint16_t [m_blockLength];
		m_pLastInputCopy = new uint16_t [m_blockLength];
		m_pMsgBuffer = new uint16_t [m_blockLength];
		for (size_t i = 0 ; i < m_blockLength ; i++)
		{
			m_pInputBuffer[i] = initVal;
			m_pLastInputCopy[i] = initVal;
			m_pMsgBuffer[i] = initVal;
		}
		m_gotLastInput = false;
		m_pMsg = new MIPRaw16bitAudioMessage(m_sampRate, m_channels, m_blockFrames, m_isSigned, MIPRaw16bitAudioMessage::LittleEndian, m_pMsgBuffer, false);
		
		m_pInputThread = new InputThread(*this);
		if (m_pInputThread->Start() < 0)
		{
			::close(m_device); 
			m_device = -1;
			delete [] m_pInputBuffer;
			delete [] m_pLastInputCopy;
			m_sigWait.destroy();
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTSTARTINPUTTHREAD);
			return false;
		}
	}

	if (accessMode == WriteOnly || accessMode == ReadWrite)
	{
		m_pOutputBuffer = new uint16_t [m_bufferLength];
		for (size_t i = 0 ; i < m_bufferLength ; i++)
			m_pOutputBuffer[i] = initVal;

		m_pOutputThread = new OutputThread(*this);
		if (m_pOutputThread->Start() < 0)
		{
			delete [] m_pOutputBuffer;
			if (m_pInputThread)
				delete m_pInputThread;
			if (m_pInputBuffer)
				delete [] m_pInputBuffer;
			if (m_pLastInputCopy)
				delete [] m_pLastInputCopy;
			if (m_pMsgBuffer)
				delete [] m_pMsgBuffer;
			if (m_pMsg)
				delete m_pMsg;
			
			::close(m_device); 
			m_device = -1;
			setErrorString(MIPOSSINPUTOUTPUT_ERRSTR_CANTSTARTOUTPUTTHREAD);
			return false;
		}
	}	

	return true;
}
Example #23
0
	void AudioCallDevice::handleWriteError (const QString& errStr)
	{
		setErrorString (errStr);
	}
bool VirtualSerialDevice::open(OpenMode mode)
{
    Q_ASSERT(QThread::currentThread() == thread());
    if (isOpen()) return true;

    d->portHandle = CreateFileA(windowsPortName(portName).toAscii(), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
    if (d->portHandle == INVALID_HANDLE_VALUE) {
        setErrorString(tr("The port %1 could not be opened: %2").
                       arg(portName, winErrorMessage(GetLastError())));
        return false;
    }

    DCB commState;
    memset(&commState, 0, sizeof(DCB));
    commState.DCBlength = sizeof(DCB);
    bool ok = GetCommState(d->portHandle, &commState);
    if (ok) {
        commState.BaudRate = CBR_115200;
        commState.fBinary = TRUE;
        commState.fParity = FALSE;
        commState.fOutxCtsFlow = FALSE;
        commState.fOutxDsrFlow = FALSE;
        commState.fInX = FALSE;
        commState.fOutX = FALSE;
        commState.fNull = FALSE;
        commState.fAbortOnError = FALSE;
        commState.fDsrSensitivity = FALSE;
        commState.fDtrControl = DTR_CONTROL_DISABLE;
        commState.ByteSize = 8;
        commState.Parity = NOPARITY;
        commState.StopBits = ONESTOPBIT;
        ok = SetCommState(d->portHandle, &commState);
    }
    if (!ok) {
        qWarning("%s setting comm state", qPrintable(winErrorMessage(GetLastError())));
    }

    // http://msdn.microsoft.com/en-us/library/aa363190(v=vs.85).aspx says this means
    // "the read operation is to return immediately with the bytes that have already been received, even if no bytes have been received"
    COMMTIMEOUTS timeouts;
    timeouts.ReadIntervalTimeout = MAXDWORD;
    timeouts.ReadTotalTimeoutMultiplier = 0;
    timeouts.ReadTotalTimeoutConstant = 0;
    timeouts.WriteTotalTimeoutMultiplier = 0;
    timeouts.WriteTotalTimeoutConstant = 0;
    SetCommTimeouts(d->portHandle, &timeouts);

    d->writeOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    d->writeCompleteNotifier = new QWinEventNotifier(d->writeOverlapped.hEvent, this);
    connect(d->writeCompleteNotifier, SIGNAL(activated(HANDLE)), this, SLOT(writeCompleted()));

    // This is how we implement readyRead notifications
    d->commEventOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    d->commEventNotifier = new QWinEventNotifier(d->commEventOverlapped.hEvent, this);
    connect(d->commEventNotifier, SIGNAL(activated(HANDLE)), this, SLOT(commEventOccurred()));

    if (!SetCommMask(d->portHandle, EV_RXCHAR)) {
        // What to do?
        qWarning("%s: Could not set comm mask, err=%d", Q_FUNC_INFO, (int)GetLastError());
    }
    bool result = WaitCommEvent(d->portHandle, &d->commEventMask, &d->commEventOverlapped);
    Q_ASSERT(result == false); // Can't see how it would make sense to be anything else...
    (void)result; // For release build
    if (GetLastError() != ERROR_IO_PENDING) {
        setErrorString(tr("An error occurred while waiting for read notifications from %1: %2").
                       arg(portName, winErrorMessage(GetLastError())));
        close();
        return false;
    }

    ok = QIODevice::open(mode);
    if (!ok) close();
    return ok;
}
/*!
    \internal

    Setup unix_key
 */
key_t QSystemSemaphorePrivate::handle(QSystemSemaphore::AccessMode mode)
{
    if (key.isEmpty()){
        errorString = QCoreApplication::tr("%1: key is empty", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle:"));
        error = QSystemSemaphore::KeyError;
        return -1;
    }

    // ftok requires that an actual file exists somewhere
    if (-1 != unix_key)
        return unix_key;

    // Create the file needed for ftok
    int built = QSharedMemoryPrivate::createUnixKeyFile(fileName);
    if (-1 == built) {
        errorString = QCoreApplication::tr("%1: unable to make key", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle:"));
        error = QSystemSemaphore::KeyError;
        return -1;
    }
    createdFile = (1 == built);

    // Get the unix key for the created file
    unix_key = ftok(QFile::encodeName(fileName).constData(), 'Q');
    if (-1 == unix_key) {
        errorString = QCoreApplication::tr("%1: ftok failed", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle:"));
        error = QSystemSemaphore::KeyError;
        return -1;
    }

    // Get semaphore
    semaphore = semget(unix_key, 1, 0666 | IPC_CREAT | IPC_EXCL);
    if (-1 == semaphore) {
        if (errno == EEXIST)
            semaphore = semget(unix_key, 1, 0666 | IPC_CREAT);
        if (-1 == semaphore) {
            setErrorString(QLatin1String("QSystemSemaphore::handle"));
            cleanHandle();
            return -1;
        }
    } else {
        createdSemaphore = true;
        // Force cleanup of file, it is possible that it can be left over from a crash
        createdFile = true;
    }

    if (mode == QSystemSemaphore::Create) {
        createdSemaphore = true;
        createdFile = true;
    }

    // Created semaphore so initialize its value.
    if (createdSemaphore && initialValue >= 0) {
        qt_semun init_op;
        init_op.val = initialValue;
        if (-1 == semctl(semaphore, 0, SETVAL, init_op)) {
            setErrorString(QLatin1String("QSystemSemaphore::handle"));
            cleanHandle();
            return -1;
        }
    }

    return unix_key;
}
bool SymmetricCipherStream::readBlock()
{
    QByteArray newData;

    if (m_bufferFilling) {
        newData.resize(m_cipher->blockSize() - m_buffer.size());
    }
    else {
        m_buffer.clear();
        newData.resize(m_cipher->blockSize());
    }

    int readResult = m_baseDevice->read(newData.data(), newData.size());

    if (readResult == -1) {
        m_error = true;
        setErrorString(m_baseDevice->errorString());
        return false;
    }
    else {
        m_buffer.append(newData.left(readResult));
    }

    if (m_buffer.size() != m_cipher->blockSize()) {
        m_bufferFilling = true;
        return false;
    }
    else {
        if (!m_cipher->processInPlace(m_buffer)) {
            m_error = true;
            setErrorString(m_cipher->errorString());
            return false;
        }
        m_bufferPos = 0;
        m_bufferFilling = false;

        if (m_baseDevice->atEnd()) {
            // PKCS7 padding
            quint8 padLength = m_buffer.at(m_buffer.size() - 1);

            if (padLength == m_cipher->blockSize()) {
                Q_ASSERT(m_buffer == QByteArray(m_cipher->blockSize(), m_cipher->blockSize()));
                // full block with just padding: discard
                m_buffer.clear();
                return false;
            }
            else if (padLength > m_cipher->blockSize()) {
                // invalid padding
                m_error = true;
                setErrorString("Invalid padding.");
                return false;
            }
            else {
                Q_ASSERT(m_buffer.right(padLength) == QByteArray(padLength, padLength));
                // resize buffer to strip padding
                m_buffer.resize(m_cipher->blockSize() - padLength);
                return true;
            }
        }
        else {
            return true;
        }
    }
}
Example #27
0
void QQmlWebSocket::onError(QAbstractSocket::SocketError error)
{
    Q_UNUSED(error)
    setErrorString(m_webSocket->errorString());
    setStatus(Error);
}
Example #28
0
bool BabelFileFormat::read(std::istream &input, chemkit::MoleculeFile *file)
{
    // get input format to use
    std::string format = option("format").toString();
    if(format.empty()){
        setErrorString("No format set for Babel conversion.");
        return false;
    }

    // setup babel arguments
    QStringList arguments;
    arguments.append(QString("-i") + format.c_str());
    arguments.append("-");
    arguments.append("-ocml");
    arguments.append("-");

    // create and start the babel process
    QProcess babel;
    babel.start("babel", arguments);
    if(!babel.waitForStarted()){
        setErrorString("Failed to start Babel process.");
        return false;
    }

    // write input data to babel via stdin
    while(!input.eof()){
        char buffer[1024];
        input.read(buffer, sizeof(buffer));
        babel.write(buffer, input.gcount());
    }

    babel.closeWriteChannel();

    // wait until the babel process is finished
    if(!babel.waitForFinished()){
        setErrorString("Babel process never finished.");
        return false;
    }

    // check babel's exit status
    if(babel.exitCode() != QProcess::NormalExit){
        setErrorString("Babel process crashed.");
        return false;
    }

    // read output data to string buffer
    std::stringstream buffer;
    buffer << babel.readAll().constData();

    // parse cml output file
    chemkit::MoleculeFile outputFile;
    outputFile.setFormat("cml");
    bool ok = outputFile.read(buffer);
    if(!ok){
        setErrorString("Failed to parse Babel's CML output: " + outputFile.errorString());
        return false;
    }

    // add molecules to file
    foreach(const boost::shared_ptr<chemkit::Molecule> &molecule, outputFile.molecules()){
        file->addMolecule(molecule);
    }

    return true;
}
Example #29
0
void LCDDisplay::refresh()
{
	char blockNumber1[1]={128};//first character of the display
	char playbackOutputString[1]={0};//initialise the playback output string as NULL
	char playIcon[1]={62}; //ASCII value of closest symbol to play icon
	char pauseIcon[1]={4}; //ASCII value of closest symbol to pause icon
	char rewindIcon[1]={127}; //ASCII value of closest symbol to rewind icon
	char fForwardIcon[1]={126}; //ASCII value of closest symbol to fast forward icon
	char *playbackString; //char pointer for the playback String
	char *trackInfoString; //char pointer for the track Info String
	char *menuString; //char pointer for the menu String
	char *errorString; //char pointer for the error String
	
	struct timeval currentTime; // contains the struct needed for gettimeofday to function

	gettimeofday(&currentTime,NULL);//saves the current time in seconds that refresh was called
	//if the last time the function ran is half a second more than the current time:
	if ((((blocks[0].lastTime.tv_sec*1000000)+blocks[0].lastTime.tv_usec)+500000) < 
	    ((currentTime.tv_sec*1000000)+currentTime.tv_usec)) {
		setPlaybackDirty(true); // set the playback dirty flag

	}
	//if the playback region is dirty and the string does not contain a NULL:
	if (playbackIsDirty() && getPlaybackString(&playbackString) != NULL) {
		std::cout << "playback Button Pressed\n";
		int tokenSize = strlen(playbackString);
      		//Based on the letter passed by the playback String enter a following case:
		switch(*playbackString){
		case 'p':
                        //copy the ASCII value into the playback output String
			strncpy(playbackOutputString,playIcon,8);
			break;
		case 'w':
			//copy the ASCII value into the playback output String
			strncpy(playbackOutputString,pauseIcon,8);
			break;
		case 'f':
			//copy the ASCII value into the playback output String
			strncpy(playbackOutputString,fForwardIcon,8);
			break;
		case 'r':
			//copy the ASCII value into the playback output String
			strncpy(playbackOutputString,rewindIcon,8);
			break;
		}
		
		write(displayDevice, &displayOptionMode, 1);//enter the option mode for the device
		write(displayDevice, &blockNumber1, 1);//set the device to begin writing to block 1
		//write the currrent contents of the playback string to the display
		write(displayDevice, playbackOutputString, 1);
		delete playbackString; //delete the contents of the playback String
		setPlaybackDirty(false); //set the playback region flag to clean
	}
	//if the track info region is dirty:
	if (trackInfoIsDirty()==true){
		blocks[1].scrollPosition=0;//set the scroll position to the first character of the region
	}
	//if the region is not dirty wait until half a second has passed and make the region dirty.
	else if ((((blocks[1].lastTime.tv_sec*1000000)+blocks[1].lastTime.tv_usec)+500000) < 
		 ((currentTime.tv_sec*1000000)+currentTime.tv_usec)) {
		setTrackInfoDirty(true);//Set the region flag to dirty
	}
	// if the track info region is dirty and the track info string does not contain NULL :
	if (trackInfoIsDirty() && getTrackInfoString(&trackInfoString) != NULL) {
		//call the write block function passing the track info string and the block number 1
		writeBlock(1,trackInfoString); 
		delete trackInfoString; // delete the track info string
		setTrackInfoDirty(false);  // set the track info region flag to clean
	}
	//if the menu region is dirty
	if (menuIsDirty()==true){
		blocks[2].scrollPosition=0;//set the scroll position to 0
	}
	//if the region is not dirty wait until half a second has passed and make the region dirty
	else if ((((blocks[2].lastTime.tv_sec*1000000)+blocks[2].lastTime.tv_usec)+500000) < 
		 ((currentTime.tv_sec*1000000)+currentTime.tv_usec)) {
		setMenuDirty(true);//Set the region flag to dirty
	}

	//if the menu region is dirt and the menuString doesnt contain NULL
	if (menuIsDirty() && getMenuString(&menuString) != NULL) {
		//call the write block function passing the menu string and the block number 2
		writeBlock(2,menuString);
		delete menuString;//delete the menu String
		setMenuDirty(false);  // set the menu region flag to clean
	}

	// if the error String is not NULL :
	if (getErrorString(&errorString) != NULL) {
		//call the write block function passing the Error string and the block number 3
		writeBlock(3,errorString);
		delete errorString; // delete the error String
		setErrorString(NULL); // set the Error String to NULL
	}
}
bool MIPDirectShowCapture::open(int width, int height, real_t frameRate, int deviceNumber)
{
	if (m_pGraph != 0)
	{
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_ALREADYOPEN);
		return false;
	}

	if (!initCaptureGraphBuilder())
		return false;

	if (!getCaptureDevice(deviceNumber))
	{
		clearNonZero();
		return false;
	}

	std::list<GUID> guids;
	std::list<GUID>::const_iterator guidIt;

	if (!listGUIDS(guids))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTLISTGUIDS);
		return false;
	}

	bool haveI420 = false;
	bool haveYUY2 = false;

	for (guidIt = guids.begin() ; guidIt != guids.end() ; guidIt++)
	{
		if (*guidIt == EMIP_MEDIASUBTYPE_I420)
			haveI420 = true;
		if (*guidIt == MEDIASUBTYPE_YUY2)
			haveYUY2 = true;
	}

	if (haveI420)
	{
		//std::cout << "Trying I420" << std::endl;		
		m_selectedGuid = EMIP_MEDIASUBTYPE_I420;
		m_subType = MIPRAWVIDEOMESSAGE_TYPE_YUV420P;
	}
	else if (haveYUY2)
	{
		//std::cout << "Trying YUY2" << std::endl;		
		m_selectedGuid = MEDIASUBTYPE_YUY2;
		m_subType = MIPRAWVIDEOMESSAGE_TYPE_YUYV;
	}
	else
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTSELECTYUV420PORYUY2);
		return false;
	}

	HRESULT hr;

	hr = CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter,(void **)(&m_pNullRenderer));
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTCREATENULLRENDERER);
		return false;
	}
	
	hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter,(void **)(&m_pSampGrabFilter));
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTCREATEGRABFILTER);
		return false;
	}

	hr = m_pSampGrabFilter->QueryInterface(IID_ISampleGrabber, (void**)&m_pGrabber);
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTCREATEGRABIFACE);
		return false;
	}

	AM_MEDIA_TYPE mt;

	ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
	mt.majortype = MEDIATYPE_Video;
	mt.subtype = m_selectedGuid;
	hr = m_pGrabber->SetMediaType(&mt);
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTSELECTYUV420PORYUY2);
		return false;
	}

	m_pGrabCallback = new GrabCallback(this);

	hr = m_pGrabber->SetCallback(m_pGrabCallback, 1);
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTSETCALLBACK);
		return false;
	}

	hr = m_pGraph->AddFilter(m_pCaptDevice, L"Capture Filter");
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTADDCAPTUREFILTER);
		return false;
	}

	if (!setFormat(width, height, frameRate))
	{
		clearNonZero();
		return false;
	}

	hr = m_pGraph->AddFilter(m_pNullRenderer, L"Null Renderer");
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTADDNULLRENDERER);
		return false;
	}

	hr = m_pGraph->AddFilter(m_pSampGrabFilter, L"Sample Grabber");
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTADDSAMPLEGRABBER);
		return false;
	}

	hr = m_pBuilder->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, m_pCaptDevice, m_pSampGrabFilter, m_pNullRenderer);
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTBUILDGRAPH);
		return false;
	}

	hr = m_pGrabber->GetConnectedMediaType(&mt);
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTGETFRAMESIZE);
		return false;
	}

	VIDEOINFOHEADER * vih = (VIDEOINFOHEADER*) mt.pbFormat;
	m_width  = vih->bmiHeader.biWidth;
	m_height = vih->bmiHeader.biHeight;
	CoTaskMemFree(mt.pbFormat);

	hr = m_pGraph->QueryInterface(IID_IMediaControl, (void **)&m_pControl);
	if (HR_FAILED(hr))
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTGETCONTROLINTERFACE);
		return false;
	}

	if (m_selectedGuid == EMIP_MEDIASUBTYPE_I420)
		m_largeFrameSize = (size_t)((m_width*m_height*3)/2);
	else
		m_largeFrameSize = (size_t)(m_width*m_height*2);

	m_pFullFrame = new uint8_t [m_largeFrameSize];
	m_pMsgFrame = new uint8_t [m_largeFrameSize];
	memset(m_pMsgFrame, 0, m_largeFrameSize);
	memset(m_pFullFrame, 0, m_largeFrameSize);

	if (m_subType == MIPRAWVIDEOMESSAGE_TYPE_YUV420P)
		m_pVideoMsg = new MIPRawYUV420PVideoMessage(m_width, m_height, m_pMsgFrame, false);
	else // MIPRAWVIDEOMESSAGE_TYPE_YUYV
		m_pVideoMsg = new MIPRawYUYVVideoMessage(m_width, m_height, m_pMsgFrame, false);

	if (!m_sigWait.init())
	{
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTINITSIGWAIT);
		return false;
	}
	
	m_captureTime = MIPTime::getCurrentTime();
	m_gotMsg = false;
	m_gotFrame = false;

	hr = m_pControl->Run();
	if (hr != S_OK && hr != S_FALSE) // Apparently S_FALSE is returned if the graph is preparing to run
	{
		m_sigWait.destroy();
		clearNonZero();
		setErrorString(MIPDIRECTSHOWCAPTURE_ERRSTR_CANTSTARTGRAPH);
		return false;
	}

	m_sourceID = 0;

	return true;
}