/*==============================================================================

FICHIER     : [unused.c]

DATE        : 2006/02/0022 22:06:17

CREATEUR    : [Linux!jef]

COMMENTAIRE :

================================================================================
	Fonction que je n'utilise plus
==============================================================================*/

static int Ac3State;

/*------------------------------------------------------------------------------
	CPUQUALITY-
Linux!jef 2005/12/05 21:47:40
------------------------------------------------------------------------------*/

int CpuQuality( GtkWidget * forme, int noPisteVideo, int noPisteAudio, int subTitleF, double * pFactor )
{
	int chapitre;
	char * device = ConfigGetString( KEY_DEVICE, "/dev/dvd" );
	char * tmpDir = ConfigGetString( KEY_TEMP, "/tmp" );
	pgcit_t *vts_pgcit;   vtsi_mat_t *vtsi_mat;
	vmgi_mat_t *vmgi_mat;
	video_attr_t *video_attr;
	int title_set_nr;
	int vts_ttn;
	pgc_t *pgc;
	char sysCmd[1024];
	int res = 0;
	char audioFormat[10];
	long long vobSize = 0;
	long long videoSize = 0;
	long long audioSize = 0;
	struct stat bstat;
	Tampon * tampon;
	TStream * stream;
	TStream * racine;
	char fName[256];
	TCbArray cbArray;
	long long size;
	long long fsize;
	char mp2Video[512];
	char mp2Audio[512];
	char vobFile[512];
	int estimatedSectors;

	vtsi_mat = Ifo[Ifo_zero->tt_srpt->title[noPisteVideo].title_set_nr]->vtsi_mat;
	vts_pgcit = Ifo[Ifo_zero->tt_srpt->title[noPisteVideo].title_set_nr]->vts_pgcit;
	video_attr = &vtsi_mat->vts_video_attr;
	vts_ttn = Ifo_zero->tt_srpt->title[noPisteVideo].vts_ttn;
	vmgi_mat = Ifo_zero->vmgi_mat;
	title_set_nr = Ifo_zero->tt_srpt->title[noPisteVideo].title_set_nr;
	pgc = vts_pgcit->pgci_srp[Ifo[title_set_nr]->vts_ptt_srpt->title[vts_ttn - 1].ptt[0].pgcn - 1].pgc;

	chapitre = ((pgc->nr_of_programs + 1) / 2) + 1;
	if( pgc->nr_of_programs == 1 )	chapitre = 1;

	DBG('c',fprintf(stderr,"Chapitre de test: %d\n", chapitre ););
	*pFactor = 1;

	size = GetSector( chapitre, pgc ) * SECTOR_SIZE;
	fsize = FsFree( tmpDir ) - size;
	if( fsize < 0 ) {
		Alerte( 0, _("Pas assez de place sur %s\nIl manque %lld octets !"), tmpDir, -fsize );
		return( -1 );
	}
/*TODO:*/
	strcpy( audioFormat,"ac3" );

	sprintf( mp2Video,"%s/cfile.m2v", tmpDir );
	sprintf( mp2Audio,"%s/cfile.%s", tmpDir, audioFormat );
	sprintf( vobFile,"%s/cfile.vob", tmpDir );

	sprintf( sysCmd, "tccat -i %s -T %d,%d ", device, noPisteVideo+1, chapitre );

	tampon = CreateTampon( sysCmd );
	if( !tampon ) {
		Alerte( 0, _("Création du tampon impossible") );
		res = -1;
		goto out;
	}
	estimatedSectors = GetSector( chapitre, pgc );
	Ac3State = 0;

	cbArray.nCb = 1;
	cbArray.callBack[0] = Avancement;

	racine = StreamAddSon( tampon->stream, NULL, &cbArray, NULL );

	sprintf( sysCmd, "tcextract -t vob -x mpeg2" );
	stream = StreamAddSon( racine, sysCmd, NULL, mp2Video );

	sprintf( sysCmd, "tcextract -t vob -x %s -a %d", audioFormat, noPisteAudio );
	stream = StreamAddBrother( stream, sysCmd, NULL, NULL );

/* Add the AC3 Filter */
	cbArray.nCb = 1;
	cbArray.callBack[0] = Ac3Filter;
	sprintf( fName, "/tmp/cfile.%s", audioFormat );

	stream = StreamAddSon( stream, NULL, &cbArray, mp2Audio );

	CreateAvancement( forme );

	InitAvancement( estimatedSectors );

	size = estimatedSectors * SECTOR_SIZE;
	DisplayAvancement(_("Analyse du chapitre %d\nTaille %s\nPiste audio: %d\nFormat audio: %s\n"),
		chapitre,
		LLSize2Giga( size ),
		noPisteAudio+1,
		audioFormat );

	TamponRun( tampon, AvancementUi );
	TamponDestroy( tampon );
	if( UserStopF ) {
		DestroyAvancement();
		res = -1;
		goto out;
	}
/* Le multiplexage ne peut etre pipeer because on a besoint des fichiers intermediaires */

	DisplayAvancement( _("\n\nMultiplexage en cours\nPatientez........\n") );

/* Multiplex the streams to obtain a vob file */

	sprintf( sysCmd,"mplex -f 8 -S 0 -M -o %s %s %s",
		vobFile,
		mp2Video,
		mp2Audio );

	system( sysCmd );


	if( !stat( vobFile, &bstat ) ) {
		vobSize = bstat.st_size;
		DBG('c',fprintf(stderr,"VOBSIZE: %lld\n", vobSize ););
	}
	if( !stat( mp2Video, &bstat ) ) {
		videoSize = bstat.st_size;
		DBG('c',fprintf(stderr,"VIDEOSIZE: %lld\n", videoSize ););
	}
	if( !stat( mp2Audio, &bstat ) ) {
		audioSize = bstat.st_size;
		DBG('c',fprintf(stderr,"AUDIOSIZE: %lld\n", audioSize ););
	}

	if( (videoSize + audioSize )  > 0 ) {
		double dCor = (double)vobSize / ((double)videoSize + (double)audioSize);
		long long totalSectors = 0;
		long long chapitreSectors;
		long long menuSize = 0;
		double dFactor;
		long long dvdBytes = GetWantedBytes();

		totalSectors = GetSector( -1, pgc );
		chapitreSectors = GetSector( chapitre, pgc );

		if( IsToggleSet(forme,"UseMenu" ))	menuSize = GetMenuSize();

		DBG('c',fprintf( stderr, "totalSectors: %lld chapitreSectors: %lld\n", totalSectors, chapitreSectors ););
/* Estimation total */
		videoSize = ( videoSize * (long long) totalSectors) / (long long) chapitreSectors;
		DBG('c',fprintf(stderr,"ESTIMATED TOTAL VIDEOSIZE: %lld\n", videoSize ););
		audioSize = ( audioSize * (long long) totalSectors ) / (long long) chapitreSectors;
		DBG('c',fprintf(stderr,"ESTIMATED TOTAL AUDIOSIZE: %lld\n", audioSize ););
		DBG('c',fprintf(stderr,"MENUSIZE: %lld\n", menuSize ););


		dFactor = (double)videoSize / (double)( dvdBytes - audioSize - menuSize );
		DBG('c',fprintf(stderr,"Facteur de correction mplex: %f dFactor: %f\n", dCor, dFactor););
		if( dCor > 0 ) {
			dFactor = dFactor * dCor;
		}
                else {
			dFactor = dFactor + (dFactor / (double) 100 * (double) 3);    // 3 % Reserve
		}
		if( subTitleF ) dFactor = dFactor + (dFactor / (double) 100);   // 1 % Reserve pour soustitre
		dFactor = dFactor + (dFactor / (double) 200); // 0.5 % Overhead fuer dvdauthor
		if (dFactor < 1)	dFactor = 1;
		DBG('c',fprintf(stderr,"Facteur: %f\n", dFactor ););
		*pFactor = dFactor;
	}
	DestroyAvancement();
out:;
	DBG('c',fprintf(stderr,"CpuQuality: exiting %d\n",res););
	unlink( vobFile );
	unlink( mp2Video );
	unlink( mp2Audio );
	return( res );
}



/*------------------------------------------------------------------------------
	CONVERTDVD-
Linux!jef 2005/12/12 22:36:50
------------------------------------------------------------------------------*/

int ConvertDvd( GtkWidget * forme, int noPisteVideo, int noPisteAudio, int noSubtitle, int useMenuF, double factor )
{
	char * device = ConfigGetString( KEY_DEVICE, "/dev/dvd" );
	char * tmpDir = ConfigGetString( KEY_TEMP, "/tmp" );
	char * isoDir = ConfigGetString( KEY_ISODIR, "/tmp" );
	pgcit_t *vts_pgcit;
	vtsi_mat_t *vtsi_mat;
	vmgi_mat_t *vmgi_mat;
	video_attr_t *video_attr;
	int title_set_nr;
	int vts_ttn;
	pgc_t *pgc;
	char sysCmd[10240]; /*KK:*/
	int res = 0;
	char audioFormat[10];
	Tampon * tampon;
	TStream * stream;
	TStream * racine;
	char fName[256];
	TCbArray cbArray;
	GtkWidget * item;
	long long size;
	char * chapitreStr;
	long long vobSize;
	int ret;
	long long fsize;
	char pFile[512];
	char vobFile[512];
	char tmpDvd[512];
	int estimatedSectors;
	const gchar * text;

/* Maj du titre du DVD */
	item = lookup_widget(GTK_WIDGET(forme), "titre" );
	text = gtk_entry_get_text( GTK_ENTRY(item) );
	strcpy( TitreDvd, text );

	vtsi_mat = Ifo[Ifo_zero->tt_srpt->title[noPisteVideo].title_set_nr]->vtsi_mat;
	vts_pgcit = Ifo[Ifo_zero->tt_srpt->title[noPisteVideo].title_set_nr]->vts_pgcit;
	video_attr = &vtsi_mat->vts_video_attr;
	vts_ttn = Ifo_zero->tt_srpt->title[noPisteVideo].vts_ttn;
	vmgi_mat = Ifo_zero->vmgi_mat;
	title_set_nr = Ifo_zero->tt_srpt->title[noPisteVideo].title_set_nr;
	pgc = vts_pgcit->pgci_srp[Ifo[title_set_nr]->vts_ptt_srpt->title[vts_ttn - 1].ptt[0].pgcn - 1].pgc;

/* Verify we have enought free space to run */
	fsize = FsFree( tmpDir ) - GetWorkBytes();
	if( fsize < 0 ) {
		Alerte( 0, _("Pas assez de place sur %s\nIl manque %lld octets !"), tmpDir, -fsize );
		return( -1 );
	}
	if( IsToggleSet( forme, "DoIso" ) ) {
		fsize = FsFree( isoDir ) - GetWantedBytes();
		if( fsize < 0 ) {
			Alerte( 0, _("Pas assez de place sur %s\nIl manque %lld octets !"), isoDir, -fsize );
			return( -1 );
		}
	}

	CreateAvancement( forme );

	sprintf( pFile,"%s/palette.txt", tmpDir );
	sprintf( vobFile,"%s/ofile.vob", tmpDir );
	sprintf( tmpDvd,"%s/dvd95", tmpDir );

	SavePalette( noPisteVideo, pFile );

/*TODO:*/
	strcpy( audioFormat,"ac3" );

/* Hack for test */
	if( !access( "/data/piste1.cat", R_OK ) ) {
		DBG('c',fprintf(stderr,"Using piste1.cat\n"););
		sprintf( sysCmd, "cat /data/piste1.cat" );
	}
	else {
		sprintf( sysCmd, "tccat -i %s -T %d,-1", device, noPisteVideo+1 );
	}
	tampon = CreateTampon( sysCmd );
	if( !tampon ) {
		Alerte( 0, _("Création du tampon impossible") );
		res = -1;
		goto out;
	}
	estimatedSectors = GetSector( -1, pgc );

	cbArray.nCb = 1;
	cbArray.callBack[0] = Avancement;

	racine = StreamAddSon( tampon->stream, NULL, &cbArray, NULL );

	if( factor > 1 )
		sprintf( sysCmd, "tcextract -t vob -x mpeg2 | tcrequant -f %s", Double2String(factor) );
	else
		sprintf( sysCmd, "tcextract -t vob -x mpeg2" );

	stream = StreamAddSon( racine, sysCmd, NULL, "|/tmp/ofile.m2v" );

	sprintf( sysCmd, "tcextract -t vob -x %s -a %d", audioFormat, noPisteAudio );
	sprintf( fName, "|/tmp/ofile.%s", audioFormat );
	stream = StreamAddBrother( stream, sysCmd, NULL, fName );

/* if subtitle selected unmux */
	if( noSubtitle != -1 ) {
		sprintf( sysCmd, "spuunmux -o %s/dvd -s %d -p %s /dev/stdin", tmpDir, noSubtitle, pFile );
		stream = StreamAddBrother( stream, sysCmd, NULL, "/dev/null" );
	}

/* Add multiplexing stage */
	sprintf( sysCmd,"mplex -f 8 -S 0 -M -o %s /tmp/ofile.m2v /tmp/ofile.%s",
		vobFile,
		audioFormat );
	TamponAddStage( tampon, sysCmd );

	InitAvancement( estimatedSectors );

	size = (long long)estimatedSectors * (long long) SECTOR_SIZE;
	DisplayAvancement( _("Convertion de la piste video %d\nTaille %s\nPiste audio: %d\nFormat audio: %s\n"),
		noPisteVideo+1,
		LLSize2Giga( size ),
		noPisteAudio+1,
		audioFormat );
	if( noSubtitle != -1 ) {
		DisplayAvancement( _("Sous titres: %d\n"), noSubtitle + 1 );
	}
	else {
		DisplayAvancement( _("Sous titres: aucun\n") );
	}

	TamponRun( tampon, AvancementUi );
	TamponDestroy( tampon );
	if( UserStopF ) {
		res = -1;
		goto out;
	}
	DisplayAvancement( _("Fin du transcodage.\n") );

	vobSize = FileSize64( vobFile );
	DBG('c',fprintf(stderr,"VOBSIZE=%lld\n", vobSize ););

	if( vobSize == 0LL ) {
		Alerte( 0,_("Fichier vob non creé !") );
		res = -1;
		goto out;
	}
	if( vobSize > GetWantedBytes() ) {
		ret = Alerte( 0,_("Fichier vob trop gros (%lld bytes) !\nDésirez vous continuer ?"), vobSize);
		if( ret != 1 ) {
			res = -1;
			goto out;
		}
	}
	DisplayAvancement( _("Taille du fichier VOB: %s\n"), LLSize2Giga( vobSize ) );
/* Create dvd95 directory */
	mkdir( tmpDvd, 0777 );
/* Remove old dump if any */
	sprintf( sysCmd,"rm -rf \"%s/%s\"", tmpDvd, TitreDvd );
	system( sysCmd );

/* DVDAUTHOR STAGE */
	DisplayAvancement( _("Création de la structure du DVD.\n") );

	chapitreStr = BuildChapitreString( noPisteVideo );
	DBG('c',fprintf(stderr,"Chapitre(%s)\n", chapitreStr ););


	sprintf( sysCmd,"cat %s", vobFile );
	tampon = CreateTampon( sysCmd );
	if( !tampon ) {
		Alerte( 0, _("Création du tampon impossible") );
		res = -1;
		goto out;
	}

	SetStreamEndCb( tampon->stream, EndOfInput, _("Finalisation.\nVeuillez patienter..........\n") );

	InitAvancement( (int)(vobSize / SECTOR_SIZE) );

	cbArray.nCb = 1;
	cbArray.callBack[0] = Avancement;

	racine = StreamAddSon( tampon->stream, NULL, &cbArray, NULL );

	if( noSubtitle != -1 ) {
		sprintf( sysCmd,"spumux -m dvd -s 0 %s/dvd.xml", tmpDir );
		stream = StreamAddSon( racine, sysCmd, NULL, NULL );

		sprintf( sysCmd,
"dvdauthor -t -a %s+%s -c %s -v pal+16:9+nopanscan+720x576 -p %s -s %s -o \"%s/%s\" -f -",
			audioFormat,
			AudioLang( noPisteVideo, noPisteAudio ),
			chapitreStr,
			pFile,
			SubLang( noPisteVideo, noSubtitle ),
			tmpDvd,
			TitreDvd );
		stream = StreamAddSon( stream, sysCmd, NULL, "/dev/null" );
	}
	else {
		sprintf( sysCmd,
"dvdauthor -t -a %s+%s -c %s -v pal+16:9+nopanscan+720x576 -p %s -o \"%s/%s\" -f -",
			audioFormat,
			AudioLang( noPisteVideo, noPisteAudio ),
			chapitreStr,
			pFile,
			tmpDvd,
			TitreDvd );
		stream = StreamAddSon( racine, sysCmd, NULL, "/dev/null" );
	}

//!!	UserStopF = 0;
	TamponRun( tampon, AvancementUi );
	TamponDestroy( tampon );
	if( UserStopF ) {
		res = -1;
		goto out;
	}
	DisplayAvancement( _("Fin de convertion.\n") );
/* Final stage: add a toc  (speedy) */
	DisplayAvancement( _("Ajout de la table des matières.\n") );
	sprintf( sysCmd,"dvdauthor -T -o \"%s/%s\"", tmpDvd, TitreDvd );
	system( sysCmd );

/* OK Ask if the user want to see the movie */
	if( IsToggleSet( forme, "ViewResult" ) ) {
		sprintf( sysCmd, "%s/%s", tmpDvd, TitreDvd );
		VisuDvdStruct( sysCmd );
	}
/* OK Ask if the user want to build the iso image */
	if( IsToggleSet( forme, "DoIso" ) ) {
		DisplayAvancement( _("Construction de l'image ISO.\n") );
		sprintf( sysCmd, "mkisofs -dvd-video -V \"%s\"  -o \"%s/%s.iso\" \"%s/%s\"",
			TitreDvd,
			isoDir,
			TitreDvd,
			tmpDvd,
			TitreDvd );

		ExecuteMkIsoFs( sysCmd );
	}
/* Burn DVD if needed */
	if( IsToggleSet( forme, "graver" ) ) {
		DisplayAvancement( _("Gravage sur DVD.\n") );
		sprintf( sysCmd, "eject %s", device );
		system( sysCmd );
		sprintf( sysCmd,"k3b \"%s/%s/VIDEO_TS\" -videodvd", tmpDvd, TitreDvd );
		system( sysCmd );
	}

out:;
	DestroyAvancement();
	DBG('c',fprintf(stderr,"ConvertDvd: exiting %d\n",res););
	unlink( vobFile );
	unlink( "/tmp/ofile.m2v" );
	unlink( pFile );
/* Remove any dvdauthor files */
	sprintf( sysCmd, "rm -f %s/dvd*.png", tmpDir );
	system( sysCmd );
	sprintf( sysCmd, "rm -f %s/dvd*.xml", tmpDir );
	system( sysCmd );
	sprintf( sysCmd, "rm -rf \"%s/%s\"", tmpDvd, TitreDvd );
	system( sysCmd );

	return( res );
}

/*------------------------------------------------------------------------------
	DOUBLE2STRING-
Linux!jef 2005/12/14 22:48:47
	PB de locale
------------------------------------------------------------------------------*/

static char * Double2String( d )
double d;
{
	static char v[50];
	char * p = v;

	sprintf( v, "%f" , d );
	while( *p ) {
		if( *p == ',' ) *p = '.';
		p++;
	}
	return( v );
}

/*------------------------------------------------------------------------------
	AC3FILTER-
Linux!jef 2005/12/08 00:13:12
------------------------------------------------------------------------------*/

static int Ac3Filter( buffer, pLg )
unsigned char * buffer;
int * pLg;
{
	int i;
	int idx = 0;
	unsigned char ch;

/* Manage ac3 filtering */

	if( Ac3State == 2 )	return( 0 );

	for( i = 0; i < *pLg; i++ ) {
		ch = buffer[i];
		switch( Ac3State ) {
			case 0 :
				if( ch == 0x0b ) {
					Ac3State = 1;
				}
				break;
			case 1 :
				if( ch == 0x77 ) {
					buffer[idx++] = 0x0b;
					buffer[idx++] = 0x77;
					Ac3State = 2;
				}
				else
					Ac3State = 0;
				break;
			case 2 :
				buffer[idx++] = ch;
				break;
		}
	}
	DBG('c',fprintf(stderr,"Ac3Filter: iLg: %d oLg: %d State: %d (%2.2x/%2.2x)\n", *pLg, idx, Ac3State, buffer[0], buffer[1] ););
	*pLg = idx;
	return( 0 );
}


/*------------------------------------------------------------------------------
	ENDOFINPUT-
Linux!jef 2006/01/17 21:41:07
------------------------------------------------------------------------------*/

static void EndOfInput( TStream * stream, void * arg )
{
	DisplayAvancement( "%s", (char *)arg );
}

