/* libmpeg_with_allegro.c -- 2002-03-03
 *
 * A simple example for using libmpeg with Allegro.  Libmpeg only
 * handles MPEG-1 though so it's not all that useful.  In particular,
 * it doesn't handle MPEGs with audio.
 *
 * MPEG library:  http://starship.python.net/~gward/mpeglib/
 *
 * Peter Wang <tjaden@users.sourceforge.net>
 */

#include <allegro.h>
#include <mpeg.h>

/* Uncomment this to use 8 bpp images */
/* #define USE_COLOR_MAP */

static int frames_to_decode;

static void ticker(void)
{
    frames_to_decode++;
}

END_OF_STATIC_FUNCTION(ticker);

int main(int argc, char *argv[])
{
    FILE *fp;
    ImageDesc img;
    BITMAP *bmp;

    if (argc != 2)
	return 1;

    fp = fopen(argv[1], "rb");
    if (!fp)
	return 1;

#ifdef USE_COLOR_MAP
    /* "8-bit colour-mapped; reasonable quality; decoding is almost as
     * fast as GRAY_DITHER" */
    SetMPEGOption(MPEG_DITHER, ORDERED_DITHER);
#else
    /* "High-quality 24_bit colour rendering; results in slowest
     * decoding" */
    SetMPEGOption(MPEG_DITHER, FULL_COLOR_DITHER);
#endif

    OpenMPEG(fp, &img);

    /* Just in case */
    switch (img.PixelSize) {
	case 8: case 15: case 16: case 24: case 32:
	    break;
	default:
	    return 1;
    }

    allegro_init();
    install_timer();
    install_keyboard();

#ifndef USE_COLOR_MAP
    set_color_depth(16);
#endif
    if (set_gfx_mode(GFX_AUTODETECT, 320, 200, 0, 0))
	return 1;

    bmp = create_bitmap_ex(img.PixelSize, img.Width, img.Height);

#ifdef USE_COLOR_MAP
    {
	PALETTE pal;
	int i;

	for (i = 0; i < img.ColormapSize; i++) {
	    pal[i].r = img.Colormap[i].red >> 2;
	    pal[i].g = img.Colormap[i].green >> 2;
	    pal[i].b = img.Colormap[i].blue >> 2;
	}

	set_palette(pal);
    }
#endif

    LOCK_FUNCTION(ticker);
    LOCK_VARIABLE(frames_to_decode);
    frames_to_decode = 0;
    install_int(ticker, 134 / img.PictureRate);
    /* unsure about the rate (I only have one test case) */

    while (1) {
	while (!frames_to_decode) {
	    if (keypressed())
		goto end;
	    yield_timeslice();
	}

	if (!GetMPEGFrame(bmp->line[0]))
	    goto end;

	blit(bmp, screen, 0, 0, 0, 0, bmp->w, bmp->h);
	frames_to_decode--;
    }

  end:

    remove_int(ticker);
    destroy_bitmap(bmp);
    CloseMPEG();
    fclose(fp);

    return 0;
}

END_OF_MAIN();

