aboutsummaryrefslogtreecommitdiffstats
path: root/screenshot.c
blob: 2c749426d56403e3988aae54294f57d8f0a26d75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*
 * Take a PNG screenshot of an SDL surface
 */

#include "compiler.h"
#include "screenshot.h"
#include "abcio.h"
#include "hostfile.h"

#include <png.h>

const char *screen_path;

static inline void *pixel_row(const SDL_Surface *surf, size_t y)
{
    return (uint8_t *)surf->pixels + (y * surf->pitch);
}

struct sort_pixel {
    uint32_t pix;			/* Pixel value */
    uint32_t pos;			/* Position index */
};

static int sort_by_pixel(const void *vp1, const void *vp2)
{
    const uint32_t pix1 = ((const struct sort_pixel *)vp1)->pix;
    const uint32_t pix2 = ((const struct sort_pixel *)vp2)->pix;

    /* A simple subtract here risks overflowing an int */
    return -(pix1 < pix2) | (pix1 > pix2);
}

/* 32-bit pixel format; the exact aspects of which are arbitrary */
static const SDL_PixelFormat argbfmt = {
    NULL,			/* palette */
    32,				/* bits per pixel */
    4,				/* bytes per pixel */
    0, 0, 0, 0,			/* precision loss (8 = all alpha lost) */
    16,				/* Rshift */
    8,				/* Gshift */
    0,				/* Bshift */
    24,				/* Ashift */
    0x00ff0000,			/* Rmask */
    0x0000ff00,			/* Gmask */
    0x000000ff,			/* Bmask */
    0xff000000,			/* Amask */
    0,				/* No actual color key */
    255				/* Completely opaque */
};

#define MAX_PALETTE 256
/* Returns the number of indicies, or -1 on failure */
static int
make_indexed(SDL_Surface *surf, uint8_t **data, png_color **palettep)
{
    struct sort_pixel *pixp = NULL;	/* Pixel pointers */
    struct sort_pixel *ppp;		/* Pixel pointer pointer */
    const uint32_t *pvp;		/* Pixel value pointer */
    uint32_t pos;			/* Current position index */
    size_t np;				/* Total number of pixels */
    size_t i;
    int x, y;
    int last_index;			/* Last allocated index */
    uint32_t last_pixel;		/* Last equivalent pixel */
    SDL_PixelFormat *fmt;		/* Cached for speed */
    SDL_PixelFormat cfmt;
    bool surface_copy = false;		/* We copied the surface */
    uint8_t *iimg = NULL;		/* Actual indexed image */
    png_color *palette = NULL;

    /* This is kind of an idiotic algorithm, but it works and is kind of fun */

    /* If this not a 32-bit surface, make it one */
    if (surf->format->BytesPerPixel != 4) {
      cfmt = argbfmt;
      surface_copy = true;	/* We created a new surface, need to free it */
      surf = SDL_ConvertSurface(surf, &cfmt, SDL_SWSURFACE);
      if (!surf)
	goto err;
    }

    /* 1. Allocate arrays and initialize the position array */
    np = surf->w * surf->h;	/* Total pixels */

    iimg = malloc(np);
    if (!iimg)
	goto err;
    pixp = malloc(np * sizeof *pixp);
    if (!pixp)
	goto err;
    palette = calloc(MAX_PALETTE, sizeof *palette);
    if (!palette)
	goto err;

    SDL_LockSurface(surf);
    ppp = pixp;
    pos = 0;
    for (y = 0; y < surf->h; y++) {
	pvp = pixel_row(surf, y);
	for (x = 0; x < surf->w; x++) {
	    ppp->pix = *pvp++;
	    ppp->pos = pos++;
	    ppp++;
	}
    }
    SDL_UnlockSurface(surf);

    /* 2. Sort by pixel value */
    qsort(pixp, np, sizeof *pixp, sort_by_pixel);

    /* 3. Create palette and index values */
    fmt = surf->format;
    ppp = pixp;
    last_pixel = ~ppp->pix;	/* Make sure we don't match on the first */
    last_index = -1;
    for (i = 0; i < np; i++) {
	if (ppp->pix != last_pixel) {
	    last_pixel = ppp->pix;
	    last_index++;
	    if (last_index >= MAX_PALETTE)
		goto err;
	    SDL_GetRGB(last_pixel, fmt,
		       &palette[last_index].red,
		       &palette[last_index].green,
		       &palette[last_index].blue);
	}
	iimg[ppp->pos] = last_index;
	ppp++;
    }

    /* Done! */
    last_index++;		/* Convert to a count */
common_exit:
    *data = iimg;
    *palettep = palette;
    if (pixp)
	free(pixp);
    if (surface_copy && surf)
      SDL_FreeSurface(surf);
    return last_index;

err:
    if (palette) {
	free(palette);
	palette = NULL;
    }
    if (iimg) {
	free(iimg);
	iimg = NULL;
    }
    last_index = -1;		/* Return -1 */
    goto common_exit;
}

static void my_png_error(png_structp png, png_const_charp errmsg)
{
    (void)errmsg;
    longjmp(png_jmpbuf(png), 1);
}

static void my_png_warning(png_structp png, png_const_charp warnmsg)
{
    (void)png;
    (void)warnmsg;
}

/* This is the pixel format that PNG uses in 8-bit RGB mode */
static const SDL_PixelFormat rgbfmt = {
    NULL,			/* palette */
    24,				/* bits per pixel */
    3,				/* bytes per pixel */
    0, 0, 0, 8,			/* precision loss (8 = all alpha lost) */
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
    0,				/* Rshift */
    8,				/* Gshift */
    16,				/* Bshift */
    0,				/* Ashift */
    0x000000ff,			/* Rmask */
    0x0000ff00,			/* Gmask */
    0x00ff0000,			/* Bmask */
#else
    16,				/* Rshift */
    8,				/* Gshift */
    0,				/* Bshift */
    0,				/* Ashift */
    0x00ff0000,			/* Rmask */
    0x0000ff00,			/* Gmask */
    0x000000ff,			/* Bmask */
#endif
    0x00000000,			/* Amask */
    0,				/* No actual color key */
    255				/* Completely opaque */
};

/*
 * This is a bit of a hack to work around potentially dangerous
 * setjmp() side effects.  The structure contains anything that
 * we may have to deallocate or clean up.
 */
struct allocable {
    uint8_t *img;		/* Image data */
    SDL_Surface *rgbsurf;	/* RGB converted surface */
    png_bytepp rowptrs;		/* Array of row pointers */
    png_color *palette;		/* Palette data */
    png_structp png;		/* PNG write structure */
    png_infop png_info;		/* PNG info structure */
    struct host_file *hf;	/* Host file structure */
};

static int do_screenshot(SDL_Surface *surf, struct allocable *a)
{
    uint8_t *row;
    size_t bytes_per_row;
    int y;
    int npalette, depth;
    time_t now;
    png_time png_now;
    SDL_PixelFormat fmt;
    png_bytepp rowptr;

    /* Get current time for timestamp */
    time(&now);
    png_convert_from_time_t(&png_now, now);

    /* Allocate row pointers */
    a->rowptrs = malloc(surf->h * sizeof *a->rowptrs);
    if (!a->rowptrs)
	return -1;

    /* First, try an indexed image */
    npalette = make_indexed(surf, &a->img, &a->palette);
    if (npalette > 0) {
	if (npalette <= 2)
	    depth = 1;
	else if (npalette <= 4)
	    depth = 2;
	else if (npalette <= 16)
	    depth = 4;
	else
	    depth = 8;

	bytes_per_row = surf->w;
	row = a->img;
    } else {
	/* Otherwise create an RGB image */
	fmt = rgbfmt; /* Is this really needed? */
	a->rgbsurf = SDL_ConvertSurface(surf, &fmt, SDL_SWSURFACE);
	if (!a->rgbsurf)
	    return -1;
	SDL_LockSurface(a->rgbsurf);
	depth = 8;
	bytes_per_row = a->rgbsurf->pitch;
	row = a->rgbsurf->pixels;
    }

    /* Generate row pointers */
    rowptr = a->rowptrs;
    for (y = 0; y < surf->h; y++) {
	*rowptr++ = row;
	row += bytes_per_row;
    }

    /* Create a PNG write and info structures */
    a->png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL,
				     my_png_error, my_png_warning);
    if (!a->png)
	return -1;

    a->png_info = png_create_info_struct(a->png);
    if (!a->png_info)
	return -1;

    if (setjmp(png_jmpbuf(a->png)))
	return -1;

    /* Open screenshot file */
    a->hf = dump_file(HF_BINARY, screen_path, "scrn%04u.png");
    if (!a->hf)
	return -1;
    png_init_io(a->png, a->hf->f);

    /* IHDR configuration */
    png_set_IHDR(a->png, a->png_info, surf->w, surf->h, depth,
		 (npalette > 0) ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_RGB,
		 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
		 PNG_FILTER_TYPE_DEFAULT);

    png_set_tIME(a->png, a->png_info, &png_now);

    if (npalette > 0)
	png_set_PLTE(a->png, a->png_info, a->palette, npalette);

    png_set_rows(a->png, a->png_info, a->rowptrs);

    png_write_png(a->png, a->png_info,
		  (depth < 8) ? PNG_TRANSFORM_PACKING : PNG_TRANSFORM_IDENTITY,
		  NULL);

    keep_file(a->hf);		/* We did it! */
    return 0;
}

int screenshot(SDL_Surface *surf)
{
    struct allocable a;
    int rv, err;

    if (!screen_path)
      return 0;			/* Screenshots disabled? */

    memset(&a, 0, sizeof a);
    rv = do_screenshot(surf, &a);
    err = errno;

    if (a.rgbsurf) {
	SDL_UnlockSurface(a.rgbsurf);
	SDL_FreeSurface(a.rgbsurf);
    }
    if (a.png)
	png_destroy_write_struct(&a.png, &a.png_info);
    if (a.palette)
	free(a.palette);
    if (a.img)
	free(a.img);
    if (a.rowptrs)
	free(a.rowptrs);

    close_file(&a.hf);

    errno = err;
    return rv;
}