#!/usr/bin/python
import sys

def read_file(file):
	try:
		f= open(file, 'r')
	except IOError as e:
		sys.exit( file + " :: " +  e.strerror )
	else:
		x = f.readlines()
		f.close()
	return x

def getBitList ( log ):
	templist = 1200*[0]  #max frame num
	for line in log:
		if line.find("POC") >= 0 and line.find("TId:") >= 0:
			list = line.split()
			templist[int(list[1])] = int(list[11])
	for i in range(len(templist)-1,0,-1):
		if templist[i] == 0:
			del templist[i]
	return templist

def getQP ( log ):
	for line in log:
		if line.find("QP                                     :") >= 0:
			list = line.split()
			return float(list[2])
	return -1

def getFPS ( log ):
	for line in log:
		if line.find("Internal Format                        :") >= 0:
			list = line.split()
			return float(list[4].translate(None, 'Hz'))
	return -1

#################################################################
#	Input :	HM/JEM encode log file for QP and QP+1
#	Output:	floatQP ( QP < floatQP < QP+1 )
#################################################################

if len(sys.argv) == 4:
	logR1 = read_file(sys.argv[1])
	logR2 = read_file(sys.argv[2])
	targetrate = float(sys.argv[3])
else:
	sys.exit("Usage: >get_floatQP.py  EnclogQP=q  EnclogQP=q+1  TargetBitrate")


QP1 = getQP ( logR1 )
QP2 = getQP ( logR2 )
if QP2 - QP1 != 1.0:
	sys.exit("The qp difference should be 1.")

margin = 0.005  #0.5%
targetrate *= (1.0 - margin)

BitListR1 = getBitList( logR1 )
BitListR2 = getBitList( logR2 )

fps  = getFPS ( logR1 )
fnum = len( BitListR1 )

cp   = fnum	#initialize QP Change Point

while 1:
	totalbit = 0
	for i in range(0, fnum):
		if i < cp:
			totalbit += BitListR1[i]
		else:
			totalbit += BitListR2[i]

	bitrate = totalbit * fps / fnum / 1000.0

	if bitrate < targetrate:
		break
	if cp < 0:
		sys.exit("float QP not found.")
	cp -= 1

print round( QP1 + ( 1.0 - float(cp)/fnum ), 5 )

