/*
* c8-panorama FILE MAX_WIDTH MAX_HEIGHT
*
* Decodes the picture behind the glasses' space ([glasses] background)
* for c8, which doesn't read pictures itself: a 360 one is hundreds of
* megabytes decoded and takes seconds, and a decoder is no thing to run
* in the compositor. The picture, shrunk to fit the limits, is written
* to stdout (a memfd of c8's): the pixels from byte 8 on, rows of
* R, G, B without padding, and only once they're all there its width and
* height (two native uint32) at the start, so a half-written one reads
* as no picture. c8 knows we're done by fd 3 closing, a pipe.
*/
#include <fcntl.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static bool put(int fd, const void *data, size_t size, off_t at) {
const char *p = data;
while (size > 0) {
ssize_t n = pwrite(fd, p, size, at);
if (n <= 0) {
return false;
}
p += n;
size -= n;
at += n;
}
return true;
}
int main(int argc, char *argv[]) {
if (argc != 4) {
fprintf(stderr, "usage: c8-panorama FILE MAX_WIDTH MAX_HEIGHT\n");
return 2;
}
/* Ours alone: a decoder's own helpers mustn't hold it open after us */
fcntl(3, F_SETFD, FD_CLOEXEC);
int max_w = atoi(argv[2]), max_h = atoi(argv[3]);
int w, h;
if (max_w < 1 || max_h < 1 ||
gdk_pixbuf_get_file_info(argv[1], &w, &h) == NULL || w < 1 ||
h < 1) {
fprintf(stderr, "c8-panorama: %s isn't a picture\n", argv[1]);
return 1;
}
/* Never enlarged: the glasses' GPU does that as well */
double scale = fmin(1, fmin((double)max_w / w, (double)max_h / h));
int tw = MAX(1, (int)(w * scale + 0.5)), th = MAX(1, (int)(h * scale + 0.5));
GError *error = NULL;
GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file_at_scale(argv[1], tw, th,
FALSE, &error);
if (pixbuf == NULL) {
fprintf(stderr, "c8-panorama: %s: %s\n", argv[1], error->message);
return 1;
}
if (gdk_pixbuf_get_colorspace(pixbuf) != GDK_COLORSPACE_RGB ||
gdk_pixbuf_get_bits_per_sample(pixbuf) != 8) {
fprintf(stderr, "c8-panorama: %s: not 8-bit RGB\n", argv[1]);
return 1;
}
tw = gdk_pixbuf_get_width(pixbuf);
th = gdk_pixbuf_get_height(pixbuf);
int channels = gdk_pixbuf_get_n_channels(pixbuf);
int stride = gdk_pixbuf_get_rowstride(pixbuf);
const guchar *pixels = gdk_pixbuf_read_pixels(pixbuf);
guchar *row = g_malloc((gsize)tw * 3);
off_t at = 8;
for (int y = 0; y < th; y++) {
const guchar *src = pixels + (gsize)y * stride;
if (channels == 3) {
if (!put(STDOUT_FILENO, src, (size_t)tw * 3, at)) {
return 1;
}
} else {
/* Over black, which is clear in the glasses */
for (int x = 0; x < tw; x++) {
int a = src[x * 4 + 3];
row[x * 3] = src[x * 4] * a / 255;
row[x * 3 + 1] = src[x * 4 + 1] * a / 255;
row[x * 3 + 2] = src[x * 4 + 2] * a / 255;
}
if (!put(STDOUT_FILENO, row, (size_t)tw * 3, at)) {
return 1;
}
}
at += (off_t)tw * 3;
}
uint32_t size[2] = { tw, th };
return put(STDOUT_FILENO, size, sizeof(size), 0) ? 0 : 1;
}