io-tga.c 23.9 KB
Newer Older
1
/* -*- mode: C; c-file-style: "linux" -*- */
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* 
 * GdkPixbuf library - TGA image loader
 * Copyright (C) 1999 Nicola Girardi <nikke@swlibero.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
21 22 23
 */

/*
24 25 26 27 28 29 30 31 32 33
 * Some NOTES about the TGA loader (2001/06/07, nikke@swlibero.org)
 *
 * - The TGAFooter isn't present in all TGA files.  In fact, there's an older
 *   format specification, still in use, which doesn't cover the TGAFooter.
 *   Actually, most TGA files I have are of the older type.  Anyway I put the 
 *   struct declaration here for completeness.
 *
 * - Error handling was designed to be very paranoid.
 */

34
#include <config.h>
35 36 37 38
#include <stdio.h>
#include <string.h>

#include "gdk-pixbuf-private.h"
39
#include "gdk-pixbuf-io.h"
40

41 42
#undef DEBUG_TGA

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
#define TGA_INTERLEAVE_MASK     0xc0
#define TGA_INTERLEAVE_NONE     0x00
#define TGA_INTERLEAVE_2WAY     0x40
#define TGA_INTERLEAVE_4WAY     0x80

#define TGA_ORIGIN_MASK         0x30
#define TGA_ORIGIN_RIGHT        0x10
#define TGA_ORIGIN_UPPER        0x20

enum {
	TGA_TYPE_NODATA = 0,
	TGA_TYPE_PSEUDOCOLOR = 1,
	TGA_TYPE_TRUECOLOR = 2,
	TGA_TYPE_GRAYSCALE = 3,
	TGA_TYPE_RLE_PSEUDOCOLOR = 9,
	TGA_TYPE_RLE_TRUECOLOR = 10,
	TGA_TYPE_RLE_GRAYSCALE = 11
};

#define LE16(p) ((p)[0] + ((p)[1] << 8))

typedef struct _IOBuffer IOBuffer;

typedef struct _TGAHeader TGAHeader;
typedef struct _TGAFooter TGAFooter;

typedef struct _TGAColormap TGAColormap;
typedef struct _TGAColor TGAColor;

typedef struct _TGAContext TGAContext;

struct _TGAHeader {
	guint8 infolen;
	guint8 has_cmap;
	guint8 type;
	
	guint8 cmap_start[2];
	guint8 cmap_n_colors[2];
	guint8 cmap_bpp;
	
	guint8 x_origin[2];
	guint8 y_origin[2];
	
	guint8 width[2];
	guint8 height[2];
	guint8 bpp;
	
	guint8 flags;
};

struct _TGAFooter {
	guint32 extension_area_offset;
	guint32 developer_directory_offset;

	/* Standard TGA signature, "TRUEVISION-XFILE.\0". */
	union {
		gchar sig_full[18];
		struct {
			gchar sig_chunk[16];
			gchar dot, null;
		} sig_struct;
	} sig;
};

struct _TGAColormap {
	gint size;
	TGAColor *cols;
};

struct _TGAColor {
	guchar r, g, b, a;
};

struct _TGAContext {
	TGAHeader *hdr;
	guint rowstride;
119
	guint completed_lines;
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	gboolean run_length_encoded;

	TGAColormap *cmap;
	guint cmap_size;

	GdkPixbuf *pbuf;
	guint pbuf_bytes;
	guint pbuf_bytes_done;
	guchar *pptr;

	IOBuffer *in;

	gboolean skipped_info;
	gboolean prepared;
	gboolean done;

136
	GdkPixbufModuleSizeFunc sfunc;
137 138
	GdkPixbufModulePreparedFunc pfunc;
	GdkPixbufModuleUpdatedFunc ufunc;
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
	gpointer udata;
};

struct _IOBuffer {
	guchar *data;
	guint size;
};

static IOBuffer *io_buffer_new(GError **err)
{
	IOBuffer *buffer;
	buffer = g_try_malloc(sizeof(IOBuffer));
	if (!buffer) {
		g_set_error(err, GDK_PIXBUF_ERROR,
			    GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
154
			    _("Cannot allocate memory for IOBuffer struct"));
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
		return NULL;
	}
	buffer->data = NULL;
	buffer->size = 0;
	return buffer;
}

static IOBuffer *io_buffer_append(IOBuffer *buffer, 
				  const guchar *data, guint len, 
				  GError **err)
{
	if (!buffer)
		return NULL;
	if (!buffer->data) {
		buffer->data = g_try_malloc(len);
		if (!buffer->data) {
			g_set_error(err, GDK_PIXBUF_ERROR,
				    GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
173
				    _("Cannot allocate memory for IOBuffer data"));
174 175 176 177 178 179
			g_free(buffer);
			return NULL;
		}
		g_memmove(buffer->data, data, len);
		buffer->size = len;
	} else {
180 181
		guchar *tmp = g_try_realloc (buffer->data, buffer->size + len);
		if (!tmp) {
182 183
			g_set_error(err, GDK_PIXBUF_ERROR,
				    GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
184
				    _("Cannot realloc IOBuffer data"));
185 186 187
			g_free(buffer);
			return NULL;
		}
188
		buffer->data = tmp;
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
		g_memmove(&buffer->data[buffer->size], data, len);
		buffer->size += len;
	}
	return buffer;
}

static IOBuffer *io_buffer_free_segment(IOBuffer *buffer, 
					guint count,
                                        GError **err)
{
	g_return_val_if_fail(buffer != NULL, NULL);
	g_return_val_if_fail(buffer->data != NULL, NULL);
	if (count == buffer->size) {
		g_free(buffer->data);
		buffer->data = NULL;
		buffer->size = 0;
	} else {
		guchar *new_buf;
		guint new_size;

		new_size = buffer->size - count;
		new_buf = g_try_malloc(new_size);
		if (!new_buf) {
			g_set_error(err, GDK_PIXBUF_ERROR,
				    GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
214
				    _("Cannot allocate temporary IOBuffer data"));
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
			g_free(buffer->data);
			g_free(buffer);
			return NULL;
		}

		g_memmove(new_buf, &buffer->data[count], new_size);
		g_free(buffer->data);
		buffer->data = new_buf;
		buffer->size = new_size;
	}
	return buffer;
}

static void io_buffer_free(IOBuffer *buffer)
{
	g_return_if_fail(buffer != NULL);
231
	g_free(buffer->data);
232 233 234 235 236 237 238 239
	g_free(buffer);
}

static void free_buffer(guchar *pixels, gpointer data)
{
	g_free(pixels);
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
static GdkPixbuf *get_contiguous_pixbuf (guint width, 
					 guint height, 
					 gboolean has_alpha)
{
	guchar *pixels;
	guint channels, rowstride, bytes;
	
	if (has_alpha) 
		channels = 4;
	else 
		channels = 3;
	
	rowstride = width * channels;
	
	if (rowstride / channels != width)
                return NULL;                

	bytes = height * rowstride;

        if (bytes / rowstride != height)
                return NULL;                

        pixels = g_try_malloc (bytes);

	if (!pixels)
		return NULL;
	
	return gdk_pixbuf_new_from_data (pixels, GDK_COLORSPACE_RGB, has_alpha, 8,
					 width, height, rowstride, free_buffer, NULL);
}

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
static void pixbuf_flip_row (GdkPixbuf *pixbuf, guchar *ph)
{
	guchar *p, *s;
	guchar tmp;
	gint count;

	p = ph;
	s = p + pixbuf->n_channels * (pixbuf->width - 1);
	while (p < s) {
		for (count = pixbuf->n_channels; count > 0; count--, p++, s++) {
			tmp = *p;
			*p = *s;
			*s = tmp;
		}
		s -= 2 * pixbuf->n_channels;
	}		
287 288
}

289
static void pixbuf_flip_vertically (GdkPixbuf *pixbuf)
290
{
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	guchar *ph, *sh, *p, *s;
	guchar tmp;
	gint count;

	ph = pixbuf->pixels;
	sh = pixbuf->pixels + pixbuf->height*pixbuf->rowstride;
	while (ph < sh - pixbuf->rowstride) {
		p = ph;
		s = sh - pixbuf->rowstride;
		for (count = pixbuf->n_channels * pixbuf->width; count > 0; count--, p++, s++) {
			tmp = *p;
			*p = *s;
			*s = tmp;
		}
		sh -= pixbuf->rowstride;
		ph += pixbuf->rowstride;
307 308 309 310 311 312
	}
}

static gboolean fill_in_context(TGAContext *ctx, GError **err)
{
	gboolean alpha;
313
	guint w, h;
314 315 316 317 318 319 320 321 322 323 324 325

	g_return_val_if_fail(ctx != NULL, FALSE);

	ctx->run_length_encoded =
		((ctx->hdr->type == TGA_TYPE_RLE_PSEUDOCOLOR)
		 || (ctx->hdr->type == TGA_TYPE_RLE_TRUECOLOR)
		 || (ctx->hdr->type == TGA_TYPE_RLE_GRAYSCALE));

	if (ctx->hdr->has_cmap)
		ctx->cmap_size = ((ctx->hdr->cmap_bpp + 7) >> 3) *
			LE16(ctx->hdr->cmap_n_colors);

326 327
	alpha = ((ctx->hdr->bpp == 16) || 
		 (ctx->hdr->bpp == 32) ||
328 329
		 (ctx->hdr->has_cmap && (ctx->hdr->cmap_bpp == 32)));

330 331 332
	w = LE16(ctx->hdr->width);
	h = LE16(ctx->hdr->height);

333 334 335 336 337 338 339 340 341 342
	if (ctx->sfunc) {
		gint wi = w;
		gint hi = h;
		
		(*ctx->sfunc) (&wi, &hi, ctx->udata);
		
		if (wi == 0 || hi == 0) 
			return FALSE;
	}

343
	ctx->pbuf = get_contiguous_pixbuf (w, h, alpha);
344

345 346
	if (!ctx->pbuf) {
		g_set_error(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
347
			    _("Cannot allocate new pixbuf"));
348 349
		return FALSE;
	}
350

351
	ctx->pbuf_bytes = ctx->pbuf->rowstride * ctx->pbuf->height;
352 353 354 355
	if (ctx->hdr->flags & TGA_ORIGIN_UPPER || ctx->run_length_encoded)
		ctx->pptr = ctx->pbuf->pixels;
	else
		ctx->pptr = ctx->pbuf->pixels + (ctx->pbuf->height - 1)*ctx->pbuf->rowstride;
356

357 358 359 360
	if (ctx->hdr->type == TGA_TYPE_PSEUDOCOLOR)
	  ctx->rowstride = ctx->pbuf->width;
	else if (ctx->hdr->type == TGA_TYPE_GRAYSCALE)
	  ctx->rowstride = (alpha ? ctx->pbuf->width * 2 : ctx->pbuf->width);
361 362 363
	else if (ctx->hdr->type == TGA_TYPE_TRUECOLOR)
		ctx->rowstride = ctx->pbuf->rowstride;

364
	ctx->completed_lines = 0;
365 366 367 368 369 370 371
	return TRUE;
}

static void parse_data_for_row_pseudocolor(TGAContext *ctx)
{
	guchar *s = ctx->in->data;
	guint upper_bound = ctx->pbuf->width;
372
	guchar *p = ctx->pptr;
373 374

	for (; upper_bound; upper_bound--, s++) {
375 376 377
		*p++ = ctx->cmap->cols[*s].r;
		*p++ = ctx->cmap->cols[*s].g;
		*p++ = ctx->cmap->cols[*s].b;
378
		if (ctx->hdr->cmap_bpp == 32)
379
			*p++ = ctx->cmap->cols[*s].a;
380 381 382 383 384
	}
}

static void swap_channels(TGAContext *ctx)
{
385 386 387
	guchar swap;
	guint count;
	guchar *p = ctx->pptr;
388
	for (count = ctx->pbuf->width; count; count--) {
389 390 391 392
	  swap = p[0];
	  p[0] = p[2];
	  p[2] = swap;
	  p += ctx->pbuf->n_channels;
393 394 395 396 397 398 399 400 401 402 403 404 405 406
	}
}

static void parse_data_for_row_truecolor(TGAContext *ctx)
{
	g_memmove(ctx->pptr, ctx->in->data, ctx->pbuf->rowstride);
	swap_channels(ctx);
}

static void parse_data_for_row_grayscale(TGAContext *ctx)
{
	guchar *s = ctx->in->data;
	guint upper_bound = ctx->pbuf->width;

407
	guchar *p = ctx->pptr;
408
	for (; upper_bound; upper_bound--) {
409 410 411 412
		p[0] = p[1] = p[2] = *s++;
		if (ctx->pbuf->n_channels == 4)
		  p[3] = *s++;
		p += ctx->pbuf->n_channels;
413 414 415 416 417
	}
}

static gboolean parse_data_for_row(TGAContext *ctx, GError **err)
{
418 419
	guint row;

420 421 422 423 424 425
	if (ctx->hdr->type == TGA_TYPE_PSEUDOCOLOR)
		parse_data_for_row_pseudocolor(ctx);
	else if (ctx->hdr->type == TGA_TYPE_TRUECOLOR)
		parse_data_for_row_truecolor(ctx);
	else if (ctx->hdr->type == TGA_TYPE_GRAYSCALE)
		parse_data_for_row_grayscale(ctx);
426 427 428 429 430 431 432 433 434 435 436

	if (ctx->hdr->flags & TGA_ORIGIN_RIGHT)
		pixbuf_flip_row (ctx->pbuf, ctx->pptr);
	if (ctx->hdr->flags & TGA_ORIGIN_UPPER)
		ctx->pptr += ctx->pbuf->rowstride;
	else
		ctx->pptr -= ctx->pbuf->rowstride;
	ctx->pbuf_bytes_done += ctx->pbuf->rowstride;
	if (ctx->pbuf_bytes_done == ctx->pbuf_bytes)
		ctx->done = TRUE;
	
437 438 439
	ctx->in = io_buffer_free_segment(ctx->in, ctx->rowstride, err);
	if (!ctx->in)
		return FALSE;
440 441 442
	row = (ctx->pptr - ctx->pbuf->pixels) / ctx->pbuf->rowstride - 1;
	if (ctx->ufunc)
		(*ctx->ufunc) (ctx->pbuf, 0, row, ctx->pbuf->width, 1, ctx->udata);
443 444 445 446 447 448 449 450
	return TRUE;
}

static void write_rle_data(TGAContext *ctx, TGAColor *color, guint *rle_count)
{
	for (; *rle_count; (*rle_count)--) {
		g_memmove(ctx->pptr, (guchar *) color, ctx->pbuf->n_channels);
		ctx->pptr += ctx->pbuf->n_channels;
451 452 453
		ctx->pbuf_bytes_done += ctx->pbuf->n_channels;
		if (ctx->pbuf_bytes_done == ctx->pbuf_bytes)
			return;
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
	}
}

static guint parse_rle_data_pseudocolor(TGAContext *ctx)
{
	guint rle_num, raw_num;
	guchar *s, tag;
	guint n;

	g_return_val_if_fail(ctx->in->size > 0, 0);
	s = ctx->in->data;

	for (n = 0; n < ctx->in->size; ) {
		tag = *s;
		s++, n++;
		if (tag & 0x80) {
			if (n == ctx->in->size) {
				return --n;
			} else {
				rle_num = (tag & 0x7f) + 1;
				write_rle_data(ctx, &ctx->cmap->cols[*s], &rle_num);
				s++, n++;
476 477 478 479
				if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) {
					ctx->done = TRUE;
					return n;
				}
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
			}
		} else {
			raw_num = tag + 1;
			if (n + raw_num >= ctx->in->size) {
				return --n;
			} else {
				for (; raw_num; raw_num--) {
					*ctx->pptr++ =
						ctx->cmap->cols[*s].r;
					*ctx->pptr++ =
						ctx->cmap->cols[*s].g;
					*ctx->pptr++ =
						ctx->cmap->cols[*s].b;
					if (ctx->pbuf->n_channels == 4)
						*ctx->pptr++ = ctx->cmap->cols[*s].a;
					s++, n++;
					ctx->pbuf_bytes_done += ctx->pbuf->n_channels;
497 498 499 500
					if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) {
						ctx->done = TRUE;
						return n;
					}
501 502 503 504
				}
			}
		}
	}
505

Matthias Clasen's avatar
Matthias Clasen committed
506
	if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) 
507
		ctx->done = TRUE;
Matthias Clasen's avatar
Matthias Clasen committed
508
	
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
	return n;
}

static guint parse_rle_data_truecolor(TGAContext *ctx)
{
	TGAColor col;
	guint rle_num, raw_num;
	guchar *s, tag;
	guint n = 0;

	g_return_val_if_fail(ctx->in->size > 0, 0);
	s = ctx->in->data;

	for (n = 0; n < ctx->in->size; ) {
		tag = *s;
		s++, n++;
		if (tag & 0x80) {
			if (n + ctx->pbuf->n_channels >= ctx->in->size) {
				return --n;
			} else {
				rle_num = (tag & 0x7f) + 1;
				col.b = *s++;
				col.g = *s++;
				col.r = *s++;
				if (ctx->hdr->bpp == 32)
					col.a = *s++;
				n += ctx->pbuf->n_channels;
536 537 538 539 540
				write_rle_data(ctx, &col, &rle_num);
				if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) {
					ctx->done = TRUE;
					return n;
				}
541 542 543 544 545 546
			}
		} else {
			raw_num = tag + 1;
			if (n + (raw_num * ctx->pbuf->n_channels) >= ctx->in->size) {
				return --n;
			} else {
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
				for (; raw_num; raw_num--) {
					ctx->pptr[2] = *s++;
					ctx->pptr[1] = *s++;
					ctx->pptr[0] = *s++;
					if (ctx->hdr->bpp == 32)
						ctx->pptr[3] = *s++;
					n += ctx->pbuf->n_channels;
					ctx->pptr += ctx->pbuf->n_channels;
					ctx->pbuf_bytes_done += ctx->pbuf->n_channels;
					if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) {
						ctx->done = TRUE;
						return n;
					}
				}
				
				if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) {
					ctx->done = TRUE;
					return n;
				}
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
			}
		}
	}
	if (ctx->pbuf_bytes_done == ctx->pbuf_bytes)
		ctx->done = TRUE;
	return n;
}

static guint parse_rle_data_grayscale(TGAContext *ctx)
{
	TGAColor tone;
	guint rle_num, raw_num;
	guchar *s, tag;
	guint n;

	g_return_val_if_fail(ctx->in->size > 0, 0);
	s = ctx->in->data;

	for (n = 0; n < ctx->in->size; ) {
		tag = *s;
		s++, n++;
		if (tag & 0x80) {
588
			if (n + (ctx->pbuf->n_channels == 4 ? 2 : 1) >= ctx->in->size) {
589 590 591 592 593
				return --n;
			} else {
				rle_num = (tag & 0x7f) + 1;
				tone.r = tone.g = tone.b = *s;
				s++, n++;
594 595 596 597
				if (ctx->pbuf->n_channels == 4) {
					tone.a = *s++;
					n++;
				}
598
				write_rle_data(ctx, &tone, &rle_num);
599 600 601 602
				if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) {
					ctx->done = TRUE;
					return n;
				}
603 604 605
			}
		} else {
			raw_num = tag + 1;
606
			if (n + raw_num * (ctx->pbuf->n_channels == 4 ? 2 : 1) >= ctx->in->size) {
607 608 609 610 611
				return --n;
			} else {
				for (; raw_num; raw_num--) {
					ctx->pptr[0] = ctx->pptr[1] = ctx->pptr[2] = *s;
					s++, n++;
612 613 614 615 616 617 618 619 620 621
					if (ctx->pbuf->n_channels == 4) {
						ctx->pptr[3] = *s++;
						n++;
					}
					ctx->pptr += ctx->pbuf->n_channels;
					ctx->pbuf_bytes_done += ctx->pbuf->n_channels;
					if (ctx->pbuf_bytes_done == ctx->pbuf_bytes) {
						ctx->done = TRUE;
						return n;
					}
622 623 624 625 626 627 628 629 630 631 632
				}
			}
		}
	}
	if (ctx->pbuf_bytes_done == ctx->pbuf_bytes)
		ctx->done = TRUE;
	return n;
}

static gboolean parse_rle_data(TGAContext *ctx, GError **err)
{
633
	guint rows = 0;
634
	guint count = 0;
635
	guint bytes_done_before = ctx->pbuf_bytes_done;
636 637

	if (ctx->hdr->type == TGA_TYPE_RLE_PSEUDOCOLOR)
638
		count = parse_rle_data_pseudocolor(ctx);
639
	else if (ctx->hdr->type == TGA_TYPE_RLE_TRUECOLOR)
640
		count = parse_rle_data_truecolor(ctx);
641
	else if (ctx->hdr->type == TGA_TYPE_RLE_GRAYSCALE)
642
		count = parse_rle_data_grayscale(ctx);
643 644 645 646 647 648 649 650

	if (ctx->hdr->flags & TGA_ORIGIN_RIGHT) {
		guchar *row = ctx->pbuf->pixels + (bytes_done_before / ctx->pbuf->rowstride) * ctx->pbuf->rowstride;
		guchar *row_after = ctx->pbuf->pixels + (ctx->pbuf_bytes_done / ctx->pbuf->rowstride) * ctx->pbuf->rowstride;
		for (; row < row_after; row += ctx->pbuf->rowstride)
			pixbuf_flip_row (ctx->pbuf, row);
	}

651 652 653
	ctx->in = io_buffer_free_segment(ctx->in, count, err);
	if (!ctx->in)
		return FALSE;
654 655 656 657 658 659

	if (ctx->done) {
		/* FIXME doing the vertical flipping afterwards is not
		 * perfect, but doing it during the rle decoding in place
		 * is considerably more work. 
		 */
Matthias Clasen's avatar
Matthias Clasen committed
660
		if (!(ctx->hdr->flags & TGA_ORIGIN_UPPER)) {
661
			pixbuf_flip_vertically (ctx->pbuf);
Matthias Clasen's avatar
Matthias Clasen committed
662 663
			ctx->hdr->flags |= TGA_ORIGIN_UPPER;
		}
664

665 666 667
	}
		
	rows = ctx->pbuf_bytes_done / ctx->pbuf->rowstride - bytes_done_before / ctx->pbuf->rowstride;
668
	if (ctx->ufunc)
669 670
		(*ctx->ufunc) (ctx->pbuf, 0, bytes_done_before / ctx->pbuf->rowstride,
			       ctx->pbuf->width, rows,
671 672
			       ctx->udata);

673 674 675 676 677 678 679 680 681 682 683 684 685 686
	return TRUE;
}

static gboolean try_colormap(TGAContext *ctx, GError **err)
{
	static guchar *p;
	static guint n;

	g_return_val_if_fail(ctx != NULL, FALSE);
	g_return_val_if_fail(ctx->cmap_size > 0, TRUE);

	ctx->cmap = g_try_malloc(sizeof(TGAColormap));
	if (!ctx->cmap) {
		g_set_error(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
687
			    _("Cannot allocate colormap structure"));
688 689 690 691 692 693
		return FALSE;
	}
	ctx->cmap->size = LE16(ctx->hdr->cmap_n_colors);
	ctx->cmap->cols = g_try_malloc(sizeof(TGAColor) * ctx->cmap->size);
	if (!ctx->cmap->cols) {
		g_set_error(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
694
			    _("Cannot allocate colormap entries"));
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
		return FALSE;
	}

	p = ctx->in->data;
	for (n = 0; n < ctx->cmap->size; n++) {
		if ((ctx->hdr->cmap_bpp == 15) || (ctx->hdr->cmap_bpp == 16)) {
			guint16 col = p[0] + (p[1] << 8);
			ctx->cmap->cols[n].b = (col >> 7) & 0xf8;
			ctx->cmap->cols[n].g = (col >> 2) & 0xf8;
			ctx->cmap->cols[n].r = col << 3;
			p += 2;
		}
		else if ((ctx->hdr->cmap_bpp == 24) || (ctx->hdr->cmap_bpp == 32)) {
			ctx->cmap->cols[n].b = *p++;
			ctx->cmap->cols[n].g = *p++;
			ctx->cmap->cols[n].r = *p++;
			if (ctx->hdr->cmap_bpp == 32)
				ctx->cmap->cols[n].a = *p++;
		} else {
			g_set_error(err, GDK_PIXBUF_ERROR, 
				    GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
				    _("Unexpected bitdepth for colormap entries"));
			return FALSE;
		}
	}
	ctx->in = io_buffer_free_segment(ctx->in, ctx->cmap_size, err);
	if (!ctx->in)
		return FALSE;
	return TRUE;
}

static gboolean try_preload(TGAContext *ctx, GError **err)
{
	if (!ctx->hdr) {
		if (ctx->in->size >= sizeof(TGAHeader)) {
			ctx->hdr = g_try_malloc(sizeof(TGAHeader));
			if (!ctx->hdr) {
				g_set_error(err, GDK_PIXBUF_ERROR,
					    GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
734
					    _("Cannot allocate TGA header memory"));
735 736 737 738
				return FALSE;
			}
			g_memmove(ctx->hdr, ctx->in->data, sizeof(TGAHeader));
			ctx->in = io_buffer_free_segment(ctx->in, sizeof(TGAHeader), err);
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
#ifdef DEBUG_TGA
			g_print ("infolen %d "
				 "has_cmap %d "
				 "type %d "
				 "cmap_start %d "
				 "cmap_n_colors %d "
				 "cmap_bpp %d "
				 "x %d y %d width %d height %d bpp %d "
				 "flags %#x",
				 ctx->hdr->infolen,
				 ctx->hdr->has_cmap,
				 ctx->hdr->type,
				 LE16(ctx->hdr->cmap_start),
				 LE16(ctx->hdr->cmap_n_colors),
				 ctx->hdr->cmap_bpp,
				 LE16(ctx->hdr->x_origin),
				 LE16(ctx->hdr->y_origin),
				 LE16(ctx->hdr->width),
				 LE16(ctx->hdr->height),
				 ctx->hdr->bpp,
				 ctx->hdr->flags);
#endif
761 762
			if (!ctx->in)
				return FALSE;
763 764 765 766 767
			if (LE16(ctx->hdr->width) == 0 || 
			    LE16(ctx->hdr->height) == 0) {
				g_set_error(err, GDK_PIXBUF_ERROR,
					    GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
					    _("TGA image has invalid dimensions"));
768
				return FALSE;
769
			}
770
			if ((ctx->hdr->flags & TGA_INTERLEAVE_MASK) != TGA_INTERLEAVE_NONE) {
771 772 773 774 775
				g_set_error(err, GDK_PIXBUF_ERROR, 
					    GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
					    _("TGA image type not supported"));
				return FALSE;
			}
776 777 778
			switch (ctx->hdr->type) {
			    case TGA_TYPE_PSEUDOCOLOR:
			    case TGA_TYPE_RLE_PSEUDOCOLOR:
779 780 781 782 783 784 785 786
				    if (ctx->hdr->bpp != 8) {
					    g_set_error(err, GDK_PIXBUF_ERROR, 
							GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
							_("TGA image type not supported"));
					    return FALSE;
				    }
				    break;
			    case TGA_TYPE_TRUECOLOR:
787
			    case TGA_TYPE_RLE_TRUECOLOR:
788 789 790 791 792 793 794 795 796
				    if (ctx->hdr->bpp != 24 &&
					ctx->hdr->bpp != 32) {
					    g_set_error(err, GDK_PIXBUF_ERROR, 
							GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
							_("TGA image type not supported"));
					    return FALSE;
				    }			      
				    break;
			    case TGA_TYPE_GRAYSCALE:
797
			    case TGA_TYPE_RLE_GRAYSCALE:
798 799 800 801 802 803 804 805
				    if (ctx->hdr->bpp != 8 &&
					ctx->hdr->bpp != 16) {
					    g_set_error(err, GDK_PIXBUF_ERROR, 
							GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
							_("TGA image type not supported"));
					    return FALSE;
				    }
				    break;
806
			    default:
807 808 809 810
				    g_set_error(err, GDK_PIXBUF_ERROR, 
						GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
						_("TGA image type not supported"));
				    return FALSE;    
811
			}
812 813
			if (!fill_in_context(ctx, err))
				return FALSE;
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
		} else {
			return TRUE;
		}
	}
	if (!ctx->skipped_info) {
		if (ctx->in->size >= ctx->hdr->infolen) {
			ctx->in = io_buffer_free_segment(ctx->in, ctx->hdr->infolen, err);
			if (!ctx->in)
				return FALSE;
			ctx->skipped_info = TRUE;
		} else {
			return TRUE;
		}
	}
	if (ctx->hdr->has_cmap && !ctx->cmap) {
		if (ctx->in->size >= ctx->cmap_size) {
			if (!try_colormap(ctx, err))
				return FALSE;
		} else {
			return TRUE;
		}
	}
	if (!ctx->prepared) {
837 838
		if (ctx->pfunc)
			(*ctx->pfunc) (ctx->pbuf, NULL, ctx->udata);
839 840 841 842 843 844
		ctx->prepared = TRUE;
	}
	/* We shouldn't get here anyway. */
	return TRUE;
}

845 846 847
static gpointer gdk_pixbuf__tga_begin_load(GdkPixbufModuleSizeFunc f0,
                                           GdkPixbufModulePreparedFunc f1,
					   GdkPixbufModuleUpdatedFunc f2,
848 849 850 851 852 853 854 855
					   gpointer udata, GError **err)
{
	TGAContext *ctx;

	ctx = g_try_malloc(sizeof(TGAContext));
	if (!ctx) {
		g_set_error(err, GDK_PIXBUF_ERROR, 
			    GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
856
			    _("Cannot allocate memory for TGA context struct"));
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
		return NULL;
	}

	ctx->hdr = NULL;
	ctx->rowstride = 0;
	ctx->run_length_encoded = FALSE;

	ctx->cmap = NULL;
	ctx->cmap_size = 0;

	ctx->pbuf = NULL;
	ctx->pbuf_bytes = 0;
	ctx->pbuf_bytes_done = 0;
	ctx->pptr = NULL;

	ctx->in = io_buffer_new(err);
	if (!ctx->in) {
		g_free(ctx);
		return NULL;
	}

	ctx->skipped_info = FALSE;
	ctx->prepared = FALSE;
	ctx->done = FALSE;

882
	ctx->sfunc = f0;
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
	ctx->pfunc = f1;
	ctx->ufunc = f2;
	ctx->udata = udata;

	return ctx;
}

static gboolean gdk_pixbuf__tga_load_increment(gpointer data,
					       const guchar *buffer,
					       guint size,
					       GError **err)
{
	TGAContext *ctx = (TGAContext*) data;
	g_return_val_if_fail(ctx != NULL, FALSE);

	if (ctx->done)
		return TRUE;

	g_return_val_if_fail(buffer != NULL, TRUE);
	ctx->in = io_buffer_append(ctx->in, buffer, size, err);
	if (!ctx->in)
		return FALSE;
	if (!ctx->prepared) {
		if (!try_preload(ctx, err))
			return FALSE;
		if (!ctx->prepared)
			return TRUE;
		if (ctx->in->size == 0)
			return TRUE;
	}

	if (ctx->run_length_encoded) {
		if (!parse_rle_data(ctx, err))
			return FALSE;
	} else {
918 919 920 921 922 923
		while (ctx->in->size >= ctx->rowstride) {
			if (ctx->completed_lines >= ctx->pbuf->height) {
				g_set_error(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_FAILED,
					    _("Excess data in file"));
				return FALSE;
			}
924 925
			if (!parse_data_for_row(ctx, err))
				return FALSE;
926 927
			ctx->completed_lines++;
		}
928 929 930 931 932 933 934 935 936 937
	}

	return TRUE;
}

static gboolean gdk_pixbuf__tga_stop_load(gpointer data, GError **err)
{
	TGAContext *ctx = (TGAContext *) data;
	g_return_val_if_fail(ctx != NULL, FALSE);

Matthias Clasen's avatar
Matthias Clasen committed
938 939 940 941 942 943 944
	if (!(ctx->hdr->flags & TGA_ORIGIN_UPPER) && ctx->run_length_encoded) {
		pixbuf_flip_vertically (ctx->pbuf);
		if (ctx->ufunc)
			(*ctx->ufunc) (ctx->pbuf, 0, 0,
				       ctx->pbuf->width, ctx->pbuf->height,
			       	       ctx->udata);
	}
945
	g_free (ctx->hdr);
946
	if (ctx->cmap) {
947
	  g_free (ctx->cmap->cols);
948 949
	  g_free (ctx->cmap);
	}
950
	if (ctx->pbuf)
951
		g_object_unref (ctx->pbuf);
952
	if (ctx->in && ctx->in->size)
953
		ctx->in = io_buffer_free_segment (ctx->in, ctx->in->size, err);
954
	if (!ctx->in) {
955
		g_free (ctx);
956 957
		return FALSE;
	}
958 959
	io_buffer_free (ctx->in);
	g_free (ctx);
960 961 962
	return TRUE;
}

963 964 965 966 967 968
#ifndef INCLUDE_tga
#define MODULE_ENTRY(type,function) function
#else
#define MODULE_ENTRY(type,function) _gdk_pixbuf__ ## type ## _ ## function
#endif

969
void
970
MODULE_ENTRY (tga, fill_vtable) (GdkPixbufModule *module)
971 972 973 974 975
{
	module->begin_load = gdk_pixbuf__tga_begin_load;
	module->stop_load = gdk_pixbuf__tga_stop_load;
	module->load_increment = gdk_pixbuf__tga_load_increment;
}
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003

void
MODULE_ENTRY (tga, fill_info) (GdkPixbufFormat *info)
{
	static GdkPixbufModulePattern signature[] = {
		{ " \x1\x1", "x  ", 100 },
		{ " \x1\x9", "x  ", 100 },
		{ "  \x2", "xz ",  99 }, /* only 99 since .CUR also matches this */
		{ "  \x3", "xz ", 100 },
		{ "  \xa", "xz ", 100 },
		{ "  \xb", "xz ", 100 },
		{ NULL, NULL, 0 }
	};
	static gchar * mime_types[] = {
		"image/x-tga",
		NULL
	};
	static gchar * extensions[] = {
		"tga",
		"targa",
		NULL
	};

	info->name = "tga";
	info->signature = signature;
	info->description = N_("The Targa image format");
	info->mime_types = mime_types;
	info->extensions = extensions;
1004
	info->flags = GDK_PIXBUF_FORMAT_THREADSAFE;
1005
	info->license = "LGPL";
1006
}