| 6 |
| #include "logging.h" |
| 7 |
| 8 | #include <assert.h> |
| 9 |
| 10 | using namespace tgvoip; |
| 11 |
| 12 | PacketReassembler::PacketReassembler(){ |
| 13 |
| 14 | } |
| 15 |
| 16 | PacketReassembler::~PacketReassembler(){ |
| 17 |
| 18 | } |
| 19 |
| 20 | void PacketReassembler::Reset(){ |
| 21 |
| 22 | } |
| 23 |
| 24 | void PacketReassembler::AddFragment(Buffer pkt, unsigned int fragmentIndex, unsigned int fragmentCount, uint32_t pts, bool keyframe, uint16_t rotation){ |
| 25 | for(Packet& packet:packets){ |
| 26 | if(packet.timestamp==pts){ |
| 27 | if(fragmentCount!=packet.partCount){ |
| 28 | LOGE("Received fragment total count %u inconsistent with previous %u", fragmentCount, packet.partCount); |
| 29 | return; |
| 30 | } |
| 31 | packet.AddFragment(std::move(pkt), fragmentIndex); |
| 32 | return; |
| 33 | } |
| 34 | } |
| 35 |
| 36 | if(pts<maxTimestamp){ |
| 37 | LOGW("Received fragment doesn't belong here (ts=%u < maxTs=%u)", pts, maxTimestamp); |
| 38 | return; |
| 39 | } |
| 40 | if(fragmentIndex>=fragmentCount){ |
| 41 | LOGE("Received fragment index %u is out of bounds %u", fragmentIndex, fragmentCount); |
| 42 | return; |
| 43 | } |
| 44 | if(fragmentCount>255){ |
| 45 | LOGE("Received fragment total count too big %u", fragmentCount); |
| 46 | return; |
| 47 | } |
| 48 |
| 49 | maxTimestamp=std::max(maxTimestamp, pts); |
| 50 |
| 51 | Packet packet(fragmentCount); |
| 52 | packet.timestamp=pts; |
| 53 | packet.isKeyframe=keyframe; |
| 54 | packet.receivedPartCount=0; |
| 55 | packet.rotation=rotation; |
| 56 | packet.AddFragment(std::move(pkt), fragmentIndex); |
| 57 |
| 58 | packets.push_back(std::move(packet)); |
| 59 | while(packets.size()>3){ |
| 60 | Packet&& old=std::move(packets[0]); |
| 61 | packets.erase(packets.begin()); |
| 62 | if(old.receivedPartCount==old.partCount){ |
| 63 | Buffer buffer=old.Reassemble(); |
| 64 | callback(std::move(buffer), old.timestamp, old.isKeyframe, old.rotation); |
| 65 | //LOGV("Packet %u reassembled", old.timestamp); |
| 66 | }else{ |
| 67 | LOGW("Packet %u not reassembled (%u of %u)", old.timestamp, old.receivedPartCount, old.partCount); |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 |
| 72 | void PacketReassembler::SetCallback(std::function<void(Buffer packet, uint32_t pts, bool keyframe, uint16_t rotation)> callback){ |
| 73 | this->callback=callback; |
| 74 | } |
| 75 |
| 76 | void PacketReassembler::Packet::AddFragment(Buffer pkt, uint32_t fragmentIndex){ |
| 77 | //LOGV("Add fragment %u/%u to packet %u", fragmentIndex, partCount, timestamp); |
| 78 | parts[fragmentIndex]=std::move(pkt); |
| 79 | receivedPartCount++; |
| 80 | } |
| 81 |
| 82 | Buffer PacketReassembler::Packet::Reassemble(){ |
| 83 | if(partCount==1){ |
| 84 | return std::move(parts[0]); |
| 85 | } |
| 86 | BufferOutputStream out(10240); |
| 87 | for(unsigned int i=0;i<partCount;i++){ |
| 88 | out.WriteBytes(parts[i]); |
| 89 | parts[i]=Buffer(); |
| 90 | } |
| 91 | return Buffer(std::move(out)); |
| 92 | } |
| 93 |