#!/usr/bin/env python
# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------------
# RzWebMediaInfo.py {tempDir} {sess_id} {transcoder} {cvfile_in} {cvfile_out} {timeseek} [opts]
#  transcoder :name of transcoder that called me
#  cvfile_in  :URL of the target web_contens
#  cvfile_out :pipe for streaming_out to renderer
#----------------------------------------------------------------------------------
# Returns Media infos and Transcoding params for given URL web_streaming_contens
# All return values must be outputted to standard_out 
# return values are Optional, if not returned, PMS will go on defaults
#---------------------------------------------------------------------------------
import os
import os.path
import sys
import subprocess
import re
import time
import re
import threading
import RzNicoPlayer
from multiprocessing import Process, Lock, Pipe

sys.path.append('regzamod')
from Common.RzCmnSubs import dbg,dbg2,dbg0,error,setdbg
from Common.RzCmnSubs import isAudio,isImage,isVideo,isWebVideo,isWebContents,conv_encoding
from Common.RzCmnSubs import gs_encode_sys,gs_debug,gs_verbose,gs_ff_loglev
from Common.RzCmnSubs import gs_python,gs_prog_ytdl,gs_prog_ytdl_s,gs_prog_streamer,gs_streamer_conf

#----------------------------------------------------------------------------------
# Basic globals/defaults
#----------------------------------------------------------------------------------
#---- debug -----------------
mc_loglev="-quiet -really-quiet"

#---- mencoder -----------------
mencoder="win32/mencoder-ZN.exe"
mencoder="win32/mencoder.exe"
mc_opt=''

#---- ffmepg -----------------
ffmpeg0="win32/ffmpeg-RZ.exe"	#good: m2ts+ac3, 	  bad:youtube-all
ffmpeg1="win32/ffmpeg-RZ.exe"	#good: youtube-live,  bad:m2ts+ac3,youtube-dash
ffmpeg2="win32/ffmpeg-RZ.exe"	#good: youtube-dash,  bad:m2ts+ac3,youtube,youtube-live
ffprog=ffmpeg1

ff_async=""
ff_async="-async 1"
ff_async="-async 5"
ff_async="-async 10"

#--- opts for general/input1 (placed before -i input1)
ff_opt0="-threads 8 -analyzeduration  1000000 "
ff_opt0="-cookies 'session=000001; domain=.example.com; path=/ history=yyyyyy'"
ff_opt0="-timeout 2000000 -chunked_post 0 -multiple_requests 1 -reconnect_streamed 1 -reconnect_at_eof 1" # has no-good-effects

ff_opt0_http="-reconnect 1" # to avoid dash-video video truncation
ff_opt0_pipe="" 			# for pipe (-reconnect is only for http)
ff_opt0_std="" 				# for other than http,pipe
ff_opt0=ff_opt0_std			# default

#--- opts for input2 (placed at after input1 and before input2)
ff_opt1=""
ff_opt1="-reconnect 1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2000 -timeout 2000000000 -y -thread_queue_size 5512 -nostats -fflags +genpts -probesize 10000000 -analyzeduration 15000000"
ff_opt1="-reconnect 1" # to avoid dash-video audio truncation

ff_opt1_http="-reconnect 1" # to avoid dash-video audio truncation
ff_opt1_pipe="" 			# for pipe (-reconnect is only for http)
ff_opt1_std=""  			# for other than http,pipe
ff_opt1=ff_opt1_std 		# default

#--- opts placed at tail (after inputs)
ff_opt2="-muxrate 24m -bufsize 1m -hls_time 30" # no good effects
ff_opt2="" 

ff_agent=""
ff_agent="-user_agent 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko'" # cause ffmpeg error
ff_agent="-user_agent Firefox/51.0.1"

g_adelay=2.0   	#audio delay
g_adelay=-2.0  	#video delay
g_adelay=0.0  	#no delay
g_aspect=0

#---- ffprobe -----------------
ffprobe="win32/ffprobe.exe"
fp_opt=''

nicoplayer="regzamod/RzWEBplayer/RzNicoPlayer.py"

ytb_account="--username regzam_yhg@yahoo.co.jp --password regzam2014"
nico_account="--username regzam_yhg@yahoo.co.jp --password regzam2014"
ytb_account=""

g_audio_bps=128000
g_audio_bps=448000

#---- actions/mode
need_geturl=1
need_getinfo=1

#---- Livestream tuning
getinfo_live_ust=0  		# =1:getinfo when ustream live (coorect, but slow)
getinfo_live_ytb=0  		# =1:getinfo when youtube live (coorect, but slow)
m3u8_useLivestream=0  		# =1:use Livestreamer for youtube_live (stable but slow), =0:use Livestreamer only for ustream, 
m3u8=""

remuxWhenCompatible=True
force_remux=False
force_trans=False
g_fps_limit=False  # max 24,25,30fps, not 48,50,60fps
asp_hack=0
m2ts=0

mode_auto=1
mode_manual=2
#mode=mode_auto
medinfo_mode=mode_manual

#---- transcode video format(container) 
trans_format="mpegts"  # better for high bitrate, but may cause dirty blocking noise for some contents
trans_format="mpegps"  # better for noise, but may cause error on REGZA for high bitrate contents

use_ffmpeg_trans=1
use_ffmpeg_remux=1
use_LivePlayer=1
LivePlayer="regzamod/RzWEBplayer/RzLivePlayer_m.py"

getinfo_type=3   #=1:by mencoder,=2:by ffmpeg, =3:by ffprove
getinfo_ytdl=0   #=1:get extra_info(size etc) by youtube_dl, =2:and use for mediainfo (fast but not accurate, and youtube only)
can_dash_480p=0  #=1:can handle dash_480p, currently not work well

youtube=0  # !=0: site is youtube
no_audio=0  # video without audio
bgmf= -1
dummy_audio="regzamod/RzIAVplayer/DefaultClips/Silent-180sec.mp3"


#---- nicovideo
# use ffmpeg: currentry doesn't work well, 
# many flv/mp4 of nicovideo seem to havn't moov atom on top
# on streaming/pipe, ffmpeg seems to be sensitive to above, 
# but mencoder seems don't care :)
nicovideo=0  	# in case of url is nicovideo, should be set follwing nicomode value
nicomode=1  	#=1:[trans_mencoder/remux_ffmpeg]+youtube-dl, =2:[trans_/remux_ffmpeg]+youtube-dl, 3:ffmpeg only
nicogetinfo=3	#=1:use mencoder  =2:use ffmpeg, =3:use ffprove for getinfo

yt_cookie_file="cookie.txt"
user="";
nico_streamer=1 # ==1: use youtube-dl ==2: use LiveStreamer

#--- display size
d_w=1280
d_h=720

d_w=1024
d_h=600

d_w=720
d_h=480

#--- youtube quality
yt_quality=35	#480p
yt_quality=22	#720p
yt_quality=37	#1080p

#--- time out secs
#timeup_geturl   =15
#timeup_getinfo  =15   # normal wait
#timeup_getinfo_l=30   # long wait for slow connection

timeup_geturl   =18
timeup_getinfo  =30   # normal wait
timeup_getinfo_l=40   # long wait for slow connection sites like nicovideo

#----------------------------------------------------------------------------------
# funcs, must be declared before call
#----------------------------------------------------------------------------------
def exec_prog (mode,args,elogf,tm,wait):
	outbuf=[]
	dbg("exec_prog: mode=%d, wait=%d, elogf=%s, args=%s" % (mode,wait,elogf,args))
	try:
		cwd="./"
		if(mode==1):
			p = subprocess.Popen(args, shell=False, cwd=cwd, stdin=None,
		    	stdout=subprocess.PIPE, stderr=elogf,
		    	close_fds=False)
		elif(mode==2):
			p = subprocess.Popen(args, shell=False, cwd=cwd, stdin=None,
		    	stdout=elogf, stderr=subprocess.PIPE,
		    	close_fds=False)
		else:
			p = subprocess.Popen(args, shell=False, cwd=cwd, stdin=None,
		    	stdout=None, stderr=None,
		    	close_fds=False)
		 	
	except OSError:
		dbg("Failed to exec %s" % args)
		return (1,outbuf)

	#---- watchdog_pipe: kill child when parant died
	pp,pc=Pipe()
	Process(target=watchdog_pipe,args=(pc,os.getpid(),p.pid)).start()
	
	#---- watchdog_timer: kill child when timeup
	if(tm>0):	#timeup time
		p2=Process(target=watchdog_timer,args=(p.pid,tm))
		p2.start()
	if(wait==False):
		return
	if(mode==1):
		(sto)=(p.stdout)
	else:
		(sto)=(p.stderr)
	while True:
		line=sto.readline()
		if not line:
			break
		outbuf.append(line)
		#dbg(line)
	ret=p.wait()
	if(tm>0):
		try:
			p2.terminate()
		except WindowsError:
			pass
	return (ret,outbuf)

#----------------------------------------------------------------------------------
def dump_errlog(elogfile):
	str=" "
	f = open(elogfile, 'r')
	for line in f:
		s=line.lower()
		if("account" in s or "error" in s):
			str +=(line.strip()+" ") 
			#print "web_logmsg=%s" % line,
	f.close()
	return (str)
				
#----------------------------------------------------------------------------------
def watchdog_timer(pid,t):
	time.sleep(t)
	os.kill(pid,9)
	
def watchdog_pipe(pc,ppid,pid):
	
	#signal.signal(signal.SIGALRM, sig_alarm)
	#signal.alarm(10)
	
	try:	# wait untill parent die, b/c parent never send to the pipe
		pc.recv()
	except EOFError: #parent seems to be killed
		pass	#Noop
	except IOError:
		pass	#Noop
	try:
		#os.kill(pid,signal.SIGKILL)
		os.kill(pid,9)
	except WindowsError:
		pass
	sys.exit()
	
#----------------------------------------------------------------------------------
def get_NicoCookies(yt_cookie_file):
	#get session info from yt_cookie_file 
	nhis=None
	nsess=None
	dmca=None
	f=open(yt_cookie_file,"r")
	for line in f:
		s=line.strip()
		pos=s.find("nicohistory")
		if(pos>-1):
			nhis=s[pos+11:].strip()
		pos=s.find("user_session")
		if(pos>-1):
			nsess=s[pos+12:].strip()
		pos=s.find("_dmca_up_id")
		if(pos>-1):
			dmca=s[pos+11:].strip()
	f.close()
	if(nhis is not None and nsess is not None):
		cookie="\"Cookie: nicohistory=%s; user_session=%s\"" % (nhis,nsess)
	elif(dmca is not None):
		cookie="\"Cookie: _dmca_up_id=%s\"" % (dmca)
	else:
		cookie=""
	dbg("get_NicoCookies: cookie="+cookie)
	return cookie
	
#----------------------------------------------------------------------------------
#disp error as video_message on renderer screen
def disp_error(msg):
	msg=msg.replace(" ","@")   # trickey encode as a parameter: avoid spaces in text,
	print "web_exit=%d" % (123)
	prog="regzamod/Common/RzDispMsg.py"
	print "web_prog_ex="+gs_python
	print "web_cvparams= %s --dpmsg %s --video_out $output" % (prog,msg)
	print "web_cvparams= --dpsize_w %d --dpsize_h %d --asp_hack %d --m2ts %d" % (d_w,d_h,asp_hack,m2ts)

#----------------------------------------------------------------------------------
def get_minfo_mc(mencoder,url,elogf):
	#------------------------------------------------------------
	# get media profile (size,fps)
	#------------------------------------------------------------
	# sample output of mencoder
	# VIDEO:  [H264]  854x480  0bpp  29.970 fps  1180.1 kbps (144.1 kbyte/s)
	# [V] filefmt:44  fourcc:0x34363248  size:854x480  fps:29.970  ftime:=0.0334

	#---- set defaults
	asp=0.0
	if(False):
		# original
		w=720.0
		h=480.0
		fps=29.970
		vc="-"	#vcodec
		vlev=0		#vlevel
		fmt="-"	#format
	else:
		#for test
		w=856.0
		h=480.0
		fps=29.970
		vc="-"	#vcodec
		vlev=0		#vlevel
		fmt="-"	#format
	
	if(nicovideo):
		(rc,outbuf)=RzNicoPlayer.getMinfo(1,nico_streamer,cvfile_in,timeup_getinfo_l)
	else:
		#%mencoder% "%cvfile_in%" -o NULL >web_info.log 2>&1
		#args=[mencoder,'"'+url+'"',"-o","NULL"]  #--> don't work well, why?
		#args=mencoder+" "+url+" -prefer-ipv4 -o NULL"
		args=mencoder+" "+url+" -o NULL"
		args=args.split()
		dbg("args=%s" % (args))
		#timeup=15.0	# timelimit for wait child ends
		timeup=timeup_getinfo	# timelimit for wait child ends
		(rc,outbuf)=exec_prog(1,args,elogf,timeup,True)
		
	dbg("get_minfo: mencoder rc=%d, outbuf_lines=%d" % (rc,len(outbuf)))
	
	dbg("------ mencoder outputs start -------------")
	if(len(outbuf)>0):
		pat_size=re.compile(" size\:[0-9]*[xX][0-9]* ")
		pat_fps=re.compile(" fps\:[0-9]*\.[0-9]* ")
		pat_vcodec=re.compile("VIDEO\: .*\[[A-Z,a-z,0-9]*\]")
		for i in range(len(outbuf)):
			str=outbuf[i]
			dbg(str)
			m=pat_size.search(str)
			if(m>=0):	#found
				str_size=str[m.start()+6:m.end()-1]
				#print "found: size_str=%s" % str_size
				wh=str_size.lower().split("x")
				#print "wh=%s" % wh
				w=float(wh[0].strip())
				h=float(wh[1].strip())
			m=pat_fps.search(str)
			if(m>=0):	#found
				str_fps=str[m.start()+5:m.end()-1]
				#print "found: str_fps=%s" % str_fps
				fps=float(str_fps)
			m=pat_vcodec.search(str)
			if(m>=0):	#found
				vc=str[m.start()+6:m.end()-1].lower()
				pos=vc.find("[")
				if(pos>-1):
					vc=vc[pos+1:]
				#print "found: vc=%s" % vc
			
	dbg("------ mencoder outputs end -------------")
	return (fmt,w,h,fps,vc,vlev,asp,rc)

def get_minfo_ff(ffmpeg,url,elogf):
	#------------------------------------------------------------
	# get media profile (size,fps) using ffmpeg
	#------------------------------------------------------------
	# sample output of ffmpeg
	#Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 640x360, 
	#  628 kb/s, 29.97 fps, 29.97 tbr, 60k tbn, 59.94 tbc (default)
	#Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 
	#  562 kb/s, 30 fps, 30 tbr, 30 tbn, 60 tbc (default)

	dbg("get_minfo_ff: start, nicovideo=%d " % (nicovideo))

	#---- set defaults
	asp=0.0
	if(False):
		# original
		w=720.0
		h=480.0
		fps=29.970
		vc="-"	#vcodec
		vlev=0
		fmt="-"	#format
	else:
		#for test
		w=1280.0
		h=720.0
		fps=29.970
		vc="-"	#vcodec
		vlev=0
		fmt="-"	#format
	
	if(nicovideo):
		args=[]
		(rc,outbuf)=RzNicoPlayer.getMinfo(2,nico_streamer,cvfile_in,timeup_getinfo_l)
	else:
		args="%s %s -i %s" % (ffmpeg,ff_agent,url)
		argm=args.split()
		if(level == "best"):
			#dash video is terrible slow?
			#timeup=30.0	# timelimit for wait child ends
			timeup=timeup_getinfo_l	# timelimit for wait child ends
		else:
			#timeup=15.0	# timelimit for wait child ends
			timeup=timeup_getinfo	# timelimit for wait child ends
		(rc,outbuf)=exec_prog(2,argm,elogf,timeup,True)
		
	dbg("get_minfo: ffmpeg rc=%d, outbuf_lines=%d" % (rc,len(outbuf)))
	dbg("args=%s" % (args))
	
	dbg("------ mencoder outputs start -------------")

	if(len(outbuf)>0):
		pat_size=re.compile("[0-9]+[xX][0-9]+")
		#pat_fps=re.compile(" fps\:[0-9]*\.[0-9]* ")
		#pat_vcodec=re.compile("Video\: [A-Z,a-z,0-9] ")
		for i in range(len(outbuf)):
			str=outbuf[i]
			dbg(str)
			pos=str.find("Video:")
			if(pos<0):
				continue
			st=str.split(",")
			for j in range(len(st)):
				str=st[j]
				#print "str No%d=%s" % (j,str)
				#---- vcodec ----
				pos=str.find("Video:")
				if(pos>-1):
					vc=str[pos+7:].lower()
					pos=vc.find(" ")
					if(pos>-1):
						vc=vc[:pos]
					#print "vcodec=%s" % (vc)
					continue
				#---- fps ----
				pos=str.find("fps")
				if(pos>-1):
					str=str[0:pos-1]
					#float() of fps may cause ValueError: invalid literal for float(): 1k
					try:
						fps=float(str.strip())
					except ValueError,e:
						pass
					continue
				#---- size ----
				m=pat_size.search(str)
				if(m>=0):	#found
					str1=str[m.start():m.end()]
					#dbg("get_minfo_ff: size str=%s, str1=%s" % (str,str1))
					wh=str1.strip().lower().split("x")
					w=float(wh[0].strip())
					h=float(wh[1].strip())
					rc=0
					#---- aspect ----
					#[SAR 1:1 DAR 16:9]
					pos=str.find("DAR")
					str=str[pos+len("DAR"):]
					#print >>sys.stderr, "DAR found str(origin)=%s" % str
					#str=str.replace("]","")
					str=re.sub("\]","",str)
					#print >>sys.stderr, "DAR found str(replaced)=%s" % str
					ar=str.split(":")
					if(len(ar)>1):
						asp=float(ar[0])/float(ar[1])
						dbg("DAR found, asp=%f" % asp)
					continue
			# 1st video found, ignore secondary videos
			break
	if(vc=="-"):
		rc= -1
	dbg("------ ffmpeg outputs end rc=%d -------------" % rc)
	return (fmt,w,h,fps,vc,vlev,asp,rc)

def get_minfo_fp(ffmpeg,url,elogf):
	#------------------------------------------------------------
	# get media profile (size,fps) using ffprobe
	#------------------------------------------------------------
	"""
	[STREAM]
	index=0
	codec_name=mpeg4
	profile=Simple Profile
	codec_type=video
	width=302
	height=540
	display_aspect_ratio=4379:7785
	level=1
	avg_frame_rate=24/1
	[/STREAM]
	[STREAM]
	index=1
	codec_name=aac
	profile=LC
	codec_type=audio
	avg_frame_rate=0/0
	[/STREAM]
	[FORMAT]
	format_name=mov,mp4,m4a,3gp,3g2,mj2
	duration=46.998000
	bit_rate=1280762
	[/FORMAT]	
	"""

	#---- set defaults
	asp=0.0
	if(False):
		# original
		w=720.0
		h=480.0
		fps=29.970
		vc="-"	#vcodec
		vlev=0
		fmt="-"	#format
	else:
		#for test
		w=1280.0
		h=720.0
		fps=29.970
		vc="-"	#vcodec
		vlev=0
		fmt="-"	#format
	
	if(nicovideo):
		args=[]
		(rc,outbuf)=RzNicoPlayer.getMinfo(3,nico_streamer,cvfile_in,timeup_getinfo_l)
	else:
		args=ffprobe+" -show_format -show_streams "+fp_opt+url
		args=args.split()
		if(level == "best"):
			#dash video is terrible slow?
			#timeup=30.0	# timelimit for wait child ends
			timeup=timeup_getinfo_l	# timelimit for wait child ends
		else:
			#timeup=15.0	# timelimit for wait child ends
			timeup=timeup_getinfo	# timelimit for wait child ends
		(rc,outbuf)=exec_prog(1,args,elogf,timeup,True)
		
	dbg("get_minfo: ffprobe rc=%d, outbuf_lines=%d" % (rc,len(outbuf)))
	dbg("args=%s" % (args))
	
	if(gs_verbose>0):
		dbg("------ ffprobe outputs start -------------")
		dbg("OUT=%s" % outbuf)
		dbg("OUT END-------------------------------------")

	pos=0
	state=0			# chunk type  =1:stream,=2:format
	stream_type=0   # stream type =1:video ,=2:audio
	stream_v=0 		# video stream number (valid from 1)
	stream_a=0		# audio stream number (valid from 1)
	if(len(outbuf)>0):
		for i in range(len(outbuf)):
			str=outbuf[i].strip()
			dbg("get_minfo_fp: line[%d]=%s" % (i,str))
			
			#---- chunks
			pos=str.find("[STREAM]")
			if(pos==0):
				dbg("found [STREAM]")
				state=1
				stream_type=0 # reset to unknown
				
			pos=str.find("[/STREAM]")
			if(pos==0):
				dbg("found [/STREAM]")
				if(stream_v==1):
					pass
					#break	#video found
			pos=str.find("[FORMAT]")
			if(pos==0):
				state=2
			
			#---- stream
			if(state==1):	#[STREAM]
				pos=str.find("codec_name=")
				if(pos==0 and vc=="-"): #not setted yet
					vc=str[pos+11:]
				pos=str.find("codec_type=")
				if(pos==0):
					str=str[pos+11:]
					dbg("found codec_type=%s" % (str))
					if("video" in str):
						stream_type=1
						stream_v+=1
					elif("audio" in str):
						stream_type=2
						stream_a+=1
			#---- video stream
			if(state==1 and stream_type==1 and stream_v==1): #video stream 1st
				pos=str.find("level=")
				if(pos==0):
					vlev=int(str[pos+6:])
					dbg("vlevel=%d" % (vlev))
				pos=str.find("width=")
				if(pos==0):
					str=str[pos+6:]
					w=float(str)
				pos=str.find("height=")
				if(pos==0):
					str=str[pos+7:]
					h=float(str)
					
				pos=str.find("level=")
				if(pos==0):
					str=str[pos+6:]
					vlev=int(str)
					
				pos=str.find("r_frame_rate=")
				if(pos==0):
					str=str[pos+13:]
					ar=str.split("/")
					if(len(ar)>1):
						fps=float(ar[0])/float(ar[1])
					
				pos=str.find("display_aspect_ratio=")
				if(pos==0):
					str=str[pos+len("display_aspect_ratio="):]
					ar=str.split(":")
					if(len(ar)>1):
						asp=float(ar[0])/float(ar[1])
			
			#---- format
			elif(state==2):	#[FORMAT]
				pos=str.find("format_name=")
				if(pos==0):
					str=str[pos+len("format_name="):]
					mv=str.split(",")
					#dbg("get_minfo_fp: found format_name=%s mv=%r" % (str,mv))
					if(len(mv)>0):
						fmt=mv[0]
					if(fmt=="mov"):
						fmt="mp4"
				#pass

	if(vc=="-"):
		rc= -1
	dbg("------ ffprobe outputs end vc=%s vlev=%d rc=%d -------------" % (vc,vlev,rc))
	return (fmt,w,h,fps,vc,vlev,asp,rc)

def get_minfo_ytdl (str,elogf):
	#------------------------------------------------------------
	# get media profile (only size,format) from  youtube-dl
	#------------------------------------------------------------
	#ex1: "137 - 1920x1080 (DASH video)+141 - audio only (DASH audio)"
	#ex2: "22 - 1280x720"
	#ex3: "95 - 720p (HLS)"
	#widthxheight is nominal, and may not be true: differ from real value
	#  18 : mp4 [360x640]
	#  43 : webm[360x640]
	#  22 : mp4 [720x1280]
	# 137 : mp4 [1080p] (DASH Video)

	dbg("get_minfo_ytdl: Start")
	#--- defaults
	w=856.0
	h=480.0
	fps=29.970
	fmt="mp4"	#format
	vc="-"	#vcodec
	vlev=0
	rc= -1 #failed
	mv=str.split()
	if(len(mv)<3):
		dbg("get_minfo_ytdl: failed, there isn't not enoufgh args")
		return (fmt,w,h,fps,vc,vlev,rc)
	dbg("get_minfo_ytdl: pos 1")
	fm=int(mv[0])
	wh=mv[2].split("x")
	if(len(wh)>1):
		w=float(wh[0])
		h=float(wh[1])
	dbg("get_minfo_ytdl: pos 2")
	if(fm==22 or fm==137):
		#720p,1080p :realiable?
		vc="h264"  #really?
		rc=0
	dbg("get_minfo_ytdl: rc=%d fmt=%d w=%d h=%d fmt=%s vc=%s" % (rc,fm,w,h,fmt,vc))
	return (fmt,w,h,fps,vc,vlev,rc)

def kick_LivePlayer(url,video_out,opt_str,dpsize_w,dpsize_h,ifps):

	print "web_prog_ex="+gs_python
	print "web_cvparams=%s %s $output " % (LivePlayer,url)
	print "web_cvparams= --temp %s --sess_id %s --clippath_a $clippath_a" % (tempb,sess_id)
	print "web_cvparams= --bgm %d --dpsize_w %d --dpsize_h %d --ifps %f" % (bgmf,dpsize_w,dpsize_h,ifps)
	print "web_cvparams= --opt_str \"%s\"" % (opt_str)
	print "web_exit=0"
	#print "web_logmsg=kick_LivePlayer: opt_str=%s" % opt_str

#----------------------------------------------------------------------------------
# main
#----------------------------------------------------------------------------------
if __name__ == "__main__":
	
	tm_start=time.time()
	timeseek=0.0
	#setdbg(gs_debug)
	dbg0("==== RzWebMediaInfo: Main Start")
	dbg0("RzWebMediaInfo: arg_cnt=%d args=%r" % (len(sys.argv),sys.argv))
	
	#---- get args ------------------
	if(len(sys.argv)<4):
		print >>sys.stderr, "Usage: python %s {temp} {sess_id} {transcoder} {cvfile_in} {cvfile_out} {timeseek} [opt_str]" % sys.argv[0]
		quit()
	myprog=sys.argv[0]
	tempb=sys.argv[1]
	sess_id=sys.argv[2]
	transcoder=sys.argv[3]
	cvfile_in=sys.argv[4]
	cvfile_out=sys.argv[5]
	timeseek=float(sys.argv[6])
	#clippath_a=sys.argv[7]
	web_cvfile_in=cvfile_in
	web_cvfile_in2=None
	
	#------------------------------------------------------------------
	# setup temp files
	#------------------------------------------------------------------
	if(True):
		#---- init settings 
		temp=tempb+"\\web"  # slash cause confusion on ffmpeg 
		if not os.path.exists(temp):
			os.makedirs(temp)
		elogfile=temp+"\\web_work("+sess_id+").log"
		elogf=open(elogfile,"w")
	else:
		#logfile="web_work.log"
		logfile=temp+"\\web\\"+"web_work("+sess_id+").log"
		logf=open(logfile,"w")
		#logf=sys.stderr
	
	if(len(sys.argv)>7):
		opt_str=sys.argv[7]	# options string
		dbg("RzWebMediainfo: opt_str="+opt_str)
		#print >>sys.stderr, "RzWebMediainfo: opt_str=%s" % opt_str
	else:
		opt_str=""	
	
	dbg("------ RzWebMediaInfo.py start -------------")
	
	#------------------------------------------------------------------
	# parse options (mainly, for youtube-dl options)
	#------------------------------------------------------------------
	#--- cache,cookies
	yt_cache_ps=0   # =1: test for use individual cache per session  
	if(yt_cache_ps):
		yt_cache_dir=tempb+"/youtube-dl(%s)" % sess_id
		yt_cookie_file=yt_cache_dir+"/"+"cookie.txt"
	else:
		yt_cookie_file=temp+"/"+"cookie("+sess_id+").txt"
	
	#--- quality
	#--------------------------------------
	# Available formats:
	#  5 : flv [240x400]
	#  17 : 3gp [144x176]
	#  36 : 3gp [240x320]
	#  18 : mp4 [360x640]
	#  43 : webm[360x640]
	#  22 : mp4 [720x1280]
	# 137 : mp4 [1080p] (DASH Video)
	# 136 : mp4 [720p] (DASH Video)
	# 135 : mp4 [480p] (DASH Video)
	# 134 : mp4 [360p] (DASH Video)
	# 133 : mp4 [240p] (DASH Video)
	# 160 : mp4 [192p] (DASH Video)
	# 141 : m4a [256k] (DASH Audio)
	# 140 : m4a [128k] (DASH Audio)
	# 139 : m4a [48k] (DASH Audio)
	#--------------------------------------
	
	pos=opt_str.rfind("qlev=")	#last param
	level="best"
	if(pos>=0):
		list=opt_str[pos+5:].split(",",1)
		level=list[0]
	uopt2=None
	uopt="-g -f best[height=720]/bestvideo[height<=480]+bestaudio/best"
	if(level == "best"):
		#yt_quality=37	#1080p
		yt_quality=137  #dash-video, don't work well: terrible slow
		#uopt="-g -f 137+22"
		uopt="-g -f bestvideo[height=1080][ext=mp4]+bestaudio/best[height<=720][height>480]/bestvideo[height=480]+bestaudio/bestvideo[height<=480]+bestaudio/best"
		
		#---- prepair second option(same as level==high) to avoid dash-video
		if(can_dash_480p):  # cover 480p DashVideo
			uopt2="-g -f best[height=720]/bestvideo[height=480]+bestaudio/bestvideo[height<=480]+bestaudio/best"
		else:
			uopt2="-g -f best"  #best except DashVideo
	elif(level == "high"):
		yt_quality=22	#720p
		if(can_dash_480p):  # cover 480p DashVideo
			uopt="-g -f best[height=720]/bestvideo[height=480]+bestaudio/bestvideo[height<=480]+bestaudio/best"
		else:
			uopt="-g -f best"  #best except DashVideo
	elif(level == "medium"):
		yt_quality=35	#480p
		uopt="-g -f best[height<=480]/best"
	elif(level == "low"):
		yt_quality=18	#360p
		uopt="-g -f best[height<=360]/worst"
	
	#--- others
	#--- latest youtube-dl stopped support --max-quality !
	if(user!=""):
		uopt += user
	uopt += " --retries 1 --quiet"
	
	#---- clear cache for reset 403 Forbidden
	#uopt += " --rm-cache-dir "  
	
	#---- use individual cache per session
	if(yt_cache_ps):
		uopt += " --cache-dir %s " % (yt_cache_dir) # win 
	

	#------------------------------------------------------------------
	# parse options (mainly, for transcoding by ffmpeg/mencoder )
	#------------------------------------------------------------------
	resize=True
	#m2ts=0  #output format
	#trans_format="mpegps"   #trans format=mpegps
	sd_zoom=1.0  	# zoom specfic for DVD
	us_zoom=1.0  	# zoom for general 
	us_zoom_pos=0  	# zoom center type 
	
	remux_start_skip=0.0
	param_ifps=0.0
	renderer=""
	if(opt_str.find("-no_audio")>=0):
		no_audio=1
	
	if(opt_str.rfind("-bgm=2")>=0):
		bgmf=2
	if(opt_str.rfind("-bgm=1")>=0):
		bgmf=1
	if(opt_str.rfind("-bgm=0")>=0):
		bgmf=0
	
	#if(opt_str.find("m2ts=1")>=0):
	#	m2ts=1
	pos=opt_str.find("trans_format=")
	if(pos>=0):
		lst=opt_str[pos+len("trans_format="):].split(",",1)
		trans_format=lst[0]
	
	if(opt_str.find("remux=0")>=0):
		remuxWhenCompatible=False
	elif(opt_str.find("remux=1")>=0):
		remuxWhenCompatible=True
	elif(opt_str.find("remux=2")>=0):
		force_remux=True
	if(opt_str.find("resize=0")>=0):
		resize=False
	pos=opt_str.find("resize_w=")
	if(pos>=0):
		lst=opt_str[pos+9:].split(",",1)
		d_w=int(lst[0])
	pos=opt_str.find("resize_h=")
	if(pos>=0):
		lst=opt_str[pos+9:].split(",",1)
		dbg("resize_h split="+lst[0])
		d_h=int(lst[0])
	pos=opt_str.find("asp_hack=")
	if(pos>=0):
		lst=opt_str[pos+9:].split(",",1)
		asp_hack=int(lst[0])
	pos=opt_str.find("sd_zoom=")
	if(pos>=0):
		lst=opt_str[pos+8:].split(",",1)
		sd_zoom=float(lst[0])
		
	pos=opt_str.find("us_zoom=")
	if(pos>=0):
		lst=opt_str[pos+len("us_zoom="):].split(",",1)
		us_zoom=float(lst[0])
	pos=opt_str.find("us_zoom_pos=")
	if(pos>=0):
		lst=opt_str[pos+len("us_zoom_pos="):].split(",",1)
		us_zoom_pos=int(lst[0])

	pos=opt_str.find("remux_start_skip=")
	if(pos>=0):
		lst=opt_str[pos+len("remux_start_skip="):].split(",",1)
		dbg("remux_start_skip="+lst[0])
		remux_start_skip=float(lst[0])
	pos=opt_str.find("fps=")
	if(pos>=0):
		lst=opt_str[pos+len("fps="):].split(",",1)
		dbg("param fps="+lst[0])
		param_ifps=float(lst[0])
	pos=opt_str.find("renderer=")
	if(pos>=0):
		lst=opt_str[pos+len("renderer="):].split(",",1)
		dbg("param renderer="+lst[0])
		renderer=lst[0]
	
	proc_type=0
	pos=opt_str.rfind("proc_type=")
	if(pos>=0):
		lst=opt_str[pos+len("proc_type="):].split(",",1)
		dbg("param renderer="+lst[0])
		proc_type=int(lst[0])
	
	pos=opt_str.rfind("fps_limit=")
	if(pos>=0):
		lst=opt_str[pos+len("fps_limit="):].split(",",1)
		dbg("param fps_limit="+lst[0])
		g_fps_limit=int(lst[0])
		
	pos=opt_str.rfind("adelay=")
	if(pos>=0):
		lst=opt_str[pos+len("adelay="):].split(",",1)
		dbg("adelay="+lst[0])
		g_adelay=float(lst[0])
	pos=opt_str.rfind("aspect=")
	if(pos>=0):
		lst=opt_str[pos+len("aspect="):].split(",",1)
		dbg("g_aspect="+lst[0])
		g_aspect=float(lst[0])
	
	#------------------------------------------------------------------
	# setup transcode options defaults
	#------------------------------------------------------------------
	#---- parse opts
	#--- no effect : b/c main using cache
	#if(timeseek==0):
	#	timeseek= -2.0
	
	#if(opt_str.find("url_parse=off")> -1):
	if("url_parse=off" in opt_str):
		need_geturl=False
	if("force_trans" in opt_str):
		remuxWhenCompatible=False
	
	# -of mpeg vs lavf
	# mpeg(mencoder muxer) cause statter on non-nornmal fps 
	# lavf(ffmpeg muxer) improve statter on non-nornmal fps 
	
	#---- judge mode
	#expand[=w:h:x:y:o:a:r]
	p_vf="-vf scale=684:456,expand=720:480,ass" # for mencoder
	p_vf_fm="-vf scale=684:456,pad=720:480:18:12" # for ffmpeg
	p_user=""
	
	if(medinfo_mode==mode_auto):
		# pass to mencoder's auto-judge, fast start and 60% will succeed, but others are ..orz
		#p_of="-of mpeg"
		#p_of="-of lavf -lavfopts format=mpegts"
		need_getinfo=False
		p_fmt="mpeg2"
		p_aspect="autoaspect=1"
		f_aspect="4:3"
		p_fps=""
	else:
		# judge options by mediainfo, almost all will succeed, but slow start... orz;
		#p_of="-of mpeg"
		#p_of="-of lavf -lavfopts format=mpegts"
		p_fmt="mpeg2"
		p_aspect="aspect=4/3"
		f_aspect="4:3"
		d_aspect=1.3333333
		p_fps="-ofps 24000/1001"
	
	#--- video format for mencoder		
	if(trans_format=="mpegps"):
		p_of="-of mpeg" 
	else:
		p_of="-of lavf -lavfopts format=mpegts" 
		if(trans_format=="m2ts"):
			m2ts=1
			#can't use mencoder for m2ts
			nicomode=2   # ffmpeg+youtube-dl
	
	#------------------------------------------------------------------
	# judge sites
	#------------------------------------------------------------------
	proc_type_sv=proc_type
	sfx=cvfile_in[-6:].lower()
	if(sfx.endswith(".mp4") or sfx.endswith(".mov") or sfx.endswith(".ts")):
		p_user="-user-agent QuickTime/7.6.2"
		need_geturl=False
	if(sfx.endswith(".flv") or sfx.endswith(".avi")):
		need_geturl=False
	
	if(cvfile_in.find("rtmp://")>=0 or cvfile_in.find("rtsp://")>=0): 
		need_geturl=False
		need_getinfo=getinfo_live_ytb
		ffprog=ffmpeg2  # doesn't work for youtube live 
	
	elif(cvfile_in.find("www.youtube.com")>=0 
		or cvfile_in.find("www.dailymotion.com")>=0
		or cvfile_in.find("www.pandora.tv")>=0
		or cvfile_in.find("channel.pandora.tv")>=0
		or cvfile_in.find("www.anitube")>=0
		#or cvfile_in.find("//m.youtube.com/")>=0 
		or proc_type==1):
		#---- Yutube type  [ffmpeg only]
		dbg("proc_type=1: use ffmpeg directly (Site may be like youtube)")
		proc_type=1 #[ffmpeg only]
		youtube=1
		ffprog=ffmpeg2  # doesn't work for youtube live 
		
	elif(cvfile_in.find("xvideos.com")>=0):
		#---- Xvideos
		dbg("Site may be: xvideos")
		proc_type=1 #[ffmpeg only]
		if(cvfile_in.startswith("http://jp.xvideos.com/")):
			#---- xvideos
			dbg("Site may be: xvideos")
			cvfile_in=cvfile_in.replace("http://jp.xvideos.com/","http://www.xvideos.com/",1)
		
	elif(cvfile_in.find("www.nicovideo.jp")>=0
		or cvfile_in.find(".fc2.com")>=0 or proc_type==2):
		#---- Nicovideo/FC2:
		proc_type=2  #[ffmpeg+youtube-dl]
		dbg("proc_type=2: use youtube-dl (Site may be like Nicovideo/FC2) ")
		if(cvfile_in.endswith("&suggest")):
			cvfile_in=cvfile_in.replace("&suggest","",1)
		# sample: http://www.nicovideo.jp/watch/sm15355324
		nicovideo=nicomode
		need_geturl=False
		need_getinfo=True  #fast startup, but not accurate aspect 
		timeseek=0.0
		if(nicomode>=2):  #use ffmpeg
			use_ffmpeg_trans=True
			use_ffmpeg_remux=True
		else: #use mencoder
			use_ffmpeg_trans=False
			use_ffmpeg_remux=True
		getinfo_type=nicogetinfo
		ffprog=ffmpeg0
		
	elif(cvfile_in.find("ustream")>=0 or proc_type==3):
		#---- ustream 
		dbg("proc_type=3: Use livestreamer (Site may be like ustream live) ")
		remuxWhenCompatible=0  # remux doesn't work well on ustream for REGZA?
		need_geturl=True
		use_ffmpeg_trans=True
		ffprog=ffmpeg1
		timeseek=0.0
		if(cvfile_in.find("recorded")<0 or cvfile_in.find("/channel/")>=0 or proc_type==3):  
			# live/channel is not url for video but playlist
			if(use_LivePlayer):
				proc_type=3 #[ffmpeg+livestreamer]
				dbg("kick kick_LivePlayer")
				#use external player for ustream live/channel
				kick_LivePlayer(cvfile_in,cvfile_out,opt_str,d_w,d_h,param_ifps)
				sys.exit(0)
			else:
				remuxWhenCompatible=0  # remux doesn't work well for m3u8(live)
				nicovideo=nicomode
				need_geturl=False
				need_getinfo=getinfo_live_ust
				use_ffmpeg_trans=True
				use_ffmpeg_remux=True
				getinfo_type=nicogetinfo
				nico_streamer=2 # use LiveStreamer
	
	elif(cvfile_in.find(".m3u8")>=0):
		# HTML live 
		proc_type=1 #[ffmpeg only]
		need_geturl=False
		need_getinfo=getinfo_live_ytb
		timeseek=0.0
	else:
		if(True):
			proc_type=2  #[ffmpeg+youtube-dl]
			dbg("Site may be: Others")
		else:
			proc_type=1  #[ffmpeg]
			dbg("Site may be: Others")
	
	if(proc_type_sv!=0):
		proc_type=proc_type_sv
	if(proc_type==1):		#[ffmpeg]
		need_geturl=True
		need_getinfo=True
	elif (proc_type==2):	#[ffmpeg+youtube-dl]
		nicovideo=nicomode  #use ffmpeg <--(pipe)-- youtube-dl
		need_geturl=False
		need_getinfo=True
		ffprog=ffmpeg1 #use new ffmpeg
		ff_stime=""    #new ffmpeg cause error if use param {-ss time} for pipe(non_seekable)
	
	dbg("Judge Site end, proc_type=%d need_geturl=%d, need_getinfo=%d, url=%s" % (proc_type,need_geturl,need_getinfo,cvfile_in))
		
	ff_stime="-ss $time_start"
	if(cvfile_in.find("rtmp://")>=0):
		ff_stime=""
		ff_agent=""
	if (proc_type==2 or proc_type==3):	#[ffmpeg+{youtube-dl|livestreamer}]
		ff_stime=""  # new ffmpeg cause error on seek pipe
	
	#---- debug print
	#print "web_logmsg=trans_format=%s" % trans_format  #display on PMS trace window
	dbg("gs_prog_ytdl=%r" % gs_prog_ytdl)
	dbg("transcoder="+transcoder)
	dbg("cvfile_in="+cvfile_in)
	dbg("cvfile_out="+cvfile_out)
	dbg("yt_cookie_file="+yt_cookie_file)
	dbg("opts="+opt_str)
	dbg("--> parsed: quality=%s, remux=%s, resize=%s resize_wh=%dx%d" % (level,remuxWhenCompatible,resize,d_w,d_h))
	dbg("medinfo_mode=%d(mode_auto=%d,mode_manual=%d)" % (medinfo_mode,mode_auto,mode_manual))
	dbg("need_geturl="+str(need_geturl)+", need_getinfo="+str(need_getinfo))
	dbg("uopt="+uopt)
	dbg("defaults: fmt=%s, aspect=%s, fps=%s" % (p_fmt,p_aspect,p_fps))
	
	#----------------------------------------------------------------------------------
	# get real_URL of web_cntent from cvfile_in
	#----------------------------------------------------------------------------------
	dbg("==== get_url start")
	dbg("need_geturl=%d" % need_geturl)
	dbg("nicovideo=%d" % nicovideo)
	
	cookie=""
	ff_cookie=""
	mc_cookie=""
	ytdl_info_str=None
	if need_geturl:
		#---- retry loop for avoid youtube dash-video (ffmpeg can't handle yet)
		for r in range(2):
			if(nicovideo):
				args=gs_prog_ytdl+uopt.split()+nico_account.split()+["--cookies",yt_cookie_file,cvfile_in]
			else:
				if(youtube and getinfo_ytdl>0):
					args=gs_prog_ytdl+ytb_account.split()+uopt.split()+["--get-format","--cookies",yt_cookie_file,cvfile_in]
				else:
					args=gs_prog_ytdl+ytb_account.split()+uopt.split()+["--cookies",yt_cookie_file,cvfile_in]
			#args=args.split()
			dbg("geturl args=%s" % (args))
			
			(rc,outbuf)=exec_prog(1,args,elogf,timeup_geturl,True)
			dbg("geturl: rc=%d, outbuf_line_count=%d" % (rc,len(outbuf)))
			dash_video=0
			if(rc==0 and len(outbuf)>0):
				if(nicovideo):
					cookie=get_NicoCookies(yt_cookie_file)
					ff_cookie="- headers %s" % cookie
					mc_cookie="-cookies -cookies-file %s" % yt_cookie_file
				web_cvfile_in=outbuf[0].rstrip()
				dbg("got web_cvfile_in=%s" % web_cvfile_in)
				
				#if(web_cvfile_in.find("/itag/")>=0 and web_cvfile_in.find("m3u8")<0):
				if(web_cvfile_in.find("m3u8")<0):
					#--- a tricky judge for dash-video: to be refined
					if(web_cvfile_in.find("/itag/137/")>=0):
						dash_video=1
					elif(web_cvfile_in.find("/itag/135/")>=0):
						dash_video=1
				
				#if(youtube and yt_quality==137 and len(outbuf)>1):
				if(youtube and len(outbuf)>1):
					for i in range(1,len(outbuf)):
						strw=outbuf[i].rstrip()
						if(strw.startswith("http")):
							web_cvfile_in2=strw
							dbg("got web_cvfile_in2=%s" % web_cvfile_in2)
						elif(getinfo_ytdl>0 and re.match(r"^\d+\s+",strw)):
							dbg("got ytdl_info_str=%s" % ytdl_info_str)
							ytdl_info_str=strw
							#--- judge not accurate!!
							#if(strw.find("DASH video")>=0):
							#	dash_video=1
				#if(False and dash_video and uopt2 is not None):
				if(dash_video and uopt2 is not None):
					#---- retry another URL, play for not Dash-video 
					dbg("Dash-Video found: retry to get another URL")
					print "web_logmsg= Dash-Video found: not supported --> retrying to get another URL"
					uopt=uopt2
				else:
					break
			else:
				web_cvfile_in=cvfile_in
				err_str=dump_errlog(elogfile)
				msg="geturl Failed, error=%d, [ %s ]" % (rc,err_str)
				print "web_logmsg=%s" % msg 
				if(True):
					dbg(msg)
					#print "web_exit=%d" % (rc)
					disp_error(msg) #disp error as video_message on renderer screen
					os._exit(rc)
				break
				
		if(False and yt_quality==137 and youtube>0):
			#args=prog_ytdl+" -g --max-quality 140 "+cvfile_in 	# worse audio (128kbps)
			#args=prog_ytdl+" -g --max-quality 141 "+cvfile_in 	# best audio (256kbps), but not exists
			#args=prog_ytdl+" -g --max-quality 22 "+cvfile_in    	# better audio (192kbps),really exists
			args=gs_prog_ytdl+["-g","--max-quality","22",cvfile_in]    	# better audio (192kbps),really exists
			#args=args.split()
			dbg("geturl args=%s" % (args))
			(rc,outbuf)=exec_prog(1,args,elogf,0,True)
			dbg("geturl: rc=%d, outbuf_line_count=%d" % (rc,len(outbuf)))
			if(rc==0 and len(outbuf)>0):
				web_cvfile_in2=outbuf[0].rstrip()
				dbg("got web_cvfile_in2=%s" % web_cvfile_in2)
			else:
				print "web_logmsg= geturl Failed, error=%d" % rc
				dump_errlog(elogfile)
				web_cvfile_in=cvfile_in
				if(False):
					dbg("geturl: failed rc=%d, let's exit" % (rc))
					print "web_exit=%d" % (rc)
					os._exit(rc)
	tm_geturl=time.time()
	
	#---- for audio delay option
	if(g_adelay!=0.0 and web_cvfile_in2 is None):
		dbg("WebMediaInfo: adelay=%f !=0 --> use 2nd input for audio" % g_adelay)
		web_cvfile_in2=web_cvfile_in
		
	#---- now fixed real url (web_cvfile_in,web_cvfile_in2)
	#---- maint. params according to url protocols
	if(web_cvfile_in.startswith("http")):
		ff_opt0=ff_opt0_http
		ff_opt1=ff_opt1_http
		
	#------------------------------------------------------------
	# get media profile & aspect/fps tunings
	#------------------------------------------------------------
	#line=VIDEO:  [H264]  854x480  0bpp  29.970 fps  1180.1 kbps (144.1 kbyte/s)
	#line=[V] filefmt:44  fourcc:0x34363248  size:854x480  fps:29.970  ftime:=0.0334
	
	dbg("get_info: web_cvfile_in=%s no_audio=%d bgmf=%d need_getinfo=%d youtube=%d use_LivePlayer%d"
		% (web_cvfile_in,no_audio,bgmf,need_getinfo,youtube,use_LivePlayer))
		
	if(web_cvfile_in.find(".m3u8")>=0): # add bgm for liveStream
		if(bgmf==1 and youtube and use_LivePlayer):
			#use external player for youtube live cams
			kick_LivePlayer(web_cvfile_in,cvfile_out,opt_str,d_w,d_h,param_ifps)
			os._exit(0)
	elif(bgmf==2 and youtube):  # change sound to BGM for any video
		#use external player for youtube live cams
		kick_LivePlayer(web_cvfile_in,cvfile_out,opt_str,d_w,d_h,param_ifps)
		os._exit(0)
		
		remuxWhenCompatible=0  # remux doesn't work well for m3u8(live)
		ffprog=ffmpeg1         # ffmpeg2 doesn't work well for m3u8(live)
		need_getinfo=getinfo_live_ytb
		
		if(m3u8_useLivestream):
			use_ffmpeg_trans=True
			ffprog=ffmpeg1
			nicovideo=nicomode
			#need_geturl=False
			use_ffmpeg_trans=True
			use_ffmpeg_remux=True
			getinfo_type=nicogetinfo
			nico_streamer=2 # use LiveStreamer
			m3u8="m3u8"

	dbg("==== getinfo start")
	dbg("need_getinfo =%d getinfo_ytdl=%d ytdl_info_str=%s" % (need_getinfo,getinfo_ytdl,ytdl_info_str))
	if need_getinfo:
		s_aspect=0.0
		do=1
		if(getinfo_ytdl>1 and ytdl_info_str is not None):
			dbg("get_minfo: exec get_minfo_ytdl")
			(s_fmt,s_w,s_h,s_fps,s_vc,s_vlev,rc)=get_minfo_ytdl(ytdl_info_str,elogf)
			dbg("get_minfo_ytdl rc=%d" % rc)
			if(rc==0): # relyable
				do=0
		if(do):
			if(getinfo_type==1):
				dbg("get_minfo: exec get_minfo_mc")
				(s_fmt,s_w,s_h,s_fps,s_vc,s_vlev,s_aspect,rc)=get_minfo_mc(mencoder,web_cvfile_in,elogf)
			elif(getinfo_type==2):
				dbg("get_minfo: exec get_minfo_ff")
				(s_fmt,s_w,s_h,s_fps,s_vc,s_vlev,s_aspect,rc)=get_minfo_ff(ffprog,web_cvfile_in,elogf)
			else:
				dbg("get_minfo: exec get_minfo_fp")
				(s_fmt,s_w,s_h,s_fps,s_vc,s_vlev,s_aspect,rc)=get_minfo_fp(ffprog,web_cvfile_in,elogf)

		dbg("get_minfo: fmt=%s, vc=%s w=%f, h=%f, (w/h=%f) fps=%f asp=%f rc=%d" % (s_fmt,s_vc,s_w,s_h,(s_w/s_h),s_fps,s_aspect,rc))
		#if(False and rc!=0):
		if(rc!=0):
			#---- Mencoder always exit=1, why?
			err_str=dump_errlog(elogfile)
			msg="get_Mediainfo: failed rc=%d, [ %s ]" % (rc,err_str)
			dbg(msg)
			#print "web_exit=%d" % (rc)
			disp_error(msg)
			
			#---- sys.exit may not really exit!!
			#sys.exit(rc)
			os._exit(rc)
	else:
		s_w=856.0
		s_h=480.0
		s_fps=29.97
		s_aspect=1.7777
		s_vc="mpegVideo"
		s_fmt="mpeg"	#format
		
	#------------------------------------------------------------
	# judge aspect ratio
	#------------------------------------------------------------
	# memcoder's autoaspect can't work if no aspect data in media
	# and, mencoder dosn't report whether aspect data exists or not.
	# So, after all, you must directly indicate aspect
	# when doubtful media_size.
	#------------------------------------------------------------
	if(s_aspect<=0):
		#not found in media info 
		s_aspect=s_w/s_h
	if(g_aspect>0):
		#forced
		s_aspect=g_aspect
	expf=0
	
	if(s_aspect >=1.35):	#wide
		p_aspect="aspect=16/9"
		f_aspect="16:9"
		d_aspect=1.7777778
	
	if(d_h >480 and asp_hack>0):
		#----------------------------------------------------
		# over 480p, regza can't disp mpeg2 with aspect 16/9 ??
		#----------------------------------------------------
		# but, "aspect=4/3"cause disp error at REGZA on some NicoVideo contents 
		# url=http://www.nicovideo.jp/watch/sm27469455 
		#----------------------------------------------------
		#p_aspect="aspect=16/9"
		p_aspect="aspect=4/3"  
		f_aspect="4:3"
		d_aspect=1.7777778
		
	if(s_aspect > d_aspect):	#wider than disp area
		expf=1		#need expand
		sc_w=d_w;
		sc_h=(d_h*d_aspect/s_aspect)
	elif(s_aspect < d_aspect):	#narrower than disp_area
		expf=1		#need expand
		sc_h=d_h;
		sc_w=(d_w*s_aspect/d_aspect)
		
	if(d_h<=480 and sd_zoom!=1.0):
		#compensate TV's over scan, should do only for like REGZA!
		dbg("video size is SD, exec sd_zoom=%f" % (sd_zoom))
		sc_w *= sd_zoom
		sc_h *= sd_zoom
		
	sc_w=(int)(sc_w+0.4)
	sc_h=(int)(sc_h+0.4)
	
	if(need_getinfo):
		#---- Test for general zooming
		#us_zoom=1.55
		#us_zoom_pos=3
		#---- scale according to minfo ----------
		if(us_zoom==1.0):
			if(expf):
				p_vf   ="-vf scale="+ str(sc_w)+":"+ str(sc_h)+",ass"+",expand="+ str(d_w)+":"+ str(d_h)
				p_vf_fm="-vf scale=%d:%d,pad=%d:%d:%d:%d" % (sc_w,sc_h,d_w,d_h,(d_w-sc_w)/4*2,(d_h-sc_h)/4*2)
			else:
				p_vf   ="-vf scale="+str(d_w)+":"+str(d_h)
				p_vf_fm="-vf scale=%d:%d" % (d_w,d_h)
		else:
			force_trans=1
			if(us_zoom>1):
				d_wz=d_w*us_zoom
				d_hz=d_h*us_zoom
			else:
				d_wz=d_w
				d_hz=d_h
			sc_wz=sc_w*us_zoom
			sc_hz=sc_h*us_zoom
			
			#--- force even
			if(int(d_wz) % 2==1):
				d_wz -=1
			if(int(d_hz) % 2==1):
				d_hz -=1
			if(int(sc_wz) % 2==1):
				sc_wz -=1
			if(int(sc_hz) % 2==1):
				sc_hz -=1
			#test
			#d_hz =1006
			#sc_hz =1006
			
			if(us_zoom_pos==0):
				# center
				crop_posx=(d_wz-d_w)/2.0  	# top left pos of cropped rect in zoomed area
				crop_posy=(d_hz-d_h)/2.0  	# top left pos of cropped rect in zoomed area
			
			elif(us_zoom_pos==1):
				# upper left
				crop_posx=0  				# top left pos of cropped rect in zoomed area
				crop_posy=0  				# top left pos of cropped rect in zoomed area
			elif(us_zoom_pos==2):
				# upper center
				crop_posx=(d_wz-d_w)/2.0  	# top left pos of cropped rect in zoomed area
				crop_posy=0  				# top left pos of cropped rect in zoomed area
			elif(us_zoom_pos==3):
				# upper right
				crop_posx=(d_wz-d_w)  		# top left pos of cropped rect in zoomed area
				crop_posy=0  				# top left pos of cropped rect in zoomed area
		
			elif(us_zoom_pos==4):
				# bottom left
				crop_posx=0  				# top left pos of cropped rect in zoomed area
				crop_posy=d_hz-d_h  		# top left pos of cropped rect in zoomed area
			elif(us_zoom_pos==5):
				# bottom center
				crop_posx=(d_wz-d_w)/2.0  	# top left pos of cropped rect in zoomed area
				crop_posy=d_hz-d_h  		# top left pos of cropped rect in zoomed area
			elif(us_zoom_pos==6):
				# bottom right
				crop_posx=d_wz-d_w  		# top left pos of cropped rect in zoomed area
				crop_posy=d_hz-d_h  		# top left pos of cropped rect in zoomed area
			
			if(expf):
				p_vf   ="-vf scale="+ str(sc_w)+":"+ str(sc_h)+",ass"+",expand="+ str(d_w)+":"+ str(d_h)
				p_vf_fm="-vf scale=%d:%d,pad=%d:%d:%d:%d,crop=%d:%d:%d:%d" % (sc_wz,sc_hz,d_wz,d_hz,(d_wz-sc_wz)/4*2,(d_hz-sc_hz)/4*2,d_w,d_h,crop_posx,crop_posy)
			else:
				p_vf   ="-vf scale="+str(d_w)+":"+str(d_h)
				p_vf_fm="-vf scale=%d:%d,crop=%d:%d:%d%d" % (d_wz,d_hz,d_w,d_h,crop_posx,crop_posy)
		
	else:
		#---- auto scaling by ffmpeg
		#ffmpeg's auto scaling fails some time!!
		#p_vf   ="-filter_complex pad=(ih+1)*16/9/sar:ih:(ow-iw)/2:(oh-ih)/2,scale=%dx%d" % (d_w,d_h)
		#p_vf_fm="-filter_complex pad=(ih+1)*16/9/sar:ih:(ow-iw)/2:(oh-ih)/2,scale=%dx%d" % (d_w,d_h)
		#p_vf   ="-filter_complex pad='if(gt(iw,(ih+1)*16/9/sar),iw,(ih+1)*16/9/sar)':ih:'if(gt(ow,iw),(ow-iw)/2,0)':'if(gt(oh,ih),(oh-ih)/2,0)',scale=%dx%d" % (d_w,d_h)
		#p_vf_fm="-filter_complex pad='if(gt(iw,(ih+1)*16/9/sar),iw,(ih+1)*16/9/sar)':ih:'if(gt(ow,iw),(ow-iw)/2,0)':'if(gt(oh,ih),(oh-ih)/2,0)',scale=%dx%d" % (d_w,d_h)
		
		#p_vf="-filter_complex scale='if(gt(dar,16/9),%s,-1)':'if(gt(dar,16/9),-1,%s)',pad=%s:%s:'if(gt(%s,iw),(%s-iw)/2,0)':'if(gt(%s,ih),(%s-ih)/2,0)'" % (d_w,d_h,d_w,d_h,d_w,d_w,d_h,d_h)
		p_vf="-filter_complex scale='if(gt(dar,16/9),%s,%s*dar)':'if(gt(dar,16/9),%s/dar,%s)',crop='if(gt(iw,%s),%s,iw)':'if(gt(ih,%s),%s,ih)',pad=%s:%s:'if(gt(%s,iw),(%s-iw)/2,0)':'if(gt(%s,ih),(%s-ih)/2,0)'" % (d_w,d_h,d_w,d_h,d_w,d_w,d_h,d_h,d_w,d_h,d_w,d_w,d_h,d_h)
		p_vf_fm=p_vf
		
	#------------------------------------------------------------
	# judge fps
	#------------------------------------------------------------
	dbg("s_fps=%f" % (s_fps))
	f_fps="-r:v 24000/1001"  #for ffmpeg
	f_fps=""    # output fps for ffmpeg
	ff_ifps=""  # input  fps for ffmpeg
	p_fps=""
	
	if(param_ifps>0):
		s_fps=param_ifps   #forced

	if(s_fps>59.8 and s_fps<60.2):
		p_fps="-ofps 30000/1001"
		f_fps="-r 30000/1001"
		if(g_fps_limit):
			force_trans=1
		
	elif(s_fps>29.8 and s_fps<30.2):
		#p_of="-of mpeg"  
		p_fps="-ofps 30000/1001"
		
	elif(s_fps>24.8 and s_fps<25.2):
		#p_of="-of mpeg"
		#for easy & smooth convert PAL to NTSC
		#ff_ifps="-r 24000/1001"  #fake input fps: treat 25fps as 24fps
		p_fps=""  #mencoder doesn't support! 25fps 
		
	elif(s_fps>23.8 and s_fps<24.2):
		#p_of="-of mpeg"
		p_fps="-ofps 24000/1001"
		
	elif(s_fps>9.8 and s_fps<20.2): # 10,15,20
		p_fps="-ofps 30000/1001"
		f_fps="-r 30000/1001"
		
	else:
		#may be VFR (like WMV) : lavf's mpegts seems can't handle well , use mpeg
		p_of="-of mpeg"
		p_fps="-ofps 24000/1001"
		f_fps="-r 240000/1001"
		
	tm_getinfo=time.time()
	
	#---------------------------------------------------------------------------------
	# Judge Remuxable
	#---------------------------------------------------------------------------------
	remux=0
	if need_getinfo:
		#print "w=%d, h=%d s_vc=%s" % (w,h,s_vc)
		if(remuxWhenCompatible and "h264" in s_vc):
			if(s_w==1920 and s_h>=1070 and s_h<=1090):
				remux=1
			elif(s_w>=1270 and s_w<=1290 and s_h>=710 and s_h<=730):
				remux=1
			elif(s_w==720 and s_h==480):
				remux=0 	#bad on regza
			if(s_vlev>=50):
				#many renderer like REGZA does't support h264 Level 5.0 or higher
				remux=0
	if(force_remux):
		remux=1
	if(force_trans):
		remux=0
	dbg("force_trans=%r Judged Remuxable=%d" % (force_trans,remux))
	#---------------------------------------------------------------------------------
	# output media info of source contents (optional)
	#---------------------------------------------------------------------------------
	dbg("output media info")
	if(need_getinfo):
		#print "web_logmsg=w=%d,h=%d,asp=%f,fps=%f,vc=%s,remux=%d" % (int(s_w),int(s_h),s_w/s_h,s_fps,s_vc,remux)
		web_medinfo="web_medinfo=fmt=%s,w=%d,h=%d,asp=%.3f,fps=%.3f,vc=%s,remux=%d" % (s_fmt,int(s_w),int(s_h),s_w/s_h,s_fps,s_vc,remux)
		print web_medinfo
		dbg("dbg "+web_medinfo)
			
		#---- NG -----------------------------
		#elif(s_w==1440 and s_h==1080):	#NG may cause bad aspect ratio
		#elif(s_w==720 and s_h==480):	#NG
		#elif(s_w==640 and s_h==480):	#NG edge cutted by overscan of fool Regza 
		#elif(s_w==640 and s_h==360):	#NG
	
	#---------------------------------------------------------------------------------
	# output real URL of source contents
	#---------------------------------------------------------------------------------
	print "web_cvfile_in="+ web_cvfile_in
	if(web_cvfile_in2 is not None):
		#may be youtube dash video
		#ffprog=ffmpeg2  # quicker start than ffmpeg1
		print "web_cvfile_in2="+ web_cvfile_in2
	else:
		if(ffprog==ffmpeg2):
			ffprog=ffmpeg1  # ffmpeg1 is more stable than ffmpeg2, except when dash-video 
			#pass

	#---------------------------------------------------------------------------------
	# output appropriate transcoder_prog_path & it's params (optional)
	#---------------------------------------------------------------------------------
	# Override transcoder prog & params, if needed. 
	# multi-lines params will be all concatinated with 1 space
	# web_prog_ex={path of transcoder}
	# web_cvparams={params for transcoder}
	#---------------------------------------------------------------------------------
	# special keywords: these will be substituted by real value on exection of transcoder
	# $input : input_file (i.e. URL of the web contents)
	# $output: output_file (i.e. named pipe for PMS's streaming out)
	# $time_start: start time
	#----------------------------------------------------------------------------------
	# defaults is ..
	# web_prog_ex= win32\\mencoder.exe
	# web_cvparams= $input -quiet -prefer-ipv6 -cache 16384 
	# web_cvparams= -of mpeg -oac lavc -ovc lavc 
	# web_cvparams= -mpegopts format=mpeg2:muxrate=500000:vbuf_size=1194:abuf_size=64 
	# web_cvparams= -lavcopts aspect=16/9:vcodec=mpeg2video:acodec=ac3:abitrate=128:keyint=5:vqscale=1:vqmin=2:vbitrate=8000 
	# web_cvparams= -vf scale=684:456,expand=720:480 -mc 0.1 -af lavcresample=48000 -srate 48000
	# web_cvparams= -ofps 30000/1001 -o $output
	#----------------------------------------------------------------------------------
	
	dbg("---- Output return params Start ----")
	dbg("remux=%d, use_ffmpeg_remux=%d, use_ffmpeg_trans=%d, nicovideo=%d " % (remux,use_ffmpeg_remux,use_ffmpeg_trans,nicovideo))

	#transcoder's input param
	if(nicovideo and nicovideo!=3):
		#use stdin , b/c input is piped from youtube-dl
		inp="-"
		inp_ff="pipe:0"
		inp2="-"
		inp2_ff="pipe:0"
		ff_cookie=""   # use piped input from youtube-dl, so needn't
		ff_agent=""    # use piped input from youtube-dl, so needn't
	else:
		#use direct url
		inp="$input"
		inp_ff="$input"
		inp2="$input2"
		inp2_ff="$input2"
	
	fp_dummy_audio=""
	fp_map=""
	if(no_audio):
		fp_dummy_audio="-i %s" % (dummy_audio)
		fp_map= "-map 0:v -map 1:a"
	
	#-------------------------------------------------------------
	# itoffset for adalay,av-sync
	#-------------------------------------------------------------
	# "-itsoffset" : to avoid video delay&statter on REGZA when remuxed
	# "-itsoffset" must be located before "-i", otherwise will have no effect 
	itsoffset=""
	itsoffset_v=""
	itsoffset_a=""
	
	if(remux and remux_start_skip!=0):
		#to improve av async of long key-interval videos on REGZA
		#Ex. Recent x264 videos' keyint value may be over 200-300! insteadof traditional value(20-30)
		#remux_start_skip=-1.6
		skip=-remux_start_skip
	else:
		skip=0.0
		
	if(g_adelay>0): 
		itsoffset_v="-itsoffset %f" % skip
		itsoffset_a="-itsoffset %f" % (skip+g_adelay)
	elif(g_adelay<0):
		itsoffset_v="-itsoffset %f" % (skip-g_adelay)
		itsoffset_a="-itsoffset %f" % skip
	elif(skip!=0.0):
		itsoffset_v="-itsoffset %f" % skip
		itsoffset_a="-itsoffset %f" % skip
		itsoffset  ="-itsoffset %f" % skip
	
	
	#----------------------------------------------------------------
	# Final Parameter Setups for Transcoder(Remux/Transcode)
	#----------------------------------------------------------------
	dbg("---- Output return params Pos 1 ----")
	ff_transfmt="vob"
	if(trans_format=="m2ts"):
		ff_transfmt="mpegts"
		ff_opt2 +=" -mpegts_m2ts_mode 1"
	
	if(remux): 
		#----------------------------------------------------------------
		# Remux
		#----------------------------------------------------------------
		if(use_ffmpeg_remux): 
			#----------------------------------------------------------------
			# Remux by ffmpeg
			#----------------------------------------------------------------
			# use ffmpeg
			# -muxrate 2M : assert minimum bitrate, regza seems dislike bitrate <2Mbps at start
			if(nicovideo==3): # use ffmpeg only, for test
				#----------------------------------------------------------------
				# Remux by ffmpeg for Nicovideo3
				#----------------------------------------------------------------
				print "web_prog_ex="+ffprog
				print "web_cvparams= %s %s %s %s %s -i %s %s -f mpegts" % (ff_cookie,ff_agent,ff_opt0,itsoffset_v,ff_stime,inp_ff,fp_dummu_audio)
				print "web_cvparams= -vcodec copy -bsf:v h264_mp4toannexb -acodec ac3 -ab %d -ar 48000" % g_audio_bps
				print "web_cvparams= %s -loglevel %s -y " % (ff_async,gs_ff_loglev)
				print "web_cvparams= %s %s $output" % (fp_map,ff_opt2)
			
			elif(nicovideo):
				#----------------------------------------------------------------
				# Remux by ffmpeg for Nicovideo
				#----------------------------------------------------------------
				print "web_prog_ex="+gs_python
				print "web_cvparams="+nicoplayer+" "+cvfile_in+" "+cvfile_out+" "+ffprog +" "+m3u8
				if(no_audio):
					print "web_cvparams= %s %s %s -i %s %s -f mpegts" % (ff_opt0_pipe,itsoffset,ff_stime,inp_ff,fp_dummy_audio)
					print "web_cvparams= -vcodec copy -bsf:v h264_mp4toannexb -acodec ac3 -ab %d -ar 48000" % g_audio_bps
					print "web_cvparams= %s -loglevel %s -y -map 0:v -map 1:a" % (ff_async,gs_ff_loglev)
					print "web_cvparams= %s %s $output" % (fp_map,ff_opt2)
				else:
					print "web_cvparams= %s %s %s -i %s -f mpegts" % (ff_opt0_pipe,itsoffset,ff_stime,inp_ff)
					print "web_cvparams= -vcodec copy -bsf:v h264_mp4toannexb -acodec ac3 -ab %d -ar 48000" % g_audio_bps
					print "web_cvparams= %s -loglevel %s -y" % (ff_async,gs_ff_loglev)
					print "web_cvparams= %s %s $output" % (fp_map,ff_opt2)
			else:
				#----------------------------------------------------------------
				# Remux by ffmpeg for Generalvideo (except Nicovideo)
				#----------------------------------------------------------------
				print "web_prog_ex="+ffprog
				if(web_cvfile_in2 is not None):
					print "web_cvparams= %s %s %s %s %s -i %s %s %s %s -i %s -f mpegts -map 0:v -map 1:a" % (
						ff_cookie,ff_agent,ff_opt0,itsoffset_v,ff_stime,inp,
						ff_opt1,itsoffset_a,ff_stime,inp2)
				else:
					print "web_cvparams= %s %s %s %s %s -i %s -f mpegts" % (
						ff_cookie,ff_agent,ff_opt0,itsoffset,ff_stime,inp_ff)
				
				print "web_cvparams= -vcodec copy -bsf:v h264_mp4toannexb -acodec ac3 -ab %d -ar 48000" % g_audio_bps
				print "web_cvparams= %s -loglevel %s -y" % (ff_async,gs_ff_loglev)
				print "web_cvparams= %s $output" % (ff_opt2)
		
		else:	#use mencoder
			#----------------------------------------------------------------
			# Remux by Mencode
			#----------------------------------------------------------------
			#mencoder can't remux h264?
			print "web_logmsg= --- do Remux ----"
			if(nicovideo):
				print "web_prog_ex=" +gs_python
				print "web_cvparams="+nicoplayer+" "+cvfile_in+" "+cvfile_out+" "+mencoder
			#print "web_cvparams= -cookies -cookies-file %s" % yt_cookie_file
			#print "web_cvparams= %s %s %s %s %s -prefer-ipv4 -cache 16384" % (mc_cookie, mc_opt, ff_stime, inp, mc_loglev)
			print "web_cvparams= %s %s %s %s %s -cache 256000" % (mc_cookie,mc_opt,ff_stime,inp,mc_loglev)
			print "web_cvparams= -of lavf -lavfopts format=mpegts -oac lavc -ovc copy"
			print "web_cvparams= -lavcopts acodec=ac3:abitrate=448000"
			print "web_cvparams= -o $output"
	else:	
		#----------------------------------------------------------------
		# Transcode
		#----------------------------------------------------------------
		dbg("---- Output return params Pos 2 ----")
		if(use_ffmpeg_trans or web_cvfile_in2 is not None):	#use ffmpeg
			#----------------------------------------------------------------
			# Transcode by ffmpeg 
			#----------------------------------------------------------------
			p_vf=p_vf_fm
			#don't use copyts, will cause bad skip/ff
			#-f mpegts: sometime cause non_zero start_time 
			#-f vob: i.e. mpegps slightly improves above, except 1280x720 (->use 1282x720 instead ^^;)
			#-vf unsharp=7:7:2.5 : strong sharpness, but dirty
			
			dbg("---- Output return params Pos 3 ----")
			print "web_prog_ex="+ffprog
			if(nicovideo==3): # use ffmpeg only, currentry not work well
				#----------------------------------------------------------------
				# Transcode by ffmpeg specific for Nicovideo3
				#----------------------------------------------------------------
				print "web_cvparams= %s %s %s %s -i %s %s -f vob" % (ff_cookie,ff_agent,ff_opt0,ff_stime,
					inp_ff,fp_dummy_audio)
				print "web_cvparams= -vcodec mpeg2video -q:v 1 -acodec ac3 -ab %d -ar 48000" % g_audio_bps
				print "web_cvparams= "+ p_vf +" -aspect %s %s -loglevel %s -y" % (f_aspect,ff_async,gs_ff_loglev)
				print "web_cvparams= $output"
				# making params all end
			else:
				#----------------------------------------------------------------
				# Transcode by ffmpeg for general
				#----------------------------------------------------------------
				if(nicovideo):
					print "web_prog_ex=" +gs_python
					print "web_cvparams="+nicoplayer+" "+cvfile_in+" "+cvfile_out+" "+ffprog +" "+m3u8
			
				dbg("---- Output return params Pos 3-1 ----")
				if(False and trans_format=="m2ts"): # m2ts
					dbg("---- Output return params Pos 3-2 ----")
					print "web_cvparams= %s %s %s %s -i %s %s -f mpegts" % (
						ff_cookie,ff_agent,ff_opt0,ff_stime,inp_ff,fp_dummy_audio)
				else:
					dbg("---- Output return params Pos 3-3 ----")
					if(web_cvfile_in2 is None or nicovideo):
						print "web_cvparams= %s %s %s %s %s -i %s %s -f %s" % (
							ff_cookie,ff_agent,ff_opt0_pipe,ff_stime,ff_ifps,inp_ff,fp_dummy_audio,ff_transfmt)
						if(gs_verbose and nicovideo):
							msg="RzWebMediaInfo: Audio delay=%f, but for Nicovideo, can't handle 2nd input to do" % g_adelay
							dbg(msg)
							print "web_logmsg=%s" % msg
					else:
						print "web_cvparams= %s %s %s %s %s %s -i %s %s %s %s -i %s -f %s -map 0:v -map 1:a" % (
							ff_cookie,ff_agent,ff_opt0,ff_ifps,
							itsoffset_v,ff_stime,inp_ff,
							ff_opt1,itsoffset_a,ff_stime,inp2_ff,ff_transfmt)
				
				dbg("---- Output return params Pos 3-4 ----")
				print "web_cvparams= -vcodec mpeg2video -q:v 1 -acodec ac3 -ab %d -ar 48000" % g_audio_bps
				print "web_cvparams= "+ p_vf +" -aspect %s %s -loglevel %s -y" % (f_aspect,ff_async,gs_ff_loglev)
				print "web_cvparams= %s %s %s $output" % (f_fps,fp_map,ff_opt2)
				dbg("---- Output return params Pos 4 ----")
		else:	#use mencoder
			#----------------------------------------------------------------
			# Transcode by Mencoder 
			#----------------------------------------------------------------
			if(nicovideo):
				print "web_prog_ex=" +gs_python
				print "web_cvparams="+nicoplayer+" "+cvfile_in+" "+cvfile_out+" "+mencoder
			#print "web_cvparams= -cookies -cookies-file %s" % yt_cookie_file
			
			#print "web_cvparams= %s %s %s %s -prefer-ipv4 -cache 16384" % (mc_cookie,ff_stime,inp,mc_loglev)
			print "web_cvparams= %s %s %s %s -cache 256000" % (mc_cookie,ff_stime,inp,mc_loglev)
			
			print "web_cvparams= "+p_of+ " -oac lavc -ovc lavc"
			#print "web_cvparams= -mpegopts format="+p_fmt+":muxrate=500000:vbuf_size=1194:abuf_size=64"
			print "web_cvparams= -mpegopts format="+p_fmt+":vbuf_size=1194:abuf_size=64"
			#print "web_cvparams= -lavcopts "+ p_aspect +":vcodec=mpeg2video:acodec=ac3:abitrate=448000:vrc_maxrate=8000000:vbitrate=8000000:keyint=10:vqscale=1:vqmin=2"
			print "web_cvparams= -lavcopts "+ p_aspect +":vcodec=mpeg2video:acodec=ac3:abitrate=448000:keyint=10:vqscale=1:vqmin=2"
			print "web_cvparams= "+ p_vf  +" -mc 0.1 -af lavcresample=48000 -srate 48000"
			print "web_cvparams= "+ p_fps +" "+p_user+" -o $output"
			
	dbg("---- Output return params Pos 5 ----")

	#----------------------------------------------------------------------------------
	# Override cvfile_out for MencoderWeb (optional, for test)
	#----------------------------------------------------------------------------------
	# print "web_cvfile_out= ./dummy.mpg"

	#----------------------------------------------------------------------------------
	# Log messages for PMS logger.info (optional)
	#----------------------------------------------------------------------------------
	dbg("---- Output return params End ----")
	tm_end=time.time()
	if(gs_verbose):
		print "web_logmsg=media: size=%dx%d (aspect=%f) fps=%f, s_vc=%s, remux=%s" % (int(s_w),int(s_h),s_w/s_h,s_fps,s_vc,remux)
		#print "web_logmsg=convert  : remux=%s, of=%s fmt=%s, vf=%s" % (remux,p_of,p_fmt,p_vf)

	dbg("mediainfo: size=%dx%d (aspect=%f) fps=%f, s_vc=%s" % (int(s_w),int(s_h),s_w/s_h,s_fps,s_vc))
	dbg("convert  : remux=%s, of=%s fmt=%s, vf=%s" % (remux,p_of,p_fmt,p_vf))
	dbg("time geturl=%f, getinfo=%f, total=%f" % (tm_geturl-tm_start,tm_getinfo-tm_geturl,tm_end-tm_start))
	dbg("------ RzWebMediaInfo.py End -------------")
	
	#----------------------------------------------------------------------------------
	# Ending
	#----------------------------------------------------------------------------------
	print "web_exit=0"
	
	elogf.close()
	sys.exit(0)
	
	