png2ff.c 1.95 KB
Newer Older
FRIGN's avatar
FRIGN committed
1
/* See LICENSE file for copyright and license details. */
2 3
#include <arpa/inet.h>

4
#include <errno.h>
FRIGN's avatar
FRIGN committed
5 6 7
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
8
#include <string.h>
FRIGN's avatar
FRIGN committed
9

FRIGN's avatar
FRIGN committed
10
#include <png.h>
FRIGN's avatar
FRIGN committed
11

12
#include "util.h"
13

14
static void
15
png_err(png_struct *pngs, const char *msg)
16
{
17
	(void)pngs;
Laslo Hunhold's avatar
Laslo Hunhold committed
18
	die("libpng: %s", msg);
19 20
}

21
static void
22 23 24 25 26 27
png_setup_reader(png_struct **s, png_info **i, uint32_t *w, uint32_t *h)
{
	*s = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, png_err, NULL);
	*i = png_create_info_struct(*s);

	if (!*s || !*i) {
Laslo Hunhold's avatar
Laslo Hunhold committed
28
		die("Failed to initialize libpng");
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
	}

	png_init_io(*s, stdin);
	if (png_get_valid(*s, *i, PNG_INFO_tRNS)) {
		png_set_tRNS_to_alpha(*s);
	}
	png_set_add_alpha(*s, 255*257, PNG_FILLER_AFTER);
	png_set_expand_gray_1_2_4_to_8(*s);
	png_set_gray_to_rgb(*s);
	png_set_packing(*s);
	png_read_png(*s, *i, PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, NULL);
	*w = png_get_image_width(*s, *i);
	*h = png_get_image_height(*s, *i);
}

static void
usage(void)
{
Laslo Hunhold's avatar
Laslo Hunhold committed
47
	die("usage: %s", argv0);
48 49
}

FRIGN's avatar
FRIGN committed
50 51 52
int
main(int argc, char *argv[])
{
53 54
	png_struct *pngs;
	png_info *pngi;
55
	uint32_t width, height, rowlen, r, i;
56 57
	uint16_t *row;
	uint8_t **pngrows;
FRIGN's avatar
FRIGN committed
58

59
	/* arguments */
60 61 62
	argv0 = argv[0], argc--, argv++;

	if (argc) {
63
		usage();
FRIGN's avatar
FRIGN committed
64
	}
FRIGN's avatar
FRIGN committed
65

66 67 68
	/* prepare */
	png_setup_reader(&pngs, &pngi, &width, &height);
	row = ereallocarray(NULL, width, (sizeof("RGBA") - 1) * sizeof(uint16_t));
69
	rowlen = width * (sizeof("RGBA") - 1);
70
	pngrows = png_get_rows(pngs, pngi);
71

FRIGN's avatar
FRIGN committed
72
	/* write data */
73
	ff_write_header(width, height);
74

FRIGN's avatar
FRIGN committed
75
	switch(png_get_bit_depth(pngs, pngi)) {
76
	case 8:
77
		for (r = 0; r < height; ++r) {
78 79
			for (i = 0; i < rowlen; i++) {
				row[i] = htons(257 * pngrows[r][i]);
80
			}
81
			efwrite(row, sizeof(uint16_t), rowlen, stdout);
FRIGN's avatar
FRIGN committed
82
		}
83 84
		break;
	case 16:
85
		for (r = 0; r < height; ++r) {
86
			efwrite(pngrows[r], sizeof(uint16_t), rowlen, stdout);
87
		}
88 89
		break;
	default:
Laslo Hunhold's avatar
Laslo Hunhold committed
90
		die("Invalid bit-depth");
FRIGN's avatar
FRIGN committed
91 92
	}

93
	/* clean up */
FRIGN's avatar
FRIGN committed
94
	png_destroy_read_struct(&pngs, &pngi, NULL);
FRIGN's avatar
FRIGN committed
95

96
	return fshut(stdout, "<stdout>");
FRIGN's avatar
FRIGN committed
97
}