Пример #1
0
void Room::RoomImpl::BroadcastRoomInformation() {
    Packet packet;
    packet << static_cast<u8>(IdRoomInformation);
    packet << room_information.name;
    packet << room_information.member_slots;
    packet << room_information.uid;
    packet << room_information.port;
    packet << room_information.preferred_game;

    packet << static_cast<u32>(members.size());
    {
        std::lock_guard<std::mutex> lock(member_mutex);
        for (const auto& member : members) {
            packet << member.nickname;
            packet << member.mac_address;
            packet << member.game_info.name;
            packet << member.game_info.id;
        }
    }

    ENetPacket* enet_packet =
        enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
    enet_host_broadcast(server, 0, enet_packet);
    enet_host_flush(server);
}
Пример #2
0
int main()
{
	// Security header
	byte* header = new byte[4];
	header = "HEAD";
	// Protocol ID
	CS_Protocol protocol = CS_Protocol::JOIN_GAME;
	// Data
	byte* data = "My_serialized_packet_data";
	// Create a new Packet
	Packet* packet = new Packet(header, protocol, data);

	std::cout << "Packet Protocol: " << std::endl;
	std::cout << packet->GetProtocolID() << std::endl;

	std::cout << "Packet Data Length: " << std::endl;
	std::cout << packet->GetDataLength() << std::endl;

	std::cout << "Packet Data: " << std::endl;
	std::cout << packet->GetData() << std::endl << std::endl;

	std::cout << "Packet Payload: " << std::endl;
	std::cout << packet->GetPayload() << std::endl << std::endl;

	std::cout << "Changed Packet Data: " << std::endl;
	byte* newData = "This data was changed by packet->SetData();";
	packet->SetData(newData);
	// Use GetPayload() to return serialized data ready for the networking stream.
	std::cout << packet->GetPayload();
	for (;;){}
}
Пример #3
0
void CPacketQueue::Add(CAutoPtr<Packet> p)
{
	CAutoLock cAutoLock(this);

	if(p)
	{
		m_size += p->GetDataSize();

		if(p->bAppendable && !p->bDiscontinuity && !p->pmt
		&& p->rtStart == Packet::INVALID_TIME
		&& !IsEmpty() && GetTail()->rtStart != Packet::INVALID_TIME)
		{
			Packet* tail = GetTail();			
			int oldsize = tail->GetCount();
			int newsize = tail->GetCount() + p->GetCount();
			tail->SetCount(newsize, max(1024, newsize)); // doubles the reserved buffer size
			memcpy(tail->GetData() + oldsize, p->GetData(), p->GetCount());
			/*
			GetTail()->Append(*p); // too slow
			*/
			return;
		}
	}

	AddTail(p);
}
Пример #4
0
HRESULT CStreamParser::ParsePlanarPCM(Packet *pPacket)
{
  CMediaType mt = m_pPin->GetActiveMediaType();

  WORD nChannels = 0, nBPS = 0, nBlockAlign = 0;
  audioFormatTypeHandler(mt.Format(), mt.FormatType(), nullptr, &nChannels, &nBPS, &nBlockAlign, nullptr);

  // Mono needs no special handling
  if (nChannels == 1)
    return Queue(pPacket);

  Packet *out = new Packet();
  out->CopyProperties(pPacket);
  out->SetDataSize(pPacket->GetDataSize());

  int nBytesPerChannel = nBPS / 8;
  int nAudioBlocks = pPacket->GetDataSize() / nChannels;
  BYTE *out_data = out->GetData();
  const BYTE *in_data = pPacket->GetData();

  for (int i = 0; i < nAudioBlocks; i += nBytesPerChannel) {
    // interleave the channels into audio blocks
    for (int c = 0; c < nChannels; c++) {
      memcpy(out_data + (c * nBytesPerChannel), in_data + (nAudioBlocks * c), nBytesPerChannel);
    }
    // Skip to the next output block
    out_data += nChannels * nBytesPerChannel;

    // skip to the next input sample
    in_data += nBytesPerChannel;
  }

  return Queue(out);
}
Пример #5
0
void Room::RoomImpl::SendWrongPassword(ENetPeer* client) {
    Packet packet;
    packet << static_cast<u8>(IdWrongPassword);

    ENetPacket* enet_packet =
        enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
    enet_peer_send(client, 0, enet_packet);
    enet_host_flush(server);
}
Пример #6
0
void Room::RoomImpl::SendJoinSuccess(ENetPeer* client, MacAddress mac_address) {
    Packet packet;
    packet << static_cast<u8>(IdJoinSuccess);
    packet << mac_address;
    ENetPacket* enet_packet =
        enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
    enet_peer_send(client, 0, enet_packet);
    enet_host_flush(server);
}
Пример #7
0
void Room::RoomImpl::SendVersionMismatch(ENetPeer* client) {
    Packet packet;
    packet << static_cast<u8>(IdVersionMismatch);
    packet << network_version;

    ENetPacket* enet_packet =
        enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
    enet_peer_send(client, 0, enet_packet);
    enet_host_flush(server);
}
Пример #8
0
	unsigned int Miner::GetHeight(int nTimeout)
	{
		Packet* packet = new Packet();
		packet->SetHeader((unsigned char)GET_HEIGHT);
		this->WritePacket(packet);
		delete(packet);
			
		Packet RESPONSE = ReadNextPacket(nTimeout);
			
		if(RESPONSE.IsNull())
			return 0;
				
		if(RESPONSE.GetData().size() == 0)
		{
			return 0;
		}

		unsigned int nHeight = bytes2uint(RESPONSE.GetData());
		ResetPacket();
			
		return nHeight;
	}
Пример #9
0
void Room::RoomImpl::SendModBanListResponse(ENetPeer* client) {
    Packet packet;
    packet << static_cast<u8>(IdModBanListResponse);
    {
        std::lock_guard lock(ban_list_mutex);
        packet << username_ban_list;
        packet << ip_ban_list;
    }

    ENetPacket* enet_packet =
        enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
    enet_peer_send(client, 0, enet_packet);
    enet_host_flush(server);
}
Пример #10
0
  void HTTP::HandlePacket(Packet& p)
  {
    String got;
    got.assign(p.GetData(), p.GetSize());
    LOG(got);

    //handle request, close connection after handling
    String response = HandleRequest(got);
    auto foundIt = m_connections.find(p.GetAddress());
    if(foundIt != m_connections.end())
      foundIt->second.sock->Send(response.c_str(), response.size());
    else
      ERR("where did the connection go!?!?");
  }
Пример #11
0
void Room::RoomImpl::SendCloseMessage() {
    Packet packet;
    packet << static_cast<u8>(IdCloseRoom);
    std::lock_guard<std::mutex> lock(member_mutex);
    if (!members.empty()) {
        ENetPacket* enet_packet =
            enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
        for (auto& member : members) {
            enet_peer_send(member.peer, 0, enet_packet);
        }
    }
    enet_host_flush(server);
    for (auto& member : members) {
        enet_peer_disconnect(member.peer, 0);
    }
}
Пример #12
0
	Core::CBlock* Miner::GetBlock(int nTimeout)
	{
		Packet* packet = new Packet();
		packet->SetHeader(GET_BLOCK);
		this->WritePacket(packet);
		delete(packet);	


		Packet RESPONSE = ReadNextPacket(nTimeout);
			
		if(RESPONSE.IsNull())
			return NULL;
		Core::CBlock* BLOCK = DeserializeBlock(RESPONSE.GetData());
		ResetPacket();
			
		return BLOCK;
	}
Пример #13
0
void Room::RoomImpl::SendStatusMessage(StatusMessageTypes type, const std::string& nickname,
                                       const std::string& username) {
    Packet packet;
    packet << static_cast<u8>(IdStatusMessage);
    packet << static_cast<u8>(type);
    packet << nickname;
    packet << username;
    std::lock_guard lock(member_mutex);
    if (!members.empty()) {
        ENetPacket* enet_packet =
            enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
        for (auto& member : members) {
            enet_peer_send(member.peer, 0, enet_packet);
        }
    }
    enet_host_flush(server);
}
Пример #14
0
void CAudioPin::JoinAudioBuffers(Packet* pBuffer, CDeMultiplexer* pDemuxer)
{
  if (pBuffer->pmt)
  {
    // Currently only uncompressed PCM audio is supported
    if (pBuffer->pmt->subtype == MEDIASUBTYPE_PCM)
    {
      //LogDebug("aud: Joinig Audio Buffers");
      WAVEFORMATEXTENSIBLE* wfe = (WAVEFORMATEXTENSIBLE*)pBuffer->pmt->pbFormat;
      WAVEFORMATEX* wf = (WAVEFORMATEX*)wfe;

      // Assuming all packets in the stream are the same size
      int packetSize = pBuffer->GetDataSize();

      int maxDurationInBytes = wf->nAvgBytesPerSec / 10; // max 100 ms buffer

      while (true)
      {
        if ((MAX_BUFFER_SIZE - pBuffer->GetDataSize() >= packetSize ) && 
            (maxDurationInBytes >= pBuffer->GetDataSize() + packetSize))
        {
          Packet* buf = pDemuxer->GetAudio(pBuffer->nPlaylist,pBuffer->nClipNumber);
          if (buf)
          {
            byte* data = buf->GetData();
            // Skip LPCM header when copying the next buffer
            pBuffer->SetCount(pBuffer->GetDataSize() + buf->GetDataSize() - LPCM_HEADER_SIZE);
            memcpy(pBuffer->GetData()+pBuffer->GetDataSize() - (buf->GetDataSize() - LPCM_HEADER_SIZE), &data[LPCM_HEADER_SIZE], buf->GetDataSize() - LPCM_HEADER_SIZE);
            delete buf;
          }
          else
          {
            // No new buffer was available in the demuxer
            break;
          }
        }
        else
        {
          // buffer limit reached
          break;
        }
      }
    }
  }
}
Пример #15
0
////////////////////////////////////////////////////////////
/// Send a packet of data to the host (must be connected first)
////////////////////////////////////////////////////////////
Socket::Status SocketTCP::Send(Packet& PacketToSend)
{
    // Let the packet do custom stuff before sending it
    PacketToSend.OnSend();

    // First send the packet size
    Uint32 PacketSize = htonl(PacketToSend.GetDataSize());
    Send(reinterpret_cast<const char*>(&PacketSize), sizeof(PacketSize));

    // Send the packet data
    if (PacketSize > 0)
    {
        return Send(PacketToSend.GetData(), PacketToSend.GetDataSize());
    }
    else
    {
        return Socket::Done;
    }
}
Пример #16
0
bool CProtocolComm::SendResponseFrame(DWORD dwRequestPacketID, Packet &packet)
{
    Packet packet_remain;
    if (WaitPopLast(0, packet_remain))
    {
        WARNING("sendResponseFrame queue get test");
        // 如果是之前请求包的重发,则立即返回结果,否则丢弃结果包
        if (packet_remain.GetPacketID() != dwRequestPacketID)
        {
            // 丢弃返回包
            WARNING("sendResponseFrame queue find diff id packet");
            // 重新放入队列,等待处理
            m_queue.Push(packet_remain);
            return false;
        }
    }

    return SendFrame(packet.GetSrcAddr(), packet.GetDestAddr(),
                     packet.GetType(), packet.GetFunction(),
                     packet.GetData(), packet.GetDataLen(), false);
}
Пример #17
0
	unsigned char Miner::SubmitBlock(uint512 hashMerkleRoot, unsigned long long nNonce, int nTimeout)
	{
		Packet* PACKET = new Packet();
		PACKET->SetHeader(SUBMIT_BLOCK);
			
		PACKET->SetData(hashMerkleRoot.GetBytes());
		std::vector<unsigned char> NONCE  = uint2bytes64(nNonce);
			
		std::vector<unsigned char> pckt = PACKET->GetData();
		pckt.insert(pckt.end(), NONCE.begin(), NONCE.end());
		PACKET->SetData(pckt);
		PACKET->SetLength(72);
			
		this->WritePacket(PACKET);
		delete(PACKET);

		Packet RESPONSE = ReadNextPacket(nTimeout);
		if(RESPONSE.IsNull())
			return 0;
			
		ResetPacket();
			
		return RESPONSE.GetHeader();
	}
Пример #18
0
Packet* cRPCCommandHandler::getResponse(const Packet* pck)
{
	Packet resp;

	if(!m_sock)
	{
		error_log("Socket error for Cluster %s:%u",m_addr,m_port);
		return NULL;
	}

	if(m_sock->Connect(m_port,m_addr) != 0)
	{
		error_log("Connect to Cluster %s:%u failed for RPC",m_addr,m_port);
		return NULL;
	}
	
	m_sock->SetBlocking(true);

	if(m_sock->Send((Packet&)*pck) != 0)
	{
		error_log("Sending Packet to Cluster %s:%u failed for RPC",m_addr,m_port);
		return NULL;
	}

	if(m_sock->Receive(resp) != 0)
	{
		error_log("Receiving Packet forum Cluster %s:%u fail on RPC",m_addr,m_port);
		return NULL;
	}

	Packet* resp_ = new Packet();
	for(uint32 i=0;i<pck->GetDataSize();i++)
		*resp_ << uint8(resp.GetData()[i]);
	m_sock->Close();
	return resp_;
}
Пример #19
0
bool PacketBuffer::PacketVaild()
{
    if (size() > 0)
    {
        //DEBUG("recv: %d", size());
        //DEBUG_HEX(raw(), size());
        Packet *pPacket = (Packet *)raw();
        // check length
        if (size() >= Packet::PACKET_MINLEN &&
            size() >= pPacket->GetPacketLen())
        {
            // check checksum and packet end
            WORD wCRC = __le16_to_cpu(*(WORD *)&(pPacket->GetData()[pPacket->GetDataLen()]));
            WORD wCalCRC = pPacket->CheckSUM(&pPacket->m_btAddr, pPacket->GetPacketLen()-2);
            if (wCRC == wCalCRC)
            {
                DEBUG("recv: %d", size());
                DEBUG_HEX(raw(), size());
                return true;
            }
            ERROR("serialport packet checksum wrong calc:%04x recv:%04X", wCalCRC, wCRC);
            DEBUG_HEX(raw(), size());
        }
        else
        {
            return false;
        }

        // throw exception
        throw(Packet::EXCEPTION_PACKET);
    }
    else
    {
        return false;
    }
}
Пример #20
0
bool SV_ReturnCharacter(ServerConnection* conn, Packet& pack)
{
    uint8_t packet_id;
    pack >> packet_id;

    if(packet_id != 0xCF) return false;

    uint32_t p_size;
    uint32_t p_id1, p_id2, p_loglen, p_chrlen;
    pack >> p_size >> p_id1 >> p_id2 >> p_loglen >> p_chrlen;
    if(!p_chrlen)
    {
        Printf(LOG_Error, "[SV] Received NULL character from server ID %u!\n", conn->ID);
        return true;
    }

    char* p_logname_c = new char[p_loglen + 1];
    p_logname_c[p_loglen] = 0;
    char* p_chrdata = new char[p_chrlen];
    pack.GetData((uint8_t*)p_chrdata, p_chrlen);
    pack.GetData((uint8_t*)p_logname_c, p_loglen);
    std::string p_logname(p_logname_c);
    delete[] p_logname_c;

    CCharacter chr;
    BinaryStream bs;
    std::vector<uint8_t>& bsb = bs.GetBuffer();
    for(uint32_t i = 0; i < p_chrlen; i++)
        bsb.push_back(p_chrdata[i]);

    delete[] p_chrdata;

    if(!chr.LoadFromStream(bs))
    {
        Printf(LOG_Error, "[SV] Received bad character from server ID %u!\n", conn->ID);
        return true;
    }

    if(!Login_Exists(p_logname))
    {
        Printf(LOG_Error, "[SV] Received character \"%s\" for non-existent login \"%s\" from server ID %u!\n", chr.Nick.c_str(), p_logname.c_str(), conn->ID);
        delete[] p_chrdata;
        return true;
    }

    bool sent_s = true;

    if(!Login_CharExists(p_logname, chr.Id1, chr.Id2, true))
    {
        if (conn->Parent->Info.GameMode == GAMEMODE_Softcore)
            chr.HatId = Config::HatIDSoftcore;
        else if (conn->Parent->Info.GameMode == GAMEMODE_Sandbox)
            chr.HatId = Config::HatIDSandbox;
        else chr.HatId = Config::HatID;
    }

    bool should_unlock = true;
    bool should_save = true;
    if(should_save && ((chr.Id2 & 0x3F000000) != 0x3F000000))
    {
        int srvHatId;
        if (conn->Parent->Info.GameMode == GAMEMODE_Softcore)
            srvHatId = Config::HatIDSoftcore;
        else if (conn->Parent->Info.GameMode == GAMEMODE_Sandbox)
            srvHatId = Config::HatIDSandbox;
        else srvHatId = Config::HatID;

        bool server_nosaving = ((conn->Parent->Info.ServerMode & SVF_NOSAVING) == SVF_NOSAVING);

        if(server_nosaving)
        {
            should_save = false;
            Printf(LOG_Trivial, "[SV] Not saving login \"%s\" (SVG_NOSAVING is set, flags %08X).\n", p_logname.c_str(), conn->Parent->Info.ServerMode);
        }
        else if(conn->Parent->Info.GameMode == GAMEMODE_Arena)
        {
            should_save = false;
            Printf(LOG_Trivial, "[SV] Not saving login \"%s\" (Arena).\n", p_logname.c_str());
        }
        else if(chr.HatId != srvHatId)
        {
            //should_save = false;
            //Printf(LOG_Trivial, "[SV] Not saving login \"%s\" (chr.HatId==%d != srvHatId==%d; GameMode=%d)\n", chr.HatId, srvHatId, conn->Parent->Info.GameMode);
            Printf(LOG_Error, "[SV] Server ID %u sent login \"%s\" with bad HatID (chr.HatId==%d != srvHatId==%d; GameMode==%d); saving with srvHatId.\n",
                conn->ID, p_logname.c_str(), chr.HatId, srvHatId, conn->Parent->Info.GameMode);
            chr.HatId = srvHatId;
        }
    }

    BinaryStream obs;
    if(!chr.SaveToStream(obs))
    {
        Printf(LOG_Error, "[SV] Internal error: unable to save A2C for character \"%s\", login \"%s\" from server ID %u!\n", chr.Nick.c_str(), p_logname.c_str(), conn->ID);
        return true;
    }

    std::vector<uint8_t>& obsb = obs.GetBuffer();
    p_chrdata = new char[obsb.size()];
    for(uint32_t i = 0; i < obsb.size(); i++)
        p_chrdata[i] = obsb[i];
    p_chrlen = obsb.size();

    bool p__locked_hat, p__locked;
    unsigned long p__id1, p__id2, p__srvid;

    if(!Login_GetLocked(p_logname, p__locked_hat, p__locked, p__id1, p__id2, p__srvid))
    {
        Printf(LOG_Error, "[DB] Error: Login_GetLocked(\"%s\", ..., ..., ..., ...).\n", p_logname.c_str());
        return true;
    }

    if(p__locked_hat)
    {
        Printf(LOG_Error, "[SV] Warning: server tried to return character for hat-locked login \"%s\".\n", p_logname.c_str());
        should_save = false;
        should_unlock = false;
    }
    else if(!p__locked)
    {
        Printf(LOG_Error, "[SV] Warning: server tried to return character for unlocked login \"%s\".\n", p_logname.c_str());
        should_save = false;
        should_unlock = false;
    }
    else if(p__id1 != p_id1 || p__id2 != p_id2)
    {
        Printf(LOG_Error, "[SV] Warning: server tried to return different character (%u:%u as opposed to locked %u:%u).\n", p_id1, p_id2, p__id1, p__id2);
        should_save = false;
        should_unlock = false;
    }
    else if(p__srvid != conn->ID)
    {
        Printf(LOG_Error, "[SV] Warning: server tried to return character while not owning it!\n");
        should_save = false;
        should_unlock = false;
    }

    if(should_save && !Login_SetCharacter(p_logname, p_id1, p_id2, p_chrlen, p_chrdata, chr.Nick))
        Printf(LOG_Error, "[DB] Error: Login_SetCharacter(\"%s\", %u, %u, %u, %08X, \"%s\").\n", p_logname.c_str(), p_id1, p_id2, p_chrlen, p_chrdata, chr.Nick.c_str());
    else
    {
        Printf(LOG_Info, "[SV] Received character \"%s\" for login \"%s\" from server ID %u.\n", chr.Nick.c_str(), p_logname.c_str(), conn->ID);
        sent_s = SVCMD_ReceivedCharacter(conn, p_logname);
        should_unlock = true;
    }

    if(should_unlock) Login_SetLocked(p_logname, false, false, 0, 0, 0); // character left the server, so unlock it
    //conn->Parent->Layer->
    if(conn->Parent->Info.ServerCaps & SERVER_CAP_DETAILED_INFO)
    {
        for(size_t i = 0; i < conn->Parent->Info.Locked.size(); i++)
        {
            if(conn->Parent->Info.Locked[i] == p_logname)
            {
                conn->Parent->Info.Locked.erase(conn->Parent->Info.Locked.begin()+i);
                i--;
            }
        }
    }


    delete[] p_chrdata;
    return sent_s;
}
Пример #21
0
HRESULT CVideoPin::FillBuffer(IMediaSample* pSample)
{
  try
  {
    Packet* buffer = NULL;

    do
    {
      if (m_pFilter->IsStopping() || m_demux.IsMediaChanging() || m_bFlushing || !m_bSeekDone || m_demux.m_bRebuildOngoing)
      {
        Sleep(1);
        return ERROR_NO_DATA;
      }

      if (m_demux.EndOfFile())
      {
        LogDebug("vid: set EOF");
        return S_FALSE;
      }

      if (m_demux.m_bVideoClipSeen || m_demux.m_bAudioRequiresRebuild && !m_demux.m_bVideoClipSeen && !m_demux.m_eAudioClipSeen->Check())
      {
        CheckPlaybackState();
        return ERROR_NO_DATA;
      }

      if (m_pCachedBuffer)
      {
        LogDebug("vid: cached fetch %6.3f clip: %d playlist: %d", m_pCachedBuffer->rtStart / 10000000.0, m_pCachedBuffer->nClipNumber, m_pCachedBuffer->nPlaylist);
        buffer = m_pCachedBuffer;
        m_pCachedBuffer = NULL;
        buffer->bDiscontinuity = true;
        
        if (m_bProvidePMT)
        {
          CMediaType mt(*buffer->pmt);
          SetMediaType(&mt);
          pSample->SetMediaType(&mt);
          m_bProvidePMT = false;
        }
      }
      else
        buffer = m_demux.GetVideo();

      if (!buffer)
      {
        if (m_bFirstSample)
          Sleep(10);
        else 
        {
          if (!m_bClipEndingNotified)
          {
            // Deliver end of stream notification to flush the video decoder.
            // This should only happen when the stream enters into paused state
            LogDebug("vid: FillBuffer - DeliverEndOfStream");
            DeliverEndOfStream();
            m_bClipEndingNotified = true;
          }
          else
            Sleep(10);
		  
          return ERROR_NO_DATA;
        }
      }
      else
      {
        bool checkPlaybackState = false;

        {
          CAutoLock lock(m_section);

          if (buffer->nNewSegment > 0)
          {
            if ((buffer->nNewSegment & NS_NEW_CLIP) == NS_NEW_CLIP)
            {
              LogDebug("vid: Playlist changed to %d - nNewSegment: %d offset: %6.3f rtStart: %6.3f rtPlaylistTime: %6.3f", 
                buffer->nPlaylist, buffer->nNewSegment, buffer->rtOffset / 10000000.0, buffer->rtStart / 10000000.0, buffer->rtPlaylistTime / 10000000.0);
            
              m_demux.m_bVideoClipSeen = true;
 
              m_bInitDuration = true;
              checkPlaybackState = true;
              m_bClipEndingNotified = false;

              if (buffer->bResuming || buffer->nNewSegment & NS_INTERRUPTED)
              {
                m_bDoFakeSeek = true;
                m_rtStreamOffset = buffer->rtPlaylistTime;
                m_bZeroTimeStream = true;
                m_demux.m_bAudioResetStreamPosition = true;
              }
              else
                m_rtStreamOffset = 0;

              // LAV video decoder requires an end of stream notification to be able to provide complete video frames
              // to downstream filters in a case where we are waiting for the audio pin to see the clip boundary as
              // we cannot provide yet the next clip's PMT downstream since audio stream could require a rebuild
              if (m_currentDecoder == CLSID_LAVVideo && (buffer->nNewSegment & NS_NEW_PLAYLIST))
              {
                LogDebug("DeliverEndOFStream LAV Only for audio pin wait (%d,%d)", buffer->nPlaylist, buffer->nClipNumber);
                DeliverEndOfStream();
              }
            }
            if ((buffer->nNewSegment & NS_STREAM_RESET) == NS_STREAM_RESET)
              m_bInitDuration = true;
          }

          if (buffer->pmt)
          {
            GUID subtype = subtype = buffer->pmt->subtype;

            if (buffer->pmt->subtype == FOURCCMap('1CVW') && m_VC1Override != GUID_NULL)
            {
              buffer->pmt->subtype = m_VC1Override;
              LogDebug("vid: FillBuffer - force VC-1 GUID");
            }

            if (!CompareMediaTypes(buffer->pmt, &m_mt))
            {
              LogMediaType(buffer->pmt);
            
              HRESULT hrAccept = S_FALSE;
              m_bProvidePMT = true;

              if (m_pReceiver && CheckVideoFormat(&buffer->pmt->subtype, &m_currentDecoder))
              {
                // Currently no other video decoders than LAV seems to be compatible with
                // the dynamic format changes
                if (m_currentDecoder == CLSID_LAVVideo)
                hrAccept = m_pReceiver->QueryAccept(buffer->pmt);
              }

              if (hrAccept != S_OK)
              {
                CMediaType mt(*buffer->pmt);
                SetMediaType(&mt);

                LogDebug("vid: graph rebuilding required");

                m_demux.m_bVideoRequiresRebuild = true;
                m_bZeroTimeStream = true;
                checkPlaybackState = true;

                //LogDebug("DeliverEndOFStream for rebuild (%d,%d)", buffer->nPlaylist, buffer->nClipNumber);
                //DeliverEndOfStream();
              }
              else
              {
                LogDebug("vid: format change accepted");
                CMediaType mt(*buffer->pmt);
                SetMediaType(&mt);
                pSample->SetMediaType(&mt);

                buffer->nNewSegment = 0;
                m_pCachedBuffer = buffer;
				
                //if (m_currentDecoder == CLSID_LAVVideo)
                //{
                //  LogDebug("DeliverEndOFStream LAV Only (%d,%d)", buffer->nPlaylist, buffer->nClipNumber);
                //  DeliverEndOfStream();
                //}

                return ERROR_NO_DATA;
              }
            } // comparemediatypes
          }
        } // lock ends

        m_rtTitleDuration = buffer->rtTitleDuration;

        if (checkPlaybackState)
        {
          buffer->nNewSegment = 0;
          m_pCachedBuffer = buffer;

          CheckPlaybackState();

          LogDebug("vid: cached push  %6.3f clip: %d playlist: %d", m_pCachedBuffer->rtStart / 10000000.0, m_pCachedBuffer->nClipNumber, m_pCachedBuffer->nPlaylist);

          return ERROR_NO_DATA;
        }

        bool hasTimestamp = buffer->rtStart != Packet::INVALID_TIME;
        REFERENCE_TIME rtCorrectedStartTime = 0;
        REFERENCE_TIME rtCorrectedStopTime = 0;

        if (hasTimestamp)
        {
          if (m_bZeroTimeStream)
          {
            m_rtStreamTimeOffset = buffer->rtStart - buffer->rtClipStartTime;
            m_bZeroTimeStream = false;
          }

          if (m_bDiscontinuity || buffer->bDiscontinuity)
          {
            LogDebug("vid: set discontinuity");
            pSample->SetDiscontinuity(true);
            pSample->SetMediaType(buffer->pmt);
            m_bDiscontinuity = false;
          }

          rtCorrectedStartTime = buffer->rtStart - m_rtStreamTimeOffset;
          rtCorrectedStopTime = buffer->rtStop - m_rtStreamTimeOffset;

          pSample->SetTime(&rtCorrectedStartTime, &rtCorrectedStopTime);

          if (m_bInitDuration)
          {
            m_pFilter->SetTitleDuration(m_rtTitleDuration);
            m_pFilter->ResetPlaybackOffset(buffer->rtPlaylistTime - rtCorrectedStartTime);
            m_bInitDuration = false;
          }

          m_pFilter->OnPlaybackPositionChange();
        }
        else // Buffer has no timestamp
          pSample->SetTime(NULL, NULL);

        pSample->SetSyncPoint(buffer->bSyncPoint);

        {
          CAutoLock lock(&m_csDeliver);

          if (!m_bFlushing)
          {
            BYTE* pSampleBuffer;
            pSample->SetActualDataLength(buffer->GetDataSize());
            pSample->GetPointer(&pSampleBuffer);
            memcpy(pSampleBuffer, buffer->GetData(), buffer->GetDataSize());

            m_bFirstSample = false;

#ifdef LOG_VIDEO_PIN_SAMPLES
            LogDebug("vid: %6.3f corr %6.3f playlist time %6.3f clip: %d playlist: %d size: %d", buffer->rtStart / 10000000.0, rtCorrectedStartTime / 10000000.0, 
              buffer->rtPlaylistTime / 10000000.0, buffer->nClipNumber, buffer->nPlaylist, buffer->GetCount());
#endif
          }
          else
          {
            LogDebug("vid: dropped sample as flush is active!");
            return ERROR_NO_DATA;
          }
        }

        //static int iFrameNumber = 0;
        //LogMediaSample(pSample, iFrameNumber++);

        delete buffer;
      }
    } while (!buffer);
    return NOERROR;
  }

  catch(...)
  {
    LogDebug("vid: FillBuffer exception");
  }

  return S_OK;
}
Пример #22
0
HRESULT CStreamParser::ParseH264AnnexB(Packet *pPacket)
{
  if (!m_pPacketBuffer) {
    m_pPacketBuffer = InitPacket(pPacket);
  }

  m_pPacketBuffer->Append(pPacket);

  BYTE *start = m_pPacketBuffer->GetData();
  BYTE *end = start + m_pPacketBuffer->GetDataSize();

  MOVE_TO_H264_START_CODE(start, end);

  while(start <= end-4) {
    BYTE *next = start + 1;

    MOVE_TO_H264_START_CODE(next, end);

    // End of buffer reached
    if(next >= end-4) {
      break;
    }

    size_t size = next - start;

    CH264Nalu Nalu;
    Nalu.SetBuffer(start, (int)size, 0);

    Packet *p2 = NULL;

    while (Nalu.ReadNext()) {
      Packet *p3 = new Packet();
      p3->SetDataSize(Nalu.GetDataLength() + 4);

      // Write size of the NALU (Big Endian)
      AV_WB32(p3->GetData(), (uint32_t)Nalu.GetDataLength());
      memcpy(p3->GetData() + 4, Nalu.GetDataBuffer(), Nalu.GetDataLength());

      if (!p2) {
        p2 = p3;
      } else {
        p2->Append(p3);
        SAFE_DELETE(p3);
      }
    }

    if (!p2)
      break;

    p2->StreamId = m_pPacketBuffer->StreamId;
    p2->bDiscontinuity = m_pPacketBuffer->bDiscontinuity;
    m_pPacketBuffer->bDiscontinuity = FALSE;

    p2->bSyncPoint = m_pPacketBuffer->bSyncPoint;
    m_pPacketBuffer->bSyncPoint = FALSE;

    p2->rtStart = m_pPacketBuffer->rtStart;
    m_pPacketBuffer->rtStart = Packet::INVALID_TIME;
    p2->rtStop = m_pPacketBuffer->rtStop;
    m_pPacketBuffer->rtStop = Packet::INVALID_TIME;

    p2->pmt = m_pPacketBuffer->pmt;
    m_pPacketBuffer->pmt = NULL;

    m_queue.Queue(p2);

    if(pPacket->rtStart != Packet::INVALID_TIME) {
      m_pPacketBuffer->rtStart = pPacket->rtStart;
      m_pPacketBuffer->rtStop = pPacket->rtStop;
      pPacket->rtStart = Packet::INVALID_TIME;
    }
    if(pPacket->bDiscontinuity) {
      m_pPacketBuffer->bDiscontinuity = pPacket->bDiscontinuity;
      pPacket->bDiscontinuity = FALSE;
    }
    if(pPacket->bSyncPoint) {
      m_pPacketBuffer->bSyncPoint = pPacket->bSyncPoint;
      pPacket->bSyncPoint = FALSE;
    }
    if(m_pPacketBuffer->pmt) {
      DeleteMediaType(m_pPacketBuffer->pmt);
    }

    m_pPacketBuffer->pmt = pPacket->pmt;
    pPacket->pmt = NULL;

    start = next;
  }

  if(start > m_pPacketBuffer->GetData()) {
    m_pPacketBuffer->RemoveHead(start - m_pPacketBuffer->GetData());
  }

  SAFE_DELETE(pPacket);

  do {
    pPacket = NULL;

    REFERENCE_TIME rtStart = Packet::INVALID_TIME, rtStop = rtStart = Packet::INVALID_TIME;

    std::deque<Packet *>::iterator it;
    for (it = m_queue.GetQueue()->begin(); it != m_queue.GetQueue()->end(); ++it) {
      // Skip the first
      if (it == m_queue.GetQueue()->begin()) {
        continue;
      }

      Packet *p = *it;
      BYTE* pData = p->GetData();

      if((pData[4]&0x1f) == 0x09) {
        m_bHasAccessUnitDelimiters = true;
      }

      if ((pData[4]&0x1f) == 0x09 || (!m_bHasAccessUnitDelimiters && p->rtStart != Packet::INVALID_TIME)) {
        pPacket = p;
        if (p->rtStart == Packet::INVALID_TIME && rtStart != Packet::INVALID_TIME) {
          p->rtStart = rtStart;
          p->rtStop = rtStop;
        }
        break;
      }

      if (rtStart == Packet::INVALID_TIME) {
        rtStart = p->rtStart;
        rtStop = p->rtStop;
      }
    }

    if (pPacket) {
      Packet *p = m_queue.Get();
      Packet *p2 = NULL;
      while ((p2 = m_queue.Get()) != pPacket) {
        p->Append(p2);
        SAFE_DELETE(p2);
      }
      // Return
      m_queue.GetQueue()->push_front(pPacket);

      Queue(p);
    }
  } while (pPacket != NULL);

  return S_OK;
}
Пример #23
0
bool CProtocolComm::SendFrame(Packet &packet)
{
    return SendFrame(packet.GetSrcAddr(), packet.GetDestAddr(),
                     packet.GetType(), packet.GetFunction(),
                     packet.GetData(), packet.GetDataLen());
}
Пример #24
0
	void Client::SendPacket(Packet &packet)
	{
		ENetPacket *enetPacket = enet_packet_create(packet.GetData(), packet.GetLength(), ENET_PACKET_FLAG_RELIABLE);
		enet_peer_send(_peer, 0, enetPacket);
	}