/*
Copyright (c) 2005-2007, Sven Berkvens-Matthijsse

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

* Neither the name of deKattenFabriek nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include	"config.h"

#include	<sys/types.h>
#include	<sys/wait.h>
#include	<time.h>
#include	<unistd.h>
#include	<stdio.h>
#include	<string.h>
#include	<errno.h>
#include	<stdlib.h>

#define		BUFFER_SIZE	65536
#define		NEW_BUFFER_SIZE	1024
#define		NUM_SAMPLES	240
#define		MIN_SAMPLES	60

#define		ETA_MOVIE_LENGTH_INCORRECT	(-5)
#define		ETA_MOVIE_LENGTH_UNKNOWN	(-4)
#define		ETA_MOVIE_LENGTH_WAITING	(-3)
#define		ETA_NOT_ENOUGH_SAMPLES		(-2)
#define		ETA_STALLED			(-1)

static	char		buffer[BUFFER_SIZE + 1], new_buffer[NEW_BUFFER_SIZE];
static	ssize_t		in_buffer, in_new_buffer;
static	pid_t		pid;
static	int		p[2];
static	unsigned int	movie_length;
static	time_t		start_time, prev_time, prev_display_time;
static	int		how_far_value[NUM_SAMPLES];
static	time_t		how_far_time[NUM_SAMPLES];
static	unsigned int	how_far_num;

/* Name:	start_child
 *
 * Description:	Starts up the child in a separate process.
 *
 * Input:	argv		- the argv of the program to start
 *
 * Output:	Nothing.
 *
 * Side effects:None.
 */

static void
start_child(char * const * const argv)
{
	/* Open a pipe in which the child is going to write.
	 */

	if (-1 == pipe(p))
	{
		(void)fprintf(stderr, "pipe() failed: %s\n", strerror(errno));
		exit(1);
	}

	/* Start mplayer in another process.
	 */

	pid = fork();
	if ((pid_t)-1 == pid)
	{
		(void)fprintf(stderr, "fork() failed: %s\n", strerror(errno));
		exit(1);
	}

	if ((pid_t)0 == pid)
	{
		/* Close the read side of the pipe.
		 */

		(void)close(p[0]);

		/* Make sure the child writes into our pipe.
		 */

		if (-1 == dup2(p[1], STDOUT_FILENO))
		{
			(void)fprintf(stderr, "dup2() failed: %s\n",
				strerror(errno));
			exit(1);
		}

		if (-1 == dup2(p[1], STDERR_FILENO))
		{
			(void)fprintf(stderr, "dup2() failed: %s\n",
				strerror(errno));
			exit(1);
		}

		if ((p[1] != STDOUT_FILENO) && (p[1] != STDERR_FILENO) &&
			(p[1] != STDIN_FILENO))
		{
			(void)close(p[1]);
		}

		/* We are the child. Start mplayer.
		 */

		execvp(argv[0], argv);

		/* If we get here, something went wrong!
		 */

		(void)fprintf(stderr, "execvp() failed: %s\n", strerror(errno));
		exit(1);
	}

	/* We're the parent. Close off the writing side here (otherwise we'll
	 * never get an EOF for this file).
	 */

	(void)close(p[1]);
}

/* Name:	read_child_data
 *
 * Description:	Reads data from the pipe to the child.
 *
 * Input:	None.
 *
 * Output:	1 if the main loop should be terminated, 0 otherwise.
 *
 * Side effects:None.
 */

static int
read_child_data(void)
{
	/* Read the program's output.
	 */

	in_new_buffer = read(p[0], (void *)new_buffer, (size_t)NEW_BUFFER_SIZE);
	if ((ssize_t)-1 == in_new_buffer)
	{
		(void)fprintf(stderr, "read() failed: %s\n", strerror(errno));
		return 1;
	}

	/* EOF?
	 */

	if ((ssize_t)0 == in_new_buffer)
		return 1;

	/* We've read data now... move the data into buffer.
	 */

	if (BUFFER_SIZE < in_buffer + in_new_buffer)
	{
		memmove(buffer,
			buffer + (in_buffer + in_new_buffer - BUFFER_SIZE),
			BUFFER_SIZE - in_new_buffer);
		in_buffer = BUFFER_SIZE - in_new_buffer;
	}

	memmove(buffer + in_buffer, new_buffer, in_new_buffer);
	in_buffer += in_new_buffer;

	/* Terminate the buffer for strstr.
	 */

	buffer[in_buffer] = 0;

	/* Main loop should continue with the new data.
	 */

	return 0;
}

/* Name:	scan_buffer
 *
 * Description:	Scans the buffer to find out how far along we are.
 *
 * Input:	None.
 *
 * Output:	Nothing.
 *
 * Side effects:None.
 */

static void
scan_buffer(void)
{
	const char	*find, *start;
	time_t		now;
	double		how_long, percentage, how_far, how_much;
	int		eta;

	/* Find the length of the movie if we don't have it yet.
	 */

	if ((unsigned int)-1 == movie_length)
	{
		find = strstr(buffer, "\nID_LENGTH=");
		if (find)
		{
			movie_length = atoi(find + 11);
			if ((unsigned int)-1 == movie_length)
				movie_length = 0;
		}
	}

	/* Find a <whitespace>V:<whitespace>*<digit>*<whitespace> sequence.
	 */

	if (in_buffer < 100)
		start = buffer;
	else
		start = buffer + (in_buffer - 100);

	find = strstr(start, " V:");
	if (!find)
		find = strstr(start, "\nV:");
	if (!find)
		return;
	how_far = atof(find + 3);

	/* Check the current time and check whether we're not updating too
	 * often.
	 */

	time(&now);
	if (now == prev_time)
		return;
	prev_time = now;

	if (movie_length > 0)
		percentage = ((double)100.0 * how_far) / movie_length;
	else
		percentage = (double)0.0;

	/* Update the sample array.
	 */

	if (how_far_num >= NUM_SAMPLES)
	{
		memmove(how_far_value, how_far_value + 1,
			sizeof(*how_far_value) * (NUM_SAMPLES - 1));
		memmove(how_far_time, how_far_time + 1,
			sizeof(*how_far_time) * (NUM_SAMPLES - 1));
		how_far_num = NUM_SAMPLES - 1;
	}
	how_far_value[how_far_num] = how_far;
	how_far_time[how_far_num] = now;
	how_far_num++;

	/* Calculate how long we still have to work to get to the end.
	 */

	if ((unsigned int)-1 == movie_length)
	{
		/* We don't know how long the movie is.
		 */

		eta = ETA_MOVIE_LENGTH_WAITING;
	}
	else if (0 == movie_length)
	{
		/* We don't know how long the movie is.
		 */

		eta = ETA_MOVIE_LENGTH_UNKNOWN;
	}
	else if (how_far_num < MIN_SAMPLES)
	{
		/* Not enough samples to determine an ETA.
		 */

		eta = ETA_NOT_ENOUGH_SAMPLES;
	}
	else if (how_far_value[0] == how_far_value[how_far_num - 1])
	{
		/* Stalled.
		 */

		eta = ETA_STALLED;
	}
	else
	{
		/* How long is the period in which the samples were recorded?
		 */

		how_long = difftime(how_far_time[how_far_num - 1],
			how_far_time[0]);

		/* How much did we do in that time?
		 */

		how_much = how_far_value[how_far_num - 1] - how_far_value[0];

		/* So now we know that we're doing how_much seconds of movie
		 * in how_long seconds of realtime. We've already done how_far
		 * seconds of movie of movie_length in total. That means that
		 * we still have (movie_length - how_far) seconds of movie to
		 * do, each second taking how_long/how_much of real time.
		 */

		if (how_far > movie_length + 20)
		{
			/* mplayer's ID_LENGTH field was inaccurate.
			 */

			eta = ETA_MOVIE_LENGTH_INCORRECT;
		}
		else if (how_far > movie_length)
		{
			/* mplayer's ID_LENGTH field was inaccurate.
			 */

			eta = 0;
		}
		else
		{
			eta = (int)((double)(movie_length - how_far) *
				(how_long / how_much));
		}
	}

	/* Display the progress on screen.
	 */

	(void)fprintf(stderr, "--> Progress: %3.2f%%  ETA: ", percentage);
	if (ETA_STALLED == eta)
	{
		(void)fprintf(stderr, "--stalled--                           ");
	}
	else if (ETA_NOT_ENOUGH_SAMPLES == eta)
	{
		(void)fprintf(stderr, "[cannot tell yet, wait: %u]            ",
			MIN_SAMPLES - how_far_num);
	}
	else if (ETA_MOVIE_LENGTH_INCORRECT == eta)
	{
		(void)fprintf(stderr, "[reported movie length inaccurate]    ");
	}
	else if (ETA_MOVIE_LENGTH_WAITING == eta)
	{
		(void)fprintf(stderr, "[waiting for stats to be reported]    ");
	}
	else if (ETA_MOVIE_LENGTH_UNKNOWN == eta)
	{
		(void)fprintf(stderr, "[mplayer did not report movie length] ");
	}
	else if (eta < 180)
	{
		(void)fprintf(stderr, "%d second%s                            ",
			eta, eta == 1 ? "" : "s");
	}
	else if (difftime(now, prev_display_time) >= 15.0)
	{
		eta /= 60;
		(void)fprintf(stderr, "%d hour%s %d minute%s                  ",
			eta / 60, (eta / 60) == 1 ? "" : "s",
			eta % 60, (eta % 60) == 1 ? "" : "s");
		prev_display_time = now;
	}
	(void)fputs("\r", stderr);
}

/* Name:	collect_status
 *
 * Description:	Collects the child's status.
 *
 * Input:	program		- the child's name
 *
 * Output:	-1 if the program should terminate with a non-zero exit code,
 *		0 if the program should exit normally.
 *
 * Side effects:None.
 */

static int
collect_status(const char * const program)
{
	int		status;

	/* Wait for the termination of the child.
	 */

	while (1)
	{
		/* Wait for a child to exit or for a signal.
		 */

		pid = wait(&status);
		if ((pid_t)-1 == pid)
		{
			if (ECHILD != errno)
				continue;
			(void)fprintf(stderr, "wait() failed: %s\n",
				strerror(errno));
			return -1;
		}

		if (!WIFSTOPPED(status))
			break;
	}

	/* Check the status.
	 */

	if (WIFEXITED(status))
	{
		/* Non-zero exit code?
		 */

		if (WEXITSTATUS(status))
		{
			(void)fprintf(stderr, "--> ERROR: %s terminated with "
				"exit code %d. Error output follows:\n",
				program, WEXITSTATUS(status));
			(void)fputs(buffer, stderr);
			return -1;
		}

		/* Program terminated normally.
		 */

		return 0;
	}

	/* Must have terminated on a signal then.
	 */

	if (!WIFSIGNALED(status))
	{
		(void)fprintf(stderr, "--> ERROR: %s terminated with an "
			"unknown exit status code %d\n", program, status);
		return -1;
	}

	/* Yes, it was a signal.
	 */

	(void)fprintf(stderr, "--> ERROR: %s terminated on signal number %d\n",
		program, WTERMSIG(status));
	return -1;
}

/* Name:	main
 *
 * Description:	Main entrance to the program.
 *
 * Input:	argc		- the number of arguments
 *		argv		- the array of arguments
 *
 * Output:	Standard exit code.
 *
 * Side effects:None.
 */

int
main(const int argc, char * const * const argv)
{
	/* At least one argument?
	 */

	if (argc < 2)
	{
		(void)fprintf(stderr, "Usage: %s command [args ...]\n",
			argv[0] ? argv[0] : "[unknown]");
		exit(1);
	}

	/* Start up the child.
	 */

	start_child(argv + 1);

	/* Initialize some values.
	 */

	in_buffer = 0;
	(void)time(&start_time);
	prev_time = start_time;
	prev_display_time = start_time;
	how_far_num = 0;
	movie_length = (unsigned int)-1;

	/* Read what the child says.
	 */

	while (1)
	{
		/* Read data from the child and exit the loop if required.
		 */

		if (read_child_data())
			break;

		/* Scan the data to find out how far along we are.
		 */

		scan_buffer();
	}

	/* Print a final newline.
	 */

	(void)fputs("\n", stderr);

	/* Collect the child's status.
	 */

	if (collect_status(argv[1]))
		return 1;

	/* We're done.
	 */

	return 0;
}
