shithub: jxl

ref: 8b780e3e59ec287937c5754521329840a69b28ee
dir: /decode.c/

View raw version
#include <u.h>
#include <libc.h>
#include <bio.h>
#include <thread.h>
#define J40_CONFIRM_THAT_THIS_IS_EXPERIMENTAL_AND_POTENTIALLY_UNSAFE
#define J40_IMPLEMENTATION
#define J40_INLINE
int __builtin_clz(unsigned int x);
int __builtin_clzll(unsigned long long x);
#include "j40.h"

static void
usage(void)
{
	fprint(2, "usage: %s\n", argv0);
}

static u8int *
readall(int f, int *outsz)
{
	int bufsz, sz, n;
	u8int *s;

	bufsz = 65535;
	s = nil;
	for(sz = 0;; sz += n){
		if(bufsz-sz < 65536){
			bufsz *= 2;
			s = realloc(s, bufsz);
		}
		if((n = readn(f, s+sz, bufsz-sz)) < 1)
			break;
	}
	if(n < 0 || sz < 1){
		if(n == 0)
			werrstr("empty");
		free(s);
		return nil;
	}
	*outsz = sz;

	return s;
}

void
threadmain(int argc, char **argv)
{
	j40_pixels_u8x4 pixels;
	u8int *p, *in, x;
	j40_image image;
	j40_frame frame;
	int sz, y, n;
	Biobuf *b;

	ARGBEGIN{
	default:
		usage();
	}ARGEND

	if((in = readall(0, &sz)) == nil || (b = Bfdopen(1, OWRITE)) == nil)
		sysfatal("%r");
	j40_from_memory(&image, in, sz, free);
	j40_output_format(&image, J40_RGBA, J40_U8X4);

	if(j40_next_frame(&image)){
		frame = j40_current_frame(&image);
		pixels = j40_frame_pixels_u8x4(&frame, J40_RGBA);
		Bprint(b, "%11s %11d %11d %11d %11d ", "a8r8g8b8", 0, 0, pixels.width, pixels.height);
		for(y = 0; y < pixels.height; ++y){
			p = (u8int*)j40_row_u8x4(pixels, y);
        	for(n = 0; n < 4*pixels.width; n += 4){
        		x = p[n+0];
        		p[n+0] = p[n+2];
        		p[n+2] = x;
        	}
            Bwrite(b, p, 4*pixels.width);
        }
    }

    if(j40_error(&image))
    	sysfatal("%s", j40_error_string(&image));

    j40_free(&image);
	Bterm(b);

	threadexitsall(nil);
}