1
0
mirror of https://github.com/danog/libtgvoip.git synced 2024-12-02 09:37:52 +01:00
libtgvoip/PacketReassembler.cpp

92 lines
2.3 KiB
C++
Raw Normal View History

2018-06-04 21:37:43 +02:00
//
// Created by Grishka on 19.03.2018.
//
#include "PacketReassembler.h"
#include "logging.h"
#include <assert.h>
2018-06-04 21:37:43 +02:00
using namespace tgvoip;
PacketReassembler::PacketReassembler(){
}
PacketReassembler::~PacketReassembler(){
}
void PacketReassembler::Reset(){
}
2019-02-05 12:41:00 +01:00
void PacketReassembler::AddFragment(Buffer pkt, unsigned int fragmentIndex, unsigned int fragmentCount, uint32_t pts, bool keyframe){
for(Packet& packet:packets){
if(packet.timestamp==pts){
if(fragmentCount!=packet.partCount){
LOGE("Received fragment total count %u inconsistent with previous %u", fragmentCount, packet.partCount);
return;
}
packet.AddFragment(std::move(pkt), fragmentIndex);
return;
}
2019-02-05 12:41:00 +01:00
}
if(pts<maxTimestamp){
LOGW("Received fragment doesn't belong here (ts=%u < maxTs=%u)", pts, maxTimestamp);
2019-02-05 12:41:00 +01:00
return;
}
if(fragmentIndex>=fragmentCount){
LOGE("Received fragment index %u is out of bounds %u", fragmentIndex, fragmentCount);
return;
}
if(fragmentCount>255){
LOGE("Received fragment total count too big %u", fragmentCount);
return;
}
maxTimestamp=std::max(maxTimestamp, pts);
2019-02-05 12:41:00 +01:00
Packet packet(fragmentCount);
packet.timestamp=pts;
packet.isKeyframe=keyframe;
packet.receivedPartCount=0;
packet.AddFragment(std::move(pkt), fragmentIndex);
packets.push_back(std::move(packet));
while(packets.size()>3){
Packet&& old=std::move(packets[0]);
packets.erase(packets.begin());
if(old.receivedPartCount==old.partCount){
Buffer buffer=old.Reassemble();
callback(std::move(buffer), old.timestamp, old.isKeyframe);
//LOGV("Packet %u reassembled", old.timestamp);
}else{
LOGW("Packet %u not reassembled (%u of %u)", old.timestamp, old.receivedPartCount, old.partCount);
}
}
}
2018-06-04 21:37:43 +02:00
2019-02-05 12:41:00 +01:00
void PacketReassembler::SetCallback(std::function<void(Buffer packet, uint32_t pts, bool keyframe)> callback){
this->callback=callback;
2018-06-04 21:37:43 +02:00
}
void PacketReassembler::Packet::AddFragment(Buffer pkt, uint32_t fragmentIndex){
//LOGV("Add fragment %u/%u to packet %u", fragmentIndex, partCount, timestamp);
parts[fragmentIndex]=std::move(pkt);
receivedPartCount++;
}
Buffer PacketReassembler::Packet::Reassemble(){
if(partCount==1){
return std::move(parts[0]);
}
BufferOutputStream out(10240);
for(unsigned int i=0;i<partCount;i++){
out.WriteBytes(parts[i]);
parts[i]=Buffer();
}
return Buffer(std::move(out));
}