]> git.draconx.ca Git - liblbx.git/blob - src/lbximg.c
lbximg: Return failure if there was a decoding error.
[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 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 <assert.h>
26 #include <getopt.h>
27 #include <errno.h>
28
29 #include "tools.h"
30 #include "image.h"
31 #include "error.h"
32 #include "lbx.h"
33
34 #include "imgoutput.h"
35
36 /* Global flags */
37 static int verbose = 0;
38 static char *outname = "out";
39 static int usepalette = 1;
40
41 enum {
42         OPT_PREFIX = UCHAR_MAX+1,
43 };
44
45 static void printusage(void)
46 {
47         puts("usage: lbximg [-i|-d] [-v] [-p palette_file] [-O override_file]"
48                           " [-f path]");
49         puts("              [-F format] [frameno ...]");
50 }
51
52 static void printhelp(void)
53 {
54         printusage();
55         puts("For now, see the man page for detailed help.");
56 }
57
58 enum {
59         MODE_NONE,
60         MODE_DECODE,
61         MODE_IDENT,
62 };
63
64 static const struct img_format {
65         img_output_func *output;
66         char name[4];
67         bool enabled;
68 } formats[] = {
69 #if HAVE_LIBPNG
70         { img_output_png, "png", 1 },
71 #endif
72         { img_output_pam, "pam", 1 },
73         { img_output_ppm, "ppm", 1 },
74         { img_output_pbm, "pbm", 1 },
75 };
76
77 static int lookup_format(const char *fmt)
78 {
79         for (size_t i = 0; i < sizeof formats / sizeof formats[0]; i++) {
80                 assert(!formats[i].name[sizeof formats[i].name - 1]);
81
82                 if (!fmt && formats[i].enabled)
83                         return i;
84
85                 if (strcmp(formats[i].name, fmt))
86                         continue;
87
88                 if (!formats[i].enabled) {
89                         tool_err(-1, "%s support disabled at build time", fmt);
90                         return -1;
91                 }
92
93                 return i;
94         }
95
96         tool_err(-1, "unknown format %s", fmt);
97         return -1;
98 }
99
100 bool img_is_masked(unsigned char **mask, unsigned width, unsigned height)
101 {
102         unsigned x, y;
103
104         for (x = y = 0; y < height; ++x < width || (x = 0, y++)) {
105                 if (mask[y][x] == 0)
106                         return true;
107         }
108
109         return false;
110 }
111
112 int parserange(unsigned frames, char *str, unsigned char *bits)
113 {
114         unsigned long start, end;
115         unsigned int i;
116         char *endptr;
117
118         start = strtoul(str, &endptr, 0);
119         if (start >= frames) {
120                 tool_err(-1, "frame %lu out of range.", start);
121                 return -1;
122         }
123
124         if (endptr == str) {
125                 tool_err(-1, "invalid frame range: %s.", str);
126                 return -1;
127         }
128
129         switch (*endptr) {
130         case '\0':
131                 end = start;
132                 break;
133         case '-':
134                 end = strtoul(endptr+1, &endptr, 0);
135                 if (end >= frames) {
136                         tool_err(-1, "frame %lu out of range.", end);
137                         return -1;
138                 }
139
140                 if (endptr == str)
141                         end = frames - 1;
142                 break;
143         default:
144                 tool_err(-1, "invalid frame range: %s.", str);
145                 return -1;
146         }
147
148         if (end < start) {
149                 tool_err(-1, "invalid frame range: %s.", str);
150                 return -1;
151         }
152
153         for (i = start; i <= end; i++) {
154                 bits[i / CHAR_BIT] |= 1 << (i % CHAR_BIT);
155         }
156
157         return 0;
158 }
159
160 int output(unsigned int frameno, const struct img_format *fmt,
161            unsigned char **framedata, unsigned char **mask,
162            unsigned int width, unsigned int height,
163            struct lbx_colour palette[static 256])
164 {
165         char name[strlen(outname) + sizeof ".65535.png"];
166         FILE *of;
167         int rc;
168
169         assert(fmt->output != NULL);
170         assert(frameno < 65536);
171         snprintf(name, sizeof name, "%s.%03d.%s", outname, frameno, fmt->name);
172
173         of = fopen(name, "wb");
174         if (!of) {
175                 tool_err(0, "failed to open %s", name);
176                 return -1;
177         }
178
179         rc = fmt->output(of, name, width, height, framedata, mask, palette);
180         if (rc < 0) {
181                 fclose(of);
182                 return -1;
183         }
184
185         if (fclose(of) == EOF) {
186                 tool_err(0, "error writing %s", name);
187                 return -1;
188         }
189                 
190         if (verbose)
191                 printf("wrote %s\n", name);
192
193         return 0;
194 }
195
196 static int loadoverride(FILE *f, struct lbx_colour palette[static 256])
197 {
198         struct lbx_image *overimg = lbx_img_open(f, &lbx_default_fops, NULL);
199         struct lbx_imginfo info;
200
201         if (!overimg) {
202                 tool_err(-1, "failed to open override image: %s", lbx_errmsg());
203                 return -1;
204         }
205         lbx_img_getinfo(overimg, &info);
206
207         if (!info.palettesz) {
208                 tool_err(-1, "override image has no palette.");
209                 lbx_img_close(overimg);
210                 return -1;
211         }
212
213         if (lbx_img_getpalette(overimg, palette) == -1) {
214                 tool_err(-1, "error reading override palette: %s", lbx_errmsg());
215                 lbx_img_close(overimg);
216                 return -1;
217         }
218
219         lbx_img_close(overimg);
220         return 0;
221 }
222
223 static int loadpalette(struct lbx_image *img, struct lbx_imginfo *info,
224                        FILE *palf, FILE *override,
225                        struct lbx_colour palette[static 256])
226 {
227         int i;
228
229         /* For sanity. */
230         if (!palf && !info->palettesz && !override) {
231                 tool_err(-1, "no palette available.");
232                 return -1;
233         }
234
235         /* Default the palette to a wonderful pink. */
236         for (i = 0; i < 256; i++) {
237                 palette[i] = (struct lbx_colour){0x3f, 0x00, 0x3f};
238         }
239
240         /* Read the external palette, if any. */
241         if (palf && lbx_img_loadpalette(palf, &lbx_default_fops, palette) != 0) {
242                 tool_err(-1, "error reading external palette: %s", lbx_errmsg());
243                 return -1;
244         }
245
246         /* Read the embedded palette, if any. */
247         if (info->palettesz && lbx_img_getpalette(img, palette) == -1) {
248                 tool_err(-1, "error reading embedded palette: %s", lbx_errmsg());
249                 return -1;
250         }
251
252         /* Read the override palette, if any. */
253         if (override && loadoverride(override, palette) == -1) {
254                 return -1;
255         }
256
257         return 0;
258 }
259
260 static int
261 decode(struct lbx_image *img, FILE *palf, FILE *override, int fmt, char **argv)
262 {
263         unsigned char *framebits;
264         struct lbx_colour palette[256];
265         struct lbx_imginfo info;
266         int ret = EXIT_SUCCESS;
267         int extracted = 0;
268         unsigned int i;
269
270         assert(fmt >= 0 && fmt < sizeof formats / sizeof formats[0]);
271
272         lbx_img_getinfo(img, &info);
273
274         framebits = calloc(1, img->frames / CHAR_BIT + 1);
275         if (!framebits) {
276                 return EXIT_FAILURE;
277         }
278
279         /* Figure out what images we're extracting. */
280         if (!argv[0]) {
281                 /* extract all images by default. */
282                 memset(framebits, -1, img->frames / CHAR_BIT + 1);
283         } else {
284                 for (i = 0; argv[i]; i++) {
285                         parserange(img->frames, argv[i], framebits);
286                 }
287         }
288
289         if (usepalette) {
290                 if (loadpalette(img, &info, palf, override, palette) == -1) {
291                         ret = EXIT_FAILURE;
292                         goto err;
293                 }
294         }
295
296         /* Extract the images, in order. */
297         for (i = 0; i < img->frames; i++) {
298                 unsigned char **data;
299                 unsigned char **mask;
300
301                 if (!(framebits[i / CHAR_BIT] & (1 << (i % CHAR_BIT))))
302                         continue;
303
304                 data = lbx_img_getframe(img, i);
305                 if (!data) {
306                         tool_err(-1, "error in frame %u: %s", i, lbx_errmsg());
307                         ret = EXIT_FAILURE;
308                         continue;
309                 }
310
311                 mask = lbx_img_getmask(img);
312
313                 if (!output(i, &formats[fmt], data, mask,
314                             img->width, img->height,
315                             usepalette ? palette : NULL)) {
316                         extracted = 1;
317                 }
318         }
319
320         if (!extracted) {
321                 tool_err(-1, "no frames extracted.");
322                 ret = EXIT_FAILURE;
323         }
324 err:
325         free(framebits);
326         return ret;
327 }
328
329 int main(int argc, char **argv)
330 {
331         int mode = MODE_NONE, fmt, opt, rc = EXIT_FAILURE;
332         struct lbx_pipe_state stdin_handle = { .f = stdin };
333         const char *file = NULL, *fmtstring = NULL;
334         FILE *palf = NULL, *overf = NULL;
335         struct lbx_image *img;
336
337         static const char sopts[] = "idnvF:f:p:O:VH";
338         static const struct option lopts[] = {
339                 { "identify",      0, NULL, 'i' },
340                 { "decode",        0, NULL, 'd' },
341                 { "verbose",       0, NULL, 'v' },
342                 { "file",          1, NULL, 'f' },
343                 { "format",        1, NULL, 'F' },
344                 { "palette",       1, NULL, 'p' },
345                 { "override",      1, NULL, 'O' },
346                 { "no-palette",    0, NULL, 'n' },
347
348                 { "output-prefix", 1, NULL,  OPT_PREFIX },
349
350                 { "version",       0, NULL, 'V' },
351                 { "usage",         0, NULL, 'U' },
352                 { "help",          0, NULL, 'H' },
353
354                 { 0 }
355         };
356
357         tool_init("lbximg", argc, argv);
358         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
359                 switch(opt) {
360                 case 'i':
361                         mode = MODE_IDENT;
362                         break;
363                 case 'd':
364                         mode = MODE_DECODE;
365                         break;
366                 case 'v':
367                         verbose = 1;
368                         break;
369                 case 'F':
370                         fmtstring = optarg;
371                         break;
372                 case 'f':
373                         file = optarg;
374                         break;
375                 case 'n':
376                         usepalette = 0;
377                         break;
378                 case 'p':
379                         palf = fopen(optarg, "rb");
380                         if (!palf) {
381                                 tool_err(0, "failed to open %s", optarg);
382                                 return EXIT_FAILURE;
383                         }
384
385                         break;
386                 case 'O':
387                         overf = fopen(optarg, "rb");
388                         if (!overf) {
389                                 tool_err(0, "failed to open %s", optarg);
390                                 return EXIT_FAILURE;
391                         }
392                         break;
393                 case OPT_PREFIX:
394                         outname = optarg;
395                         break;
396                 case 'V':
397                         tool_version();
398                         return EXIT_SUCCESS;
399                 case 'U':
400                         printusage();
401                         return EXIT_SUCCESS;
402                 case 'H':
403                         printhelp();
404                         return EXIT_SUCCESS;
405                 default:
406                         return EXIT_FAILURE;
407                 }
408         }
409
410         if (mode == MODE_NONE) {
411                 tool_err(-1, "you must specify a mode.");
412                 return EXIT_FAILURE;
413         }
414
415         fmt = lookup_format(fmtstring);
416         if (fmt < 0)
417                 return EXIT_FAILURE;
418
419         if (file)
420                 img = lbx_img_fopen(file);
421         else
422                 img = lbx_img_open(&stdin_handle, &lbx_pipe_fops, NULL);
423
424         if (!img) {
425                 tool_err(-1, "failed to open image: %s.", lbx_errmsg());
426                 return EXIT_FAILURE;
427         }
428
429         if (verbose || mode == MODE_IDENT) {
430                 struct lbx_imginfo info;
431
432                 if (!file)
433                         file = "stdin";
434
435                 lbx_img_getinfo(img, &info);
436                 printf("%s is %hux%hu LBX image, %hhu frame(s)%s%s%s\n",
437                        file, img->width, img->height, img->frames,
438                        info.palettesz ? ", embedded palette" : "",
439                        img->chunk     ? ", chunked" : "",
440                        info.looping   ? ", loops" : "");
441         }
442
443         switch (mode) {
444         case MODE_IDENT:
445                 rc = 0;
446                 break;
447         case MODE_DECODE:
448                 rc = decode(img, palf, overf, fmt, &argv[optind]);
449                 break;
450         }
451
452         lbx_img_close(img);
453         return rc;
454 }