/*
 * test.c: Map the slowdown factor in gdk_scale_simple() when reducing
 * by a large ratio. See https://bugzilla.gnome.org/show_bug.cgi?id=80925
 *
 * cc -O test.c -o test `pkg-config --cflags --libs gtk+-2.0`
 *
 *	Martin Guy <martinwguy@gmail.com>, November 2016.
 */

#include <gtk/gtk.h>
#include <sys/time.h>

static void run_test(GdkPixbuf *sourcePixbuf, int to_width, int to_height);

int
main(int argc, char **argv)
{
    GtkWidget *window;
    GdkPixbuf *sourcePixbuf = NULL;	/* As read from a file */
    GtkWidget *widget;		/* As displayed on the screen */
    char *filename =  (argc > 1) ? argv[1] : "image.jpg";
    double area_ratio;
    guint32 from_width, from_height;
    guint32 to_width, to_height;

    gtk_init(&argc, &argv);

    /* Make pixbuf, then make image from pixbuf because
     * gtk_image_new_from_file() doesn't flag errors */
    {
	GError *error = NULL;
	sourcePixbuf = gdk_pixbuf_new_from_file(filename, &error);
	if (sourcePixbuf == NULL) {
	    g_message("%s", error->message);
	    return 1; /* exit() */
	}
    }
    from_width = gdk_pixbuf_get_width(sourcePixbuf);
    from_height = gdk_pixbuf_get_height(sourcePixbuf);

    printf("Scaling width:\n");
    to_height = from_height;
    for (to_width=20; to_width >= 1; to_width--) {
	run_test(sourcePixbuf, to_width, to_height);
    }

    printf("Scaling height:\n");
    to_width = from_width;
    for (to_height=20; to_height >= 1; to_height--) {
	run_test(sourcePixbuf, to_width, to_height);
    }

    printf("Scaling both:\n");
    for (to_width = 40; to_width >= 1; to_width--) {
	to_height = to_width;
	run_test(sourcePixbuf, to_width, to_height);
    }
	
    return 0;
}

static void
run_test(GdkPixbuf *sourcePixbuf, int to_width, int to_height)
{
    guint32 from_width = gdk_pixbuf_get_width(sourcePixbuf);
    guint32 from_height = gdk_pixbuf_get_height(sourcePixbuf);
    double size_ratio = (double)from_width / to_width;
    double area_ratio = (from_height * from_width) / (to_width * to_height);

    struct itimerval init;
    struct itimerval b4, afta;
    int i;

    if (size_ratio == 1.0) size_ratio = (double)from_height / to_height;

    init.it_value.tv_sec = 86400;
    init.it_value.tv_usec = 0;
    init.it_interval.tv_sec = 86400;
    init.it_interval.tv_usec = 0;
    setitimer(ITIMER_PROF, &init, NULL);

    getitimer(ITIMER_PROF, &b4);
    for (i=0; i<100; i++) {
	g_object_unref(gdk_pixbuf_scale_simple(sourcePixbuf,
					       to_width, to_height,
					       GDK_INTERP_BILINEAR));
    }
    getitimer(ITIMER_PROF, &afta);

    printf("%dx%d->%dx%d, size ratio %.2f, area ratio %.2f, %d msec\n",
	from_width, from_height, to_width, to_height,
	size_ratio, area_ratio,
	(b4.it_value.tv_sec*1000+b4.it_value.tv_usec/1000) -
	(afta.it_value.tv_sec*1000+afta.it_value.tv_usec/1000));
}
