| 6 |
| #include "../logging.h" |
| 7 | #include <stdlib.h> |
| 8 |
| 9 | using namespace tgvoip; |
| 10 | using namespace tgvoip::video; |
| 11 |
| 12 | Buffer ParityFEC::Encode(std::vector<Buffer>& packets){ |
| 13 | size_t maxSize=0; |
| 14 |
| 15 | for(Buffer& pkt:packets){ |
| 16 | maxSize=std::max(maxSize, pkt.Length()); |
| 17 | } |
| 18 | Buffer result(maxSize+2); // add 2 bytes for length |
| 19 | uint8_t* _result=*result; |
| 20 | memset(_result, 0, result.Length()); |
| 21 | for(Buffer& pkt:packets){ |
| 22 | for(size_t i=0;i<pkt.Length();i++){ |
| 23 | _result[i] ^= pkt[i]; |
| 24 | } |
| 25 | uint16_t len=(uint16_t)pkt.Length(); |
| 26 | _result[maxSize] ^= (uint8_t)len; |
| 27 | _result[maxSize+1] ^= (uint8_t)(len >> 8); |
| 28 | } |
| 29 |
| 30 | return std::move(result); |
| 31 | } |
| 32 |
| 33 | Buffer ParityFEC::Decode(std::vector<Buffer>& dataPackets, Buffer &fecPacket){ |
| 34 | size_t maxSize=0; |
| 35 | for(Buffer& pkt:dataPackets){ |
| 36 | maxSize=std::max(maxSize, pkt.Length()); |
| 37 | } |
| 38 |
| 39 | if(fecPacket.Length()<maxSize+2){ |
| 40 | LOGE("ParityFEC: FEC packet too small (%u, expected >=%u)", (unsigned int)fecPacket.Length(), (unsigned int)maxSize+2); |
| 41 | return Buffer(); |
| 42 | } |
| 43 | Buffer result=Buffer::CopyOf(fecPacket); |
| 44 | uint8_t* _result=*result; |
| 45 | unsigned int emptyCount=0; |
| 46 | for(Buffer& pkt:dataPackets){ |
| 47 | if(pkt.Length()==0){ |
| 48 | emptyCount++; |
| 49 | continue; |
| 50 | } |
| 51 | for(size_t i=0;i<pkt.Length();i++){ |
| 52 | _result[i] ^= pkt[i]; |
| 53 | } |
| 54 | uint16_t len=(uint16_t)pkt.Length(); |
| 55 | _result[maxSize] ^= (uint8_t)len; |
| 56 | _result[maxSize+1] ^= (uint8_t)(len >> 8); |
| 57 | } |
| 58 | if(emptyCount!=1){ |
| 59 | LOGE("ParityFEC: %u packets lost", emptyCount); |
| 60 | return Buffer(); |
| 61 | } |
| 62 |
| 63 | uint16_t len=(uint16_t)_result[maxSize] | ((uint16_t)_result[maxSize+1] << 8); |
| 64 | if(len>maxSize){ |
| 65 | LOGE("ParityFEC: incorrect length %u", len); |
| 66 | return Buffer(); |
| 67 | } |
| 68 | LOGV("ParityFEC decoded packet size %u", len); |
| 69 |
| 70 | result.Resize(len); |
| 71 | return std::move(result); |
| 72 | } |
| 73 |