]> git.draconx.ca Git - liblbx.git/blobdiff - src/image.c
liblbx: Add a hard check for image leadin versus frame count.
[liblbx.git] / src / image.c
index 4f1a2bd0c805e718f234c9ca92794058afcddb62..adc6a43427289a20b581255abd70be6c1b3c908f 100644 (file)
-#ifdef HAVE_CONFIG_H
-#      include "config.h"
-#endif
-
+/*
+ * 2ooM: The Master of Orion II Reverse Engineering Project
+ * Library for working with LBX image files.
+ * Copyright © 2006-2011, 2013-2014 Nick Bowler
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+#include <config.h>
 #include <stdlib.h>
-#include <stdint.h>
+#include <string.h>
 #include <assert.h>
+#include <stdbool.h>
+#include <inttypes.h>
 #include <errno.h>
 
-#include "byteorder.h"
+#include "pack.h"
 #include "misc.h"
 #include "lbx.h"
+#include "error.h"
 #include "image.h"
 
-struct lbx_image {
-       uint16_t width, height;
-       uint16_t wtf1;
-       uint16_t offs, frames;
-       uint16_t pal;
+#define FLAG_RAW       0x0100 /* Image is stored as a flat array of bytes. */
+#define FLAG_OVERWRITE 0x0400 /* Draw each frame on a clean slate (unsure). */
+#define FLAG_BUILDING  0x0800 /* Buildings have this, related to shadow? */
+#define FLAG_PALETTE   0x1000 /* Image contains embedded palette. */
+#define FLAG_LOOPING   0x2000 /* Loop over all frames in the image (unsure). */
 
-       FILE *f;
-       long foff;
+#define FLAG_ALL (FLAG_RAW|FLAG_OVERWRITE|FLAG_BUILDING|FLAG_PALETTE|FLAG_LOOPING)
+
+#define HDR_LEN 12
+
+/* States for image readout */
+enum {
+       READ_STATE_INIT,
+       READ_STATE_HEADER,
+       READ_STATE_DATA,
+       READ_STATE_DONE,
+};
+
+struct lbx_image_priv {
+       struct lbx_image pub;
+
+       unsigned short wtf, flags;
+       unsigned char  wtf2;
 
-       int currentframe;
-       int currentx, currenty;
-       unsigned char **framedata;
+       const struct lbx_file_ops *fops;
+       int (*dtor)(void *handle);
+       void *f;
 
-       uint32_t offsets[];
+       /* State of frame readout */
+       unsigned currentx, currenty, currentn;
+       int read_state;
+
+       unsigned long offsets[];
 };
 
-struct lbx_image *lbximg_fopen(FILE *f)
+static struct lbx_image_priv *lbx_img_init(unsigned char hdr[static HDR_LEN])
 {
-       struct lbx_image tmp = {.f = f}, *new = NULL;
-
-       if (fread(&tmp.width,  sizeof tmp.width,   1, f) != 1) goto readerr;
-       if (fread(&tmp.height, sizeof tmp.height,  1, f) != 1) goto readerr;
-       if (fread(&tmp.wtf1,   sizeof tmp.wtf1,    1, f) != 1) goto readerr;
-       if (fread(&tmp.offs,   sizeof tmp.offs,    1, f) != 1) goto readerr;
-       if (fread(&tmp.frames, sizeof tmp.frames,  1, f) != 1) goto readerr;
-       if (fread(&tmp.pal,    sizeof tmp.pal,     1, f) != 1) goto readerr;
-
-       tmp.width  = letohs(tmp.width);  tmp.foff += sizeof tmp.width;
-       tmp.height = letohs(tmp.height); tmp.foff += sizeof tmp.height;
-       tmp.wtf1   = letohs(tmp.wtf1);   tmp.foff += sizeof tmp.wtf1;
-       tmp.offs   = letohs(tmp.offs);   tmp.foff += sizeof tmp.offs;
-       tmp.frames = letohs(tmp.frames); tmp.foff += sizeof tmp.frames;
-       tmp.pal    = letohs(tmp.pal);    tmp.foff += sizeof tmp.pal;
-
-       /* For some reason, the format seems to need this. */
-       tmp.offs++;
-       tmp.frames++;
-
-       /* Format constraints. */
-       if (tmp.offs <= tmp.frames) {
-               lbx_errno = LBX_EFORMAT;
+       unsigned short nframes = unpack_16_le(hdr+6);
+       struct lbx_image_priv *img;
+
+       img = malloc(sizeof *img + sizeof img->offsets[0] * (nframes+1));
+       if (!img) {
+               lbx_error_raise(LBX_ENOMEM);
                return NULL;
        }
 
-       /*
-        * DEBUG ONLY.  These assertions exist to catch otherwise valid image
-        * files which differ from what I believe to be true of all LBX images.
-        * If we never find any exceptions, we can replace the assertions with
-        * assumptions.
-        */
-       _lbx_assert(tmp.wtf1 == 0);
-       _lbx_assert(tmp.offs == tmp.frames + 1);
-       _lbx_assert(tmp.pal  == 0 || tmp.pal == 0x1000);
+       *img = (struct lbx_image_priv) {
+               .pub.width  = unpack_16_le(hdr+0),
+               .pub.height = unpack_16_le(hdr+2),
+               .wtf        = unpack_16_le(hdr+4),
+               .pub.frames = hdr[6],
+               .wtf2       = hdr[7],
+               .pub.leadin = hdr[8],
+               .pub.chunk  = hdr[9],
+               .flags      = unpack_16_le(hdr+10),
+       };
 
-       new = malloc(sizeof *new + tmp.offs * sizeof *new->offsets);
-       if (!new) {
-               lbx_errno = -errno;
+       if (img->flags & FLAG_OVERWRITE)
+               img->pub.chunk = 1;
+
+       if (img->flags & FLAG_LOOPING)
+               img->pub.leadin = 0;
+
+       if (img->pub.leadin >= img->pub.frames) {
+               lbx_error_raise(LBX_EFORMAT);
+               free(img);
                return NULL;
        }
 
-       *new = tmp;
-       new->currentframe = -1;
+       return img;
+}
 
-       if (fread(new->offsets, sizeof *new->offsets, new->offs, f)!= new->offs)
-               goto readerr;
-       new->foff += sizeof *new->offsets * new->offs;
+struct lbx_image *lbx_img_open(void *f, const struct lbx_file_ops *fops,
+                               int (*destructor)(void *))
+{
+       unsigned char hdr_buf[HDR_LEN];
+       struct lbx_image_priv *img;
 
-       return new;
-readerr:
-       if (feof(f)) {
-               lbx_errno = LBX_EEOF;
-       } else {
-               lbx_errno = -errno;
+       if (fops->read(hdr_buf, sizeof hdr_buf, f) != sizeof hdr_buf) {
+               if (fops->eof(f))
+                       lbx_error_raise(LBX_EEOF);
+               return NULL;
        }
 
-       free(new);
-       return NULL;
+       img = lbx_img_init(hdr_buf);
+       if (!img)
+               return NULL;
+
+       img->f    = f;
+       img->fops = fops;
+       img->dtor = destructor;
+
+       /*
+        * DEBUG ONLY.  These assertions exist to catch otherwise valid image
+        * files which differ from what I believe to be true of all LBX images.
+        * When we can decode every image, then these assertions should be
+        * replaced with constraints.
+        */
+       _lbx_assert(img->wtf  == 0); /* version? */
+       _lbx_assert(img->wtf2 == 0); /* very likely is simply reserved. */
+       _lbx_assert(!(img->flags & ~FLAG_ALL));
+
+       /* Read all offsets.  Should be merged with identical code in lbx.c */
+       for (unsigned i = 0; i <= img->pub.frames; i++) {
+               unsigned char buf[4];
+
+               if (fops->read(buf, sizeof buf, f) != sizeof buf) {
+                       if (fops->eof(f))
+                               lbx_error_raise(LBX_EEOF);
+                       free(img);
+                       return NULL;
+               }
+
+               img->offsets[i] = unpack_32_le(buf);
+       }
+
+       return &img->pub;
 }
 
-static int _lbx_drawrow(int first, struct lbx_image *img)
+static int pipe_close(void *f)
 {
-       uint16_t type, yval, count, xval;
-       unsigned char *pos;
-       unsigned char abyss;
-       size_t rc;
+       struct lbx_pipe_state *p = f;
+       int rc;
+
+       rc = fclose(p->f);
+       free(p);
+       return rc;
+}
 
-       assert(img->framedata);
+static int file_close(void *f)
+{
+       return fclose((FILE *)f);
+}
 
-       if (fread(&type, sizeof type, 1, img->f) != 1) goto readerr;
-       type = letohs(type); img->foff += sizeof type;
+struct lbx_image *lbx_img_fopen(const char *file)
+{
+       struct lbx_pipe_state *p;
+       FILE *f;
 
-       if (first) {
-               img->currentx = 0;
-               img->currenty = 0;
-               type = 0;
+       f = fopen(file, "rb");
+       if (!f) {
+               lbx_error_raise(-errno);
+               return NULL;
        }
 
-       if (type == 0) {
-               if (fread(&yval,  sizeof yval,  1, img->f) != 1) goto readerr;
-               yval = letohs(yval); img->foff += sizeof yval;
-               if (yval == 1000)
-                       return 1;
-               if (fread(&count, sizeof count, 1, img->f) != 1) goto readerr;
-               count = letohs(count); img->foff += sizeof count;
-               if (fread(&xval,  sizeof xval,  1, img->f) != 1) goto readerr;
-               xval = letohs(xval); img->foff += sizeof xval;
-               if (xval == 1000)
-                       return 1;
-
-               /* Ensure that the row fits in the image. */
-               if (img->height - img->currenty <= yval || xval >= img->width) {
-                       lbx_errno = LBX_EFORMAT;
-                       return -1;
-               }
+       if (fseek(f, 0, SEEK_CUR) == 0)
+               return lbx_img_open(f, &lbx_default_fops, file_close);
 
-               img->currenty += yval;
-               img->currentx  = xval;
-       } else {
-               if (fread(&xval,  sizeof xval,  1, img->f) != 1) goto readerr;
-               xval = letohs(xval); img->foff += sizeof xval;
+       p = malloc(sizeof *p);
+       if (!p) {
+               lbx_error_raise(LBX_ENOMEM);
+               fclose(f);
+               return NULL;
+       }
 
-               if (img->width - img->currentx <= xval) {
-                       lbx_errno = LBX_EFORMAT;
-                       return -1;
-               }
-               img->currentx += xval;
+       *p = (struct lbx_pipe_state) { .f = f };
+       return lbx_img_open(p, &lbx_pipe_fops, pipe_close);
+}
 
-               count = type;
+int lbx_img_seek(struct lbx_image *pub, unsigned frame)
+{
+       struct lbx_image_priv *img = (struct lbx_image_priv *)pub;
 
+       if (frame >= pub->frames) {
+               lbx_error_raise(LBX_EINVAL);
+               return -1;
        }
 
-       if (count > img->width - img->currentx) {
-               lbx_errno = LBX_EFORMAT;
+       if (img->fops->seek(img->f, img->offsets[frame], SEEK_SET)) {
                return -1;
        }
 
-       pos = &img->framedata[img->currenty][img->currentx];
-       rc  = fread(pos, 1, count, img->f);
-       img->currentx += rc;
-       img->foff     += rc;
+       if (!(img->flags & FLAG_RAW)) {
+               unsigned char buf[4];
 
-       if (rc < count)
-               goto readerr;
+               /* Read frame header */
+               if (img->fops->read(buf, 4, img->f) != 4) {
+                       if (img->fops->eof(img->f))
+                               lbx_error_raise(LBX_EEOF);
+                       return -1;
+               }
+
+               if (unpack_16_le(buf) != 1) {
+                       lbx_error_raise(LBX_EFORMAT);
+                       return -1;
+               }
 
-       if (count % 2) {
-               if (fread(&abyss, 1, 1, img->f) != 1)
-                       goto readerr;
-               img->foff += 1;
+               img->currentx = 0;
+               img->currenty = unpack_16_le(buf+2);
+               if (img->currenty > img->pub.height) {
+                       lbx_error_raise(LBX_EFORMAT);
+                       return -1;
+               }
        }
 
+       img->read_state = READ_STATE_HEADER;
        return 0;
-readerr:
-       if (feof(img->f)) {
-               lbx_errno = LBX_EEOF;
-       } else {
-               lbx_errno = -errno;
-       }
-       return -1;
 }
 
-unsigned char **lbximg_getframe(struct lbx_image *img, int frame)
+long lbx_img_read_row_header(struct lbx_image *pub, unsigned *x, unsigned *y)
 {
-       if (frame >= img->frames || frame < 0) {
-               lbx_errno = LBX_ERANGE;
-               return NULL;
-       }
+       struct lbx_image_priv *img = (struct lbx_image_priv *)pub;
+       unsigned short length, offset;
+       unsigned char buf[4];
 
-       if (!img->framedata) {
-               unsigned char *tmp;
-               int i;
+       if (img->read_state != READ_STATE_HEADER) {
+               lbx_error_raise(LBX_EINVAL);
+               return -1;
+       }
 
-               tmp = malloc(img->width * img->height);
-               if (!tmp) {
-                       lbx_errno = -errno;
-                       return NULL;
+       /* Raw images have no row headers */
+       if (img->flags & FLAG_RAW) {
+               img->currentn = img->pub.width;
+               *y = img->currenty++;
+               *x = 0;
+
+               if (*y < img->pub.height) {
+                       img->read_state = READ_STATE_DATA;
+                       return img->currentn;
+               } else {
+                       img->read_state = READ_STATE_DONE;
+                       return 0;
                }
+       }
 
-               img->framedata = malloc(img->height * sizeof *img->framedata);
-               if (!img->framedata) {
-                       lbx_errno = -errno;
-                       free(tmp);
-                       return NULL;
+       do {
+               if (img->fops->read(buf, sizeof buf, img->f) != sizeof buf) {
+                       if (img->fops->eof(img->f))
+                               lbx_error_raise(LBX_EEOF);
+                       return -1;
                }
 
-               for (i = 0; i < img->height; i++) {
-                       img->framedata[i] = tmp + i * img->width;
+               length = unpack_16_le(buf+0);
+               offset = unpack_16_le(buf+2);
+
+               if (length == 0) {
+                       if (offset == 1000) {
+                               img->read_state = READ_STATE_DONE;
+                               return 0;
+                       } else if (offset > img->pub.height - img->currenty) {
+                               lbx_error_raise(LBX_EFORMAT);
+                               return -1;
+                       }
+
+                       img->currenty += offset;
+                       img->currentx  = 0;
                }
-       }
+       } while (length == 0);
 
-       /* Start over if we are backtracking. */
-       if (img->currentframe > frame)
-               img->currentframe == -1;
+       if (offset > img->pub.width - img->currentx) {
+               lbx_error_raise(LBX_EFORMAT);
+               return -1;
+       }
+       img->currentx += offset;
 
-       /* We must have previous frame decoded to continue. */
-       if (frame > img->currentframe + 1) {
-               if (!lbximg_getframe(img, frame-1))
-                       return NULL;
+       if (length > img->pub.width - img->currentx) {
+               lbx_error_raise(LBX_EFORMAT);
+               return -1;
        }
+       img->currentn = length;
 
-       if (img->currentframe != frame) {
-               int rc, first = 1;
+       img->read_state = READ_STATE_DATA;
+       *x = img->currentx;
+       *y = img->currenty;
 
-               if (_lbx_fseek(img->f, &img->foff, img->offsets[frame]) == -1)
-                       return NULL;
+       return img->currentn;
+}
 
-               do {
-                       rc = _lbx_drawrow(first, img);
-                       if (rc == -1)
-                               return NULL;
-                       first = 0;
+long lbx_img_read_row_data(struct lbx_image *pub, void *buf)
+{
+       struct lbx_image_priv *img = (struct lbx_image_priv *)pub;
 
-                       if (!rc && img->foff > img->offsets[frame+1]) {
-                               lbx_errno = LBX_EFORMAT;
-                               return NULL;
-                       }
-               } while (!rc);
+       if (img->read_state != READ_STATE_DATA) {
+               lbx_error_raise(LBX_EINVAL);
+               return -1;
        }
 
-       img->currentframe = frame;
-       return img->framedata;
+       if (img->fops->read(buf, img->currentn, img->f) != img->currentn) {
+               if (img->fops->eof(img->f))
+                       lbx_error_raise(LBX_EEOF);
+               return -1;
+       }
+
+       if (!(img->flags & FLAG_RAW)) {
+               /* Skip padding byte, if any */
+               if (img->currentn % 2) {
+                       if (img->fops->seek(img->f, 1, SEEK_CUR))
+                               return -1;
+               }
+       }
+
+       img->read_state = READ_STATE_HEADER;
+       img->currentx += img->currentn;
+
+       return img->currentn;
 }
 
-int lbximg_loadpalette(FILE *f, struct lbx_colour palette[static 256])
+static int read_palette(void *f, const struct lbx_file_ops *fops,
+                        struct lbx_colour *palette, unsigned count,
+                       bool external)
 {
-       uint8_t entry[4];
-       int i;
+       assert(count <= 256);
+       for (unsigned i = 0; i < count; i++) {
+               unsigned char buf[4];
 
-       for (i = 0; i < 256; i++) {
-               if (fread(entry, sizeof entry, 1, f) != 1) {
-                       lbx_errno = (feof(f)) ? LBX_EEOF : -errno;
+               if (fops->read(buf, 4, f) != 4) {
+                       if (fops->eof(f))
+                               lbx_error_raise(LBX_EEOF);
                        return -1;
                }
 
-               if (entry[0] != 1) {
-                       lbx_errno = LBX_EFORMAT;
+               if (buf[0] != external) {
+                       lbx_error_raise(LBX_EFORMAT);
                        return -1;
                }
 
-               palette[i] = (struct lbx_colour){
-                       .red   = entry[1] << 2,
-                       .green = entry[2] << 2,
-                       .blue  = entry[3] << 2,
+               palette[i] = (struct lbx_colour) {
+                       .red    = buf[1] & 0x3f,
+                       .green  = buf[2] & 0x3f,
+                       .blue   = buf[3] & 0x3f,
+                       .active = 1,
                };
        }
 
        return 0;
 }
 
-int
-lbximg_getpalette(struct lbx_image *img, struct lbx_colour palette[static 256])
+int lbx_img_loadpalette(void *f, const struct lbx_file_ops *fops,
+                        struct lbx_colour *palette)
 {
-       size_t hdrlen = 6*(sizeof img->pal)+(img->offs)*(sizeof *img->offsets);
-       unsigned int i;
-       size_t rc;
+       return read_palette(f, fops, palette, 256, true);
+}
 
-       uint16_t zero, count;
-       uint8_t  entry[4];
+int lbx_img_getpalette(struct lbx_image *pub, struct lbx_colour *out)
+{
+       struct lbx_image_priv *img = (struct lbx_image_priv *)pub;
+       unsigned long palette_start, palette_count, palette_offset;
+       unsigned char buf[4];
+       int rc;
 
        /* Do nothing if the image doesn't have embedded palette data. */
-       if (img->pal == 0)
+       if (!(img->flags & FLAG_PALETTE))
                return 0;
 
-       /* Palette data is located right after the header. */
-       if (_lbx_fseek(img->f, &img->foff, hdrlen) == -1)
-               return -1;
-       
-       /* Palette header */
-       if (fread(&zero,  sizeof zero,  1, img->f) != 1) goto readerr;
-       if (fread(&count, sizeof count, 1, img->f) != 1) goto readerr;
-       zero  = letohs(zero);  img->foff += sizeof zero;
-       count = letohs(count); img->foff += sizeof count;
-
-       if (zero != 0 || count > 256) {
-               lbx_errno = LBX_EFORMAT;
+       palette_offset = 16 + 4ul * img->pub.frames;
+       if (img->fops->seek(img->f, palette_offset, SEEK_SET)) {
                return -1;
        }
 
-       if (hdrlen + 2*(sizeof zero) + count*(sizeof entry) > img->offsets[0]) {
-               lbx_errno = LBX_EFORMAT;
+       /* Read embedded palette header */
+       if (img->fops->read(buf, 4, img->f) < 4)
+               goto readerr;
+
+       palette_start = unpack_16_le(buf+0);
+       palette_count = unpack_16_le(buf+2);
+       if (palette_start + palette_count > 256) {
+               lbx_error_raise(LBX_EFORMAT);
                return -1;
        }
 
-       for (i = 0; i < count; i++) {
-               rc = fread(entry, 1, sizeof entry, img->f);
-               img->foff += rc;
-
-               if (rc < sizeof entry) {
-                       goto readerr;
-               }
-
-               if (entry[0] != 0) {
-                       lbx_errno = LBX_EFORMAT;
+       if (out) {
+               rc = read_palette(img->f, img->fops,
+                                 out+palette_start, palette_count,
+                                 false);
+               if (rc < 0)
                        return -1;
-               }
-
-               palette[i] = (struct lbx_colour){
-                       .red   = entry[1] << 2,
-                       .green = entry[2] << 2,
-                       .blue  = entry[3] << 2,
-               };
        }
 
-       return 0;
+       return palette_count;
 readerr:
-       lbx_errno = feof(img->f) ? LBX_EEOF : -errno;
+       if (img->fops->eof(img->f))
+               lbx_error_raise(LBX_EEOF);
        return -1;
 }
 
-void lbximg_getinfo(struct lbx_image *img, struct lbx_imginfo *info)
+int lbx_img_close(struct lbx_image *pub)
 {
-       *info = (struct lbx_imginfo) {
-               .width   = img->width,
-               .height  = img->height,
-               .nframes = img->frames,
-       };
-}
+       struct lbx_image_priv *img = (struct lbx_image_priv *)pub;
+       int rc = 0;
 
-void lbximg_close(struct lbx_image *img)
-{
-       if (!img) return;
-
-       if (img->framedata) {
-               free(img->framedata[0]);
-               free(img->framedata);
-       }
-
-       if (img->f) {
-               fclose(img->f);
+       if (img && img->dtor) {
+               rc = img->dtor(img->f);
        }
-
        free(img);
+
+       return rc;
 }