// // Created by bruno on 13. 7. 2026. // #include "packet.h" #include "crc32.h" #include #include #define MAGIC 0xCA55 #define PACKET_SIZE 223 uint8_t *build_stream( uint8_t *file, uint32_t size, uint32_t *outSize) { uint32_t packets = (size + PACKET_SIZE - 1) / PACKET_SIZE; /* estimate: preamble 256 bytes sync 16 bytes packets: header 4 payload 223 crc 4 */ uint32_t capacity = 256 + 16 + packets * (4 + 2 + 2 + 223 + 4); uint8_t *out = malloc(capacity); uint32_t pos = 0; /* preamble */ for (int i = 0; i < 256; i++) out[pos++] = 0x55; /* sync */ uint8_t sync[] = { 0xD3, 0x91, 0xAC, 0x55, 0x77, 0x22, 0xF0, 0x0F }; memcpy( out + pos, sync, sizeof(sync)); pos += sizeof(sync); uint32_t offset = 0; for (uint32_t p = 0; p < packets; p++) { uint16_t magic = MAGIC; uint16_t packet = p; uint16_t len = size - offset > PACKET_SIZE ? PACKET_SIZE : size - offset; memcpy(out + pos, &magic, 2); pos += 2; memcpy(out + pos, &packet, 2); pos += 2; memcpy(out + pos, &len, 2); pos += 2; memcpy(out + pos, file + offset, len); pos += len; uint32_t crc = calcCRC32( file + offset, len); memcpy(out + pos, &crc, 4); pos += 4; offset += len; } *outSize = pos; return out; }