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