/* libSDL and libVLC sample code
 * Copyright © 2008 Sam Hocevar <sam@zoy.org>

 Copyright (c) 2010 Tomasz Kazmierczak
 Copyright (c) 2010 Tomasz Wisniewski
 Modified the original code by Sam Hocevar in order to adapt to the game and
 relicensed from Do What The Fuck You Want To Public License to GNU GPLv3

 This file is part of Cytadela

 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program. If not, see <http://www.gnu.org/licenses/>.  *
 */

#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <stdlib.h>

#include <SDL/SDL.h>
#include <SDL/SDL_mutex.h>

#include <vlc/vlc.h>

#define VIDEOWIDTH 640
#define VIDEOHEIGHT 400

struct ctx
{
    SDL_Surface *surf;
    SDL_mutex *mutex;
};

static void lock(struct ctx *ctx, void **pp_ret)
{
    SDL_LockMutex(ctx->mutex);
    SDL_LockSurface(ctx->surf);
    *pp_ret = ctx->surf->pixels;
}

static void unlock(struct ctx *ctx)
{
    SDL_UnlockSurface(ctx->surf);
    SDL_UnlockMutex(ctx->mutex);
}

bool play(const char *filename, SDL_Surface *screen, bool offOnFinish, bool audio)
{
    char clock[64], cunlock[64], cdata[64];
    char width[32], height[32], pitch[32];
	char chroma[8];
    libvlc_instance_t *libvlc;
    libvlc_media_t *m;
    libvlc_media_player_t *mp;
    char const *vlc_argv[] =
    {
        "-q",
        //"-vvvvv",
        //"--plugin-path", VLC_TREE "/modules",
        "--ignore-config", /* Don't use VLC's config files */
        audio ? "" : "--noaudio",
        "--vout", "vmem",
        "--vmem-width", width,
        "--vmem-height", height,
        "--vmem-pitch", pitch,
        "--vmem-chroma", chroma,
        "--vmem-lock", clock,
        "--vmem-unlock", cunlock,
        "--vmem-data", cdata,
        "--no-video-title-show"
    };
    int vlc_argc = sizeof(vlc_argv) / sizeof(*vlc_argv);

    SDL_Surface *empty;
    SDL_Event event;
    SDL_Rect rect;

    struct ctx ctx;

	empty = SDL_CreateRGBSurface(SDL_SWSURFACE, VIDEOWIDTH, VIDEOHEIGHT,
	                             screen->format->BitsPerPixel, 0, 0, 0, 0);
	uint32_t aMask = 0;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
	uint32_t bMask = 0xFF0000;
	uint32_t gMask = 0x00FF00;
	uint32_t rMask = 0x0000FF;
	if(screen->format->BitsPerPixel == 32) {
		bMask = 0xFF000000;
		gMask = 0x00FF0000;
		rMask = 0x0000FF00;
		aMask = 0x000000FF;
	}
#else
	uint32_t bMask = 0x000000FF;
	uint32_t gMask = 0x0000FF00;
	uint32_t rMask = 0x00FF0000;
	if(screen->format->BitsPerPixel == 32)
		aMask = 0xFF000000;
#endif
	ctx.surf = SDL_CreateRGBSurface(SDL_SWSURFACE, VIDEOWIDTH, VIDEOHEIGHT,
									screen->format->BitsPerPixel, rMask, gMask, bMask, aMask);

    ctx.mutex = SDL_CreateMutex();

    /*
     *  Initialise libVLC
     */
    sprintf(clock, "%lld", (long long int)(intptr_t)lock);
    sprintf(cunlock, "%lld", (long long int)(intptr_t)unlock);
    sprintf(cdata, "%lld", (long long int)(intptr_t)&ctx);
    sprintf(width, "%i", VIDEOWIDTH);
    sprintf(height, "%i", VIDEOHEIGHT);
	sprintf(pitch, "%i", VIDEOWIDTH*screen->format->BytesPerPixel);
	sprintf(chroma, "RV%i", screen->format->BitsPerPixel);

    libvlc = libvlc_new(vlc_argc, vlc_argv);
    m = libvlc_media_new_location(libvlc, filename);

	mp = libvlc_media_player_new_from_media(m);
    libvlc_media_release(m);

	libvlc_media_player_play(mp);

	/*
     *  Main loop
     */
	rect.w = 0;
    rect.h = 0;
    rect.x = (int)((screen->w - VIDEOWIDTH) / 2);
    rect.y = (int)((screen->h - VIDEOHEIGHT) / 2);

	bool done = false;
    while(not done)
    {
        int action = 0;

        /* Keys: enter, escape (quit) */
        while( SDL_PollEvent( &event ) ) 
        {
            switch(event.type)
            {
            case SDL_QUIT:
                done = true;
                break;
            case SDL_KEYDOWN:
                action = event.key.keysym.sym;
                break;
            }
        }

        switch(action)
        {
        case SDLK_ESCAPE:
        case SDLK_RETURN:
		case SDLK_KP_ENTER:
            done = true;
            break;
        case ' ':
			libvlc_media_player_pause(mp);
			break;
        }


        /* Blitting the surface does not prevent it from being locked and
         * written to by another thread, so we use this additional mutex. */
        SDL_LockMutex(ctx.mutex);
        SDL_BlitSurface(ctx.surf, NULL, screen, &rect);
        SDL_UnlockMutex(ctx.mutex);

        SDL_Flip(screen);
        SDL_Delay(10);

        SDL_BlitSurface(empty, NULL, screen, &rect);

		libvlc_state_t state = libvlc_media_player_get_state(mp);
		if(state == libvlc_Ended)
			done = offOnFinish;
    }

    /*
     * Stop stream and clean up libVLC
     */
    libvlc_media_player_stop(mp);

    libvlc_media_player_release(mp);
    libvlc_release(libvlc);

    SDL_DestroyMutex(ctx.mutex);
    SDL_FreeSurface(ctx.surf);
    SDL_FreeSurface(empty);

    return true;
}
