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

 Copyright (c) 2010, 2013 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 <assert.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(void *data, void **p_pixels)
{
	struct ctx *ctx = (struct ctx *)data;

	SDL_LockMutex(ctx->mutex);
	SDL_LockSurface(ctx->surf);
	*p_pixels = ctx->surf->pixels;
	return NULL; /* picture identifier, not needed here */
}

static void unlock(void *data, void *id, void *const *p_pixels)
{
	struct ctx *ctx = (struct ctx *)data;

	SDL_UnlockSurface(ctx->surf);
	SDL_UnlockMutex(ctx->mutex);

	assert(id == NULL); /* picture identifier, not needed here */
}

static void display(void *data, void *id)
{
	/* VLC wants to display the video */
	(void) data;
	assert(id == NULL);
}

bool play(const char *filename, SDL_Surface *screen, bool offOnFinish, bool audio)
{
	libvlc_instance_t *libvlc;
	libvlc_media_t *m;
	libvlc_media_player_t *mp;
	char const *vlc_argv[] =
	{
	    "--ignore-config", /* Don't use VLC's config files */
	    audio ? "" : "--noaudio",
	    "--no-xlib", /* tell VLC to not use Xlib */
	    "--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
	 */
	libvlc = libvlc_new(vlc_argc, vlc_argv);
	m = libvlc_media_new_path(libvlc, filename);
	mp = libvlc_media_player_new_from_media(m);
	libvlc_media_release(m);

	libvlc_video_set_callbacks(mp, lock, unlock, display, &ctx);
	char format[40];
	sprintf(format, "RV%d", screen->format->BitsPerPixel);
	libvlc_video_set_format(mp, format, VIDEOWIDTH, VIDEOHEIGHT, VIDEOWIDTH*(screen->format->BitsPerPixel / 8));
	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);

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

		switch(action) {
		case SDLK_ESCAPE:
		case SDLK_RETURN:
		case SDLK_KP_ENTER:
			stop = true;
			break;
		case ' ':
			libvlc_media_player_pause(mp);
			break;
		}
		if(stop)
			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 and offOnFinish)
			break;
	}

	/*
	 * 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;
}
