Example #1
0
	def get_surface(self,element):
		
		""" Return data from a video, to be able to compute the optimal bitrate to fullfill the disk.
			SIZE is the size in kbytes
			SURFACE is the surface in square pixels
			LENGTH is the efective length in seconds
			AUDIORATE is the audio rate """
		
		length = float(element["olength"])
		speed1,speed2=devede_other.get_speedup(element)
		if (speed1!=speed2): # we are speeding up the film, so we must take it into account
			length*=((float(speed2))/(float(speed1)))

		if element["cutting"]!=0: # we want only half the file
			length/=2

		surface = float(element["width"]*element["height"])
		
		surface/=84480.0 # normalize surface respect to 352x240
		
		if (element["copy_audio"]):
			audiorate=element["oarate"]
		else:
			audiorate=element["arate"]

		if (element["ismpeg"]):
			size=element["filesize"]/1000
		else:
			size=(length*(element["vrate"]+audiorate))/8

		return size,surface,length,audiorate
Example #2
0
	def get_surface(self,element):
		
		""" Return data from a video, to be able to compute the optimal bitrate to fullfill the disk.
			SIZE is the size in kbytes
			SURFACE is the surface in square pixels
			LENGTH is the efective length in seconds
			AUDIORATE is the audio rate """
		
		length = float(element["olength"])
		speed1,speed2=devede_other.get_speedup(element)
		if (speed1!=speed2): # we are speeding up the film, so we must take it into account
			length*=((float(speed2))/(float(speed1)))

		if element["cutting"]!=0: # we want only half the file
			length/=2

		surface = float(element["width"]*element["height"])
		
		surface/=84480.0 # normalize surface respect to 352x240
		
		if (element["copy_audio"]):
			audiorate=element["oarate"]
		else:
			audiorate=element["arate"]

		if (element["ismpeg"]):
			size=element["filesize"]/1000
		else:
			size=(length*(element["vrate"]+audiorate))/8

		return size,surface,length,audiorate
Example #3
0
	def set_video_values(self):
	
		""" Sets the video values in the main window when the user clicks
		a chapter """
	
		title,chapter=self.get_marked()
		if (chapter!=-1) and (title!=-1) and (title<len(self.structure)) and (chapter<len(self.structure[title])):
			found2=self.structure[title]
			found=found2[chapter]
			
			w=self.tree.get_object("oaspect")
			if (found["aspect"])>1.5:
				w.set_text("16:9")
			else:
				w.set_text("4:3")
				
			w=self.tree.get_object("o_size")
			w.set_text(str(found["owidth"])+"x"+str(found["oheight"]))
			
			w=self.tree.get_object("leng")
			w.set_text(str(found["olength"]))
			
			w=self.tree.get_object("vrate")
			w.set_text(str(found["vrate"]))
			
			w=self.tree.get_object("arate")
			w.set_text(str(found["arate"]))
			
			w=self.tree.get_object("eleng")
			speed1,speed2=devede_other.get_speedup(found)
			length=devede_other.calcula_tamano_parcial(found["vrate"],found["arate"],found["filesize"],found["olength"],len(found["sub_list"]),found["ismpeg"],found["isvob"],found["cutting"],speed1,speed2)
			#length=int(((found["vrate"]+found["arate"])*found["olength"])/8000)
			w.set_text(str(int(length/1000)))
			
			w=self.tree.get_object("achap")
			if found["lchapters"]==0:
				w.set_text(_("no chapters"))
			else:
				w.set_text(str(int(found["lchapters"])))
			
			w=self.tree.get_object("video_format")
			if found["fps"]==25:
				w.set_text("25 (PAL)")
			elif found["fps"]==30:
				if (found["ofps"]==24) and (self.disctocreate!="vcd") and (self.disctocreate!="svcd") and (self.disctocreate!="cvd"):
					w.set_text("24 (NTSC)")
				else:
					w.set_text("30 (NTSC)")
			else:
				w.set_text(str(int(found["fps"])))
			
			w=self.tree.get_object("fsizem")
			w.set_text(str(found["width"])+"x"+str(found["height"]))

		else:

			w=self.tree.get_object("oaspect")
			w.set_text("")
			w=self.tree.get_object("o_size")
			w.set_text("")
			w=self.tree.get_object("leng")
			w.set_text("")
			w=self.tree.get_object("vrate")
			w.set_text("")
			w=self.tree.get_object("arate")
			w.set_text("")
			w=self.tree.get_object("eleng")
			w.set_text("")
			w=self.tree.get_object("achap")
			w.set_text("")
			w=self.tree.get_object("video_format")
			w.set_text("")
			w=self.tree.get_object("fsizem")
			w.set_text("")
			
		total=devede_other.calcula_tamano_total(self.structure,self.global_vars["menu_sound_duration"],self.disctocreate)
		total/=1000
		
		tamano,minvrate,maxvrate = devede_other.get_dvd_size(self.tree,self.disctocreate)
		
		w=self.tree.get_object("usage")
		if total>tamano:
			w.set_fraction(1.0)
			addv=1
		else:
			w.set_fraction(total/tamano)
			addv=0
		w.set_text(str(addv+int((total/tamano)*100))+"%")
Example #4
0
	def set_global_values(self):

		""" Repaints all the data about the current film, recalculating
			the size needed and other params """
		
		if self.file_properties==None:
			empty=True
		else:
			empty=False
	
		w=self.tree.get_object("o_size2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["owidth"])+"x"+str(self.file_properties["oheight"]))

		w=self.tree.get_object("leng2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["olength"]))
		
		w=self.tree.get_object("fps")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["ofps"]))

		w=self.tree.get_object("vrate2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["ovrate"]))

		w=self.tree.get_object("arate2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["oarate"]))
	
		w=self.tree.get_object("video_rate")
		vrate=w.get_value()
		w=self.tree.get_object("audio_rate")
		arate=w.get_value()
	
		w=self.tree.get_object("full_length")
		if w.get_active():
			divide=False
			divide2=0
		else:
			divide=True
			divide2=1
		
		w=self.tree.get_object("eleng2")
		if empty:
			w.set_text("")
		else:
			w2=self.tree.get_object("ismpeg")
			w4=self.tree.get_object("isvob")
			props={}
			props["ofps"]=self.file_properties["ofps"]
			props["ofps2"]=self.file_properties["ofps2"]
			w3=self.tree.get_object("video_pal")
			if w3.get_active():
				props["fps"]=25
			else:
				props["fps"]=30
			w3=self.tree.get_object("copy_audio")
			props["copy_audio"]=w3.get_active()
			w3=self.tree.get_object("ismpeg")
			props["ismpeg"]=w3.get_active()
			print "Props: "+str(props)
			speed1,speed2=devede_other.get_speedup(props)
			l=devede_other.calcula_tamano_parcial(vrate,arate,self.file_properties["filesize"],self.file_properties["olength"],len(self.file_properties["sub_list"]),w2.get_active(),w4.get_active(),divide2,speed1,speed2)
			#if w2.get_active():
			#	l=int(self.file_properties["filesize"]/1000000)
			#else:
			#	l=int(((vrate+arate)*self.file_properties["olength"])/8000)
			#	if divide:
			#		l/=2
			
			#l+=int((8.0*float(len(self.file_properties["sub_list"]))*self.file_properties["olength"])/8000.0)
			w.set_text(str(int(l/1000)))
		
		w=self.tree.get_object("f_size2")
		if empty:
			w.set_text("")
		else:
			w.set_text(str(self.file_properties["width"])+"x"+str(self.file_properties["height"]))		
Example #5
0
	def set_video_values(self):
	
		""" Sets the video values in the main window when the user clicks
		a chapter """
	
		title,chapter=self.get_marked()
		if (chapter!=-1) and (title!=-1) and (title<len(self.structure)) and (chapter<len(self.structure[title])):
			found2=self.structure[title]
			found=found2[chapter]
			
			w=self.tree.get_object("oaspect")
			if (found["aspect"])>1.5:
				w.set_text("16:9")
			else:
				w.set_text("4:3")
				
			w=self.tree.get_object("o_size")
			w.set_text(str(found["owidth"])+"x"+str(found["oheight"]))
			
			w=self.tree.get_object("leng")
			w.set_text(str(found["olength"]))
			
			w=self.tree.get_object("vrate")
			w.set_text(str(found["vrate"]))
			
			w=self.tree.get_object("arate")
			w.set_text(str(found["arate"]))
			
			w=self.tree.get_object("eleng")
			speed1,speed2=devede_other.get_speedup(found)
			length=devede_other.calcula_tamano_parcial(found["vrate"],found["arate"],found["filesize"],found["olength"],len(found["sub_list"]),found["ismpeg"],found["isvob"],found["cutting"],speed1,speed2)
			#length=int(((found["vrate"]+found["arate"])*found["olength"])/8000)
			w.set_text(str(int(length/1000)))
			
			w=self.tree.get_object("achap")
			if found["lchapters"]==0:
				w.set_text(_("no chapters"))
			else:
				w.set_text(str(int(found["lchapters"])))
			
			w=self.tree.get_object("video_format")
			if found["fps"]==25:
				w.set_text("25 (PAL)")
			elif found["fps"]==30:
				if (found["ofps"]==24) and (self.disctocreate!="vcd") and (self.disctocreate!="svcd") and (self.disctocreate!="cvd"):
					w.set_text("24 (NTSC)")
				else:
					w.set_text("30 (NTSC)")
			else:
				w.set_text(str(int(found["fps"])))
			
			w=self.tree.get_object("fsizem")
			w.set_text(str(found["width"])+"x"+str(found["height"]))

		else:

			w=self.tree.get_object("oaspect")
			w.set_text("")
			w=self.tree.get_object("o_size")
			w.set_text("")
			w=self.tree.get_object("leng")
			w.set_text("")
			w=self.tree.get_object("vrate")
			w.set_text("")
			w=self.tree.get_object("arate")
			w.set_text("")
			w=self.tree.get_object("eleng")
			w.set_text("")
			w=self.tree.get_object("achap")
			w.set_text("")
			w=self.tree.get_object("video_format")
			w.set_text("")
			w=self.tree.get_object("fsizem")
			w.set_text("")
			
		total=devede_other.calcula_tamano_total(self.structure,self.global_vars["menu_sound_duration"],self.disctocreate)
		total/=1000
		
		tamano,minvrate,maxvrate = devede_other.get_dvd_size(self.tree,self.disctocreate)
		
		w=self.tree.get_object("usage")
		if total>tamano:
			w.set_fraction(1.0)
			addv=1
		else:
			w.set_fraction(total/tamano)
			addv=0
		w.set_text(str(addv+int((total/tamano)*100))+"%")
Example #6
0
	def __init__(self,videofile,filename,filefolder,progresbar,proglabel,disctype,title,chapter,stream):

		""" This class adds the subtitles to an already converted file

		VIDEOFILE contains the parameters to convert the video
		FILENAME is the generic file name given by the user
		FILEFOLDER is the path where all the temporary and finall files will be created
		PROGRESBAR is the progress bar where the class will show the progress
		PROGLABEL is the label where the class will show what is it doing
		DISCTYPE can be dvd, vcd, svcd, cvd or divx
		TITLE and CHAPTER are the numbers used to identify the TITLE and CHAPTER number for this file
		STREAMS is the stream number (to allow to add several subtitles)
		"""

		devede_executor.executor.__init__(self,filename,filefolder,progresbar)
		progresbar.pulse()
		proglabel.set_text(_("Adding subtitles to")+"\n"+videofile["filename"])
		self.currentfile=self.create_filename(filefolder+filename,title,chapter,disctype=="divx")

		subtitle_list=videofile["sub_list"][stream]

		# generate the XML file

		self.error=""

		try:
			print "Trying to create "+filefolder+filename+"_sub.xml"
			fichero=open(filefolder+filename+"_sub.xml","w")
		except IOError:
			print "IOError en subtitulos"
			self.print_error=_("Failed to write to the destination directory.\nCheck that you have privileges and free space there.")
			self.initerror=True
			return
		
		fichero.write('<subpictures format="')
		if (videofile["fps"]==25) :
			fichero.write('PAL')
		else:
			fichero.write('NTSC')
		fichero.write('">\n\t<stream>')
		if (subtitle_list["sub_codepage"]!="UTF-8"):
			final_type="UTF-8"
			subfilename=os.path.join(filefolder,filename+"_sub_tmp.sub")
			self.deletesub=subfilename
			if 0!=devede_other.check_utf().convert_to_UTF8(subtitle_list["subtitles"],subfilename,subtitle_list["sub_codepage"]):
				#except IOError:
				print "IOError al convertir a UTF8"
				self.print_error=_("Failed to write to the destination directory.\nCheck that you have privileges and free space there.")
				self.initerror=True
				return
		else:
			self.deletesub=""
			final_type=subtitle_list["sub_codepage"]
			subfilename=subtitle_list["subtitles"]
		fichero.write('\n\t\t<textsub filename="'+self.expand_xml(subfilename)+'"')

		if (sys.platform=="win32") or (sys.platform=="win64"):
			if os.path.isfile(os.path.join(os.environ["WINDIR"],"Fonts","devedesans.ttf")):
				fichero.write('\n\t\tfont="devedesans.ttf"')
			else:
				fichero.write('\n\t\tfont="ARIAL.ttf"')
		else:
			fichero.write('\n\t\tfont="devedesans.ttf"')
		if ((subtitle_list["sub_codepage"]!="") and (subtitle_list["sub_codepage"]!="ASCII")):
			fichero.write('\n\t\tcharacterset="'+final_type+'"')
		fichero.write('\n\t\thorizontal-alignment="center"')

		if (videofile["fps"]==25):
			ancho=716
			alto=572
			tamanofont=videofile["subfont_size"]
		else:
			ancho=716
			alto=476
			tamanofont=videofile["subfont_size"]

		margin_hor=int((58*ancho)/720)
		margin_vert=int((28*alto)/576)
		bottom_margin=margin_vert

		fichero.write('\n\t\tmovie-width="'+str(ancho-4)+'"')
		fichero.write('\n\t\tmovie-height="'+str(alto-4)+'"')
		fichero.write('\n\t\tleft-margin="'+str(margin_hor)+'"')
		fichero.write('\n\t\tright-margin="'+str(margin_hor)+'"')

		if subtitle_list["subtitles_up"]:
			tamanofont-=1
			bottom_margin=4+(alto/8) # put it in the border of 16:9 aspect ratio

		fichero.write('\n\t\tbottom-margin="'+str(bottom_margin)+'"')
		fichero.write('\n\t\ttop-margin="'+str(margin_vert)+'"')

		fichero.write('\n\t\tfontsize="'+str(tamanofont)+'.0"')

		fill_color = 'rgba(%.0f%%, %.0f%%, %.0f%%, %.0f%%)' % tuple(
			float(item)/655.35 for item in videofile["sub_fill_color"]
		)
		fichero.write('\n\t\tfill-color="%s"' % fill_color)

		outline_color = 'rgba(%.0f%%, %.0f%%, %.0f%%, %.0f%%)' % tuple(
			float(item)/655.35 for item in videofile["sub_outline_color"]
		)
		fichero.write('\n\t\toutline-color="%s"' % outline_color)

		if (videofile["fps"]==30):
			if (videofile["ofps"]==24) and ((disctype=="dvd") or (disctype=="divx")):
				fps_out="24000/1001"
			else:
				fps_out="30000/1001"
		else:
			fps_out="25"

		if videofile["ismpeg"]:
			fps_out=videofile["ofps2"]
			print "FPS sub 1 original"
		else:
			print "FPS sub 1 final"

		fichero.write('\n\t\tmovie-fps="'+str(fps_out)+'"')
		speed1,speed2=devede_other.get_speedup(videofile)
		if speed1==speed2:
			fps_out_subs=fps_out
			print "FPS sub 2 final"
		else:
			if speed2==24:
				fps_out_subs="24"
			else:
				fps_out_subs=videofile["ofps2"]
			print "FPS sub 2 original"

		fichero.write('\n\t\tsubtitle-fps="'+fps_out_subs+'"')
		fichero.write('\n\t\tvertical-alignment="bottom" />')
		fichero.write("\n\t</stream>\n</subpictures>")
		fichero.close()
		
		comando=""
		if (sys.platform=="win32") or (sys.platform=="win64"):
			comando=["spumux.exe"]
			comando.append("-m")
			if disctype=="vcd":
				comando.append("svcd")
			else:
				comando.append(disctype)
			comando.append("-s")
			comando.append(str(stream))
			
			comando.append(filefolder+filename+"_sub.xml")
			comando.append("-i")
			comando.append(self.currentfile)
			comando.append("-o")
			comando.append(self.currentfile+".sub")
			self.print_error=_("Conversion failed.\nIt seems a bug of SPUMUX.")
			self.launch_program(comando,output=True)
		else:
			comando="spumux -m "
			if disctype=="vcd":
				comando+="svcd"
			else:
				comando+=disctype
		
			comando+=' -s '+str(stream)+' "'+filefolder+filename+'_sub.xml"'
		
			self.print_error=_("Conversion failed.\nIt seems a bug of SPUMUX.")
			self.launch_shell(comando,output=True,stdinout=[self.currentfile,self.currentfile+".sub"])
	def __init__(self,global_vars,videofile,filename,filefolder,progresbar,proglabel,disctype,title,chapter,threads,seconds,encpass,fix_ac3):

		""" This class converts a video file to MPEG-1 or MPEG-2 format

		VIDEOFILE contains the parameters to convert the video
		FILENAME is the generic file name given by the user
		FILEFOLDER is the path where all the temporary and finall files will be created
		PROGRESBAR is the progress bar where the class will show the progress
		PROGLABEL is the label where the class will show what is it doing
		DISCTYPE can be dvd, vcd, svcd, cvd or divx
		TITLE and CHAPTER are the numbers used to identify the TITLE and CHAPTER number for this file
		THREADS is the number of threads to use
		SECONDS is the number of seconds we want to convert (for previews) 
		ENCPASS is the number of encoding pass"""
		
		devede_executor.executor.__init__(self,filename,filefolder,progresbar)
		self.printout=False

		self.percent2=120
		self.film_length=float(videofile["olength"])
		if seconds==0:
			self.divide=float(videofile["olength"])
			if (videofile["cutting"]==1) or (videofile["cutting"]==2): # if we want only one half of the file
				self.divide/=2
		else:
			self.divide=float(seconds)

		if self.divide==0:
			self.divide=1

		self.error=""
		progresbar.set_fraction(0)
		progresbar.set_text("")
		
		if videofile["ismpeg"]: # if the file hasn't to be converted, we simply copy or link it
			self.pulse=True
			self.print_error=_("File copy failed\nMaybe you ran out of disk space?")
			if seconds==0:
				texto=_("Copying the file")+"\n"
			else:
				texto=_("Creating preview")+"\n"
			proglabel.set_text(texto+videofile["filename"])
			currentfile=self.create_filename(filefolder+filename,title,chapter,disctype=="divx")
		
			print "\ncurrentfile is: ", currentfile , "\n" 

			try:
				os.remove(currentfile)
			except:
				pass

			if (sys.platform=="win32") or (sys.platform=="win64"):
				# links do not work on windows, so just copy the file
				# self.launch_shell('copy "'+videofile["path"].replace('"','""')+'" "'+currentfile+'"',output=False)
				# Only hardlinks are available on 2000 and XP, reparse points are available from vista onwards.
				win32file.CreateHardLink(currentfile, videofile["path"].replace('"','""'))
			else:
				if len(videofile["sub_list"])==0:
					self.launch_shell('ln -s "'+videofile["path"].replace('"','\\"')+'" "'+currentfile+'"',output=False)
				else:
					self.launch_shell('cp "'+videofile["path"].replace('"','\\"')+'" "'+currentfile+'"',output=False)
			return

		isvob=videofile["isvob"]

		self.pulse=False
		if seconds==0:
			texto=(_("Converting files from title %(title_number)s (pass %(pass_number)s)\n\n%(file_name)s") % {"title_number":str(title),"pass_number":str(encpass),"file_name":videofile["filename"]} )
			proglabel.set_text(texto) #+" "+str(title)+" Pass: "******"\n\n"+videofile["filename"] )
		else:
			texto=_("Creating preview")
			proglabel.set_text(texto+"\n"+videofile["filename"])

		addbars=False
		framerate=int(videofile["ofps"])
		videorate=int(videofile["vrate"])
		audiorate=self.adjust_audiorate(int(videofile["arate"]),disctype=="dvd")
		
		audio_final_rate=int(videofile["arateunc"])
		audiodelay=float(videofile["adelay"])
		final_framerate=float(videofile["fps"])
		aspect_ratio_original=videofile["oaspect"]
		aspect_ratio_final=videofile["aspect"]
		resx_final=videofile["width"]
		resy_final=videofile["height"]
		resx_original=videofile["owidth"]
		resy_original=videofile["oheight"]
		copy_audio=videofile["copy_audio"]
		sound51=videofile["sound51"]
		gop12=videofile["gop12"]
		audiostream=videofile["audio_stream"]
		swap_fields=videofile["swap_fields"]
		volume=videofile["volume"]
		audio_tracks=len(videofile["audio_list"])

		if (videofile["resolution"]==0) and (disctype=="divx"):
			default_res=True
		else:
			default_res=False
		
		speed1,speed2=devede_other.get_speedup(videofile)
		if speed1==speed2:
			speedup=None
		else:
			speedup=str(speed1)+":"+str(speed2)
	
		if aspect_ratio_original<1.3:
			aspect_ratio_original=float(videofile["owidth"])/(float(videofile["oheight"]))
		if aspect_ratio_original<1.33333333:
			aspect_ratio_original=1.33333333
	
		max_videorate=int(videorate*2)
		min_videorate=int(videorate*0.75)
		
		dsize,minvid,maxvid=devede_other.get_dvd_size(None,disctype)
		
		if max_videorate>maxvid:
			max_videorate=maxvid
		if min_videorate<minvid:
			min_videorate=minvid
			
		if videofile["blackbars"]==0: # check if has to add black bars
			addbars=True
			if (videofile["rotate"]==90) or (videofile["rotate"]==270):
				resx_original2=resy_original
				resy_original2=resx_original
				aratio=1/aspect_ratio_original
			else:
				resx_original2=resx_original
				resy_original2=resy_original
				aratio=aspect_ratio_original

			if (resx_original2%2)==1:
				resx_original2+=1
			if (resy_original2%2)==1:
				resy_original2+=1
			
			resy_tmp = int(resy_final*aspect_ratio_final/aratio)
			resx_tmp = int(resx_final*aratio/aspect_ratio_final)
			
			
			if (resx_tmp>resx_final):
				resx_inter=resx_final
				resy_inter=resy_tmp
			else:
				resx_inter=resx_tmp
				resy_inter=resy_final
			
			#resx_inter=resx_original2
			#resy_inter=int((resy_original2*aspect_ratio_original)/aspect_ratio_final)
			if (resx_inter%2)==1:
				resx_inter-=1
			if (resy_inter%2)==1:
				resy_inter-=1
			
			#if ((resy_inter<resy_original) or (resy_original+5>resy_inter)):
			#	addbars=False

		if addbars==False:
			resx_inter=resx_final
			resy_inter=resy_final
		else:
			if (resx_inter==resx_final):
				addx=0
				addy=int((resy_final-resy_inter)/2)
				if(addy%2)==1:
					addy+=1
			else:
				addy=0
				addx=int((resx_final-resx_inter)/2)
				if(addx%2)==1:
					addx+=1
					
		
		command_var=["ffmpeg"]
		#command_var=["avconv"]

		command_var.append("-i")
		command_var.append(videofile["path"])
		
		if (volume!=100):
			command_var.append("-vol")
			command_var.append(str((256*volume)/100))
		
		if (audiodelay!=0.0) and (copy_audio==False) and (isvob==False):
			command_var.append("-itsoffset")
			command_var.append(str(audiodelay))
			command_var.append("-i")
			command_var.append(videofile["path"])
			command_var.append("-map")
			command_var.append("1:0")
			for l in range(audio_tracks):
				command_var.append("-map")
				command_var.append("0"+":"+str(l+1))
		
		if (isvob==False):
			cmd_line=""
			
			extra_params=videofile["params_vf"] # take the VF extra params
			while (extra_params!=""):
				extra_params,new_param=devede_other.get_new_param(extra_params)
				if (new_param!="") and (new_param!=','):
					while (len(new_param)>1) and (new_param[0]==','):
						new_param=new_param[1:]
					while (len(new_param)>1) and (new_param[-1]==','):
						new_param=new_param[:-1]
					if new_param=="fifo":
						continue
					if cmd_line!="":
						cmd_line+=",fifo,"
					cmd_line+=new_param
			
			if videofile["deinterlace"]=="yadif":
				if (cmd_line!=""):
					cmd_line+=",fifo,"
				cmd_line+="yadif"
			
			vflip=0
			hflip=0
	
			if (videofile["rotate"]==90):
				if (cmd_line!=""):
					cmd_line+=",fifo,"
				cmd_line+="transpose=1"
			elif (videofile["rotate"]==270):
				if (cmd_line!=""):
					cmd_line+=",fifo,"
				cmd_line+="transpose=2"
			elif (videofile["rotate"]==180):
				vflip=1
				hflip=1
			
			if (videofile["vmirror"]):
				vflip=1-vflip
			if (videofile["hmirror"]):
				hflip=1-hflip
	
			if (vflip==1):
				if (cmd_line!=""):
					cmd_line+=",fifo,"
				cmd_line+="vflip"
			if (hflip==1):
				if (cmd_line!=""):
					cmd_line+=",fifo,"
				cmd_line+="hflip"
			
			if addbars and ((resx_inter!=resx_original) or (resy_inter!=resy_original)) and (default_res==False):
				if (cmd_line!=""):
					cmd_line+=",fifo,"
				cmd_line+="scale="+str(resx_inter)+":"+str(resy_inter)+",fifo,pad="+str(resx_final)+":"+str(resy_final)+":"+str(addx)+":"+str(addy)+":0x000000"
			
			if cmd_line!="":
				command_var.append("-vf")
				command_var.append(cmd_line)
			
		
		command_var.append("-y")

		vcd=False
		
		if (disctype!="divx"):
			command_var.append("-target")
			if (disctype=="dvd"):
				if final_framerate==30:
					command_var.append("ntsc-dvd")
				elif (framerate==24):
					command_var.append("film-dvd")
				else:
					command_var.append("pal-dvd")
				if (copy_audio==False):
					command_var.append("-acodec")
					if fix_ac3:
						command_var.append("ac3_fixed")
					else:
						command_var.append("ac3")
				#command_var.append("-maxrate")
				#command_var.append("7000k")
				#command_var.append("-minrate")
				#command_var.append("2200k")
			elif (disctype=="vcd"):
				vcd=True
				if final_framerate==30:
					command_var.append("ntsc-vcd")
				else:
					command_var.append("pal-vcd")
			elif (disctype=="svcd"):
				if final_framerate==30:
					command_var.append("ntsc-svcd")
				else:
					command_var.append("pal-svcd")
			elif (disctype=="cvd"):
				if final_framerate==30:
					command_var.append("ntsc-svcd")
				else:
					command_var.append("pal-svcd")
		else: # DivX
			command_var.append("-vcodec")
			command_var.append("mpeg4")
			command_var.append("-acodec")
			command_var.append("libmp3lame")
			command_var.append("-f")
			command_var.append("avi")
		
		if  (not isvob):
			command_var.append("-sn") # no subtitles

		if copy_audio or isvob:
			command_var.append("-acodec")
			command_var.append("copy")
		#else:
		#	if (disctype=="divx"):
		#		command_var.append("-acodec")
		#		command_var.append("mp3")

		#if (audiostream!=10000):
		#	command_var.append("-aid")
		#	command_var.append(str(audiostream))

		if isvob:
			command_var.append("-vcodec")
			command_var.append("copy")
		
		if (vcd==False):
			if final_framerate==30:
				if (framerate==24) and ((disctype=="dvd") or (disctype=="divx")):
					str_final_framerate="24000/1001"
					keyintv=15
					telecine=True
				else:
					str_final_framerate="30000/1001"
					keyintv=18
			else:
				str_final_framerate=str(int(final_framerate))
				keyintv=15
		
		if (disctype=="divx"):
			command_var.append("-g")
			command_var.append("300")
		elif gop12 and (isvob==False):
			command_var.append("-g")
			command_var.append("12")
		
		command_var.append("-bf")
		command_var.append("2")
		command_var.append("-strict")
		command_var.append("1")
		
		if seconds!=0:
			command_var.append("-t")
			command_var.append(str(seconds))
		else:
			if videofile["cutting"]==1: # first half only
				command_var.append("-t")
				command_var.append(str(videofile["olength"]/2))
			elif videofile["cutting"]==2: # second half only
				command_var.append("-ss")
				command_var.append(str((videofile["olength"]/2)-5)) # start 5 seconds before

		#if (audiodelay!=0.0) and (copy_audio==False) and (isvob==False):
		#	command_var.append("-delay")
		#	command_var.append(str(audiodelay))

		command_var.append("-ac")
		if (sound51) and ((disctype=="dvd") or (disctype=="divx")):
			command_var.append("6")
		else:
			command_var.append("2")

		#if (isvob==False) and (default_res==False):
		#	command_var.append("-ofps")
		#	command_var.append(str_final_framerate)

		if disctype=="divx":
			command_var.append("-vtag")
			command_var.append("DX50")

		lineatemp=""
		acoma=False;
		
		#if swap_fields:
		#	lineatemp+="phase=a"
		#	acoma=True
		
		passlog_var = None
		
		if (videofile["deinterlace"]!="none") and (videofile["deinterlace"]!="yadif") and (isvob==False):
			command_var.append("-deinterlace")
			
		print "Addbars "+str(addbars)+" resx_o "+str(resx_original)+" resy_o "+str(resy_original)
		print "resx_i "+str(resx_inter)+" resy_i "+str(resy_inter)
 
 		if (isvob==False) and (vcd==False):
				command_var.append("-s")
				command_var.append(str(resx_final)+"x"+str(resy_final))

		# Currently Mencoder supports up to 8 threads
		if isvob==False:
			threads
			
			if threads>1:
				command_var.append("-threads")
				command_var.append(str(threads))

			command_var.append("-trellis")
			if videofile["trellis"]:
				command_var.append("1")
			else:
				command_var.append("0")
		
			if videofile["mbd"]==0:
				command_var.append("-mbd")
				command_var.append("0")
			elif videofile["mbd"]==1:
				command_var.append("-mbd")
				command_var.append("1")
			elif videofile["mbd"]==2:
				command_var.append("-mbd")
				command_var.append("2")
	
			if (vcd==False):
				command_var.append("-b")
				command_var.append(str(videorate)+"000")
		
			#if disctype!="divx":
			#	lavcopts+=":keyint="+str(keyintv)
			if(copy_audio==False) and (vcd==False):
#					lavcopts+=":acodec="
#					if disctype=="dvd":
#						if fix_ac3:
#							lavcopts+="ac3_fixed"
#						else:
#							lavcopts+="ac3"
#					else:
#						lavcopts+="mp2"
					#lavcopts+=":abitrate="+str(audiorate)
				command_var.append("-ab")
				command_var.append(str(audiorate)+"000")

			if (default_res==False):
				command_var.append("-aspect")
				if aspect_ratio_final>1.4:
					command_var.append("16:9")
				else:
					command_var.append("4:3")
			
			passlog_var=None
			if (encpass>0)  and (isvob==False):
				command_var.append("-pass")
				command_var.append(str(encpass))
				passlog_var=os.path.join(filefolder,filename)+".log"
				if encpass==1:
					try:
						os.remove(passlog_var)
					except:
						 pass
					#if videofile["turbo1stpass"]:
					#	lavcopts+=":turbo"

#	
#		if (disctype=="divx") and (copy_audio==False) and (isvob==False):
#			lameopts="abr:br="+str(audiorate)
#			command_var.append("-lameopts")
#			extra_params=videofile["params_lame"] # take the LAME extra params
#			while (extra_params!=""):
#				extra_params,new_param=devede_other.get_new_param(extra_params)
#				if (new_param!="") and (new_param!=':'):
#					while (len(new_param)>1) and (new_param[0]==':'):
#						new_param=new_param[1:]
#					while (len(new_param)>1) and (new_param[-1]==':'):
#						new_param=new_param[:-1]
#					lameopts+=":"+new_param
#			command_var.append(lameopts)
	
		currentfile=self.create_filename(filefolder+filename,title,chapter,disctype=="divx")

		if (passlog_var != None) and (isvob==False):
			command_var.append("-passlogfile")
			command_var.append(passlog_var)

		if (encpass==1) and (isvob==False):
			command_var.append("-y")
			command_var.append("/dev/null")
		else:
			command_var.append(currentfile)
		
		at=audio_tracks
		while (at>1):
			if (volume!=100):
				command_var.append("-vol")
				command_var.append(str((256*volume)/100))
			command_var.append("-newaudio")
			at-=1
			

		extra_params=videofile["params"] # take the extra params
		while (extra_params!=""):
			extra_params,new_param=devede_other.get_new_param(extra_params)
			if new_param!="":
				command_var.append(new_param)

		self.print_error=_("Conversion failed.\nIt seems a bug of Mencoder.")
		if (videofile["params"]!="") or (videofile["params_vf"]!="") or (videofile["params_lame"]!=""):
			self.print_error+="\n"+_("Also check the extra params passed to Mencoder for syntax errors.")
		self.error_not_done=True
		self.launch_program(command_var,read_chars=300)
Example #8
0
	def __init__(self,global_vars,videofile,filename,filefolder,progresbar,proglabel,disctype,title,chapter,threads,seconds,encpass):

		""" This class converts a video file to MPEG-1 or MPEG-2 format

		VIDEOFILE contains the parameters to convert the video
		FILENAME is the generic file name given by the user
		FILEFOLDER is the path where all the temporary and finall files will be created
		PROGRESBAR is the progress bar where the class will show the progress
		PROGLABEL is the label where the class will show what is it doing
		DISCTYPE can be dvd, vcd, svcd, cvd or divx
		TITLE and CHAPTER are the numbers used to identify the TITLE and CHAPTER number for this file
		THREADS is the number of threads to use
		SECONDS is the number of seconds we want to convert (for previews) 
		ENCPASS is the number of encoding pass"""
		
		devede_executor.executor.__init__(self,filename,filefolder,progresbar)
		self.printout=False

		self.percent2=120
		if seconds==0:
			self.divide=float(videofile["olength"])
			if (videofile["cutting"]==1) or (videofile["cutting"]==2): # if we want only one half of the file
				self.divide/=2
		else:
			self.divide=float(seconds)

		if self.divide==0:
			self.divide=1

		self.error=""
		progresbar.set_fraction(0)
		progresbar.set_text("")
		
		if videofile["ismpeg"]: # if the file hasn't to be converted, we simply copy or link it
			self.pulse=True
			self.print_error=_("File copy failed\nMaybe you ran out of disk space?")
			if seconds==0:
				texto=_("Copying the file")+"\n"
			else:
				texto=_("Creating preview")+"\n"
			proglabel.set_text(texto+videofile["filename"])
			currentfile=self.create_filename(filefolder+filename,title,chapter,disctype=="divx")
		
			print "\ncurrentfile is: ", currentfile , "\n" 

			try:
				os.remove(currentfile)
			except:
				pass

			if (sys.platform=="win32") or (sys.platform=="win64"):
				# links do not work on windows, so just copy the file
				# self.launch_shell('copy "'+videofile["path"].replace('"','""')+'" "'+currentfile+'"',output=False)
				# Only hardlinks are available on 2000 and XP, reparse points are available from vista onwards.
				win32file.CreateHardLink(currentfile, videofile["path"].replace('"','""'))
			else:
				if len(videofile["sub_list"])==0:
					self.launch_shell('ln -s "'+videofile["path"].replace('"','\\"')+'" "'+currentfile+'"',output=False)
				else:
					self.launch_shell('cp "'+videofile["path"].replace('"','\\"')+'" "'+currentfile+'"',output=False)
			return

		isvob=videofile["isvob"]

		self.pulse=False
		if seconds==0:
			texto=(_("Converting files from title %(title_number)s (pass %(pass_number)s)\n\n%(file_name)s") % {"title_number":str(title),"pass_number":str(encpass),"file_name":videofile["filename"]} )
			proglabel.set_text(texto) #+" "+str(title)+" Pass: "******"\n\n"+videofile["filename"] )
		else:
			texto=_("Creating preview")
			proglabel.set_text(texto+"\n"+videofile["filename"])

		addbars=False
		framerate=int(videofile["ofps"])
		videorate=int(videofile["vrate"])
		audiorate=self.adjust_audiorate(int(videofile["arate"]),disctype=="dvd")
		
		audio_final_rate=int(videofile["arateunc"])
		audiodelay=float(videofile["adelay"])
		final_framerate=float(videofile["fps"])
		aspect_ratio_original=videofile["oaspect"]
		aspect_ratio_final=videofile["aspect"]
		resx_final=videofile["width"]
		resy_final=videofile["height"]
		resx_original=videofile["owidth"]
		resy_original=videofile["oheight"]
		copy_audio=videofile["copy_audio"]
		sound51=videofile["sound51"]
		gop12=videofile["gop12"]
		audiostream=videofile["audio_stream"]
		swap_fields=videofile["swap_fields"]
		volume=videofile["volume"]
		if (videofile["resolution"]==0) and (disctype=="divx"):
			default_res=True
		else:
			default_res=False
		
		speed1,speed2=devede_other.get_speedup(videofile)
		if speed1==speed2:
			speedup=None
		else:
			speedup=str(speed1)+":"+str(speed2)
	
		if aspect_ratio_original<1.3:
			aspect_ratio_original=float(videofile["owidth"])/(float(videofile["oheight"]))
		if aspect_ratio_original<1.33333333:
			aspect_ratio_original=1.33333333
	
		max_videorate=int(videorate*2)
		min_videorate=int(videorate*0.75)
		
		dsize,minvid,maxvid=devede_other.get_dvd_size(None,disctype)
		
		if max_videorate>maxvid:
			max_videorate=maxvid
		if min_videorate<minvid:
			min_videorate=minvid
			
		if videofile["blackbars"]==0: # check if has to add black bars
			addbars=True
			if (videofile["rotate"]==90) or (videofile["rotate"]==270):
				resx_original2=resy_original
				resy_original2=resx_original
			else:
				resx_original2=resx_original
				resy_original2=resy_original

			if (resx_original2%2)==1:
				resx_original2+=1
			if (resy_original2%2)==1:
				resy_original2+=1
			resx_inter=resx_original2
			resy_inter=int((resy_original2*aspect_ratio_original)/aspect_ratio_final)
			if (resy_inter%2)==1:
				resy_inter+=1
			
			# due to a bug in MENCODER, we put bars only up and down, never left and right,
			# and we don't scale it if we have to add only 4 or less lines, because it is
			# too much work for so little profit
			
			if ((resy_inter<resy_original) or (resy_original+5>resy_inter)):
				addbars=False

		if addbars==False:
			resx_inter=resx_original
			resy_inter=resy_original
		else:
			addx=0
			addy=int((resy_inter-resy_original)/2)
			if(addy%2)==1:
				addy+=1

		command_var=[]
		if (sys.platform!="win32") and (sys.platform!="win64"):
			command_var=["mencoder"]
		else:
			command_var=["mencoder.exe"]

		if (disctype=="dvd") or (disctype=="divx"):
			audio_desired_final_rate=48000
		else:
			audio_desired_final_rate=44100

		afvalues=""

		if isvob==False:
			if ((audio_final_rate!=audio_desired_final_rate) and (copy_audio==False)) or (speedup!=None):
				command_var.append("-srate")
				command_var.append(str(audio_desired_final_rate))
				afvalues+="lavcresample="+str(audio_desired_final_rate)
			
			if (copy_audio==False) and volume!=100:
				if afvalues!="":
					afvalues+=":"
				afvalues+="volume="+str(10*math.log(volume/10,10))

			# Add the speedup code

			if speedup!=None:
				command_var.append("-speed")
				command_var.append(speedup)

		if afvalues!="":
			command_var.append("-af")
			command_var.append(afvalues)
			
		command_var.append("-noautosub")

		command_var.append("-oac")
		if copy_audio or isvob:
			command_var.append("copy")
		else:
			if (disctype=="divx"):
				command_var.append("mp3lame")
			else:
				command_var.append("lavc")

		if (audiostream!=10000):
			command_var.append("-aid")
			command_var.append(str(audiostream))


		
		telecine=False
		if final_framerate==30:
			if (framerate==24) and ((disctype=="dvd") or (disctype=="divx")):
				str_final_framerate="24000/1001"
				keyintv=15
				telecine=True
			else:
				str_final_framerate="30000/1001"
				keyintv=18
		else:
			str_final_framerate=str(int(final_framerate))
			keyintv=15
		
		if gop12:
			keyintv=12
		
		command_var.append("-ovc")
		if isvob:
			command_var.append("copy")
		else:
			command_var.append("lavc")
		
		if (disctype!="divx"):
			command_var.append("-of")
			command_var.append("mpeg")
			command_var.append("-mpegopts")
			if disctype=="dvd":
				if telecine and isvob==False:
					command_var.append("format=dvd:tsaf:telecine")
				else:
					command_var.append("format=dvd:tsaf")
			elif disctype=="vcd":
				command_var.append("format=xvcd")
			elif (disctype=="svcd") or (disctype=="cvd"):
				command_var.append("format=xsvcd")
			else:
				print "Error, disc format incorrect. Talk with the creator."
				sys.exit(1)

		if seconds!=0:
			command_var.append("-endpos")
			command_var.append(str(seconds))
		else:
			if videofile["cutting"]==1: # first half only
				command_var.append("-endpos")
				command_var.append(str(videofile["olength"]/2))
			elif videofile["cutting"]==2: # second half only
				command_var.append("-ss")
				command_var.append(str((videofile["olength"]/2)-5)) # start 5 seconds before

		if (audiodelay!=0.0) and (copy_audio==False) and (isvob==False):
			command_var.append("-delay")
			command_var.append(str(audiodelay))

		if sound51:
			command_var.append("-channels")
			command_var.append("6")

		if (isvob==False) and (default_res==False):
			command_var.append("-ofps")
			command_var.append(str_final_framerate)

		if disctype=="divx":
			command_var.append("-ffourcc")
			command_var.append("DX50")

		lineatemp=""
		acoma=False;
		
		if swap_fields:
			lineatemp+="phase=a"
			acoma=True
		
		extra_params=videofile["params_vf"] # take the VF extra params
		while (extra_params!=""):
			extra_params,new_param=devede_other.get_new_param(extra_params)
			if (new_param!="") and (new_param!=','):
				while (len(new_param)>1) and (new_param[0]==','):
					new_param=new_param[1:]
				while (len(new_param)>1) and (new_param[-1]==','):
					new_param=new_param[:-1]
				if acoma:
					lineatemp+=","
				lineatemp+=new_param
				acoma=True
		
		vmirror=0
		hmirror=0
		passlog_var = None
		
		if videofile["deinterlace"]!="none":
			if acoma:
				lineatemp+=","
			if videofile["deinterlace"]!="yadif":
				lineatemp+="pp="+videofile["deinterlace"]
			else:
				lineatemp+="yadif=0"
			acoma=True
			
		if videofile["rotate"]==180:
			vmirror=1-vmirror
			hmirror=1-hmirror
		
		if videofile["vmirror"]:
			vmirror=1-vmirror
		
		if videofile["hmirror"]:
			hmirror=1-hmirror
		
		if vmirror==1:
			if acoma:
				lineatemp+=","
			lineatemp+="flip"
			acoma=True
		
		if hmirror==1:
			if acoma:
				lineatemp+=","
			lineatemp+="mirror"
			acoma=True
		
		print "Addbars "+str(addbars)+" resx_o "+str(resx_original)+" resy_o "+str(resy_original)
		print "resx_i "+str(resx_inter)+" resy_i "+str(resy_inter)
		if addbars and ((resx_inter!=resx_original) or (resy_inter!=resy_original)) and (default_res==False):
			if acoma:
				lineatemp+=","
			lineatemp+="expand="+str(resx_inter)+":"+str(resy_inter)+":"+str(addx)+":"+str(addy)
			acoma=True

		if videofile["rotate"]==90:
			if acoma:
				lineatemp+=","
			lineatemp+="rotate=1"
			acoma=True
		
		if videofile["rotate"]==270:
			if acoma:
				lineatemp+=","
			lineatemp+="rotate=2"
			acoma=True

		if ((resx_inter!=resx_final) or (resy_inter!=resy_final)) and (default_res==False):
			if acoma:
				lineatemp+=","
			lineatemp+="scale="+str(resx_final)+":"+str(resy_final)
			acoma=True
		
		if disctype!="divx":
			if acoma:
				lineatemp+=","
			lineatemp+="harddup"
			acoma=True

		if (lineatemp!="") and (isvob==False):
			command_var.append("-vf")		
			command_var.append(lineatemp)

		if isvob==False:
			command_var.append("-lavcopts")
			
			lavcopts=""
			
			# Currently Mencoder supports up to 8 threads
			if threads>8:
				nthreads=8
			else:
				nthreads=threads
			
			if nthreads>1:
				lavcopts="threads="+str(nthreads)+":"
			lavcopts+="vcodec="
			if disctype=="vcd":
				lavcopts+="mpeg1video"
			elif disctype=="divx":
				lavcopts+="mpeg4"
			else:
				lavcopts+="mpeg2video"
		
			if videofile["trellis"]:
				lavcopts+=":trell"
		
			if videofile["mbd"]==0:
				lavcopts+=":mbd=0"	
			elif videofile["mbd"]==1:
				lavcopts+=":mbd=1"
			elif videofile["mbd"]==2:
				lavcopts+=":mbd=2"
	
			lavcopts+=":sc_threshold=1000000000:cgop"

			if disctype!="divx":
				lavcopts+=":vstrict=0:vrc_maxrate="+str(max_videorate)
				lavcopts+=":vrc_buf_size="
				if (disctype=="vcd"):
					lavcopts+="327"
				elif (disctype=="svcd") or (disctype=="cvd"):
					lavcopts+="917"
				elif (disctype=="dvd"):
					lavcopts+="1835"
			if disctype=="vcd":
				lavcopts+=":vrc_minrate="+str(min_videorate)
	
			lavcopts+=":vbitrate="+str(videorate)
		
			if disctype!="divx":
				lavcopts+=":keyint="+str(keyintv)
				if(copy_audio==False):
					lavcopts+=":acodec="
					if disctype=="dvd":
						lavcopts+="ac3"
					else:
						lavcopts+="mp2"
					lavcopts+=":abitrate="+str(audiorate)

			if (default_res==False):
				if aspect_ratio_final>1.4:
					lavcopts+=":aspect=16/9"
				else:
					lavcopts+=":aspect=4/3"
			
			if encpass > 0:
				lavcopts+=":vpass="******".log"
				if encpass==1:
					try:
						os.remove(passlog_var)
					except:
						 pass
					if videofile["turbo1stpass"]:
						lavcopts+=":turbo"
				
	
			extra_params=videofile["params_lavc"] # take the LAVC extra params
			while (extra_params!=""):
				extra_params,new_param=devede_other.get_new_param(extra_params)
				if (new_param!="") and (new_param!=':'):
					while (len(new_param)>1) and (new_param[0]==':'):
						new_param=new_param[1:]
					while (len(new_param)>1) and (new_param[-1]==':'):
						new_param=new_param[:-1]
					lavcopts+=":"+new_param
			command_var.append(lavcopts)
	
		if (disctype=="divx") and (copy_audio==False) and (isvob==False):
			lameopts="abr:br="+str(audiorate)
			command_var.append("-lameopts")
			extra_params=videofile["params_lame"] # take the LAME extra params
			while (extra_params!=""):
				extra_params,new_param=devede_other.get_new_param(extra_params)
				if (new_param!="") and (new_param!=':'):
					while (len(new_param)>1) and (new_param[0]==':'):
						new_param=new_param[1:]
					while (len(new_param)>1) and (new_param[-1]==':'):
						new_param=new_param[:-1]
					lameopts+=":"+new_param
			command_var.append(lameopts)
	
		currentfile=self.create_filename(filefolder+filename,title,chapter,disctype=="divx")

		if (passlog_var != None):
			command_var.append("-passlogfile")
			command_var.append(passlog_var)

		command_var.append("-o")
		command_var.append(currentfile)
		command_var.append(videofile["path"])

		extra_params=videofile["params"] # take the extra params
		while (extra_params!=""):
			extra_params,new_param=devede_other.get_new_param(extra_params)
			if new_param!="":
				command_var.append(new_param)

		self.print_error=_("Conversion failed.\nIt seems a bug of Mencoder.")
		if (videofile["params"]!="") or (videofile["params_vf"]!="") or (videofile["params_lavc"]!="") or (videofile["params_lame"]!=""):
			self.print_error+="\n"+_("Also check the extra params passed to Mencoder for syntax errors.")
		self.error_not_done=True
		self.launch_program(command_var,read_chars=300)
    def __init__(self, global_vars, videofile, filename, filefolder,
                 progresbar, proglabel, disctype, title, chapter, threads,
                 seconds, encpass, fix_ac3):
        """ This class converts a video file to MPEG-1 or MPEG-2 format

		VIDEOFILE contains the parameters to convert the video
		FILENAME is the generic file name given by the user
		FILEFOLDER is the path where all the temporary and finall files will be created
		PROGRESBAR is the progress bar where the class will show the progress
		PROGLABEL is the label where the class will show what is it doing
		DISCTYPE can be dvd, vcd, svcd, cvd or divx
		TITLE and CHAPTER are the numbers used to identify the TITLE and CHAPTER number for this file
		THREADS is the number of threads to use
		SECONDS is the number of seconds we want to convert (for previews) 
		ENCPASS is the number of encoding pass"""

        devede_executor.executor.__init__(self, filename, filefolder,
                                          progresbar)
        self.printout = False

        self.percent2 = 120
        self.film_length = float(videofile["olength"])
        if seconds == 0:
            self.divide = float(videofile["olength"])
            if (videofile["cutting"]
                    == 1) or (videofile["cutting"]
                              == 2):  # if we want only one half of the file
                self.divide /= 2
        else:
            self.divide = float(seconds)

        if self.divide == 0:
            self.divide = 1

        self.error = ""
        progresbar.set_fraction(0)
        progresbar.set_text("")

        if videofile[
                "ismpeg"]:  # if the file hasn't to be converted, we simply copy or link it
            self.pulse = True
            self.print_error = _(
                "File copy failed\nMaybe you ran out of disk space?")
            if seconds == 0:
                texto = _("Copying the file") + "\n"
            else:
                texto = _("Creating preview") + "\n"
            proglabel.set_text(texto + videofile["filename"])
            currentfile = self.create_filename(filefolder + filename, title,
                                               chapter, disctype == "divx")

            print "\ncurrentfile is: ", currentfile, "\n"

            try:
                os.remove(currentfile)
            except:
                pass

            if (sys.platform == "win32") or (sys.platform == "win64"):
                # links do not work on windows, so just copy the file
                # self.launch_shell('copy "'+videofile["path"].replace('"','""')+'" "'+currentfile+'"',output=False)
                # Only hardlinks are available on 2000 and XP, reparse points are available from vista onwards.
                win32file.CreateHardLink(currentfile,
                                         videofile["path"].replace('"', '""'))
            else:
                if len(videofile["sub_list"]) == 0:
                    self.launch_shell('ln -s "' +
                                      videofile["path"].replace('"', '\\"') +
                                      '" "' + currentfile + '"',
                                      output=False)
                else:
                    self.launch_shell('cp "' +
                                      videofile["path"].replace('"', '\\"') +
                                      '" "' + currentfile + '"',
                                      output=False)
            return

        isvob = videofile["isvob"]

        self.pulse = False
        if seconds == 0:
            texto = (_(
                "Converting files from title %(title_number)s (pass %(pass_number)s)\n\n%(file_name)s"
            ) % {
                "title_number": str(title),
                "pass_number": str(encpass),
                "file_name": videofile["filename"]
            })
            proglabel.set_text(
                texto
            )  #+" "+str(title)+" Pass: "******"\n\n"+videofile["filename"] )
        else:
            texto = _("Creating preview")
            proglabel.set_text(texto + "\n" + videofile["filename"])

        addbars = False
        framerate = int(videofile["ofps"])
        videorate = int(videofile["vrate"])
        audiorate = self.adjust_audiorate(int(videofile["arate"]),
                                          disctype == "dvd")

        audio_final_rate = int(videofile["arateunc"])
        audiodelay = float(videofile["adelay"])
        final_framerate = float(videofile["fps"])
        aspect_ratio_original = videofile["oaspect"]
        aspect_ratio_final = videofile["aspect"]
        resx_final = videofile["width"]
        resy_final = videofile["height"]
        resx_original = videofile["owidth"]
        resy_original = videofile["oheight"]
        copy_audio = videofile["copy_audio"]
        sound51 = videofile["sound51"]
        gop12 = videofile["gop12"]
        audiostream = videofile["audio_stream"]
        swap_fields = videofile["swap_fields"]
        volume = videofile["volume"]
        audio_tracks = len(videofile["audio_list"])

        if (videofile["resolution"] == 0) and (disctype == "divx"):
            default_res = True
        else:
            default_res = False

        speed1, speed2 = devede_other.get_speedup(videofile)
        if speed1 == speed2:
            speedup = None
        else:
            speedup = str(speed1) + ":" + str(speed2)

        if aspect_ratio_original < 1.3:
            aspect_ratio_original = float(videofile["owidth"]) / (float(
                videofile["oheight"]))
        if aspect_ratio_original < 1.33333333:
            aspect_ratio_original = 1.33333333

        max_videorate = int(videorate * 2)
        min_videorate = int(videorate * 0.75)

        dsize, minvid, maxvid = devede_other.get_dvd_size(None, disctype)

        if max_videorate > maxvid:
            max_videorate = maxvid
        if min_videorate < minvid:
            min_videorate = minvid

        if videofile["blackbars"] == 0:  # check if has to add black bars
            addbars = True
            if (videofile["rotate"] == 90) or (videofile["rotate"] == 270):
                resx_original2 = resy_original
                resy_original2 = resx_original
                aratio = 1 / aspect_ratio_original
            else:
                resx_original2 = resx_original
                resy_original2 = resy_original
                aratio = aspect_ratio_original

            if (resx_original2 % 2) == 1:
                resx_original2 += 1
            if (resy_original2 % 2) == 1:
                resy_original2 += 1

            resy_tmp = int(resy_final * aspect_ratio_final / aratio)
            resx_tmp = int(resx_final * aratio / aspect_ratio_final)

            if (resx_tmp > resx_final):
                resx_inter = resx_final
                resy_inter = resy_tmp
            else:
                resx_inter = resx_tmp
                resy_inter = resy_final

            #resx_inter=resx_original2
            #resy_inter=int((resy_original2*aspect_ratio_original)/aspect_ratio_final)
            if (resx_inter % 2) == 1:
                resx_inter -= 1
            if (resy_inter % 2) == 1:
                resy_inter -= 1

            #if ((resy_inter<resy_original) or (resy_original+5>resy_inter)):
            #	addbars=False

        if addbars == False:
            resx_inter = resx_final
            resy_inter = resy_final
        else:
            if (resx_inter == resx_final):
                addx = 0
                addy = int((resy_final - resy_inter) / 2)
                if (addy % 2) == 1:
                    addy += 1
            else:
                addy = 0
                addx = int((resx_final - resx_inter) / 2)
                if (addx % 2) == 1:
                    addx += 1

        command_var = ["ffmpeg"]
        #command_var=["avconv"]

        command_var.append("-i")
        command_var.append(videofile["path"])

        if (volume != 100):
            command_var.append("-vol")
            command_var.append(str((256 * volume) / 100))

        if (audiodelay != 0.0) and (copy_audio == False) and (isvob == False):
            command_var.append("-itsoffset")
            command_var.append(str(audiodelay))
            command_var.append("-i")
            command_var.append(videofile["path"])
            command_var.append("-map")
            command_var.append("1:0")
            for l in range(audio_tracks):
                command_var.append("-map")
                command_var.append("0" + ":" + str(l + 1))

        if (isvob == False):
            cmd_line = ""

            extra_params = videofile["params_vf"]  # take the VF extra params
            while (extra_params != ""):
                extra_params, new_param = devede_other.get_new_param(
                    extra_params)
                if (new_param != "") and (new_param != ','):
                    while (len(new_param) > 1) and (new_param[0] == ','):
                        new_param = new_param[1:]
                    while (len(new_param) > 1) and (new_param[-1] == ','):
                        new_param = new_param[:-1]
                    if new_param == "fifo":
                        continue
                    if cmd_line != "":
                        cmd_line += ",fifo,"
                    cmd_line += new_param

            if videofile["deinterlace"] == "yadif":
                if (cmd_line != ""):
                    cmd_line += ",fifo,"
                cmd_line += "yadif"

            vflip = 0
            hflip = 0

            if (videofile["rotate"] == 90):
                if (cmd_line != ""):
                    cmd_line += ",fifo,"
                cmd_line += "transpose=1"
            elif (videofile["rotate"] == 270):
                if (cmd_line != ""):
                    cmd_line += ",fifo,"
                cmd_line += "transpose=2"
            elif (videofile["rotate"] == 180):
                vflip = 1
                hflip = 1

            if (videofile["vmirror"]):
                vflip = 1 - vflip
            if (videofile["hmirror"]):
                hflip = 1 - hflip

            if (vflip == 1):
                if (cmd_line != ""):
                    cmd_line += ",fifo,"
                cmd_line += "vflip"
            if (hflip == 1):
                if (cmd_line != ""):
                    cmd_line += ",fifo,"
                cmd_line += "hflip"

            if addbars and ((resx_inter != resx_original) or
                            (resy_inter != resy_original)) and (default_res
                                                                == False):
                if (cmd_line != ""):
                    cmd_line += ",fifo,"
                cmd_line += "scale=" + str(resx_inter) + ":" + str(
                    resy_inter) + ",fifo,pad=" + str(resx_final) + ":" + str(
                        resy_final) + ":" + str(addx) + ":" + str(
                            addy) + ":0x000000"

            if cmd_line != "":
                command_var.append("-vf")
                command_var.append(cmd_line)

        command_var.append("-y")

        vcd = False

        if (disctype != "divx"):
            command_var.append("-target")
            if (disctype == "dvd"):
                if final_framerate == 30:
                    command_var.append("ntsc-dvd")
                elif (framerate == 24):
                    command_var.append("film-dvd")
                else:
                    command_var.append("pal-dvd")
                if (copy_audio == False):
                    command_var.append("-acodec")
                    if fix_ac3:
                        command_var.append("ac3_fixed")
                    else:
                        command_var.append("ac3")
                #command_var.append("-maxrate")
                #command_var.append("7000k")
                #command_var.append("-minrate")
                #command_var.append("2200k")
            elif (disctype == "vcd"):
                vcd = True
                if final_framerate == 30:
                    command_var.append("ntsc-vcd")
                else:
                    command_var.append("pal-vcd")
            elif (disctype == "svcd"):
                if final_framerate == 30:
                    command_var.append("ntsc-svcd")
                else:
                    command_var.append("pal-svcd")
            elif (disctype == "cvd"):
                if final_framerate == 30:
                    command_var.append("ntsc-svcd")
                else:
                    command_var.append("pal-svcd")
        else:  # DivX
            command_var.append("-vcodec")
            command_var.append("mpeg4")
            command_var.append("-acodec")
            command_var.append("libmp3lame")
            command_var.append("-f")
            command_var.append("avi")

        if (not isvob):
            command_var.append("-sn")  # no subtitles

        if copy_audio or isvob:
            command_var.append("-acodec")
            command_var.append("copy")
        #else:
        #	if (disctype=="divx"):
        #		command_var.append("-acodec")
        #		command_var.append("mp3")

        #if (audiostream!=10000):
        #	command_var.append("-aid")
        #	command_var.append(str(audiostream))

        if isvob:
            command_var.append("-vcodec")
            command_var.append("copy")

        if (vcd == False):
            if final_framerate == 30:
                if (framerate == 24) and ((disctype == "dvd") or
                                          (disctype == "divx")):
                    str_final_framerate = "24000/1001"
                    keyintv = 15
                    telecine = True
                else:
                    str_final_framerate = "30000/1001"
                    keyintv = 18
            else:
                str_final_framerate = str(int(final_framerate))
                keyintv = 15

        if (disctype == "divx"):
            command_var.append("-g")
            command_var.append("300")
        elif gop12 and (isvob == False):
            command_var.append("-g")
            command_var.append("12")

        command_var.append("-bf")
        command_var.append("2")
        command_var.append("-strict")
        command_var.append("1")

        if seconds != 0:
            command_var.append("-t")
            command_var.append(str(seconds))
        else:
            if videofile["cutting"] == 1:  # first half only
                command_var.append("-t")
                command_var.append(str(videofile["olength"] / 2))
            elif videofile["cutting"] == 2:  # second half only
                command_var.append("-ss")
                command_var.append(str((videofile["olength"] / 2) -
                                       5))  # start 5 seconds before

        #if (audiodelay!=0.0) and (copy_audio==False) and (isvob==False):
        #	command_var.append("-delay")
        #	command_var.append(str(audiodelay))

        command_var.append("-ac")
        if (sound51) and ((disctype == "dvd") or (disctype == "divx")):
            command_var.append("6")
        else:
            command_var.append("2")

        #if (isvob==False) and (default_res==False):
        #	command_var.append("-ofps")
        #	command_var.append(str_final_framerate)

        if disctype == "divx":
            command_var.append("-vtag")
            command_var.append("DX50")

        lineatemp = ""
        acoma = False

        #if swap_fields:
        #	lineatemp+="phase=a"
        #	acoma=True

        passlog_var = None

        if (videofile["deinterlace"] != "none") and (
                videofile["deinterlace"] != "yadif") and (isvob == False):
            command_var.append("-deinterlace")

        print "Addbars " + str(addbars) + " resx_o " + str(
            resx_original) + " resy_o " + str(resy_original)
        print "resx_i " + str(resx_inter) + " resy_i " + str(resy_inter)

        if (isvob == False) and (vcd == False):
            command_var.append("-s")
            command_var.append(str(resx_final) + "x" + str(resy_final))

        # Currently Mencoder supports up to 8 threads
        if isvob == False:
            threads

            if threads > 1:
                command_var.append("-threads")
                command_var.append(str(threads))

            command_var.append("-trellis")
            if videofile["trellis"]:
                command_var.append("1")
            else:
                command_var.append("0")

            if videofile["mbd"] == 0:
                command_var.append("-mbd")
                command_var.append("0")
            elif videofile["mbd"] == 1:
                command_var.append("-mbd")
                command_var.append("1")
            elif videofile["mbd"] == 2:
                command_var.append("-mbd")
                command_var.append("2")

            if (vcd == False):
                command_var.append("-b")
                command_var.append(str(videorate) + "000")

            #if disctype!="divx":
            #	lavcopts+=":keyint="+str(keyintv)
            if (copy_audio == False) and (vcd == False):
                #					lavcopts+=":acodec="
                #					if disctype=="dvd":
                #						if fix_ac3:
                #							lavcopts+="ac3_fixed"
                #						else:
                #							lavcopts+="ac3"
                #					else:
                #						lavcopts+="mp2"
                #lavcopts+=":abitrate="+str(audiorate)
                command_var.append("-ab")
                command_var.append(str(audiorate) + "000")

            if (default_res == False):
                command_var.append("-aspect")
                if aspect_ratio_final > 1.4:
                    command_var.append("16:9")
                else:
                    command_var.append("4:3")

            passlog_var = None
            if (encpass > 0) and (isvob == False):
                command_var.append("-pass")
                command_var.append(str(encpass))
                passlog_var = os.path.join(filefolder, filename) + ".log"
                if encpass == 1:
                    try:
                        os.remove(passlog_var)
                    except:
                        pass

        at = audio_tracks
        while (at > 1):
            if (volume != 100):
                command_var.append("-vol")
                command_var.append(str((256 * volume) / 100))
            command_var.append("-newaudio")
            at -= 1

        extra_params = videofile["params"]  # take the extra params
        while (extra_params != ""):
            extra_params, new_param = devede_other.get_new_param(extra_params)
            if new_param != "":
                command_var.append(new_param)

        currentfile = self.create_filename(filefolder + filename, title,
                                           chapter, disctype == "divx")

        if (passlog_var != None) and (isvob == False):
            command_var.append("-passlogfile")
            command_var.append(passlog_var)

        if (encpass == 1) and (isvob == False):
            command_var.append("-y")
            command_var.append("/dev/null")
        else:
            command_var.append(currentfile)

        self.print_error = _("Conversion failed.\nIt seems a bug of Mencoder.")
        if (videofile["params"] != "") or (videofile["params_vf"] != "") or (
                videofile["params_lame"] != ""):
            self.print_error += "\n" + _(
                "Also check the extra params passed to Mencoder for syntax errors."
            )
        self.error_not_done = True
        self.launch_program(command_var, read_chars=300)
Example #10
0
    def __init__(self, videofile, filename, filefolder, progresbar, proglabel,
                 disctype, title, chapter, stream):
        """ This class adds the subtitles to an already converted file

		VIDEOFILE contains the parameters to convert the video
		FILENAME is the generic file name given by the user
		FILEFOLDER is the path where all the temporary and finall files will be created
		PROGRESBAR is the progress bar where the class will show the progress
		PROGLABEL is the label where the class will show what is it doing
		DISCTYPE can be dvd, vcd, svcd, cvd or divx
		TITLE and CHAPTER are the numbers used to identify the TITLE and CHAPTER number for this file
		STREAMS is the stream number (to allow to add several subtitles)
		"""

        devede_executor.executor.__init__(self, filename, filefolder,
                                          progresbar)
        progresbar.pulse()
        proglabel.set_text(
            _("Adding subtitles to") + "\n" + videofile["filename"])
        self.currentfile = self.create_filename(filefolder + filename, title,
                                                chapter, disctype == "divx")

        subtitle_list = videofile["sub_list"][stream]

        # generate the XML file

        self.error = ""

        try:
            print "Trying to create " + filefolder + filename + "_sub.xml"
            fichero = open(filefolder + filename + "_sub.xml", "w")
        except IOError:
            print "IOError en subtitulos"
            self.print_error = _(
                "Failed to write to the destination directory.\nCheck that you have privileges and free space there."
            )
            self.initerror = True
            return

        fichero.write('<subpictures format="')
        if (videofile["fps"] == 25):
            fichero.write('PAL')
        else:
            fichero.write('NTSC')
        fichero.write('">\n\t<stream>')
        if (subtitle_list["sub_codepage"] != "UTF-8"):
            final_type = "UTF-8"
            subfilename = os.path.join(filefolder, filename + "_sub_tmp.sub")
            self.deletesub = subfilename
            if 0 != devede_other.check_utf().convert_to_UTF8(
                    subtitle_list["subtitles"], subfilename,
                    subtitle_list["sub_codepage"]):
                #except IOError:
                print "IOError al convertir a UTF8"
                self.print_error = _(
                    "Failed to write to the destination directory.\nCheck that you have privileges and free space there."
                )
                self.initerror = True
                return
        else:
            self.deletesub = ""
            final_type = subtitle_list["sub_codepage"]
            subfilename = subtitle_list["subtitles"]
        fichero.write('\n\t\t<textsub filename="' +
                      self.expand_xml(subfilename) + '"')

        if (sys.platform == "win32") or (sys.platform == "win64"):
            if os.path.isfile(
                    os.path.join(os.environ["WINDIR"], "Fonts",
                                 "devedesans.ttf")):
                fichero.write('\n\t\tfont="devedesans.ttf"')
            else:
                fichero.write('\n\t\tfont="ARIAL.ttf"')
        else:
            fichero.write('\n\t\tfont="devedesans.ttf"')
        if ((subtitle_list["sub_codepage"] != "")
                and (subtitle_list["sub_codepage"] != "ASCII")):
            fichero.write('\n\t\tcharacterset="' + final_type + '"')
        fichero.write('\n\t\thorizontal-alignment="center"')

        if (videofile["fps"] == 25):
            ancho = 716
            alto = 572
            tamanofont = videofile["subfont_size"]
        else:
            ancho = 716
            alto = 476
            tamanofont = videofile["subfont_size"]

        margin_hor = int((58 * ancho) / 720)
        margin_vert = int((28 * alto) / 576)
        bottom_margin = margin_vert

        fichero.write('\n\t\tmovie-width="' + str(ancho - 4) + '"')
        fichero.write('\n\t\tmovie-height="' + str(alto - 4) + '"')
        fichero.write('\n\t\tleft-margin="' + str(margin_hor) + '"')
        fichero.write('\n\t\tright-margin="' + str(margin_hor) + '"')

        if subtitle_list["subtitles_up"]:
            tamanofont -= 1
            bottom_margin = 4 + (alto / 8
                                 )  # put it in the border of 16:9 aspect ratio

        fichero.write('\n\t\tbottom-margin="' + str(bottom_margin) + '"')
        fichero.write('\n\t\ttop-margin="' + str(margin_vert) + '"')

        fichero.write('\n\t\tfontsize="' + str(tamanofont) + '.0"')

        fill_color = 'rgba(%.0f%%, %.0f%%, %.0f%%, %.0f%%)' % tuple(
            float(item) / 655.35 for item in videofile["sub_fill_color"])
        fichero.write('\n\t\tfill-color="%s"' % fill_color)

        outline_color = 'rgba(%.0f%%, %.0f%%, %.0f%%, %.0f%%)' % tuple(
            float(item) / 655.35 for item in videofile["sub_outline_color"])
        fichero.write('\n\t\toutline-color="%s"' % outline_color)

        if (videofile["fps"] == 30):
            if (videofile["ofps"] == 24) and ((disctype == "dvd") or
                                              (disctype == "divx")):
                fps_out = "24000/1001"
            else:
                fps_out = "30000/1001"
        else:
            fps_out = "25"

        if videofile["ismpeg"]:
            fps_out = videofile["ofps2"]
            print "FPS sub 1 original"
        else:
            print "FPS sub 1 final"

        fichero.write('\n\t\tmovie-fps="' + str(fps_out) + '"')
        speed1, speed2 = devede_other.get_speedup(videofile)
        if speed1 == speed2:
            fps_out_subs = fps_out
            print "FPS sub 2 final"
        else:
            if speed2 == 24:
                fps_out_subs = "24"
            else:
                fps_out_subs = videofile["ofps2"]
            print "FPS sub 2 original"

        fichero.write('\n\t\tsubtitle-fps="' + fps_out_subs + '"')
        fichero.write('\n\t\tvertical-alignment="bottom" />')
        fichero.write("\n\t</stream>\n</subpictures>")
        fichero.close()

        comando = ""
        if (sys.platform == "win32") or (sys.platform == "win64"):
            comando = ["spumux.exe"]
            comando.append("-m")
            if disctype == "vcd":
                comando.append("svcd")
            else:
                comando.append(disctype)
            comando.append("-s")
            comando.append(str(stream))

            comando.append(filefolder + filename + "_sub.xml")
            comando.append("-i")
            comando.append(self.currentfile)
            comando.append("-o")
            comando.append(self.currentfile + ".sub")
            self.print_error = _(
                "Conversion failed.\nIt seems a bug of SPUMUX.")
            self.launch_program(comando, output=True)
        else:
            comando = "spumux -m "
            if disctype == "vcd":
                comando += "svcd"
            else:
                comando += disctype

            comando += ' -s ' + str(
                stream) + ' "' + filefolder + filename + '_sub.xml"'

            self.print_error = _(
                "Conversion failed.\nIt seems a bug of SPUMUX.")
            self.launch_shell(
                comando,
                output=True,
                stdinout=[self.currentfile, self.currentfile + ".sub"])