/***********************************************************************
 * VirtualDubMod project
 *
 * Copyright (C) 2002
 *
 * File added by Cyrius
 *
 * 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 (see the file COPYING); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * or visit http://www.gnu.org/copyleft/gpl.html
 *
 ***********************************************************************
 *
 *
 *
 */

#include "SRTOutput.h"
#include "../Error.h"

char SRTOutputFile::szME[]="SRTOutputFile";

SRTOutputFile::SRTOutputFile(void)
: AudioOutputFile(false) {
	num_sub = 1;
	begin = 0;
}

BOOL SRTOutputFile::process_data(int serial, bool key_frame, LPVOID buffer, LONG length, LONG nSamples) {
	char *text = (char *)buffer;

	if(!text || (length<=0))
		return TRUE;

	bool is_sub = false;
	for(int i=0 ; i<length ; i++) {
		if(isgraph(text[i]) ) {
			is_sub = true;
			break;
		}
	}

	if(is_sub) {
		char num[] = "9999999999";
		sprintf(num, "%ld\n", num_sub);
		num_sub++;
		char time[] = "00:00:00,000 --> 00:00:00,000     ";
		int ms1 = begin % 1000;
		int s1  = (begin / 1000) % 60;
		int m1  = (begin / 1000 / 60) % 60;
		int h1  = begin / 1000 / 60 / 60;

		__int64 end = begin + nSamples;
		int ms2 = end % 1000;
		int s2  = (end / 1000) % 60;
		int m2  = (end / 1000 / 60) % 60;
		int h2  = end / 1000 / 60 / 60;

		sprintf(time, "%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\n", h1,m1,s1,ms1,h2,m2,s2,ms2);

		_writeData(num, strlen(num));
		_writeData(time, strlen(time));

		for(int i=0 ; i<length ; i++) {
			if( (text[i] != 0x00) && (text[i] != 0x0D) )
				_writeData(&text[i], 1);
		}
		_writeData("\n\n", 2);
	}

	begin += nSamples;

	return TRUE;
}

void SRTOutputFile::_writeData(LPVOID buffer, LONG length) {
	if(fastIO)
		fastIO->Put(buffer, length);
	else {
		DWORD n_write = 0;
		if( (!WriteFile(hFile, buffer, length, &n_write, NULL)) || (n_write!=length))
			throw MyWin32Error("%s: %%s", GetLastError(), szME);
	}
}