]> git.draconx.ca Git - liblbx.git/blob - src/lbximg.c
liblbx: Clean up embedded palette handling
[liblbx.git] / src / lbximg.c
1 /*
2  *  2ooM: The Master of Orion II Reverse Engineering Project
3  *  Simple command-line tool to convert an LBX image to other formats.
4  *  Copyright © 2006-2011, 2013-2014 Nick Bowler
5  *
6  *  This program is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 #include <config.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stdbool.h>
23 #include <string.h>
24 #include <limits.h>
25 #include <stdint.h>
26 #include <assert.h>
27 #include <getopt.h>
28 #include <errno.h>
29
30 #include "tools.h"
31 #include "image.h"
32 #include "error.h"
33 #include "lbx.h"
34
35 #include "imgoutput.h"
36
37 #define MIN(a, b) ((a) < (b) ? (a) : (b))
38
39 /* Global flags */
40 static int verbose = 0;
41 static char *outname = "out";
42 static int usepalette = 1;
43
44 enum {
45         OPT_PREFIX = UCHAR_MAX+1,
46 };
47
48 static void printusage(void)
49 {
50         puts("usage: lbximg [-i|-d] [-v] [-p palette_file] [-O override_file]"
51                           " [-f path]");
52         puts("              [-F format] [frameno ...]");
53 }
54
55 static void printhelp(void)
56 {
57         printusage();
58         puts("For now, see the man page for detailed help.");
59 }
60
61 enum {
62         MODE_NONE,
63         MODE_DECODE,
64         MODE_IDENT,
65 };
66
67 static const struct img_format {
68         img_output_func *output;
69         char name[4];
70         bool enabled;
71 } formats[] = {
72 #if HAVE_LIBPNG
73         { img_output_png, "png", 1 },
74 #endif
75         { img_output_pam, "pam", 1 },
76         { img_output_ppm, "ppm", 1 },
77         { img_output_pbm, "pbm", 1 },
78 };
79
80 static int lookup_format(const char *fmt)
81 {
82         for (size_t i = 0; i < sizeof formats / sizeof formats[0]; i++) {
83                 assert(!formats[i].name[sizeof formats[i].name - 1]);
84
85                 if (!fmt && formats[i].enabled)
86                         return i;
87
88                 if (strcmp(formats[i].name, fmt))
89                         continue;
90
91                 if (!formats[i].enabled) {
92                         tool_err(-1, "%s support disabled at build time", fmt);
93                         return -1;
94                 }
95
96                 return i;
97         }
98
99         tool_err(-1, "unknown format %s", fmt);
100         return -1;
101 }
102
103 bool img_is_masked(unsigned char *mask, unsigned width, unsigned height)
104 {
105         unsigned long npixels = (unsigned long) width * height;
106         unsigned long mask_sz = npixels / CHAR_BIT + (npixels % CHAR_BIT != 0);
107
108         for (unsigned long i = 0; i < mask_sz; i++) {
109                 if (i+1 < mask_sz) {
110                         if (mask[i] != (unsigned char)-1)
111                                 return true;
112                 } else {
113                         unsigned char test = (1u << npixels % CHAR_BIT) - 1;
114
115                         if ((mask[i] & test) != test)
116                                 return true;
117                 }
118         }
119
120         return false;
121 }
122
123 int parserange(unsigned frames, char *str, unsigned char *bits)
124 {
125         unsigned long start, end;
126         unsigned int i;
127         char *endptr;
128
129         start = strtoul(str, &endptr, 0);
130         if (start >= frames) {
131                 tool_err(-1, "frame %lu out of range.", start);
132                 return -1;
133         }
134
135         if (endptr == str) {
136                 tool_err(-1, "invalid frame range: %s.", str);
137                 return -1;
138         }
139
140         switch (*endptr) {
141         case '\0':
142                 end = start;
143                 break;
144         case '-':
145                 end = strtoul(endptr+1, &endptr, 0);
146                 if (end >= frames) {
147                         tool_err(-1, "frame %lu out of range.", end);
148                         return -1;
149                 }
150
151                 if (endptr == str)
152                         end = frames - 1;
153                 break;
154         default:
155                 tool_err(-1, "invalid frame range: %s.", str);
156                 return -1;
157         }
158
159         if (end < start) {
160                 tool_err(-1, "invalid frame range: %s.", str);
161                 return -1;
162         }
163
164         for (i = start; i <= end; i++) {
165                 bits[i / CHAR_BIT] |= 1 << (i % CHAR_BIT);
166         }
167
168         return 0;
169 }
170
171 int output(unsigned int frameno, const struct img_format *fmt,
172            unsigned char *pixels, unsigned char *pixel_mask,
173            unsigned int width, unsigned int height,
174            struct lbx_colour palette[static 256])
175 {
176         char name[strlen(outname) + sizeof ".65535.png"];
177         FILE *of;
178         int rc;
179
180         assert(fmt->output != NULL);
181         assert(frameno < 65536);
182         snprintf(name, sizeof name, "%s.%03d.%s", outname, frameno, fmt->name);
183
184         of = fopen(name, "wb");
185         if (!of) {
186                 tool_err(0, "failed to open %s", name);
187                 return -1;
188         }
189
190         rc = fmt->output(of, name, width, height, pixels, pixel_mask, palette);
191         if (rc < 0) {
192                 fclose(of);
193                 return -1;
194         }
195
196         if (fclose(of) == EOF) {
197                 tool_err(0, "error writing %s", name);
198                 return -1;
199         }
200
201         if (verbose)
202                 printf("wrote %s\n", name);
203
204         return 0;
205 }
206
207 static int loadoverride(FILE *f, struct lbx_colour palette[static 256])
208 {
209         struct lbx_image *img;
210         int rc, ret = 0;
211
212         img = lbx_img_open(f, &lbx_default_fops, NULL);
213         if (!img) {
214                 tool_err(-1, "failed to open override image: %s", lbx_errmsg());
215                 return -1;
216         }
217
218         rc = lbx_img_getpalette(img, palette);
219         if (rc < 0) {
220                 tool_err(-1, "error reading override palette: %s", lbx_errmsg());
221                 ret = -1;
222         } else if (rc == 0) {
223                 tool_err(-1, "override image has no palette.");
224                 ret = -1;
225         }
226
227         lbx_img_close(img);
228         return ret;
229 }
230
231 static int loadpalette(struct lbx_image *img, FILE *palf, FILE *override,
232                        struct lbx_colour *palette)
233 {
234         int rc, ret = -1;
235
236         /* Default the palette to a wonderful pink. */
237         for (unsigned i = 0; i < 256; i++) {
238                 palette[i] = (struct lbx_colour){0x3f, 0x00, 0x3f};
239         }
240
241         /* Read the external palette, if any. */
242         if (palf) {
243                 rc = lbx_img_loadpalette(palf, &lbx_default_fops, palette);
244                 if (rc < 0) {
245                         tool_err(-1, "error reading external palette: %s", lbx_errmsg());
246                         return -1;
247                 }
248
249                 ret = 0;
250         }
251
252         /* Read the embedded palette */
253         rc = lbx_img_getpalette(img, palette);
254         if (rc < 0) {
255                 tool_err(-1, "error reading embedded palette: %s", lbx_errmsg());
256                 return -1;
257         } else if (rc > 0) {
258                 ret = 0;
259         }
260
261         /* Read the override palette, if any. */
262         if (override) {
263                 rc = loadoverride(override, palette);
264                 if (rc < 0)
265                         return -1;
266                 ret = 0;
267         }
268
269         /* If we literally have no palette data at all, may as well fail. */
270         if (ret < 0)
271                 tool_err(-1, "no palette available.");
272         return ret;
273 }
274
275 /* Return true iff a divides b. */
276 static bool divides(unsigned a, unsigned b)
277 {
278         if (b == 0)
279                 return true;
280         if (a == 0)
281                 return false;
282
283         return b % a == 0;
284 }
285
286 /* Set n bits starting from offset in the bitmap. */
287 static void
288 set_bits(unsigned char *bitmap, unsigned long offset, unsigned long n)
289 {
290         if (offset % CHAR_BIT) {
291                 bitmap[offset/CHAR_BIT] |= (n >= CHAR_BIT ? -1u : (1u << n) - 1)
292                                   << offset%CHAR_BIT;
293
294                 n -= MIN(n, CHAR_BIT - offset%CHAR_BIT);
295                 offset += CHAR_BIT - offset%CHAR_BIT;
296         }
297
298         if (n > CHAR_BIT) {
299                 memset(&bitmap[offset/CHAR_BIT], -1, n/CHAR_BIT);
300
301                 offset += n - n%CHAR_BIT;
302                 n %= CHAR_BIT;
303         }
304
305         if (n) {
306                 bitmap[offset/CHAR_BIT] |= (1u << n) - 1;
307         }
308 }
309
310 static int decode_frame(struct lbx_image *img, unsigned n,
311                         unsigned char *pixels, unsigned char *pixel_mask)
312 {
313         unsigned x, y;
314         long rc;
315
316         rc = lbx_img_seek(img, n);
317         if (rc < 0) {
318                 tool_err(-1, "frame %u: invalid frame: %s\n", n, lbx_errmsg());
319                 return -1;
320         }
321
322         while ((rc = lbx_img_read_row_header(img, &x, &y)) != 0) {
323                 unsigned long offset;
324
325                 if (rc < 0) {
326                         tool_err(-1, "frame %u: invalid row: %s", n, lbx_errmsg());
327                         return -1;
328                 }
329
330                 offset = (unsigned long) y * img->width + x;
331                 rc = lbx_img_read_row_data(img, pixels+offset);
332                 if (rc < 0) {
333                         tool_err(-1, "frame %u: error reading row: %s\n", n, lbx_errmsg());
334                         return -1;
335                 }
336
337                 set_bits(pixel_mask, offset, rc);
338         }
339
340         return 0;
341 }
342
343 static int
344 decode(struct lbx_image *img, FILE *palf, FILE *override, int fmt, char **argv)
345 {
346         unsigned char *pixels = NULL, *pixel_mask = NULL, *framebits = NULL;
347         struct lbx_colour palette[256];
348         int rc, ret = EXIT_FAILURE;
349         int extracted = 0;
350         unsigned int i;
351         size_t npixels, mask_sz;
352
353         assert(fmt >= 0 && fmt < sizeof formats / sizeof formats[0]);
354
355         npixels = img->width;
356         if (img->height && npixels >= SIZE_MAX / img->height) {
357                 tool_err(-1, "image too large");
358                 goto err;
359         }
360         npixels *= img->height;
361
362         /* Ensure there is at least 1 byte to allocate */
363         if (npixels == 0)
364                 npixels = 1;
365
366         framebits = calloc(1, img->frames / CHAR_BIT + 1);
367         if (!framebits) {
368                 tool_err(0, "failed to allocate memory");
369                 goto err;
370         }
371
372         pixels = calloc(img->width, img->height);
373         if (!pixels) {
374                 tool_err(0, "failed to allocate memory");
375                 goto err;
376         }
377
378         mask_sz = npixels / CHAR_BIT + (npixels % CHAR_BIT != 0);
379         pixel_mask = malloc(mask_sz);
380         if (!pixel_mask) {
381                 tool_err(0, "failed to allocate memory");
382                 goto err;
383         }
384
385         /* Figure out what images we're extracting. */
386         if (!argv[0]) {
387                 /* extract all images by default. */
388                 memset(framebits, -1, img->frames / CHAR_BIT + 1);
389         } else {
390                 for (i = 0; argv[i]; i++) {
391                         parserange(img->frames, argv[i], framebits);
392                 }
393         }
394
395         if (usepalette) {
396                 if (loadpalette(img, palf, override, palette) == -1) {
397                         ret = EXIT_FAILURE;
398                         goto err;
399                 }
400         }
401
402         /* Extract the images, in order. */
403         ret = EXIT_SUCCESS;
404         for (i = 0; i < img->frames; i++) {
405                 if (divides(img->chunk, i))
406                         memset(pixel_mask, 0, mask_sz);
407
408                 rc = decode_frame(img, i, pixels, pixel_mask);
409                 if (rc < 0) {
410                         ret = EXIT_FAILURE;
411                         goto err;
412                 }
413
414                 if (framebits[i / CHAR_BIT] & (1u << (i % CHAR_BIT))) {
415                         rc = output(i, &formats[fmt], pixels, pixel_mask,
416                                     img->width, img->height,
417                                     usepalette ? palette : NULL);
418
419                         if (rc == 0) {
420                                 extracted = 1;
421                         }
422                 }
423         }
424
425         if (!extracted) {
426                 tool_err(-1, "no frames extracted.");
427                 ret = EXIT_FAILURE;
428         }
429 err:
430         free(pixels);
431         free(pixel_mask);
432         free(framebits);
433         return ret;
434 }
435
436 int main(int argc, char **argv)
437 {
438         int mode = MODE_NONE, fmt, opt, rc = EXIT_FAILURE;
439         struct lbx_pipe_state stdin_handle = { .f = stdin };
440         const char *file = NULL, *fmtstring = NULL;
441         const char *ext_palette = NULL, *ovr_palette = NULL;
442         FILE *palf = NULL, *overf = NULL;
443         struct lbx_image *img;
444
445         static const char sopts[] = "idnvF:f:p:O:VH";
446         static const struct option lopts[] = {
447                 { "identify",      0, NULL, 'i' },
448                 { "decode",        0, NULL, 'd' },
449                 { "verbose",       0, NULL, 'v' },
450                 { "file",          1, NULL, 'f' },
451                 { "format",        1, NULL, 'F' },
452                 { "palette",       1, NULL, 'p' },
453                 { "override",      1, NULL, 'O' },
454                 { "no-palette",    0, NULL, 'n' },
455
456                 { "output-prefix", 1, NULL,  OPT_PREFIX },
457
458                 { "version",       0, NULL, 'V' },
459                 { "usage",         0, NULL, 'U' },
460                 { "help",          0, NULL, 'H' },
461
462                 { 0 }
463         };
464
465         tool_init("lbximg", argc, argv);
466         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
467                 switch(opt) {
468                 case 'i':
469                         mode = MODE_IDENT;
470                         break;
471                 case 'd':
472                         mode = MODE_DECODE;
473                         break;
474                 case 'v':
475                         verbose = 1;
476                         break;
477                 case 'F':
478                         fmtstring = optarg;
479                         break;
480                 case 'f':
481                         file = optarg;
482                         break;
483                 case 'n':
484                         usepalette = 0;
485                         break;
486                 case 'p':
487                         ext_palette = optarg;
488
489                         break;
490                 case 'O':
491                         ovr_palette = optarg;
492                         break;
493                 case OPT_PREFIX:
494                         outname = optarg;
495                         break;
496                 case 'V':
497                         tool_version();
498                         return EXIT_SUCCESS;
499                 case 'U':
500                         printusage();
501                         return EXIT_SUCCESS;
502                 case 'H':
503                         printhelp();
504                         return EXIT_SUCCESS;
505                 default:
506                         return EXIT_FAILURE;
507                 }
508         }
509
510         if (mode == MODE_NONE) {
511                 tool_err(-1, "you must specify a mode.");
512                 return EXIT_FAILURE;
513         }
514
515         fmt = lookup_format(fmtstring);
516         if (fmt < 0)
517                 return EXIT_FAILURE;
518
519         if (file)
520                 img = lbx_img_fopen(file);
521         else
522                 img = lbx_img_open(&stdin_handle, &lbx_pipe_fops, NULL);
523
524         if (!img) {
525                 tool_err(-1, "failed to open image: %s.", lbx_errmsg());
526                 return EXIT_FAILURE;
527         }
528
529         if (ext_palette && !(palf = fopen(ext_palette, "rb"))) {
530                 tool_err(0, "failed to open %s", optarg);
531                 return EXIT_FAILURE;
532         }
533
534         if (ovr_palette && !(overf = fopen(ovr_palette, "rb"))) {
535                 tool_err(0, "failed to open %s", optarg);
536                 return EXIT_FAILURE;
537         }
538
539         if (verbose || mode == MODE_IDENT) {
540                 struct lbx_imginfo info;
541                 int palette_count;
542
543                 if (!file)
544                         file = "stdin";
545
546                 palette_count = lbx_img_getpalette(img, NULL);
547                 if (palette_count < 0) {
548                         tool_err(-1, "error reading image: %s", lbx_errmsg());
549                         return EXIT_FAILURE;
550                 }
551
552                 lbx_img_getinfo(img, &info);
553                 printf("%s is %hux%hu LBX image, %hhu frame(s)%s%s%s\n",
554                        file, img->width, img->height, img->frames,
555                        palette_count  ? ", embedded palette" : "",
556                        img->chunk     ? ", chunked" : "",
557                        info.looping   ? ", loops" : "");
558         }
559
560         switch (mode) {
561         case MODE_IDENT:
562                 rc = 0;
563                 break;
564         case MODE_DECODE:
565                 rc = decode(img, palf, overf, fmt, &argv[optind]);
566                 break;
567         }
568
569         lbx_img_close(img);
570         if (palf)
571                 fclose(palf);
572         if (overf)
573                 fclose(overf);
574         return rc;
575 }