80 lines
2.0 KiB
C

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "img_png.h"
#include "../common/utils.h"
#define BUFSIZE 1024
const unsigned char img_png_signature[] = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'};
// Reads magic number and determines if data is PNG
int png_can_decode(const uint8_t *data, size_t size) {
if (size < 8) return 0;
return memcmp(data, img_png_signature, 8) == 0;
}
struct img_png_chunk read_chunk(FILE *fp) {
struct img_png_chunk cur_chunk;
// Read chunk length
unsigned char len[4];
if(fread(len, sizeof(*len), 4, fp) < 4) {
fprintf(stderr, "Couldn\'t read chunk length.\n");
exit(EXIT_FAILURE);
}
cur_chunk.length = char_to_uint32(len);
printf("Chunk length: %lu\n", (unsigned long) cur_chunk.length);
// Read chunk type
if(fread(cur_chunk.chunk_type, sizeof(*cur_chunk.chunk_type), 4, fp) < 4) {
fprintf(stderr, "Couldn\'t read chunk type.\n");
exit(EXIT_FAILURE);
}
printf("Chunk type: %.*s\n", 4, cur_chunk.chunk_type);
// Read chunk data
size_t chunk_size = cur_chunk.length / sizeof(unsigned char);
printf("Chunk size: %zu\n", chunk_size);
cur_chunk.chunk_data = malloc(chunk_size);
if(!cur_chunk.chunk_data) {
perror("Failed to allocate chunk data!");
exit(EXIT_FAILURE);
}
if(fread(cur_chunk.chunk_data, 1, cur_chunk.length, fp) != cur_chunk.length) {
if(feof(fp)) {
fprintf(stderr, "File ended prematurely.\n");
exit(EXIT_FAILURE);
}
fprintf(stderr, "Failed to read chunk data!\n");
exit(EXIT_FAILURE);
}
return cur_chunk;
}
image_t* png_decode (const uint8_t *data, size_t size) {
return NULL;
}
void png_destroy(struct image_decoder *self) {
if (self) {
free(self);
self = NULL;
} else self = NULL;
}
image_decoder_t* png_decoder_create () {
image_decoder_t* decoder = malloc(sizeof(image_decoder_t));
decoder->name = "PNG";
decoder->can_decode = png_can_decode;
decoder->decode = png_decode;
decoder->destroy = png_destroy;
return decoder;
}