Beispiel #1
0
QByteArray OpusHead::toByteArray() const
{
    QByteArray data;

    // Magic signature
    data += QByteArray("OpusHead", 8);

    // Version
    data.push_back(static_cast<char>(0x01));

    // Channel count
    data.push_back(static_cast<char>(channelCount_));

    // Pre-skip
    size_t pos = data.size();
    data.resize(data.size() + sizeof(preSkip_));
    qToLittleEndian(preSkip_, reinterpret_cast<uchar*>(data.data()) + pos);

    // Input sample rate
    pos = data.size();
    data.resize(data.size() + sizeof(inputSampleRate_));
    qToLittleEndian(inputSampleRate_, reinterpret_cast<uchar*>(data.data()) + pos);

    // Output gain
    pos = data.size();
    data.resize(data.size() + sizeof(outputGain_));
    qToLittleEndian(outputGain_, reinterpret_cast<uchar*>(data.data()) + pos);

    // Channel mapping family
    data.push_back(static_cast<char>(0));

    return data;
}
Beispiel #2
0
void FileController::saveFile(QString src, QString line) {
    if(path.isEmpty()) {
        saveDialogEnable();
    }
    else {

        QFile file(path);
        file.open(QIODevice::ReadWrite);
        QByteArray srcBytes;
        QByteArray lineBytes;

        string lineStd = line.toStdString();
        for(int i = 0; i < lineStd.size(); ++i) {
            lineBytes.push_back(lineStd[i]);
        }

        string srcStd = src.toStdString();

        for(int i = 0; i < srcStd.size(); ++i) {
            srcBytes.push_back(srcStd[i]);
        }
        file.resize(0);

        file.write(lineBytes);
        file.write("\n");
        file.write(srcBytes);
    }
}
Beispiel #3
0
void MutableMap::saveToFile(QString filename) {
    int count=0;
    char cur_data=0;
    unsigned char d_mask=0x80;

    QByteArray binblob = QByteArray();
    const char hdr[16] = {'M','A','P',0x00,0x40,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
    for(unsigned i=0; i<16; i++) {
        binblob.push_back(hdr[i]);
    }

    while(count < data.size()) {
        d_mask=0x80;
        cur_data=0x00;
        while(d_mask>=0x01) {
            if(data.at(count))
                cur_data |= d_mask;
            d_mask >>= 1;
            count++;
        }
        binblob.push_back(cur_data);
    }

    QFile mf(filename);
    if(mf.open(QIODevice::WriteOnly)) {
        mf.write(binblob);
    }
}
QByteArray CBNLSProtocol :: SEND_BNLS_NULL( )
{
	QByteArray packet;
	packet.push_back( (char)0 );							// packet length will be assigned later
	packet.push_back( (char)0 );							// packet length will be assigned later
	packet.push_back( BNLS_NULL );					// BNLS_NULL
	AssignLength( packet );
	return packet;
}
Beispiel #5
0
    void DumpTest()
    {
        QByteArray arr;
        arr.push_back(1);
        arr.push_back(0x10);
        arr.push_back(0x1f);

        std::cout << PcUtils::DumpQByteArray(arr) << std::endl;
    }
Beispiel #6
0
static QByteArray convName(const QString& name) {
    // Strip unicode & get rid of quotes, brackets.
    QByteArray b;
    for (QChar c : name) {
        if (c <= 127 && c != QChar('"') && c != QChar('[') && c != QChar(']')) {
            b.push_back(c.toLatin1());
        } else {
            b.push_back('?');
        }
    }
    return b;
}
Beispiel #7
0
QByteArray GetPixelData(const QImage& img) {
    QByteArray result;
    for (int i = 0; i < img.width(); i++) {
        for (int j = 0; j < img.height(); j++) {
            QRgb c = img.pixel(i, j);
            result.push_back(qRed(c));
            result.push_back(qGreen(c));
            result.push_back(qBlue(c));
        }
    }
    return result;
}
QByteArray CBNLSProtocol :: SEND_BNLS_WARDEN_RAW( quint32 cookie, QByteArray raw )
{
	QByteArray packet;
	packet.push_back( (char)0 );											// packet length will be assigned later
	packet.push_back( (char)0 );											// packet length will be assigned later
	packet.push_back( BNLS_WARDEN );								// BNLS_WARDEN
	packet.push_back( 1 );											// BNLS_WARDEN_RAW
	packet.append(Util::fromUInt32(cookie));					// cookie
	packet.append(Util::fromUInt16(raw.size( )));	// raw length
	packet.append(raw);							// raw
	AssignLength( packet );
	return packet;
}
void EasyTransferPi::sendData(uint8_t *dataPtr, uint8_t lenght)
{
    uint8_t CS=lenght;
    QByteArray dataArray;
    dataArray.push_back(0x06);
    dataArray.push_back(0x85);
    dataArray.push_back(lenght);
    for (int i = 0; i < lenght; ++i) {
        dataArray.push_back(dataPtr[i]);
        CS^=*(dataPtr+i);
    }
    dataArray.push_back(CS);
    portManager->writeData(dataArray);
}
void msl::updateLEDs()
{
    qDebug() << "Updating LEDs!";
	QByteArray array;

    array.push_back(SET_COLOR);
    array.push_back(DIRECT_LED);
	array.push_back((char)this->ui.verticalSlider_uv->value());
	array.push_back((char)this->ui.verticalSlider_white->value());
	array.push_back(this->colorDialog->currentColor().red());
	array.push_back(this->colorDialog->currentColor().green());
	array.push_back(this->colorDialog->currentColor().blue());
	unsigned char checksum=0;
	for(QByteArray::iterator it = array.begin(); it != array.end(); ++it)
	{
        checksum^=*it;
	}
	array.push_back(checksum);

    //Start with AA 55
    array.push_front(0x55);
    array.push_front(0xAA);



	emit sendArray(array);
}
Beispiel #11
0
QByteArray CGameSlot :: GetQByteArray( ) const
{
	QByteArray b;
	b.push_back( m_PID );
	b.push_back( m_DownloadStatus );
	b.push_back( m_SlotStatus );
	b.push_back( m_Computer );
	b.push_back( m_Team );
	b.push_back( m_Colour );
	b.push_back( m_Race );
	b.push_back( m_ComputerType );
	b.push_back( m_Handicap );
	return b;
}
Beispiel #12
0
const QByteArray &Mnist::getImage(int index)
{
    if (images.contains(index)) {
        return images[index];
    }

    QByteArray rawImage = rawImages[index];
    QByteArray image;

//    for (int i = 0; i < nbRows; i ++) {
//        for (int j = 0; j < nbCols; j++) {
//            cout << ("00"+QString::number((int) (quint8)rawImage[i*nbCols+j])).right(3).toStdString() << "|";
//        }
//        cout << endl;
//    }

    for (int i = 0; i < nbRows; i += 4) {
        for (int j = 0; j < nbCols; j += 4) {
            int finalValue = 0;

            auto reducePixel = [&](int i, int j) {
                return (quint8(rawImage[i*nbCols+j]) + quint8(rawImage[(i+1)*nbCols+j]) + quint8(rawImage[i*nbCols+(j+1)]) + quint8(rawImage[(i+1)*nbCols+(j+1)]))/4;
            };

            int val;
            val = reducePixel(i, j);
            finalValue+= val >= 120;
            finalValue+= val > 160;
            finalValue *= 3;
            val = reducePixel(i, j+2);
            finalValue+= val >= 120;
            finalValue+= val > 160;
            finalValue *= 3;
            val = reducePixel(i+2, j);
            finalValue+= val >= 120;
            finalValue+= val > 160;
            finalValue *= 3;
            val = reducePixel(i+2, j+2);
            finalValue+= val >= 120;
            finalValue+= val > 160;

            image.push_back(finalValue);
        }
    }

//    QList<int> values;
//    for (int i = 0; i < image.size(); i++) {
//        values.push_back(i*81+image[i]);
//    }

//    MnistGraphics graphics;
//    graphics.run(QList<QVector<int>>() << values.toVector());

    images[index] = image;

    return images[index];
}
Beispiel #13
0
    void CRC32::TestAgainRaw()
    {
        QByteArray data;
        for(int i = 0; i < 32; ++i) data.push_back(i);

        Platform::dword rawCrc = Utils::UpdateCRC32(data.data(), data.size());
        Platform::dword boostCrc = Utils::CRC32(data).checksum();

        TUT_ASSERT(rawCrc == boostCrc);
    }
QByteArray CBNLSProtocol :: SEND_BNLS_WARDEN_SEED( quint32 cookie, quint32 seed )
{
	char Client[] = {  80,  88,  51,  87 };	// "W3XP"

	QByteArray packet;
	packet.push_back( (char)0 );								// packet length will be assigned later
	packet.push_back( (char)0 );								// packet length will be assigned later
	packet.push_back( BNLS_WARDEN );					// BNLS_WARDEN
	packet.push_back( (char)0 );								// BNLS_WARDEN_SEED
	packet.append(Util::fromUInt32(cookie));		// cookie
	packet.append(QByteArray(Client, 4));			// Client
	packet.append(Util::fromUInt16(4));	// length of seed
	packet.append(Util::fromUInt32(seed));		// seed
	packet.push_back( (char)0 );								// username is blank
	packet.append(Util::fromUInt16(0));	// password length
														// password
	AssignLength( packet );
	return packet;
}
void OsiTransportTest::sendTestData(CConnection* that)
{
	QByteArray qdata;
	qdata.reserve(sizeof(testData)/sizeof(testData[0]));
	for (char c: testData)
	{
		qdata.push_back(c);
	}

	that->send(qdata, (quint32)0, qdata.size());
}
Beispiel #16
0
void ExportAsciiDialog::createEnglishAscii(){
    QFont f("Consolas,Courier,monospace", 8);
    m_ui->asciiTextEdit->setFont(f);

    QByteArray s;
    s.reserve(boardBuffer.size() + 2 * boardBuffer[0].size() * 3);

    s.append("  ");
    for (int i=0; i<boardBuffer[0].size(); ++i){
        s.push_back(' ');
        s.push_back( 'A' + (i > 7 ? i+1 : i) );
    }
    s.push_back('\n');

    for (int y=0; y<boardBuffer.size(); ++y){
        s.append( QString("%1").arg(boardBuffer.size() - y, 2) );

        for (int x=0; x<boardBuffer[y].size(); ++x){
            if (boardBuffer[y][x].black())
                s.append(" #");
            else if (boardBuffer[y][x].white())
                s.append(" O");
            else if (isStar(x, y))
                s.append(" +");
            else
                s.append(" .");
        }

        s.append( QString(" %1\n").arg(boardBuffer.size() - y, 2) );
    }

    s.append("  ");
    for (int i=0; i<boardBuffer[0].size(); ++i){
        s.push_back(' ');
        s.push_back( 'A' + (i > 7 ? i+1 : i) );
    }

    m_ui->asciiTextEdit->setPlainText(s);
}
Beispiel #17
0
    void UdpChannel::SendData(std::vector<Platform::byte> const &data)
    {
        QByteArray dataArray;
        for (int i = 0; i < data.size(); ++i)
        {
            dataArray.push_back(data[i]);
        }

        boost::shared_ptr<iNet::SocketData> socketData(
          new iNet::SocketData(m_remouteInf.getAddress(), m_cfg.localPotr(), dataArray));

        m_socket->SendData(socketData);
    }
Beispiel #18
0
void AudioInput::flushCheck(const QByteArray &frame, bool terminator) {
	qlFrames.push_back(frame);
	if (! terminator && qlFrames.size() < iAudioFrames)
		return;

	int flags = g_struct.iTarget;
	if (terminator)
		flags = g_struct.iPrevTarget;

	flags |= (umtType << 5);

	char data[1024];
	data[0] = static_cast<unsigned char>(flags);

	PacketDataStream pds(data + 1, 1023);
	pds << iFrameCounter - qlFrames.size();

	if (terminator)
		qlFrames.push_back(QByteArray()); 

	for (int i=0;i<qlFrames.size(); ++i) {
		const QByteArray &qba = qlFrames.at(i);
		unsigned char head = static_cast<unsigned char>(qba.size());
		if (i < qlFrames.size() - 1)
			head |= 0x80;
		pds.append(head);
		pds.append((char*)(&qba[0]), qba.size());
	}

	//test
	//g_struct.s.lmLoopMode = Settings::Local;

	if (g_struct.s.lmLoopMode == Settings::Local)
	{
		//如果是本地预览声音,则添加到本地预览声音缓存
		QByteArray qba;
		for(int i=0; i<pds.size()+1; i++)
		{
			qba.push_back(data[i]);
		}
		LoopUser::lpLoopy.addFrame(qba);
	}
		
	else if (g_struct.trans)
	{
		//获得到数据,准备发送                123+1
		g_struct.trans->SendAudioData(data,pds.size() + 1); 
	}

	qlFrames.clear();
}
Beispiel #19
0
void XbeeLink::readBytes()
{
	xbee_pkt *xbeePkt;
	xbeePkt = xbee_getpacketwait(this->m_xbeeCon);
	if(!(NULL==xbeePkt))
	{
		QByteArray data;
		for(unsigned int i=0;i<=xbeePkt->datalen;i++)
		{
			data.push_back(xbeePkt->data[i]);
		}
		qDebug() << data;
		emit bytesReceived(this,data);
	}
}
void XbeeLink::readBytes()
{
	xbee_pkt *xbeePkt;
	xbeePkt = xbee_getpacketwait(this->m_xbeeCon);
	if(!(NULL==xbeePkt))
	{
		QByteArray data;
		for(unsigned int i=0;i<=xbeePkt->datalen;i++)
		{
			data.push_back(xbeePkt->data[i]);
        }

		_logInputDataRate(data.length(), QDateTime::currentMSecsSinceEpoch());
		emit bytesReceived(this, data);
	}
}
Beispiel #21
0
void XbeeLink::readBytes()
{
	xbee_pkt *xbeePkt;
	xbeePkt = xbee_getpacketwait(this->m_xbeeCon);
	if(!(NULL==xbeePkt))
	{
		QByteArray data;
		for(unsigned int i=0;i<=xbeePkt->datalen;i++)
		{
			data.push_back(xbeePkt->data[i]);
        }

        emit bytesReceived(this, data);

        // Log the amount and time received for future data rate calculations.
        QMutexLocker dataRateLocker(&dataRateMutex);
        logDataRateToBuffer(inDataWriteAmounts, inDataWriteTimes, &inDataIndex, data.length(), QDateTime::currentMSecsSinceEpoch());
	}
}
bool CBNLSProtocol :: ValidateLength( QByteArray &content )
{
	// verify that bytes 1 and 2 (indices 0 and 1) of the content array describe the length

	quint16 Length;
	QByteArray LengthBytes;

	if( content.size( ) >= 2 && content.size( ) <= 65535 )
	{
		LengthBytes.push_back( content[0] );
		LengthBytes.push_back( content[1] );
		Length = Util::extractUInt16( LengthBytes );

		if( Length == content.size( ) )
			return true;
	}

	return false;
}
Beispiel #23
0
WebSocket *WebSocket::upgradeFromHttp(QTcpSocket *socket)
{
	QByteArray key;
	for (;;) {
		QByteArray line;
		for (;;) {
			char ch;
			if (socket->read(&ch, 1) != 1)
				return NULL;

			if (ch == '\n')
				break;
			if (ch != '\r')
				line.push_back(ch);
		}

		const char *prefix = "Sec-WebSocket-Key: ";
		if (line.startsWith(prefix))
			key = line.right(line.length() - strlen(prefix));
		else if (!line.length())
			break;
	}

	if (!key.length())
		return NULL;

	key.append("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");

	QCryptographicHash hash(QCryptographicHash::Sha1);
	hash.addData(key.data(), key.size());

	QString response = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ";
	response.append(hash.result().toBase64());
	response.append("\r\n\r\n");

	socket->write(response.toUtf8().constData(), response.length());

	return new WebSocket(socket);
}
Beispiel #24
0
QByteArray *Packet::fromHexString(QString string)
{
	QString stripped = string.remove(QRegExp("[^a-zA-Z0-9]")); //Removes everything except a-z (and capital) and 0-9

	//Error, its not an even numbered string (so not in correct form)
	if(stripped.size() % 2 != 0)
		return NULL;

	QByteArray *buffer = new QByteArray(stripped.size() % 2, '\0');
	bool good;
	for(int i = 0; i < stripped.size(); i+=2)
	{
		QStringRef hex(&stripped, i, 2);
		uint8 c = (uint8)hex.toString().toUShort(&good, 16);
		if(!good)
		{
			delete buffer;
			return NULL;
		}

		buffer->push_back(c);
	}
	return buffer;
}
Beispiel #25
0
bool getGatewayMacAddress(quint32 ipv4Host, QByteArray& mac)
{
	std::vector<char> data(512 * 1024);

	int mib[6];
	mib[0] = CTL_NET;
	mib[1] = PF_ROUTE;
	mib[2] = 0;
	mib[3] = AF_INET;
	mib[4] = NET_RT_FLAGS;
	mib[5] = RTF_LLINFO;

	size_t cb = data.size();
	if (sysctl(mib, 6, &data[0], &cb, NULL, 0)  == 0) {
		const char *p = &data[0];
		const char *pe = p + cb;
		const rt_msghdr *rtm;
		for (; p != pe; p += rtm->rtm_msglen) {
	        rtm = reinterpret_cast<const rt_msghdr*>(p);

			const sockaddr_inarp *sin = reinterpret_cast<const sockaddr_inarp*>(rtm + 1);
			const sockaddr_dl *sdl = reinterpret_cast<const sockaddr_dl*>(sin + 1);

			if (sdl->sdl_alen) {
				if (ntohl(sin->sin_addr.s_addr) == ipv4Host) {
					u_char *cp = (u_char*)LLADDR(sdl);
					for (int i = 0; i < 6; i++) {
						mac.push_back(cp[i]);
					}
					return true;
				}
			}
		}
	}
	return false;
}
Beispiel #26
0
void AudioInput::encodeAudioFrame() {
	int iArg;
	//ClientUser *p=ClientUser::get(g.uiSession);
	int i;
	float sum;
	short max;

	short *psSource;

	iFrameCounter++;

	if (! bRunning) {
		return;
	}

	MutexLocker l(&qmSpeex);

	bResetProcessor = false;

	if (bResetProcessor) {
		if (sppPreprocess)
			speex_preprocess_state_destroy(sppPreprocess);
		if (sesEcho)
			speex_echo_state_destroy(sesEcho);

		sppPreprocess = speex_preprocess_state_init(iFrameSize, iSampleRate);

		iArg = 1;
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_VAD, &iArg);
		//speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC, &iArg);
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_DENOISE, &iArg);
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_DEREVERB, &iArg);

		iArg = 30000;
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg);

		float v = 30000.0f / static_cast<float>(g_struct.s.iMinLoudness);
		iArg = (floorf(20.0f * log10f(v)));
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &iArg);

		iArg = g_struct.s.iNoiseSuppress;
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg);

		if (iEchoChannels > 0) {
			sesEcho = speex_echo_state_init_mc(iFrameSize, iFrameSize*10, 1, bEchoMulti ? iEchoChannels : 1);
			iArg = iSampleRate;
			speex_echo_ctl(sesEcho, SPEEX_ECHO_SET_SAMPLING_RATE, &iArg);
			speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_ECHO_STATE, sesEcho);

			Trace("AudioInput: ECHO CANCELLER ACTIVE");
		} else {
			sesEcho = NULL;
		}

		bResetProcessor = false;
	}

	int iIsSpeech=1;
	psSource = psMic;
/*
	//回音消除和音质处理
	if (bEcho && sesEcho && psSpeaker)
	{
		speex_echo_cancellation(sesEcho, psMic, psSpeaker, psClean);
		iIsSpeech=speex_preprocess_run(sppPreprocess, psClean);
		psSource = psClean;
	} 
	else {
		iIsSpeech=speex_preprocess_run(sppPreprocess, psMic);
		psSource = psMic;
	}*/

	/*sum=1.0f;
	for (i=0;i<iFrameSize;i++)
		sum += static_cast<float>(psSource[i] * psSource[i]);
	float micLevel = sqrtf(sum / static_cast<float>(iFrameSize));
	dPeakSignal=20.0f*log10f(micLevel / 32768.0f);
	if (dPeakSignal < -96.0f)
		dPeakSignal = -96.0f;

	spx_int32_t prob = 0;
	speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_GET_PROB, &prob);
	fSpeechProb = static_cast<float>(prob) / 100.0f;

	float level = (g_struct.s.vsVAD == Settings::SignalToNoise) ? fSpeechProb : (1.0f + dPeakMic / 96.0f);

	if (level > g_struct.s.fVADmax)
		iIsSpeech = 1;
	else if (level > g_struct.s.fVADmin && bPreviousVoice)
		iIsSpeech = 1;
	else
		iIsSpeech = 0;

	if (! iIsSpeech) {
		iHoldFrames++;
		if (iHoldFrames < g_struct.s.iVoiceHold)
			iIsSpeech=1;
	} else {
		iHoldFrames = 0;
	}*/

	//tIdle.restart();
	/*
	int r = celt_encoder_ctl(ceEncoder, CELT_SET_POST_MDCT_CALLBACK(celtBack, NULL));
	qWarning() << "Set Callback" << r;
	*/

	//编码 speex或者CELT
	unsigned char buffer[512];
	int len;

	if (umtType == MessageHandler::UDPVoiceCELT) {
		if (cCodec == NULL)
		{
			cCodec = CELTCodec::instance();
			ceEncoder = cCodec->encoderCreate();
		}
		else if (cCodec && ! bPreviousVoice) {
			cCodec->encoder_ctl(ceEncoder, CELT_RESET_STATE);
		}

		cCodec->encoder_ctl(ceEncoder, CELT_SET_PREDICTION(0));

		cCodec->encoder_ctl(ceEncoder,CELT_SET_BITRATE(iAudioQuality));
		len = cCodec->encode(ceEncoder, psSource, SAMPLE_RATE / 50, buffer, 512);
		iBitrate = len * 50 * 8;
		
		/*////////////////////////////////////////////////////////////////////////

		if (m_de_cdDecoder == NULL) {
			m_de_cdDecoder = cCodec->decoderCreate();
		}
		
		celt_int16 fout2[2560]={0};

		if (cCodec)
		{
			int len3 = cCodec->decode(m_de_cdDecoder, buffer, len, fout2, SAMPLE_RATE / 50);
			len3++;

			UINT dwDataWrote;
			if( FAILED(g_pWaveFile.Write( SAMPLE_RATE / 50*2*2, (BYTE*)fout2, 
				&dwDataWrote ) ))
			{
				int a=0;
				a++;
			}
			else
			{
				OutputDebugString(L"plushuwav g_pWaveFile.Write 3");				
			}
		}

		///////////////////////////////////////////////////////////////////////*/
	} 
	else {
		assert(0);
	}

	QByteArray qba;
	for(int i=0; i<len; i++)
	{
		qba.push_back(buffer[i]);
	}

	flushCheck(qba, false);

	if (! iIsSpeech)
		iBitrate = 0;

	bPreviousVoice = iIsSpeech;
}
bool ContractionHierarchies::Preprocess( IImporter* importer, QString dir )
{
	QString filename = fileInDirectory( dir, "Contraction Hierarchies" );

	std::vector< IImporter::RoutingNode > inputNodes;
	std::vector< IImporter::RoutingEdge > inputEdges;

	if ( !importer->GetRoutingNodes( &inputNodes ) )
		return false;
	if ( !importer->GetRoutingEdges( &inputEdges ) )
		return false;

	unsigned numEdges = inputEdges.size();
	unsigned numNodes = inputNodes.size();

	Contractor* contractor = new Contractor( numNodes, inputEdges );
	std::vector< IImporter::RoutingEdge >().swap( inputEdges );
	contractor->Run();

	std::vector< Contractor::Witness > witnessList;
	contractor->GetWitnessList( witnessList );

	std::vector< ContractionCleanup::Edge > contractedEdges;
	std::vector< ContractionCleanup::Edge > contractedLoops;
	contractor->GetEdges( &contractedEdges );
	contractor->GetLoops( &contractedLoops );
	delete contractor;

	ContractionCleanup* cleanup = new ContractionCleanup( inputNodes.size(), contractedEdges, contractedLoops, witnessList );
	std::vector< ContractionCleanup::Edge >().swap( contractedEdges );
	std::vector< ContractionCleanup::Edge >().swap( contractedLoops );
	std::vector< Contractor::Witness >().swap( witnessList );
	cleanup->Run();

	std::vector< CompressedGraph::Edge > edges;
	std::vector< NodeID > map;
	cleanup->GetData( &edges, &map );
	delete cleanup;

	{
		std::vector< unsigned > edgeIDs( numEdges );
		for ( unsigned edge = 0; edge < edges.size(); edge++ ) {
			if ( edges[edge].data.shortcut )
				continue;
			unsigned id = 0;
			unsigned otherEdge = edge;
			while ( true ) {
				if ( otherEdge == 0 )
					break;
				otherEdge--;
				if ( edges[otherEdge].source != edges[edge].source )
					break;
				if ( edges[otherEdge].target != edges[edge].target )
					continue;
				if ( edges[otherEdge].data.shortcut )
					continue;
				id++;
			}
			edgeIDs[edges[edge].data.id] = id;
		}
		importer->SetEdgeIDMap( edgeIDs );
	}

	std::vector< IRouter::Node > nodes( numNodes );
	for ( std::vector< IImporter::RoutingNode >::const_iterator i = inputNodes.begin(), iend = inputNodes.end(); i != iend; i++ )
		nodes[map[i - inputNodes.begin()]].coordinate = i->coordinate;
	std::vector< IImporter::RoutingNode >().swap( inputNodes );

	std::vector< IRouter::Node > pathNodes;
	{
		std::vector< IImporter::RoutingNode > edgePaths;
		if ( !importer->GetRoutingEdgePaths( &edgePaths ) )
			return false;
		pathNodes.resize( edgePaths.size() );
		for ( unsigned i = 0; i < edgePaths.size(); i++ )
			pathNodes[i].coordinate = edgePaths[i].coordinate;
	}

	if ( !importer->GetRoutingEdges( &inputEdges ) )
		return false;

	{
		std::vector< QString > inputNames;
		if ( !importer->GetRoutingWayNames( &inputNames ) )
			return false;

		QFile nameFile( filename + "_names" );
		if ( !openQFile( &nameFile, QIODevice::WriteOnly ) )
			return false;

		std::vector< unsigned > nameMap( inputNames.size() );
		for ( unsigned name = 0; name < inputNames.size(); name++ ) {
			nameMap[name] = nameFile.pos();
			QByteArray buffer = inputNames[name].toUtf8();
			buffer.push_back( ( char ) 0 );
			nameFile.write( buffer );
		}

		nameFile.close();
		nameFile.open( QIODevice::ReadOnly );
		const char* test = ( const char* ) nameFile.map( 0, nameFile.size() );
		for ( unsigned name = 0; name < inputNames.size(); name++ ) {
			QString testName = QString::fromUtf8( test + nameMap[name] );
			assert( testName == inputNames[name] );
		}

		for ( unsigned edge = 0; edge < numEdges; edge++ )
			inputEdges[edge].nameID = nameMap[inputEdges[edge].nameID];
	}

	{
		std::vector< QString > inputTypes;
		if ( !importer->GetRoutingWayTypes( &inputTypes ) )
			return false;

		QFile typeFile( filename + "_types" );
		if ( !openQFile( &typeFile, QIODevice::WriteOnly ) )
			return false;

		QStringList typeList;
		for ( unsigned type = 0; type < inputTypes.size(); type++ )
			typeList.push_back( inputTypes[type] );

		typeFile.write( typeList.join( ";" ).toUtf8() );
	}

	for ( std::vector< IImporter::RoutingEdge >::iterator i = inputEdges.begin(), iend = inputEdges.end(); i != iend; i++ ) {
		i->source = map[i->source];
		i->target = map[i->target];
	}

	CompressedGraphBuilder* builder = new CompressedGraphBuilder( 1u << m_settings.blockSize, nodes, edges, inputEdges, pathNodes );
	if ( !builder->run( filename, &map ) )
		return false;
	delete builder;

	importer->SetIDMap( map );

	return true;
}
Beispiel #28
0
void AudioInput::encodeAudioFrame() {
	int iArg;
	//ClientUser *p=ClientUser::get(g.uiSession);
	int i;
	float sum;
	short max;

	short *psSource;

	iFrameCounter++;

	if (! bRunning) {
		return;
	}

	/*sum=1.0f;
	for (i=0;i<iFrameSize;i++)
		sum += static_cast<float>(psMic[i] * psMic[i]);

	iLevel = sqrtf(sum / static_cast<float>(iFrameSize)) * 9/32768.0f;
	dPeakMic=20.0f*log10f(sqrtf(sum / static_cast<float>(iFrameSize)) / 32768.0f);
	if (dPeakMic < -96.0f)
		dPeakMic = -96.0f;

	max = 1;
	for (i=0;i<iFrameSize;i++)
		max = static_cast<short>(abs(psMic[i]) > max ? abs(psMic[i]) : max);
	dMaxMic = max;

	if (psSpeaker && (iEchoChannels > 0)) {
		sum=1.0f;
		for (i=0;i<iFrameSize;i++)
			sum += static_cast<float>(psSpeaker[i] * psSpeaker[i]);
		dPeakSpeaker=20.0f*log10f(sqrtf(sum / static_cast<float>(iFrameSize)) / 32768.0f);
		if (dPeakSpeaker < -96.0f)
			dPeakSpeaker = -96.0f;
	} else {
		dPeakSpeaker = 0.0;
	}*/

	MutexLocker l(&qmSpeex);

	bResetProcessor = false;

	if (bResetProcessor) {
		if (sppPreprocess)
			speex_preprocess_state_destroy(sppPreprocess);
		if (sesEcho)
			speex_echo_state_destroy(sesEcho);

		sppPreprocess = speex_preprocess_state_init(iFrameSize, iSampleRate);

		iArg = 1;
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_VAD, &iArg);
		//speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC, &iArg);
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_DENOISE, &iArg);
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_DEREVERB, &iArg);

		iArg = 30000;
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg);

		float v = 30000.0f / static_cast<float>(g_struct.s.iMinLoudness);
		iArg = (floorf(20.0f * log10f(v)));
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &iArg);

		iArg = g_struct.s.iNoiseSuppress;
		speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg);

		if (iEchoChannels > 0) {
			sesEcho = speex_echo_state_init_mc(iFrameSize, iFrameSize*10, 1, bEchoMulti ? iEchoChannels : 1);
			iArg = iSampleRate;
			speex_echo_ctl(sesEcho, SPEEX_ECHO_SET_SAMPLING_RATE, &iArg);
			speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_ECHO_STATE, sesEcho);

			Trace("AudioInput: ECHO CANCELLER ACTIVE");
		} else {
			sesEcho = NULL;
		}

		bResetProcessor = false;
	}

	int iIsSpeech=1;
	psSource = psMic;
/*
	//回音消除和音质处理
	if (bEcho && sesEcho && psSpeaker)
	{
		speex_echo_cancellation(sesEcho, psMic, psSpeaker, psClean);
		iIsSpeech=speex_preprocess_run(sppPreprocess, psClean);
		psSource = psClean;
	} 
	else {
		iIsSpeech=speex_preprocess_run(sppPreprocess, psMic);
		psSource = psMic;
	}*/

	/*sum=1.0f;
	for (i=0;i<iFrameSize;i++)
		sum += static_cast<float>(psSource[i] * psSource[i]);
	float micLevel = sqrtf(sum / static_cast<float>(iFrameSize));
	dPeakSignal=20.0f*log10f(micLevel / 32768.0f);
	if (dPeakSignal < -96.0f)
		dPeakSignal = -96.0f;

	spx_int32_t prob = 0;
	speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_GET_PROB, &prob);
	fSpeechProb = static_cast<float>(prob) / 100.0f;

	float level = (g_struct.s.vsVAD == Settings::SignalToNoise) ? fSpeechProb : (1.0f + dPeakMic / 96.0f);

	if (level > g_struct.s.fVADmax)
		iIsSpeech = 1;
	else if (level > g_struct.s.fVADmin && bPreviousVoice)
		iIsSpeech = 1;
	else
		iIsSpeech = 0;

	if (! iIsSpeech) {
		iHoldFrames++;
		if (iHoldFrames < g_struct.s.iVoiceHold)
			iIsSpeech=1;
	} else {
		iHoldFrames = 0;
	}*/

	//tIdle.restart();
	/*
	int r = celt_encoder_ctl(ceEncoder, CELT_SET_POST_MDCT_CALLBACK(celtBack, NULL));
	qWarning() << "Set Callback" << r;
	*/

	//编码 speex或者CELT
	unsigned char buffer[512];
	int len;

	if (umtType != MessageHandler::UDPVoiceSpeex) {
		if (cCodec == NULL)
		{
			cCodec = new CELTCodec;
			umtType = MessageHandler::UDPVoiceCELT;
			ceEncoder = cCodec->encoderCreate();
		}
		else if (cCodec && ! bPreviousVoice) {
			cCodec->encoder_ctl(ceEncoder, CELT_RESET_STATE);
		}

		cCodec->encoder_ctl(ceEncoder, CELT_SET_PREDICTION(0));

		cCodec->encoder_ctl(ceEncoder,CELT_SET_BITRATE(iAudioQuality));
		len = cCodec->encode(ceEncoder, psSource, SAMPLE_RATE / 100, buffer, 512);
		iBitrate = len * 100 * 8;
	} 
	else {
		int vbr = 0;
		speex_encoder_ctl(esSpeex, SPEEX_GET_VBR_MAX_BITRATE, &vbr);
		if (vbr != iAudioQuality) {
			vbr = iAudioQuality;
			speex_encoder_ctl(esSpeex, SPEEX_SET_VBR_MAX_BITRATE, &vbr);
		}

		if (! bPreviousVoice)
			speex_encoder_ctl(esSpeex, SPEEX_RESET_STATE, NULL);

		speex_encode_int(esSpeex, psSource, &sbBits);
		len = speex_bits_write(&sbBits, reinterpret_cast<char *>(buffer), 127);
		iBitrate = len * 50 * 8;
		speex_bits_reset(&sbBits);
	}

	QByteArray qba;
	for(int i=0; i<len; i++)
	{
		qba.push_back(buffer[i]);
	}

	flushCheck(qba, false);

	if (! iIsSpeech)
		iBitrate = 0;

	bPreviousVoice = iIsSpeech;
}
Beispiel #29
0
void ExportAsciiDialog::createJapaneseAscii(bool isMono){
#ifdef Q_WS_WIN
    const char* monospace   = "\xef\xbc\xad\xef\xbc\xb3\x20\xe3\x82\xb4\xe3\x82\xb7\xe3\x83\x83\xe3\x82\xaf"; // ms gothic
    const char* propotional = "\xef\xbc\xad\xef\xbc\xb3\x20\xef\xbc\xb0\xe3\x82\xb4\xe3\x82\xb7\xe3\x83\x83\xe3\x82\xaf"; // ms p-gothic
#elif defined(Q_WS_MAC)
    const char* monospace   = "Osaka\342\210\222\347\255\211\345\271\205"; // Osaka-tohaba
    const char* propotional = "Osaka"; // Osaka
#else
    const char* monospace   = "monospace";
    const char* propotional = "Takao Pゴシック";
#endif

    QFont f(isMono ? monospace : propotional, 8);
    m_ui->asciiTextEdit->setFont(f);
qDebug() << f.family();

    QByteArray s;
    s.reserve(boardBuffer.size() + 2 * boardBuffer[0].size() * 3);

    const char* top[]    = {"\xe2\x94\x8f","\xe2\x94\xaf","\xe2\x94\x93"};
    const char* center[] = {"\xe2\x94\xa0","\xe2\x94\xbc","\xe2\x94\xa8"};
    const char* bottom[] = {"\xe2\x94\x97","\xe2\x94\xb7","\xe2\x94\x9b"};
    const char* header[] = {"\xef\xbc\xa1","\xef\xbc\xa2","\xef\xbc\xa3","\xef\xbc\xa4","\xef\xbc\xa5","\xef\xbc\xa6","\xef\xbc\xa7","\xef\xbc\xa8","\xef\xbc\xaa","\xef\xbc\xab","\xef\xbc\xac","\xef\xbc\xad","\xef\xbc\xae","\xef\xbc\xaf","\xef\xbc\xb0","\xef\xbc\xb1","\xef\xbc\xb2","\xef\xbc\xb3","\xef\xbc\xb4","\xef\xbc\xb5","\xef\xbc\xb6","\xef\xbc\xb7","\xef\xbc\xb8","\xef\xbc\xb9","\xef\xbc\xba"};
    int headerNum = sizeof(header)/sizeof(header[0]);

    // 2byte space
    if (isMono)
        s.append("\xe3\x80\x80");
    else
        s.append("\xef\xbc\xbf");

    for (int i=0, j=0; i<boardBuffer[0].size(); ++i, ++j){
        if (j >= headerNum)
            j = 0;
        s.push_back( header[j] );
        if (isMono == false && j != 12 && j != 16)
            s.push_back(' ');
    }

    s.push_back('\n');

    for (int y=0; y<boardBuffer.size(); ++y){
        if (isMono)
            s.append( QString().sprintf("%2d", boardBuffer.size() - y) );
        else
            s.append( QString().sprintf("%02d", boardBuffer.size() - y) );

        const char** b = y == 0 ? top : y == boardBuffer.size() - 1 ? bottom : center;

        for (int x=0; x<boardBuffer[y].size(); ++x){
            if (boardBuffer[y][x].black())
                s.append("\xe2\x97\x8f");
            else if (boardBuffer[y][x].white())
                s.append("\xe2\x97\x8b");
            else{
                if (x == 0)
                    s.append(b[0]);
                else if (x == boardBuffer[y].size() - 1)
                    s.append(b[2]);
                else if (isStar(x, y))
                    s.append("\xe2\x95\x8b");
                else
                    s.append(b[1]);
            }
        }

        if (isMono)
            s.append( QString().sprintf("%2d\n", boardBuffer.size() - y) );
        else
            s.append( QString().sprintf("%02d\n", boardBuffer.size() - y) );
    }

    // 2byte space
    if (isMono)
        s.append("\xe3\x80\x80");
    else
        s.append("\xef\xbc\xbf");

    for (int i=0, j=0; i<boardBuffer[0].size(); ++i, ++j){
        if (j >= headerNum)
            j = 0;
        s.push_back( header[j] );
        if (isMono == false && j != 12 && j != 16)
            s.push_back(' ');
    }

    m_ui->asciiTextEdit->setPlainText(s);
}
Beispiel #30
0
void CGProxy::readLocalPackets()
{
	QByteArray bytes = m_LocalSocket->readAll();
	m_LocalBytes += bytes;

	while( m_LocalBytes.size( ) >= 4 )
	{
		if( m_LocalBytes.at(0) == W3GS_HEADER_CONSTANT )
		{
			QByteArray LengthBytes;
			LengthBytes.push_back( m_LocalBytes[2] );
			LengthBytes.push_back( m_LocalBytes[3] );
			quint16 length = qFromLittleEndian<quint16>((uchar*)LengthBytes.data());

			if(length >= 4)
			{
				if( m_LocalBytes.size( ) >= length )
				{
					QByteArray data = QByteArray(m_LocalBytes, length);
					QDataStream ds(data);

					bool forward = true;

					if( m_LocalBytes.at(1) == CGameProtocol :: W3GS_CHAT_TO_HOST )
					{
						if( data.size( ) >= 5 )
						{
							int i = 5;
							char Total = data[4];

							if( Total > 0 && data.size( ) >= i + Total )
							{
								i += Total;
								unsigned char Flag = data[i + 1];
								i += 2;

								QString MessageString;

								if( Flag == 16 && data.size( ) >= i + 1 )
								{
									ds.skipRawData(i);
									MessageString = CGameProtocol :: ExtractString(ds);
								}
								else if( Flag == 32 && data.size( ) >= i + 5 )
								{
									ds.skipRawData(i+4);
									MessageString = CGameProtocol :: ExtractString(ds);
								}

								QString Command = MessageString.toLower();

								if( Command.size( ) >= 1 && Command.at(0) == '/' )
								{
									forward = false;

									if( Command.size( ) >= 5 && Command.mid( 0, 4 ) == "/re " )
									{
										// 										if( m_BNET->GetLoggedIn( ) )
										// 										{
										// 											//if( !m_BNET->GetReplyTarget( ).empty( ) )
										// 											{
										// 												//m_BNET->QueueChatCommand( MessageString.substr( 4 ), m_BNET->GetReplyTarget( ), true );
										// 												SendLocalChat( "Whispered to " + m_BNET->GetReplyTarget( ) + ": " + MessageString.substr( 4 ) );
										// 											}
										// 											else
										// 												SendLocalChat( "Nobody has whispered you yet." );
										// 										}
										// 										else
										// 											SendLocalChat( "You are not connected to battle.net." );
									}
									else if( Command == "/status" )
									{
										if( m_LocalSocket )
										{
											if( m_GameIsReliable && m_ReconnectPort > 0 )
												SendLocalChat( "GProxy++ disconnect protection: enabled" );
											else
												SendLocalChat( "GProxy++ disconnect protection: disabled" );
										}
									}
								}
							}
						}
					}

					if( forward )
					{
						m_LocalPackets.push_back( new CCommandPacket( W3GS_HEADER_CONSTANT, m_LocalBytes[1], data ) );
						m_PacketBuffer.push_back( new CCommandPacket( W3GS_HEADER_CONSTANT, m_LocalBytes[1], data ) );
						m_TotalPacketsReceivedFromLocal++;
					}

					m_LocalBytes = QByteArray(m_LocalBytes.begin( ) + length, m_LocalBytes.size() - length);
				}
				else
					return;
			}
			else
			{
				qDebug() << "[GPROXY] received invalid packet from local player (bad length)";
				m_LeaveGameSent = true;
				m_LocalSocket->disconnectFromHost( );
				return;
			}
		}
		else
		{
			qDebug() << ( "[GPROXY] received invalid packet from local player (bad header constant)" );
			m_LeaveGameSent = true;
			m_LocalSocket->disconnectFromHost( );
			return;
		}
	}

	processLocalPackets();
}