/******************************************************************************
 * TTYplayer                                                        VERSION 0.1
 ******************************************************************************
 * A program to replay video files generated by ttyvideo on SGI hardware at
 * a more correct framerate
 *
 * INTRODUCTION
 *   ttyvideo is a program for video-input-equipped SGI workstations. It takes
 *   video input and ouputs the ASCII version of it to the terminal. Recordings
 *   can be taken with commands like "./ttyvideo > video.txt" which can then
 *   be played back with "cat video.txt".
 *
 *   Modern computer systems are too fast to play back these "video files" 
 *   using the cat command. This program provides the ability to play back
 *   these recordings at a slower speed.
 *
 * USAGE
 *   The program can either be compiled or run directly by adding a #! line at
 *   the start of the file pointing to your D compiler. For example:
 *     #!/opt/dmd/bin/dmd -run
 *
 *   ttyplayer [options] file
 *   Options:
 *     --help		Displays usage information
 *     --version	Displays version information
 *     --file filename	Sets the filename. Required if more than just --play
 *			or --info is used
 *     --info		Displays information about the specified file
 *     --play		Plays the specified file
 *     --speed x	Sets the frame delay speed to x. Default is 60000uS
 *
 *   Examples
 *     ttyplayer file.txt
 *     ttyplayer --play file.txt
 *     ttyplayer --info file.txt
 *     ttyplayer --play --file file.txt
 *     ttyplayer --play --speed 500 --file file.txt
 *
 * SYSTEM REQUIREMENTS
 *   This program should probably work on any system where a D compiler is
 *   available.
 *
 * ABOUT
 *   This program was written by David Goodwin (email dgsoftnz@gmail.com) to 
 *   see what the D programming language is like. While it works, it could 
 *   probably be done better.
 *
 *   TTYplayer v0.1 (C) Copyright David Goodwin, 2008.
 *
 * LICENSE
 *   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 2 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, write to the Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *****************************************************************************/

/* ttyplayer: A program to replay video files generated by ttyvideo on SGI 
 * hardware at a more correct framerate.
 */

import std.stdio;
import std.stream;
import std.c.time;
import std.string;    // atoi is needed for --speed option

/* Program Entry Point
 */
int main(string[] args) {
	string filename = "";
	int speed = 60000;
	bool play = false;
	bool shinfo = false;

	// Make sure we have at least 1 parameter specified
	if (args.length < 2) {
		writefln("Error: Not enough parameters");
		print_usage();
		return 1;	// Return an error
	}
	
	for (int i = 1; i < args.length; i++) {
		if (args[i] == "--help") {
			print_usage();
			return 0;
		}
		else if (args[i] == "--version") {
			print_version();
			return 0;
		}
		else if (args[i] == "--play") {
			play = true;
			if (args.length == i+2) {
				i++;
				filename = args[i];
			}
		}
		else if (args[i] == "--speed") {
			if (args.length < i+2) {
				writefln("Error: Speed not specified.");
				print_usage();
				return 1;
			}
			i++;
			if (!starts_with(args[i],"--")){
				speed = atoi(args[i]);
			}
			else {
				writefln("Error: '", args[i], "' is not a valid speed");
				print_usage();
				return 1;
			}
		}
		else if (args[i] == "--info") {
			shinfo = true;
			if (args.length == i+2) {
				i++;
				filename = args[i];
			}
		}
		else if (args[i] == "--file") {
			if (args.length < i+2) {
				writefln("Error: Filename not specified.");
				print_usage();
				return 1;
			}
			i++;
			filename = args[i];
		}
		else {
			writefln("Unknown parameter: ", args[i]);
		}
	}
	
	if ((filename == "") && (play || shinfo)) {
		writefln("Error: filename not specified.");
		print_usage();
		return 1;
	}
	
	if ((filename == "") && (args.length == 2)) {
		filename = args[1];
	}
	
	if (filename == "") {
		writefln("Error: filename not specified.");
		print_usage();
		return 1;
	}
	
	if (play || (!play && !shinfo))
		play_video(filename, speed);
	if (shinfo)
		print_info(filename);
	
	return 0;
}

/* Prints version information
 */
void print_version() {
	writefln("TTYplayer v0.1");
	writefln("\t(C) Copyright David Goodwin, 2008.\n");
}

/* Prints usage information
 */
void print_usage() {
	writefln("Usage: ttyplayer [options] file");
	writefln("Options:");
	writefln("  --help\t\tDisplays this information");
	writefln("  --version\t\tDisplays version information");
	writefln("  --file filename\tSets the filename. Required if more than just --play or --info is used.");
	writefln("  --info\t\tDisplays information about the specified file");
	writefln("  --play\t\tPlays the specified file.");
	writefln("  --speed x\t\tSets the Frame delay speed to x. The default value is 60000uS");
	writefln("\n");
	writefln("Examples:");
	writefln("  ttyplayer file.txt");
	writefln("  ttyplayer --play file.txt");
	writefln("  ttyplayer --info file.txt");
	writefln("  ttyplayer --play --file file.txt");
	writefln("  ttyplayer --play --speed 500 --file file.txt");
}

/* Prints information about the specified video file
 */
void print_info(string filename) {
	// Open the input file
	File input = new File;
	input.open(filename, FileMode.In);

	// Get the info and print it
	video_info info = get_info(input);
	info.filename = filename;
	print_info(info);

	// Close the input file
	input.close();
}

/* Plays the specified video file at the specified speed
 */
void play_video(string filename, int speed) {

	// Open the input file
	File input = new File;
	input.open(filename, FileMode.In);

	video_info info = get_info(input);
	info.filename = filename;

	if (info.isVideo) {
		writefln("Loaded a video file");
	}
	else {
		writefln("File loaded was not video");
	}
	
	// Get the first frame
	auto frame = get_next_frame(input, info);

	while (frame.isFrame) {
		print_frame(frame);
		frame = get_next_frame(input, info);
		usleep(speed);
	}

	// Now we start the timer and do how ever many FPS we need.

	// Close the input file
	input.close();
}

/* Gets the next video frame
 */
video_frame get_next_frame(File inputfile, video_info info) {
	video_frame frame;
	
	int i = 0;
	for (;i < 25 && !inputfile.eof(); i++) {
		frame.frame_data[i] = inputfile.readLine();
	}
	
	if (i < 25) frame.isFrame = false;
	else frame.isFrame = true;
	
	return frame;
}

/* Prints a video frame to the terminal
 */ 
void print_frame(video_frame frame) {
	for (int i = 0; i < frame.frame_data.length; i++) {
		// We use the C stdio function because % is a formatting character
		// in the D writefln functino
		std.c.stdio.puts(&(frame.frame_data[i] ~ '\0')[0]);
	}
}

/* Loads the data in video_input from the specified file.
 */
video_info get_info(File inputfile) {
	video_info info;

	// Try and get "-- Video:"
	string curlin = inputfile.readLine();
	if (curlin != "-- Video:") {
		info.isVideo = false;
		return info;
	} else {
		info.isVideo = true;
	}

	// Read the next line
	curlin = inputfile.readLine();

	int i = 0;
	for (i = 0; i < 14; i++) {
		string s2 =curlin[0 ..2];

		// Make sure we are looking at a field
		if (s2 != "VL") {
			info.found_fields = i;
			return info;
		}
		
		// Try and find "VL device is "
		if (starts_with(curlin, "VL device is ")) {
			info.device = curlin[13 .. curlin.length];
		}
		else if (starts_with(curlin, "VL_FORMAT is ")) {
			info.format = curlin[13 .. curlin.length];
		}
		else if (starts_with(curlin, "VL muxswitch is ")) {
			info.muxswitch = curlin[16 .. curlin.length];
		}
		else if (starts_with(curlin, "VL timing is ")) {
			info.timing = curlin[13 .. curlin.length];
		}
		else if (starts_with(curlin, "VL packing is ")) {
			info.packing = curlin[14 .. curlin.length];
		}
		else if (starts_with(curlin, "VL pixel size is ")) {
			info.pixel_size = curlin[17 .. curlin.length];
		}
		else if (starts_with(curlin, "VL cap_type: ")) {
			info.cap_type = curlin[13 .. curlin.length];
		}
		else if (starts_with(curlin, "VL offset is ")) {
			info.offset = curlin[13 .. curlin.length];
		}
		else if (starts_with(curlin,  "VL zoom is ")) {
			info.zoom = curlin[11 .. curlin.length];
		}
		else if (starts_with(curlin, "VL rate is ")) {
			//VL rate is 30/1 (frame/second)
			info.FPS = curlin[11 .. curlin.length];
			// parse into just a number. We will assume it is always
			// two digits.
			//info.frame_rate = curlin[11..13];
		}
		else if (starts_with(curlin, "VL size is ")) {
			info.size = curlin[11 .. curlin.length];
		}
		else if (starts_with(curlin, "VL buffer size is ")) {
			info.buffer_size = curlin[18 .. curlin.length];
		}
		else if (starts_with(curlin, "VL bytes_per_transfer (video) = ")) {
			info.bytes_per_transfer = curlin[32 .. curlin.length];
		}
		else if (starts_with(curlin, "VL sequence value divider = ")) {
			info.sequence_value_divider = curlin[28 .. curlin.length];
		}
		else {
			// It is a field we dont know
			writefln("Unknown field: ", curlin);
		}

		curlin = inputfile.readLine();
	}

	info.found_fields = i;
	return info;
}

/* Prints the specified video_info structure to the terminal
 */
void print_info(video_info info) {
	writefln("Filename: ", info.filename);
	writefln("Fields found: ", info.found_fields);
	writefln("Device: ", info.device);
	writefln("Format: ", info.format);
	writefln("muxswitch: ", info.muxswitch);
	writefln("timing: ", info.timing);
	writefln("packing: ", info.packing);
	writefln("Pixel Size: ", info.pixel_size);
	writefln("Capture type: ", info.cap_type);
	writefln("Offset: ", info.offset);
	writefln("Zoom: ", info.zoom);
	writefln("Frame Rate: ", info.FPS);
	writefln("Frames in a second: ", info.frame_rate);
	writefln("Frame Size: ", info.size);
	writefln("Buffer Size: ", info.buffer_size);
	writefln("Bytes Per Transfer: ", info.bytes_per_transfer);
	writefln("Sequence Value Divider: ", info.sequence_value_divider);
}

/* A custom starts_with function as D doesnt appear to come with one.
 */
bool starts_with(string str, string prefix) {
	// everything starts with the empty string
	if (prefix.length == 0) return true; 
	// the only thing that the empty string starts with is the empty
	// string which should be matched by above.
	if (str.length == 0) return false; 
	
	// If the prefix is longer than the string then the string obviously
	// does not start with it
	if (str.length < prefix.length) return false;
	

	string s1 = str[0 .. prefix.length];
	
	if (s1 == prefix) {
		return true;
	}
	else {
		return false;
	}
}

/* A function to test the custom starts_with function. Never run
 * by the program. Here only to document how the starts_with function
 * works.
 */
void test_startswith() {
	writefln("String 1: abacus123");
	writefln("String 2: abacus");
	writefln("String 3: Hello, World!");
	writefln("String 4: abacu123");
	writefln("String 5: ''");
	
	// does string1 start with string 2? yes
	bool s1s2 = starts_with("abacus123","abacus");
	// does string 4 start with string 2? no
	bool s4s2 = starts_with("abacu123","abacus");
	// does string 3 start with string 2? no
	bool s3s2 = starts_with("Hello, World!","abacus");
	// does string 1 start with string 5? yes
	bool s1s5 = starts_with("abacus123","");
	// does string 5 start with string 1? no
	bool s5s1 = starts_with("","abacus123");
	// does string 5 start with string 5? yes
	bool s5s5 = starts_with("","");
	
	
	writefln("1,2: true  - ", s1s2); // true
	writefln("4,2: false - ", s4s2); // false
	writefln("3,2: false - ", s3s2); // false
	writefln("1,5: true  - ", s1s5); // true
	writefln("5,1: false - ", s5s1); // false
	writefln("5,5: true  - ", s5s5); // true
}

/*
Stores information about a ttyvideo output file

Video Information is of the form:
-- Video:
VL device is vino
VL_FORMAT is IndyCam
VL muxswitch is IndyCam
VL timing is 525-line 4x ntsc subcarrier 768x486
VL packing is RGBA
VL pixel size is 4 bytes
VL cap_type: one frame per transfer
VL offset is 0,0
VL zoom is 1/1
VL rate is 30/1 (frame/second)
VL size is 640 x 480 (for one frame)
VL buffer size is 7 frames
VL bytes_per_transfer (video) = 1228800b
VL sequence value divider = 2
*/
struct video_info {
	string filename;
	bool isVideo;
	int found_fields;
	int frame_rate;
	string device;	//VL device is vino
	string format;	//VL_FORMAT is IndyCam
	string muxswitch;	//VL muxswitch is IndyCam
	string timing;	//VL timing is 525-line 4x ntsc subcarrier 768x486
	string packing;	//VL packing is RGBA
	string pixel_size;	//VL pixel size is 4 bytes
	string cap_type;	//VL cap_type: one frame per transfer
	string offset;	//VL offset is 0,0
	string zoom;	//VL zoom is 1/1
	string FPS;	//VL rate is 30/1 (frame/second)
	string size;	//VL size is 640 x 480 (for one frame)
	string buffer_size;	//VL buffer size is 7 frames
	string bytes_per_transfer;	//VL bytes_per_transfer (video) = 1228800b
	string sequence_value_divider;	//VL sequence value divider = 2
}

/* Stores a video frame.
 */
struct video_frame {
	string[25] frame_data;
	bool isFrame; // Set to false if the video has ended and this is one past the last frame
}