/*******************************************************************
          TGOP - trace GOP structure and show Time Code
 *******************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "mpeg_io.h"
#include "sequence_header.h"
#include "timecode.h"

void tgop(char *path);

int main(int argc, char **argv)
{
	if(argc < 2){
		fprintf(stderr, "Usage:\n");
		fprintf(stderr, "%s mpeg2video", argv[0]);
		exit(EXIT_FAILURE);
	}

	tgop(argv[1]);

	return EXIT_SUCCESS;
}

void tgop(char *path)
{
	int GOP;
	MPEG_IO p;
	SEQUENCE_HEADER s;
	int code;

	static const char frame_rate[16][16] = {
		"invalid",   /* 0000 */
		"23.976",    /* 0001 */
		"24",        /* 0010 */
		"25",        /* 0011 */
		"29.97",     /* 0100 */
		"30",        /* 0101 */
		"50",        /* 0110 */
		"59.94",     /* 0111 */
		"60",        /* 1000 */
		"reserved",  /* 1001 */
		"reserved",  /* 1010 */
		"reserved",  /* 1011 */
		"reserved",  /* 1100 */
		"reserved",  /* 1101 */
		"reserved",  /* 1110 */
		"reserved",  /* 1111 */
	};

	static const char yuv[4][16] = {
		"invalid",
		"4:2:0",
		"4:2:2",
		"4:4:4",
	};
	
	if(!open_mpeg_file(path, &p)){
		fprintf(stderr, "%s - can't open\n", path);
		exit(EXIT_FAILURE);
	}

	if(!next_marker(&p)){
		fprintf(stderr, "%s - is not MPEG file\n", path);
		exit(EXIT_FAILURE);
	}

	code = get_bits(&p, 32);
	if(code != 0x1B3){
		fprintf(stderr, "%s - is not MPEG Video file\n", path);
		fprintf(stderr, "[DEBUG] code=%d\n", code);
		exit(EXIT_FAILURE);
	}

	if(!read_sequence_header(&p, &s)){
		fprintf(stderr, "%s - has invalid sequence header\n", path);
		exit(EXIT_FAILURE);
	}

	fprintf(stdout, "%dx%d, ", s.h_size, s.v_size);
	fprintf(stdout, "%s fps, ", frame_rate[s.frame_rate]);
	fprintf(stdout, "%d bps, ", s.bit_rate * 400);
	if(s.mpeg1){
		fprintf(stdout, "MPEG-1 Video\n");
	}else{
		if(s.se.progressive){
			fprintf(stdout, "Progressive");
		}else{
			fprintf(stdout, "Interlace");
		}
		fprintf(stdout, " MPEG-2 Video");
		fprintf(stdout, " YUV=%s\n", yuv[s.se.chroma_format]);
	}

	GOP = 0;
	while(next_marker(&p)){
		code = get_bits(&p, 32);
		if(!GOP && code == 0x100){
			fprintf(stderr, "%s - has no GOP\n", path);
			exit(EXIT_FAILURE);
		}
		if(code == 0x1B8){
			TIMECODE t;
			
			GOP += 1;
			get_timecode(&p, &t);

			fprintf(stdout, "%d - %02d:%02d:%02d:%02d %c\n", GOP, t.hh, t.mm, t.ss, t.ff, t.drop?'D':' ');
			fflush(stdout);
		}
	}
			
		

	close_mpeg_file(&p);

}
	

	