Exemplo n.º 1
0
void CHCEmulator::ReadRemoteVersionInfoCompleteEvent(TUint8 aError, THCIConnHandle aConnH)
	{
	ClearPacket();

	iConsole.Printf(_L("Sending ReadRemoteVersionInfoComplete Event (error 0x%02x)...\n"), aError);

	PutBytes(KHCIUARTEventHeader);
	PutBytes(KHCIReadRemoteVersionInfoCode);
	PutBytes(KHCIReadRemoteVersionInfoLength);
	PutBytes(aError);
	PutBytes(aConnH, 2);
	PutBytes(KEmulatedRemoteVersionInfo1,4);
	PutBytes(KEmulatedRemoteVersionInfo2,1);

	WritePacket();	
	}
Exemplo n.º 2
0
void CHCEmulator::WriteLinkPolicySettingsCompleteEvent(TUint8 aError, THCIConnHandle aConnH)
	{
	ClearPacket();

	iConsole.Printf(_L("Sending WriteLinkPolicySettingsComplete Event (error 0x%02x)...\n"), aError);

	PutBytes(KHCIUARTEventHeader);
	PutBytes(KHCICommandCompleteEventCode);
	PutBytes(KHCIWriteLinkPolicySettingsCompleteLength);
	PutBytes(1); //1 command token
	PutBytes(KWriteLinkPolicySettingsOpcode,2);
	PutBytes(aError);
	PutBytes(aConnH, 2);

	WritePacket();	
	}
Exemplo n.º 3
0
int UserClient::_CmdRSTO( OmniPacket *packet )
{
	int errCode = ERROR_OK;
	char ret[BUFLEN];
	bzero( ret, BUFLEN );
	char param[NODELEN];

	PARSE_TAG_INIT( packet->mHeader );
	PARSE_TAG_NEXT( packet->mHeader, param );
	gLog.log("Restore Table [%s]", param );

	errCode = Table::Restore( param );
	sprintf( ret, "RSTO %lu %d 0\r\n", packet->mTrid, errCode );
	WritePacket( ret, strlen(ret) );

	return errCode;
}
Exemplo n.º 4
0
void CMsregPacketHeader::WriteDataToFile(CFile& cfFile, DWORD& dwChecksum)
{
	// Write inherited data.
	CMsregPacket::WriteDataToFile(cfFile, dwChecksum);

	// Write customer ID.
	WriteString(cfFile, m_csCustomerId, dwChecksum);

	// Write packet count.
	WriteDword(cfFile, PacketCount(), dwChecksum);

	// Write packets.
	for (int i = 0; i < PacketCount(); i++)
	{
		WritePacket(cfFile, GetPacket(i));
	}
}
Exemplo n.º 5
0
void CHCEmulator::InquiryResultEvent()
	{
	TInt resultsInPacket = Min(((iCurrentInquiryResponse % 5) + 1) , (KEmulatedInquiryNumberDevicesFound - iCurrentInquiryResponse));
	
	ClearPacket();

	TInt error = KHCIOK;

	iConsole.Printf(_L("Sending InquiryResult Event (error 0x%02x)...\n"), error);

	PutBytes(KHCIUARTEventHeader);
	PutBytes(KHCIInquiryResultEventCode);
	PutBytes(1 + (14 * resultsInPacket));
	PutBytes(resultsInPacket);
	
	for (TInt i = 0; i < resultsInPacket; i++)
		{
		// stick them all in one event!
		
		PutAddress(iInquiryAddresses[iCurrentInquiryResponse + i]);
		PutBytes(KEmulatedInquiryPageScanRepetionMode);
		PutBytes(KEmulatedInquiryPageScanPeriodMode);
		PutBytes(KEmulatedInquiryPageScanMode);
		PutBytes(KEmulatedInquiryClassOfDevice,3);
		PutBytes(KEmulatedInquiryClockOffset,2);
		}

	WritePacket();
	
	iCurrentInquiryResponse += resultsInPacket;
	
	// Wait for another result if we've not done them all, else complete inquiry
	if(iCurrentInquiryResponse < KEmulatedInquiryNumberDevicesFound)
		{
		iInquiryTimer->Start();
		}
	else
		{
		InquiryCompleteEvent(KHCIOK);
		}
	}
Exemplo n.º 6
0
static int cpia_usb_transferCmd(void *privdata, u8 *command, u8 *data)
{
	int err = 0;
	int databytes;
	struct usb_cpia *ucpia = (struct usb_cpia *)privdata;
	struct usb_device *udev = ucpia->dev;

	if (!udev) {
		DBG("Internal driver error: udev is NULL\n");
		return -EINVAL;
	}

	if (!command) {
		DBG("Internal driver error: command is NULL\n");
		return -EINVAL;
	}

	databytes = (((int)command[7])<<8) | command[6];

	if (command[0] == DATA_IN) {
		u8 buffer[8];

		if (!data) {
			DBG("Internal driver error: data is NULL\n");
			return -EINVAL;
		}

		err = ReadPacket(udev, command, buffer, 8);
		if (err < 0)
			return err;

		memcpy(data, buffer, databytes);
	} else if(command[0] == DATA_OUT)
		WritePacket(udev, command, data, databytes);
	else {
		DBG("Unexpected first byte of command: %x\n", command[0]);
		err = -EINVAL;
	}

	return 0;
}
Exemplo n.º 7
0
static void HandleDelayedPackets()
{
  AVPacket pkt;

  while (true)
  {
    PreparePacket(&pkt);
    int got_packet;
    int error = ReceivePacket(s_codec_context, &pkt, &got_packet);
    if (error)
    {
      ERROR_LOG(VIDEO, "Error while stopping video: %d", error);
      break;
    }

    if (!got_packet)
      break;

    WritePacket(pkt);
  }
}
Exemplo n.º 8
0
/**
 * This function send packet
 */
static jdwpTransportError JNICALL 
TCPIPSocketTran_WritePacket(jdwpTransportEnv* env, const jdwpPacket* packet)
{

    if (packet == 0) {
        SetLastTranError(env, "packet is 0", 0);
        return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
    }

    SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket;
    if (envClientSocket == INVALID_SOCKET) {
        SetLastTranError(env, "there isn't an open connection to a debugger", 0);
        LeaveCriticalSendSection(env);
        return JDWPTRANSPORT_ERROR_ILLEGAL_STATE;
    }

    EnterCriticalSendSection(env);
    jdwpTransportError err = WritePacket(env, envClientSocket, packet);
    LeaveCriticalSendSection(env);
    return err;
} //TCPIPSocketTran_WritePacket
Exemplo n.º 9
0
int UserClient::_CmdLOUT( OmniPacket *packet )
{
	int errCode = ERROR_OK;
	map<string, UserClient*>::iterator iter = mHashMap.find( mUserID );
	if( iter == mHashMap.end() )
	{
		gLog.log("No user info");
	}
	else
	{
		mHashMap.erase( iter );
	}

	DumpMap();

	char ret[BUFLEN];
	bzero( ret, BUFLEN );
	sprintf( ret, "LOUT %lu %d 0\r\n", packet->mTrid, errCode );
	WritePacket( ret, strlen(ret) );

	EventChannel::EventCallback( (struct bufferevent*)buffer_event, 0, this );
	return errCode;
}
Exemplo n.º 10
0
void interrupt NetISR (void)
{
	if (doomcom.command == CMD_SEND)
	{
//I_ColorBlack (0,0,63);
		WritePacket ((char *)&doomcom.data, doomcom.datalength);
	}
	else if (doomcom.command == CMD_GET)
	{
//I_ColorBlack (63,63,0);

		if (ReadPacket () && packetlen <= sizeof(doomcom.data) )
		{
			doomcom.remotenode = 1;
			doomcom.datalength = packetlen;
			memcpy (&doomcom.data, &packet, packetlen);
		}
		else
			doomcom.remotenode = -1;

	}
//I_ColorBlack (0,0,0);
}
Exemplo n.º 11
0
BOOL KPcapFileRecorder::Record( 
	TCHAR *szFileName,
	PROTO_TYPE pt,
	PACKET_DIR dir,
	ULONG uLocalIp,
	USHORT uLocalPort,
	ULONG uRemoteIP,
	USHORT uRemotePort,
	PVOID pData, 
	ULONG uDataLen )
{
	BOOL bResult = FALSE;
	PVOID pBuffer = NULL;
	ULONG uPackSize = 0;
	
	switch( pt )
	{
	case enumPT_TCP:
		{
			uPackSize = MakeTcpPacket( dir, uLocalIp, uLocalPort, uRemoteIP, uRemotePort, pData, uDataLen, &pBuffer );
		}
		break;
	case enumPT_UDP:
		{
			uPackSize = MakeUdpPacket( dir, uLocalIp, uLocalPort, uRemoteIP, uRemotePort, pData, uDataLen, &pBuffer );
		}
		break;
	}
	
	if( uPackSize )
	{
		bResult = WritePacket( szFileName, pBuffer, uPackSize );
		free( pBuffer );
		pBuffer = NULL;
	}
	return bResult;
}
Exemplo n.º 12
0
void CHCEmulator::VendorSpecificDebugCompleteEvent(TUint16 aOpCode, const TDesC8& aRemainderBuf)
	{
	ClearPacket();
	
	//  Just send back the payload we got in Vendor Specific Command. This is used by
	//  the tproxy HCIProxy test program, to be found in HCIProxy's directory.

	const TUint KFixedParamSize = 3;
	const TUint KMaxUserParamSize  = 255 - KFixedParamSize;
	TUint userParamSize = (aRemainderBuf.Length() < KMaxUserParamSize) ?
						   aRemainderBuf.Length() : KMaxUserParamSize;

	PutBytes(KHCIUARTEventHeader);
	PutBytes(KHCICommandCompleteEventCode);
	PutBytes(KFixedParamSize + userParamSize);
	PutBytes(1);	// numPackets
	PutBytes(aOpCode, 2);
	for (int i = 0; i < userParamSize; i++)
		PutBytes(aRemainderBuf[i]);

	iConsole.Printf(_L("Sending C.C.E (opcode VendorSpecificDebug), user param size %d...\n"),
					userParamSize);
	WritePacket();
	}
Exemplo n.º 13
0
	void ClientSession::H_New_Search_Session(const boost::system::error_code& error ,
            SearchProtoMessage msg,char * content_buf_ptr)
	{
		if (!error)
		{
		//根据任务类型创建新的session,然后再继续监听接下来的连接的请求
            string  path = _WriteToFile_(content_buf_ptr, _pic_len_) ; 
            LOG(INFO)<<"ClientSession :: file path "<<path; 
			SearchSession * session = g_session_manager->CreateSession<SearchSession>( msg , path ,GetSessionID());
            if(content_buf_ptr != NULL)
            {
                delete []content_buf_ptr;
                content_buf_ptr = NULL;
            }
            session->Start();
            WritePacket();
		}
		else
		{
            LOG(ERROR)<< "ClientSession :: Read file content Error"<<error.message();
			g_session_manager->Recycle(GetSessionID());
		}

	}
Exemplo n.º 14
0
int UserClient::_CmdLSIN( OmniPacket *packet )
{
	char userid[NODELEN];
	char passwd[NODELEN];
	int errCode = ERROR_OK;

	PARSE_TAG_INIT( packet->mHeader );
	PARSE_TAG_NEXT( packet->mHeader, userid );
	PARSE_TAG_NEXT( packet->mHeader, passwd );
	gLog.log("userid[%s] passwd[%s]", userid, passwd );

	if( errCode == 0 )
	{
		strcpy( mUserID, userid );
		mHashMap.insert( pair<const char*, UserClient*>(userid, this) );
	}
	DumpMap();

	char ret[BUFLEN];
	bzero( ret, BUFLEN );
	sprintf( ret, "LSIN %lu %d 0\r\n", packet->mTrid, errCode );
	WritePacket( ret, strlen(ret) );
	return errCode;
}
Exemplo n.º 15
0
void handle_event(int fd, short, void *v)
{
  bool success;

  size_t index = (size_t) v;
  Assert(index < connections.Size());

  ConnectData *cdata = connections[index];
  Assert(cdata->live);

  if (cdata->write_buf.size != 0) {
    success = WritePacket(fd, &cdata->write_buf);
    if (success) {
      cdata->write_buf.base = NULL;
      cdata->write_buf.pos = NULL;
      cdata->write_buf.size = 0;
    }
  }
  else {
    size_t length = cdata->read_buf.pos - cdata->read_buf.base;

    success = ReadPacket(fd, &cdata->read_buf);
    if (success) {
      size_t data_length =
        cdata->read_buf.pos - cdata->read_buf.base - UINT32_LENGTH;
      Buffer transaction_buf(cdata->read_buf.base + UINT32_LENGTH,
                             data_length);

      Transaction *t = new Transaction();
      if (!t->Read(&transaction_buf)) {
        logout << "ERROR: Corrupt packet data" << endl;
        delete t;
        return;
      }

      handling_transaction = true;
      t->Execute();

      cdata->read_buf.pos = cdata->read_buf.base;
      cdata->read_buf.Ensure(UINT32_LENGTH);
      cdata->read_buf.pos += UINT32_LENGTH;
      t->WriteResult(&cdata->read_buf);

      cdata->write_buf.base = cdata->read_buf.base;
      cdata->write_buf.pos = cdata->write_buf.base;
      cdata->write_buf.size = cdata->read_buf.pos - cdata->read_buf.base;

      cdata->read_buf.pos = cdata->read_buf.base;

      success = WritePacket(fd, &cdata->write_buf);
      if (success) {
        cdata->write_buf.base = NULL;
        cdata->write_buf.pos = NULL;
        cdata->write_buf.size = 0;
      }

      // watch for initial and final transactions.

      if (t->IsInitial()) {
        Assert(!spawn_count.IsSpecified());
        received_initial++;
      }

      if (t->IsFinal()) {
        Assert(received_final < received_initial);
        received_final++;
        if (received_final == received_initial) {
          // this was the last client, so cleanup and exit.
          logout << "Final transaction received, finishing..."
                 << endl << flush;
          close(server_socket);

          ClearBlockCaches();
          ClearMemoryCaches();
          AnalysisFinish(0);
        }
      }

      delete t;
      handling_transaction = false;
    }
    else if ((ssize_t) length == cdata->read_buf.pos - cdata->read_buf.base) {
      // connection is closed. there is nothing to read so remove the event.
      event_del(&cdata->ev);
      close(cdata->fd);

      cdata->live = false;
      cdata->read_buf.Reset(0);
      cdata->write_buf.Reset(0);
    }
  }
}
Exemplo n.º 16
0
void EQStream::Write(int eq_fd)
{
queue<EQProtocolPacket *> ReadyToSend;
bool SeqEmpty=false,NonSeqEmpty=false;
deque<EQProtocolPacket *>::iterator sitr;

	// Check our rate to make sure we can send more
	MRate.lock();
	int32 threshold=RateThreshold;
	MRate.unlock();
	if (BytesWritten > threshold) {
		//cout << "Over threshold: " << BytesWritten << " > " << threshold << endl;
		return;
	}

	// If we got more packets to we need to ack, send an ack on the highest one
	MAcks.lock();
	if (CompareSequence(LastAckSent, NextAckToSend) == SeqFuture)
		SendAck(NextAckToSend);
	MAcks.unlock();

	// Lock the outbound queues while we process
	MOutboundQueue.lock();

	// Place to hold the base packet t combine into
	EQProtocolPacket *p=NULL;

#ifdef RETRANSMITS
	// if we have a timeout defined and we have not received an ack recently enough, retransmit from beginning of queue
	if (RuleR(EQStream, RetransmitTimeoutMult) && !SequencedQueue.empty() && NextSequencedSend && (GetState()==ESTABLISHED) && ((retransmittimer+retransmittimeout) < Timer::GetCurrentTime())) {
		_log(NET__NET_TRACE, _L "Timeout since last ack received, starting retransmit at the start of our unacked buffer (seq %d, was %d)." __L, SequencedBase, SequencedBase+NextSequencedSend);
		NextSequencedSend = 0;
		retransmittimer = Timer::GetCurrentTime(); // don't want to endlessly retransmit the first packet
	}
#endif

	// Find the next sequenced packet to send from the "queue"
	sitr = SequencedQueue.begin();
	if (sitr!=SequencedQueue.end())
	sitr += NextSequencedSend;
	
	// Loop until both are empty or MaxSends is reached
	while(!SeqEmpty || !NonSeqEmpty)  {

		// See if there are more non-sequenced packets left
		if (!NonSequencedQueue.empty()) {
			if (!p) {
				// If we don't have a packet to try to combine into, use this one as the base
				// And remove it form the queue
				p = NonSequencedQueue.front();
				_log(NET__NET_COMBINE, _L "Starting combined packet with non-seq packet of len %d" __L, p->size);
				NonSequencedQueue.pop();
			} else if (!p->combine(NonSequencedQueue.front())) {
				// Tryint to combine this packet with the base didn't work (too big maybe)
				// So just send the base packet (we'll try this packet again later)
				_log(NET__NET_COMBINE, _L "Combined packet full at len %d, next non-seq packet is len %d" __L, p->size, (NonSequencedQueue.front())->size);
				ReadyToSend.push(p);
				BytesWritten+=p->size;
				p=NULL;
				
				if (BytesWritten > threshold) {
					// Sent enough this round, lets stop to be fair
					_log(NET__RATES, _L "Exceeded write threshold in nonseq (%d > %d)" __L, BytesWritten, threshold);
					break;
				}
			} else {
				// Combine worked, so just remove this packet and it's spot in the queue
				_log(NET__NET_COMBINE, _L "Combined non-seq packet of len %d, yeilding %d combined." __L, (NonSequencedQueue.front())->size, p->size);
				delete NonSequencedQueue.front();
				NonSequencedQueue.pop();
			}
		} else {
			// No more non-sequenced packets
			NonSeqEmpty=true;
		}

		if (sitr!=SequencedQueue.end()) {
//_log(NET__NET_COMBINE, _L "Send Seq with %d seq packets starting at seq %d, next send %d, and %d non-seq packets." __L, 
//	SequencedQueue.size(), SequencedBase, NextSequencedSend, NonSequencedQueue.size());
if(uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
	_log(NET__ERROR, _L "Pre-Send Seq NSS=%d Invalid Sequenced queue: BS %d + SQ %d != NOS %d" __L, NextSequencedSend, SequencedBase, SequencedQueue.size(), NextOutSeq);
}
if(NextSequencedSend > SequencedQueue.size()) {
	_log(NET__ERROR, _L "Pre-Send Next Send Sequence is beyond the end of the queue NSS %d > SQ %d" __L, NextSequencedSend, SequencedQueue.size());
}
			uint16 seq_send = SequencedBase + NextSequencedSend;	//just for logging...
if(SequencedQueue.empty()) {
_log(NET__ERROR, _L "Tried to write a packet with an empty queue (%d is past next out %d)" __L, seq_send, NextOutSeq);
SeqEmpty=true;
continue;
}
/*if(CompareSequence(NextOutSeq, seq_send) == SeqFuture) {
_log(NET__ERROR, _L "Tried to write a packet beyond the end of the queue! (%d is past next out %d)" __L, seq_send, NextOutSeq);
sitr=SequencedQueue.end();
continue;
}*/
#ifdef RETRANSMITS
			if (!RuleB(EQStream, RetransmitAckedPackets) && (*sitr)->acked) {
				_log(NET__NET_TRACE, _L "Not retransmitting seq packet %d because already marked as acked" __L, seq_send);
				sitr++;
				NextSequencedSend++;
			} else if (!p) {
#else
			if (!p) {
#endif
				// If we don't have a packet to try to combine into, use this one as the base
				// Copy it first as it will still live until it is acked
				p=(*sitr)->Copy();
				_log(NET__NET_COMBINE, _L "Starting combined packet with seq packet %d of len %d" __L, seq_send, p->size);
				sitr++;
				NextSequencedSend++;
			} else if (!p->combine(*sitr)) {
				// Trying to combine this packet with the base didn't work (too big maybe)
				// So just send the base packet (we'll try this packet again later)
				_log(NET__NET_COMBINE, _L "Combined packet full at len %d, next seq packet %d is len %d" __L, p->size, seq_send, (*sitr)->size);
				ReadyToSend.push(p);
				BytesWritten+=p->size;
				p=NULL;

				if (BytesWritten > threshold) {
					// Sent enough this round, lets stop to be fair
					_log(NET__RATES, _L "Exceeded write threshold in seq (%d > %d)" __L, BytesWritten, threshold);
					break;
				}
			} else {
				// Combine worked
				_log(NET__NET_COMBINE, _L "Combined seq packet %d of len %d, yeilding %d combined." __L, seq_send, (*sitr)->size, p->size);
				sitr++;
				NextSequencedSend++;
			}
if(uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
	_log(NET__ERROR, _L "Post send Invalid Sequenced queue: BS %d + SQ %d != NOS %d" __L, SequencedBase, SequencedQueue.size(), NextOutSeq);
}
if(NextSequencedSend > SequencedQueue.size()) {
	_log(NET__ERROR, _L "Post send Next Send Sequence is beyond the end of the queue NSS %d > SQ %d" __L, NextSequencedSend, SequencedQueue.size());
}
		} else {
			// No more sequenced packets
			SeqEmpty=true;
		}
	}
	// Unlock the queue
	MOutboundQueue.unlock();

	// We have a packet still, must have run out of both seq and non-seq, so send it
	if (p) {
		_log(NET__NET_COMBINE, _L "Final combined packet not full, len %d" __L, p->size);
		ReadyToSend.push(p);
		BytesWritten+=p->size;
	}

	// Send all the packets we "made"
	while(!ReadyToSend.empty()) {
		p = ReadyToSend.front();
		WritePacket(eq_fd,p);
		delete p;
		ReadyToSend.pop();
	}
	
	//see if we need to send our disconnect and finish our close
	if(SeqEmpty && NonSeqEmpty) {
		//no more data to send
		if(CheckState(CLOSING)) {
			_log(NET__DEBUG, _L "All outgoing data flushed, closing stream." __L );
			//we are waiting for the queues to empty, now we can do our disconnect.
			//this packet will not actually go out until the next call to Write().
			_SendDisconnect();
			SetState(DISCONNECTING);
		}
	}
}

void EQStream::WritePacket(int eq_fd, EQProtocolPacket *p)
{
uint32 length;
sockaddr_in address;
	address.sin_family = AF_INET;
	address.sin_addr.s_addr=remote_ip;
	address.sin_port=remote_port;
#ifdef NOWAY
	uint32 ip=address.sin_addr.s_addr;
	cout << "Sending to: " 
		<< (int)*(unsigned char *)&ip
		<< "." << (int)*((unsigned char *)&ip+1)
		<< "." << (int)*((unsigned char *)&ip+2)
		<< "." << (int)*((unsigned char *)&ip+3)
		<< "," << (int)ntohs(address.sin_port) << "(" << p->size << ")" << endl;

	p->DumpRaw();
	cout << "-------------" << endl;
#endif
	length=p->serialize(buffer);
	if (p->opcode!=OP_SessionRequest && p->opcode!=OP_SessionResponse) {
		if (compressed) {
			uint32 newlen=EQProtocolPacket::Compress(buffer,length, _tempBuffer, 2048);
			memcpy(buffer,_tempBuffer,newlen);
			length=newlen;
		}
		if (encoded) {
			EQProtocolPacket::ChatEncode(buffer,length,Key);
		}

		*(uint16 *)(buffer+length)=htons(CRC16(buffer,length,Key));
		length+=2;
	}
	//dump_message_column(buffer,length,"Writer: ");
	sendto(eq_fd,(char *)buffer,length,0,(sockaddr *)&address,sizeof(address));
	AddBytesSent(length);
}
Exemplo n.º 17
0
void AVIDump::AddFrame(const u8* data, int width, int height, int stride, const Frame& state)
{
  // Assume that the timing is valid, if the savestate id of the new frame
  // doesn't match the last one.
  if (state.savestate_index != s_last_savestate_index)
  {
    s_last_savestate_index = state.savestate_index;
    s_last_frame_is_valid = false;
  }

  CheckResolution(width, height);
  s_src_frame->data[0] = const_cast<u8*>(data);
  s_src_frame->linesize[0] = stride;
  s_src_frame->format = s_pix_fmt;
  s_src_frame->width = s_width;
  s_src_frame->height = s_height;

  // Convert image from {BGR24, RGBA} to desired pixel format
  s_sws_context =
      sws_getCachedContext(s_sws_context, width, height, s_pix_fmt, s_width, s_height,
                           s_codec_context->pix_fmt, SWS_BICUBIC, nullptr, nullptr, nullptr);
  if (s_sws_context)
  {
    sws_scale(s_sws_context, s_src_frame->data, s_src_frame->linesize, 0, height,
              s_scaled_frame->data, s_scaled_frame->linesize);
  }

  // Encode and write the image.
  AVPacket pkt;
  PreparePacket(&pkt);
  int got_packet = 0;
  int error = 0;
  u64 delta;
  s64 last_pts;
  // Check to see if the first frame being dumped is the first frame of output from the emulator.
  // This prevents an issue with starting dumping later in emulation from placing the frames
  // incorrectly.
  if (!s_last_frame_is_valid)
  {
    s_last_frame = state.ticks;
    s_last_frame_is_valid = true;
  }
  if (!s_start_dumping && state.first_frame)
  {
    delta = state.ticks;
    last_pts = AV_NOPTS_VALUE;
    s_start_dumping = true;
  }
  else
  {
    delta = state.ticks - s_last_frame;
    last_pts = (s_last_pts * s_codec_context->time_base.den) / state.ticks_per_second;
  }
  u64 pts_in_ticks = s_last_pts + delta;
  s_scaled_frame->pts = (pts_in_ticks * s_codec_context->time_base.den) / state.ticks_per_second;
  if (s_scaled_frame->pts != last_pts)
  {
    s_last_frame = state.ticks;
    s_last_pts = pts_in_ticks;
    error = SendFrameAndReceivePacket(s_codec_context, &pkt, s_scaled_frame, &got_packet);
  }
  if (!error && got_packet)
  {
    WritePacket(pkt);
  }
  if (error)
    ERROR_LOG(VIDEO, "Error while encoding video: %d", error);
}
Exemplo n.º 18
0
void CHCEmulator::BuildAndWriteCommandPacket(TPacketType aType, TUint16 aOpcode, TUint8 aError)
/**
	For 'easy' packets
**/
	{
	iPacket.Zero();

	TUint8 numpackets = 1;					// <--- adjustable

	switch (aType)
		{
		case ECommandStatusEvent:
			{
			PutBytes(KHCIUARTEventHeader);
			PutBytes(KHCICommandStatusEventCode);
			PutBytes(KHCICommandStatusEventLength);
			PutBytes(aError);
			PutBytes(numpackets);
			PutBytes(aOpcode,2);
			break;
			}
		case ECommandCompleteEvent:
			{
			switch (aOpcode)
				{
				case KReadBufferSizeOpcode:
					{
					PutBytes(KHCIUARTEventHeader);
					PutBytes(KHCICommandCompleteEventCode);
					PutBytes(KHCIReadBufferSizeCommandCompleteEventLength);
					PutBytes(numpackets);
					PutBytes(aOpcode,2);
					PutBytes(aError);
					PutBytes(KEmulatedHCSizeACLBuffers,2);
					PutBytes(KEmulatedHCSizeSCOBuffers,1);
					PutBytes(KEmulatedHCNumberACLBuffers,2);
					PutBytes(KEmulatedHCNumberSCOBuffers,2);
					break;
					}
				case KReadBdaddrOpcode:
					{
					PutBytes(KHCIUARTEventHeader);
					PutBytes(KHCICommandCompleteEventCode);
					PutBytes(KHCIReadBdaddrCommandCompleteEventLength);
					PutBytes(numpackets);
					PutBytes(aOpcode,2);
					PutBytes(aError);
					PutAddress(KEmulatedHCAddress);
					break;
					}
				case KReadLocalNameOpcode:
					{
					PutBytes(KHCIUARTEventHeader);
					PutBytes(KHCICommandCompleteEventCode);
					PutBytes(KHCIReadLocalNameCommandCompleteEventLength);
					PutBytes(numpackets);
					PutBytes(aOpcode,2);
					PutBytes(aError);
					PutName(iLocalName);
					break;
					}
				case KResetOpcode:
				case KSetHostControllerToHostFlowOpcode:
				case KWritePageTimeoutOpcode:
				case KHostBufferSizeOpcode:
				case KWriteScanEnableOpcode:
				case KWriteConnectionAcceptTimeoutOpcode:
				case KChangeLocalNameOpcode:
				case KInquiryCancelOpcode:
				case KWriteVoiceSettingOpcode:
				case KWriteCurrentIACLAPOpcode:
				case KSetEventMaskOpcode:
				case KNopOpcode:
					{
					PutBytes(KHCIUARTEventHeader);
					PutBytes(KHCICommandCompleteEventCode);
					PutBytes(KHCIDefaultCommandCompleteEventLength);
					PutBytes(numpackets);
					PutBytes(aOpcode,2);
					PutBytes(aError);
					}
					break;
					
				case KReadLocalSupportedFeaturesOpcode:
					{
					PutBytes(KHCIUARTEventHeader);
					PutBytes(KHCICommandCompleteEventCode);
					PutBytes(KHCIReadLocalSupportedFeaturesLength);
					PutBytes(numpackets);
					PutBytes(aOpcode,2);
					PutBytes(aError);
					PutBytes(KEmulatedLocalSupportedFeatures1,4);
					PutBytes(KEmulatedLocalSupportedFeatures2,4);
					}
					break;
					
				case KReadLocalVersionInfoOpcode:
					{
					PutBytes(KHCIUARTEventHeader);
					PutBytes(KHCICommandCompleteEventCode);
					PutBytes(KHCIReadLocalVersionInformationLength);
					PutBytes(numpackets);
					PutBytes(aOpcode,2);
					PutBytes(aError);
					PutBytes(KEmulatedLocalVersion1,4);
					PutBytes(KEmulatedLocalVersion2,4);
					}
					break;
					
				case KReadClassOfDeviceOpcode:
					{
					PutBytes(KHCIUARTEventHeader);
					PutBytes(KHCICommandCompleteEventCode);
					PutBytes(KHCIReadCoDLength);
					PutBytes(numpackets);
					PutBytes(aOpcode,2);
					PutBytes(aError);
					PutBytes(KEmulatedCoD,3);	
					}
					break;
					
				}
			break;
			}
		}
	WritePacket();
	}
Exemplo n.º 19
0
void EQStream::Write(int eq_fd)
{
	std::queue<EQProtocolPacket *> ReadyToSend;
	bool SeqEmpty=false, NonSeqEmpty=false;
	std::deque<EQProtocolPacket *>::iterator sitr;

	// Check our rate to make sure we can send more
	MRate.lock();
	int32 threshold=RateThreshold;
	MRate.unlock();
	if (BytesWritten > threshold) {
		return;
	}

	// If we got more packets to we need to ack, send an ack on the highest one
	MAcks.lock();
	if (CompareSequence(LastAckSent, NextAckToSend) == SeqFuture)
		SendAck(NextAckToSend);
	MAcks.unlock();

	// Lock the outbound queues while we process
	MOutboundQueue.lock();

	// Place to hold the base packet t combine into
	EQProtocolPacket *p=nullptr;

	if(GetExecutablePlatform() == ExePlatformWorld || GetExecutablePlatform() == ExePlatformZone) {
		// if we have a timeout defined and we have not received an ack recently enough, retransmit from beginning of queue
		if (RETRANSMIT_TIMEOUT_MULT && !SequencedQueue.empty() && NextSequencedSend &&
			(GetState()==ESTABLISHED) && ((retransmittimer+retransmittimeout) < Timer::GetCurrentTime())) {
			Log.Out(Logs::Detail, Logs::Netcode, _L "Timeout since last ack received, starting retransmit at the start of our unacked "
				"buffer (seq %d, was %d)." __L, SequencedBase, SequencedBase+NextSequencedSend);
			NextSequencedSend = 0;
			retransmittimer = Timer::GetCurrentTime(); // don't want to endlessly retransmit the first packet
		}
	}

	// Find the next sequenced packet to send from the "queue"
	sitr = SequencedQueue.begin();
	if (sitr!=SequencedQueue.end())
	sitr += NextSequencedSend;

	// Loop until both are empty or MaxSends is reached
	while(!SeqEmpty || !NonSeqEmpty) {

		// See if there are more non-sequenced packets left
		if (!NonSequencedQueue.empty()) {
			if (!p) {
				// If we don't have a packet to try to combine into, use this one as the base
				// And remove it form the queue
				p = NonSequencedQueue.front();
				Log.Out(Logs::Detail, Logs::Netcode, _L "Starting combined packet with non-seq packet of len %d" __L, p->size);
				NonSequencedQueue.pop();
			} else if (!p->combine(NonSequencedQueue.front())) {
				// Tryint to combine this packet with the base didn't work (too big maybe)
				// So just send the base packet (we'll try this packet again later)
				Log.Out(Logs::Detail, Logs::Netcode, _L "Combined packet full at len %d, next non-seq packet is len %d" __L, p->size, (NonSequencedQueue.front())->size);
				ReadyToSend.push(p);
				BytesWritten+=p->size;
				p=nullptr;

				if (BytesWritten > threshold) {
					// Sent enough this round, lets stop to be fair
					Log.Out(Logs::Detail, Logs::Netcode, _L "Exceeded write threshold in nonseq (%d > %d)" __L, BytesWritten, threshold);
					break;
				}
			} else {
				// Combine worked, so just remove this packet and it's spot in the queue
				Log.Out(Logs::Detail, Logs::Netcode, _L "Combined non-seq packet of len %d, yeilding %d combined." __L, (NonSequencedQueue.front())->size, p->size);
				delete NonSequencedQueue.front();
				NonSequencedQueue.pop();
			}
		} else {
			// No more non-sequenced packets
			NonSeqEmpty=true;
		}

		if (sitr!=SequencedQueue.end()) {
			if(uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
				Log.Out(Logs::Detail, Logs::Netcode, _L "Pre-Send Seq NSS=%d Invalid Sequenced queue: BS %d + SQ %d != NOS %d" __L, NextSequencedSend, SequencedBase, SequencedQueue.size(), NextOutSeq);
			}

			if(NextSequencedSend > SequencedQueue.size()) {
				Log.Out(Logs::Detail, Logs::Netcode, _L "Pre-Send Next Send Sequence is beyond the end of the queue NSS %d > SQ %d" __L, NextSequencedSend, SequencedQueue.size());
			}
			uint16 seq_send = SequencedBase + NextSequencedSend;	//just for logging...
			
			if(SequencedQueue.empty()) {
				Log.Out(Logs::Detail, Logs::Netcode, _L "Tried to write a packet with an empty queue (%d is past next out %d)" __L, seq_send, NextOutSeq);
				SeqEmpty=true;
				continue;
			}

			if(GetExecutablePlatform() == ExePlatformWorld || GetExecutablePlatform() == ExePlatformZone) {
				if (!RETRANSMIT_ACKED_PACKETS && (*sitr)->acked) {
					Log.Out(Logs::Detail, Logs::Netcode, _L "Not retransmitting seq packet %d because already marked as acked" __L, seq_send);
					sitr++;
					NextSequencedSend++;
				} else if (!p) {
					// If we don't have a packet to try to combine into, use this one as the base
					// Copy it first as it will still live until it is acked
					p=(*sitr)->Copy();
					Log.Out(Logs::Detail, Logs::Netcode, _L "Starting combined packet with seq packet %d of len %d" __L, seq_send, p->size);
					++sitr;
					NextSequencedSend++;
				} else if (!p->combine(*sitr)) {
					// Trying to combine this packet with the base didn't work (too big maybe)
					// So just send the base packet (we'll try this packet again later)
					Log.Out(Logs::Detail, Logs::Netcode, _L "Combined packet full at len %d, next seq packet %d is len %d" __L, p->size, seq_send, (*sitr)->size);
					ReadyToSend.push(p);
					BytesWritten+=p->size;
					p=nullptr;

					if (BytesWritten > threshold) {
						// Sent enough this round, lets stop to be fair
						Log.Out(Logs::Detail, Logs::Netcode, _L "Exceeded write threshold in seq (%d > %d)" __L, BytesWritten, threshold);
						break;
					}
				} else {
					// Combine worked
					Log.Out(Logs::Detail, Logs::Netcode, _L "Combined seq packet %d of len %d, yeilding %d combined." __L, seq_send, (*sitr)->size, p->size);
					++sitr;
					NextSequencedSend++;
				}
			} else {
				if (!p) {
					// If we don't have a packet to try to combine into, use this one as the base
					// Copy it first as it will still live until it is acked
					p=(*sitr)->Copy();
					Log.Out(Logs::Detail, Logs::Netcode, _L "Starting combined packet with seq packet %d of len %d" __L, seq_send, p->size);
					++sitr;
					NextSequencedSend++;
				} else if (!p->combine(*sitr)) {
					// Trying to combine this packet with the base didn't work (too big maybe)
					// So just send the base packet (we'll try this packet again later)
					Log.Out(Logs::Detail, Logs::Netcode, _L "Combined packet full at len %d, next seq packet %d is len %d" __L, p->size, seq_send, (*sitr)->size);
					ReadyToSend.push(p);
					BytesWritten+=p->size;
					p=nullptr;

					if (BytesWritten > threshold) {
						// Sent enough this round, lets stop to be fair
						Log.Out(Logs::Detail, Logs::Netcode, _L "Exceeded write threshold in seq (%d > %d)" __L, BytesWritten, threshold);
						break;
					}
				} else {
					// Combine worked
					Log.Out(Logs::Detail, Logs::Netcode, _L "Combined seq packet %d of len %d, yeilding %d combined." __L, seq_send, (*sitr)->size, p->size);
					++sitr;
					NextSequencedSend++;
				}
			}

			if(uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
				Log.Out(Logs::Detail, Logs::Netcode, _L "Post send Invalid Sequenced queue: BS %d + SQ %d != NOS %d" __L, SequencedBase, SequencedQueue.size(), NextOutSeq);
			}
			if(NextSequencedSend > SequencedQueue.size()) {
				Log.Out(Logs::Detail, Logs::Netcode, _L "Post send Next Send Sequence is beyond the end of the queue NSS %d > SQ %d" __L, NextSequencedSend, SequencedQueue.size());
			}
		} else {
			// No more sequenced packets
			SeqEmpty=true;
		}
	}
	// Unlock the queue
	MOutboundQueue.unlock();

	// We have a packet still, must have run out of both seq and non-seq, so send it
	if (p) {
		Log.Out(Logs::Detail, Logs::Netcode, _L "Final combined packet not full, len %d" __L, p->size);
		ReadyToSend.push(p);
		BytesWritten+=p->size;
	}

	// Send all the packets we "made"
	while(!ReadyToSend.empty()) {
		p = ReadyToSend.front();
		WritePacket(eq_fd,p);
		delete p;
		ReadyToSend.pop();
	}

	//see if we need to send our disconnect and finish our close
	if(SeqEmpty && NonSeqEmpty) {
		//no more data to send
		if(CheckState(CLOSING)) {
			Log.Out(Logs::Detail, Logs::Netcode, _L "All outgoing data flushed, closing stream." __L );
			//we are waiting for the queues to empty, now we can do our disconnect.
			//this packet will not actually go out until the next call to Write().
			_SendDisconnect();
			SetState(DISCONNECTING);
		}
	}
}
Exemplo n.º 20
0
void CG2Packet::WritePacket(CG2Packet* pPacket)
{
	if ( pPacket == NULL ) return;
	WritePacket( pPacket->m_nType, pPacket->m_nLength, pPacket->m_bCompound );
	Write( pPacket->m_pBuffer, pPacket->m_nLength );
}
Exemplo n.º 21
0
void Connect (void)
{
	struct time	time;
	int			oldsec;
	int			localstage, remotestage;
	char		str[20];
	char		idstr[7];
	char		remoteidstr[7];
	unsigned long		idnum;
	int			i;
	
//
// wait for a good packet
//
	printf (STR_ATTEMPT"\n");

//
// build a (hopefully) unique id string by hashing up the current milliseconds
// and the interrupt table
//
	if (CheckParm ("-player1"))
		idnum = 0;
	else if (CheckParm ("-player2"))
		idnum = 999999;
	else
	{
		gettime (&time);
		idnum = time.ti_sec*100+time.ti_hund;
		for (i=0 ; i<512 ; i++)
			idnum += ((unsigned far *)0)[i];
		idnum %= 1000000;
	}
	
	idstr[0] = '0' + idnum/ 100000l;
	idnum -= (idstr[0]-'0')*100000l;
	idstr[1] = '0' + idnum/ 10000l;
	idnum -= (idstr[1]-'0')*10000l;
	idstr[2] = '0' + idnum/ 1000l;
	idnum -= (idstr[2]-'0')*1000l;
	idstr[3] = '0' + idnum/ 100l;
	idnum -= (idstr[3]-'0')*100l;
	idstr[4] = '0' + idnum/ 10l;
	idnum -= (idstr[4]-'0')*10l;
	idstr[5] = '0' + idnum;
	idstr[6] = 0;
	
//
// sit in a loop until things are worked out
//
// the packet is:  ID000000_0
// the first field is the idnum, the second is the acknowledge stage
// ack stage starts out 0, is bumped to 1 after the other computer's id
// is known, and is bumped to 2 after the other computer has raised to 1
//
	oldsec = -1;
	localstage = remotestage = 0;

	do
	{
		while ( bioskey(1) )
		{
			if ( (bioskey (0) & 0xff) == 27)
				Error ("\n\n"STR_NETABORT);
		}

		if (ReadPacket ())
		{
			packet[packetlen] = 0;
			printf ("read : %s\n",packet);
			if (packetlen != 10)
				continue;
			if (strncmp(packet,"ID",2) )
				continue;
			if (!strncmp (packet+2,idstr,6))
				Error ("\n\n"STR_DUPLICATE);
			strncpy (remoteidstr,packet+2,6);
				
			remotestage = packet[9] - '0';
			localstage = remotestage+1;
			oldsec = -1;
		}

		gettime (&time);
		if (time.ti_sec != oldsec)
		{
			oldsec = time.ti_sec;
			sprintf (str,"ID%s_%i",idstr,localstage);
			WritePacket (str,strlen(str));
			printf ("wrote: %s\n",str);
		}

	} while (localstage < 2);

//
// decide who is who
//
	if (strcmp(remoteidstr,idstr) > 0)
		doomcom.consoleplayer = 0;
	else
		doomcom.consoleplayer = 1;
	

//
// flush out any extras
//
	while (ReadPacket ())
	;
}