msgba/src/packet/send_frame.c

56 lines
1.9 KiB
C
Raw Normal View History

2023-03-13 00:06:19 +01:00
#include <endian.h>
#include <stdlib.h>
#include <msgba/packet/send_frame.h>
void
msPacketSendFrameDestroy(struct msPacketSendFrame **send_frame) {
free ((*send_frame)->outputBuffer);
(*send_frame)->outputBuffer = NULL;
free (*send_frame);
*send_frame = NULL;
}
struct msPacketSendFrame *
msPacketSendFrameNew(unsigned int stride, size_t outputBufferSize, color_t *const outputBuffer) {
struct msPacketSendFrame *self = malloc(sizeof *self);
color_t *outputBufferClone = malloc (sizeof *outputBufferClone * outputBufferSize);
for (size_t i = 0; i < outputBufferSize; i++) {
outputBufferClone[i] = outputBuffer[i];
}
self->outputBufferSize = outputBufferSize;
self->stride = stride;
self->outputBuffer = outputBufferClone;
return self;
}
unsigned char *
msPacketSendFrameSerialize(struct msPacketSendFrame *const self, size_t *len) {
unsigned char *bytes;
unsigned int stride = self->stride;
2023-03-13 01:37:13 +01:00
size_t outputBufferSizeBytes = self->outputBufferSize * sizeof (uint32_t);
2023-03-13 00:06:19 +01:00
stride = htobe32(stride);
*len = (sizeof self->stride) + (sizeof self->outputBufferSize) + (outputBufferSizeBytes);
outputBufferSizeBytes = htobe64(outputBufferSizeBytes);
bytes = malloc(*len);
#define GOTO_END_SERIALIZE_FAIL() \
free(bytes); \
2023-03-13 01:37:13 +01:00
bytes = NULL; \
2023-03-13 00:06:19 +01:00
goto return_ms_packet_send_frame_serialize;
FILE *fp = fmemopen(bytes, sizeof *bytes * *len, "w");
if (fwrite(&self->stride, sizeof self->stride, 1, fp) == -1) {
GOTO_END_SERIALIZE_FAIL();
}
if (fwrite(&outputBufferSizeBytes, sizeof outputBufferSizeBytes, 1, fp) == -1) {
GOTO_END_SERIALIZE_FAIL();
}
2023-03-13 01:37:13 +01:00
for (size_t i = 0; i < self->outputBufferSize; i++) {
color_t pixel = self->outputBuffer[i];
if (fwrite(&pixel, sizeof pixel, 1, fp) == -1) {
GOTO_END_SERIALIZE_FAIL();
}
2023-03-13 00:06:19 +01:00
}
return_ms_packet_send_frame_serialize:
2023-03-13 01:37:13 +01:00
fclose(fp);
2023-03-13 00:06:19 +01:00
return bytes;
}